Quita un elemento del principio del array

  • « array_search
  • array_slice »
  • PHP Manual
  • Funciones de Arrays
  • Quita un elemento del principio del array

array_shift

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

array_shift — Quita un elemento del principio del array

Descripción

array_shift ( array &$array ) : mixed

array_shift() Quita el primer valor del array y lo devuelve, acortando el array un elemento y corriendo el array hacia abajo. Todas la claves del array numéricas serán modificadas para que empiece contando desde cero mientras que las claves literales no se verán afectadas.

Nota: Esta función ejecutará un reset() en el puntero de array del array de entrada después de su uso.

Parámetros

array

El array de entrada.

Valores devueltos

Devuelve el valor quitado, o null si el array está vacío o no es un array.

Ejemplos

Ejemplo #1 Ejemplo de array_shift()

<?php
$stack = array("naranja", "plátano", "manzana", "frambuesa");
$fruit = array_shift($stack);
print_r($stack);
?>

El resultado del ejemplo sería:

Array
(
    [0] => plátano
    [1] => manzana
    [2] => frambuesa
)

y naranja será asigando a $fruit.

Ver también

  • array_unshift() - Añadir al inicio de un array uno a más elementos
  • array_push() - Inserta uno o más elementos al final de un array
  • array_pop() - Extrae el último elemento del final del array

User Contributed Notes

Anonymous 29-Jun-2020 07:05
"$stack" in the example should be called "$queue".
hmztsc at gmail dot com 07-Feb-2020 07:58
// i wanted to remove first array inside to array
// but doesn't work for me : array_shift();

$cargo_file =
Array
(
    [0] => Array
        (
            [0] => Country
            [1] => CountryCode
            [2] => City
            [3] => CityOtherLanguage
            [4] => PostCode
            [5] => Days
        )

    [1] => Array
        (
            [0] => Turkey
            [1] => TR
            [2] => Istanbul
            [3] => Istanbul
            [4] => 34930
            [5] => 9
        )

)

$cargo_file = array_shift($cargo_file);

echo "<pre>";
print_r($cargo_file);
echo "</pre>";

// result after :

/*
Array
(
    [0] => Country
    [1] => CountryCode
    [2] => City
    [3] => CityOtherLanguage
    [4] => PostCode
    [5] => Days
)
*/

i developed a solution

function removeFirstArray($array){

    $new_array = [];
    foreach ($array as $key => $value) {
        if($key > 0){
            $new_array[] = $value;
        }
    }

    return $new_array;
}

$cargo_file= removeFirstArray($cargo_file);

echo "<pre>";
print_r($cargo_file);
echo "</pre>";

Array
(
    [0] => Array
        (
            [0] => Turkey
            [1] => TR
            [2] => Istanbul
            [3] => Istanbul
            [4] => 34930
            [5] => 9
        )

)
wheberson dot com dot br at gmail dot com 26-Sep-2019 01:35
// Ex. 1: signedShiftArray (['A', 'B', 'C', 'D'], 2)        ->        ['C', 'D', 'A', 'B']
// Ex. 2: signedShiftArray (['A', 'B', 'C', 'D'], -3)        ->        ['B', 'C', 'D', 'A']
// Ex. 3: signedShiftArray (['A', 'B', 'C', 'D'], -7)        ->        ['B', 'C', 'D', 'A']

function signedShiftArray ($aItems, $aOffset)

{
    if (empty ($aItems))
        return [];
    else if (empty ($aOffset))
        return $aItems;
    else {
        $t= count ($aItems);
        $n= $aOffset % $t;
        $m= $aOffset > 0 ? $n : $t + $aOffset;
        return array_merge (array_slice ($aItems, $n), array_slice ($aItems, 0, $m));
    }
}
vasiliauskas dot agnius at gmail dot com 07-Mar-2019 08:37
Sometimes instead of shuffling array you just need to rotate it. We can easily rotate left an array with such code:
<?php
$arr[] = array_shift($arr);
?>
biziclop at vipmail dot hu 17-Jan-2018 10:49
<?php

//Be careful when using array_pop/shift/push/unshift with irregularly indexed arrays:

$shifty = $poppy = array(
  2 => '(2)',
  1 => '(1)',
  0 => '(0)',
);                         print_r( $shifty );

array_shift( $shifty );    print_r( $shifty );
//     [0] => (1)
//     [1] => (0)

array_pop( $poppy );       print_r( $poppy );
//     [2] => (2)
//     [1] => (1)

$shifty = $poppy = array(
  'a' => 'A',
  'b' => 'B',
  '(0)',
  '(1)',
  'c' => 'C',
  'd' => 'D',
);                                     print_r( $shifty );

array_shift( $shifty );                print_r( $shifty );
//     [b] => B
//     [0] => (0)
//     [1] => (1)
//     [c] => C
//     [d] => D

array_unshift( $shifty, 'unshifted');  print_r( $shifty );
//     [0] => unshifted
//     [b] => B
//     [1] => (0)
//     [2] => (1)
//     [c] => C
//     [d] => D

array_pop( $poppy );                   print_r( $poppy );
//     [a] => A
//     [b] => B
//     [0] => (0)
//     [1] => (1)
//     [c] => C

array_push( $poppy, 'pushed');         print_r( $poppy );
//     [a] => A
//     [b] => B
//     [0] => (0)
//     [1] => (1)
//     [c] => C
//     [2] => pushed

?>
mah dot di at live dot com 07-Mar-2016 02:35
This removeAdd function, the first argument shift your array then unshif the second argument to your array. first argument is an array and second argument can be int or str.

<?php
function removeAdd ($arr, $newer){
    $a = array_shift($arr);
    $b = array_unshift($arr, $newer);
    foreach ($arr as $value){
        echo $value."<br />";
    }
}

$a = array(1,2,3,4,5,6);
foreach ($a as $current){
    echo $current."<br />";
}
echo "<hr />";
removeAdd($a, 0);
?>

OUTPUT:
1
2
3
4
5
6
_______

0
2
3
4
5
6
michaeljanikk at gmail dot com 14-May-2014 01:26
To remove an element from the MIDDLE of an array (similar to array_shift, only instead of removing the first element, we want to remove an element in the middle, and shift all keys that follow down one position)

Note that this only works on enumerated arrays.

<?php
$array = array('a', 'b', 'c', 'd', 'e', 'e');
/*
array(6) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "e"
}
*/

$indexToRemove = 2;
unset($array[$indexToRemove]);
$array = array_slice($array, 0);

/*
array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "d"
  [3]=>
  string(1) "e"
  [4]=>
  string(1) "e"
}
*/
?>

I hope this helps someone!
drum_inc at yahoo dot com 23-Aug-2013 05:27
Assignment in line, does not remove the element.

$first = array_shift( $arr = array( 0 => '1st', 2 => '2nd', 3 => '3rd') );
print_r( $first );
print_r( $arr );

Output:
1st
Array
(
    [0] => 1st
    [2] => 2nd
    [3] => 3rd
)
elad dot yosifon at gmail dot com 10-Aug-2013 06:47
Notice:
the complexity of array_pop() is O(1).
the complexity of array_shift() is O(n).
array_shift() requires a re-index process on the array, so it has to run over all the elements and index them.
info at chihoang dot de 20-Apr-2011 09:46
This doesn't work with a 2 dimensional array. With 2 dimensional array I do this:

<?php
$backup = $arr;
$first = array_shift ( $backup );
?>
ar at xonix dot ch 14-Aug-2010 03:54
If you need the first or last entry of an array, then this could help you.

<?php
function array_last_entry($arr){
    if(!is_array($arr))
        return;

    if(empty($arr))
        return;

    return end($arr);
}

function array_first_entry($arr){
    if(!is_array($arr))
        return;

    if(empty($arr))
        return;

    reset($arr);
    return current($arr);
}

$arr = array( '5' => 'five', '3' => 'three', '8' => 'eight',);

echo 'last entry: '.array_last_entry($arr).'<br>';

echo 'first entry: '.array_first_entry($arr).'<br>';

echo 'alternative output:<br>';

echo 'last entry: '.$arr[count($arr)-1];

echo '<br>first entry: '.$arr[0];
?>

The output will look like:
last entry: eight
first entry: five
alternative output:
last entry:
first entry:

As you can see, if you have to handle arrays with non-continuous indexes, these functions may be very helpful.
patrick at pwfisher dot com 21-Aug-2009 08:23
Here's a utility function to parse command line arguments.

<?php
/**
 * CommandLine class
 *
 * @package             Framework
 */
/**
 * Command Line Interface (CLI) utility class.
 *
 * @author              Patrick Fisher <patrick@pwfisher.com>
 * @since               August 21, 2009
 * @package             Framework
 * @subpackage          Env
 */
class CommandLine {

    /**
     * PARSE ARGUMENTS
     *
     * [pfisher ~]$ echo "<?php
     * >     include('CommandLine.php');
     * >     \$args = CommandLine::parseArgs(\$_SERVER['argv']);
     * >     echo "\n", '\$out = '; var_dump(\$args); echo "\n";
     * > ?>" > test.php
     *
     * [pfisher ~]$ php test.php plain-arg --foo --bar=baz --funny="spam=eggs" --alsofunny=spam=eggs \
     * > 'plain arg 2' -abc -k=value "plain arg 3" --s="original" --s='overwrite' --s
     *
     * $out = array(12) {
     *   [0]                => string(9) "plain-arg"
     *   ["foo"]            => bool(true)
     *   ["bar"]            => string(3) "baz"
     *   ["funny"]          => string(9) "spam=eggs"
     *   ["alsofunny"]      => string(9) "spam=eggs"
     *   [1]                => string(11) "plain arg 2"
     *   ["a"]              => bool(true)
     *   ["b"]              => bool(true)
     *   ["c"]              => bool(true)
     *   ["k"]              => string(5) "value"
     *   [2]                => string(11) "plain arg 3"
     *   ["s"]              => string(9) "overwrite"
     * }
     *
     * @author              Patrick Fisher <patrick@pwfisher.com>
     * @since               August 21, 2009
     * @see                 http://www.php.net/manual/en/features.commandline.php
     *                      #81042 function arguments($argv) by technorati at gmail dot com, 12-Feb-2008
     *                      #78651 function getArgs($args) by B Crawford, 22-Oct-2007
     * @usage               $args = CommandLine::parseArgs($_SERVER['argv']);
     */
    public static function parseArgs($argv){

        array_shift($argv);
        $out                            = array();

        foreach ($argv as $arg){

            // --foo --bar=baz
            if (substr($arg,0,2) == '--'){
                $eqPos                  = strpos($arg,'=');

                // --foo
                if ($eqPos === false){
                    $key                = substr($arg,2);
                    $value              = isset($out[$key]) ? $out[$key] : true;
                    $out[$key]          = $value;
                }
                // --bar=baz
                else {
                    $key                = substr($arg,2,$eqPos-2);
                    $value              = substr($arg,$eqPos+1);
                    $out[$key]          = $value;
                }
            }
            // -k=value -abc
            else if (substr($arg,0,1) == '-'){

                // -k=value
                if (substr($arg,2,1) == '='){
                    $key                = substr($arg,1,1);
                    $value              = substr($arg,3);
                    $out[$key]          = $value;
                }
                // -abc
                else {
                    $chars              = str_split(substr($arg,1));
                    foreach ($chars as $char){
                        $key            = $char;
                        $value          = isset($out[$key]) ? $out[$key] : true;
                        $out[$key]      = $value;
                    }
                }
            }
            // plain-arg
            else {
                $value                  = $arg;
                $out[]                  = $value;
            }
        }
        return $out;
    }
}
?>
regs at voidship dot net 03-Nov-2008 12:50
Using array_shift over larger array was fairly slow.  It sped up as the array shrank, most likely as it has to reindex a smaller data set.

For my purpose, I used array_reverse, then array_pop, which doesn't need to reindex the array and will preserve keys if you want it to (didn't matter in my case).

Using direct index references, i.e., array_test[$i], was fast, but direct index referencing + unset for destructive operations was about the same speed as array_reverse and array_pop.  It also requires sequential numeric keys.
chris {at} w3style {dot} co {dot} uk 05-Oct-2008 06:06
As pointed out earlier, in PHP4, array_shift() modifies the input array by-reference, but it doesn't return the first element by reference.  This may seem like very unexpected behaviour.  If you're working with a collection of references (in my case XML Nodes) this should do the trick.

<?php

/**
 * This function exhibits the same behaviour is array_shift(), except
 * it returns a reference to the first element of the array instead of a copy.
 *
 * @param array &$array
 * @return mixed
 */
function &array_shift_reference(&$array)
{
  if (count($array) > 0)
  {
    $key = key($array);
    $first =& $array[$key];
  }
  else
  {
    $first = null;
  }
  array_shift($array);
  return $first;
}

class ArrayShiftReferenceTest extends UnitTestCase
{

  function testFunctionRemovesFirstElementOfNumericallyIndexedArray()
  {
    $input = array('foo', 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionRemovesFirstElementOfAssociativeArray()
  {
    $input = array('x' => 'foo', 'y' => 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('y' => 'bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionReturnsReferenceToFirstElementOfNumericallyIndexedArray()
  {
    $foo = 'foo';
    $input = array(&$foo, 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsReferenceToFirstElementOfAssociativeArray()
  {
    $foo = 'foo';
    $input = array('x' => &$foo, 'y' => 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsNullIfEmptyArrayPassedAsInput()
  {
    $input = array();
    $first = array_shift_reference($input);
    $this->assertNull($first, '%s: Array has no first element so NULL should be returned');
  }

}

?>
sggoyal at gmail dot com 07-Sep-2008 10:08
// To Change order of Array by Saurabh Goyal
    function change_array_order($table,$order)
    {
       //init the new table
       $new_table = array();
       foreach($order as $colname)
       {
          $new_table[$colname] = $table[$colname];
       }
       return $new_table;
    }

if array value like:-
$row = array('usr_id'=>'23','usr_name'=>'Saurabh', 'usr_surname'=>'Goyal','usr_firstname'=>'Saurabh');

//you want change order & show only particular field
change_array_order($row,array('usr_name','usr_firstname',
                                            'usr_surname'));

Regard's

Saurabh Goyal
http://sggoyal.blogspot.com
nospam at dyce dot losethisbit dot com 02-Jul-2008 05:15
Just a useful version which returns a simple array with the first key and value. Porbably a better way of doing it, but it works for me ;-)

<?php

function array_kshift(&$arr)
{
  list($k) = array_keys($arr);
  $r  = array($k=>$arr[$k]);
  unset($arr[$k]);
  return $r;
}

// test it on a simple associative array
$arr = array('x'=>'ball','y'=>'hat','z'=>'apple');

print_r($arr);
print_r(array_kshift($arr));
print_r($arr);

?>

Output:

Array
(
    [x] => ball
    [y] => hat
    [z] => apple
)
Array
(
    [x] => ball
)
Array
(
    [y] => hat
    [z] => apple
)
Maikel 19-Feb-2008 09:43
In response to nando_f at nothingsimple dot com

The example is correct,  array_shift do an unset to first element  because the parameter is passed by reference
Ben 02-Oct-2007 09:17
baughmankr at appstate dot edu, I think this is more efficient.

<?php
function array_shorten($arr)
{
  list($k) = array_keys($arr);
  unset($arr[$k]);
  return $arr;
}
?>
baughmankr at appstate dot edu 18-Sep-2007 02:04
I needed to remove the first set of keys and values from an associative array.  Had to write this function:

function shortenArray($_arr)
{
    $i=1;
    $_shorter=array();
    foreach ($_arr as $k => $v)
    {
        if ($i != 1)
        {
            $_shorter[$k] = $v;
        }
        $i++;
    }
    return $_shorter;
}
dmhouse at gmail dot com 08-Aug-2007 01:54
If you want a version of array_shift() that works non-destructively (i.e., an easy function to grab the first element of the array without modifying the array), try reset().
Traps 09-Jul-2007 10:52
For those that may be trying to use array_shift() with an array containing references (e.g. working with linked node trees), beware that array_shift() may not work as you expect: it will return a *copy* of the first element of the array, and not the element itself, so your reference will be lost.

The solution is to reference the first element before removing it with array_shift():

<?php

// using only array_shift:
$a = 1;
$array = array(&$a);
$b =& array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 1, b = 2

// solution: referencing the first element first:
$a = 1;
$array = array(&$a);
$b =& $array[0];
array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 2, b = 2

?>
C_Prevost at myob 30-Apr-2007 04:52
no, it demonstrates quite well that it removes the first element in the original array, updating the keys, and that it also returns the original first element.
richard at happymango dot me dot uk 12-Apr-2007 06:09
If you want to loop through an array, removing its values one at a time using array_shift() but also want the key as well, try this.

<?php

while($key = key($array))
{
     $value = array_shift($array);
     //code goes here
}

?>

its like foreach but each time the value is removed from the array so it eventually ends up empty

<?php

//example below

$airports = array
(
    "LGW" => "London Gatwick",
    "LHR" => "London Heathrow",
    "STN" => "London Stanstead"
);

echo count($airports)." Airport in the array<br /><br />";

while($key = key($airports))
{
    $value = array_shift($airports);
    echo $key." is ".$value."<br />";
}

echo "<br />".count($airports)." Airport left in the array";

?>

Example Outputs:

3 Airport in the array

LGW is London Gatwick
LHR is London Heathrow
STN is London Stanstead

0 Airport left in the array
alreece45 at yahoo dot com 09-Aug-2006 08:13
I haven't really read into it, but if you're complaining about a change in PHP 5.0.5 that made it so you couldn't do:

<?php

$val = array_shift(preg_split());

?>

or

<?php

$val = array_shit(function_that_returns_array);

?>

Then you're not using this function correctly. This function's argument is supposed to be a pointer to a variable. It then modifies that variable and returns a value. When you specify a function, php CAN NOT modify the return value of that function. It should be common sense but apparently its not.

Also, on a efficiency note, you might want to consider using another function such as reset or perhaps making your own function such as below:

<?php

function first_element($array) {

return reset($array);

}

?>

Unless of course for some reason you need to save the microseconds this takes.

}
bmr at ediweb dot org 31-May-2006 07:27
If the array has non-numerical keys, array_shift extracts the first element, whichever is the key, and recompute the numerical keys, if there are any. Ie :

$array = array("c" => "ccc", 0 => "aaa", "d" => "ddd", 5 => "bbb");
$first = array_shift($array);
echo '$first = ' . $first . ', $array = ' . var_export($array, true);

will display :

$first = ccc, $array = array ( 0 => 'aaa', 'd' => 'ddd', 1 => 'bbb', )

It means that array_shift works with associative arrays too, and leaves the keys unchanged if they are non-numerical.
19-Sep-2005 07:57
<?php

//----------------------------------------------------------
// The combination of array_shift/array_unshift
// greatly simplified a function I created for
// generating relative paths. Before I found them
// the algorithm was really squirrely, with multiple
// if tests, length calculations, nested loops, etc.
// Great functions.
//----------------------------------------------------------

function create_relative_path($inSourcePath, $inRefPath)
{
    // break strings at slashes
    $s_parts            = explode('/', $inSourcePath);
    $r_parts            = explode('/', $inRefPath);

    // delete items up to the first non-equal part
    while ($s_parts[0] === $r_parts[0])
    {
        array_shift($s_parts);
        array_shift($r_parts);
    }

    // add wild card to r_parts for each remaining
    // item of s_parts
    while ($s_parts[0])
    {
        array_unshift($r_parts, '..');
        array_shift($s_parts);
    }

    return implode('/', $r_parts);
}

//----------------------------------------------------------
// Example:
//     Given a source path $sp generates the relative
//     location of $rp. $sp could be assigned using
//     $_SERVER['PHP_SELF'] but it's hardcoded for
//     the example.
//----------------------------------------------------------
$sp = '/WebServer/Documents/MyBigProject/php/project_script.php';
$rp = '/WebServer/Documents/MyLibraries/lib_script.php';

// plugging them into the function
$rel_path = create_relative_path($sp, $rp);

// yeilds
'../../../MyLibraries/lib_script.php'

// and it could be used like
include_once(create_relative_path($_SERVER['PHP_SELF'], $rp));
lukasz dot dywicki DEL at gmail dot com 27-Jul-2005 05:48
Im using this function to browse arrays from database. For example data:
<?php
$data = array(
      array('row 1-cell 1','row 1-cell 2'),
      array('row 2-cell 1','row 2-cell 2'),
      array('row 3-cell 1','row 3-cell 2'),
);

while($row=array_shift($data)) {
      echo $row[0];
}
?>
Output:
row 1-cell 1
row 2-cell 1
row 3-cell 1
arturo {dot} ronchi {at} gmail {dot} com 20-Apr-2005 06:24
Here is a little function if you would like to get the top element and rotate the array afterwards.

function array_rotate(&$arr)
{
  $elm = array_shift($arr);
  array_push($arr, $elm);
  return $elm;
}
09-Feb-2005 04:27
This function will save the key values of an array, and it will work in lower versions of PHP:

<?php

function array_shift2(&$array){
    reset($array);
    $key = key($array);
    $removed = $array[$key];
    unset($array[$key]);
    return $removed;
}

?>
James McGuigan 14-Dec-2004 11:26
while(array_shift()) can be used to process multiple arrays and/or database results in a single loop. The || short circuts and only evaluates the first statement until it runs out of data.

It can help to reduce duplicated code (the rule is code once and once only).

Note that each ($row = ) statement much be encased in ()'s otherwise you will get funny results. If you use two array_shift($array) statements and forget the ()'s, you will repeatedly get the first element of the first array for the for the count of the $array.

<?php

require_once('class.db.php');

$sql = "SELECT title FROM links";
$result = mysql_query($sql, $db->connection);

$defaults = array(
     array('title' => 'None'),
     array('title' => 'Unknown')
);

while ( ($row = mysql_fetch_assoc($result))
     || ($row = array_shift($defaults)))
{
  echo $row['title'] . "<br>";
}

?>

This will print out (depending on database contents):
Title1
Title2
Title3
...
None
Unknown


Extraer una parte de un array

  • « array_shift
  • array_splice »
  • PHP Manual
  • Funciones de Arrays
  • Extraer una parte de un array

array_slice

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

array_slice — Extraer una parte de un array

Descripción

array_slice ( array $array , int $offset , int $length = null , bool $preserve_keys = false ) : array

array_slice() devuelve la secuencia de elementos del array array tal y como se especifica en los parámetros offset y length.

Parámetros

array

El array de entrada.

offset

Si el índice dado por offset no es negativo, la secuencia empezará en esa posición del array. Si el offset es negativo, la secuencia empezará en esa posición empezando por el final del array.

length

Si la longitud dada por length es positiva, la secuencia tendrá hasta tantos elementos como indique el valor. Si el array es más corto que length, solamente estarán presentes los elementos disponibles del array. Si se proporciona length y es negativo, la secuencia finalizará en tantos elementos empezando por el final del array. Si se omite, entonces la secuencia contendrá todo el contenido desde offset hasta el final del array.

preserve_keys

Observe que array_slice() reordenará y reinicializará los índices numéricos del array de forma predeterminada. Se puede cambiar esta comportamiento estableciendo el parámetro preserve_keys a true.

Valores devueltos

Devuelve la parte del array. Si el índice es mayor que el tamaño del array, devuelve un array vacío.

Historial de cambios

Versión | Descripción
5.2.4 | El valor predeterminado del parámetro length se cambió a NULL. Una length NULL ahora indica a la función que use la longitud de array. Antes de esta versión, una length NULL se tomaba como de longitud cero (no se devolvía nada).
5.0.2 | Se añadió el parámetro opcional preserve_keys.

Ejemplos

Ejemplo #1 Ejemplos de array_slice()

<?php
$entrada = array("a", "b", "c", "d", "e");

$salida = array_slice($entrada, 2);      // devuelve "c", "d", y "e"
$salida = array_slice($entrada, -2, 1);  // devuelve "d"
$salida = array_slice($entrada, 0, 3);   // devuelve "a", "b", y "c"

// observe las diferencias en las claves de los arrays
print_r(array_slice($entrada, 2, -1));
print_r(array_slice($entrada, 2, -1, true));
?>

El resultado del ejemplo sería:

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

Ver también

  • array_splice() - Elimina una porción del array y la reemplaza con otra cosa
  • unset() - Destruye una variable especificada
  • array_chunk() - Divide un array en fragmentos

User Contributed Notes

nathan dot fiscaletti at gmail dot com 30-Dec-2017 01:46
If you want an associative version of this you can do the following:

function array_slice_assoc($array,$keys) {
    return array_intersect_key($array,array_flip($keys));
}

However, if you want an inverse associative version of this, just use array_diff_key instead of array_intersect_key.

function array_slice_assoc_inverse($array,$keys) {
    return array_diff_key($array,array_flip($keys));
}

Example:

$arr = [
    'name' => 'Nathan',
    'age' => 20,
    'height' => 6
];

array_slice_assoc($arr, ['name','age']);

will return

Array (
     'name' = 'Nathan',
     'age' = 20
)

Where as

array_slice_assoc_inverse($arr, ['name']);

will return

Array (
    'age' = 20,
    'height' = 6
)
SomeGuy 24-Jun-2016 09:17
Thank to taylorbarstow here the function with the unset feature.
<?php
function array_slice_assoc(&$array,$keys,$unset = true) {
    $return = array_intersect_key($array, array_flip($keys));
    if ($unset) {
        foreach ($keys as $value) {
            unset($array[$value]);
        }
    }
    return $return;
}
?>
kansey 12-Aug-2015 09:32
To save the sort order of a numeric index in the array. Version php =>5.5.26
/*
Example
*/

$arr = array( "1" =>2, "2" =>3 , "3" =>5 );

print_r(array_slice($arr,1,null,true));

/*
Result

Array
(
[2] => 3
[3] => 5
)
*/
Ray.Paseur often uses Gmail 06-Jun-2013 02:44
<?php
// CHOP $num ELEMENTS OFF THE FRONT OF AN ARRAY
// RETURN THE CHOP, SHORTENING THE SUBJECT ARRAY
function array_chop(&$arr, $num)
{
    $ret = array_slice($arr, 0, $num);
    $arr = array_slice($arr, $num);
    return $ret;
}
Nathan - thefiscster510 at gmail dot com 29-Mar-2011 10:38
If you want to remove a specified entry from an array i made this mwethod...

<?php
$array = array("Entry1","entry2","entry3");

$int = 3; //Number of entries in the array
$int2 = 0; //Starter array spot... it will begine its search at 0.
$del_num = 1; //Represents the second entry in the array... which is the one we will happen to remove this time... i.e. 0 = first entry, 1 = second entry, 2 = third...........

$newarray = array(); //Empty array that will be the new array minus the specified entry...
print_r($array) . "<br>";    //print original array contents
print_r($newarray). "<br>"; //print the new empty array

do
{
$user = $array[$int2];
$key = array_search($user, $array);
if ($key == $del_num)
{

}
else
{
$newarray[] = $array[$int2];
}

$int2 = $int2 + 1;
} while ($int2 < $int);

print_r($newarray). "<br>"; //print the new array

?>
delew 11-Feb-2011 01:17
just a little tip.
to preserve keys without providing length: use NULL

array_slice($array, $my_offset, NULL, true);
xananax at yelostudio dot com 02-Feb-2011 07:23
<?php
/**
 * Reorders an array by keys according to a list of values.
 * @param array $array the array to reorder. Passed by reference
 * @param array $list the list to reorder by
 * @param boolean $keepRest if set to FALSE, anything not in the $list array will be removed.
 * @param boolean $prepend if set to TRUE, will prepend the remaining values instead of appending them
 * @author xananax AT yelostudio DOT com
 */
function array_reorder(array &$array,array $list,$keepRest=TRUE,$prepend=FALSE,$preserveKeys=TRUE){
    $temp = array();
    foreach($list as $i){
        if(isset($array[$i])){
            $tempValue = array_slice(
                $array,
                array_search($i,array_keys($array)),
                1,
                $preserveKeys
            );
            $temp[$i] = array_shift($tempValue);
            unset($array[$i]);
        }
    }
    $array = $keepRest ?
        ($prepend?
            $array+$temp
            :$temp+$array
        )
        : $temp;
}

/** exemple ** /
$a = array(
    'a'    =>    'a',
    'b'    =>    'b',
    'c'    =>    'c',
    'd'    =>    'd',
    'e'    =>    'e'
);
$order = array('c','b','a');

array_reorder($a,$order,TRUE);
echo '<pre>';
print_r($a);
echo '</pre>';
/** exemple end **/
?>
jamon at clearsightdesign dot com 10-Apr-2009 05:46
I was trying to find a good way to find the previous several and next several results from an array created in a MySQL query. I found that most MySQL solutions to this problem were complex. Here is a simple function that returns the previous and next rows from the array.

<?php

/*
** function array_surround by Jamon Holmgren of ClearSight Design
** Version 1.0 - 4/10/2009
** Please direct comments and questions to my first name at symbol clearsightdesign.com
**
** Returns an array with only the $before and $after number of results
** This is set to work best with MySQL data results
** Use this to find the rows immediately before and after a particular row, as many as you want
**
** Example usage:
**   $mysql_ar is an array of results from a MySQL query and the current id is $cur_id
**   We want to get the row before this one and five rows afterward
**
** $near_rows = array_surround($mysql_ar, "id", $cur_id, 1, 5)
**
**   Previous row is now $near_rows[-1]
**   Current row is now $near_rows[0]
**   Next row is $near_rows[1] ... etc
**   If there is no previous row, $near_rows[-1] will not be set...test for it with is_array($near_rows[-1])
**
*/
function array_surround($src_array, $field, $value, $before = 1, $after = 1) {
    if(is_array($src_array)) {
        // reset all the keys to 0 through whatever in case they aren't sequential
        $new_array = array_values($src_array);
        // now loop through and find the key in array that matches the criteria in $field and $value
        foreach($new_array as $k => $s) {
            if($s[$field] == $value) {
                // Found the one we wanted
                $ck = $k; // put the key in the $ck (current key)
                break;
            }
        }
        if(isset($ck)) { // Found it!
            $result_start = $ck - $before; // Set the start key
            $result_length = $before + 1 + $after; // Set the number of keys to return
            if($result_start < 0) { // Oops, start key is before first result
                $result_length = $result_length + $result_start; // Reduce the number of keys to return
                $result_start = 0; // Set the start key to the first result
            }
            $result_temp = array_slice($new_array, $result_start, $result_length); // Slice out the results we want
            // Now we have an array, but we want array[-$before] to array[$after] not 0 to whatever.
            foreach($result_temp as $rk => $rt) { // set all the keys to -$before to +$after
                $result[$result_start - $ck + $rk] = $rt;
            }
            return $result;
        } else { // didn't find it!
            return false;
        }
    } else { // They didn't send an array
        return false;
    }
}

?>

I hope you find this useful! I welcome constructive criticism or comments or of course praise ;) -- just e-mail me.

- Jamon Holmgren
Mr. P 14-Nov-2008 02:11
Note that offset is not the same thing as key. Offset always starts at 0, while keys might be any number.

So this:

<?php print_r(array_slice(array(0 => 0, 5 => 5, 13 => 13),1)); ?>

will result in this:
Array
(
    [0] => 5
    [1] => 13
)
s0i0m at dreamevilconcepts dot com 12-Sep-2008 07:53
Using the varname function referenced from the array_search page, submitted by dcez at land dot ru. I created a multi-dimensional array splice function. It's usage is like so:

$array['admin'] = array('blah1', 'blah2');
$array['voice'] = array('blah3', 'blah4');
array_cut('blah4', $array);

...Would strip blah4 from the array, no matter where the position of it was in the array ^^ Returning this...

Array ( [admin] => Array ( [0] => blah1 [1] => blah2 ) [voice] => Array ( [0] => blah3 ) )

Here is the code...

<?php

  function varname ($var)
  {
    // varname function by dcez at land dot ru
    return (isset($var)) ? array_search($var, $GLOBALS) : false;
  }

  function array_cut($needle, $haystack)
  {
    foreach ($haystack as $k => $v)
    {
      for ($i=0; $i<count($v); $i++)
        if ($v[$i] === $needle)
        {
          return array_splice($GLOBALS[varname($haystack)][$k], $i, 1);
          break; break;
        }
    }

?>

Check out dreamevilconcept's forum for more innovative creations!
ted.devito at 9gmail9 dot 99com 02-May-2008 09:21
based on worldclimb's arem(), here is a recursive array value removal tool that can work with multidimensional arrays.

function remove_from_array($array,$value){
    $clear = true;
    $holding=array();

    foreach($array as $k => $v){
        if (is_array($v)) {
            $holding [$k] = remove_from_array ($v, $value);
            }
        elseif ($value == $v) {
            $clear = false;
            }
        elseif($value != $v){
            $holding[$k]=$v; // removes an item by combing through the array in order and saving the good stuff
        }
    }
    if ($clear) return $holding; // only pass back the holding array if we didn't find the value
}
worldclimb at 99gmail99 dot com 21-Mar-2008 12:51
array_slice can be used to remove elements from an array but it's pretty simple to use a custom function.

One day array_remove() might become part of PHP and will likely be a reserved function name, hence the unobvious choice for this function's names.

<?
function arem($array,$value){
    $holding=array();
    foreach($array as $k => $v){
        if($value!=$v){
            $holding[$k]=$v;
        }
    }
    return $holding;
}

function akrem($array,$key){
    $holding=array();
    foreach($array as $k => $v){
        if($key!=$k){
            $holding[$k]=$v;
        }
    }
    return $holding;
}

$lunch = array('sandwich' => 'cheese', 'cookie'=>'oatmeal','drink' => 'tea','fruit' => 'apple');
echo '<pre>';
print_r($lunch);
$lunch=arem($lunch,'apple');
print_r($lunch);
$lunch=akrem($lunch,'sandwich');
print_r($lunch);
echo '</pre>';
?>

(remove 9's in email)
aexchecker at yahoo dot com 04-Oct-2007 08:39
<?php
/**
 * @desc
 * Combines two arrays by inserting one into the other at a given position then
 * returns the result.
 *
 * @since   2007/10/04
 * @version v0.7 2007/10/04 18:47:52
 * @author  AexChecker <AexChecker@yahoo.com>
 * @param   array $source
 * @param   array $destination
 * @param   int [optional] $offset
 * @param   int [optional] $length
 * @return  array
 */
function array_insert($source, $destination, $offset = NULL, $length = NULL) {
    if (!is_array($source) || empty($source)) {
        if (is_array($destination) && !empty($destination)) {
            return $destination;
        }
        return array();
    }
    if (is_null($offset)) {
        return array_merge($destination, $source);
    }
    $offset = var2int($offset);
    if (is_null($length)) {
        if ($offset === 0) {
            return array_merge($source, array_slice($destination, 1));
        }
        if ($offset === -1) {
            return array_merge(array_slice($destination, 0, -1), $source);
        }
        return array_merge(
            array_slice($destination, 0, $offset),
            $source,
            array_slice($destination, ++$offset)
        );
    }
    if ($offset === 0) {
        return array_merge($source, array_slice($destination, $length));
    }
    $destination_count = count($destination);
    $length = var2int($length);
    if ($offset > 0) {
        if ($destination_count - $offset < 1) {
            return array_merge($destination, $source);
        }
    } else{
        if (($t = $destination_count + $offset) < 1) {
            return array_merge($source, $destination);
        }
        $offset = $t;
    }
    if ($length > 0) {
        $length+= $offset;
    } elseif ($length < 0 && !($length * -1 < $destination_count)) {
        return $source;
    } else {
        $length = $offset;
    }
    return array_merge(
        array_slice($destination, 0, $offset),
        $source,
        array_slice($destination, $length)
    );
}
?>
aflavio at gmail dot com 01-Mar-2007 01:43
/**
    * Remove a value from a array
    * @param string $val
    * @param array $arr
    * @return array $array_remval
    */
    function array_remval($val, &$arr)
    {
          $array_remval = $arr;
          for($x=0;$x<count($array_remval);$x++)
          {
              $i=array_search($val,$array_remval);
              if (is_numeric($i)) {
                  $array_temp  = array_slice($array_remval, 0, $i );
                $array_temp2 = array_slice($array_remval, $i+1, count($array_remval)-1 );
                $array_remval = array_merge($array_temp, $array_temp2);
              }
          }
          return $array_remval;
    }

$stack=Array('apple','banana','pear','apple', 'cherry', 'apple');
array_remval("apple", $stack);

//output: Array('banana','pear', 'cherry')
06-May-2006 12:21
If you specify the fourth argument (to not reassign the keys), then there appears to be no way to get the function to return all values to the end of the array. Assigning -0 or NULL or just putting two commas in a row won't return any results.
taylorbarstow at the google mail service 07-Apr-2006 02:01
Array slice function that works with associative arrays (keys):

function array_slice_assoc($array,$keys) {
    return array_intersect_key($array,array_flip($keys));
}
andreasblixt (at) msn (dot) com 06-Sep-2005 09:53
<?php
    // Combines two arrays by inserting one into the other at a given position then returns the result
    function array_insert($src, $dest, $pos) {
        if (!is_array($src) || !is_array($dest) || $pos <= 0) return FALSE;
        return array_merge(array_slice($dest, 0, $pos), $src, array_slice($dest, $pos));
    }
?>
bishop 08-Dec-2004 01:58
Sometimes you need to pick certain non-integer and/or non-sequential keys out of an array. Consider using the array_pick() implementation below to pull specific keys, in a specific order, out of a source array:

<?php

$a = array ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$b = array_pick($a, array ('d', 'b'));

// now:
// $a = array ('a' => 1, 'c' => '3');
// $b = array ('d' => 4, 'b' => '2');

function &array_pick(&$array, $keys)
{
    if (! is_array($array)) {
        trigger_error('First parameter must be an array', E_USER_ERROR);
        return false;
    }

    if (! (is_array($keys) || is_scalar($keys))) {
        trigger_error('Second parameter must be an array of keys or a scalar key', E_USER_ERROR);
        return false;
    }

    if (is_array($keys)) {
        // nothing to do
    } else if (is_scalar($keys)) {
        $keys = array ($keys);
    }

    $resultArray = array ();
    foreach ($keys as $key) {
        if (is_scalar($key)) {
            if (array_key_exists($key, $array)) {
                $resultArray[$key] = $array[$key];
                unset($array[$key]);
            }
        } else {
            trigger_error('Supplied key is not scalar', E_USER_ERROR);
            return false;
        }
    }

    return $resultArray;
}

?>
developer at i-space dot org 03-Feb-2002 08:22
remember that array_slice returns an array with the current element. you must use array_slice($array, $index+1) if you want to get the next elements.


Elimina una porción del array y la reemplaza con otra cosa

  • « array_slice
  • array_sum »
  • PHP Manual
  • Funciones de Arrays
  • Elimina una porción del array y la reemplaza con otra cosa

array_splice

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

array_splice — Elimina una porción del array y la reemplaza con otra cosa

Descripción

array_splice ( array &$input , int $offset , int $length = 0 , mixed $replacement = array() ) : array

Elimina los elementos designados por offset y length del array input, y los reemplaza con los elementos del array replacement, si se proporcionan.

Observe que las claves numéricas de input no se preservan.

Nota: Si replacement no es un array, será moldeado a uno (esto es, (array) $replacement). Esto puede resultar en un comportamiento inesperado cuando se usa un objeto o replacement null

Parámetros

input

El array de entrada.

offset

Si el índice dado por offset es positivo, el inicio de la porción eliminada estará en ese índice desde el principio del array input. Si offset es negativo, se comienza desde el final del array input.

length

Si se omite la longitud dada por length, se elimina todo desde offset hasta el final del array. Si se especifica length y es positivo, se eliminarán tantos elementos como indique la longitud. Si se especifica length y es negativo, el final de la porción eliminada será de tantos elementos como indique la longitud desde el final del array. Si se especifica length y es cero, no se eliminará ningún elemento. Consejo: para eliminar todo desde offset hasta el final del array cuando también se especifique replacement, use count($input) para length.

replacement

Si se especifica el array replacement, los elementos eliminados serán reemplazados con los elementos de este array.

Si offset y length son tales que no se elimina nada, los elementos del array replacement serán insertados en el lugar especificado por offset. Observe que las claves del array replacement no se preservan.

Si replacement es sólo un elemento, no es necesario poner array() alrededor de él, a menos que el elemento sea un array, un objeto o null.

Valores devueltos

Devuelve un array que consiste en los elementos extraídos.

Ejemplos

Ejemplo #1 Ejemplos de array_splice()

<?php
$entrada = array("rojo", "verde", "azul", "amarillo");
array_splice($entrada, 2);
// $entrada ahora es array("rojo", "verde")

$entrada = array("rojo", "verde", "azul", "amarillo");
array_splice($entrada, 1, -1);
// $entrada ahora es array("rojo", "amarillo")

$entrada = array("rojo", "verde", "azul", "amarillo");
array_splice($entrada, 1, count($entrada), "naranja");
// $entrada ahora es array("rojo", "naranja")

$entrada = array("rojo", "verde", "azul", "amarillo");
array_splice($entrada, -1, 1, array("negro", "granate"));
// $entrada ahora es array("rojo", "verde",
//          "azul", "negro", "granate")

$entrada = array("rojo", "verde", "azul", "amarillo");
array_splice($entrada, 3, 0, "púpura");
// $entrada ahora es array("rojo", "verde",
//          "azul", "púpura", "amarillo");
?>

Ejemplo #2 Ejemplos de array_splice()

Las siguientes sentencias cambian el valor de $entrada de la misma manera:

<?php
array_push($entrada, $x, $y);
array_splice($entrada, count($entrada), 0, array($x, $y));
array_pop($entrada);
array_splice($entrada, -1);
array_shift($entrada);
array_splice($entrada, 0, 1);
array_unshift($entrada, $x, $y);
array_splice($entrada, 0, 0, array($x, $y));
$entrada[$x] = $y; // para arrays donde la clave es igual al índice
array_splice($entrada, $x, 1, $y);
?>

Ver también

  • array_slice() - Extraer una parte de un array
  • unset() - Destruye una variable especificada
  • array_merge() - Combina dos o más arrays

User Contributed Notes

Hayley Watson 26-Sep-2017 12:31
For an analogous function that works on strings rather than arrays, see substr_replace.
gilberg_vrn 25-Apr-2016 02:45
array_splice with preserve keys

<?php
function array_splice_preserve_keys(&$array, $from, $length = null) {
    $result = array_slice($array, $from, $length, true);
    $array = array_slice($array, $from + $length, null, true);

    return $result;
}
?>

Example:

<?php
$array = [
    1 => 'a',
    2 => 'b',
    26 => 'z'
];

var_dump(array_splice_preserve_keys($array, 0, 1), $array);
/**
 * array(1) {
 *  [1]=>
 *   string(1) "a"
 *  }
 * array(2) {
 *  [2]=>
 *  string(1) "b"
 *  [26]=>
 *  string(1) "z"
 * }
 */
?>
vitospericolato at gmail dot com 08-Apr-2016 08:54
To remove elements from an array, based on array values:

<?php
$i_to_remove=array();

foreach($array_to_prune as $i=>$value){
  if(cond_to_delete($value)) $i_to_remove[]=$i;
}
foreach($i_to_remove as $j=>$i)
  array_splice($array_to_prune,$i-$j,1);

?>
StanE 22-Oct-2015 08:50
array_splice() does not preserve numeric keys. The function posted by "weikard at gmx dot de" won't do that either because array_merge() does not preserve numeric keys either.

Use following function instead:

<?php
function arrayInsert($array, $position, $insertArray)
{
    $ret = [];

    if ($position == count($array)) {
        $ret = $array + $insertArray;
    }
    else {
        $i = 0;
        foreach ($array as $key => $value) {
            if ($position == $i++) {
                $ret += $insertArray;
            }

            $ret[$key] = $value;
        }
    }

    return $ret;
}
?>

Example:
<?php
$a = [
    295 => "Hello",
    58 => "world",
];

$a = arrayInsert($a, 1, [123 => "little"]);

/*
Output:
Array
(
    [295] => Hello
    [123] => little
    [58] => world
)
*/
?>

It preserves numeric keys. Note that the function does not use a reference to the original array but returns a new array (I see absolutely no reason how the performance would be increased by using a reference when modifying an array through PHP script code).
guillaume dot lacourt at gmail dot com 20-Jun-2015 01:30
Using array_splice when you traverse array with internal pointer's function reset the array, eg:

<?php
end($arrOfData);
$last = key($arrOfData);
reset($arrOfData);
while (($data = current($arrOfData))) {
  if ($last === key($arrOfData)) {
    array_splice($arrOfData, $last, 1);
   // current($arrOfData) => first value of $arrOfData
  }
}
Anonymous 11-Sep-2014 01:07
<?php
function array_slice2( $array, $offset, $length = 0 )
{
  if( $offset < 0 )
    $offset = sizeof( $array ) + $offset;

  $length = ( !$length ? sizeof( $array ) : ( $length < 0 ? sizeof( $array ) - $length : $length + $offset ) );

  for( $i = $offset; $i < $length; $i++ )
    $tmp[] = $array[$i];

  return $tmp;
}
?>
antrik 09-Jul-2014 07:20
Prompted by dire need, and inspired by some of the existing notes, I came up with this:

/* Like array_splice(), but preserves the key(s) of the replacement array. */
function array_splice_assoc(&$input, $offset, $length = 0, $replacement = array()) {
  $tail = array_splice($input, $offset);
  $extracted = array_splice($tail, 0, $length);
  $input += $replacement + $tail;
  return $extracted;
};

Apart from preserving the keys, it behaves just like the regular array_splice() for all cases I could think of.

So for example the regular array_splice()

$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
print_r(array_splice($input, -4, 3, array('foo1' => 'bar', 'foo2' => 'baz')));
print_r($input);

will give:

Array
(
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [a] => 1
    [b] => 2
    [0] => bar
    [1] => baz
    [f] => 6
)

But with array_splice_assoc()

$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
print_r(array_splice_assoc($input, -4, 3, array('foo1' => 'bar', 'foo2' => 'baz')));
print_r($input);

we get:

Array
(
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [a] => 1
    [b] => 2
    [foo1] => bar
    [foo2] => baz
    [f] => 6
)

A typical use case would be replacing an element identified by a particular key, which we could achieve with:

$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
array_splice_assoc($input, array_search('d', array_keys($input)), 1, array('foo' => 'bar'));
print_r($input);

giving us:

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
    [foo] => bar
    [e] => 5
    [f] => 6
)
thom 02-Jan-2014 02:31
Maybe it will help someone else: I was trying to strip off the last part of an array using this section, more or less as follows:

<?php array_splice($array, $offset); ?>

Now it could occur in my code that <?php $offset === 0 ?>, in which case the array is returned as-is and not, as you might expect, an empty array because everything is stripped off. Obviously it is not really useful anyway to "strip off everything", but I was reminded of that the hard way and this may spare someone some time, hopefully.
royanee at yahoo dot com 25-Jan-2013 05:03
When trying to splice an associative array into another, array_splice is missing two key ingredients:
  - a string key for identifying the offset
  - the ability to preserve keys in the replacement array

This is primarily useful when you want to replace an item in an array with another item, but want to maintain the ordering of the array without rebuilding the array one entry at a time.

<?php
function array_splice_assoc(&$input, $offset, $length, $replacement) {
        $replacement = (array) $replacement;
        $key_indices = array_flip(array_keys($input));
        if (isset($input[$offset]) && is_string($offset)) {
                $offset = $key_indices[$offset];
        }
        if (isset($input[$length]) && is_string($length)) {
                $length = $key_indices[$length] - $offset;
        }

        $input = array_slice($input, 0, $offset, TRUE)
                + $replacement
                + array_slice($input, $offset + $length, NULL, TRUE);
}

$fruit = array(
        'orange' => 'orange',
        'lemon' => 'yellow',
        'lime' => 'green',
        'grape' => 'purple',
        'cherry' => 'red',
);

// Replace lemon and lime with apple
array_splice_assoc($fruit, 'lemon', 'grape', array('apple' => 'red'));

// Replace cherry with strawberry
array_splice_assoc($fruit, 'cherry', 1, array('strawberry' => 'red'));
?>

Note: I have not tested this with negative offsets and lengths.
mrsohailkhan at gmail dot com 21-Oct-2011 12:34
array_splice, split an array into 2 arrays. The returned arrays is the 2nd argument actually and the used array e.g $input here contains the 1st argument of array, e.g

<?php
$input = array("red", "green", "blue", "yellow");
print_r(array_splice($input, 3)); // Array ( [0] => yellow )
print_r($input); //Array ( [0] => red [1] => green [2] => blue )
?>

if you want to replace any array value do simple like that,

first search the array index you want to replace

<?php $index = array_search('green', $input);// index = 1 ?>

and then use it as according to the definition

<?php
array_splice($input, $index, 1, array('mygreeen')); //Array ( [0] => red [1] => mygreeen [2] => blue [3] => yellow )
?>

so here green is replaced by mygreen.

here 1 in array_splice above represent the number of items to be replaced. so here start at index '1' and replaced only one item which is 'green'
news_yodpeirs at thoftware dot de 20-Jul-2011 08:20
Sometimes you may want to insert one array into another and just work on with the resulting array. array_splice() doesn't support this, as the resulting array isn't the returned value but the first argument, which is changed by reference.

Therefore you may use the following function, which inserts array $ins in array $src at position $pos. $rep can be used if $ins shouldn't be just inserted, but should replace some existing elements (the number of elements to be replaced is given in $rep).

<?php
function array_insert($src,$ins,$pos,$rep=0) {
  array_splice($src,$pos,$rep,$ins);
  return($src);
}
?>
charette dot s at gmail 21-Jul-2010 08:26
If you want to append null values wrap them in an array:

<?php

    $a = array('Hey', 'hey', 'my', 'my');
    array_splice($a, 1, 0, null);
    print_r($a);

?>
Array
(
    [0] => Hey
    [1] => hey
    [2] => my
    [3] => my
)

<?php

    $b = array('Hey', 'hey', 'my', 'my');
    array_splice($b, 1, 0, array(null));
    print_r($b);

?>
Array
(
    [0] => Hey
    [1] =>
    [2] => hey
    [3] => my
    [4] => my
)
news_yodpeirs at thoftware dot de 01-Apr-2010 01:32
Splicing with NULL as replacement may result in unexpected behavior too. Typecasting NULL into an array results in an empty array (as "(array)NULL" equals "array()"). That means, instead of creating an element with value NULL just no new element ist created (just as if there was no replacement specified).

If you want the splicing to create a new element with value NULL you have to use "array(NULL)" instead of NULL.

You should expect this if you read the explanation carefully, but just as objects are considered as a special case for replacement, NULL should be too.

The explanation of replacement better should read: "If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL."

And the note better should be: "If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object or NULL replacement."

jmtc
daniele centamore 02-Aug-2009 07:48
just useful functions to move an element using array_splice.

<?php

// info at danielecentamore dot com

// $input  (Array) - the array containing the element
// $index (int) - the index of the element you need to move

function moveUp($input,$index) {
      $new_array = $input;

       if((count($new_array)>$index) && ($index>0)){
                 array_splice($new_array, $index-1, 0, $input[$index]);
                 array_splice($new_array, $index+1, 1);
             }

       return $new_array;
}

function moveDown($input,$index) {
       $new_array = $input;

       if(count($new_array)>$index) {
                 array_splice($new_array, $index+2, 0, $input[$index]);
                 array_splice($new_array, $index, 1);
             }

       return $new_array;
 }

$input = array("red", "green", "blue", "yellow");

$newinput = moveUp($input, 2);
// $newinput is array("red", "blue", "green", "yellow")

$input = moveDown($newinput, 1);
// $input is array("red", "green", "blue", "yellow")

?>
strata_ranger at hotmail dot com 01-Jul-2009 11:53
Should you want a similar function for splicing strings together, here is a rough equivalent:

<?php
function str_splice($input, $offset, $length=null, $splice='')
{
  $input = (string)$input;
  $splice = (string)$splice;
  $count = strlen($input);

  // Offset handling (negative values measure from end of string)
  if ($offset<0) $offset = $count + $offset;

  // Length handling (positive values measure from $offset; negative, from end of string; omitted = end of string)
  if (is_null($length)) $length = $count;
  elseif ($length < 0)  $length = $count-$offset+$length;

  // Do the splice
  return substr($input, 0, $offset) . $splice . substr($input, $offset+$length);
}

$string = "The fox jumped over the lazy dog.";

// Outputs "The quick brown fox jumped over the lazy dog."
echo str_splice($string, 4, 0, "quick brown ");

?>

Obviously this is not for cases where all you need to do is a simple search-and-replace.
dead dot screamer at seznam dot cz 12-Feb-2009 05:28
I need <?php array_Splice()?> function, that use array keys instead of order (offset and length) because of associated arrays, and this is result:

<?php
/**
 *    first variation
 *
 *    $input is input array
 *    $start is index of slice begin
 *    $end is index of slice end, if this is null, $replacement will be inserted (in the same way as original array_Slice())
 *indexes of $replacement are preserved in both examples
 */
function array_KSplice1(&$input, $start, $end=null, $replacement=null)
{
    $keys=array_Keys($input);
    $values=array_Values($input);
    if($replacement!==null)
    {
        $replacement=(array)$replacement;
        $rKeys=array_Keys($replacement);
        $rValues=array_Values($replacement);
    }

    $start=array_Search($start,$keys,true);
    if($start===false)
        return false;
    if($end!==null)
    {
        $end=array_Search($end,$keys,true);
        // if $end not found, exit
        if($end===false)
            return false;
        // if $end is before $start, exit
        if($end<$start)
            return false;
        // index to length
        $end-=$start-1;
    }

    // optional arguments
    if($replacement!==null)
    {
        array_Splice($keys,$start,$end,$rKeys);
        array_Splice($values,$start,$end,$rValues);
    }
    else
    {
        array_Splice($keys,$start,$end);
        array_Splice($values,$start,$end);
    }

    $input=array_Combine($keys,$values);

    return $input;
}

/**
 *    second variation
 *
 *    $input is input array
 *    $start is index of slice begin
 *    $length is length of slice, what will be replaced, if is zero, $replacement will be inserted (in the same way as original array_Slice())
 */
function array_KSplice2(&$input, $start, $length=0, $replacement=null)
{
    $keys=array_Keys($input);
    $values=array_Values($input);
    if($replacement!==null)
    {
        $replacement=(array)$replacement;
        $rKeys=array_Keys($replacement);
        $rValues=array_Values($replacement);
    }

    $start=array_Search($start,$keys,true);
    if($start===false)
        return false;

    // optional arguments
    if($replacement!==null)
    {
        array_Splice($keys,$start,$length,$rKeys);
        array_Splice($values,$start,$length,$rValues);
    }
    else
    {
        array_Splice($keys,$start,$length);
        array_Splice($values,$start,$length);
    }

    $input=array_Combine($keys,$values);

    return $input;
}

$array=range(1,10);
var_Dump(array_KSplice1($array,3,3,array(100=>101,102,103,104)));

$array=range(1,10);
var_Dump(array_KSplice2($array,3,3,array(100=>101,102,103,104)));

?>

Both examples output:
array(11) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [100]=>
  int(101)
  [101]=>
  int(102)
  [102]=>
  int(103)
  [103]=>
  int(104)
  [6]=>
  int(7)
  [7]=>
  int(8)
  [8]=>
  int(9)
  [9]=>
  int(10)
}
madmax at max-worlds dot net 23-Sep-2008 06:23
Note:  If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object replacement .

Example :

<?php
class A()
{
    private $a;
    private $b;
    public function __construct()
    {
        $this->a = "foo";
        $this->b = "bar";
    }
}

$array = array();
array_splice($array, 0, 0, new A());
print_r($array);
?>

Outputs :

Array : Array
{
    [0] => foo
    [1] => bar
}

Solution : Enforce the array() on the object.

<?php
array_splice($array, 0, 0, array(new Object());
?>

Source : http://bugs.php.net/bug.php?id=44485
loushou - life dot 42 at gmail dot com 27-Jul-2008 04:39
i miss posted the actual function...
here is the real one lol

<?php

function q_sort(&$Info, $Index, $Left, $Right)
{
  echo "memory usage <b>".memory_get_usage()."</b><br/>\n";
  $L_hold = $Left;
  $R_hold = $Right;
  $Pivot = $Left;
  $PivotValue = $Info[$Left];
  while ($Left < $Right)
  {
    while (($Info[$Right][$Index] >= $PivotValue[$Index]) && ($Left < $Right))
      $Right--;
    if ($Left != $Right)
    {
      $Info[$Left] = $Info[$Right];
      $Left++;
    }
    while (($Info[$Left][$Index] <= $PivotValue[$Index]) && ($Left < $Right))
      $Left++;
    if ($Left != $Right)
    {
      $Info[$Right] = $Info[$Left];
      $Right--;
    }
  }
  $Info[$Left] = $PivotValue;
  $Pivot = $Left;
  $Left = $L_hold;
  $Right = $R_hold;
  if ($Left < $Pivot)
    q_sort($Info, $Index, $Left, $Pivot-1);
  if ($Right > $Pivot)
    q_sort($Info, $Index, $Pivot+1, $Right);
}

?>
Francis 27-Apr-2008 12:27
Do you need to sort a 2D array on just one of its variables while trying to preserve somewhat the original order?

<?php

function sort_2d_array($array, $position, $order = "ASC"){
  if (!is_array($array)) return $array;
  if (count($array) < 2) return $array;
  $new = array($array[0]);
  for ($cnt = 1; $cnt <= count($array) - 1; $cnt++){
    $stop = 0;
    $splice = 0;
    for ($newcnt = 0; $newcnt <= count($new) - 1; $newcnt++){
      if ($stop == 0){
        if ($order == "ASC")
        if ($array[$cnt][$position] < $new[$newcnt][$position]){
          $splice = $newcnt;
          $stop = 1;
        } // splice position for ASC
        if ($order == "DESC")
        if ($array[$cnt][$position] > $new[$newcnt][$position]){
          $splice = $newcnt;
          $stop = 1;
        } // splice position for DESC
      } // stop vying for position
    } // cycle through new array to find position
    if ($stop == 0){
      $new[] = $array[$cnt];
    } else {
      array_splice($new, $splice, 0, array($array[$cnt]));
    } // splice into new array while keeping somewhat the original order
  } // cycle through original array
  return $new;
} // sort_2d_array

?>

Application Example: In-House Search Engine
Here we are trying to find the word apple in the website by sort of the most recent occurances first, but the number of occurances first.

We've already sorted the mysql output by the date desc and have counted the no of occurances and have placed those in an array for the final query.

I've used this function to further sort the occurances but somewhat keep the original mysql sort order.

Key
[0] Record number
     [0] Record ID
     [1] Source Table
     [2] No of Occurances Pinged

  ---------------------------

[0]
     [0] 24530
     [1] Blogs
     [2] 1

[1]
     [0] 24400
     [1] Blogs
     [2] 1

[2]
     [0] 24240
     [1] Blogs
     [2] 4

[3]
     [0] 243422
     [1] Classifieds
     [2] 1

[4]
     [0] 243100
     [1] Classifieds
     [2] 1

After running...

<?php
sort_2d_array($array, 2, "DESC");
?>

We have...

[0]
     [0] 24240
     [1] Blogs
     [2] 4

[1]
     [0] 24530
     [1] Blogs
     [2] 1

[2]
     [0] 24400
     [1] Blogs
     [2] 1

[3]
     [0] 243422
     [1] Classifieds
     [2] 1

[4]
     [0] 243100
     [1] Classifieds
     [2] 1

Might be useful to someone...
pauljamescampbell at gmail dot com 06-Feb-2008 06:46
Here's my own take on an array slice method that preserves keys from an associative array.

<?php
/**
 * Array slice function that preserves associative keys
 *
 * @function associativeArraySlice
 *
 * @param  Array  $array  Array to slice
 * @param  Integer  $start
 * @param  Integer  $end
 *
 * @return  Array
 */
function associativeArraySlice($array, $start, $end) {
    // Method param restrictions
    if($start < 0) $start = 0;
    if($end > count($array)) $end = count($array);

    // Process vars
    $new = Array();
    $i = 0;

    // Loop
    foreach($array as $key => $value) {
        if($i >= $start && $i < $end) {
            $new[$key] = $value;
        }
        $i++;
    }
    return($new);
}
?>
mip at ycn dot com 08-Mar-2007 05:37
Ever wounder what array_splice is doing to your references, then try this little script and see the output.

<?php

$a = "a";
$b = "b";
$c = "c";
$d = "d";
$arr = array();
$arr[] =& $a;
$arr[] =& $b;
$arr[] =& $c;
array_splice($arr,1,0,array($d));
$sec_arr = array();
$sec_arr[] =& $d;
array_splice($arr,1,0,$sec_arr);

$arr[0] = "test"; // should be $a
$arr[3] = "test2"; // should be $b
$arr[1] = "this be d?"; // should be $d
$arr[2] = "or this be d?"; // should be $d
var_dump($arr);
var_dump($a);
var_dump($b);
var_dump($d);
?>

The output will be (PHP 4.3.3):

array(5) {
  [0]=>
  &string(4) "test"
  [1]=>
  &string(10) "this be d?"
  [2]=>
  string(13) "or this be d?"
  [3]=>
  &string(5) "test2"
  [4]=>
  &string(1) "c"
}
string(4) "test"
string(5) "test2"
string(10) "this be d?"

So array_splice is reference safe, but you have to be careful about the generation of the replacement array.

have fun, cheers!
ahigerd at stratitec dot com 24-Jan-2007 06:07
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
bdjumakov at gmail dot com 31-Aug-2006 12:11
Someone might find this function usefull. It just takes a given element from the array and moves it before given element into the same array.

<?php
function array_move($which, $where, $array)
{
    $tmp  = array_splice($array, $which, 1);
    array_splice($array, $where, 0, $tmp);
    return $array;
}
?>
Paul 11-Feb-2006 10:06
In PHP 4.3.10, at least, it seems that elements that are inserted as part of the replacement array are inserted BY REFERENCE (that is, as though with the =& rather than = assignment operation). So if your replacement array contains elements that references to variables that you can also access via other variable name, then this will be true of the elements in the final array too.

In particular, this means that it is safe to use array_splice() on arrays of objects, as you won't be creating copies of the objects (as it is so easy to do in PHP 4).
weikard at gmx dot de 15-Sep-2005 05:53
You cannot insert with array_splice an array with your own key. array_splice will always insert it with the key "0".

<?php
// [DATA]
$test_array = array (
  row1 => array (col1 => 'foobar!', col2 => 'foobar!'),
  row2 => array (col1 => 'foobar!', col2 => 'foobar!'),
  row3 => array (col1 => 'foobar!', col2 => 'foobar!')
);

// [ACTION]
array_splice ($test_array, 2, 0, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
    [row1] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [row2] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [0] => Array (
            [colX] => foobar2
        )

    [row3] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )
)

But you can use the following function:

function array_insert (&$array, $position, $insert_array) {
  $first_array = array_splice ($array, 0, $position);
  $array = array_merge ($first_array, $insert_array, $array);
}

<?php
// [ACTION]

array_insert ($test_array, 2, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
    [row1] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [row2] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [rowX] => Array (
            [colX] => foobar2
        )

    [row3] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )
)

[NOTE]

The position "0" will insert the array in the first position (like array_shift). If you try a position higher than the langth of the array, you add it to the array like the function array_push.
csaba at alum dot mit dot edu 13-Aug-2005 02:31
Appending arrays
If you have an array $a2 whose values you would like to append to an array $a1 then four methods you could use are listed below in order of increasing time.  The last two methods took significantly more time than the first two.  The most surprising lesson is that using the & incurs a time hit.

<?php
foreach ($a2 as $elem) $a1[]=$elem;
foreach ($a2 as &$elem) $a1[]=$elem;
array_splice ($a1, count($a1), 0, $a2);
$a1 = array_merge($a1, $a2);
?>

Csaba Gabor from Vienna
randomdestination at gmail dot com 22-Jul-2005 01:52
To split an associative array based on it's keys, use this function:

<?php
function &array_split(&$in) {
    $keys = func_get_args();
    array_shift($keys);

    $out = array();
    foreach($keys as $key) {
        if(isset($in[$key]))
            $out[$key] = $in[$key];
        else
            $out[$key] = null;
        unset($in[$key]);
    }

    return $out;
}
?>

Example:
<?php
$testin = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$testout =& array_split($testin, 'a', 'b', 'c');

print_r($testin);
print_r($testout);
?>

Will print:

Array
(
    [d] => 4
)
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

Hope this helps anyone!
gideon at i6developments dot com 17-Jul-2004 09:45
array_splice dynamically updates the total number of entries into the array. So for instance I had a case where I needed to insert a value into every 4th entry of the array from the back. The problem was when it added the first, because the total number was dynamically updated, it would only add after the 3rd then the 2nd and so one. The solution I found is to track the number of inserts which were done and account for them dynamically.

Code:
<?php
    $modarray = array_reverse($mili);
    $trig=1;
        foreach($modarray as $rubber => $glue) {
            if($rubber!="<BR>") {
            $i++;
            $b++;
            if ($i==4) {
                $trig++;
                if($trig<=2) {
                array_splice($modarray,$b,0,"<BR>");
                }elseif($trig>=3){
                array_splice($modarray,$b+($trig-2),0,"<BR>");
                }
                $i=0;
                };
                };
        };
    $fixarray = array_reverse($modarray);

?>
rolandfoxx at yahoo dot com 30-Mar-2004 12:16
Be careful, array_splice does not behave like you might expect should you try to pass it an object as the replacement argument.  Consider the following:

<?php
//Very truncated
class Tree {
  var $childNodes

  function addChild($offset, $node) {
    array_splice($this->childNodes, $offset, 0, $node);
    //...rest of function
  }

}

class Node {
  var $stuff
  ...
}

$tree = new Tree();
// ...set 2 nodes using other functions...
echo (count($tree->childNodes)); //Gives 2
$newNode = new Node();
// ...set node attributes here...
$tree->addChild(1, $newNode);
echo(count($tree->childNodes)); //Expect 3?  wrong!
?>

In this case, the array has a number of items added to it equal to the number of attributes in the new Node object and the values thereof  I.e, if your Node object has 2 attributes with values "foo" and "bar", count($tree->childNodes) will now return 4, with the items "foo" and "bar" added to it.  I'm not sure if this qualifies as a bug, or is just a byproduct of how PHP handles objects.

Here's a workaround for this problem:
function array_insertobj(&$array, $offset, $insert) {
  $firstPart = array_slice($array, 0, $offset);
  $secondPart = array_slice($array, $offset);
  $insertPart = array($insert);
  $array = array_merge($firstPart, $insertPart, $secondPart);
}

Note that this function makes no allowances for when $offset equals the first or last index in the array.  That's because array_unshift and array_push work just fine in those cases.  It's only array_splice that can trip you up.  Obviously, this is kinda tailor-made for arrays with numeric keys when you don't really care what said keys are, but i'm sure you could adapt it for associative arrays if you needed it.
kbrown at horizon dot sk dot ca 11-Aug-2003 12:40
[ Editor's Note: If you're not concerned with the indexes being contiguously numbered (such as for an associative array) then unset($ar[$ind]); will accomplish the same as the code below without requiring splice/splice/merge.  If contiguous numbering IS a concern (such as for indexed arrays), you can still save time by using: unset($ar[$ind]); $ar = array_values($ar); ]

Removing elements from arrays

This works better - much quicker

<?php
$ar = array("einstein", "bert", "colin", "descartes", "renoir");
$a = array_slice($ar, 0, $ind);
$b = array_slice($ar, $ind + 1);
$ar = array_merge($a, $b);
?>
plintus at smtp dot ru 14-Apr-2003 01:59
key-safe:

<?php
function array_kslice ($array, $offset, $length = 0) {
$k = array_slice (array_keys ($array), $offset, $length);
$v = array_slice (array_values ($array), $offset, $length);
for ($i = 0; $i < count ($k); $i ++) $r[$k[$i]] = $v[$i];
return $r;
}
?>

smth like this. hope you like it more than versions above :)
tsunaquake DOESNTLIKESPAM @ wp DOT pl 11-Nov-2002 10:56
It is possible to use a string instead of offset, eg if you want to deletre the entry $myArray['entry'] then you can simply do it like this:

<?php
array_splice($myArray, 'entry', 1);
?>

Note that you can use unset($myArray['entry']) as well but then, it doesn't enable you to remove more than one entry and it doesn't replace anything in the array, if that's what you intend to do.
18-Jun-2002 07:14
Please note that array_splice() 's second argument is an OFFSET and not an INDEX.

Lets say you want to
$array_of_items = array ('nothing','myitem','hisitem','heritem');
$sid = array_search('myitem',$array_of_items);
echo $sid; /* prints out 1, since index element 1 is "myitem" */

Now, lets say we want to remove that "myitem" from the array:

<?php
$array_of_items = array_splice($array_of_items,(1+$sid),1);
?>

Notice how you have to add a one to the $sid variable?  That is because offset item 1 is "nothing" and since $sid is currently 1 (the index of "myitem"), we add 1 more to it to find out
 its OFFSET.

DO NOT DO THIS:
 $array_of_items = array_splice($array_of_items,$sid,1);
paule at cs dot tamu dot edu 12-Jun-2002 09:59
to kokos@lac.lviv.ua:

Good point about the code not doing what you expected.

The failure to check for the insert case like you pointed out is not a bug, however. I didn't add code to handle that because the key of such an added index is more or less undefined in an unordered associative array. Put another way, if your array is associative and not auto-indexed, you most likely care enough about your keys to want to set them explicitly.
paule at cs dot tamu dot edu 06-Jun-2002 11:09
After reading KoKos' post above, I thought that the code I posted right before his should do what he wanted. However, my original post neglected to note the little "Tip" in the documentation above, about a single element replacement.

If one changes the lines in my code above that says:

<?php
                if(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
?>

to instead say:

<?php
                if(is_string($replacement))
                    $new_array[$key]=$replacement;
                elseif(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
?>

that will solve the problem.

Sorry for the omission.
kokos at lac dot lviv dot ua 06-Jun-2002 08:26
It may seem obvious from the above posts, but cost me a bit of
braindamage to figure this out...

Contrary to the equivalence noted on this page
$input[$x] = $y   <==>   array_splice ($input, $x, 1, $y)
array_splice() will not always work as expected,
even provided that you have only INTEGER keys!

The following code:
   $t=array('a','b','c','d','e');
   var_dump($t);

<?php
   unset($t[0],$t[1],$t[3]);
   $t[0]='f';
   var_dump($t);

   array_splice($t,0,1,'g');
   var_dump($t);
?>

Will produce:
array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
}
array(3) {
  [2]=>
  string(1) "c"
  [4]=>
  string(1) "e"
  [0]=>
  string(1) "f"
}
array(3) {
  [0]=>
  string(1) "g"
  [1]=>
  string(1) "e"
  [2]=>
  string(1) "f"
}

Note the position of $t[0] in the second call to var_dump().
And of course, array_splice() left it intact, changing $t[2] instead.
This is because it operates the _offset_, not the _index_.  :)
I think that "equivalence note" should be considered buggy.  ;)))

Best wishes.
KoKos.
jrhardytwothousandtwo at yahoo dot com 14-Feb-2002 11:54
A reference is made to INSERT'ing into an array here with array_splice, however its not explained very well.  I hope this example will help others find what took me days to research.

<?php
$original_array = array(1,2,3,4,5);
$insert_into_key_position = 3;
$item_to_insert = "blue";

$returned = array_splice($original_array, $insert_into_key_position, 0, $item_to_insert);

// $original_array will now show:

// 1,2,3,blue,4,5
?>

Remember that you are telling the array to insert the element into the KEY position.  Thus the elements start with key 0 and so on 0=>1, 1=>2, 2=>3, 3=>blue, 4=>4, 5=>5.  And walla, you've inserted.  I can't say if this is of any value for named keys, or multidimensional arrays.  However it does work for single dimensional arrays.

$returned should be an empty array as nothing was returned.  This would have substance if you were doing a replace instead.
leingang AT math DOT rutgers DOT edu 15-Jan-2002 07:32
array_splice resets the internal pointer of $input.  In fact, many array functions do this.  Caveat programmor!


Calcular la suma de los valores de un array

  • « array_splice
  • array_udiff_assoc »
  • PHP Manual
  • Funciones de Arrays
  • Calcular la suma de los valores de un array

array_sum

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

array_sum — Calcular la suma de los valores de un array

Descripción

array_sum ( array $array ) : number

array_sum() devuelve la suma de los valores de un array.

Parámetros

array

El array de entrada.

Valores devueltos

Devuelve la suma de los valores como un valor de tipo integer o float; 0 si el array está vacío.

Ejemplos

Ejemplo #1 Ejemplos de array_sum()

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

El resultado del ejemplo sería:

sum(a) = 20
sum(b) = 6.9

User Contributed Notes

There are no user contributed notes for this page.


Computa la diferencia entre arrays con una comprobación de indices adicional, compara la información mediante una función de llamada de retorno

  • « array_sum
  • array_udiff_uassoc »
  • PHP Manual
  • Funciones de Arrays
  • Computa la diferencia entre arrays con una comprobación de indices adicional, compara la información mediante una función de llamada de retorno

array_udiff_assoc

(PHP 5, PHP 7, PHP 8)

array_udiff_assoc — Computa la diferencia entre arrays con una comprobación de indices adicional, compara la información mediante una función de llamada de retorno

Descripción

array_udiff_assoc ( array $array1 , array $array2 , array $... = ? , callable $value_compare_func ) : array

Computa la diferencia entre arrays con una comprobación de indices adicional, compara la información mediante una función de llamada de retorno.

Nota: Por favor, observe que esta función sólo comprueba una dimensión de un array n-dimensional. Por supuesto, se pueden comprobar dimensiones más profundas usando, por ejemplo, array_udiff_assoc($array1[0], $array2[0], "alguna_func_comparacion");.

Parámetros

array1

El primer array.

array2

El segundo array.

value_compare_func

La función de comparación debe devolver un entero menor, igual o mayor que cero si el primer argumento se considera que sea respectivamente menor, igual o mayor que el segundo. Observe que antes de PHP 7.0.0 este entero debía estar en el rango de -2147483648 a 2147483647.

callback ( mixed $a, mixed $b ) : int

Valores devueltos

array_udiff_assoc() devuelve un array que contiene todos los valores de array1 que no están presentes en ninguno de los demás argumentos. Observe que las claves se usan en la comparación a diferencia de array_diff() y array_udiff(). La comparación de la información de los arrays' se lleva a cabo usando una llamada de retorno proporcionada por el usuario. En este aspecto, el comportamiento es opuesto al de array_diff_assoc(), que usa una función interna para la comparación.

Ejemplos

Ejemplo #1 Ejemplo de array_udiff_assoc()

<?php
class cr {
    private $miembro_privado;
    function cr($val)
    {
        $this->miembro_privado = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->miembro_privado === $b->miembro_privado) return 0;
        return ($a->miembro_privado > $b->miembro_privado)? 1:-1;
    }
}

$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$resultado = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($resultado);
?>

El resultado del ejemplo sería:

Array
(
    [0.1] => cr Object
        (
            [miembro_privado:private] => 9
        )

    [0.5] => cr Object
        (
            [miembro_privado:private] => 12
        )

    [0] => cr Object
        (
            [miembro_privado:private] => 23
        )
)

En el ejemplo de arriba se ve que el par "1" => new cr(4) está presente en ambos arrays, y que, de esta manera, no está en la salida de la función.

Ver también

  • array_diff() - Calcula la diferencia entre arrays
  • array_diff_assoc() - Calcula la diferencia entre arrays con un chequeo adicional de índices
  • array_diff_uassoc() - Calcula la diferencia entre arrays con un chequeo adicional de índices que se realiza por una función de devolución de llamada suministrada por el usuario
  • array_udiff() - Computa la diferencia entre arrays, usando una llamada de retorno para la comparación de datos
  • array_udiff_uassoc() - Computa la diferencia entre arrays con una verificación de índices adicional, compara la información y los índices mediante una función de llamada de retorno
  • array_intersect() - Calcula la intersección de arrays
  • array_intersect_assoc() - Calcula la intersección de arrays con un chequeo adicional de índices
  • array_uintersect() - Computa una intersección de arrays, compara la información mediante una función de llamada de retorno
  • array_uintersect_assoc() - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información mediante una función de retrollamada
  • array_uintersect_uassoc() - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información y los índices mediante funciones de retrollamada por separado

User Contributed Notes

m dot ario dot huq at gmail dot com 05-Mar-2018 06:28
The example #1 can be modified (PHP 7 or higher) by using Spaceship operator (<=>):

<?php
//…
static function comp_func_cr($a, $b)
{
    return $a->priv_member <=> $b->priv_member;
}
//…
?>
tmquang6805 at yahoo dot com 25-May-2014 09:54
Difference between array_udiff_assoc() and array_diff_assoc()

- array_udiff_assoc(): Compares the DATA with the user supplied callback function
- array_diff_assoc(): Compares the INDEX with the user supplied callback function


Computa la diferencia entre arrays con una verificación de índices adicional, compara la información y los índices mediante una función de llamada de retorno

  • « array_udiff_assoc
  • array_udiff »
  • PHP Manual
  • Funciones de Arrays
  • Computa la diferencia entre arrays con una verificación de índices adicional, compara la información y los índices mediante una función de llamada de retorno

array_udiff_uassoc

(PHP 5, PHP 7, PHP 8)

array_udiff_uassoc — Computa la diferencia entre arrays con una verificación de índices adicional, compara la información y los índices mediante una función de llamada de retorno

Descripción

array_udiff_uassoc ( array $array1 , array $array2 , array $... = ? , callable $value_compare_func , callable $key_compare_func ) : array

Computa la diferencia entre arrays con una verificación de índices adicional, compara la información y los índices mediante una función de llamada de retorno.

Observe que las claves son usadas en la comparación, a diferencia de array_diff() y array_udiff().

Parámetros

array1

El primer array.

array2

El segundo array.

value_compare_func

La función de comparación debe devolver un entero menor, igual o mayor que cero si el primer argumento se considera que sea respectivamente menor, igual o mayor que el segundo. Observe que antes de PHP 7.0.0 este entero debía estar en el rango de -2147483648 a 2147483647.

callback ( mixed $a, mixed $b ) : int
key_compare_func

La comparación de las claves (índices) se hace también mediante la función de llamada de retorno key_compare_func. Este comportamiento es diferente del de array_udiff_assoc(), ya que esta última compara los índices usando una función interna.

Valores devueltos

Devuelve un array que contiene todos los valores de array1 que no están presentes en ningno de los demás argumentos.

Ejemplos

Ejemplo #1 Ejemplo de array_udiff_uassoc()

<?php
class cr {
    private $miembro_privado;
    function cr($val)
    {
        $this->miembro_privado = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->miembro_privado === $b->miembro_privado) return 0;
        return ($a->miembro_privado > $b->miembro_privado)? 1:-1;
    }

    static function comp_func_key($a, $b)
    {
        if ($a === $b) return 0;
        return ($a > $b)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$resultado = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($resultado);
?>

El resultado del ejemplo sería:

Array
(
    [0.1] => cr Object
        (
            [miembro_privado:private] => 9
        )

    [0.5] => cr Object
        (
            [miembro_privado:private] => 12
        )

    [0] => cr Object
        (
            [miembro_privado:private] => 23
        )
)

En el ejemplo de arriba se ve que el par "1" => new cr(4) está presente en ambos arrays, y que, de esta manera, no está en la salida de la función. Recuerde que debe de proporcionar 2 funciones de llamada de retorno.

Notas

Nota: Por favor, observe que esta función sólo comprueba una dimensión de un array n-dimensional. Por supuesto, se pueden comprobar dimensiones más profundas usando, por ejemplo, array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func");.

Ver también

  • array_diff() - Calcula la diferencia entre arrays
  • array_diff_assoc() - Calcula la diferencia entre arrays con un chequeo adicional de índices
  • array_udiff() - Computa la diferencia entre arrays, usando una llamada de retorno para la comparación de datos
  • array_udiff_assoc() - Computa la diferencia entre arrays con una comprobación de indices adicional, compara la información mediante una función de llamada de retorno
  • array_intersect() - Calcula la intersección de arrays
  • array_intersect_assoc() - Calcula la intersección de arrays con un chequeo adicional de índices
  • array_uintersect() - Computa una intersección de arrays, compara la información mediante una función de llamada de retorno
  • array_uintersect_assoc() - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información mediante una función de retrollamada
  • array_uintersect_uassoc() - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información y los índices mediante funciones de retrollamada por separado

User Contributed Notes

There are no user contributed notes for this page.


Computa la diferencia entre arrays, usando una llamada de retorno para la comparación de datos

  • « array_udiff_uassoc
  • array_uintersect_assoc »
  • PHP Manual
  • Funciones de Arrays
  • Computa la diferencia entre arrays, usando una llamada de retorno para la comparación de datos

array_udiff

(PHP 5, PHP 7, PHP 8)

array_udiff — Computa la diferencia entre arrays, usando una llamada de retorno para la comparación de datos

Descripción

array_udiff ( array $array1 , array $array2 , array $... = ? , callable $value_compare_func ) : array

Computa la diferencia de los arrays usando una función tipo llamada de retorno para la comparación de datos. Esto difiere de array_diff(), la cual usa una función interna para la comparación de datos.

Parámetros

array1

El primer array.

array2

El segundo array

value_compare_func

La función llamada de retorno para la comparación.

La función de comparación debe devolver un entero menor, igual o mayor que cero si el primer argumento se considera que sea respectivamente menor, igual o mayor que el segundo. Observe que antes de PHP 7.0.0 este entero debía estar en el rango de -2147483648 a 2147483647.

callback ( mixed $a, mixed $b ) : int

Valores devueltos

Devuelve un array que contiene todos los valores de array1 que no están presentes en ninguno de los otros argumentos.

Ejemplos

Ejemplo #1 Ejemplo de array_udiff() usando objetos de stdClass

<?php
// Arrays a comparar
$array1 = array(new stdclass, new stdclass,
                new stdclass, new stdclass,
               );

$array2 = array(
                new stdclass, new stdclass,
               );

// Establecer algunas propiedades para cada objeto
$array1[0]->width = 11; $array1[0]->height = 3;
$array1[1]->width = 7;  $array1[1]->height = 1;
$array1[2]->width = 2;  $array1[2]->height = 9;
$array1[3]->width = 5;  $array1[3]->height = 7;

$array2[0]->width = 7;  $array2[0]->height = 5;
$array2[1]->width = 9;  $array2[1]->height = 2;

function compare_by_area($a, $b) {
    $areaA = $a->width * $a->height;
    $areaB = $b->width * $b->height;

    if ($areaA < $areaB) {
        return -1;
    } elseif ($areaA > $areaB) {
        return 1;
    } else {
        return 0;
    }
}

print_r(array_udiff($array1, $array2, 'compare_by_area'));
?>

El resultado del ejemplo sería:

Array
(
    [0] => stdClass Object
        (
            [width] => 11
            [height] => 3
        )

    [1] => stdClass Object
        (
            [width] => 7
            [height] => 1
        )

)

Ejemplo #2 Ejemplo de array_udiff() usando objetos de DateTime

<?php
class MyCalendar {
    public $free = array();
    public $booked = array();

    public function __construct($week = 'now') {
        $start = new DateTime($week);
        $start->modify('Monday this week midnight');
        $end = clone $start;
        $end->modify('Friday this week midnight');
        $interval = new DateInterval('P1D');
        foreach (new DatePeriod($start, $interval, $end) as $freeTime) {
            $this->free[] = $freeTime;
        }
    }

    public function bookAppointment(DateTime $date, $note) {
        $this->booked[] = array('date' => $date->modify('midnight'), 'note' => $note);
    }

    public function checkAvailability() {
        return array_udiff($this->free, $this->booked, array($this, 'customCompare'));
    }

    public function customCompare($free, $booked) {
        if (is_array($free)) $a = $free['date'];
        else $a = $free;
        if (is_array($booked)) $b = $booked['date'];
        else $b = $booked;
        if ($a == $b) {
            return 0;
        } elseif ($a > $b) {
            return 1;
        } else {
            return -1;
        }
    }
}

// Crear un calendario para citas semanales
$myCalendar = new MyCalendar;

// Anotar varias citas para esta semana
$myCalendar->bookAppointment(new DateTime('Monday this week'), "Cleaning GoogleGuy's apartment.");
$myCalendar->bookAppointment(new DateTime('Wednesday this week'), "Going on a snowboarding trip.");
$myCalendar->bookAppointment(new DateTime('Friday this week'), "Fixing buggy code.");

// Comprobar los días disponibles comparando las fechas de $booked con las de $free
echo "I'm available on the following days this week...\n\n";
foreach ($myCalendar->checkAvailability() as $free) {
    echo $free->format('l'), "\n";
}
echo "\n\n";
echo "I'm busy on the following days this week...\n\n";
foreach ($myCalendar->booked as $booked) {
    echo $booked['date']->format('l'), ": ", $booked['note'], "\n";
}
?>

El resultado del ejemplo sería:

I'm available on the following days this week...

Tuesday
Thursday

I'm busy on the following days this week...

Monday: Cleaning GoogleGuy's apartment.
Wednesday: Going on a snowboarding trip.
Friday: Fixing buggy code.

Notas

Nota: Por favor note que esta función sólo analiza una dimensión de un array n-dimensional. Por supuesto, puede analizar dimensiones más profundas usando array_udiff($array1[0], $array2[0], "data_compare_func");.

Ver también

  • array_diff() - Calcula la diferencia entre arrays
  • array_diff_assoc() - Calcula la diferencia entre arrays con un chequeo adicional de índices
  • array_diff_uassoc() - Calcula la diferencia entre arrays con un chequeo adicional de índices que se realiza por una función de devolución de llamada suministrada por el usuario
  • array_udiff_assoc() - Computa la diferencia entre arrays con una comprobación de indices adicional, compara la información mediante una función de llamada de retorno
  • array_udiff_uassoc() - Computa la diferencia entre arrays con una verificación de índices adicional, compara la información y los índices mediante una función de llamada de retorno
  • array_intersect() - Calcula la intersección de arrays
  • array_intersect_assoc() - Calcula la intersección de arrays con un chequeo adicional de índices
  • array_uintersect() - Computa una intersección de arrays, compara la información mediante una función de llamada de retorno
  • array_uintersect_assoc() - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información mediante una función de retrollamada
  • array_uintersect_uassoc() - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información y los índices mediante funciones de retrollamada por separado

User Contributed Notes

Jorge Morales (morales2k) 20-Dec-2018 02:17
I find it that this is an ideal place to apply the spaceship operator, but it was not used in the examples.

Here is Example#1 using the spaceship operator in the comparison function.

    <?php
    // Arrays to compare
    $array1 = array(new stdclass, new stdclass,
                    new stdclass, new stdclass,
                   );

    $array2 = array(
                    new stdclass, new stdclass,
                   );

    // Set some properties for each object
    $array1[0]->width = 11; $array1[0]->height = 3;
    $array1[1]->width = 7;  $array1[1]->height = 1;
    $array1[2]->width = 2;  $array1[2]->height = 9;
    $array1[3]->width = 5;  $array1[3]->height = 7;

    $array2[0]->width = 7;  $array2[0]->height = 5;
    $array2[1]->width = 9;  $array2[1]->height = 2;

    function compare_by_area($a, $b) {
        $areaA = $a->width * $a->height;
        $areaB = $b->width * $b->height;

        return $areaA <=> $areaB;
    }

    print_r(array_udiff($array1, $array2, 'compare_by_area'));
    ?>

The output is:
    Array
    (
        [0] => stdClass Object
            (
                [width] => 11
                [height] => 3
            )

        [1] => stdClass Object
            (
                [width] => 7
                [height] => 1
            )

    )

I find it is pretty awesome you can substitute all of these lines:
    if ($areaA < $areaB) {
        return -1;
    } elseif ($areaA > $areaB) {
        return 1;
    } else {
        return 0;
    }

with just:

    return $areaA <=> $areaB;

Neat!
napcoder 27-Jul-2016 08:38
Note that the compare function is used also internally, to order the arrays and choose which element compare against in the next round.

If your compare function is not really comparing (ie. returns 0 if elements are equals, 1 otherwise), you will receive an unexpected result.
b4301775 at klzlk dot com 15-Jun-2011 11:09
Quick example for using array_udiff to do a multi-dimensional diff

Returns values of $arr1 that are not in $arr2

<?php
$arr1 = array( array('Bob', 42), array('Phil', 37), array('Frank', 39) );

$arr2 = array( array('Phil', 37), array('Mark', 45) );

$arr3 = array_udiff($arr1, $arr2, create_function(
    '$a,$b',
    'return strcmp( implode("", $a), implode("", $b) ); ')
    );

print_r($arr3);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => Bob
            [1] => 42
        )

    [2] => Array
        (
            [0] => Frank
            [1] => 39
        )

)
1

Hope this helps someone
jared 07-Jul-2009 12:27
Note that php does the string conversion *before* sending the values to the callback function.
adam dot jorgensen dot za at gmail dot com 08-Oct-2008 06:51
It is not stated, by this function also diffs array1 to itself, removing any duplicate values...
grantwparks at gmail dot com 31-Dec-2007 07:15
Re: "convoluted"

I think the point being made is that array_udiff() can be used not only for comparisons between homogenous arrays, as in your example (and definitely the most common need), but it can be used to compare heterogeneous arrays, too.

Consider:

<?php
function compr_1($a, $b) {
    $aVal = is_array($a) ? $a['last_name'] : $a;
    $bVal = is_array($b) ? $b['last_name'] : $b;
    return strcasecmp($aVal, $bVal);
}

$aEmployees = array(
    array('last_name'  => 'Smith',
            'first_name' => 'Joe',
            'phone'      => '555-1000'),
    array('last_name'  => 'Doe',
            'first_name' => 'John',
            'phone'      => '555-2000'),
    array('last_name'  => 'Flagg',
            'first_name' => 'Randall',
            'phone'      => '666-1000')
    );

$aNames = array('Doe', 'Smith', 'Johnson');

$result = array_udiff($aEmployees, $aNames, "compr_1");

print_r($result);
?>

Allowing me to get the "employee" that's not in the name list:

Array ( [2] => Array ( [last_name] => Flagg [first_name] => Randall [phone] => 666-1000 ) )

Something interesting to note, is that the two arguments to the compare function don't correspond to array1 and array2.  That's why there has to be logic in it to handle that either of the arguments might be pointing to the more complex employee array.  (Found this out the hard way.)
Colin 02-Aug-2006 01:15
I think the example given here using classes is convoluting things too much to demonstrate what this function does.

array_udiff() will walk through array_values($a) and array_values($b) and compare each value by using the passed in callback function.

To put it another way, array_udiff() compares $a[0] to $b[0], $b[1], $b[2], and $b[3] using the provided callback function.  If the callback returns zero for any of the comparisons then $a[0] will not be in the returned array from array_udiff().  It then compares $a[1] to $b[0], $b[1], $b[2], and $b[3].  Then, finally, $a[2] to $b[0], $b[1], $b[2], and $b[3].

For example, compare_ids($a[0], $b[0]) === -5 while compare_ids($a[1], $b[1]) === 0.  Therefore, $a[1] is not returned from array_udiff() since it is present in $b.

<?
$a = array(
        array(
                'id' => 10,
                'name' => 'John',
                'color' => 'red',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
);

$b = array(
        array(
                'id' => 15,
                'name' => 'Nancy',
                'color' => 'black',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
        array(
                'id' => 40,
                'name' => 'John',
                'color' => 'orange',
        ),
);

function compare_ids($a, $b)
{
    return ($a['id'] - $b['id']);
}
function compare_names($a, $b)
{
    return strcmp($a['name'], $b['name']);
}

$ret = array_udiff($a, $b, 'compare_ids');
var_dump($ret);

$ret = array_udiff($b, $a, 'compare_ids');
var_dump($ret);

$ret = array_udiff($a, $b, 'compare_names');
var_dump($ret);
?>

Which returns the following.

In the first return we see that $b has no entry in it with an id of 10.
<?
array(1) {
  [0]=>
  array(3) {
    ["id"]=>
    int(10)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(3) "red"
  }
}
?>

In the second return we see that $a has no entry in it with an id of 15 or 40.
<?
array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    int(15)
    ["name"]=>
    string(5) "Nancy"
    ["color"]=>
    string(5) "black"
  }
  [3]=>
  array(3) {
    ["id"]=>
    int(40)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(6) "orange"
  }
}
?>

In third return we see that all names in $a are in $b (even though the entry in $b whose name is 'John' is different, the anonymous function is only comparing names).
<?
array(0) {
}
?>
dmhouse at gmail dot com 20-Jan-2005 01:44
Very easy way of achieving a case-insensitive version of array_diff (or indeed array_diff_assoc, array_intersect or any of these types of functions which have a similar function that takes a callback function as one of their parameters):

array_udiff($array1, $array2, 'strcasecmp');

This works because strcasecmp() compares two strings case-insensitively, as compared to the array_diff() which compares two strings by using the == operator, which is case-sensitive.
aidan at php dot net 28-May-2004 07:11
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat


Calcula la intersección de arrays con una comprobación de índices adicional, compara la información mediante una función de retrollamada

  • « array_udiff
  • array_uintersect_uassoc »
  • PHP Manual
  • Funciones de Arrays
  • Calcula la intersección de arrays con una comprobación de índices adicional, compara la información mediante una función de retrollamada

array_uintersect_assoc

(PHP 5, PHP 7, PHP 8)

array_uintersect_assoc — Calcula la intersección de arrays con una comprobación de índices adicional, compara la información mediante una función de retrollamada

Descripción

array_uintersect_assoc ( array $array1 , array $array2 , array $... = ? , callable $value_compare_func ) : array

Calcula la intersección de arrays con una comprobación de índices adicional, compara la información mediante una función de retrollamada.

Observe que las claves se usan en la comparación, a diferencia de array_uintersect(). La información se compara usando una función de retrollamada.

Parámetros

array1

El primer array.

array2

El segundo array.

value_compare_func

La función de comparación debe devolver un entero menor, igual o mayor que cero si el primer argumento se considera que sea respectivamente menor, igual o mayor que el segundo. Observe que antes de PHP 7.0.0 este entero debía estar en el rango de -2147483648 a 2147483647.

callback ( mixed $a, mixed $b ) : int

Valores devueltos

Devuelve un array que contiene todos los valores de array1 que están presentes en todos los argumentos.

Ejemplos

Ejemplo #1 Ejemplo de array_uintersect_assoc()

<?php
$array1 = array("a" => "verde", "b" => "marrón", "c" => "azul", "rojo");
$array2 = array("a" => "VERDE", "B" => "marrón", "amarillo", "rojo");

print_r(array_uintersect_assoc($array1, $array2, "strcasecmp"));
?>

El resultado del ejemplo sería:

Array
(
    [a] => verde
)

Ver también

  • array_uintersect() - Computa una intersección de arrays, compara la información mediante una función de llamada de retorno
  • array_intersect_assoc() - Calcula la intersección de arrays con un chequeo adicional de índices
  • array_intersect_uassoc() - Calcula la intersección de arrays con una comprobación adicional de índices, los cuales se comparan con una función de retrollamada
  • array_uintersect_uassoc() - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información y los índices mediante funciones de retrollamada por separado

User Contributed Notes

There are no user contributed notes for this page.


Calcula la intersección de arrays con una comprobación de índices adicional, compara la información y los índices mediante funciones de retrollamada por separado

  • « array_uintersect_assoc
  • array_uintersect »
  • PHP Manual
  • Funciones de Arrays
  • Calcula la intersección de arrays con una comprobación de índices adicional, compara la información y los índices mediante funciones de retrollamada por separado

array_uintersect_uassoc

(PHP 5, PHP 7, PHP 8)

array_uintersect_uassoc — Calcula la intersección de arrays con una comprobación de índices adicional, compara la información y los índices mediante funciones de retrollamada por separado

Descripción

array_uintersect_uassoc ( array $array1 , array $array2 , array $... = ? , callable $value_compare_func , callable $key_compare_func ) : array

Calcula la intersección de arrays con una comprobación de índices adicional, compara la información y los índices mediante funciones de retrollamada por separado.

Parámetros

array1

El primer array.

array2

El segundo array.

value_compare_func

La función de comparación debe devolver un entero menor, igual o mayor que cero si el primer argumento se considera que sea respectivamente menor, igual o mayor que el segundo. Observe que antes de PHP 7.0.0 este entero debía estar en el rango de -2147483648 a 2147483647.

callback ( mixed $a, mixed $b ) : int
key_compare_func

La función de retrollamada de comparación de claves.

Valores devueltos

Devuelve un array que contiene todos los valores de array1 que están presentes en todos los argumentos.

Ejemplos

Ejemplo #1 Ejemplo de array_uintersect_uassoc()

<?php
$array1 = array("a" => "verde", "b" => "marrón", "c" => "azul", "rojo");
$array2 = array("a" => "VERDE", "B" => "marrón", "amarillo", "rojo");

print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp"));
?>

El resultado del ejemplo sería:

Array
(
    [a] => verde
    [b] => marrón
)

Ver también

  • array_uintersect() - Computa una intersección de arrays, compara la información mediante una función de llamada de retorno
  • array_intersect_assoc() - Calcula la intersección de arrays con un chequeo adicional de índices
  • array_intersect_uassoc() - Calcula la intersección de arrays con una comprobación adicional de índices, los cuales se comparan con una función de retrollamada
  • array_uintersect_assoc() - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información mediante una función de retrollamada

User Contributed Notes

aidan at php dot net 31-Aug-2004 03:52
Please note, the correct function synopsis is:

array array_uintersect_uassoc ( array array1, array array2 [, array ...], callback data_compare_func, callback key_compare_func)

You may specifiy as many arrays as you like, but the last two parameters must be valid call back functions.


Computa una intersección de arrays, compara la información mediante una función de llamada de retorno

  • « array_uintersect_uassoc
  • array_unique »
  • PHP Manual
  • Funciones de Arrays
  • Computa una intersección de arrays, compara la información mediante una función de llamada de retorno

array_uintersect

(PHP 5, PHP 7, PHP 8)

array_uintersect — Computa una intersección de arrays, compara la información mediante una función de llamada de retorno

Descripción

array_uintersect ( array $array1 , array $array2 , array $... = ? , callable $value_compare_func ) : array

Computa una intersección de arrays, compara la información mediante una función de llamada de retorno.

Parámetros

array1

El primer array.

array2

El segundo array.

value_compare_func

La función de comparación debe devolver un entero menor, igual o mayor que cero si el primer argumento se considera que sea respectivamente menor, igual o mayor que el segundo. Observe que antes de PHP 7.0.0 este entero debía estar en el rango de -2147483648 a 2147483647.

callback ( mixed $a, mixed $b ) : int

Valores devueltos

Devuelve un array que contiene todos los valores de array1 que están presentes en todos los argumentos.

Ejemplos

Ejemplo #1 Ejemplo de array_uintersect()

<?php
$array1 = array("a" => "verde", "b" => "marrón", "c" => "azul", "rojo");
$array2 = array("a" => "VERDE", "B" => "marrón", "amarillo", "rojo");

print_r(array_uintersect($array1, $array2, "strcasecmp"));
?>

El resultado del ejemplo sería:

Array
(
    [a] => verde
    [b] => marrón
    [0] => rojo
)

Ver también

  • array_intersect() - Calcula la intersección de arrays
  • array_intersect_assoc() - Calcula la intersección de arrays con un chequeo adicional de índices
  • array_uintersect_assoc() - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información mediante una función de retrollamada
  • array_uintersect_uassoc() - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información y los índices mediante funciones de retrollamada por separado

User Contributed Notes

rob dot c dot ruiz at gmail dot com 15-Nov-2018 11:21
When trying to do a case insensitive comparison between arrays of words, the strcasecmp function works very nicely with this one like so:

$arr1 = array('blue', 'green', 'red');

$arr2 = array('BLUE', 'Purple', 'Red');

$loose_matches = array_uintersect($arr1, $arr2, 'strcasecmp');

print_r($loose_matches) // array('blue', 'red');
Hayley Watson 01-Jan-2018 10:25
As for the other "compare function" callbacks, the return value from the callback function doesn't need to be -1, 0, or 1.

cmp($a,$b) just needs to be <0, =0, or >0 depending on whether $a<$b, $a=$b, or $a>$b.
Nate at RuggFamily dot com 02-Feb-2007 12:03
I want to stress that in the user function, you do need to return either a 1 or a -1 properly; you cannot simply return 0 if the results are equal and 1 if they are not.

The following code is incorrect:

<?php
function myfunction($v1,$v2)
{
if ($v1===$v2)
    {
    return 0;
    }
return 1;
}

$a1=array(1, 2, 4);
$a2=array(1, 3, 4);
print_r(array_uintersect($a1,$a2,"myfunction"));
?>

This code is correct:

<?php
function myfunction($v1,$v2)
{
if ($v1===$v2)
    {
    return 0;
    }
if ($v1 > $v2) return 1;
return -1;
}
$a1=array(1, 2, 4);
$a2=array(1, 3, 4);
print_r(array_uintersect($a1,$a2,"myfunction"));
?>


Elimina valores duplicados de un array

  • « array_uintersect
  • array_unshift »
  • PHP Manual
  • Funciones de Arrays
  • Elimina valores duplicados de un array

array_unique

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

array_unique — Elimina valores duplicados de un array

Descripción

array_unique ( array $array , int $sort_flags = SORT_STRING ) : array

Toma un array y devuelve un nuevo array sin valores duplicados.

Tenga en cuenta que las claves se conservan. Si múltiples elementos se comparan bajo el parámetro sort_flags, entonces la clave y el valor del primer elemento igual se conservarán.

Nota: Dos elementos son considerados iguales solo si (string) $elem1 === (string) $elem2, es decir, cuando la representación en formato de string sea la misma, se usará el primer elemento.

Parámetros

array

El array de entrada.

sort_flags

El segundo parámetro opcional sort_flags se puede utilizar para modificar el tipo de orden usando estos valores:

Indicadores de tipos de orden:

  • SORT_REGULAR - compara ítems normalmente (no cambia los tipos)
  • SORT_NUMERIC - compara ítems numéricamente
  • SORT_STRING - compara ítems como strings
  • SORT_LOCALE_STRING - compara ítems como strings, basados en la configuración regional en uso.

Valores devueltos

Devuelve el array filtrado.

Historial de cambios

Versión | Descripción
7.2.0 | Si el parámetro sort_flags es SORT_STRING, el array anterior ha sido copiado y se han eliminado los elementos no únicos (sin empaquetar el array posteriormente), pero ahora se construye un nuevo array añadiendo los elementos únicos. Esto puede dar lugar a diferentes índices numéricos.
5.2.10 | Se volvió a cambiar el valor predeterminado de sort_flags a SORT_STRING.
5.2.9 | Se añadió el parámetro opcional sort_flags con el valor predeterminado SORT_REGULAR. Antes de 5.2.9, esta función se usaba para ordenar el array con SORT_STRING internamente.

Ejemplos

Ejemplo #1 Ejemplo de array_unique()

<?php
$entrada = array("a" => "verde", "rojo", "b" => "verde", "azul", "rojo");
$resultado = array_unique($entrada);
print_r($resultado);
?>

El resultado del ejemplo sería:

Array
(
    [a] => verde
    [0] => rojo
    [1] => azul
)

Ejemplo #2 array_unique() y tipos

<?php
$entrada = array(4, "4", "3", 4, 3, "3");
$resultado = array_unique($entrada);
var_dump($resultado);
?>

El resultado del ejemplo sería:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

Ver también

  • array_count_values() - Cuenta todos los valores de un array

Notas

Nota: Observe que array_unique() no está pensado para que trabaje con arrays multidimensionales.

User Contributed Notes

contact at evoweb dot fr 16-Feb-2021 08:32
Here is a solution to make unique values keeping empty values for an array with keys :

<?php
function array_unique_kempty($array) {
    $values = array_unique($array);
    $return = array_combine(array_keys($array), array_fill(0,count($array),null));
    return array_merge($return,$values);
}

$myArray = [
    "test1" => "aaa",
    "test2" => null,
    "test3" => "aaa",
    "test4" => "bbb",
    "test5" => null,
    "test6" => "ccc",
    "test7" => "ddd",
    "test8" => "ccc"
];

echo "<pre>".print_r(array_unique_kempty($myArray),true)."</pre>";

/*
Array
(
    [test1] => aaa
    [test2] =>
    [test3] =>
    [test4] => bbb
    [test5] =>
    [test6] => ccc
    [test7] => ddd
    [test8] =>
)
*/
?>
Eduardo Corts Vzquez (ecortes) 08-Jan-2021 10:19
Create multidimensional array unique for any single key index.

<?php

$users = [
    ['id' => 1, 'name' => 'ecortes', 'phone' => '1111111'],
    ['id' => 2, 'name' => 'canepa', 'phone' => '222222'],
    ['id' => 1, 'name' => 'john', 'phone' => '3333333'],
];

function array_unique_multi($array, $key) {
    return array_reduce($array, function($acc, $curr) use($key) {
        if(!in_array($curr[$key], array_column($acc, $key))) {
            array_push($acc, $curr);
        }
        return $acc;
    }, []);
}

//Call the function
$unique_users = array_unique_multi($users, 'id');

//output
$users = [
    ['id' => 1, 'name' => 'ecortes', 'phone' => '1111111'],
    ['id' => 2, 'name' => 'canepa', 'phone' => '222222'],
];
?>
falundir at gmail dot com 19-Jun-2018 05:51
I find it odd that there is no version of this function which allows you to use a comparator callable in order to determine items equality (like array_udiff and array_uintersect). So, here's my version for you:

<?php
function array_uunique(array $array, callable $comparator): array {
    $unique_array = [];
    do {
        $element = array_shift($array);
        $unique_array[] = $element;

        $array = array_udiff(
            $array,
            [$element],
            $comparator
        );
    } while (count($array) > 0);

    return $unique_array;
}
?>

And here is a test code:

<?php
class Foo {

    public $a;

    public function __construct(int $a) {
        $this->a = $a;
    }
}

$array_of_objects = [new Foo(2), new Foo(1), new Foo(3), new Foo(2), new Foo(2), new Foo(1)];

$comparator = function (Foo $foo1, Foo $foo2): int {
    return $foo1->a <=> $foo2->a;
};

var_dump(array_uunique($array_of_objects, $comparator)); // should output [Foo(2), Foo(1), Foo(3)]
?>
subhrajyoti dot de007 at gmail dot com 01-Jun-2018 05:25
Simple and clean way to get duplicate entries removed from a multidimensional array.

<?php
          $multi_array = $multi_array [0];
          $multi_array = array_unique($multi_array);
          print_r($multi_array);
?>
Matt S 26-Apr-2018 02:45
In case you are looking for a function that works like array_unique but does not do the string conversion first.

<?php
function array_unique_full($arr, $strict = false) {
    return array_filter($arr, function($v, $k) use ($arr, $strict) {
        return array_search($v, $arr, $strict) === $k;
    }, ARRAY_FILTER_USE_BOTH);
}
?>
Fabiano 04-Jan-2018 10:22
As for PHP 7.1.12, this is the comparison between array_keys(array_flip()), array_flip(array_flip()), for each elimination and array_unique. The array_keys(array_flip()) is the fastest method to remove duplication values from a single dimension array:

<?php

$max = 1000000;
$arr = range(1,$max,3);
$arr2 = range(1,$max,2);
$arr = array_merge($arr,$arr2);

$time = -microtime(true);
$res1 = array_unique($arr);
$time += microtime(true);

echo "<br>deduped to ".count($res1)." in ".$time;
// deduped to 666667 in 0.78185796737671
// memory used: 33558528

$time = -microtime(true);
$res2 = array_flip(array_flip($arr));
$time += microtime(true);

echo "<br><br>deduped to ".count($res2)." in ".$time;
// deduped to 666667 in 0.072191953659058
// memory used: 3774873

$time = -microtime(true);
$res3 = array();
foreach($arr as $key=>$val) {
    $res3[$val] = true;
}
$res3 = array_keys($res3);
$time += microtime(true);

echo "<br /><br>deduped to ".count($res3)." in ".$time;
// deduped to 666667 in 0.095494985580444
// memory used: 33558528

$time = -microtime(true);
$res4 = array_keys(array_flip($arr));
$time += microtime(true);

echo "<br /><br>deduped to ".count($res4)." in ".$time;
// deduped to 666667 in 0.05807900428772
// memory used: 33558528
calexandrepcjr at gmail dot com 20-Jun-2017 03:19
Following the Ghanshyam Katriya idea, but with an array of objects, where the $key is related to object propriety that you want to filter the uniqueness of array:

<?php
function obj_multi_unique($obj, $key = false)
    {
        $totalObjs = count($obj);
        if (is_array($obj) && $totalObjs > 0 && is_object($obj[0]) && ($key && !is_numeric($key))) {
            for ($i = 0; $i < $totalObjs; $i++) {
                if (isset($obj[$i])) {
                    for ($j = $i + 1; $j < $totalObjs; $j++) {
                        if (isset($obj[$j]) && $obj[$i]->{$key} === $obj[$j]->{$key}) {
                            unset($obj[$j]);
                        }
                    }
                }
            }
            return array_values($obj);
        } else {
            throw new Exception('Invalid argument or your array of objects is empty');
        }
    }
?>
stoff@ 20-Jan-2017 03:23
In reply to performance tests array_unique vs foreach.

In PHP7 there were significant changes to Packed and Immutable arrays resulting in the performance difference to drop considerably. Here is the same test on php7.1 here;
http://sandbox.onlinephpfunctions.com/code/2a9e986690ef8505490489581c1c0e70f20d26d1

$max = 770000; //large enough number within memory allocation
$arr = range(1,$max,3);
$arr2 = range(1,$max,2);
$arr = array_merge($arr,$arr2);

$time = -microtime(true);
$res1 = array_unique($arr);
$time += microtime(true);
echo "deduped to ".count($res1)." in ".$time;
// deduped to 513333 in 1.0876770019531

$time = -microtime(true);
$res2 = array();
foreach($arr as $key=>$val) {
    $res2[$val] = true;
}
$res2 = array_keys($res2);
$time += microtime(true);
echo "<br />deduped to ".count($res2)." in ".$time;
// deduped to 513333 in 0.054931879043579
zoolyka at gmail dot com 18-Jan-2016 10:48
I found the simplest way to "unique" multidimensional arrays as follows:

<?php

$array = array(
    'a' => array(1, 2),
    'b' => array(1, 2),
    'c' => array(2, 2),
    'd' => array(2, 1),
    'e' => array(1, 1),
);

$array = array_map('json_encode', $array);
$array = array_unique($array);
$array = array_map('json_decode', $array);

print_r($array);

?>

As you can see "b" will be removed without any errors or notices.
tim at heuer dot nz 11-Oct-2015 10:57
I created a function for doing array_unique with a custom in_array function. So, if elements are considered in the array passed to this function, the array returned won't include elements that are considered equal and only return the values from the first array that are not considered in the array:

<?php

function uniqueBy(array $array, callable $in_array_func) {
    $result = array();
    foreach ($array as $key => $item) {
        if (!$in_array_func($item, $result)) {
            $result[$key] = $item;
        }
    }
    return $result;
}

?>

Example usage:

<?php

$in_array_func = function($item, $array) {
    $fromBower = function($item) {
        $result = substr($item, strpos($item, 'bower_components'));
        return $result;
    };
    foreach ($array as $myItem) {
        if ($fromBower($item) == $fromBower($myItem)) {
            return true;
        }
    }
    return false;
};

// ...
$jss = uniqueBy($jss, $in_array_func);
?>
Ludovico Grossi 19-Dec-2014 02:01
[Editor's note: please note that this will not work well with non-scalar values in the array. Array keys can not be arrays themselves, nor streams, resources, etc. Flipping the array causes a change in key-name]

You can do a super fast version of array_unique directly in PHP, even faster than the other solution posted in the comments!

Compared to the built in function it is 20x faster! (2x faster than the solution in the comments).

<?php
function superfast_array_unique($array) {
    return array_keys(array_flip($array));
}
?>

This works faster for small and big arrays.
Ghanshyam Katriya(anshkatriya at gmail) 09-Dec-2014 10:15
Create multidimensional array unique for any single key index.
e.g I want to create multi dimentional unique array for specific code

Code :
My array is like this,

<?php
$details = array(
    0 => array("id"=>"1", "name"=>"Mike",    "num"=>"9876543210"),
    1 => array("id"=>"2", "name"=>"Carissa", "num"=>"08548596258"),
    2 => array("id"=>"1", "name"=>"Mathew",  "num"=>"784581254"),
);
?>

You can make it unique for any field like id, name or num.

I have develop this function for same :
<?php
function unique_multidim_array($array, $key) {
    $temp_array = array();
    $i = 0;
    $key_array = array();

    foreach($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return $temp_array;
}
?>

Now, call this function anywhere from your code,

something like this,
<?php
$details = unique_multidim_array($details,'id');
?>

Output will be like this :
<?php
$details = array(
    0 => array("id"=>"1","name"=>"Mike","num"=>"9876543210"),
    1 => array("id"=>"2","name"=>"Carissa","num"=>"08548596258"),
);
?>
mostafatalebi at rocketmail dot com 13-Dec-2013 02:38
If you find the need to get a sorted array without it preserving the keys, use this code which has worked for me:

<?php

$array = array("hello", "fine", "good", "fine", "hello", "bye");

$get_sorted_unique_array = array_values(array_unique($array));

?>

The above code returns an array which is both unique and sorted from zero.
bx16soupapes at gmail dot com 11-Jun-2013 07:55
Another form to make an array unique (manual):

This is my array

Array
(
    [0] => Array
        (
            [0] => 40665
            [1] => 40665
            [2] => 40665
            [3] => 40665
            [4] => 40666
            [5] => 40666
            [6] => 40666
            [7] => 40666
            [8] => 40667
            [9] => 40667
            [10] => 40667
            [11] => 40667
            [12] => 40667
            [13] => 40668
            [14] => 40668
            [15] => 40668
            [16] => 40668
            [17] => 40668
            [18] => 40669
            [19] => 40669
            [20] => 40670
            [21] => 40670
            [22] => 40670
            [23] => 40670
            [24] => 40671
            [25] => 40671
            [26] => 40671
            [27] => 40671
            [28] => 40671
        )

    [1] => Array
        (
            [0] => 40672
            [1] => 40672
            [2] => 40672
            [3] => 40672
        )

)

this is my script:

    $anterior = 0;
    foreach($item as $array_key => $array_value)
    {
            echo "<li>$array_key";
            echo "<ul>";
            foreach($array_value as $xarray_key => $xarray_value){
                if($xarray_value != $anterior) {
                    echo "<li>$xarray_key => $xarray_value";
                    $item_nuevo[$array_key][] = $xarray_value;    // or to use the same key number $item_nuevo[$array_key][$xarray_key] = $xarray_value;
                }
                $anterior = $xarray_value;
            }
            echo "</ul>";
    }

result:

0
    0 => 40665
    4 => 40666
    8 => 40667
    13 => 40668
    18 => 40669
    20 => 40670
    24 => 40671

1
    0 => 40672

saludos desde chile.
sashasimkin at gmail dot com 25-Apr-2012 01:26
My object unique function:

<?php
function object_unique( $obj ){
    $objArray = (array) $obj;

    $objArray = array_intersect_assoc( array_unique( $objArray ), $objArray );

    foreach( $obj as $n => $f ) {
        if( !array_key_exists( $n, $objArray ) ) unset( $obj->$n );
    }

    return $obj;
}
?>

And these code:

<?php
class Test{
    public $pr0 = 'string';
    public $pr1 = 'string1';
    public $pr2 = 'string';
    public $pr3 = 'string2';
}

$obj = new Test;

var_dump( object_unique( $obj ) );
?>

returns:
object(Test)[1]
  public 'pr0' => string 'string' (length=6)
  public 'pr1' => string 'string1' (length=7)
  public 'pr3' => string 'string2' (length=7)
gma (at) qoob (dot) gr 12-Nov-2011 10:07
Lets say that you want to capture unique values from multidimensional arrays and flatten them in 0 depth.

i.e.
<?php
$tmp = array( 'a' => array( 1,2,3,4 ), 'b' => array( 'c' => array( 4,5,6,7 ) ) );
?>

will return with array_flat( $tmp ) --> array( 1,2,3,4,5,6,7 );

I hope that the function will help someone

<?php
/**
 * @params      : $a            array           the recursion array
 *              : $s            array           storage array
 *              : $l            integer         the depth level
 *
 */
if( !function_exists( 'array_flat' ) )
{
    function array_flat( $a, $s = array( ), $l = 0 )
    {
        # check if this is an array
        if( !is_array( $a ) )                           return $s;

        # go through the array values
        foreach( $a as $k => $v )
        {
            # check if the contained values are arrays
            if( !is_array( $v ) )
            {
                # store the value
                $s[ ]       = $v;

                # move to the next node
                continue;

            }

            # increment depth level
            $l++;

            # replace the content of stored values
            $s              = array_flat( $v, $s, $l );

            # decrement depth level
            $l--;

        }

        # get only unique values
        if( $l == 0 ) $s = array_values( array_unique( $s ) );

        # return stored values
        return $s;

    } # end of function array_flat( ...

}
?>
Friendly Code 01-Aug-2011 03:48
I required a function that removed a specific duplicate entry from an array and ignoring all others so came up with this:

<?php
function specified_array_unique($array, $value)
{
    $count = 0;

    foreach($array as $array_key => $array_value)
    {
        if ( ($count > 0) && ($array_value == $value) )
        {
            unset($array[$array_key]);
        }

        if ($array_value == $value) $count++;
    }

    return array_filter($array);
}
?>
0cool.f 23-May-2011 03:54
Hope this can help...

<?php
function array_unique_key_group($array) {
    if(!is_array($array))
        return false;

    $temp = array_unique($array);
    foreach($array as $key => $val) {
        $i = array_search($val,$temp);
        if(!empty($i) && $key != $i) {
            $temp[$i.','.$key] = $temp[$i];
            unset($temp[$i]);
        }
    }
    return $temp;
}
?>

this function return an array that is unique, but preserve every key for the element...
sorry for bad english I'm italian...

$array['asd'] = 'value';
$array['lol'] = 'value';
$array['foo'] = 'val';
$array['bar'] = 'val';

var_dump(array_unique_key_group($array));
// will be output
array(2) { ["asd,lol"]=> string(5) "value" ["foo,bar"]=> string(3) "val" }
Anonymous 16-Jun-2010 05:46
It's often faster to use a foreache and array_keys than array_unique:

    <?php

    $max = 1000000;
    $arr = range(1,$max,3);
    $arr2 = range(1,$max,2);
    $arr = array_merge($arr,$arr2);

    $time = -microtime(true);
    $res1 = array_unique($arr);
    $time += microtime(true);
    echo "deduped to ".count($res1)." in ".$time;
    // deduped to 666667 in 32.300781965256

    $time = -microtime(true);
    $res2 = array();
    foreach($arr as $key=>$val) {
        $res2[$val] = true;
    }
    $res2 = array_keys($res2);
    $time += microtime(true);
    echo "<br />deduped to ".count($res2)." in ".$time;
    // deduped to 666667 in 0.84372591972351

    ?>
regeda at inbox dot ru 12-Apr-2010 08:11
recursive array unique for multiarrays

<?php
function super_unique($array)
{
  $result = array_map("unserialize", array_unique(array_map("serialize", $array)));

  foreach ($result as $key => $value)
  {
    if ( is_array($value) )
    {
      $result[$key] = super_unique($value);
    }
  }

  return $result;
}
?>
brendel at krumedia dot de 24-Feb-2010 11:47
Prior to 5.2.9 you may create a list of unique objects this way:

<?php
for (; ; ) {
  // ...
  $uniqueObjectList[spl_object_hash($myObject)] = $myObject;
}
?>
amri [ at t] dhstudio dot eu 18-Dec-2009 02:36
I searched how to show only the de-duplicate elements from array, but failed.
Here is my solution:

<?php
function arrayUniqueElements($array)
{
return array_unique(array_diff_assoc($array1,array_unique($array1)));
};
?>

Example:
<?php
$arr1 = array('foo', 'bar', 'xyzzy', '&', 'xyzzy',
'baz', 'bat', '|', 'xyzzy', 'plugh',
'xyzzy', 'foobar', '|', 'plonk', 'xyzzy',
'apples', '&', 'xyzzy', 'oranges', 'xyzzy',
'pears','foobar');

$result=arrayUniqueElements($arr1);
print_r($result);exit;
?>

Output:

Array
(
[4] => xyzzy
[12] => |
[16] => &
[21] => foobar
)
dirk dot avery a t gmail 30-Apr-2009 08:45
Although array_unique is not intended to work with multi-dimensional arrays, it does on 5.2.9.  However, it does not for 5.2.5.  Beware.
serg dot podtynnyi at gmail dot com 06-Feb-2009 11:21
//Remove duplicates from a text files and dump result in one file for example: emails list, links list etc

<?php

$data1 = file("data1.txt");
$data2 = file("data2.txt");

file_put_contents('unique.txt', implode('', array_unique(array_merge($data1,$data2))));
?>
jusvalceanu - SPAM at SPAM - yahoo dot com 06-Nov-2008 02:23
so .... my problem was multidimensional sort.

<?php
      $new = array();
      $exclude = array("");
      for ($i = 0; $i<=count($attribs)-1; $i++) {
         if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
      }

?>

Array $attribs is an array contaning arrays. Each array in the $attrib array consists in multiple fields (ex: name, lenght, price, etc.) to be more simpler in speech think that $attrib is the array resulted by a search sql query done by a visitator on your online shoopping website ... (so ... each array in the $attrib is a product :P) if you want to sort only the uniq results use the above or use this:

<?php

   /* Our Array of products */
   $attribs[] = array(
                           "name"         => "Test Product 1",
                           "length"     => "42 cm",
                           "weight"     => "0,5 kg",
                           "price"     => "10 $",
                           "stock"     => "100",
                        );

   $attribs[] = array(
                           "name"         => "Test Product 2",
                           "length"     => "42 cm",
                           "weight"     => "1,5 kg",
                           "price"     => "10 $",
                           "stock"     => "200",
                        );

    /* The nice stuff */

      $new = array();
      $exclude = array("");
      for ($i = 0; $i<=count($attribs)-1; $i++) {
         if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
      }

      print_r($new); // $new is our sorted array

?>

Have fun tweaking this ;)) i know you will ;))

From Romania With Love
quecoder at gmail 25-Aug-2008 10:30
another method to get unique values is :

<?php
$alpha=array('a','b','c','a','b','d','e','f','f');

$alpha= array_keys(array_count_values($alpha));

print_r($alpha);
?>

Output:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )
Dorphalsig 28-Jul-2008 09:47
I had a problem with array_unique and multidimensional arrays ... Maybe there's a better way to do this, but this will work for any dimensional arrays.

<?php
function arrayUnique($myArray)
{
    if(!is_array($myArray))
           return $myArray;

    foreach ($myArray as &$myvalue){
        $myvalue=serialize($myvalue);
    }

    $myArray=array_unique($myArray);

    foreach ($myArray as &$myvalue){
        $myvalue=unserialize($myvalue);
    }

    return $myArray;

}
?>
PHP Expert 14-Apr-2008 05:34
Case insensitive for PHP v4.x and up.

<?php

function in_iarray($str, $a) {
    foreach ($a as $v) {
        if (strcasecmp($str, $v) == 0) {
            return true;
        }
    }
    return false;
}

function array_iunique($a) {
    $n = array();
    foreach ($a as $k => $v) {
        if (!in_iarray($v, $n)) {
            $n[$k]=$v;
        }
    }
    return $n;
}

$input = array("aAa","bBb","cCc","AaA","ccC","ccc","CCC","bBB","AAA","XXX");
$result = array_iunique($input);
print_r($result);

/*
Array
(
    [0] => aAa
    [1] => bBb
    [2] => cCc
    [9] => XXX
)
*/
?>
Ray dot Paseur at SometimesUsesGmail dot com 01-Mar-2008 07:46
I needed to identify email addresses in a data table that were replicated, so I wrote the array_not_unique() function:

<?php

function array_not_unique($raw_array) {
    $dupes = array();
    natcasesort($raw_array);
    reset ($raw_array);

    $old_key    = NULL;
    $old_value    = NULL;
    foreach ($raw_array as $key => $value) {
        if ($value === NULL) { continue; }
        if ($old_value == $value) {
            $dupes[$old_key]    = $old_value;
            $dupes[$key]        = $value;
        }
        $old_value    = $value;
        $old_key    = $key;
    }
return $dupes;
}

$raw_array     = array();
$raw_array[1]    = 'abc@xyz.com';
$raw_array[2]    = 'def@xyz.com';
$raw_array[3]    = 'ghi@xyz.com';
$raw_array[4]    = 'abc@xyz.com'; // Duplicate

$common_stuff    = array_not_unique($raw_array);
var_dump($common_stuff);
?>
mnbayazit 28-Oct-2007 02:18
Case insensitive; will keep first encountered value.

<?php

function array_iunique($array) {
    $lowered = array_map('strtolower', $array);
    return array_intersect_key($array, array_unique($lowered));
}

?>
webmaster at jukkis dot net 30-Jul-2007 04:08
Another way to 'unique column' an array, in this case an array of objects:
Keep the desired unique column values in a static array inside the callback function for array_filter.

Example:
<?php
/* example object */
class myObj {
  public $id;
  public $value;
  function __construct( $id, $value ) {
    $this->id = $id;
    $this->value = $value;
  }
}

/* callback function */
function uniquecol( $obj ) {
  static $idlist = array();

  if ( in_array( $obj->id, $idlist ) )
    return false;

  $idlist[] = $obj->id;
  return true;
}

/* a couple of arrays with second array having an element with same id as the first */
$list  = array( new myObj( 1, 1  ), new myObj( 2, 100 ) );
$list2 = array( new myObj( 1, 10 ), new myObj( 3, 100 ) );
$list3 = array_merge( $list, $list2 );

$unique = array_filter( $list3, 'uniquecol' );
print_r( $list3 );
print_r( $unique );

?>

In addition, use array_merge( $unique ) to reindex.
Ome_Henk 27-Oct-2006 12:16
For people looking at the flip flip method for getting unique values in a simple array. This is the absolute fastest method:

<?php
$unique = array_keys(array_flip($array));
?>

It's marginally faster as:
<?php
$unique = array_merge(array_flip(array_flip($array)));
?>

And it's marginally slower as:
<?php
$unique array_flip(array_flip($array)); // leaves gaps
?>

It's still about twice as fast or fast as array_unique.

This tested on several different machines with 100000 random arrays. All machines used a version of PHP5.
geuis dot teses at gmail dot com 09-Oct-2006 10:27
Here's the shortest line of code I could find/create to remove all duplicate entries from an array and then reindex the keys.

<?php

// Fruits, vegetables, and other food:
$var = array('apple','banana','carrot','cat','dog','egg','eggplant','fish');

$var = array_values(array_unique($var));
?>
keneks at gmail dot com 30-Sep-2006 07:01
Taking the advantage of array_unique, here is a simple function to check if an array has duplicate values.

It simply compares the number of elements between the original array and the array_uniqued array.

<?php

function array_has_duplicates(array $array)
{
    $uniq = array_unique($array);
    return count($uniq) != count($array);
}

?>
uditsawhney at yahoo dot com 15-Jul-2006 12:14
<?php

//Fn for array_unique column-wise for multi-dimensioanl array without losing keys | Start
function array_uniquecolumn($arr)
{
    $rows   = sizeof($arr);
    $columns = sizeof($arr[0]);

    $columnkeys = array_keys($arr[0]);

    for($i=0; $i<$columns; $i++)
    {
        for($j=0;$j<$rows;$j++)
        {
            for($k = $j+1; $k<$rows; $k++)
            {
                if($arr[$j][$columnkeys[$i]] == $arr[$k][$columnkeys[$i]])
                    $arr[$k][$columnkeys[$i]] = "";
            }
        }

    }

return ($arr);

}
//Fn for array_unique column-wise for multi-dimensioanl array without losing keys | Stop

$arrUGCourse[]= array(  "CTR" => "1",

                        "UGCOURSE"=>"ABC",

                        "TSINITIATE"=>"540",

                        "COUNT"=>"34",

                        "ENTRY_DT"=>"2006-05-01",

                        "CUMULATIVE"=> 44);

$arrUGCourse[]= array(  "CTR" => "2",

                        "UGCOURSE"=>"ABC",

                        "TSINITIATE"=>"5401",

                        "COUNT"=>"341",

                        "ENTRY_DT"=>"2006-05-11",

                        "CUMULATIVE"=> 44);

print_r(array_uniquecolumn($arrUGCourse));

?>
agarcia at rsn dot com dot co 31-Mar-2006 12:41
This is a script for multi_dimensional arrays

<?php
function remove_dup($matriz) {
    $aux_ini=array();
    $entrega=array();
    for($n=0;$n<count($matriz);$n++)
    {
        $aux_ini[]=serialize($matriz[$n]);
    }
    $mat=array_unique($aux_ini);
    for($n=0;$n<count($matriz);$n++)
    {

            $entrega[]=unserialize($mat[$n]);

    }
    return $entrega;
}
?>
mcmeijer at yahoo dot com 27-Jan-2006 05:18
This is a recursive arrayUnique function for arrays of any dimension. (tested with 4-dimensional array)
The line '$newArray=deleteEmpty($newArray);' is optional and removes empty keys and values
<?php
function arrayUnique($myArray)
    {
    $newArray = Array();
    if (is_array($myArray))
        {
        foreach($myArray as $key=>$val)
            {
            if (is_array($val))
                {
                $val2 = arrayUnique($val);
                }
            else
                {
                $val2 = $val;
                $newArray=array_unique($myArray);
                $newArray=deleteEmpty($newArray);
                break;
                }
            if (!empty($val2))
                {
                $newArray[$key] = $val2;
                }
            }
        }
    return ($newArray);
    }

function deleteEmpty($myArray)
    {
    $retArray= Array();
    foreach($myArray as $key=>$val)
        {
        if (($key<>"") && ($val<>""))
            {
            $retArray[$key] = $val;
            }
        }
    return $retArray;
    }
?>
memandeemail at gmail dot com 03-Jan-2006 10:47
Problem:
I have loaded an array with the results of a database
query.  The Fields are 'FirstName' and 'LastName'.

I would like to find a way to contactenate the two
fields, and then return only unique values for the
array.  For example, if the database query returns
three instances of a record with the FirstName John
and the LastName Smith in two distinct fields, I would
like to build a new array that would contain all the
original fields, but with John Smith in it only once.
Thanks for: Colin Campbell

Solution:

<?php
/**
 * The same thing than implode function, but return the keys so
 *
 * <code>
 * $_GET = array('id' => '4587','with' => 'key');
 * ...
 * echo shared::implode_with_key('&',$_GET,'='); // Resultado: id=4587&with=key
 * ...
 * </code>
 *
 * @param string $glue Oque colocar entre as chave => valor
 * @param array $pieces Valores
 * @param string $hifen Separar chave da array do valor
 * @return string
 * @author memandeemail at gmail dot com
 */
function implode_with_key($glue = null, $pieces, $hifen = ',') {
  $return = null;
  foreach ($pieces as $tk => $tv) $return .= $glue.$tk.$hifen.$tv;
  return substr($return,1);
}

/**
 * Return unique values from a tree of values
 *
 * @param array $array_tree
 * @return array
 * @author memandeemail at gmail dot com
 */
function array_unique_tree($array_tree) {
  $will_return = array(); $vtemp = array();
  foreach ($array_tree as $tkey => $tvalue) $vtemp[$tkey] = implode_with_key('&',$tvalue,'=');
  foreach (array_keys(array_unique($vtemp)) as $tvalue) $will_return[$tvalue] = $array_tree[$tvalue];
  return $will_return;
}

$problem = array_fill(0,3,
array('FirstName' => 'John', 'LastName' => 'Smith')
);

$problem[] = array('FirstName' => 'Davi', 'LastName' => 'S. Mesquita');
$problem[] = array('FirstName' => 'John', 'LastName' => 'Tom');

print_r($problem);

print_r(array_unique_tree($problem));
?>
csaba at alum dot mit dot edu 09-Jun-2004 07:17
The following is an efficient, adaptable implementation of array_unique which always retains the first key having a given value:

<?php
function array_unique2(&$aray) {
    $aHash = array();
    foreach ($aray as $key => &$val) if (@$aHash[$val]++) unset ($aray[$key]);
}
?>

It is also adaptable to multi dimensional arrays.  For example, if your array is a sequence of (multidimensional) points, then in place of @$aHash[$val]++ you could use @$aHash[implode("X",$val)]++
If you want to not have holes in your array, you can do an array_merge($aray) at the end.

Csaba Gabor
spunk at dasspunk dot NOSPAM dot com 14-Nov-2001 04:52
I needed a way of retaining the original array's keys in the new, unique array. I came up with this. It works for my purposes but may need refinement.

<?php
function my_array_unique($somearray)
{
    asort($somearray);
    reset($somearray);
    $currentarrayvar = current($somearray);
    foreach ($somearray as $key=>$var)
    {
        if (next($somearray) != $currentarrayvar)
        {
            $uniquearray[$key] = $currentarrayvar;
            $currentarrayvar = current($somearray);
        }
    }
    reset($uniquearray);
    return $uniquearray;
}
?>


Añadir al inicio de un array uno a más elementos

  • « array_unique
  • array_values »
  • PHP Manual
  • Funciones de Arrays
  • Añadir al inicio de un array uno a más elementos

array_unshift

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

array_unshift — Añadir al inicio de un array uno a más elementos

Descripción

array_unshift ( array &$array , mixed $... = ? ) : int

array_unshift() añade los elementos pasados al inicio de array. Observe que la lista de elementos se añade como un todo, por lo que los elementos añadidos permanecen en el mismo orden. Todas las claves numéricas del array serán modificadas empezando a contar desde cero mientras que las claves literales no serán cambiadas.

Parámetros

array

El array de entrada.

...

Los valores a añadir al inicio.

Valores devueltos

Devuelve el nuevo número de elementos del array.

Historial de cambios

Versión | Descripción
7.3.0 | Esta función ahora puede ser llamada con un solo parámetro. Anteriormente, se requerían al menos dos parámetros.

Ejemplos

Ejemplo #1 Ejemplo de array_unshift()

<?php
$cola = array("naranja", "banana");
array_unshift($cola, "manzana", "frambuesa");
print_r($cola);
?>

El resultado del ejemplo sería:

Array
(
    [0] => manzana
    [1] => frambuesa
    [2] => naranja
    [3] => banana
)

Ver también

  • array_shift() - Quita un elemento del principio del array
  • array_push() - Inserta uno o más elementos al final de un array
  • array_pop() - Extrae el último elemento del final del array

User Contributed Notes

Richard Akindele 16-Mar-2016 06:31
Another way to tack something to the beginning of an array is with array_merge().

$plans = array('AARP'=>'Senior', 'AAA'=>'Automobile Club');

$plans = array_merge(array("BAR"=>"Best Available Rate"),  $plans);
daniel at smallboxcms dot com 17-Apr-2015 08:18
Anonymous' associative version wasn't working for me, but it did with this small tweak:

function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    $arr = array_reverse($arr, true);
    return $arr;
}
Anonymous 19-Nov-2011 09:44
Sahn's example almost works but has a small error. Try it like this if you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

<?php
function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    return = array_reverse($arr, true);
}
?>
sergei at gmx dot net 03-Oct-2007 08:49
You can preserve keys and unshift an array with numerical indexes in a really simple way if you'll do the following:

<?php
$someArray=array(224=>'someword1', 228=>'someword2', 102=>'someword3', 544=>'someword3',95=>'someword4');

$someArray=array(100=>'Test Element 1 ',255=>'Test Element 2')+$someArray;
?>

now the array looks as follows:

array(
100=>'Test Element 1 ',
255=>'Test Element 2'
224=>'someword1',
228=>'someword2',
102=>'someword3',
544=>'someword3',
95=>'someword4'
);
amschroeder at gmail dot com 26-Mar-2007 09:13
This becomes a nice little problem if you index your arrays out of order (while manually sorting).  For example:

<?php
$recordMonths[3] = '8/%/2006';
$recordMonths[4] = '7/%/2004';
$recordMonths[0] = '3/%/2007';
$recordMonths[1] = '2/%/2007';
$recordMonths[5] = '12/%/2000';
$recordMonths[6] = '11/%/2000';
$recordMonths[7] = '10/%/2000';
$recordMonths[2] = '1/%/2007';

for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[$i];
    echo "singleMonth: $singleMonth <br />";
}
array_unshift($recordMonths,'%');
for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[$i];
    echo "singleMonth: $singleMonth <br />";
}
?>

Produces:

singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 1/%/2007
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: %
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: 1/%/2007

It reindexes them based on the order they were created.  It seems like if an array has all numeric indexes, then it should reindex them based on the order of their index.  Just my opinion...
John Brooking 02-Jun-2006 06:54
I had a need tonight to convert a numeric array from 1-based to 0-based, and found that the following worked just fine due to the "side effect" of renumbering:

<?php
   array_unshift( $myArray, array_shift( $myArray ));
?>
php at electricsurfer dot com 26-Feb-2004 06:20
even simpler unshifting of a reference !
<?php
/**
 * @return int
 * @param $array array
 * @param $value mixed
 * @desc Prepend a reference to an element to the beginning of an array. Renumbers numeric keys, so $value is always inserted to $array[0]
 */
function array_unshift_ref(&$array, &$value)
{
   $return = array_unshift($array,'');
   $array[0] =& $value;
   return $return;
}
?>
lagroue 09-Nov-2003 04:46
Last version of PHP deprecated unshifting of a reference.
You can use this function instead :

<?php
function array_unshift1 (& $ioArray, $iValueWrappedInAnArray) {
    $lNewArray = false;
    foreach (array_keys ($ioArray) as $lKey)
        $lNewArray[$lKey+1] = & $ioArray[$lKey];
    $ioArray = array (& $iValueWrappedInAnArray[0]);
    if ($lNewArray)
        foreach (array_keys ($lNewArray) as $lKey)
             $ioArray[] = & $lNewArray[$lKey];
    return count($ioArray);
}

// before last PHP (now generates a deprecation warning)
array_unshift ($a, &$v);
// since last PHP (caution, there is a wrapping array !!)
array_unshift1 ($a, array (&$v));
?>
chris dot NoThxSpam dot given at hp dot com 23-Jul-2003 12:17
If you need to change the name of a key without changing its position in the array this function may be useful.

<?php
function array_key_change($Old, $New, $In, $NewVal=NULL) {
        $Temp = array();
        while(isset($Temp[$Old]) == false) {
                list($k, $v) = each($In);
                $Temp[$k] = $v;
                unset($In[$k]);
        }
        if($NewVal == NULL) {
                $NewVal = $Temp[$Old];
        }
        unset($Temp[$Old]);
        $Temp = array_reverse($Temp);
        $In = array_merge(array($New=>$NewVal), $In);
        while(list($k,$v) = each($Temp)) {
                $In = array_merge(array($k=>$v), $In);
        }
        return($In);
}
?>
rsmith_NOSPAM_ at _NOSPAM_unitec dot ac dot nz 30-Jul-2002 07:00
array_merge() will also reindex (see array_merge() manual entry), but the '+' operator won't, so...

<?php
$arrayone=array("newkey"=>"newvalue") + $arrayone;
?>

does the job.
robert dot wills at fuzzbrain dot uklinux dot net 07-Feb-2002 06:02
Actually this problem with the keys getting reindexed only happens when the keys are numerical:

<?php

$a = array("f"=>"five", "s" =>"six", "t" =>
        "twenty");

print_r($a);
echo "\n";
foreach($a as $key=>$val)
{
    echo "k: $key v: $val \n";
}

array_unshift($a, "zero");
print_r($a);
echo "\n";
foreach($a as $key=>$val)
{
    echo "k: $key v: $val \n";
}
?>

Array
(
    [f] => five
    [s] => six
    [t] => twenty
)

k: f v: five
k: s v: six
k: t v: twenty
Array
(
    [0] => zero
    [f] => five
    [s] => six
    [t] => twenty
)

k: 0 v: zero
k: f v: five
k: s v: six
k: t v: twenty
sahn at hmc dot edu 27-Jul-2001 12:21
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

<?php
function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    $arr = array_reverse($arr, true);
    return count($arr);
}
?>


Devuelve todos los valores de un array

  • « array_unshift
  • array_walk_recursive »
  • PHP Manual
  • Funciones de Arrays
  • Devuelve todos los valores de un array

array_values

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

array_values — Devuelve todos los valores de un array

Descripción

array_values ( array $array ) : array

array_values() devuelve todos los valores del array array e indexa numéricamente el array.

Parámetros

array

El array.

Valores devueltos

Devuelve un array indexeado de valores.

Ejemplos

Ejemplo #1 Ejemplo de array_values()

<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>

El resultado del ejemplo sería:

Array
(
    [0] => XL
    [1] => gold
)

Ver también

  • array_keys() - Devuelve todas las claves de un array o un subconjunto de claves de un array
  • array_combine() - Crea un nuevo array, usando una matriz para las claves y otra para sus valores

User Contributed Notes

biziclop at vipmail dot hu 01-May-2014 11:47
Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the 'foreach' ordering:

<?php
$a = array(
 3 => 11,
 1 => 22,
 2 => 33,
);
$a[0] = 44;

print_r( array_values( $a ));
==>
Array(
  [0] => 11
  [1] => 22
  [2] => 33
  [3] => 44
)
?>
heber dot gentilin at gmail dot com 21-Aug-2013 06:43
/**
* Return the new array from the offset index
*/
function array_values_from($array, $offset_index = 0) {
    if (!is_array($array))
        return null;
    $index = (int)$offset_index;
    foreach($array as $i => $value)
        $array_return[$index++] = $value;
    return $array_return;
}
Certainist 22-Apr-2013 03:51
Non-recursive simplest array_flatten.

<?php

function array_flatten($arr) {
    $arr = array_values($arr);
    while (list($k,$v)=each($arr)) {
        if (is_array($v)) {
            array_splice($arr,$k,1,$v);
            next($arr);
        }
    }
    return $arr;
}

?>
info at djdb dot be 29-Jan-2013 12:45
<?php
$array = array("size" => "XL", "color" => "gold","x" => " ","y" => "gold","z" => "");
print_r(array_values($array));
?>
wil result:
Array ( [0] => XL [1] => gold [2] => [3] => gold [4] => )
kapilgopinath at gmail dot com 09-Mar-2012 06:57
extract all values from a multi dimesnsional array or a nexted json object
function array_keys_multi($array,&$vals)
{
    foreach ($array as $key => $value) {

        if (is_array($value)) {

            array_keys_multi($value,$vals);

        }else{

            $vals[] = $value;
        }
    }

    return $vals;
}
a dot ross at amdev dot eu 30-May-2011 12:21
<?php
/**
 * Flattens an array, or returns FALSE on fail.
 */
function array_flatten($array) {
  if (!is_array($array)) {
    return FALSE;
  }
  $result = array();
  foreach ($array as $key => $value) {
    if (is_array($value)) {
      $result = array_merge($result, array_flatten($value));
    }
    else {
      $result[$key] = $value;
    }
  }
  return $result;
}
?>
abimaelrc 10-May-2011 05:39
This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
<?php
/**
 * Get all values from specific key in a multidimensional array
 *
 * @param $key string
 * @param $arr array
 * @return null|string|array
 */
function array_value_recursive($key, array $arr){
    $val = array();
    array_walk_recursive($arr, function($v, $k) use($key, &$val){
        if($k == $key) array_push($val, $v);
    });
    return count($val) > 1 ? $val : array_pop($val);
}

$arr = array(
    'foo' => 'foo',
    'bar' => array(
        'baz' => 'baz',
        'candy' => 'candy',
        'vegetable' => array(
            'carrot' => 'carrot',
        )
    ),
    'vegetable' => array(
        'carrot' => 'carrot2',
    ),
    'fruits' => 'fruits',
);

var_dump(array_value_recursive('carrot', $arr)); // array(2) { [0]=> string(6) "carrot" [1]=> string(7) "carrot2" }
var_dump(array_value_recursive('apple', $arr)); // null
var_dump(array_value_recursive('baz', $arr)); // string(3) "baz"
var_dump(array_value_recursive('candy', $arr)); // string(5) "candy"
var_dump(array_value_recursive('pear', $arr)); // null
?>
aowie1 at gmail dot com 19-Jan-2011 12:23
I needed a function that recursively went into each level of the array to order (only the indexed) arrays... and NOT flatten the whole thing.

Solution:
<?php
function array_values_recursive($arr){
        $arr = array_values($arr);
        foreach($arr as $key => $val)
            if(array_values($val) === $val)
                $arr[$key] = array_values_recursive($val);

        return $arr;
}
?>
geo dot artemenko at gmail dot com 04-May-2010 12:37
same array_flatten function, compressed and preserving keys.

function array_flatten($a,$f=array()){
  if(!$a||!is_array($a))return '';
  foreach($a as $k=>$v){
    if(is_array($v))$f=array_flatten($v,$f);
    else $f[$k]=$v;
  }
  return $f;
}
Carsten Milkau 01-Nov-2009 04:46
Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus "preserving keys" may have different interpretations. Ivan's function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.

<?php
/*
 * Flattening a multi-dimensional array into a
 * single-dimensional one. The resulting keys are a
 * string-separated list of the original keys:
 *
 * a[x][y][z] becomes a[implode(sep, array(x,y,z))]
 */

function array_flatten_sep($sep, $array) {
  $result = array();
  $stack = array();
  array_push($stack, array("", $array));

  while (count($stack) > 0) {
    list($prefix, $array) = array_pop($stack);

    foreach ($array as $key => $value) {
      $new_key = $prefix . strval($key);

      if (is_array($value))
        array_push($stack, array($new_key . $sep, $value));
      else
        $result[$new_key] = $value
    }
  }

  return $result;
}

/*
 * Flattening a multi-dimensional array into an
 * n-dimensional one. The last n keys of each element are
 * preserved. If this results in ambiguities, results are
 * undefined.
 *
 * a[x_1][x_2]...[x_m]  becomes  a[x_{m-n+1}]...[x_m]
 */
function array_flatten_n($array, $n) {
  $result = array();
  $stack = array();
  array_push($stack, array(array(), $array));

  while (count($stack) > 0) {
    list($prefix, $array) = array_pop($stack);

    foreach ($array as $key => $value) {
      if (is_array($value)) {
        $new_prefix = array_values($prefix);
        array_push($new_prefix, $key);
        if (count($new_prefix) >= n)
          array_shift($new_prefix);

        array_push($stack, array($new_prefix, $value));
      } else {
        $array = $result;
        foreach ($prefix as $pkey) {
           if (!is_array($array[$pkey]))
             $array[$pkey] = array();
           $array = $array[$pkey];
        }
        $array[$key] = $value;
      }
    }
  }

  return $result;
}
?>
karl dot rixon at gmail dot com 18-Sep-2009 02:57
A modification of wellandpower at hotmail.com's function to perform array_values recursively. This version will only re-index numeric keys, leaving associative array indexes alone.

<?php

function array_values_recursive($array) {
    $temp = array();
    foreach ($array as $key => $value) {
        if (is_numeric($key)) {
            $temp[] = is_array($value) ? array_values_recursive($value) : $value;
        } else {
            $temp[$key] = is_array($value) ? array_values_recursive($value) : $value;
        }
    }
    return $temp;
}

?>
chrysb at gmail dot com 24-Sep-2008 12:34
If you are looking for a way to count the total number of times a specific value appears in array, use this function:

<?php
function array_value_count ($match, $array)
{
    $count = 0;

    foreach ($array as $key => $value)
    {
        if ($value == $match)
        {
            $count++;
        }
    }

    return $count;
}
?>

This should really be a native function of PHP.
madhamster 12-Jun-2008 04:18
Good function, if you want to acces associative array element by position:

<?php

$array = array('fruit'=>'apple', 'juice'=>'orange', 'color'=>'lime');

$array = array_values($array);

echo $array[2];

?>
rene dot zak at post dot cz 24-Apr-2008 01:05
<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => ' ',
    'fruit4' => ' ',
    'fruit5' => 'apple');

    for ($i = 0; $i <  count($array); $i++) {
    $key=key($array);
    $val=$array[$key];
    if ($val<> ' ') {
       echo $key ." = ".  $val ." <br> ";
       }
     next($array);
    }

/*
fruit1 = apple
fruit2 = orange
fruit5 = apple
*/
?>
bluej100 at gmail dot com 07-Sep-2007 10:10
Most of the array_flatten functions don't allow preservation of keys. Mine allows preserve, don't preserve, and preserve only strings (default).

<?
// recursively reduces deep arrays to single-dimensional arrays
// $preserve_keys: (0=>never, 1=>strings, 2=>always)
function array_flatten($array, $preserve_keys = 1, &$newArray = Array()) {
  foreach ($array as $key => $child) {
    if (is_array($child)) {
      $newArray =& array_flatten($child, $preserve_keys, $newArray);
    } elseif ($preserve_keys + is_string($key) > 1) {
      $newArray[$key] = $child;
    } else {
      $newArray[] = $child;
    }
  }
  return $newArray;
}

// Tests

$array = Array(
  'A' => Array(
    1 => 'foo',
    2 => Array(
      'a' => 'bar'
    )
  ),
  'B' => 'baz'
);

echo 'var_dump($array);'."\n";
var_dump($array);
echo 'var_dump(array_flatten($array, 0));'."\n";
var_dump(array_flatten($array, 0));
echo 'var_dump(array_flatten($array, 1));'."\n";
var_dump(array_flatten($array, 1));
echo 'var_dump(array_flatten($array, 2));'."\n";
var_dump(array_flatten($array, 2));
?>
deceze at gmail dot YesThatsGoogleMail dot com 03-Sep-2007 12:31
Please note that 'wellandpower at hotmail.com's recursive merge doesn't work. Here's the fixed version:

<?php

function array_values_recursive($array) {
   $flat = array();

   foreach ($array as $value) {
           if (is_array($value)) $flat = array_merge($flat, array_values_recursive($value));
           else $flat[] = $value;
   }
   return $flat;
}

?>
warmo_at_o2_dot_pl 21-Mar-2007 10:42
@Yassin Ezbakhe <yassin88 at gmail dot com>
When we have to flatten multidimensional array of strings or numbers this method could be much faster.
Inconvenience of this method is, that its speed depends on size of strings/numbers, which array contains - bigger strings, lower efficiency.
Conclusion: Use this method for small amount of data in arrays (less than 500B per element in my case) which have many dimensions, in other case, use Yassin Ezbakhe method.

<?php

function md_implode($array, $glue = '')
{
    if (is_array ($array))
    {
        $output = '';
        foreach ($array as $v)
        {
            $output .= md_implode($v, $glue);
        }
        return $output;
    }
    else
    {
        return $array.$glue;
    }
}

function md_array_flatten($md_array)
{
    $flat_array = explode ('#|#',md_implode($md_array,'#|#')); // "#|#" is a sample delimiter
    array_pop($flat_array); // to remove last empty element
    return $flat_array;
}

//Usage:
$flat_array = md_array_flatten($some_md_array)

?>
ahigerd at stratitec dot com 24-Jan-2007 06:07
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
wellandpower at hotmail.com 29-Aug-2006 05:56
The function here flatterns an entire array and was not the behaviour I expected from a function of this name.

I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.

In order to do this, you will want this function:

function array_values_recursive($array) {
   $temp = array();

   foreach ($array as $value) {
           if(is_array($value)) { $temp[] = array_values_recursive($value); }
           else { $temp[] = $value; }
   }
   return $temp;
}

Hopefully this will assist.
wizglins at gmx dot ch 13-Apr-2006 12:21
In case you want to replace all keys in multiarrays by integers starting at 0, the following function might help.

<?php

function numerieren($array)
{
$array_v = array_values($array);
$count_v = count($array_v);

for ($i=0; $i<$count_v; $i++)
  if (is_array($array_v[$i]))
    $array_v[$i] = numerieren($array_v[$i]);
return $array_v;
}

?>
Yassin Ezbakhe <yassin88 at gmail dot com> 31-Aug-2005 04:28
<?php
/**********************************************
 *
 *   PURPOSE: Flatten a deep multidimensional array into a list of its
 *   scalar values
 *
 *   array array_values_recursive (array array)
 *
 *   WARNING: Array keys will be lost
 *
 *********************************************/

function array_values_recursive($array)
{
    $arrayValues = array();

    foreach ($array as $value)
    {
        if (is_scalar($value) OR is_resource($value))
        {
             $arrayValues[] = $value;
        }
        elseif (is_array($value))
        {
             $arrayValues = array_merge($arrayValues, array_values_recursive($value));
        }
    }

    return $arrayValues;
}
?>

This function is an improved and faster version of the one posted by <27-Apr-2004 09:47>
27-Apr-2004 06:47
<?php
/**
   flatten an arbitrarily deep multidimensional array
   into a list of its scalar values
   (may be inefficient for large structures)
   (will infinite recurse on self-referential structures)
   (could be extended to handle objects)
*/
function array_values_recursive($ary)
{
   $lst = array();
   foreach( array_keys($ary) as $k ){
      $v = $ary[$k];
      if (is_scalar($v)) {
         $lst[] = $v;
      } elseif (is_array($v)) {
         $lst = array_merge( $lst,
            array_values_recursive($v)
         );
      }
   }
   return $lst;
}
?>

code till dawn!  -mark meves!
nopy at users dot sourceforge dot net 24-Oct-2003 03:36
Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.

For example, if your PHP momory_limits is 8MB,
 and says there's a BIG array $bigArray which allocate 5MB of memory.

Doing this will cause PHP exceeds the momory limits:

<?php
  $bigArray = array_values( $bigArray );
?>

It's because array_values() does not re-index $bigArray directly,
it just re-index it into another array, and assign to itself later.
mailseppel at gmx dot de 04-Oct-2002 04:10
Remember, that the following way of fetching data from a mySql-Table will do exactly the thing as carl described before: An array, which data may be accessed both by numerical and DB-ID-based Indexes:

<?php
$row = mysql_fetch_array($db_result, $db_link);
?>

Hope I haven't misunderstood anything here.. :)
carl at thep.lu.se 29-Jan-2002 03:59
Indeed you can, and that's what's so great about it. I have, for instance, a function that returns the results of a database query as an array. I want to keep the order that the entries were returned in, but at the same time I want to be able to access them _either_ by the position _or_ by some other index (such as some sort of ID in the database, gotten from elsewhere). In this case, I can make the function return an array from id to [array of values], and by a simple call to array_values() this is transformed into an array indexed from 0 to count()-1. Useful.


Aplicar una función de usuario recursivamente a cada miembro de un array

  • « array_values
  • array_walk »
  • PHP Manual
  • Funciones de Arrays
  • Aplicar una función de usuario recursivamente a cada miembro de un array

array_walk_recursive

(PHP 5, PHP 7, PHP 8)

array_walk_recursive — Aplicar una función de usuario recursivamente a cada miembro de un array

Descripción

array_walk_recursive ( array &$array , callable $callback , mixed $userdata = null ) : bool

Aplica la función definida por el usuario callback a cada elemento del array. Esta función opera de forma recursiva sobre arrays con más niveles.

Parámetros

array

El array de entrada.

callback

Por lo general, callback recibe dos parámetros. El valor del parámetro array es el primero, y la clave/índice es el segundo.

Nota:

Si callback necesita trabajar con los valores reales del array, especifique el primer parámetro de callback como una referencia. Entonces, cualquier cambio realizado sobre esos elementos será efectuado sobre el array original mismo.

userdata

Si se define el parámetro opcional userdata, éste será pasado como el tercer parámetro al callback.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de array_walk_recursive()

<?php
$dulce = array('a' => 'manzana', 'b' => 'banano');
$frutas = array('dulce' => $dulce, 'acido' => 'limón');

function prueba_imprimir($item, $clave)
{
    echo "$clave contiene $item\n";
}

array_walk_recursive($frutas, 'prueba_imprimir');
?>

El resultado del ejemplo sería:

a contiene manzana
b contiene banano
acido contiene limón

Notará que la clave 'dulce' nunca es mostrada. Cualquier clave que contenga un valor array no será pasada a la función.

Ver también

  • array_walk() - Aplicar una función proporcionada por el usuario a cada miembro de un array

User Contributed Notes

lincoln dot du dot j at gmail dot com 21-Jul-2020 02:24
Normal function solution

//1,2,2,3,6,7,3,1,4,2
$arr=[
    [1,2],
    [2,3],
    6,7,[3,1,[4,2]]
];

function a($array){
    static $res=[];
    foreach($array as $val){
        if(is_array($val)){
            a($val);
        }else{
            $res[]=$val;
        }
    }
    return $res;
}

print_r(a($arr));
mike at mpsharp dot com 13-Jul-2019 04:32
Here's a more general solution to modifying the array to which the leaf belongs.   You can unset the current key, or add siblings, etc.

<?php
/**
 * Modified version of array_walk_recursive that passes in the array to the callback
 * The callback can modify the array or value by specifying a reference for the parameter.
 *
 * @param array The input array.
 * @param callable $callback($value, $key, $array)
 */
function array_walk_recursive_array(array &$array, callable $callback) {
    foreach ($array as $k => &$v) {
        if (is_array($v)) {
            array_walk_recursive_array($v, $callback);
        } else {
            $callback($v, $k, $array);
        }
    }
}
?>
Dario 01-Oct-2018 06:42
I was looking for how to change values of array since you can't pass array by reference anymore in new PHP versions, here is simple solution

<?php
array_walk_recursive(
    $myArray,
    function (&$value) {
        if (/*some condition*/) {
            $value = 'New value';
        }
    }
);
?>

After that $myArray will be altered with new value.
r 08-Apr-2018 02:54
How to modify external variable from inside recursive function using userdata argument.

<?php
$arr = [
   'one' => ['one_one' => 11, 'one_two' => 12],
   'two' => 2
];

$counter = 0;

//Does not persist
array_walk_recursive( $arr, function($value, $key, $counter) {
   $counter++;
   echo "$value : $counter";
}, $counter);
echo "counter : $counter";

// result
// 11 : 1
// 12 : 1
// 2 : 1
// counter: 0

//Persists only in same array node
array_walk_recursive( $arr, function($value, $key, &$counter) {
   $counter++;
   echo "$value : $counter";
}, $counter);

// result
// 11 : 1
// 12 : 2
// 2 : 1
// counter : 0

//Fully persistent. Using 'use' keyword
array_walk_recursive( $arr, function($value, $key) use (&$counter) {
   $counter++;
   echo "$value : $counter";
}, $counter);
echo "counter : $counter";

// result
// 11 : 1
// 12 : 2
// 2 : 3
// counter : 3
seductiveapps.com 14-Mar-2018 05:45
usage :
$nd = $newsApp2->dataSources();
//walkArray ($nd, 'walkArray_printKey', 'walkArray_printValue');
// prints the entire array

$x = chaseToPath ($nd, 'RSS_list/English News',false);
walkArray ($x, 'walkArray_printKey', 'walkArray_printValue');
// prints everything under $nd['RSS_list']['English News']

function &chaseToPath (&$wm, $path, $create=false) {
    //var_dump ($create); die();
    //echo '$wm=<pre>'; var_dump ($wm);echo '</pre>'; //die();
    //$path = str_replace ('/', '/d/', $path);
    //$path .= '/d';
    $nodes = explode ('/', $path);
    $chase = &chase ($wm, $nodes, $create);

    //echo '$wm=<pre>'; var_dump ($wm);echo '</pre>'; die();
    /*
    $dbg = array (
        '$path' => $path,
        '$nodes' => $nodes,
        '$wm' => $wm,
        '$chase' => $chase
    );
    echo '$dbg=<pre style="background:red;color:yellow;">'; var_dump ($dbg); echo '</pre>';
    */
    //die();

    $false = false;
    if (good($chase)) {
        $arr = &result($chase);
        return $arr;
    } else return $false;
}

function &chase (&$arr, $indexes, $create=false) {
        if (false) {
        echo 'sitewide/functions.php --- $arr=<pre>'; var_dump ($arr); echo '</pre>';
        echo 'sitewide/functions.php --- $indexes=<pre>'; var_dump ($indexes); echo '</pre>';
        echo 'sitewide/functions.php --- $create=<pre>'; var_dump ($create); echo '</pre>';
        }
    $r = &$arr;
    foreach ($indexes as $idx) {
            //echo 'sitewide/functions.php --- $idx=<pre>'; var_dump ($idx); var_dump (array_key_exists($idx,$r)); var_dump ($r); echo '</pre>';
            if (
                    is_array($r)
                    && (
                            $create===true
                            || array_key_exists($idx,$r)
                    )
            ) {
                    if ($create===true && !array_key_exists($idx,$r)) $r[$idx]=array();
                    //echo 'sitewide/functions.php --- $idx=<pre>'; var_dump ($idx); echo '</pre>';
                    $r = &$r[$idx];
            } else {
                    $err = array(
                    'msg' => 'Could not walk the full tree',
                    'vars' => array(
                            '$idx--error'=>$idx,
                            '$indexes'=>$indexes,
                            '$arr'=>$arr
                            )
                    );
                    badResult (E_USER_NOTICE, $err);
                    $ret = false; // BUG #2 squashed
                    return $ret;
            }
    }

        //echo 'sitewide/functions.php --- $r=<pre>'; var_dump ($r); echo '</pre>';
    return goodResult($r);
}
seductiveapps.com 14-Mar-2018 05:10
function walkArray (&$a, $keyCallback, $valueCallback, $k='', $level=0, $path='') {
// usage : walkArray ($someRecursiveArray, 'walkArray_printKey', 'walkArray_printValue');
// can handle recursive arrays. a nested array is a recursive array.
// is faster, especially on large arrays, than RecuriveArrayIterator, see speed testing comment at http://php.net/manual/en/class.recursiveiteratoriterator.php
// provides detailed information to callbacks on where in the data we are, something that array_walk_recursive just doesnt do.
// passes data around as pointers, not copies of data.
    if (
        !function_exists($keyCallback)
        && !function_exists($valueCallback)
    ) {
        return badResult (E_USER_ERROR, array (
            'msg' => 'walkArray() was called without $keyCallback or $valueCallback as existing function names. see also : call_user_func() in PHP manual.'
        );
    }

    if (!is_array($a)) {
        return badResult (E_USER_ERROR, array (
            'msg' => 'walkArray() was called but $a parameter passed is not an array.'
        ));
    } else {
        foreach ($a as $k=>&$v) {
            $cd = array ( // callback data
                'type' => 'key',
                'path' => $path,
                'level' => $level,
                'k' => &$k,
                'v' => &$v
            );
            if (!is_null($keyCallback)) call_user_func ($keyCallback, $cd);
            if (is_array ($v)) {
                walkArray ($a[$k], $keyCallback, $valueCallback, $k, $level+1, $path.'/'.$k);
            } else {
                $cd['type'] = 'value';
                if (!is_null($valueCallback)) call_user_func ($valueCallback, $cd);
            }
        }
    }
    return true;
}

function walkArray_printKey ($cd) {
    echo '<div style="background:blue;color:yellow;border-radius:5px;padding:2px;margin-top:5px;">'.PHP_EOL;
    $indent = 20 * $cd['level'];
    echo '<div style="padding-left:'.$indent.'px">'.PHP_EOL;
    echo 'key : '.$cd['k'].'<br/>'.PHP_EOL;
    echo 'path : '.$cd['path'].'<br/>'.PHP_EOL;
    echo '</div>'.PHP_EOL;
    echo '</div>'.PHP_EOL;
}

function walkArray_printValue ($cd) {
    echo '<pre style="background:green;color:white;border-radius:5px;padding:2px;margin-top:2px;">'.PHP_EOL;
    $indent = 20 * $cd['level'];
    echo '<div style="padding-left:'.$indent.'px">'.PHP_EOL;
    echo 'key : '.$cd['k'].'<br/>'.PHP_EOL;
    echo 'path : '.$cd['path'].'<br/>'.PHP_EOL;
    echo 'value : '.$cd['v'].'<br/>'.PHP_EOL;
    echo '</div>'.PHP_EOL;
    echo '</pre>'.PHP_EOL;
}

// the only thing you have to change in this code is the badResult() function, but you could raise an exception or return false
CommentUser 07-Jul-2017 01:55
The following code, which returns back a flattened array of sorts into the $results array, in newer versions of PHP raises the error "PHP Fatal error:  Call-time pass-by-reference has been removed":

<?php

$results = array();

function example_function ($item, $key, &$arr_values)
{
    $arr_values[$key] = $item;
}

array_walk_recursive($data, 'example_function', &$results);

print_r($results);

?>

This can be fixed using an anonymous function:

<?php

$results = array();

array_walk_recursive($data, function ($item, $key) use (&$results){$results[$key] = $item;});

print_r($results);

?>
lincoln dot du dot j at gmail dot com 03-Jul-2017 06:40
multidimensional array to single array

$array=[1=>[2,5=>[4,2],[7,8=>[3,6]],5],4];
$arr=[];
array_walk_recursive($array, function($k){global $arr; $arr[]=$k;});
print_r($arr);

Output

Array ( [0] => 2 [1] => 4 [2] => 2 [3] => 7 [4] => 3 [5] => 6 [6] => 5 [7] => 4 )
Anonymous 03-Jul-2017 06:39
multidimensional array to single array

$array=[1=>[2,5=>[4,2],[7,8=>[3,6]],5],4];
$arr=[];
array_walk_recursive($array, function($k){global $arr; $arr[]=$k;});
print_r($arr);

Output

Array ( [0] => 2 [1] => 4 [2] => 2 [3] => 7 [4] => 3 [5] => 6 [6] => 5 [7] => 4 )
webdiecinove at gmail dot com 04-Jan-2017 04:34
If you want print a multidimensional array, you could try this (the array I use is just an example).
Then, I use array_walk_recursive with a function that checks the type of items:

$arraytest=array();
$arraytest["firstlev1"] = "First level";
$arraytest["firstlev2"] = array(
                0 => array(
                    "secondlev11"=>"Title1",
                    "secondlev12"=>"Subtitle1",
                    "secondlev13" => array(
                        0 => array("othertitle"=>"other title", "othersubtitle"=>"other sub title"),
                        1 => array("info"=>"Informations", "otherinfo"=>"Other info")
                    )
                ),
                1 => array(
                        "secondlev21"=>"Title2",
                        "secondlev22"=>"Subtitle2"
                )
);

function testitems($theitem,$thekey){

    if(is_array($theitem)){
        foreach($theitem as $thekey=> $theitem2){
            echo "<br>the key: $thekey..........the item: $theitem2";
        }
    }
    else{
            echo "<br>the value:  $theitem";

    }

}

array_walk_recursive($arraytest, 'testitems');
KH 01-Nov-2016 05:43
Example for the use of $userdata:

$userdata is the third parameter of the callback function.
The first parameter is $item, the second is $key, and the third one is $userdata.

<?php
$sweet = array('a' => 'Apfel', 'b' => 'Banane');
$fruits = array('süß' => $sweet, 'sauer' => 'Zitrone');

function test_print($item, $key, $info)
{
    echo "$key beinhaltet $item $info\n";
}

array_walk_recursive($fruits, 'test_print', '  ... Bio');
?>

generates

a beinhaltet Apfel ... Bio
b beinhaltet Banane ... Bio
sauer beinhaltet Zitrone ... Bio
php at genjo dot fr 13-Mar-2015 05:33
I use RecursiveIteratorIterator with parameter CATCH_GET_CHILD to iterate on leafs AND nodes instead of array_walk_recursive function :

<?php
// Iteration on leafs AND nodes
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($candidate), RecursiveIteratorIterator::CATCH_GET_CHILD) as $key => $value) {
    echo 'My node ' . $key . ' with value ' . $value . PHP_EOL;
}
?>
robin leffmann 28-Jan-2015 03:48
A simple solution for walking a nested array to obtain the last set value of a specified key:

<?php

$key = 'blah';
$val = null;
array_walk_recursive( $your_array,
                      function($v, $k, $u) { if($k === $u[0]) $u[1] = $v; },
                      [$key ,&$val] );

echo "$key = $val";

?>
gk at anuary dot com 07-Mar-2014 09:29
array_walk_recursive itself cannot unset values. Even though you can pass array by reference, unsetting the value in the callback will only unset the variable in that scope.

<?php
/**
 * http://uk1.php.net/array_walk_recursive implementation that is used to remove nodes from the array.
 *
 * @param array The input array.
 * @param callable $callback Function must return boolean value indicating whether to remove the node.
 * @return array
 */
function walk_recursive_remove (array $array, callable $callback) {
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            $array[$k] = walk_recursive_remove($v, $callback);
        } else {
            if ($callback($v, $k)) {
                unset($array[$k]);
            }
        }
    }

    return $array;
}
?>

An up to date implementation of the above function can be looked up from https://github.com/gajus/marray/blob/master/src/marray.php#L116.
Anonymous 21-Nov-2013 10:42
since PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.
Rodrigo Guariento 23-Aug-2013 01:27
Simple array_walk_recursive:

// var example
$myArray = Array(
  Array('keyA1' => '    textA1 ', 'keyA2' => '  textA2     '),
  Array('keyB1' => '    textB1 ', 'sub' =>
        Array('keyB1_sub1' => '      textB1_sub1   '),
          Array('keyB1_sub2' => '      textB1_sub2   ')
      ),
  Array('keyC1' => '    textC1 ', 'keyC2' => '  textC2     '),
  Array('keyD1' => '    textD1 ', 'keyD2' => '  textD2     '),
  Array('keyE1' => '    textE1 ', 'keyE2' => '  textE2     ')
);

// function for "trim" (or your function, use same structure)
function trimming($data) {
  if (gettype($data) == 'array')
    return array_map("trimming", $data);
  else
    return trim($data);
}

// get array
$myArray = array_map("trimming", $myArray);

// show array trimmed
var_dump($myArray);

/*
RESULT

array (size=5)
  0 =>
    array (size=2)
      'keyA1' => string 'textA1' (length=6)
      'keyA2' => string 'textA2' (length=6)
  1 =>
    array (size=3)
      'keyB1' => string 'textB1' (length=6)
      'sub' =>
        array (size=1)
          'keyB1_sub1' => string 'textB1_sub1' (length=11)
      0 =>
        array (size=1)
          'keyB1_sub2' => string 'textB1_sub2' (length=11)
  2 =>
    array (size=2)
      'keyC1' => string 'textC1' (length=6)
      'keyC2' => string 'textC2' (length=6)
  3 =>
    array (size=2)
      'keyD1' => string 'textD1' (length=6)
      'keyD2' => string 'textD2' (length=6)
  4 =>
    array (size=2)
      'keyE1' => string 'textE1' (length=6)
      'keyE2' => string 'textE2' (length=6)

*/
none at of dot your dot biz 03-Jun-2013 10:50
Since this is only mentioned in the footnote of the output of one of the examples, I feel it should be spelled out:

* THIS FUNCTION ONLY VISITS LEAF NODES *

That is to say that if you have a tree of arrays with subarrays of subarrays, only the plain values at the leaves of the tree will be visited by the callback function.  The callback function isn't ever called for a nodes in the tree that subnodes (i.e., a subarray).  This has the effect as to make this function unusable for most practical situations.
chris at willowsconsulting dot ie 23-Oct-2012 10:11
To convert all values of an array in UTF8, do this:

<?php

function convert_before_json(&$item, &$key)
{
   $item=utf8_encode($item);
}

array_walk_recursive($your_array,"convert_before_json");

?>
cyranix at cyranix dot com 28-Oct-2011 07:45
I needed to add or modify values in an array with unknown structure. I was hoping to use array_walk_recursive for the task, but because I was also adding new nodes I came up with an alternate solution.

<?php

    /**
     * Sets key/value pairs at any depth on an array.
     * @param $data an array of key/value pairs to be added/modified
     * @param $array the array to operate on
     */
    function setNodes($data, &$array)
    {
        $separator = '.'; // set this to any string that won't occur in your keys
        foreach ($data as $name => $value) {
            if (strpos($name, $separator) === false) {
                // If the array doesn't contain a special separator character, just set the key/value pair.
                // If $value is an array, you will of course set nested key/value pairs just fine.
                $array[$name] = $value;
            } else {
                // In this case we're trying to target a specific nested node without overwriting any other siblings/ancestors.
                // The node or its ancestors may not exist yet.
                $keys = explode($separator, $name);
                // Set the root of the tree.
                $opt_tree =& $array;
                // Start traversing the tree using the specified keys.
                while ($key = array_shift($keys)) {
                    // If there are more keys after the current one...
                    if ($keys) {
                        if (!isset($opt_tree[$key]) || !is_array($opt_tree[$key])) {
                            // Create this node if it doesn't already exist.
                            $opt_tree[$key] = array();
                        }
                        // Redefine the "root" of the tree to this node (assign by reference) then process the next key.
                        $opt_tree =& $opt_tree[$key];
                    } else {
                        // This is the last key to check, so assign the value.
                        $opt_tree[$key] = $value;
                    }
                }
            }
        }
    }

?>

Sample usage:

<?php

$x = array();
setNodes(array('foo' => 'bar', 'baz' => array('quux' => 42, 'hup' => 101)), $x);
print_r($x); // $x has the same structure as the first argument
setNodes(array('jif.snee' => 'hello world', 'baz.quux.wek' => 5), $x);
print_r($x); // added $x['jif']['snee'] and modified $x['baz']['quux'] to be array('wek' => 5)

?>
ghoffman at salientdigital dot com 13-Oct-2011 10:29
If you are wanting to change the values of an existing multi-dimensional array, as it says above in the note, you need to specify the first argument as a reference. All that means is, be sure to precede the $item variable with an ampersand (&) as in the good_example below.

Unfortunately the PHP example given doesn't do this. It actually took me a while to figure out why my function wasn't changing the original array, even though I was passing by reference.

Here's the tip: Don't return any value from the function! Just change the value of $item that you passed in by reference. This is rather counter-intuitive since the vast majority of functions return a value.

<?php
// array_walk_recursive fails to change your array unless you pass by reference.
// Don't return values from your filter function, even though it's quite logical at a glance!
function bad_example($item,$key){
   if($key=='test'){
       return 'PHP Rocks';  // Don't do it
   }else{
      return $item;  // Don't do this either
   }
}

// array_walk_recursive pass-by-reference example
function good_example(&$item,$key){
   if($key=='test'){
        $item='PHP Rocks'; // Do This!
   }
}

$arr = array('a'=>'1','b'=>'2','test'=>'Replace This');

array_walk_recursive($arr,'bad_example');
var_dump($arr);
/**
 * no errors, but prints...
 * array('a'=>'1','b'=>'2','test'=>'Replace This');
 */

array_walk_recursive($arr,'good_example');
var_dump($arr);
/**
 * prints...
 * array('a'=>'1','b'=>'2','test'=>'PHP Rocks');
 */

?>

Returning a value from your function does work if you pass by reference and modify $item before you return, but you will eat up memory very, very fast if you try it, even on an example as small as the one here.

One other silly thing you might try first is something like this:

<?php
// Resist the urge to do this, it doesn't work.
$filtered = array_walk_recursive($unfiltered,'filter_function');
?>

Of course, $filtered is just TRUE afterwards, not the filtered results you were wanting. Oh, it ran your function recursively alright, but changed all the values in the local function scope only and returns a boolean as the documentation states.
rob at yurkowski dot net 26-Oct-2010 11:16
If you don't really particularly care about the keys of an array, you can capture all values quite simply:

<?php

$sample = array('dog' => 'woof', 'cat' => array('angry' => 'hiss', 'happy' => 'purr'), 'aardvark' => 'kssksskss');
$output = array();

// Push all $val onto $output.
array_walk_recursive($sample, create_function('$val, $key, $obj', 'array_push($obj, $val);'), &output);

// Printing
echo nl2br(print_r($output, true));

/*
* Array
* (
*  [0] => woof
*  [1] => hiss
*  [2] => purr
*  [3] => kssksskss
* )
*/
?>

[EDIT BY danbrown AT php DOT net: In a note added by 'FaustoFilho' on 17-MAY-2011, the following information was appended to this note.

[If you intend to use this] "function to extract the last key value of an array, don't forget to insert a currency sign ($) signal before '$output' at 7th line.

This value must be a variable, and if you forgot to assign this signal, your code won't work, displaying an error like this:

Parse error: syntax error, unexpected ')', expecting T_PAAMAYIM_NEKUDOTAYIM in /path/to/script.php on line 7."]
bradbeattie at gmail dot com 27-Aug-2010 11:18
The description says "If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference." This isn't necessarily helpful as the function you're calling might be built in (e.g. trim or strip_tags). One option would be to create a version of these like so.

<?php
    function trim_by_reference(&$string) {
        $string = trim($string);
    }
?>

The downside to this approach is that you need to create a wrapper function for each function you might want to call. Instead, we can use PHP 5.3's inline function syntax to create a new version of array_walk_recursive.

<?php
    /**
     * This function acts exactly like array_walk_recursive, except that it pretends that the function
     * its calling replaces the value with its result.
     *
     * @param $array The first value of the array will be passed into $function as the primary argument
     * @param $function The function to be called on each element in the array, recursively
     * @param $parameters An optional array of the additional parameters to be appeneded to the function
     *
     * Example usage to alter $array to get the second, third and fourth character from each value
     *     array_walk_recursive_referential($array, "substr", array("1","3"));
     */
    function array_walk_recursive_referential(&$array, $function, $parameters = array()) {
        $reference_function = function(&$value, $key, $userdata) {
            $parameters = array_merge(array($value), $userdata[1]);
            $value = call_user_func_array($userdata[0], $parameters);
        };
        array_walk_recursive($array, $reference_function, array($function, $parameters));
    }
?>

The advantage here is that we only explicitly define one wrapper function instead of potentially dozens.
amoffat at amoffat dot com 04-Jun-2008 05:15
<?
function my_array_map() {
    $args = func_get_args();
    $arr = array_shift($args);

    foreach ($args as $fn) {
        $nfn = create_function('&$v, $k, $fn', '$v = $fn($v);');
        array_walk_recursive($arr, $nfn, $fn);
    }
    return $arr;
}
?>

takes an array as the first argument, and functions as the other arguments.  it applies those functions recursively to the array
JW 14-Mar-2008 05:59
This function has a serious bug, which is still not fixed as of the PHP 5.2.5 release. After you call it, it can accidentally modify your original array. Save yourself hours of frustration by reading on.

The bug is here: http://bugs.php.net/bug.php?id=42850, and it looks like it will be fixed for 5.3.

If the array that you walk contains other array elements, they will be turned into references. This will happen even if the callback function doesn't take its first argument by reference, and doesn't do anything to the values.

For example, try this:
<?php
$data = array ('key1' => 'val1', 'key2' => array('key3' => 'val3'));
function foo($item, $key){}
var_dump($data);
?>

The original array has no references. Now try this:
<?php
array_walk_recursive($data,'foo');
var_dump($data);
?>

Now key2 is a reference, not just an array. So if you do this:
<?php
function test($item){$item['key2'] = array();}
test($data);
var_dump($data);
?>

you will see that test modifies $data, even though it shouldn't.

One workaround is to immediately make a deep copy of the array after calling array_walk_recursive, like this:
<?php
function array_duplicate($input) {
  if (!is_array($input)) return $input;
  $output = array();
  foreach ($input as $key => $value) {
    $output[$key] = array_duplicate($value);
  }
  return $output;
}
array_walk_recursive($data,'foo');
$data = array_duplicate($data);
var_dump($data);
?>

After doing that, the references are gone.
ik at paulkaspers dot nl 15-Oct-2006 01:46
To egingell at sisna dot com:

There is a small bug in your function, the following line should be changed:
From: if ($value != $saved_value || $saved_key != $key) {
Into: if ($value !== $saved_value || $saved_key !== $key) {

It's a nice function, because I was searching for something to change the keys of a multiple dimension array.
gabrielu at hotmail dot com 21-Feb-2006 01:13
I decided to add to the previous PHP 4 compatible version of array_walk_recursive() so that it would work within a class and as a standalone function.  Both instances are handled by the following function which I modified from omega13a at sbcglobal dot net.

The following example is for usage within a class.  To use as a standalone function take it out of the class and rename it.  (Example: array_walk_recursive_2)

<?php
class A_Class {

function array_walk_recursive(&$input, $funcname, $userdata = '') {
  if(!function_exists('array_walk_recursive')) {
    if(!is_callable($funcname))
      return false;

    if(!is_array($input))
      return false;

    foreach($input as $key=>$value) {
      if(is_array($input[$key])) {
        if(isset($this)) {
          eval('$this->' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
        } else {
          if(@get_class($this))
            eval(get_class() . '::' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
          else
            eval(__FUNCTION__ . '($input[$key], $funcname, $userdata);');
        }
      } else {
        $saved_value = $value;

        if(is_array($funcname)) {
          $f = '';
          for($a=0; $a<count($funcname); $a++)
            if(is_object($funcname[$a])) {
              $f .= get_class($funcname[$a]);
            } else {
              if($a > 0)
                $f .= '::';
              $f .= $funcname[$a];
            }
          $f .= '($value, $key' . (!empty($userdata) ? ', $userdata' : '') . ');';
          eval($f);
        } else {
          if(!empty($userdata))
            $funcname($value, $key, $userdata);
          else
            $funcname($value, $key);
        }

        if($value != $saved_value)
          $input[$key] = $value;
      }
    }
    return true;
  } else {
    array_walk_recursive($input, $funcname, $userdata);
  }
}

function kv_addslashes(&$v, $k) {
  $v = addslashes($v);
}
}
?>

Usage:
<?php
$arr = array(
  'a' => '"Hello World"',
  'b' => "'Hello World'",
  'c' => "Hello 'Worl\"d",
  'd' => array(
    'A' => 'H"e"l"l"o" "W"o"r"l"d'
    )
  );

$class = new A_Class();
$class->array_walk_recursive($arr, array(&$class, 'kv_addslashes'));
print_r($arr);
?>
omega13a at sbcglobal dot net 21-Dec-2005 04:21
This is a peice of code I wrote that appears to create this function for PHP 4.

<?php
if (!function_exists('array_walk_recursive'))
{
    function array_walk_recursive(&$input, $funcname, $userdata = "")
    {
        if (!is_callable($funcname))
        {
            return false;
        }

        if (!is_array($input))
        {
            return false;
        }

        foreach ($input AS $key => $value)
        {
            if (is_array($input[$key]))
            {
                array_walk_recursive($input[$key], $funcname, $userdata);
            }
            else
            {
                $saved_value = $value;
                if (!empty($userdata))
                {
                    $funcname($value, $key, $userdata);
                }
                else
                {
                    $funcname($value, $key);
                }

                if ($value != $saved_value)
                {
                    $input[$key] = $value;
                }
            }
        }
        return true;
    }
}
?>

Please note it is a conditionaly set function and will have to be put before any call to it.

If there is anything wrong with it, please email me.


Aplicar una función proporcionada por el usuario a cada miembro de un array

  • « array_walk_recursive
  • array »
  • PHP Manual
  • Funciones de Arrays
  • Aplicar una función proporcionada por el usuario a cada miembro de un array

array_walk

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

array_walk — Aplicar una función proporcionada por el usuario a cada miembro de un array

Descripción

array_walk ( array &$array , callable $callback , mixed $userdata = null ) : bool

Aplica la función definida por el usuario dada por callback a cada elemento del array dado por array.

array_walk() no le afecta el puntero de arrays interno de array. array_walk() recorrerá el array completo sin tener en cuenta la posición del puntero.

Parámetros

array

El array de entrada.

callback

Normalmente, callback asume dos parámetros. El primero, los valores de los parámetros de array, y el segundo la clave/índice.

Nota:

Si callback necesita trabajar con los valores reales del array, especifique el primer parámetro de callback como una referencia. Así, cualquier cambio hecho a esos elementos serán hechos al mismo array original.

Nota:

Muchas funciones internas (por ejemplo strtolower()) lanzarán una advertencia si se pasan más argumentos de los esperados y no son utilizables directamente como callback.

Sólo se pueden cambiar potencialmente los valores del parámetro array; no se puede alterar su estructura, esto es, el programador no puede añadir, destruir o reordenar elementos. Si la llamada de retorno no respeta este requisito, el comportamiento de esta función será indefinido e impredecible.

userdata

Si se proporciona el parámetro opcional userdata, éste será pasado como el tercer parámetro de la función dada por callback.

Valores devueltos

Devuelve true.

Errores/Excepciones

A partir de PHP 7.1.0, un ArgumentCountError será lanzado si la función callback requiere más de 2 parámetros (el valor y la clave del miembro del array). Anteriormente, si la función callback requería más de 2 parámetros, se generaba un error de nivel E_WARNING cada vez que array_walk() llamaba a callback.

Ejemplos

Ejemplo #1 Ejemplo de array_walk()

<?php
$frutas = array("d" => "limón", "a" => "naranja", "b" => "banana", "c" => "manzana");

function test_alter(&$elemento1, $clave, $prefijo)
{
    $elemento1 = "$prefijo: $elemento1";
}

function test_print($elemento2, $clave)
{
    echo "$clave. $elemento2<br />\n";
}

echo "Antes ...:\n";
array_walk($frutas, 'test_print');

array_walk($frutas, 'test_alter', 'fruta');
echo "... y después:\n";

array_walk($frutas, 'test_print');
?>

El resultado del ejemplo sería:

Antes ...:
d. limón
a. naranja
b. banana
c. manzana
... y después:
d. fruta: limón
a. fruta: naranja
b. fruta: banana
c. fruta: manzana

Ver también

  • array_walk_recursive() - Aplicar una función de usuario recursivamente a cada miembro de un array
  • iterator_apply() - Llamar a una función para cada elemento de un iterador
  • list() - Asignar variables como si fueran un array
  • each() - Devolver el par clave/valor actual de un array y avanzar el cursor del array
  • call_user_func_array() - Llamar a una llamada de retorno con un array de parámetros
  • array_map() - Aplica la retrollamada a los elementos de los arrays dados
  • foreach

User Contributed Notes

mystral77 at gmail dot com 24-Jun-2020 02:54
Hello,

If you want to add values with same key from two arrays :

<?php
function add(&$item,$key,$search) {
    $item += (is_array($search))?((isset($search[$key]))?$search[$key]:0):0;
}

$a = ["orange" => 2, "banana" => 3, "apple" => 1];
$b = ["orange" => 1, "apple" => 4];

array_walk($c,"add",$b);

echo "<pre>".print_r($c,true)."</pre>";
?>

This will output:

"orange" => 3,
"banana" => 3,
"apple" => 5
taj at yahoo dot fr 27-Feb-2019 11:42
// We can make that with this simple FOREACH loop :

$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

foreach($fruits as $cls => $vls)
{
  $fruits[$cls] = "fruit: ".$vls;
}

Results:

Array
(
    [d] => fruit: lemon
    [a] => fruit: orange
    [b] => fruit: banana
    [c] => fruit: apple
)
EllisGL 01-Aug-2018 06:15
For those that think they can't use array_walk to change / replace a key name, here you go:

<?php
function array_explore(array &$array, callable $callback)
{
    array_walk($array, function(&$value, $key) use (&$array, $callback)
    {
        $callback($array, $key, $value);

        if(is_array($value))
        {
            array_explore($value, $callback);
        }
    });
}

/**
 * Stolen from: https://stackoverflow.com/questions/13233405/change-key-in-associative-array-in-php
 */
function renameKey(array &$data, $oldKey, $newKey, $ignoreMissing = false, $replaceExisting = false)
{
    if (!empty($data))
    {
        if (!array_key_exists($oldKey, $data))
        {
            if ($ignoreMissing)
            {
                return FALSE;
            }

            throw new \Exception('Old key does not exist.');
        }
        else
        {
            if (array_key_exists($newKey, $data))
            {
                if ($replaceExisting)
                {
                    unset($data[$newKey]);
                }
                else
                {
                    throw new \Exception('New key already exist.');
                }
            }

            $keys = array_keys($data);

            // Fix from EllisGL: http://php.net/manual/en/function.array-search.php#122377
            $keys[array_search($oldKey, array_map('strval', $keys))] = $newKey;

            $data = array_combine($keys, $data);

            return TRUE;
        }
    }

    return FALSE;
}

$array = [
    "_10fish" => 'xyz',
    "_11fish" => [
        "_22" => "a", "b", "c"
        ],
    "someFish" => [
        'xyz',
        '@attributes' => ['type' => 'cod']
        ]
    ];

array_explore($array, function(&$value, $key)
{
    // Replace key '@attrutes' with '_attributes'
    if('@attributes' === $key)
    {
        renameKey($value, $key, '_attributes');
    }

});

print_r($array);
?>
01001coder at gmail dot com 05-Dec-2017 10:19
I noticed that :

PHP ignored arguments type when using array_walk() even if there was

declare(strict_types=1) .

See this code as an example ...

<?php
declare(strict_types=1);

$fruits = array("butter" => 5.3, "meat" => 7, "banana" => 3);

function test_print(int $item2, $key) {
    echo "$key: $item2<br />\n";
}

array_walk($fruits, 'test_print');

?>

The output is :

butter: 5
meat: 7
banana: 3

whilst the expecting output is :

Fatal error: Uncaught TypeError: Argument 1 passed to test_print() must be of the type integer

because "butter" => 5.3 is float

I asked someone about it and they said "this was caused by the fact that callbacks called from internal code will always use weak type". But I tried to do some tests and this behavior is not an issue when using call_user_func().
vrrivaro at YESIUSEGMAIL dot gmail dot SO dot com 18-Mar-2017 02:40
The output of the example is only correct if viewed through a web browser. If you pass it through to PHP-CLI, you will get to see the additional HTML line breaks, however.
fantomx1 at gmail dot com 22-Aug-2016 08:08
Since array_walk cannot modify / change / reindex keys as already mentioned, i provide this small wrapping function which accomplishes passing array reference and index using closures , "use" keyword.

function indexArrayByElement($array, $element)
{
    $arrayReindexed = [];
    array_walk(
        $array,
        function ($item, $key) use (&$arrayReindexed, $element) {
            $arrayReindexed[$item[$element]] = $item;
        }
    );
    return $arrayReindexed;
}
fred 30-Dec-2015 09:01
Correction for the speed test from zlobnygrif.

<?php
// Test results
$array1 = test('array_walk');
$array2 = test('array_walk_list_each');
$array3 = test('array_walk_foreach1');
$array4 = test('array_walk_foreach2');

// Check arrays for equal
var_dump($array1 == $array2, $array1 == $array3, $array1 == $array4);

// Test function 1
function array_walk_list_each(&$array, $function, $userData = null) {
   /* make sure we walk the array each time */
    reset($array);
    while ( list($key, $value) = each($array) )
        $function($array[$key], $key, $userData);
}

// Test function 2
function array_walk_foreach1(&$array, $function, $userData = null) {
    foreach ($array as $key => &$value )
        $function($value, $key, $userData);
}

// Test function 3
function array_walk_foreach2(&$array, $function, $userData = null) {
    foreach ($array as $key => $value )
        $function($array[$key], $key, $userData);
}

function some_function(&$value, $key, $userData) {
    $value = "$key => $userData";
}

function test($function, $count = 10000, $arrayElements = 1000) {
    echo $function, ' ... ';
    $array = array_fill(0, $arrayElements, "some text value");

    $timer = microtime(true);
    for( $i = 0; ++$i < $count; )
        /* change data for each $i */
        $function($array, 'some_function', 'some user data ' . $i);
    printf("%.3f sec\n", microtime(true) - $timer);

    return $array;
}
ezhacher at gmail dot com 27-Aug-2014 12:45
Calling an array Walk inside a class

If the class is static:
array_walk($array, array('self', 'walkFunction'));
or
array_walk($array, array('className', 'walkFunction'));

Otherwise:
array_walk($array, array($this, 'walkFunction'));
chaley at brtransport dot com 16-Jun-2014 12:46
There is a note about 3 years ago regarding using this for trimming. array_map() may be cleaner for this. I haven't checked the time/resource impact:

$result = array_map("trim", $array);
zlobnygrif at gmail dot com 17-Jul-2013 05:41
Some speed tests

<?php
// Test results
$array1 = test('array_walk');
$array2 = test('array_walk_list_each');
$array3 = test('array_walk_foreach1');
$array4 = test('array_walk_foreach2');

// Check arrays for equal
var_dump($array1 == $array2, $array1 == $array3, $array1 == $array4);

// Test function 1
function array_walk_list_each(&$array, $function, $userData = null) {
    while ( list($key, $value) = each($array) )
        $function($array[$key], $key, $userData);
}

// Test function 2
function array_walk_foreach1(&$array, $function, $userData = null) {
    foreach ($array as $key => &$value )
        $function($value, $key, $userData);
}

// Test function 3
function array_walk_foreach2(&$array, $function, $userData = null) {
    foreach ($array as $key => $value )
        $function($array[$key], $key, $userData);
}

function some_function(&$value, $key, $userData) {
    $value = "$key => $userData";
}

function test($function, $count = 10000, $arrayElements = 1000) {
    echo $function, ' ... ';
    $array = array_fill(0, $arrayElements, "some text value");

    $timer = microtime(true);
    for( $i = 0; ++$i < $count; )
        $function($array, 'some_function', 'some user data');
    printf("%.3f sec\n", microtime(true) - $timer);

    return $array;
}
?>

Output (PHP 5.4.9-4ubuntu2.2 (cli) (built: Jul 15 2013 18:24:39))
=========================
array_walk ... 13.572 sec
array_walk_list_each ... 0.027 sec
array_walk_foreach1 ... 15.356 sec
array_walk_foreach2 ... 17.416 sec
bool(true)
bool(true)
bool(true)

Output (PHP 5.5.0 (cli) (built: Jul 16 2013 17:59:42) - same server)
=========================
array_walk ... 4.776 sec
array_walk_list_each ... 0.006 sec
array_walk_foreach1 ... 4.482 sec
array_walk_foreach2 ... 5.166 sec
bool(true)
bool(true)
bool(true)

PHP 5.5 array_walk looks pretty good but list each is more and more quickly...
brian at access9 dot net 24-May-2013 10:03
array_walk does not work on SplFixedArray objects:
<?php
$array = new SplFixedArray(2);
$array[0] = 'test_1';
$array[1] = 'test_2';

array_walk($array, function(&$val){
    $val .= '__';
    return $val;
});
foreach ($array as $a) {
    echo "$a\n";
}
?>

result is:
test_1
test_2
gold[at]evolved.net.nz 27-Mar-2013 10:08
For all those people trying to shoe-horn trim() into array_walk() and have found all these tricks to work around the issue with array_walk() passing 2 parameters to the callback...

Check out array_map().

http://php.net/array_map

It's all sorts of win.

For the record. I'm one of these people and after 15 years of php development I'm pleased to say that there's still things I'm learning. :)  I just found out about array_map() myself...
espertalhao04 at hotmail dot com 26-Dec-2012 11:35
here is a simple and yet easy to use implementation of this function.
the 'original' function has the problem that you can't unset a value.
with my function, YOU CAN!

<?php
function array_walk_protected(&$a,$s,$p=null)
{
    if(!function_exists($s)||!is_array($a))
    {
        return false;
    }

    foreach($a as $k=>$v)
    {
        if(call_user_func_array($s,array(&$a[$k],$k,$p))===false)
        {
            unset($a[$k]);
        }
    }
}

function get_name(&$e,$i,$p)
{
    echo "$i: $e<br>";
    return false;
}

$m=array('d'=>'33','Y'=>55);

array_walk_protected($m,'get_name');

var_dump($m); //returns array(0) { }
?>

i called it array_walk_protected because it is protected against the unexpected behavior of unsetting the value with the original function.

to delete an element, simply return false!!!
nothing else is needed!
unsetting $e, under your created function, will keep the same array as-is, with no changes!

by the way, the function returns false if $a is not array or $s is not a string!

limitations: it only can run user defined functions.
i hope you like it!
manuscle at gmail dot com 06-Dec-2011 07:16
example with closures, checking and deleting value in array:

<?php
$array = array('foo' => 'bar', 'baz' => 'bat');

array_walk($array, function($val,$key) use(&$array){
    if ($val == 'bar') {
        unset($array[$key]);
    }
});

var_dump($array);
alex_stanhope at hotmail dot com 26-Oct-2011 01:16
I wanted to walk an array and reverse map it into a second array.  I decided to use array_walk because it should be faster than a reset,next loop or foreach(x as &$y) loop.

<?php
$output = array();
array_walk($input, 'gmapmark_reverse', $output);

function gmapmark_reverse(&$item, $index, &$target) {
    $target[$item['form_key']] = $index;
}
?>

In my debugger I can see that $target is progressively updated, but when array_walk returns, $output is empty.  If however I use a (deprecated) call-by-reference:

<?php
array_walk($input, 'gmapmark_reverse', &$output);
?>

$output is returned correctly.  Unfortunately there's not an easy way to suppress the warnings:

<?php
@array_walk($input, 'gmapmark_reverse', &$output);
?>

doesn't silence them.  I've designed a workaround using a static array:

<?php
$reverse = array();
array_walk($input, 'gmapmark_reverse');
// call function one last time to get target array out, because parameters don't work
$reverse = gmapmark_reverse($reverse);

function gmapmark_reverse(&$item, $index = 0) {
  static $target;
  if (!$target) {
    $target = array();
  }
  if (isset($item['form_key'])) {
    $target[$item['form_key']] = $index;
  }
  return($target);
}
?>
tufanbarisyildirim at gmail dot com 05-Oct-2011 06:15
Filter an array by using key.

<?php
    $product_1 = 'test';
    $product_2 = 'test 2';

    function array_key_filter($array,$callback = 'trim')
    {
        $filtered = array();
        array_walk($array,function ($degeri,$degisken_adi) use (&$filtered,$callback)
        {
            if($callback($degisken_adi))
            {
                $filtered[$degisken_adi] =  $degeri;
            }
        });

        return $filtered;
    }

    #using

    $degiskenler = array_key_filter(get_defined_vars(),function($key)
    {
        return strpos($key,'product_') === 0;
    });

    print_r($degiskenler);
?>
output:

Array
(
    [product_1] => test
    [product_2] => test 2
)
Maxim 11-Jul-2011 12:23
Note that using array_walk with intval is inappropriate.
There are many examples on internet that suggest to use following code to safely escape $_POST arrays of integers:
<?php
array_walk($_POST['something'],'intval'); // does nothing in PHP 5.3.3
?>
It works in _some_ older PHP versions (5.2), but is against specifications. Since intval() does not modify it's arguments, but returns modified result, the code above has no effect on the array and will leave security hole in your website.

You can use following instead:
<?php
$_POST['something'] = array_map(intval,$_POST['something']);
?>
@jfredys 22-Mar-2011 05:07
I was looking for trimming all the elements in an array, I found this as the simplest solution:

<?php
array_walk($ids, create_function('&$val', '$val = trim($val);'));
?>
http://alex.moutonking.com/wordpress 15-Feb-2011 10:49
For completeness one has to mention the possibility of using this function with PHP 5.3 closures:

<?php
$names = array("D\'Artagnan", "Aramis", "Portos");
array_walk($names, function(&$n) {
  $n = stripslashes($n);
});
?>

The trap with array_walk being it doesn't return the array, instead it's modified by reference.
op_adept at yahoo dot co dot uk 02-Dec-2010 03:20
Prefix array values with keys and retrieve as a glued string, the original array remains unchanged. I used this to create some SQL queries from arrays.

<?php

function array_implode_prefix($outer_glue, $arr, $inner_glue, $prefix=false){
    array_walk( $arr , "prefix", array($inner_glue, $prefix) );
    return implode($outer_glue, $arr);
}

function prefix(&$value, $key, array $additional){
    $inner_glue = $additional[0];
    $prefix = isset($additional[1])? $additional[1] : false;
    if($prefix === false) $prefix = $key;

    $value = $prefix.$inner_glue.$value;
}

//Example 1:
$order_by = array("3"=>"ASC", "2"=>"DESC", "7"=>"ASC");
echo array_implode_prefix(",", $order_by, " ");
//Output: 3 ASC,2 DESC,7 ASC

//Example 2:
$columns = array("product_id", "category_id", "name", "description");
$table = "product";

echo array_implode_prefix(", ", $columns, ".", $table);
//Output:product.product_id, product.category_id, product.name, product.description

//Example 3 (function prefix) won't really be used on its own
$pre= "vacation";
$value = "lalaland";
prefix($value, $pre, array("."));
echo $value;

//Output: vacation.lalaland

?>
matthew at codenaked dot org 02-Sep-2010 11:24
Using lambdas you can create a handy zip function to zip together the keys and values of an array. I extended it to allow you to pass in the "glue" string as the optional userdata parameter. The following example is used to zip an array of email headers:

<?php

/**
 * Zip together the keys and values of an array using the provided glue
 *
 * The values of the array are replaced with the new computed value
 *
 * @param array $data
 * @param string $glue
 */
function zip(&$data, $glue=': ')
{
    if(!is_array($data)) {
        throw new InvalidArgumentException('First parameter must be an array');
    }

    array_walk($data, function(&$value, $key, $joinUsing) {
        $value = $key . $joinUsing . $value;
    }, $glue);
}

$myName = 'Matthew Purdon';
$myEmail = 'matthew@example.com';
$from = "$myName <$myEmail>";

$headers['From'] = $from;
$headers['Reply-To'] = $from;
$headers['Return-path'] = "<$myEmail>";
$headers['X-Mailer'] = "PHP" . phpversion() . "";
$headers['Content-Type'] = 'text/plain; charset="UTF-8"';

zip($headers);

$headers = implode("\n", $headers);
$headers .= "\n";

echo $headers;

/*
From: Matthew Purdon <matthew@example.com>
Reply-To: Matthew Purdon <matthew@example.com>
Return-path: <matthew@example.com>
X-Mailer: PHP5.3.2
Content-Type: text/plain; charset="UTF-8"
*/
?>
arekandrei at yandex dot ru 03-Jan-2010 07:30
You can use lambda function as a second parameter:

<?php
array_walk($myArray, function(&$value, $key){
    // if you want to change array values then "&" before the $value is mandatory.
});
?>

Example (multiply positive values by two):

<?php
$myArray = array(1, 2, 3, 4, 5);

array_walk($myArray, function(&$value, $index){
    if ($value > 0) $value *= 2;
});
?>
rustamabd at gmail dot com 13-Dec-2009 06:32
Don't forget about the array_map() function, it may be easier to use!

Here's how to lower-case all elements in an array:

<?php
    $arr = array_map('strtolower', $arr);
?>
erelsgl at gmail dot com 04-Mar-2009 03:40
If you want to unset elements from the callback function, maybe what you really need is array_filter.
jab_creations_-at_-yahoo_-dot-_com 26-Nov-2008 04:08
Unfortunately I spent a lot of time trying to permanently apply the effects of a function to an array using the array_walk function when instead array_map was what I wanted. Here is a very simple though effective example for those who may be getting overly frustrated with this function...

<?php
$fruits = array("Lemony & Fresh","Orange Twist","Apple Juice");

print_r($fruits);
echo '<br />';

function name_base($key)
{
 $name2 = str_replace(" ", "_", $key);
 $name3 = str_replace("&", "and", $name2);
 $name4 = strtolower($name3);
 echo $name4.'<br />';
 return $name4;
}
echo '<br />';

$test = array_map('name_base', $fruits);
$fruits_fixed = $test;
echo '<br />';
print_r($fruits_fixed);
?>
peterzuzek AT gmail DOT com 16-Nov-2008 09:04
I had some problems using this function - it didn't want to apply PHP-defined functions. So I decided to write my own - here it is. I had to use some generic-programming skills, didn't really checked the speed (I think it could be slow)... I believe it could be much better, but I don't know, how - well, I guess multiple array support and recursion would be nice. So?

Prototype:
bool arrayWalk(array &$arry, callback $callback, mixed $params=false)

<?php

    function arrayWalk(&$arry, $callback, $params=false) {
        $P=array(""); // parameters
        $a=""; // arguement string :)

        if($params !== false) { // add parameters
            if(is_array($params)) { // multiple additional parameters
                foreach($params as $par)
                    { $P[]=$par; }
            }
            else // just one additional
                { $P[]=$params; }
        }

        for( // create the arguement string
            $i=0; isset($P[$i]); ++$i
        )
            { $a.='$'.chr($i + 97).', '; } // random argument names

        $a=substr($a, 0, -2); // to get rid of the last comma and two spaces

        $func=create_function($a, 'return '.$callback.'('.$a.');'); // the generic function

        if(is_callable($func)) {
            for( // cycle through array
                $i=0; isset($arry[$i]); ++$i
            ) {
                $P[0]=$arry[$i]; // first element must be the first argument - array value
                $arry[$i] = call_user_func_array($func, $P); // assign the new value obtained by the generic function
            }
        }
        else
            { return false; } // failure - function not callable

        return true; // success!
    } // arrayWalk()

?>

One big problem I've noticed so far - for example, if you wanted to use str_replace on the array, you'd fail - simply because of the arguement order of str_replace, where the string modified is the third arguement, not the first as arrayWalk requires.

So, still some work left...
diyism 30-Oct-2008 11:18
When i pass the third parameter by reference in php5.2.5,
happened this: Warning: Call-time pass-by-reference has been deprecated - argument passed by value...

And to set allow_call_time_pass_reference to true in php.ini won't work, according to http://bugs.php.net/bug.php?id=19699   thus to work around:

<?php
array_walk($arrChnOut, create_function('&$v, $k, $arr_rtn', 'if ($k{0}!="_") {$arr_rtn[0]["_".$v[\'ID\']]=$v; unset($arr_rtn[0][$k]);}'), array(&$arrChnOut));
?>
jerk at yoosic dot de 21-Dec-2006 08:05
if you want to modify every value of an multidimensional array use this function used here:

<?php

$array = array (1=>1, 2=> 2, 3 => array(1=>11, 2=>12, 3=>13));
$text = "test";

function modarr(&$array, $text) {
        foreach ($array as $key => $arr) {
                if(is_array($arr)) $res[$key] = modarr(&$arr,$text);
                // modification function here
                else $res[$key] = $arr.$text;
                }
        return $res;
}

$erg = modarr($array, $text);

print_r($erg);

?>

result will be_

<?php
Array ( [1] => 1test [2] => 2test [3] => Array ( [1] => 11test [2] => 12test [3] => 13test ) )
?>
ludvig dot ericson at gmail dot com 21-Nov-2005 06:09
In response to 'ibolmo', this is an extended version of string_walk, allowing to pass userdata (like array_walk) and to have the function edit the string in the same manner as array_walk allows, note now though that you have to pass a variable, since PHP cannot pass string literals by reference (logically).

<?php
function string_walk(&$string, $funcname, $userdata = null) {
    for($i = 0; $i < strlen($string); $i++) {
        # NOTE: PHP's dereference sucks, we have to do this.
        $hack = $string{$i};
        call_user_func($funcname, &$hack, $i, $userdata);
        $string{$i} = $hack;
    }
}

function yourFunc($value, $position) {
    echo $value . ' ';
}

function yourOtherFunc(&$value, $position) {
    $value = str_rot13($value);
}

# NOTE: We now need this ugly $x = hack.
string_walk($x = 'interesting', 'yourFunc');
// Ouput: i n t e r e s t i n g

string_walk($x = 'interesting', 'yourOtherFunc');
echo $x;
// Output: vagrerfgvat
?>

Also note that calling str_rot13() directly on $x would be much faster ;-) just a sample.
Andrzej Martynowicz at gmail dot com 18-Sep-2005 06:03
It can be very useful to pass the third (optional) parameter by reference while modifying it permanently in callback function. This will cause passing modified parameter to next iteration of array_walk(). The exaple below enumerates items in the array:

<?php
function enumerate( &$item1, $key, &$startNum ) {
   $item1 = $startNum++ ." $item1";
}

$num = 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', $num );

print_r( $fruits );

echo '$num is: '. $num ."\n";
?>

This outputs:

Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 1

Notice at the last line of output that outside of array_walk() the $num parameter has initial value of 1. This is because array_walk() does not take the third parameter by reference.. so what if we pass the reference as the optional parameter..

<?php
$num = 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', &$num ); // reference here

print_r( $fruits );

echo '$num is: '. $num ."\n";
echo "we've got ". ($num - 1) ." fruits in the basket!";
?>

This outputs:
Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 5
we've got 4 fruits in the basket!

Now $num has changed so we are able to count the items (without calling count() unnecessarily).

As a conclusion, using references with array_walk() can be powerful toy but this should be done carefully since modifying third parameter outside the array_walk() is not always what we want.
el_porno at web dot de 27-May-2005 03:03
You want to get rid of the whitespaces users add in your form fields...?
Simply use...:

class SomeVeryImportantClass
{
...
    public function mungeFormData(&$data)
    {
        array_walk($data, array($this, 'munge'));
    }

    private function munge(&$value, &$key)
    {
        if(is_array($value))
        {
            $this->mungeFormData($value);
        }
        else
        {
            $value = trim($value);
        }
    }
...
}

so...
$obj = new SomeVeryImportantClass;
$obj->mungeFormData($_POST);
___
eNc
Enlightened One 07-Apr-2005 11:17
Beware that "array ($this, method)" construct. If you're wanting to alter members of the "$this" object inside "method" you should construct the callback like this:

  $callback[] = &$this;
  $callback[] = method;
  array_walk ($input, $callback);

Creating your callback using the array() method as suggested by "appletalk" results in a copy of $this being passed to method, not the original object, therefor any changes made to the object by method will be lost when array_walk() returns. While you could construct the callback with "array(&$this, method)", I believe this relies on the deprecated runtime pass-by-reference mechanism which may be removed in future releases of PHP. Better to not create a dependence on that feature now than having to track it down and fix it in the future.
bisqwit at iki dot fi 03-Sep-2004 04:54
It's worth nothing that array_walk can not be used to change keys in the array.
The function may be defined as (&$value, $key) but not (&$value, &$key).
Even though PHP does not complain/warn, it does not modify the key.


Crea un array

  • « array_walk
  • arsort »
  • PHP Manual
  • Funciones de Arrays
  • Crea un array

array

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

array — Crea un array

Descripción

array ( mixed $... = ? ) : array

Crea un array. Leer la sección el tipo array para más información sobre que es un array.

Parámetros

...

Sintaxis "índice => valores", separados por comas, define índice y valores. El índice puede ser de tipo cadena o numérico. Cuando se omite el índice, se genera un índice numérico automáticamente, empezando por 0. Si el índice es numérico, el siguiente índice generado será el número del índice mayor +1. Nótese que cuando se crean dos índices idénticos, el último sobrescribe el primero.

Tener una coma al final de la última entrada definida en el array, aunque no es usual, sigue siendo sintaxis válida.

Valores devueltos

Devuelve un array de parámetros. Los parámetros puede ser devolver un índice con el operador =>. Leer la sección en El tipo array para más información en que es un array.

Ejemplos

El siguiente ejemplo demuestra como crear un array de dos dimensiones, como especificar claves para un array asociativo y como omitir y continuar índices numéricos en array normales.

Ejemplo #1 Ejemplo de array()

<?php
$fruits = array (
    "frutas"  => array("a" => "naranja", "b" => "plátano", "c" => "manzana"),
    "números" => array(1, 2, 3, 4, 5, 6),
    "hoyos"   => array("primero", 5 => "segundo", "tercero")
);
?>

Ejemplo #2 Array() con índice automático

<?php
$array = array(1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13);
print_r($array);
?>

El resultado del ejemplo sería:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

Nótese que el índice '3' se ha definido en dos ocasiones y mantiene su valor final de 13. El índice 4 se ha definido después del índice 8 y el siguiente índice generado (valor 19) es 9, ya que el índice mayor era 8.

Este ejemplo crea un array de base 1.

Ejemplo #3 array() con índice de base 1

<?php
$firstquarter = array(1 => 'Enero', 'Febrero', 'Marzo');
print_r($firstquarter);
?>

El resultado del ejemplo sería:

Array
(
    [1] => Enero
    [2] => Febrero
    [3] => Marzo
)

Como en perl, se puede acceder al valor del array dentro de comillas dobles. Sin embargo, con PHP se necesita adjuntar el array enter claves.

Ejemplo #4 Accessing an array inside double quotes

<?php

$foo = array('bar' => 'baz');
echo "Hola {$foo['bar']}!"; // Hola baz!

?>

Notas

Nota:

array() es un constructor de lenguaje para representar arrays y no es una función.

Ver también

  • array_pad() - Rellena un array a la longitud especificada con un valor
  • list() - Asignar variables como si fueran un array
  • count() - Cuenta todos los elementos de un array o algo de un objeto
  • range() - Crear un array que contiene un rango de elementos
  • foreach
  • El tipo array

User Contributed Notes

razvan_bc at yahoo dot com 18-May-2020 06:49
an array can execute code.
i try this on php 7.4 (xampp version)

<?php

[
     $msg='HI GUYS !'
    ,print ($msg)
    ,(function()use ($msg){
        print 'here is php';
    })()
    ,print ' I`m just an array ,alive one'
];

?>
ayyappan dot ashok at gmail dot com 18-Apr-2016 06:26
The code bellow by dave@wp.pl:

$var_name='var';
$var=array(0,1,2,3,4);
echo $$var_name[2];

//prints NOTHING instead 2.
// prints 2 with PHP version 7.01 onwards

Note :
This results 2 with PHP version 7.01 onwards. Other versions throws a notice error
majkel 20-Apr-2015 09:13
During initialization php parses every value as expression. One can declare variables, do calculations, or even manipulate "current" array

<?php

$arr['A'] = [
    &$arr, // circular reference
    'key' => 'val',
    $arr['B'] = [ // declare array, insert key and then value
        'a' => 'b',
    ],
    ucfirst(strtolower('SOME TEXT')),
    true ? 'TRUE' : 'FALSE', // evaluate expression
    $x  = 3, // declare variable
    $x *= 3, // perform calculations
];

var_dump($arr);

// Output
/*
array(2) {
  'B' => array(1) {
    'a' => string(1) "b"
  }
  'A' => array(7) {
    [0] => array(2) {
      'B' => array(1) {
        ...
      }
      'A' => &array
    }
    'key' => string(3) "val"
    [1] => array(1) {
      'a' => string(1) "b"
    }
    [2] => string(9) "Some text"
    [3] => string(4) "TRUE"
    [4] => int(3)
    [5] => int(9)
  }
}
*/
?>
dave at wp dot pl 27-Feb-2015 03:55
The code bellow:

$var_name='var';
$var=array(0,1,2,3,4);
echo $$var_name[2];

prints NOTHING instead 2.
ole dot aanensen at gmail dot com 10-Jun-2014 08:13
As of PHP 5.4.x you can now use 'short syntax arrays' which eliminates the need of this function.

Example #1 'short syntax array'
<?php
    $a = [1, 2, 3, 4];
    print_r($a);
?>

The above example will output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Example #2 'short syntax associative array'
<?php
    $a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];
    print_r($a);
?>

The above example will output:
Array
(
    [one] => 1
    [two] => 2
    [three] => 3
    [four] => 4
)
sergei dot solomonov at gmail dot com 02-Oct-2013 08:53
Consider:
file inc1.php
-------------
<?php
return 'key';

file inc2.php
-------------
<?php
return 'value';

Test:
<?php
$a = [
    include 'inc1.php' => include 'inc2.php'
];
var_dump($a);

/* It works!!!
array(1) {
  'key' =>
  string(5) "value"
}
*/
qeremy 07-Mar-2012 02:50
Some tricky functions;

<?php
function is_array_assoc($arr) {
    if (is_array($arr)) {
        foreach ($arr as $k => $v) {
            if (is_string($k) || (is_int($k) && $k < 0)) {
                return 1;
            }
        }
        return 0;
    }
    return -1;
}

function is_array_multi($arr) {
    return is_array($arr)
        ? (count($arr) != count($arr, COUNT_RECURSIVE) ? 1 : 0)
        : -1;
}

$arr[] = array("foo", "bar", 1.09);
$arr[] = array("red", "yellow", 1 => "foo");
$arr[] = array("red", "yellow", -1 => "foo");
$arr[] = array("x" => array("red", "yellow"), "y" => array("one", "two"));
$arr[] = array();
$arr[] = "s";

foreach ($arr as $a) {
    echo is_array_assoc($a) ."\n";
}
echo "\n";
foreach ($arr as $a) {
    echo is_array_multi($a) ."\n";
}
?>

0
0
1
1
0
-1

0
0
0
1
0
-1

<?php
function array_count($arr) {
    $r = 0;
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $r++;
        }
    }
    return $r;
}

function array_count_all($arr, $r = 0) {
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $r = array_count_all($v, $r);
            $r++;
        }
    }
    return $r;
}

$a = array("foo", "bar", 1.09, array(1,2,3), array("a" => "aaa"));
echo array_count($a); // 2

$a = array(
    "foo", "bar", 1.09,
    "x" => array(1,2,3),
    array("a" => "aaa", "b" => array(), "c" => array(""), "d" => array("")),
    "e" => array(""),
    "z" => array(""),
    "q" => array("", array()),
    "w" => array("lorem", 1 => "impsum", 18, "dolor", array("last as 11th array"))
);
echo array_count_all($a); // 11
?>
r0h4rd at gmail dot com 06-Feb-2011 02:59
"Quick and dirty" class to get an offset of multidimensional array by given path (sorry, that without comments).

<?php

    class ArrayAsPathException extends Exception {}

    class ArrayAsPath {
        protected
            $data = array(),
            $separator = '.';

        public function __construct (array $data = array()) {
            $this->data = $data;
        }

        public function set ($value, $path = null) {
            if (!isset($path)) {
                $this->data = $value;
            }

            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            $code = '';
            $pices = '[\''.$pathtoken.'\']';
            while ($pathtoken !== false) {
                if (($pathtoken = strtok($separator)) !== false) {
                    $code .= 'if (!isset($this->data'.$pices.')) $this->data'.$pices.' = array(); ';
                    $pices .= '[\''.$pathtoken.'\']';
                } else {
                    $code .= 'return $this->data'.$pices.' = $value;';
                }
            }

            return eval($code);
        }

        public function get ($path = '', $default = null) {
            $result = $this->data;
            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            while ($pathtoken !== false) {
                if (!isset($result[$pathtoken]) || is_string($result)) {
                    if (isset($default)) {
                        return $default;
                    }

                    throw new ArrayAsPathException ('Can\'t find "'.$pathtoken.'" in "'.$path.'"');
                }

                $result = $result[$pathtoken];
                $pathtoken = strtok($separator);
            }

            return $result ? $result : $default;
        }

        public function has ($path) {
            $result = $this->data;
            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            while ($pathtoken !== false) {
                if (!isset($result[$pathtoken]) || is_string($result)) {
                    return false;
                }

                $result = $result[$pathtoken];
                $pathtoken = strtok($separator);
            }

            return true;
        }

        public function setSepatator ($separator) {
            $this->separator = $separator;
        }

        public function getSeparator ($separator) {
            return $this->separator;
        }
    }

?>

Code:
<?php

    $params = new ArrayAsPath;
    $params->set(array(
        'foo' => array(
            'bar' => array(
                'item' => 'Value'
            )
        )
    ));

    try {
        $params->set('test', 'foo.bar.far.new');
        printf(
            'Array:<pre>%s</pre>
            foo.bar.item:<pre>%s</pre>
            foo.bar.far:<pre>%s</pre>
            foo.bar.far.new<pre>%s</pre>',
            var_export($params->get(), true),
            var_export($params->get('foo.bar.item'), true),
            var_export($params->get('foo.bar.far'), true),
            var_export($params->get('foo.bar.far.new'), true)
        );
    } catch (ArrayAsPathException $e) {
        echo 'Oops! It seems that something is wrong. '.$e->getMessage();
    }

?>

Will display:
Array:
array (
  'foo' =>
  array (
    'bar' =>
    array (
      'item' => 'Value',
      'far' =>
      array (
        'new' => 'test',
      ),
    ),
  ),
)

foo.bar.item:
'Value'

foo.bar.far:
array (
  'new' => 'test',
)

foo.bar.far.new:
'test'
eugene at ultimatecms dot co dot za 03-Mar-2010 06:29
This is a useful way to get foreign key variables from a specific sql table.
This function can be used to include all relevant data from all relating tables:

<?php
function get_string_between($string, $start, $end){
         $string = " ".$string;
         $ini = strpos($string,$start);
         if($ini == 0)
                return $tbl;
         $ini += strlen($start);
         $len = strpos($string,$end,$ini) - $ini;
         return substr($string,$ini,$len);
}

function get_foreign_keys($tbl) {
        $query = query_getrow("SHOW CREATE TABLE ".mysql_escape_string($tbl));

        $dat = explode('CONSTRAINT',$query[1]);
        foreach($dat as $d => $a) {
                if(strpos($a,"FOREIGN KEY"))
                $data['keys'][] = array($tbl,get_string_between($a,"` FOREIGN KEY (`","`) REFERENCES"));
        }

        foreach($dat as $d => $a) {
                if(strpos($a,"REFERENCE"))
                $data['references'][] = explode('` (`',get_string_between($a,"REFERENCES `","`) ON"));
        }
        return $data;
}

//Example code:

        $data = get_foreign_keys('task_table');
        echo '<pre>';
        print_r($data);
        echo '</pre>';

?>

// $query[1] outputs:

CREATE TABLE `task_table` (
  `task_id` int(64) NOT NULL auto_increment,
  `ticket_id` int(64) NOT NULL,
  `task_type` varchar(64) NOT NULL,
  `comment` text,
  `assigned_to` int(11) default NULL,
  `dependant` int(64) default NULL,
  `resolved` int(1) default NULL,
  PRIMARY KEY  (`task_id`),
  KEY `ticket_id` (`ticket_id`,`dependant`),
  KEY `assigned_to` (`assigned_to`),
  KEY `task_dependant` (`dependant`),
  CONSTRAINT `task_table_ibfk_1` FOREIGN KEY (`ticket_id`) REFERENCES `tickets_table` (`ticket_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `task_table_ibfk_2` FOREIGN KEY (`assigned_to`) REFERENCES `contact_table` (`contact_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `task_table_ibfk_3` FOREIGN KEY (`dependant`) REFERENCES `task_table` (`task_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1

// $data outputs:
Array (
    [keys] => Array
        (
            [0] => Array
                (
                    [0] => task_table
                    [1] => ticket_id
                )

            [1] => Array
                (
                    [0] => task_table
                    [1] => assigned_to
                )

            [2] => Array
                (
                    [0] => task_table
                    [1] => dependant
                )
        )

    [references] => Array
        (
            [0] => Array
                (
                    [0] => tickets_table
                    [1] => ticket_id
                )

            [1] => Array
                (
                    [0] => contact_table
                    [1] => contact_id
                )

            [2] => Array
                (
                    [0] => task_table
                    [1] => task_id
                )
        )
)
kamil at navikam dot pl 03-Jun-2009 03:42
Easy function to unarray an array :-)
It will make $array['something'] => $something.
Usefull for making code more clear.

example of use:
<?
function unarray($row) {
    foreach($row as $key => $value) {
        global $$key;
        $$key = $value;
    }
}

$sql = mysql_query("SELECT * FROM `pracownicy`");
while ($row = mysql_fetch_assoc($sql)) {
    unarray($row);
    echo $idpracownika.'<br>'; //instead of $row['idpracownika']
}
?>
Marcel G 27-Apr-2009 03:49
I encountered the following but didn't see it documented/reported anywhere so I'll just mentioned it here.

As written in the manual:
"When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1".

This generated index has always the largest integer used as a key so far. So adding $a[5] = 'foo'; after an $a[10] = 'bar'; will not force the next generated index to be 6 but to be 11 as 10 was the highest index encountered until here.

Anyway, the following can happen:
<?php
$max_int = 2147483647; // Max value for integer on a 32-bit system
$arr = array();

$arr[1] = 'foo'; // New generated index will be 2
$arr[ $max_int ] = 'bar'; // Caution: Next generated index will be -2147483648 due to the integer overflow!
$arr[0] = 'bar'; // The highest value should be 2147483648 but due to the i-overflow it is -2147483648 so current index 0 is larger. The new generated index therefore is 1!
$arr[]  = 'failure'; // Warning: Cannot add element to the array as the next element is already occupied.
?>
jonberglund at gmail dot com 07-Jul-2008 09:25
The following function (similar to one above) will render an array as a series of HTML select options (i.e. "<option>...</option>"). The problem with the one before is that there was no way to handle <optgroup>, so this function solves that issue.

function arrayToSelect($option, $selected = '', $optgroup = NULL)
{
    $returnStatement = '';

    if ($selected == '') {
        $returnStatement .= '<option value="" selected="selected">Select one...</option>';
    }

    if (isset($optgroup)) {
        foreach ($optgroup as $optgroupKey => $optgroupValue) {
            $returnStatement .= '<optgroup label="' . $optgroupValue . '">';

            foreach ($option[$optgroupKey] as $optionKey => $optionValue) {
                if ($optionKey == $selected) {
                    $returnStatement .= '<option selected="selected" value="' . $optionKey . '">' . $optionValue . '</option>';
                } else {
                    $returnStatement .= '<option value="' . $optionKey . '">' . $optionValue . '</option>';
                }
            }

            $returnStatement .= '</optgroup>';
        }
    } else {
        foreach ($option as $key => $value) {
            if ($key == $selected) {
                $returnStatement .= '<option selected="selected" value="' . $key . '">' . $value . '</option>';
            } else {
                $returnStatement .= '<option value="' . $key . '">' . $value . '</option>';
            }
        }
    }

    return $returnStatement;
}

 So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an <optgroup> label. So, with this function, if only a single array is passed to the function (i.e. "arrayToSelect($stateList)") then it will simply spit out a bunch of "<option>" elements. On the other hand, if two arrays are passed to it, the second array becomes a "key" for translating the first array.

Here's a further example:

$countryList = array(
    'CA'        => 'Canada',
    'US'        => 'United States');

$stateList['CA'] = array(
    'AB'        => 'Alberta',
    'BC'        => 'British Columbia',
    'AB'        => 'Alberta',
    'BC'        => 'British Columbia',
    'MB'        => 'Manitoba',
    'NB'        => 'New Brunswick',
    'NL'        => 'Newfoundland/Labrador',
    'NS'        => 'Nova Scotia',
    'NT'        => 'Northwest Territories',
    'NU'        => 'Nunavut',
    'ON'        => 'Ontario',
    'PE'        => 'Prince Edward Island',
    'QC'        => 'Quebec',
    'SK'        => 'Saskatchewan',
    'YT'        => 'Yukon');

$stateList['US'] = array(
    'AL'        => 'Alabama',
    'AK'        => 'Alaska',
    'AZ'        => 'Arizona',
    'AR'        => 'Arkansas',
    'CA'        => 'California',
    'CO'        => 'Colorado',
    'CT'        => 'Connecticut',
    'DE'        => 'Delaware',
    'DC'        => 'District of Columbia',
    'FL'        => 'Florida',
    'GA'        => 'Georgia',
    'HI'        => 'Hawaii',
    'ID'        => 'Idaho',
    'IL'        => 'Illinois',
    'IN'        => 'Indiana',
    'IA'        => 'Iowa',
    'KS'        => 'Kansas',
    'KY'        => 'Kentucky',
    'LA'        => 'Louisiana',
    'ME'        => 'Maine',
    'MD'        => 'Maryland',
    'MA'        => 'Massachusetts',
    'MI'        => 'Michigan',
    'MN'        => 'Minnesota',
    'MS'        => 'Mississippi',
    'MO'        => 'Missouri',
    'MT'        => 'Montana',
    'NE'        => 'Nebraska',
    'NV'        => 'Nevada',
    'NH'        => 'New Hampshire',
    'NJ'        => 'New Jersey',
    'NM'        => 'New Mexico',
    'NY'        => 'New York',
    'NC'        => 'North Carolina',
    'ND'        => 'North Dakota',
    'OH'        => 'Ohio',
    'OK'        => 'Oklahoma',
    'OR'        => 'Oregon',
    'PA'        => 'Pennsylvania',
    'RI'        => 'Rhode Island',
    'SC'        => 'South Carolina',
    'SD'        => 'South Dakota',
    'TN'        => 'Tennessee',
    'TX'        => 'Texas',
    'UT'        => 'Utah',
    'VT'        => 'Vermont',
    'VA'        => 'Virginia',
    'WA'        => 'Washington',
    'WV'        => 'West Virginia',
    'WI'        => 'Wisconsin',
    'WY'        => 'Wyoming');

...

<select name="state" id="state"><?php echo arrayToSelect($stateList,'',$countryList) ?></select>
<select name="country" id="country"><?php echo arrayToSelect($countryList,'US') ?></select>
sebasg37 at gmail dot com 12-Feb-2008 11:32
Recursive function similar to print_r for describing anidated arrays in html <ol>. Maybe it's useful for someone.

<?php
function describeAnidatedArray($array)
{
    $buf = '';
    foreach($array as $key => $value)
    {
        if(is_array($value))
        {
            $buf .= '<ol>' . describeAnidatedArray($value) . '</ol>';
        }
        else
            $buf .= "<li>$value</li>";
    }
    return $buf;
}

// Example:
$array = array("a", "b", "c", array("1", "2", array("A", "B")), array("3", "4"), "d");

echo describeAnidatedArray($array);
?>

output:

# a
# b
# c

   1. 1
   2. 2
         1. A
         2. B

   1. 3
   2. 4

# d
jon hohle 16-Nov-2007 05:12
Here are shorter versions of sam barrow's functions. From a PHP perspective these are O(1) (without getting into what's going on in the interpreter), instead of O(n).

<?php
function randomKey(array $array)
{
    return randomElement(array_keys($array));
}

function randomElement(array $array)
{
    if (count($array) === 0)
    {
        trigger_error('Array is empty.',  E_USER_WARNING);
        return null;
    }

    $rand = mt_rand(0, count($array) - 1);
    $array_keys = array_keys($array);

    return $array[$array_keys[$rand]];
}
?>
Mike Mackintosh 29-Oct-2007 09:38
If you need to add an object as an array key, for example an object from Simple XML Parser, you can use the following.

File.XML
<?xml version="1.0" encoding="UTF-8"?>
<Settings type="General">
  <Setting name="SettingName">This This This</Setting>
</Settings>

The script:
<?php
$raw = $xml =  new SimpleXMLElement('File.XML');
foreach($raw->Setting as $A => $B)
{
    // Set Array From XML
    $Setting[(string) $B['name']] = (string)  $B[0];
}
?>
By telling the key to read the object as a string, it will let you set it.

Hope this helps someone out!
webmaster at phpemailformprocessor dot com 06-Aug-2006 09:48
When using an array to create a list of keys and values for a select box generator which will consist of states I found using "NULL" as an index and ""(empty value) as a value to be useful:

<?php

$states = array(
    0    => 'Select a State',
    NULL => '',
    1    => 'AL - Alabama',
    2    => 'AK - Alaska',
    # And so on ...
);

$select = '<select name="state" id="state" size="1">'."\r\n";

foreach($states as $key => $value){
    $select .= "\t".'<option value="'.$key.'">' . $value.'</option>'."\r\n";
}

$select .= '</select>';

echo $select;

?>

 This will print out:

<select name="state" id="state" size="1">
    <option value="0">Select a State</option>
    <option value=""></option>
    <option value="1">AL - Alabama</option>
    <option value="2">AK - Alaska</option>
    # And so on ...

</select>

Now a user has a blank value to select if they later decide to not provide their address in the form. The first two options will return TRUE when checked against the php function - EMPTY() after the form is submitted when processing the form
jupiter at nospam dot com 02-Jun-2006 03:33
<?php

// changes any combination of multiarray elements and subarrays
// into a consistent 2nd level multiarray, tries to preserves keys
function changeMultiarrayStructure($multiarray, $asc = 1) {
  if ($asc == 1) {  // use first subarrays for new keys of arrays
    $multiarraykeys = array_reverse($multiarray, true);
  } else {  // use the last array keys
    $multiarraykeys = $multiarray;  // use last subarray keys
  }  // end array reordering
  $newarraykeys = array();  // establish array
  foreach ($multiarraykeys as $arrayvalue) {  // build new array keys
    if (is_array($arrayvalue)) {  // is subarray an array
      $newarraykeys = array_keys($arrayvalue) + $newarraykeys;
    }  // if count(prevsubarray)>count(currentarray), extras survive
  }  // end key building loop
  foreach ($multiarray as $newsubarraykey => $arrayvalue) {
    if (is_array($arrayvalue)) {  // multiarray element is an array
      $i = 0;  // start counter for subarray key
      foreach ($arrayvalue as $subarrayvalue) {  // access subarray
        $newmultiarray[$newarraykeys[$i]][$newsubarraykey] = $subarrayvalue;
        $i++;  // increase counter
      }  // end subarray loop
    } else {  // multiarray element is a value
      foreach ($newarraykeys as $newarraykey) {  // new subarray keys
        $newmultiarray[$newarraykey][$newsubarraykey] = $arrayvalue;
      }  // end loop for array variables
    }  // end conditional
  }  // end new multiarray building loop
  return $newmultiarray;
}

// will change
$old = array('a'=>1,'b'=>array('e'=>2,'f'=>3),'c'=>array('g'=>4),'d'=>5);
// to
$new = array('e'=>array('a'=>1,'b'=>2,'c'=>4,'d'=>5),
  'f'=>array('a'=>1,'b'=>3,'d'=>5));

// note: if $asc parameter isn't default, last subarray keys used

?>

The new key/value assignment pattern is clearer with bigger arrays.
I use this to manipulate input/output data from my db. Enjoy.
bill at carneyco dot com 02-Feb-2006 08:42
I wanted to be able to control the flow of data in a loop instead of just building tables with it or having to write 500 select statements for single line items. This is what I came up with thanks to the help of my PHP brother in FL. Hope someone else gets some use out it.
<?

//set array variable
$results = array();

//talk to the db
$query = "SELECT * FROM yourtable";
$result = mysql_query($query) or die(mysql_error());

//count the rows and fields
$totalRows = mysql_num_rows($result);
$totalFields = mysql_num_fields($result);

//start the loop
for ( $i = 0; $i < $totalRows; ++$i ) {

//make it 2 dim in case you change your order
  $results[$i] = mysql_fetch_array($result);

//call data at will controlling the loop with the array
echo $results[your_row_id]['your_field_name']; }

//print the entire array to see what lives where
print_r($results);  ?>
php 07-Jan-2006 03:30
This function converts chunks of a string in an array:

function array_str($str, $len) {
  $newstr = '';
  for($i = 0; $i < strlen($str); $i++) {
    $newstr .= substr($str, $i, $len);
  }
  return $newstr;
}

use it as:

$str = "abcdefghilmn";
echo "<table width=\"100%\">\n";
foreach(array_str($str, 4) as $chunk) {
  echo "<tr><td>".$chunk."</td></tr>\n";
}
echo "</table>";

this prints:

------
abcd
------
efgh
------
ilmn
------

It don't use regular expressions. Please add this function to php :)
matthiasDELETETHIS at ansorgs dot de 31-May-2005 02:52
How to use array() to create an array of references rather than of copies? (Especially needed when dealing with objects.) I played around somewhat and found a solution: place & before the parameters of array() that shall be references. My PHP version is 4.3.10.

Demonstration:

<?php
$ref1 = 'unchanged';
$ref2 = & $ref1;

$array_of_copies = array($ref1, $ref2);
print_r($array_of_copies); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_copies[0] = 'changed'; // $ref1 = 'changed'; is not equivalent, as it was _copied_ to the array
print_r($array_of_copies); // prints: Array ( [0] => changed [1] => unchanged )

$array_of_refs = array(& $ref1, & $ref2); // the difference: place & before arguments
print_r($array_of_refs); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_refs[0] = 'changed'; // $ref1 = 'changed'; is equivalent as $array_of_refs[0] references $ref1
print_r($array_of_refs, true); // prints: Array ( [0] => changed [1] => changed )
?>
aissatya at yahoo dot com 16-May-2005 01:48
<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
<?php
$fruits = array (
   "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
   "numbers" => array(1, 2, 3, 4, 5, 6),
   "holes"  => array("first", 5 => "second", "third")
);
?>
brian at blueeye dot us 21-Apr-2005 05:34
If you need, for some reason, to create variable Multi-Dimensional Arrays, here's a quick function that will allow you to have any number of sub elements without knowing how many elements there will be ahead of time. Note that this will overwrite an existing array value of the same path.

<?php
// set_element(array path, mixed value)
function set_element(&$path, $data) {
    return ($key = array_pop($path)) ? set_element($path, array($key=>$data)) : $data;
}
?>

For example:

<?php
echo "<pre>";
$path = array('base', 'category', 'subcategory', 'item');
$array = set_element($path, 'item_value');
print_r($array);
echo "</pre>";
?>

Will display:
Array
(
    [base] => Array
        (
            [category] => Array
                (
                    [subcategory] => Array
                        (
                            [item] => item_value
                        )
                )
        )
)
mortoray at ecircle-ag dot com 18-Feb-2005 05:35
Be careful if you need to use mixed types with a key of 0 in an array, as several distinct forms end up being the same key:

$a = array();
$a[null] = 1;
$a[0] = 2;
$a['0'] = 3;
$a["0"] = 4;
$a[false] = 5;
$a[0.0] = 6;
$a[''] = 7;
$a[] = 8;

print_r( $a );

This will print out only 3 values: 6, 7, 8.
rdude at fuzzelish dot com 17-Feb-2005 01:35
If you are creating an array with a large number of static items, you will find serious performance differences between using the array() function and the $array[] construct. For example:
<?
 // Slower method
 $my_array = array(1, 2, 3, ? 500);

 // Faster method
 $my_array[] = 1;
 $my_array[] = 2;
 $my_array[] = 3;
 ?
 $my_array[] = 500;
?>
phpm at nreynolds dot me dot uk 11-Jan-2005 08:24
This helper function creates a multi-dimensional array. For example, creating a three dimensional array measuring 10x20x30: <?php $my_array = multi_dim(10, 20, 30); ?>

<?php

function multi_dim()
{
    $fill_value = null;

    for ($arg_index = func_num_args() - 1; $arg_index >= 0; $arg_index--) {
        $dim_size = func_get_arg($arg_index);
        $fill_value = array_fill(0, $dim_size, $fill_value);
    }

    return $fill_value;
}

?>
baZz 16-Oct-2003 03:27
Chek this out!!!. Suppose that you want to create an array like the following:
<?php
  $arr1 = (
    0 => array ("customer"=>"Client 1","Item a"),
    1 => array ("customer"=>"Client 2","Item b")
  );
?>
Seems prety easy, but what if you want to generate it dinamically woops!!!.  Imagine that you have a file with thousands of lines and each line is a purchase order from diferent clients:
<?php
/*function to add elements*/
function addArray(&$array, $id, $var)
{
    $tempArray = array( $var => $id);
    $array = array_merge ($array, $tempArray);
}
/*The same as above but the element is an array*/
function addArrayArr(&$array, $var, &$array1)
{
    $tempArray = array($var => $array1);
    $array = array_merge ($array, $tempArray);
}
/*labels of our array or heders of the file*/
$keyarr = array("customer","item");
/*info that may you read from a file line 1 and 2*/
$valarr0 = array("Client 1","Item a");
$valarr1 = array("Client 2","Item b");

$numofrows = 2;/*In our case is just two lines*/
$tmpArray = array();
for($i = 0; $i < $numofrows; $i++){
  $tmp = "valarr$i";
  $tmpvar = ${$tmp};/*Using var of vars tricky tricky*/
  foreach( $keyarr as $key=>$value){
    addArray($tmparr,$tmpvar[$key],$value);
  }
  addArrayArr($finalarr,$i,$tmparr);
} /*voila all it's perfectly ordered on finalarr*/

/*Here we just print the info but you can insert it into a database*/
echo "Customer: ".$finalarr[0]["customer"]."<br>";
echo "Item: ".$finalarr[0]["item"]."<br>";
echo "Customer: ".$finalarr[1]["customer"]."<br>";
echo "Item: ".$finalarr[1]["item"]."<br>";
?>

The lines above should print something like:
Customer: Client 1
Item: Item a
Customer: Client 2
Item: Item b
I hope someone find this useful.
TCross1 at hotmail dot com 03-Sep-2003 12:38
here is the sort of "textbook" way to output the contents of an array which avoids using foreach() and allows you to index & iterate through the array as you see fit:

<?php

$arrayName = array("apples", "bananas", "oranges", "pears");
$arrayLength = count($arrayName);

for ($i = 0; $i < $arrayLength; $i++){
    echo "arrayName at[" . $i . "] is: [" .$arrayName[$i] . "]<br>\n";
}

?>

enjoy!

-tim
10-May-2003 03:53
Similarly to a comment by stlawson at sbcglobal dot net on this page:
http://www.php.net/basic-syntax.instruction-separation

It is usually advisable to define your arrays like this:
$array = array(
     'foo',
     'bar',
);

Note the comma after the last element - this is perfectly legal. Moreover,
it's best to add that last comma so that when you add new elements to the
array, you don't have to worry about adding a comma after what used to be
the last element.

<?php
$array = array(
     'foo',
     'bar',
     'baz',
);
?>
marcel at labor-club dot de 24-Feb-2003 07:58
i tried to find a way to create BIG multidimensional-arrays. but the notes below only show the usage of it, or the creation of small arrays like $matrix=array('birne', 'apfel', 'beere');

for an online game, i use a big array (50x80) elements.
it's no fun, to write the declaration of it in the ordinary way.

here's my solution, to create an 2d-array, filled for example with raising numbers.

<?php
$matrix=array();
$sx=30;
$sy=40;
$i=1;
for ($y=0; $y<$sy; $y++)
{
    array_push($matrix,array());
    for ($x=0; $x<$sx; $x++)
    {
        array_push($matrix[$y],array());
        $matrix[$x][$y]=$i;
        $i++;
    }
}
?>

if there is a better way, plz send an email. i always want to learn more php!
MadLogic at Paradise dot net dot nz 31-Oct-2002 02:39
Heres a simple yet intelligent way of setting an array, grabbing the values from the array using a loop.

<?php
$ary = array("1"=>'One','Two',"3"=>'Three');
$a = '0'; $b = count($ary);
while ($a <= $b) {
  $pr = $ary[$a];
  print "$pr<br>";
  $a++;
}
?>
mads at __nospam__westermann dot dk 23-Oct-2002 07:39
In PHP 4.2.3 (and maybe earlier versions) arrays with numeric indexes may be initialized to start at a specific index and then automatically increment the index. This will save you having to write the index in front of every element for arrays that are not zero-based.

The code:

<?php
                  $a = array
        (
            21    => 1,
            2,
            3,
        );
    print '<pre>';
    print_r($a);
    print '</pre>';
?>

will print:

<?php
Array
(
    [21] => 1
    [22] => 2
    [23] => 3
)
?>
John 18-Jul-2002 11:48
Be careful not to create an array on top of an already existing variable:

<?php
$name = "John";
$name['last'] = "Doe";
?>

$name becomes "Dohn" since 'last' evaluates to the 0th position of $name.
Same is true for multi-arrays.
jay at ezlasvegas dot net 20-Apr-2002 04:21
If you want to create an array of a set size and you have PHP4, use
array_pad(array(), $SIZE, $INITIAL_VALUE); This can be handy if you wish
to initialize a bunch of variables at once:

list($Var1, $Var2, etc) = array_pad(array(), $NUMBER_OF_VARS,
$INITIAL_VALUE);

Jay Walker
Las Vegas Hotel Associate
http://www.ezlasvegas.net
jjm152 at hotmail dot com 10-Mar-2002 06:22
The easiest way to "list" the values of either a normal 1 list array or a multi dimensional array is to use a foreach() clause.

Example for 1 dim array:

<?php
   $arr = array( 1, 2, 3, 4, 5 );
   foreach ( $arr as $val ) {
       echo "Value: $Val\n";
      }
?>

For multi dim array:

<?php
     $arr = array( 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four, 5 => 'five');
      foreach ( $arr as $key => $value ) {
       echo "Key: $key, Value: $value\n";
      }
?>

This is quite possibly the easiest way i've found to iterate through an array.
tobiasquinteiro at ig dot com dot br 29-Jan-2002 12:25
<?
        // This is a small script that shows how to use an multiple array
        for($x = 0;$x < 10;$x++){
                for($y = 0;$y < 10;$y++){
                        $mat[$x][$y] = "$x,$y";
                }
        }

        for($x = 0;$x < count($mat);$x++){
                for($y = 0;$y < count($mat[$x]);$y++){
                        echo    "mat[$x][$y]: " .
                                $mat[$x][$y] . " ";
                }
                echo "\n";
        }
?>
joshua dot e at usa dot net 24-May-2001 11:12
Here's a cool tip for working with associative arrays-
Here's what I was trying to accomplish:

I wanted to hit a DB, and load the results into an associative array, since I only had key/value pairs returned. I loaded them into an array, because I wanted to manipulate the data further after the DB select, but I didn't want to hit the DB more than necessary.

Here's how I did it:

<?php
//assume db connectivity
//load it all into the associative array
$sql = "SELECT key,value FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)) {
$myArray[$row[0]] = $row[1];
}
//now we expand it
while(list($key,$value) = each($myArray)) {
echo "$key : $value";
}
?>

I found this to be super efficient, and extremely cool.
slicky at newshelix dot com 20-Mar-2001 01:57
Notice that you can also add arrays to other arrays with the $array[] "operator" while the dimension doesn't matter.

Here's an example:
$x[w][x] = $y[y][z];
this will give you a 4dimensional assosiative array.
$x[][] = $y[][];
this will give you a 4dimensional non assosiative array.

So let me come to the point. This get interessting for shortening things up. For instance:

<?php
        foreach ($lines as $line){
            if(!trim($line)) continue;
            $tds[] = explode("$delimiter",$line);
        }
?>
rubein at earthlink dot net 26-Sep-2000 11:07
Multidimensional arrays are actually single-dimensional arrays nested inside other single-dimensional arrays.

$array[0] refers to element 0 of $array
$array[0][2] refers to element 2 of element 0 of $array.

If an array was initialized like this:

$array[0] = "foo";
$array[1][0] = "bar";
$array[1][1] = "baz";
$array[1][2] = "bam";

then:
is_array($array) = TRUE
is_array($array[0]) = FALSE
is_array($array[1]) = TRUE
count($array) = 2 (elements 0 and 1)
count($array[1] = 3 (elements 0 thru 2)

This can be really useful if you want to return a list of arrays that were stored in a file or something:

$array[0] = unserialize($somedata);
$array[1] = unserialize($someotherdata);

if $somedata["foo"] = 42 before it was serialized previously, you'd now have this:
$array[0]["foo"] = 42


Ordena un array en orden inverso y mantiene la asociación de índices

  • « array
  • asort »
  • PHP Manual
  • Funciones de Arrays
  • Ordena un array en orden inverso y mantiene la asociación de índices

arsort

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

arsort — Ordena un array en orden inverso y mantiene la asociación de índices

Descripción

arsort ( array &$array , int $sort_flags = SORT_REGULAR ) : bool

Esta función ordena un array de manera que los índices del array mantienen su correlación con los elementos del array asociados.

Es usado principalmente cuando se ordenan arrays asociativos cuando el orden de los elementos es importante.

Nota:

Si dos miembros se comparan como iguales, su orden relativo en el array oredenado será indefinido.

Parámetros

array

El array de entrada.

sort_flags

Se puede modificar el comportamiento del ordenado usando el parámetro opcional sort_flags, par más información vea sort().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de arsort()

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

El resultado del ejemplo sería:

a = orange
d = lemon
b = banana
c = apple

Las frutas han sido ordenadas en orden inverso alfabético, se ha mantenido el índice asocidado con cada elemento.

Ver también

  • asort() - Ordena un array y mantiene la asociación de índices
  • comparación de funciones de orden de arrays

User Contributed Notes

stephenakins at gmail dot com 09-Jun-2017 01:25
I have two servers; one running 5.6 and another that is running 7.  Using this function on the two servers gets me different results when all of the values are the same.

<?php

$list = json_decode('{"706":2,"703":2,"702":2,"696":2,"658":2}', true);

print_r($list);

arsort($list);
echo "<br>";

print_r($list);

?>

PHP 5.6 results:
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )
Array ( [658] => 2 [696] => 2 [702] => 2 [703] => 2 [706] => 2 )

PHP 7 results:
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )
sebas2day 07-May-2012 02:52
If you are dealing with a multidimensional array you want to sort, then this might be helpfull:

<?php
function array_sort($arr){
    if(empty($arr)) return $arr;
    foreach($arr as $k => $a){
        if(!is_array($a)){
            arsort($arr); // could be any kind of sort
            return $arr;
        }else{
            $arr[$k] = array_sort($a);
        }
    }
    return $arr;
}
?>
FatBat 13-Oct-2011 01:40
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>
jordancdarwin at googlemail dot com 15-Dec-2007 02:21
A lot of people seem to trip up on this and ask me questions as to debugging. Bear in mind that this returns boolean, and does not return an array of affected items.

$array = array("One"=>1, "Three" => 3,"Two" =>2);
print_r(asort($array));

If successful, will return 1, and error if there is a string used. Useful to note so then people stop asking me :D
rodders_plonker at yahoo dot com 21-Aug-2000 06:43
I was having trouble with the arsort() function on an older version of PHP which was returning an error along the lines of 'wrong perameter count for function arsort' when I tried to use a flag for numeric sorting (2/SORT_NUMERIC).
I figured, as I only wanted to sort integers, I could pad numbers from the left to a specific length with 0's (using the lpad function provided by improv@magma.ca in the notes at http://www.php.net/manual/ref.strings.php).
A string sort then correctly sorts numerically (i.e. {30,2,10,21} becomes {030,021,010,002} not {30,21,2,10}) when echoing the number an (int)$string_name hides the leading 0's.

Made my day :).

Rodders.
morgan at anomalyinc dot com 24-Nov-1999 07:30
If you need to sort a multi-demension array, for example, an array such as

$TeamInfo[$TeamID]["WinRecord"]
$TeamInfo[$TeamID]["LossRecord"]
$TeamInfo[$TeamID]["TieRecord"]
$TeamInfo[$TeamID]["GoalDiff"]
$TeamInfo[$TeamID]["TeamPoints"]

and you have say, 100 teams here, and want to sort by "TeamPoints":

first, create your multi-dimensional array. Now, create another, single dimension array populated with the scores from the first array, and with indexes of corresponding team_id... ie
$foo[25] = 14
$foo[47] = 42
or whatever.
Now, asort or arsort the second array.
Since the array is now sorted by score or wins/losses or whatever you put in it, the indices are all hoopajooped.
If you just walk through the array, grabbing the index of each entry, (look at the asort example. that for loop does just that) then the index you get will point right back to one of the values of the multi-dimensional array.
Not sure if that's clear, but mail me if it isn't...
-mo


Ordena un array y mantiene la asociación de índices

  • « arsort
  • compact »
  • PHP Manual
  • Funciones de Arrays
  • Ordena un array y mantiene la asociación de índices

asort

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

asort — Ordena un array y mantiene la asociación de índices

Descripción

asort ( array &$array , int $sort_flags = SORT_REGULAR ) : bool

Esta función ordena un array manteniendo la correlación de los índices del array con los elementos con los que están asociados. Esta función se utiliza principalmente para ordenar arrays asociativos en los que el orden es importante.

Nota:

Si dos miembros se comparan como iguales, su orden relativo en el array oredenado será indefinido.

Parámetros

array

El array de entrada.

sort_flags

Quizá se necesita cambiar el comportamiento del ordenado usando este parámetro opcional sort_flags, para más información ver sort().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de la función asort()

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

El resultado del ejemplo sería:

c = apple
b = banana
d = lemon
a = orange

Las frutas han sido ordenadas alfabeticamente, y se ha mantenido el índice asociado con cada elemento.

Ver también

  • arsort() - Ordena un array en orden inverso y mantiene la asociación de índices
  • comparación de funciones de orden de arrays

User Contributed Notes

marty8zhang at gmail dot com 06-Oct-2020 04:26
"This function sorts an array such that array indices maintain their correlation with the array elements they are associated with."

Note this sentence in the description has a quite important implication especially when you're working with an originally non-indexed (or say integer-indexed) array and JSON encoding/decoding.
I'm not reporting this as a bug, because the end result does fit into the description.

<?php

$myArray = ['small_image', 'image'];
var_dump(json_encode($myArray)); // string(23) "["small_image","image"]"
var_dump(is_object($myArray)); // bool(false)

asort($myArray);
$myJson = json_encode($myArray);
var_dump($myJson); // string(31) "{"1":"image","0":"small_image"}"
var_dump(is_object($myArray)); // bool(false)

/*
 * class stdClass#1 (2) {
 *     public $1 =>
 *     string(5) "image"
 *     public $0 =>
 *     string(11) "small_image"
 * }
 */
var_dump(json_decode($myJson));

?>
Jesse K 31-Aug-2020 07:49
'asort' is fine for sorting arrays in English, but if accented characters exist in the array then it is better to use the 'asort' method of PHP's Collator class:
https://www.php.net/manual/en/class.collator.php

$collator = new \Collator('fr_CA');
$collator->asort($french_list);

There are options for using `setlocale()` to control `asort` behaviour, but it isn't reliable across systems.
For instance, in my development environment I only have access to the following locals:

$ locale -a
C
C.UTF-8
POSIX
elhanafi123 at gmail dot com 20-Sep-2018 09:47
I have written this function so its sort an multidimensional array with a specific key.

<?php
function sort_array($array, $sort_value, $reverse = false){
    $value = $result = array();

    foreach($array as $key => $rows){
        $value[$key] = strtolower($rows[$sort_value]);
    }

    if($reverse == true){
        arsort($value);
    }else{
        asort($value);
    }

    foreach($value as $keys => $null){
        $result[] = $array[$keys];
    }

    return $result;
}
?>

Examples

<?php

$array = array(array('a' => 'foo'), array('a' => 'foo4'), array('a' => 'foo2'), array('a' => 'foo3'));
print_r($array);
//Array ( [0] => Array ( [a] => foo ) [1] => Array ( [a] => foo4 ) [2] => Array ( [a] => foo2 ) [3] => Array ( [a] => foo3 ) )

print_r(sort_array($array, 'a'));
//Array ( [0] => Array ( [a] => foo ) [1] => Array ( [a] => foo2 ) [2] => Array ( [a] => foo3 ) [3] => Array ( [a] => foo4 ) )

print_r(sort_array($array, 'a', true));
//Array ( [0] => Array ( [a] => foo4 ) [1] => Array ( [a] => foo3 ) [2] => Array ( [a] => foo2 ) [3] => Array ( [a] => foo ) )

?>
aditycse at gmail dot com 07-Aug-2015 12:41
/*
 * Name : Aditya Mehrotra
 * Email: aditycse@gmail.com
 */
//Example for sorting by values for an alphanumeric array also having case-sensitive data
$exampleArray1 = $exampleArray2 = array(
    0 => 'example1',
    1 => 'Example10',
    2 => 'example12',
    3 => 'Example2',
    4 => 'example3',
    5 => 'EXAMPLE10',
    6 => 'example10'
);

//default sorting
asort($exampleArray1);

// alphanumeric with case-sensitive data sorting by values
asort($exampleArray2, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);

//output of defaut sorting
print_r($exampleArray1);
/*
 * output of default sorting
  Array
  (
  [5] => EXAMPLE10
  [1] => Example10
  [3] => Example2
  [0] => example1
  [6] => example10
  [2] => example12
  [4] => example3
  )
 */

print_r($exampleArray2);
/*
 * output of alphanumeric with case-sensitive data sorting by values
 Array
(
    [0] => example1
    [3] => Example2
    [4] => example3
    [5] => EXAMPLE10
    [1] => Example10
    [6] => example10
    [2] => example12
)
 */
stephen [ at ] brooksie-net [ dot ] co [ dot ] uk 01-Mar-2013 04:37
It is obviously necessary to log the keys used as so we don't overwrite previous entries in the array ;o)

N.B. this also effects the timings, but still faster than the alternatives :

     * int : 0.00159    (ms)
     * str : 0.00092    (ms)

<?php
private function _keySort(Array $data)
    {
        $keys = array();

        foreach($data as $row) {

            $keyIncrement =
                (!isset($keys[$row[$this->_orderField]]))
                    ? $keys[$row[$this->_orderField]] = 0
                    : ++$keys[$row[$this->_orderField]];

            $tempArray[$row[$this->_orderField].$keyIncrement] = $row;
        }

        if ($this->_orderDirection == 'DESC') {
            krsort($tempArray, SORT_NATURAL | SORT_FLAG_CASE );
        } else {
            ksort($tempArray, SORT_NATURAL | SORT_FLAG_CASE);
        }

        return $tempArray;

    }
?>
nick ([AT]) nickyost ([DOT]) com 15-Sep-2011 03:32
This function can be used to sort multidimensional arrays with almost no work whatsoever by using the individual values within the custom sort function.

This function passes the entire child element even if it is not a string. If it is an array, as would be the case in multidimensional arrays, it will pass the whole child array as one parameter.

Therefore, do something elegant like this:

<?php
     // Sort the multidimensional array
     usort($results, "custom_sort");
     // Define the custom sort function
     function custom_sort($a,$b) {
          return $a['some_sub_var']>$b['some_sub_var'];
     }
?>

This does in 4 lines what other functions took 40 to 50 lines to do. This does not require you to create temporary arrays or anything. This is, for me, a highly preferred solution.

Hope it helps!
Anon 06-May-2011 05:37
Case insensitive sort in one line:

<?php

array_multisort(array_map('strtolower', $array), $array);

?>
rick at toewsweb dot net 28-Apr-2011 04:40
On sorting by value first, then by key (cf., 2008-01-31 notes by mike at clear-link dot com):

What occurred to me to solve this problem was to extract the keys and values into separate arrays, then use array_multisort to get the desired order:

Ex:
<?php
$kvpairs = array('noun' => 'thought', 'animal' => 'fish', 'abstract' => 'thought', 'food' => 'fish', 'verb' => 'fish');
print "before:\n";
print_r($kvpairs);

// Essentially, one line of code is all that's needed for the sort:
array_multisort(array_values($kvpairs), array_keys($kvpairs), $kvpairs);

print "after:\n";
print_r($kvpairs);
?>

before:
Array
(
    [noun] => thought
    [animal] => fish
    [abstract] => thought
    [food] => fish
    [verb] => fish
)
after:
Array
(
    [animal] => fish
    [food] => fish
    [verb] => fish
    [abstract] => thought
    [noun] => thought
)

Of course, array_multisort allows you to specify sort order (SORT_ASC, SORT_DESC) and sort type (SORT_REGULAR, SORT_STRING, SORT_NUMERIC) for each array you pass it.
Eran 21-Apr-2009 05:15
i made this sample multi dimensional array sort to someone who needed to read lines from a text file instead of using sql - order by statement.

the idea is to take the key and sort(order) the specific column and then order the entire of the array as the selected column asort returned.

<?php
/**
 *
 * This sample is reading text data
 * and perform a sort to a 2 dimensional array
 * just like a normal sql do to "order by asc"
 *
 */

$foo = array();

/*
# SORT_REGULAR - compare items normally (don't change types)
# SORT_NUMERIC - compare items numerically
# SORT_STRING - compare items as strings
*/
$sort_by = SORT_REGULAR;

/*
# 0 - order by name column
# 1 - order by age column
# 2 - order by rank column
# 3 - order by color column
*/
$order_by = 1;

// source file
$line_of_text[1] = 'a1name|f2age|h3rank|jcolor';
$line_of_text[2] = 'b1name|d2age|i3rank|k4color';
$line_of_text[0] = 'c1name|e2age|g3rank|l4color';

// make array
for ($x=0; $x<=2; $x++)
{
    $line = explode('|',$line_of_text[$x]);

    // save it by coulmns otherwise it will saved like rows
    for ($i=0; $i<=3; $i++) {
          $foo[$i][$x] = $line[$i];
    }
}

// get the key order
$a = $foo[$order_by];

// sort
asort($a, $sort_by);

// start print
echo "<table cellpudding=0 cellspacing=0 border=1>\n";
        echo "<tr>\n";
          echo "<td>key</td>\n";
          echo "<td>name</td>\n";
          echo "<td>age</td>\n";
          echo "<td>rank</td>\n";
          echo "<td>color</td>\n";
        echo "</tr>\n";

// print by key order
foreach ($a as $k => $v) {
    echo "<tr>\n";
      echo "<td>$k</td>\n";
      // you can print here a for loop (0 to num of columns[=3])
      echo "<td>".$foo[0][$k]."</td>\n";
      echo "<td>".$foo[1][$k]."</td>\n";
      echo "<td>".$foo[2][$k]."</td>\n";
      echo "<td>".$foo[3][$k]."</td>\n";
    echo "</tr>\n";
}
echo "</table>\n";
?>
bakatamas at freemail dot hu 15-Feb-2008 02:34
Dear mike at clear-link dot com!

I needed a case insensitive version of your function. It is still not perfect as I have to do something with country specific characters (öüóoúéáuíÖÜÓOÚÉÁUÍ)

function akisort(&$array,$valrev=false,$keyrev=false)
    {
    if ($valrev)
        {
        arsort($array);
        }
        else
        {
        asort($array);
        };
    $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num)
        {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        $tmp2 = array();
        foreach($tmp as $key => $value)
            {
            $tmp2[] = $key;
            $number = $value;
            };
        natcasesort($tmp2);
        reset($tmp2);
        print_r($tmp2);
        unset($tmp);
        foreach($tmp2 as $key => $value)
            {
            $tmp[$value] = $number;
            };
        if($keyrev)
            {
            $tmp = array_reverse($tmp, true);
            };
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $i+$num;
        };
};
mike at clear-link dot com 31-Jan-2008 03:56
Small typo in the aksort function I just submitted. Here's the entire thing again, with the correction noted:

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if ($valrev) { arsort($array); } else { asort($array); }
  $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num) {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $i+$num;
        // Fixed from previous post: $i = $num;
    }
}
?>
mike at clear-link dot com 31-Jan-2008 03:23
For a recent project I needed to sort an associative array by value first, and then by key if a particular value appeared multiple times. I wrote this function to accomplish the task. Note that the parameters default to sort ascending on both keys and values, but allow granular control over each.

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if ($valrev) { arsort($array); } else { asort($array); }
    $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num) {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $num;
    }
}

// Example
$tmp = array('ca'=>1,'cb'=>2,'ce'=>1,'pa'=>2,'pe'=>1);

// Standard asort
asort($tmp);
print_r($tmp);

// Sort value ASC, key ASC
aksort($tmp);
print_r($tmp);

// Sort value DESC, key ASC
aksort($tmp,true);
print_r($tmp);

// Sort value DESC, key DESC
aksort($tmp,true,true);
print_r($tmp);

// Results
Array
(
    [pe] => 1
    [ca] => 1
    [ce] => 1
    [cb] => 2
    [pa] => 2
)
Array
(
    [ca] => 1
    [ce] => 1
    [pe] => 1
    [cb] => 2
    [pa] => 2
)
Array
(
    [cb] => 2
    [pa] => 2
    [ca] => 1
    [ce] => 1
    [pe] => 1
)
Array
(
    [pa] => 2
    [cb] => 2
    [pe] => 1
    [ce] => 1
    [ca] => 1
)
mzvarik at gmail dot com 16-Jan-2008 09:29
I noticed that my function mentioned earlier is very misleading - somebody please delete that note!

This is how you sort:
<?php
setlocale (LC_ALL, 'czech');
$array = array("a", "c", "c");
usort ($array, 'strcoll');
print_r($array);
?>
przemekkus [at] interia [dot] pl 02-Nov-2007 06:34
Function written by a dot brandon at chello dot nl has an error  - wrong variable name. It should be:

if($rev) arsort($named_hash,$flags=0) ;

instead of

if($reverse) arsort($named_hash,$flags=0) ;
a dot brandon at chello dot nl 25-Jun-2007 07:18
I use this for quasi-SQL orderby. Loosely based on smileaf. Any good for you nerds?

<?

function named_records_sort($named_recs, $order_by, $rev=false, $flags=0)
{// Create 1-dimensional named array with just
 // sortfield (in stead of record) values
    $named_hash = array();
     foreach($named_recs as $key=>$fields)
             $named_hash["$key"] = $fields[$order_by];

 // Order 1-dimensional array,
 // maintaining key-value relations
    if($reverse) arsort($named_hash,$flags=0) ;
    else asort($named_hash, $flags=0);

 // Create copy of named records array
 // in order of sortarray
    $sorted_records = array();
    foreach($named_hash as $key=>$val)
           $sorted_records["$key"]= $named_recs[$key];

return $sorted_records;} // named_recs_sort()

function show_sorted_records($named_recs, $order_by, $rev=false, $flags=0)
{$sorted_records=named_records_sort($named_recs, $order_by, $rev, $flags);
foreach($sorted_records as $name=>$fields)
  {echo "<b>$name</b>   ";
   foreach($fields as $field=>$val)
          echo "$field = $val "; echo "<br>";}
} // show_sorted_records()

$girl_friends=array();
$girl_friends["Anna"]=
array("born"=>'1989-08-22',"cupsize"=>'B-',"IQ"=>105, "daddy"=>'rich');
$girl_friends["Zoe"]
=array("born"=>'1978-03-11',"cupsize"=>'C#',"IQ"=>130, "daddy"=>'poor');
$girl_friends["Lilly"]
=array("born"=>'1985-06-16',"cupsize"=>'DD',"IQ"=>90, "daddy"=>'nasty');

$order_by="cupsize"; echo "And the winners are: <br>";
show_sorted_records($girl_friends, $order_by, true);

?>
gunnar at taljaren dot se 14-Jun-2007 01:00
for ($i=0;$i<5;$i++)
   $values[] = $i;
asort($values);

works, but
for ($i=0;$i<5;$i++)
   $values[$i] =$i;
asort($values);
doesn't!
smileaf at smileaf dot org 24-Jan-2007 06:34
Ok I was mistaken, after re-reading the previous post the ".$key" is important. What caused the sorting issue for me wasn't that at all. But rather something else.
doing an: asort($records, $flags); before returning fixes the sorting problems.
The sorting problem I was refearing to causes a character based sorting done on numeric data.
so instead of:
1
2
3
...
10
12
20
It was returned back as
1
10
12
2
20
3
...
basically what I was trying to fix in the first place.
richard at happymango dot me dot uk 23-Nov-2006 03:52
This is a fixed version of the same function I posted below. Now it will handle duplicate entries in the sorted field. EG: If there were two records that had the name Heathrow it would still work.

<?php

function record_sort($records, $field, $reverse=false)
{
    $hash = array();

    foreach($records as $key => $record)
    {
        $hash[$record[$field].$key] = $record;
    }

    ($reverse)? krsort($hash) : ksort($hash);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}

?>
richard at happymango dot me dot uk 22-Nov-2006 03:35
This is a function to sort an indexed 2D array by a specified sub array key, either ascending or descending.

It is usefull for sorting query results from a database by a particular field after the query has been returned

This function can be quite greedy. It recreates the array as a hash to use ksort() then back again

By default it will sort ascending but if you specify $reverse as true it will return the records sorted descending

<?php

function record_sort($records, $field, $reverse=false)
{
    $hash = array();

    foreach($records as $record)
    {
        $hash[$record[$field]] = $record;
    }

    ($reverse)? krsort($hash) : ksort($hash);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}

// Example below

$airports = array
(
    array( "code" => "LHR", "name" => "Heathrow" ),
    array( "code" => "LGW", "name" => "Gatwick" ),
);

printf("Before: <pre>%s</pre>", print_r($airports, true));

$airports = record_sort($airports, "name");

printf("After: <pre>%s</pre>", print_r($airports, true));

?>

Example Outputs:

Before: Array
(
    [0] => Array ( [code] => LHR, [name] => Heathrow )
    [1] => Array ( [code] => LGW, [name] => Gatwick )
)

After: Array
(
    [0] => Array ( [code] => LGW, [name] => Gatwick )
    [1] => Array ( [code] => LHR, [name] => Heathrow )
)
php at web-in-time dot com 05-Sep-2006 02:47
acecream's function works fine, especially with the spectre extension.

nevertheless sometimes the index values have to be kept. To achieve this, just replace:

$sorted_arr[] = $array[$arr_key];

with:

$sorted_arr[$arr_key] = $array[$arr_key];
rojaro 23-Jun-2004 07:38
Advanced sort array by second index function, which produces ascending (default) or descending output and uses optionally natural case insensitive sorting (which can be optionally case sensitive as well).
Only the first two arguments are required.

<?php

function sabsi ($array, $index, $order='asc', $natsort=FALSE, $case_sensitive=FALSE) {
  if(is_array($array) && count($array)>0) {
    foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
    if(!$natsort) ($order=='asc')? asort($temp) : arsort($temp);
    else {
      ($case_sensitive)? natsort($temp) : natcasesort($temp);
      if($order!='asc') $temp=array_reverse($temp,TRUE);
    }
    foreach(array_keys($temp) as $key) (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
    return $sorted;
  }
  return $array;
}

?>
spectre at hellfish dot NOSPAM dot org 28-Apr-2003 09:54
that works nicely, tho it breaks the result-array up if one or more of arrays indexes are deleted before sorting. this one should fix it up:

change:
for ($i = 0; $i < sizeof($array); $i++) {

to:
foreach ($array as $i => $k) {
mbevan at marginsoftware dot com 03-Dec-2002 01:25
Nevermind... use my last note as a quick tip: if you wish to keep the keys, use asort() and arsort() in place of sort() and rsort().
31-Jul-2002 06:48
Similar to above but for an array of arrays instead of an array of objects.

<?php
function aasort($x,$var,$cmp='strcasecmp'){
  if ( is_string($var) ) $var = "'$var'";
  uasort($x,
    create_function('$a,$b',
      'return '.$cmp.'( $a['.$var.'],$b['.$var.']);')
  );
  return $x;
}
?>
phzzzt .a.t. acm .d.o.t. org 31-Jul-2002 06:32
Similar to above but for an array of arrays instead of an array of objects.

<?php
function aasort($x,$var,$cmp='strcasecmp'){
  if ( is_string($var) ) $var = "\'$var\'";
  uasort($x,
    create_function('$a,$b',
      'return '.$cmp.'( $a['.$var.'],$b['.$var.']);')
  );
  return $x;
}
?>
salchicha at cable dot net dot co 03-Apr-2002 01:23
Here's one I whipped up to allow you to sort an array of a specific class by a member or function:

<?php
// Sort a class by one of its members (even lowercase!!!)
function casort($arr, $var) {
   $tarr = array();
   $rarr = array();
   for($i = 0; $i < count($arr); $i++) {
      $element = $arr[$i];
      $tarr[] = strtolower($element->{$var});
   }

   reset($tarr);
   asort($tarr);
   $karr = array_keys($tarr);
   for($i = 0; $i < count($tarr); $i++) {
      $rarr[] = $arr[intval($karr[$i])];
   }

   return $rarr;
}
?>

It works very well. For example, I have a Room class with members title, isActive(), date, etc. I can sort an array by casort($rooms, "title") or casort($rooms, "isActive()") and it'll work.
rcwang at cmu dot edu 02-Mar-2002 05:42
Here's my version of sorting multi-dimensional array by 2nd index.
Feel free to change the code to suit your needs.

<?php
function aSortBySecondIndex($multiArray, $secondIndex) {
    while (list($firstIndex, ) = each($multiArray))
        $indexMap[$firstIndex] = $multiArray[$firstIndex][$secondIndex];
    asort($indexMap);
    while (list($firstIndex, ) = each($indexMap))
        if (is_numeric($firstIndex))
            $sortedArray[] = $multiArray[$firstIndex];
        else $sortedArray[$firstIndex] = $multiArray[$firstIndex];
    return $sortedArray;
}
?>
freeman at generalresources dot com 04-May-2001 04:51
The asortbyindex($sortarray, $index) looks like sort not asort. The key of the $sortarray was changed.
sweetland at whoadammit dot com 15-Aug-2000 12:02
Here's a little routine I whipped up to sort multi-dimensional arrays:
<?php
/**
 ** comesafter ($s1, $s2)
 **
 ** Returns 1 if $s1 comes after $s2 alphabetically, 0 if not.
 **/

function comesafter ($s1, $s2) {
        /**
         ** We don't want to overstep the bounds of one of the strings and segfault,
         ** so let's see which one is shorter.
         **/

        $order = 1;

        if (strlen ($s1) > strlen ($s2)) {
                $temp = $s1;
                $s1 = $s2;
                $s2 = $temp;
                $order = 0;
        }

        for ($index = 0; $index < strlen ($s1); $index++) {
                /**
                 ** $s1 comes after $s2
                 **/

                if ($s1[$index] > $s2[$index]) return ($order);

                /**
                 ** $s1 comes before $s2
                 **/

                if ($s1[$index] < $s2[$index]) return (1 - $order);
        }

        /**
         ** Special case in which $s1 is a substring of $s2
         **/

        return ($order);
}

/**
 ** asortbyindex ($sortarray, $index)
 **
 ** Sort a multi-dimensional array by a second-degree index. For instance, the 0th index
 ** of the Ith member of both the group and user arrays is a string identifier. In the
 ** case of a user array this is the username; with the group array it is the group name.
 ** asortby
 **/

function asortbyindex ($sortarray, $index) {
        $lastindex = count ($sortarray) - 1;
        for ($subindex = 0; $subindex < $lastindex; $subindex++) {
                $lastiteration = $lastindex - $subindex;
                for ($iteration = 0; $iteration < $lastiteration;    $iteration++) {
                        $nextchar = 0;
                        if (comesafter ($sortarray[$iteration][$index], $sortarray[$iteration + 1][$index])) {
                                $temp = $sortarray[$iteration];
                                $sortarray[$iteration] = $sortarray[$iteration + 1];
                                $sortarray[$iteration + 1] = $temp;
                        }
                }
        }
        return ($sortarray);
}
?>

It's a bit long with all the comments, but I hope it helps.
bwuhlman at tallships dot ca 02-Aug-2000 03:01
Well, actually, asort has *two* annoying features.

It works perfectly well sorting hashes (or associative arrays, as you might have it), but doggedly refuses to sort regular arrays maintaining index assocation. Kind've makes sense, but the docs don't explicitly say you can't do it.

Urgggh.
jacko at kring dot co dot uk 24-Feb-2000 11:26
asort has one anoying feature, it ignores any default or implicit order in the data.  i.e. if two elements of an array contain "banana" then it is not garanteed that the first will still be the first after the sort.
This makes the Burrows-Wheeler block sort a bit of a pain to impliment, with a trailing string having to be appended to all strings before sorting, and removed after sorting. To maintain the so called "banana" order.


Crear un array que contiene variables y sus valores

  • « asort
  • count »
  • PHP Manual
  • Funciones de Arrays
  • Crear un array que contiene variables y sus valores

compact

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

compact — Crear un array que contiene variables y sus valores

Descripción

compact ( mixed $varname1 , mixed $... = ? ) : array

Crea un array que contiene variables y sus valores.

Por cada variable, compact() busca una variable con ese nombre en la tabla de símbolos actual y las añade al array de salida de modo que el nombre de la variable se convierte en la clave y el contenido de la variable se convierte en el valor para esa clave. En pocas palabras, hace lo contrario que extract().

Nota:

Antes de PHP 7.3, cualquier cadena que no esté establecida se omitirá silenciosamente.

Parámetros

varname1

compact() toma un número variable de parámetros. Cada parámetro puede ser una cadena que contiene el nombre de la variable, o un array de nombres de variables. El array puede contener otros arrays de nombres de variables dentro de él; compact() los trata recursivamente.

Valores devueltos

Devuelve un array de salida con todas las variables añadidas a él.

Ejemplos

Ejemplo #1 Ejemplo de compact()

<?php
$ciudad  = "San Francisco";
$estado = "CA";
$evento = "SIGGRAPH";

$vars_región = array("ciudad", "estado");

$resultado = compact("evento", "nada_aquí", $vars_región);
print_r($resultado);
?>

El resultado del ejemplo sería:

Array
(
    [evento] => SIGGRAPH
    [ciudad] => San Francisco
    [estado] => CA
)

Notas

Nota: A tener en consideración

Ya que las variables variables no se pueden usar con Arrays Superglobales de PHP dentro de funciones, los arrays Superglobales no pueden ser pasados a compact().

Ver también

  • extract() - Importar variables a la tabla de símbolos actual desde un array

User Contributed Notes

lekiagospel at gmail dot com 13-Jan-2020 01:20
Consider these two examples. The first as used in the manual, and  the second a slight variation of it.

Example #1

<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", $location_vars);
print_r($result);
?>

Example #1 above  will output:

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

Example #2

<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", "location_vars");
print_r($result);
?>

Example #2 above will output:

Array
(
    [event] => SIGGRAPH

    [location_vars] => Array
        (
            [0] => city
            [1] => state
        )

)

In the first example, the value of the variable $location_values (which is an array containing city, and state) is passed to compact().

In the second example, the name of the variable $location_vars  (i.e  without the '$' sign) is passed to compact() as a string. I hope this further clarifies the points made in the manual?
jmarkmurph at yahoo dot com 26-Jan-2016 01:45
So compact('var1', 'var2') is the same as saying array('var1' => $var1, 'var2' => $var2) as long as $var1 and $var2 are set.
Robc 19-Jan-2011 03:16
The description says that compact is the opposite of extract() but it is important to understand that it does not completely reverse extract().  In particluar compact() does not unset() the argument variables given to it (and that extract() may have created).  If you want the individual variables to be unset after they are combined into an array then you have to do that yourself.
M Spreij 24-May-2007 06:10
Can also handy for debugging, to quickly show a bunch of variables and their values:

<?php
print_r(compact(explode(' ', 'count acw cols coldepth')));
?>

gives

Array
(
    [count] => 70
    [acw] => 9
    [cols] => 7
    [coldepth] => 10
)


Cuenta todos los elementos de un array o algo de un objeto

  • « compact
  • current »
  • PHP Manual
  • Funciones de Arrays
  • Cuenta todos los elementos de un array o algo de un objeto

count

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

count — Cuenta todos los elementos de un array o algo de un objeto

Descripción

count ( mixed $array_or_countable , int $mode = COUNT_NORMAL ) : int

Cuenta todos los elementos en un array o algo de un objeto.

En objetos, si se tiene SPL instalado, se puede enganchar a count() implementado la interfaz Countable. Esta interfaz tiene solamente un método, Countable::count(), el cual devuelve el valor retornado por la función count().

Véase la sección Array del manual para una explicación detallada sobre cómo se implementan y usan los arrays en PHP.

Parámetros

array_or_countable

Un array o un objeto Countable.

mode

Si el parámetro opcional mode está establecido a COUNT_RECURSIVE (o 1), count() contará el array de forma recursiva. Esto es particularmente útil para contar todos los elementos de un array multidimensional.

Precaución

count() puede detectar recursividad para evitar un bucle infinito, pero emitirá un mensaje E_WARNING cada vez que lo haga (en caso de que el array se contenga a sí mismo más de una vez) y devolverá una cuenta mayor de la que se podría esperar.

Valores devueltos

Devuelve el número de elementos en array_or_countable, Cuando el parámetro no es un array ni un objecto con la interfaz Countable implementada, devolverá 1. Existe una excepción, si array_or_countable es null, devolverá 0.

Ejemplos

Ejemplo #1 Ejemplo de count()

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));

$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
var_dump(count($b));

var_dump(count(null));

var_dump(count(false));
?>

El resultado del ejemplo sería:

int(3)
int(3)

Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 // as of PHP 7.2
int(0)

Warning: count(): Parameter must be an array or an object that implements Countable in … on line 14 // as of PHP 7.2
int(1)

Ejemplo #2 Ejemplo de count() recursivo

<?php
$comida = array('frutas' => array('naranja', 'plátano', 'manzana'),
                'verduras' => array('zanahoria', 'col', 'guisante'));

// Cuenta recursiva
echo count($comida, COUNT_RECURSIVE); // muestra 8

// Cuenta normal
echo count($comida); // muestra 2

?>

Historial de cambios

Versión | Descripción
7.2.0 | count() generará una advertencia si se pasan tipos contables no válido al parámetro array_or_countable.

Ver también

  • is_array() - Comprueba si una variable es un array
  • isset() - Determina si una variable está definida y no es null
  • empty() - Determina si una variable está vacía
  • strlen() - Obtiene la longitud de un string
  • is_countable() - Verifica que el contenido de una variable es un valor contable

User Contributed Notes

vojtaripa at gmail dot com 25-Jun-2020 12:29
To get the count of the inner array you can do something like:

$inner_count = count($array[0]);
echo ($inner_count);
max at schimmelmann dot org 08-Mar-2020 12:12
In special situations you might only want to count the first level of the array to figure out how many entries you have, when they have N more key-value-pairs.

<?php

$data = [
    'a' => [
        'bla1' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
        'bla2' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
        'bla3' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
        'bla4' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
    ],
    'b' => [
        'bla1' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
        'bla2' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
    ],
    'c' => [
        'bla1' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ]
    ]
];
$count = array_sum(array_values(array_map('count', $data)));
// will return int(7)
var_dump($count);

// will return 31
var_dump(count($data, 1));
?>
XavDeb 30-Jan-2020 10:59
If you want to know the sub-array containing the MAX NUMBER of values in a 3 dimensions array, here is a try (maybe not the nicest way, but it works):

function how_big_is_the_biggest_sub ($array)  {
   // we parse the 1st level
   foreach ($array AS $key => $array_lvl2) {
         //within level 2, we count the 3d levels max
            $lvl2_nb = array_map( 'count',  $array_lvl2) ;
            $max_nb = max($lvl2_nb);
         // we store the matching keys, it might be usefull
            $max_key = array_search($max_nb, $lvl2_nb);
            $max_nb_all[$max_key.'|'.$key] = $max_nb;
        }
       // now we want the max from all levels 2, so one more time
        $real_max = max($max_nb_all);
        $real_max_key = array_search($real_max, $max_nb_all);
        list($real_max_key2, $real_max_key1) = explode('|', $real_max_key);
                // preparing result
        $biggest_sub['max'] = $real_max;
        $biggest_sub['key1'] = $real_max_key1;
        $biggest_sub['key2'] = $real_max_key2;

        return $biggest_sub;
}
/*
$cat_poids_max['M']['Juniors'][] = 55;
$cat_poids_max['M']['Juniors'][] = 61;
$cat_poids_max['M']['Juniors'][] = 68;
$cat_poids_max['M']['Juniors'][] = 76;
$cat_poids_max['M']['Juniors'][] = 100;

$cat_poids_max['M']['Seniors'][] = 55;
$cat_poids_max['M']['Seniors'][] = 60;
$cat_poids_max['M']['Seniors'][] = 67;
$cat_poids_max['M']['Seniors'][] = 75;
$cat_poids_max['M']['Seniors'][] = 84;
$cat_poids_max['M']['Seniors'][] = 90;
$cat_poids_max['M']['Seniors'][] = 100;
//....
$cat_poids_max['F']['Juniors'][] = 52;
$cat_poids_max['F']['Juniors'][] = 65;
$cat_poids_max['F']['Juniors'][] = 74;
$cat_poids_max['F']['Juniors'][] = 100;

$cat_poids_max['F']['Seniors'][] = 62;
$cat_poids_max['F']['Seniors'][] = 67;
$cat_poids_max['F']['Seniors'][] = 78;
$cat_poids_max['F']['Seniors'][] = 86;
$cat_poids_max['F']['Seniors'][] = 100;
*/
$biggest_sub = how_big_is_the_biggest_sub($cat_poids_max);
echo "<li> ".$biggest_sub['key1']." ==> ".$biggest_sub['key2']." ==> ".$biggest_sub['max']; // displays : M ==> Seniors ==> 7
Anonymous 05-Oct-2019 05:52
For a Non Countable Objects

$count = count($data);
print "Count: $count\n";

Warning:  count(): Parameter must be an array or an object that implements Countable in example.php on line 159

#Quick fix is to just cast the non-countable object as an array..

$count = count((array) $data);
print "Count: $count\n";

Count: 250
jerome dot gds at gmail dot com 20-Sep-2019 12:53
to end the debate: count() is the same as empty()

test code below:

results on my computer:

count : double(0.81396999359131)
empty : double(0.81621310710907)

using isset($test[0]) is a bit slower than empty;
test without adding value to the array in function ****Test: still the same.

<?php

function average(array $test)
{
    $sum = 0;
    foreach($test as $value) {
        $sum += $value;
    }

    return $sum;
}

function countTest(array $test)
{
    $i = 0;
    while ($i++ < 1000000) {
        count($test);
        $test["lol$i"] = "teset$i";
    }
}

function emptyTest(array $test)
{
    $i = 0;
    while ($i++ < 1000000) {
        empty($test);
        $test["lol$i"] = "teset$i";
    }
}

$test = [];
$i = 0;
while ($i++ < 20000000) {
    $test[] = $i;
}

$j = 10;
$value = $j;
$count = [];
$isEmpty = [];
while ($j--) {
    $time = microtime(true);
    countTest($test);
    $count[] = microtime(true) - $time;

    $time = microtime(true);
    emptyTest($test);
    $isEmpty[] = microtime(true) - $time;
}

var_dump(average($count) / $value);
var_dump(average($isEmpty) / $value);
lucasfsmartins at gmail dot com 07-Mar-2019 11:26
If you are on PHP 7.2+, you need to be aware of "Changelog" and use something like this:

<?php
$countFruits = is_array($countFruits) || $countFruits instanceof Countable ? count($countFruits) : 0;
?>

You can organize your code to ensure that the variable is an array, or you can extend the Countable so that you don't have to do this check.
flavioaugusto dot br at gmail dot com 01-Mar-2019 02:55
Criada para contar quantos níveis um array multidimensional possui.

function count_multiLevel($matrix, $_LEVEL = 0){

        /* Variáveis de recursão */
        $_COUNT = $_LEVEL;

        /* Verifica se o ARRAY foi instanciado */
        if (is_setVar($matrix)){

            /* Verifica se a variável é um ARRAY */
            if(is_array($matrix)){

                /* Loop de elementos da matriz*/
                foreach ($matrix as $elements => $value) {

                    /* Auxiliar para verificação posterior */
                    $_AUX = $_COUNT;

                    /* Verifiando os Nós */
                    if (is_array($matrix[$elements])) {
                        $_COUNT = count_multiLevel($matrix[$elements], $_LEVEL+1);
                    }
                    /* Cereja do bolo */
                    if($_AUX > $_COUNT)
                        $_COUNT = $_AUX;
                }
                /* Retorn do resultado da operação */
                return $_COUNT;

            }else{
                /* Em casos que o valor passado não seja uma matriz/array */
                return -1;
            }
        }
    }
buyatv at gmail dot com 27-Jan-2017 09:16
You can not get collect sub array count when use the key on only one sub array in an array:

$a = array("a"=>"appple", b"=>array('a'=>array(1,2,3),'b'=>array(1,2,3)));
$b = array("a"=>"appple", "b"=>array(array('a'=>array(1,2,3),'b'=>array(1,2,3)), array(1,2,3),'b'=>array(1,2,3)), array('a'=>array(1,2,3),'b'=>array(1,2,3))));

echo count($a['b']);  // 2 NOT 1, expect 1
echo count($b['b']);  // 3,   expected
buyatv at gmail dot com 26-Jan-2017 10:32
You can not get collect sub array count when there is only one sub array in an array:

$a = array ( array ('a','b','c','d'));
$b = array ( array ('a','b','c','d'), array ('e','f','g','h'));

echo count($a);  // 4 NOT 1, expect 1
echo count($b);  // 2,   expected
php_count at cubmd dot com 22-Nov-2016 03:12
All the previous recursive count solutions with $depth option would not avoid infinite loops in case the array contains itself more than once.
Here's a working solution:

<?php
    /**
     * Recursively count elements in an array. Behaves exactly the same as native
     * count() function with the $depth option. Meaning it will also add +1 to the
     * total count, for the parent element, and not only counting its children.
     * @param $arr
     * @param int $depth
     * @param int $i (internal)
     * @return int
     */
    public static function countRecursive(&$arr, $depth = 0, $i = 0) {
        $i++;
        /**
         * In case the depth is 0, use the native count function
         */
        if (empty($depth)) {
            return count($arr, COUNT_RECURSIVE);
        }
        $count = 0;
        /**
         * This can occur only the first time when the method is called and $arr is not an array
         */
        if (!is_array($arr)) {
            return count($arr);
        }

        // if this key is present, it means you already walked this array
        if (isset($arr['__been_here'])) {
            return 0;
        }

        $arr['__been_here'] = true;

        foreach ($arr as $key => &$value) {
            if ($key !== '__been_here') {
                if (is_array($value) && $depth > $i) {
                    $count += self::countRecursive($value, $depth, $i);
                }

                $count++;
            }
        }

        // you need to unset it when done because you're working with a reference...
        unset($arr['__been_here']);
        return $count;
    }
?>
ThisIsNotImportant 17-Dec-2015 03:10
About 2d arrays, you have many way to count elements :

<?php
$MyArray = array ( array(1,2,3),
                   1,
                   'a',
                   array('a','b','c','d') );

// All elements
echo count($MyArray ,COUNT_RECURSIVE);  // output 11 (9 values + 2 arrays)

// First level elements
echo count($MyArray );                  // output 4 (2 values+ 2 arrays)

// Both level values, but only values
echo(array_sum(array_map('count',$MyArray ))); //output 9 (9 values)

// Only second level values
echo (count($MyArray ,COUNT_RECURSIVE)-count($MyArray )); //output 7 ((all elements) - (first elements))
?>
pied-pierre 04-Jun-2015 05:27
A function of one line to find the number of elements that are not arrays, recursively :

function count_elt($array, &$count=0){
  foreach($array as $v) if(is_array($v)) count_elt($v,$count); else ++$count;
  return $count;
}
JumpIfBelow 05-May-2015 02:18
As I see in many codes, don't use count to iterate through array.
Onlyranga says you could declare a variable to store it before the for loop.
I agree with his/her approach, using count in the test should be used ONLY if you have to count the size of the array for each loop.

You can do it in the for loop too, so you don't have to "search" where the variable is set.
e.g.
<?php
    $array = [1, 5, 'element'];
    for($i = 0, $c = count($array); $i < $c; $i++)
        var_dump($array[$i]);
?>
onlyranga at gmail dot com 28-Apr-2014 02:14
[Editor's note: array at from dot pl had pointed out that count() is a cheap operation; however, there's still the function call overhead.]

If you want to run through large arrays don't use count() function in the loops , its a over head in performance,  copy the count() value into a variable and use that value in loops for a better performance.

Eg:

// Bad approach

for($i=0;$i<count($some_arr);$i++)
{
    // calculations
}

// Good approach

$arr_length = count($some_arr);
for($i=0;$i<$arr_length;$i++)
{
    // calculations
}
Gerd Christian Kunze 11-Dec-2013 12:56
Get maxWidth and maxHeight of a two dimensional array..?

Note:
1st dimension = Y (height)
2nd dimension = X (width)
e.g. rows and cols in database result arrays

<?php
$TwoDimensionalArray = array( 0 => array( 'key' => 'value', ...), ... );
?>

So for Y (maxHeight)
<?php
$maxHeight = count( $TwoDimensionalArray )
?>

And for X (maxWidth)
<?php
$maxWidth = max( array_map( 'count',  $TwoDimensionalArray ) );
?>

Simple? ;-)
danny at dannymendel dot com 13-Jun-2007 01:14
I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.

// $limit is set to the number of recursions
<?php
function count_recursive ($array, $limit) {
    $count = 0;
    foreach ($array as $id => $_array) {
        if (is_array ($_array) && $limit > 0) {
            $count += count_recursive ($_array, $limit - 1);
        } else {
            $count += 1;
        }
    }
    return $count;
}
?>
alexandr at vladykin dot pp dot ru 08-Nov-2006 04:28
My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).

<?php
  function getArrCount ($arr, $depth=1) {
      if (!is_array($arr) || !$depth) return 0;

     $res=count($arr);

      foreach ($arr as $in_ar)
         $res+=getArrCount($in_ar, $depth-1);

      return $res;
  }
?>


Devuelve el elemento actual en un array

  • « count
  • each »
  • PHP Manual
  • Funciones de Arrays
  • Devuelve el elemento actual en un array

current

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

current — Devuelve el elemento actual en un array

Descripción

current ( array|object $array ) : mixed

Cada array tiene un puntero interno a su elemento "actual", que es iniciado desde el primer elemento insertado en el array.

Parámetros

array

El array.

Valores devueltos

La función current() simplemente devuelve el valor del elemento del array que está siendo apuntado por el puntero interno. No desplaza el puntero de ninguna manera. Si el puntero interno apunta más allá del final de la lista de elementos o el array está vacío, current() devolverá false.

Advertencia

Esta función puede devolver el valor booleano false, pero también puede devolver un valor no booleano que se evalúa como false. Por favor lea la sección sobre Booleanos para más información. Use el operador === para comprobar el valor devuelto por esta función.

Historial de cambios

Versión | Descripción
7.0.0 | array ahora siempre se pasa por el valor. Antes de esta versión, se pasaba por referencia si era posible, y por el valor de lo contrario.

Ejemplos

Ejemplo #1 Ejemplo de uso de current() y similares

<?php
$transport = array('pie', 'bici', 'coche', 'avión');
$mode = current($transport); // $mode = 'pie';
$mode = next($transport);    // $mode = 'bici';
$mode = current($transport); // $mode = 'bici';
$mode = prev($transport);    // $mode = 'pie';
$mode = end($transport);     // $mode = 'avión';
$mode = current($transport); // $mode = 'avión';

$arr = array();
var_dump(current($arr)); // bool(false)

$arr = array(array());
var_dump(current($arr)); // array(0) { }
?>

Notas

Nota: The results of calling current() on an empty array and on an array, whose internal pointer points beyond the end of the elements, are indistinguishable from a bool false element. To properly traverse an array which may contain false elements, see the foreach() function. Los resultados al llamar current() en un array vacío y en un array, cuyo puntero interno apunta más allá del final de los elementos, son indistinguibles de un elemento de tipo bool false. Para recorrer adecuadamente un array que puede contener elementos false, ver la función foreach().

Ver también

  • end() - Establece el puntero interno de un array a su último elemento
  • key() - Obtiene una clave de un array
  • each() - Devolver el par clave/valor actual de un array y avanzar el cursor del array
  • prev() - Rebobina el puntero interno del array
  • reset() - Establece el puntero interno de un array a su primer elemento
  • next() - Avanza el puntero interno de un array

User Contributed Notes

leozmm at outlook dot com 24-Sep-2019 08:02
Array can be passed by both REFERENCE and EXPRESSION on `current`, because current doesn't move array's internal pointer,
this is not true for other functions like: `end`, `next`, `prev` etc.

<?php
    function foo() {return array(1,2,3);}
    echo current(foo());  // this print '1'
    echo end(foo());      // this print error: Only variables should be passed by reference
?>
xedin dot unknown at gmail dot com 10-Jul-2018 01:28
Array functions, such as `current()` and `rewind()` will work on `Traversable` as well, PHP 5.0 - 7.3, but not in HHVM:

<?php

$queue = new ArrayIterator(array('adasdasd'));
reset($queue);
$current = current($queue);
var_dump($current);

?>

See https://3v4l.org/VjCHR
pdarmis at gmail dot com 06-Aug-2017 06:22
Based on this example http://php.net/manual/en/function.current.php#116128 i would like to add the following.  As Vasily points out in his example
<?php
$prices = array(
    0 => '1300990',
    1 => '500',
    2 => '600'
);
foreach($prices as $key => $price){
    if($price < 1000){
        unset($prices[$key]);
    }
}

var_dump(current($prices)); // bool(false)
?>
The above example will not work and return false for version of PHP between 5.2.4 and 5.6.29. The issue is not present on PHP versions >= 7.0.1
A different workaround (at least from Vasily's example) would be to use reset() before using current() in order to reset the array pointer to start.
<?php
$prices = array(
    0 => '1300990',
    1 => '500',
    2 => '600'
);
foreach($prices as $key => $price){
    if($price < 1000){
        unset($prices[$key]);
    }
}
reset($prices);
var_dump(current($prices)); // string(7) "1300990"
?>
jodevweb at gmail dot com 16-Sep-2016 02:50
As Sergey stated a long time ago in this notes, when adding to the array using the brackets syntax, current won't return the last added value. Instead of moving the pointer with end(), you simply can get the last value with <?php $my_array[count($my_array) - 1] ?> (only applies to a non-associative array).
Vasily Yudin (st-2 at mail dot ru) 12-Nov-2014 08:51
If you do current() after using uset() on foreach statement, you can get FALSE in PHP version 5.2.4 and above.
There is example:
<?php
$prices = array(
    0 => '1300990',
    1 => '500',
    2 => '600'
);
foreach($prices as $key => $price){
    if($price < 1000){
        unset($prices[$key]);
    }
}

var_dump(current($prices)); // bool(false)
?>
If you do unset() without foreach? all will be fine.
<?php
$prices = array(
    0 => '1300990',
    1 => '500',
    2 => '600'
);
unset($prices[1]);
unset($prices[2]);

var_dump(current($prices));
?>
Pratip Ghosh 14-May-2014 05:55
If we unset any element from an array, and then try the current function, I noted it returned FALSE. To overcome this limitation, you can use array_values function to re-order the tree.
strate at yandex dot com 30-Oct-2013 07:11
Note, that you can pass array by expression, not only by reference (as described in doc).

<?php
var_dump( current( array(1,2,3) ) ); // (int) 1
?>
michael at squiloople dot com 10-Jan-2012 07:44
current() also works on objects:

<?php

  echo current((object) array('one', 'two')); // Outputs: one

?>
aefxx 15-May-2008 08:39
A simple copy function that not only copies the given array but ensures the copy's pointer is set to the exact same position:

<?php
function array_copy(&array)
{
    $key = key($array);
    $copy = $array;

    while (($copy_key = key($copy)) !== NULL) {
        if ($copy_key == $key) break;
        next($copy);
    }

    return $copy;
}
?>

That's all ... bye.
gregory at gregory dot net 27-Feb-2008 09:07
It took me a while to figure this out, but there is a more consistent way to figure out whether you really went past the end of the array, than using each().

You see, each() gets the value BEFORE advancing the pointer, and next() gets the value AFTER advancing the pointer. When you are implementing the Iterator interface, therefore, it's a real pain in the behind to use each().

And thus, I give you the solution:
To see if you've blown past the end of the array, use key($array) and see if it returns NULL. If it does, you're past the end of the array -- keys can't be null in arrays.

Nifty, huh? Here's how I implemented the Iterator interface in one of my classes:

<?php

/**
 * DbRow file
 * @package PalDb
 */

/**
 * This class lets you use Db rows and object-relational mapping functionality.
 */

class DbRow implements Iterator
{
    /**
     * The DbResult object that gave us this row through fetchDbRows
     * @var DbResult
     */
    protected $result;

    /**
     * The fields of the row
     * @var $fields
     */
    protected $fields;

    /**
     * Constructor
     *
     * @param PDOStatement $stmt
     *  The PDO statement object that this result uses
     * @param DbResult $result
     *  The result that produced this row through fetchDbRows
     */
    function __construct($result)
    {
        $this->result = $result;
    }

    /**
     * Get the DbResult object that gave us this row through fetchDbRows
     * @return DbResult
     *
     * @return unknown
     */
    function getResult()
    {
        return $this->result;
    }

    function __set(
        $name,
        $value)
    {
        $this->fields[$name] = $value;
    }

    function __get(
        $name)
    {
        if (isset($this->fields[$name]))
            return $this->fields[$name];
        else
            return null;
    }

    /**
     * Iterator implementation - rewind
     */
    function rewind()
    {
        $this->beyondLastField = false;
        return reset($this->fields);
    }

    function valid()
    {
        return !$this->beyondLastField;
    }

    function current()
    {
        return current($this->fields);
    }

    function key()
    {
        return key($this->fields);
    }

    function next()
    {
        $next = next($this->fields);
        $key = key($this->fields);
        if (isset($key)) {
            return $next[1];
        } else {
            $this->beyondLastField = true;
            return false; // doesn't matter what we return here, see valid()
        }
    }

    private $beyondLastField = false;
};

Hope this helps someone.
vaclav dot sir at gmail dot com 13-Aug-2007 09:23
To that "note": You won't be able to distinguish the end of an array from a boolean FALSE element, BUT you can distinguish the end from a NULL value of the key() function.

Example:
<?php
if (key($array) === null) {
    echo "You are in the end of the array.";
} else {
    echo "Current element: " . current($array);
}
?>
mdeng at kabenresearch dot com 23-Apr-2004 11:04
For large array(my sample was 80000+ elements), if you want to traverse the array in sequence, using array index $a[$i] could be very inefficient(very slow). I had to switch to use current($a).
vitalib at 012 dot net dot il 02-Dec-2003 02:10
Note that by copying an array its internal pointer is lost:

<?php
$myarray = array(0=>'a', 1=>'b', 2=>'c');
next($myarray);
print_r(current($myarray));
echo '<br>';
$a = $myarray;
print_r(current($a));
?>

Would output 'b' and then 'a' since the internal pointer wasn't copied. You can cope with that problem using references instead, like that:

<?php
$a =& $myarray;
?>
retestro_REMOVE at SPAM_esperanto dot org dot il 01-Mar-2003 06:31
The docs do not specify this, but adding to the array using the brackets syntax:
     <?php $my_array[] = $new_value; ?>
will not advance the internal pointer of the array. therefore, you cannot use current() to get the last value added or key() to get the key of the most recently added element.

You should do an end($my_array) to advance the internal pointer to the end ( as stated in one of the notes on end() ), then

    <?php
     $last_key = key($my_array);  // will return the key
     $last_value = current($my_array);  // will return the value
    ?>

If you have no need in the key, $last_value = end($my_array) will also do the job.

- Sergey.


Devolver el par clave/valor actual de un array y avanzar el cursor del array

  • « current
  • end »
  • PHP Manual
  • Funciones de Arrays
  • Devolver el par clave/valor actual de un array y avanzar el cursor del array

each

(PHP 4, PHP 5, PHP 7)

each — Devolver el par clave/valor actual de un array y avanzar el cursor del array

Advertencia

Esta función ha sido declarada OBSOLETA a partir de PHP 7.2.0. Su uso está totalmente desaconsejado.

Descripción

each ( array &$array ) : array

Devuelve el par clave/valor actual de un array y avanza el cursor del array.

Después de que each() haya sido ejecutado, el cursor del array será puesto en el siguiente elemento del array, o pasado el último elemento si alcanza el final del array. Se tiene que usar reset() si se quiere atravesar de nuevo el array usando each.

Parámetros

array

El array de entrada.

Valores devueltos

Devuelve el par clave/valor actual del array dado por array. Este par es devuelto en un array de cuatro elementos, con las claves 0, 1, key, y value. Los elementos 0 y key contienen el nombre de la clave del elemento del array, y 1 y value contienen la información.

Si el puntero interno del array apunta al final del contenido de array, each() devuelve false.

Ejemplos

Ejemplo #1 Ejemplo de each()

<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>

$bar ahora contienelos siguientes pares clave/valor:

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>

$bar ahora contienelos siguientes pares clave/valor:

Array
(
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
)

each() se usa normalmente junto con list() para atravesar un array. Aquí hay un ejemplo:

Ejemplo #2 Atravesar un array con each()

<?php
$fruta = array('a' => 'manzana', 'b' => 'banana', 'c' => 'arándano');

reset($fruta);
while (list($clave, $valor) = each($fruta)) {
    echo "$clave => $valor\n";
}
?>

El resultado del ejemplo sería:

a => manzana
b => banana
c => arándano

Precaución

Ya que asignar un array a otra variable reinicia el puntero del array original (nuestro ejemplo de arriba causaría un bucle sin fin), hemos asignado $fruta a otra variable dentro del bucle.

Advertencia

each() también aceptará objetos, pero puede devolver resultados inesperados. Por lo tanto, no se recomienda iterar propiedades de objetos con each().

Ver también

  • key() - Obtiene una clave de un array
  • list() - Asignar variables como si fueran un array
  • current() - Devuelve el elemento actual en un array
  • reset() - Establece el puntero interno de un array a su primer elemento
  • next() - Avanza el puntero interno de un array
  • prev() - Rebobina el puntero interno del array
  • foreach
  • Iteración de Objetos

User Contributed Notes

man13or at hotmail dot fr 03-Feb-2020 07:49
Hello, since each() and list() often "betray" very old applications, I simply recommend not to use them anymore.

If you want to assign variables based on an associative array,
Replace this:

while(list ($key, $value) = each ($my_array)) {
    $$key = $value;
}

with this:

foreach ($my_array as $key => $value) {
    $$key = $value;
}
Henk Poley 30-Aug-2019 07:30
Rector has an automated fix ('ListEachRector') to migrate away from `each()`:

https://github.com/rectorphp/rector/blob/master/docs/AllRectorsOverview.md#listeachrector

If you look at the code example you'll see this is even quite simple to do by hand.
phpcoder at gmail dot com 25-Jun-2019 09:36
each was deprecated because it exposed too much of the internal implementation details, blocking language development. ("We can't do X because it would break each().")

https://wiki.php.net/rfc/deprecations_php_7_2#each

If you want an array pointer, maintain it yourself. Probably a good idea anyway, because then it's visible in the code.
Anonymous 04-Aug-2018 01:12
An odd function to deprecate. If you're keeping track of an array pointer in a collection outside a foreach loop you don't care about performance and the utility of this function is core.

Instead you must call two functions: current() and then next() to replicate its behaviour.
13975001197 at 163 dot com 08-Apr-2018 03:58
In PHP 7.2 we can use foreach() to replace each(), such as:

foreach($array as $key => $value) {
    //do something
}
janhsh at tiscalinet dot be 24-Sep-2017 01:57
The following example is invalid in PHP 7 :

<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (list($key, $val) = each($fruit)) {
    echo "$key => $val\n";
}
?>

The correct writing is
<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while ($Item= each($fruit)) {
    $key=$Item[0];
    $val=$Item[1];
    echo "$key => $val\n";
}
?>

This is because the "list ()" command on the left no longer works in PHP 7 and there is no replacement command.
Which is very deplorable because this command was strongly used and allowed in a simple way to assign variables from array.
ayyappan dot ashok at gmail dot com 18-Apr-2016 09:21
/* Iterating using objects via each */

class SAI
{
   public function __toString()
   {
          return __CLASS__;
   }
}
$a = new SAI();
$b = new SAI();
$c = new SAI();
$d = new SAI();
$e = new SAI();

$objarray = array($a,$b,$c,$d,$e);
reset($objarray);
while (list($key, $val) = each($objarray))
{
    echo "$key => $val\n";
}
//Results
0 => SAI
1 => SAI
2 => SAI
3 => SAI
4 => SAI

Warning:
each() will also accept objects, but may return unexpected results. It's therefore not recommended to iterate though object properties with each().
nino dot skopac at gmail dot com 02-Jul-2015 01:30
<?php
function each_v2($arr) {
    // same as each() but when it hits end of array, it resets it
    static $i = 0;

    if (isset($arr[$i])) {
        // exists¸
        return $arr[$i++];
    } else {
        // reset $i to 0 and repeat
        $i = 0;
        return each_v2($arr);
    }
}
?>
gaviel 18-Mar-2011 03:53
Ok Here's one for iterating multidimensional array .. using foreach

    <?php
        $members = array(
                            "member1" => array (
                                                "First Name" => "Robert",
                                                "Last Name" => "Burton",
                                                "Age" => "20"
                                                ),
                            "member2" => array (
                                                "First Name" => "Cheska",
                                                "Last Name" => "Vladesk",
                                                "Age" => "21"
                                                ),
                            "member3" => array (
                                                "First Name" => "Gino",
                                                "Last Name" => "Marley",
                                                "Age" => "19"
                                                ),
                            "member4" => array (
                                                "First Name" => "Jake",
                                                "Last Name" => "White",
                                                "Age" => "16"
                                                ),
                            );
        $dataSetCount = count($members);
        echo "<h1>There are $dataSetCount members</h1>";

        $i = 0;
        foreach ($members as $each_members) {
            $i++;
            echo "<h2>Member $i</h2>";
                foreach ($each_members as $position => $details) {
                    echo "<b>$position</b>" . ": " . $details . "<br />";
                }
            }
    ?>
massimo dot modica at tin dot it 03-Feb-2010 02:36
If you forget to reset the array before each(), the same code may give different results with different php versions.

<?php

$a = array(1,2,3);

foreach ($a AS $k => $v) $a[$k] = 2*$v;

while(list($k2, $v2) = each($a)) { echo($v2."\n"); }

?>

In PHP 5.2.0:

2
4
6

In PHP 5.2.6:

4
6
php at omit dot ianco dot co dot uk 13-Apr-2008 06:10
I wanted to be able to add to an array while looping through it. foreach does not allow this because it is using a secret copy of the array. each makes this possible (tested on PHP 4).
<?php
$shopping_list = array('oysters', 'caviare');
reset ($shopping_list);
while (list($key, $value) = each ($shopping_list)) {
    if ($value == 'oysters') $shopping_list[] = 'champagne';
    elseif ($value == 'champagne') $shopping_list[] = 'ice';
}
print_r($shopping_list);
// Array ( [0] => oysters [1] => caviare [2] => champagne [3] => ice )
?>
wolfeym38 at yahoo dot com 11-Jun-2007 11:28
Regarding speed of foreach vs while(list) =each
I wrote a benchmark script and the results are that clearly foreach is faster. MUCH faster. Even with huge arrays (especially with huge arrays). I tested with sizes 100,000. 1,000,000 and 10,000,000. To do the test with 10 million i had to set my memory limit real high, it was close to 1gb by the time it actually worked. Anyways,

<?php
function getDiff($start, $end) {
    $s = explode(' ', $start);
    $stot = $s[1] + $s[0];
    $e = explode(' ', $end);
    $etot = $e[1] + $e[0];
    return $etot - $stot;
}

$lim=10000000;
$arr = array();
for ($i=0; $i<$lim; $i++) {
    $arr[$i] = $i/2;
}

$start = microtime();
foreach ($arr as $key=>$val);

$end = microtime();
echo "time for foreach = " . getDiff($start, $end) . ".\n";

reset($arr);
$start = microtime();
while (list($key, $val) = each($arr));
$end = microtime();
echo "time list each = " . getDiff($start, $end) . ".\n";
?>

here are some of my results: with 1,000,000
time for foreach = 0.0244591236115.
time list each = 0.158002853394.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0245339870453.
time list each = 0.154260158539.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0269000530243.
time list each = 0.157305955887.

then with 10,000,000:
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 1.96586894989.
time list each = 14.1371650696.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.02504014969.
time list each = 13.7696218491.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.0246758461.
time list each = 13.8425710201.

by the way, these results are with php 5.2 i believe, and a linux machine with 3gb of ram and 2.8ghz dual core pentium
michael k (name der redaktion bekannt.) 10-May-2007 12:36
If you want to iterate over a two-dimensional, sparse array, and want to  first display every first element, then every second and so on, you can use this code:

 $fruits = array ( "fruits"  => array ( "a" => "orange",
                                      "b" => "banana",
                                      "c" => "apple"
                                    ),
                 "numbers" => array ( 1,
                                      2,
                                      3,
                                      4,
                                      5,
                                      6
                                    ),
                 "holes"   => array (      "first",
                                      5 => "second",
                                           "third",
                                     10 => "fourth",
                                    )
               );

$done = False;
while ($done == False) {
       $done = True;

       // Important: &$val has to be a reference (use the &),
       // if you don't, the internal counter of $val will be
       // re-initialized each time and you loop over the first elements
       // for eternity.

       foreach($fruits as $key => &$val) {

               if (list($inner_key, $inner_val) = each(&$val)) {
                       $done = False;
                       echo "$key : : $inner_key => $inner_val  <br>  \n";
               }

       }
}

NOTE: this is just a quick hack, if you know a better way, post it!
sjoerd-php at linuxonly dot nl 31-Mar-2006 06:04
Use foreach instead of while, list and each. Foreach is:
- easier to read
- faster
- not influenced by the array pointer, so it does not need reset().

It works like this:
<?php
$arr = array('foo', 'bar');
foreach ($arr as $value) {
    echo "The value is $value.";
}

$arr = array('key' => 'value', 'foo' => 'bar');
foreach ($arr as $key => $value) {
    echo "Key: $key, value: $value";
}
?>
matthew at mhalls dot net 04-Dec-2005 03:58
To panania at 3ringwebs dot com:

If you know for certain that you are only receiving one row, the while becomes redundant. To shorten your code:

$strSQL = "SELECT * FROM table WHERE id=1";
$RecordsetSelect = $db->runQuery ($strSQL);
list($key, $val) = mysql_fetch_row($RecordsetSelect);
echo "$key => $val\n";
mysql_free_result($RecordsetSelect);

With only one row being returned this is more elegant a solution, but just being nit-picky in essence. It also shows another quick way of using list.
amby2 at izh dot com 24-Nov-2005 09:55
I've found a compact way to cycle through an associative array using for statement (not while, as it has been done in the most of examples below):

<?php

for (reset($array); list($key) = each($array);) {
  echo $key;
  echo $array[$key];
}

?>

or

<?php

for (reset($array); list($key, $value) = each($array);) {
  echo $key;
  echo $value;
  echo $array[$key];
}

?>

You hardly forget to add reset($array) code line using such construction.
Sopinon 23-Jul-2005 05:17
If you want to display the hole structure (tree) of your array, then you can use this recursive solution.

<?PHP
$tree= "";
array_tree($your_array);
echo $tree;

// Recursive Function
function array_tree($array, $index=0){
    global $tree;
    $space="";
    for ($i=0;$i<$index;$i++){
        $space .= "     ";
    }
    if(gettype($array)=="array"){
        $index++;
        while (list ($x, $tmp) = each ($array)){
            $tree .= $space."$x => $tmp\n";
            array_tree($tmp, $index);
        }
    }
}
?>
james at gogo dot co dot nz 02-Nov-2004 07:29
It's worth noting that references to an array don't have thier own array pointer, and taking a reference to an array doesn't reset it's array pointer, so this works as you would expect it would by eaching the first three items of the array, rather than the first item 3 times.

<?php
  $x = array(1,2,3);

  print_r(each($x));
  echo "\n";

  $y =& $x;
  print_r(each($y));
  echo "\n";

  $z =& $y;
  print_r(each($z));
  echo "\n";
?>
wodzuY2k at anronet dot pl 04-Aug-2002 12:41
This function will help you dump any variable into XML structure.

        //dump var into simple XML structure
        function var_dump_xml($tagname,$variable,$level=0)
         {
            for($i=0;$i<$level;$i++) $marg.=' ';
            if (eregi('^[0-9].*$',$tagname)) $tagname='tag_'.$tagname; //XML tag cannot start with [0-9] character
            if (is_array($variable))
             {
                echo $marg."<$tagname>\n";
                while (list ($key, $val) = each ($variable))  var_dump_xml($key,$val,$level+1);
                echo $marg."</$tagname>\n";
             }
            elseif (strlen($variable)>0)
             {
                 echo $marg."<$tagname>".htmlspecialchars($variable)."</$tagname>\n";
             };
         };

        /*
        example:

        $myVar = array("name"=>"Joe", "age"=>"26", "children"=>array("Ann","Michael"));
        var_dump_xml("myVarTag",$myVar);
        */
Gillis at dancrea dot com 26-May-2002 10:13
I wrote a short and pretty simple script to search through associative arrays for some value in the values, heres a simplifyed example of it:

<?php

$foo['bob'] = "bob is ugly";
$foo['bill'] = "bill is rich";
$foo['barbie'] = "barbie is cute";
$search = "rich";

echo "searching the array foo for $search:<br>";
reset ($foo);
while (list ($key, $val) = each ($foo)) {
if (preg_match ("/$search/i", $val)) {
    print "A match was found in $key.<br />";
} else {
    print "A match was not found in $key.<br />";
}
}

?>

will output:
Searching the array foo for rich:
A match was not found in bob
A match was found in bill
A match was not found in barbie
13-Feb-2002 04:10
I usually work a lot with 2D arrays. Since I've had some trouble traversing them correctly maybe someone out there also experienced those problems and can use this one.

It's based on a 2D-array called $array[$x][$y]. At some (but not necessarily all) (x,y) there is a value I want to reach. Note that I do not know beforehand the ranges of $x or $y (that is their highest and lowest values).

while (list ($x, $tmp) = each ($array)) {
   while (list ($y, $val) = each ($tmp)) {
      echo "$x, $y, $val";
   }
}

The answer for each (x,y) pair can thus be (providng, of course those values where in your array beforehand):

1, 1, 2
2, 2, 0
3, 1, 1
5, 2, 2
5, 1, 2

Note that only the (x,y) pairs with a corresponding value is shown.

Hang in there
Jon Egil Strand
NTNU
tk at turtle-entertainment dot de 29-Jan-2001 11:33
Be sure to use the integrated functions "unset();" or "reset();" - many people forget this and wonder about the created output!
kris at angelanthony dot com 25-Oct-2000 01:03
Remember to use "reset()" if you iterate over an array with "each()" more than once!  Example:

while(list($key,$value) = each($array)){
 // code here
}

NOW the internal pointer on $array is at the end of the array, and another attempt at an iteration like the one above will result in zero executions of the code within the "while" block.  You MUST call "reset($array)" to reset the internal array pointer before iterating over the array again from the first element.


Establece el puntero interno de un array a su último elemento

  • « each
  • extract »
  • PHP Manual
  • Funciones de Arrays
  • Establece el puntero interno de un array a su último elemento

end

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

end — Establece el puntero interno de un array a su último elemento

Descripción

end ( array &$array ) : mixed

end() avanza el puntero interno del array hasta su último elemento y devuelve su valor.

Parámetros

array

El array. Este array es pasado por referencia porque es modificado por la función. Esto significa que se debe pasar una variable real y no una función que devuelve un array porque solamente variables puede ser pasadas por referencia.

Valores devueltos

Devuelve el valor del último elemento o false si el array está vacío.

Ejemplos

Ejemplo #1 Ejemplo de end()

<?php

$fruits = array('manzana', 'plátano', 'arándano');
echo end($fruits); // arándano

?>

Ver también

  • current() - Devuelve el elemento actual en un array
  • each() - Devolver el par clave/valor actual de un array y avanzar el cursor del array
  • prev() - Rebobina el puntero interno del array
  • reset() - Establece el puntero interno de un array a su primer elemento
  • next() - Avanza el puntero interno de un array
  • array_key_last() - Obtiene la última clave de un array

User Contributed Notes

aaaaa976 at gmail dot com 16-Nov-2018 11:12
To get the first element:

    // Get first item.
    foreach ($array as $item) {
        $first = $item;
        break;
    }
    // $first will have the first element.
Aleksandr 28-Apr-2018 04:17
<?php
$A=[1];
print_r($A);
end($A[5]);
print_r($A);
?>

Array
(
    [0] => 1
)
Array
(
    [0] => 1
    [5] =>
)
Jacob 15-Jul-2017 05:55
Attempting to get the value of a key from an empty array through end() will result in NULL instead of throwing an error or warning becuse end() on an empty array results in false:

<?php

$a = ['a' => ['hello' => 'a1','world' => 'a2'],
      'b' => ['hello' => 'b1','world' => 'b2'],
      'c' => ['hello' => 'c1','world' => 'c2']
    ];
$b = [];

var_dump(end($a)['hello']);
var_dump(end($b)['hello']);
var_dump(false['hello']);

?>

Results in:

string(2) "c1"
NULL
NULL
Omolewa stephen 24-Oct-2016 06:16
I found using pathinfo very useful in getting extension of  a file.
<? Php
  $filename = dictionary.txt;
   $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)) ;

echo $ext; // txt
?>
goran 14-May-2016 05:16
In case you need add separator at end

$numbers = array('1','2','3','4');
        foreach ($numbers as $number){
            echo $number;
            if (end($numbers) != $number){
                echo ', ';
            }
        }
ivijan dot stefan at gmail dot com 08-May-2014 04:47
I found that the function end() is the best for finding extensions  on file name. This function cleans backslashes and takes the extension of a file.

<?php
private function extension($str){
    $str=implode("",explode("\\",$str));
    $str=explode(".",$str);
    $str=strtolower(end($str));
     return $str;
}

// EXAMPLE:
$file='name-Of_soMe.File.txt';
echo extension($file); // txt
?>

Very simple.
Jason 18-Mar-2013 10:37
$filename = 'somefile.jpg';

php v5.4 does not support the following statement.
echo end(explode(".", $filename)); // return jpg string

instead you have to split into 2 statements
$file = explode(".", $filename);
echo end ($file);
jorge at REMOVETHIS-2upmedia dot com 01-Mar-2012 01:20
If all you want is the last item of the array without affecting the internal array pointer just do the following:

<?php

function endc( $array ) { return end( $array ); }

$items = array( 'one', 'two', 'three' );
$lastItem = endc( $items ); // three
$current = current( $items ); // one
?>

This works because the parameter to the function is being sent as a copy, not as a reference to the original variable.
franz at develophp dot org 01-Dec-2010 03:06
It's interesting to note that when creating an array with numeric keys in no particular order, end() will still only return the value that was the last one to be created. So, if you have something like this:

    <?php
    $a = array();
    $a[1] = 1;
    $a[0] = 0;
    echo end($a);
    ?>

This will print "0".
laurence at crazypillstudios dot com 07-Jun-2010 02:12
this is a function to move items in an array up or down in the array. it is done by breaking the array into two separate arrays and then have a loop creates the final array adding the item we want to move when the counter is equal to the new position we established the array key, position and direction were passed via a query string

<?php
//parameters
//$array- the array you are modifying
//$keytomove - the key of the item you wish to move
//$pos - the current position of the item: used a count($array) function
//and then loop with incrementing integer to add the position to the up //or down button
//$dir - the direction you want to move it - "up"/"dn"

function change_pos($array, $keytomove, $pos, $dir){
    //count the original number of rows
    $count = count($array);
    //set the integer we will use to place the moved item
    if($dir=="up"){
        if($pos==1){
            //if the item is already first and we try moving it up
            //we send it to the end of the array
            $change = $count;
        }else{
            //anywhere else it just moves back one closer to the start of the array
            $change = $pos-1;
        }
    }
    //do the same for the down button
    if($dir=="dn"){
        if($pos==$count){
            $change = 1;
        }else{
            $change = $pos+1;
        }
    }
    //copy the element that you wish to move
    $move = $array[$keytomove];
    //delete the original from the main array
    unset($array[$keytomove]);
    //create an array of the names of the values we
    //are not moving
    $preint = 1;
    foreach($array as $c){
        $notmoved["{$preint}"] = $c['name'];
    $preint++;
    }
    //loop through all the elements
    $int = 1;
    while($int<=$count){
        //dynamically change the key of the unmoved item as we increment the counter
        $notmovedkey = $notmoved["$int"];
        //when the counter is equal to the position we want
        //to place the moved entry we pump it into a new array
        if($int==$change){
            $neworder["{$keytomove}"] = $move;
        }
        //add all the other array items if the position number is not met and
        //resume adding them once the moved item is written
        if($contkey!=""){
            $neworder["{$notmovedkey}"] = $array["{$notmovedkey}"];
        }
    $int++;
    }

    return($neworder);
}
?>

This is not too elegant but it works.
Sam Yong - hellclanner at live dot com 23-Aug-2009 05:05
Take note that end() does not recursively set your multiple dimension arrays' pointer to the end.

Take a look at the following:
<?php

// create the array for testing
$a = array();
$i = 0;
while($i++ < 3){
$a[] = array(dechex(crc32(mt_rand())),dechex(crc32('lol'.mt_rand())));
}

// show the array tree
echo '<pre>';var_dump($a);

// set the pointer of $a to the end
end($a);

// get the current element of $a
var_dump(current($a));
// get the current element of the current element of $a
var_dump(current(current($a)));

?>

You will notice that you probably get something like this:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(8) "764d8d20"
    [1]=>
    string(8) "85ee186d"
  }
  [1]=>
  array(2) {
    [0]=>
    string(8) "c8c72466"
    [1]=>
    string(8) "a0fdccb2"
  }
  [2]=>
  array(2) {
    [0]=>
    string(8) "3463a31b"
    [1]=>
    string(8) "589f6b63"
  }
}

array(2) {
  [0]=>
  string(8) "3463a31b"
  [1]=>
  string(8) "589f6b63"
}

string(8) "3463a31b"

The array elements' pointer are still at the first one as current. So do take note.
jasper at jtey dot com 11-Jul-2006 12:48
This function returns the value at the end of the array, but you may sometimes be interested in the key at the end of the array, particularly when working with non integer indexed arrays:

<?php
// Returns the key at the end of the array
function endKey($array){
 end($array);
 return key($array);
}
?>

Usage example:
<?php
$a = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($a); // will output "three"
?>
ken at expitrans dot com 27-Oct-2005 09:02
Please note that from version 5.0.4 ==> 5.0.5 that this function now takes an array. This will possibly break some code for instance:

<?php

echo ">> ".end(array_keys(array('x' => 'y')))."\n";

?>

which will return "Fatal error: Only variables can be passed by reference" in version <= 5.0.4 but not in 5.0.5.

If you run into this problem with nested function calls, then an easy workaround is to assign the result from array_keys (or whatever function) to an intermediary variable:

<?php

$x = array_keys(array('x' => 'y'));
echo ">> ".end($x)."\n";

?>
28-Aug-2002 06:34
If you need to get a reference on the first or last element of an array, use these functions because reset() and end() only return you a copy that you cannot dereference directly:

<?php
function first(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
reset($array);
return &$array[key($array)];
}

function last(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
end($array);
return &$array[key($array)];
}
?>
28-Aug-2002 06:17
When adding an element to an array, it may be interesting to know with which key it was added. Just adding an element does not change the current position in the array, so calling key() won't return the correct key value; you must first position at end() of the array:

<?php
function array_add(&$array, $value) {
$array[] = $value; // add an element
end($array); // important!
return key($array);
}
?>


Importar variables a la tabla de símbolos actual desde un array

  • « end
  • in_array »
  • PHP Manual
  • Funciones de Arrays
  • Importar variables a la tabla de símbolos actual desde un array

extract

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

extract — Importar variables a la tabla de símbolos actual desde un array

Descripción

extract ( array &$array , int $flags = EXTR_OVERWRITE , string $prefix = null ) : int

Importa variables desde un array a la tabla de símbolos actual.

Comprueba cada clave para ver si tiene un nombre de variable válido. También comprueba las colisiones con las variables existentes en la tabla de símbolos.

Advertencia

No use extract() sobre datos no confiables, como la entrada del usuario (p.e. $_GET, $_FILES).

Parámetros

array

Un array asociativo. Esta función trata a las claves como nombres de variables y a los valores como valores de variables. Por cada par clave/valor creará una variable en la tabla de símbolos actual, sujeta a los parámetros flags y prefix.

Se debe usar un array asociativo; un array indexado numéricamente no producirá resultados a menos que se use EXTR_PREFIX_ALL o EXTR_PREFIX_INVALID.

flags

La manera en que las claves no-válidas/numéricas y las colisiones son tratadas está determinda por el parámetro flags. Puede ser uno de los valores siguientes:

EXTR_OVERWRITE
Si hay una colisión, sobrescribe la variable existente.
EXTR_SKIP
Si hay una colisión, no sobrescribe la variable existente.
EXTR_PREFIX_SAME
Si hay una colisión, prefija el nombre de la variable con prefix.
EXTR_PREFIX_ALL
Prefija todos los nombres de variables con prefix.
EXTR_PREFIX_INVALID
Sólo prefija los nombres de variables no-válidas/numéricas con prefix.
EXTR_IF_EXISTS
Sobrescribe la variable sólo si ya existe en la tabla de símbolos actual, de otro modo no hace nada. Esto es útil para definir una lista de variables válidas y después extraer sólo aquellas variables que se definieron fuera de $_REQUEST, por ejemplo.
EXTR_PREFIX_IF_EXISTS
Crea nombres de variables con prefijo sólo si la versión no prefijada de la misma variable existe en la tabla de símbolos actual.
EXTR_REFS
Extrae las variables como referencias. Esto significa que los valores de las variables importadas están todavía referenciados por los valores del parámetro array. Se puede usar esta bandera por sí misma o combinarla con cualquier otra bandera usando el operador OR en flags.

Si no se especifica flags, se asume que es EXTR_OVERWRITE.

prefix

Observe que prefix sólo es requerido si flags es EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID o EXTR_PREFIX_IF_EXISTS. Si el resultado prefijado no es un nombre de variable válido, ésta no es importada a la tabla de símbolos actual. Los prefijos son separados de las claves del array mediante un caracter de subrayado.

Valores devueltos

Devuelve el número de variables importadas con éxito a la tabla de símbolos.

Ejemplos

Ejemplo #1 Ejemplo de extract()

Un posible uso de extract() es importar a la tabla de símbolos las variables contenidas en un array asociativo devuelto por wddx_deserialize().

<?php

/* Se supone que $var_array es un array devuelto desde
   wddx_deserialize */

$tamaño = "grande";
$var_array = array("color" => "azul",
                   "tamaño"  => "medio",
                   "forma" => "esfera");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $tamaño, $forma, $wddx_tamaño\n";

?>

El resultado del ejemplo sería:

azul, grande, esfera, medio

El $tamaño no se ha sobrescrito ya que se especificó EXTR_PREFIX_SAME, lo que resulta en la creación de $wddx_tamaño. Si se hubiera especificado EXTR_SKIP, $wddx_tamaño no se habría creado. EXTR_OVERWRITE causaría que $tamaño tuviera el valor "medio", y EXTR_PREFIX_ALL resultaría en variables nuevas llamadas $wddx_color, $wddx_tamaño, y $wddx_forma.

Notas

Advertencia

No use extract() en datos que no son de confianza, como las entradas de usuario (esto es, $_GET, $_FILES, etc.). Si lo hace, asegúrese de usar uno de los valores de flags que no sobrescriban, como EXTR_SKIP, y sepa que debería realizar la extracción en el mismo orden que fue definido en variables_order dentro de php.ini.

Ver también

  • compact() - Crear un array que contiene variables y sus valores
  • list() - Asignar variables como si fueran un array

User Contributed Notes

amolocaleb at gmail dot com 26-Jul-2018 05:14
If an object is typecasted into an array and "extracted",only the public properties will be accessible.Methods are of course omitted.
<?php
class Test{
    public $name = '';

    protected $age = 10;

    public $status = 'disabled';

    private $isTrue = false;

    public function __construct()
    {
        $this->name = 'Amolo';
        $this->status = 'active';
    }

    public function getName()
    {
        return $this->name;
    }

    public function getAge()
    {
        return $this->age;
    }

    public function getStatus()
    {
        return $this->status;
    }

}

$obj = (array) new Test();
var_dump($obj);
/* array(4) { ["name"]=> string(5) "Amolo" ["*age"]=> int(10) ["status"]=> string(6) "active" ["TestisTrue"]=> bool(false) } */
extract((array)new Test());
echo  $name; //Amolo
echo  $status; //active
echo $age;//Notice: Undefined variable: age
echo $isTrue;//Notice: Undefined variable: isTrue
phatsk+php at gmail dot com 18-Jun-2018 06:59
Using extract's return parameter can lead to unintended results, particularly with EXTR_REFS:

<?php

$my_data = [
    'count' => 15,
    'name' => 'foo',
];

$count = extract( $my_data, EXTR_REFS );

echo $my_data['count']; // 2, not 15.
mrkhoa99 at gmail dot com 29-May-2018 03:29
We can use extract () function for Template Engine:

<?php
#Template.php

class Template
{
    protected $viewVars;

    public function renderPage($tpl)
    {
        ob_start();
        extract($this->viewVars, EXTR_SKIP);
        include $tpl;
        return ob_end_flush();
    }

    public function assign($arr)
    {
        foreach ($arr as $key => $value) {
            $this->viewVars[$key] = $value;
        }
        return $this;
    }
}

$template = new Template();
$template->assign(
   [ 'pageHeader' => 'Page Header', 'content' => 'This is the content page']
);
$template->renderPage('tpl.php');

#tpl.php

<h1><?= $pageHeader; ?></h1>
<p><?= $content ;?></p>

Output:

Page Header
This is the content page
bob 18-Jan-2015 08:35
Note that extract() will only create or overwrite variables in the current scope, so
<?
function test(){
 $a=Array('b'=>1,'c'=>2);
 extract($a);
}
test();
exit("$b");
?>
will produce no output, whereas
<?
function test(){
 global $b;
 $a=Array('b'=>1,'c'=>2);
 extract($a);
}
test();
exit("$b");
?>
will output 1.
dmikam 18-Sep-2014 10:18
I have made some tests to compare the speed of next constructions:
<?php

extract($ARRAY);

// vs.

foreach($ARRAY as $key=>$value)
    $$key = $value;
?>

Surprisingly for me extract is 20%-80% slower then foreach construction. I don't really understand why, but it's so.
CertaiN 10-Jan-2014 04:38
[New Version]

Example Usage:
<?php
$_GET['A']['a'] = '  CORRECT(including some spaces)    ';
$_GET['A']['b'] = '  CORRECT(including some spaces)    ';
$_GET['A']['c'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['A']['d']['invalid_structure'] = 'INVALID';

$_GET['B']['a'] = '  CORRECT(including some spaces)    ';
$_GET['B']['b'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['B']['c']['invalid_structure'] = 'INVALID';
$_GET['B']["Invalid UTF-8 sequence: \xe3\xe3\xe3"] = 'INVALID';

$_GET['C']['a'] = '  CORRECT(including some spaces)    ';
$_GET['C']['b'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['C']['c']['invalid_structure'] = 'INVALID';
$_GET['C']["Invalid UTF-8 sequence: \xe3\xe3\xe3"] = 'INVALID';

$_GET['unneeded_item'] = 'UNNEEDED';

var_dump(filter_struct_utf8(INPUT_GET, array(
    'A' => array(
        'a' => '',
        'b' => FILTER_STRUCT_TRIM,
        'c' => '',
        'd' => '',
    ),
    'B' => FILTER_STRUCT_FORCE_ARRAY,
    'C' => FILTER_STRUCT_FORCE_ARRAY | FILTER_STRUCT_TRIM,
)));
?>

Example Result:
array(3) {
  ["A"]=>
  array(4) {
    ["a"]=>
    string(36) "  CORRECT(including some spaces)    "
    ["b"]=>
    string(30) "CORRECT(including some spaces)"
    ["c"]=>
    string(0) ""
    ["d"]=>
    string(0) ""
  }
  ["B"]=>
  array(3) {
    ["a"]=>
    string(36) "  CORRECT(including some spaces)    "
    ["b"]=>
    string(0) ""
    ["c"]=>
    string(0) ""
  }
  ["C"]=>
  array(3) {
    ["a"]=>
    string(30) "CORRECT(including some spaces)"
    ["b"]=>
    string(0) ""
    ["c"]=>
    string(0) ""
  }
}
CertaiN 10-Jan-2014 04:37
[New Version]
This function is very useful for filtering complicated array structure.
Also, Some integer bitmasks and invalid UTF-8 sequence detection are available.

Code:
<?php
/**
 * @param  integer $type    Constant like INPUT_XXX.
 * @param  array   $default Default structure of the specified super global var.
 *                          Following bitmasks are available:
 *  + FILTER_STRUCT_FORCE_ARRAY - Force 1 dimensional array.
 *  + FILTER_STRUCT_TRIM        - Trim by ASCII control chars.
 *  + FILTER_STRUCT_FULL_TRIM   - Trim by ASCII control chars,
 *                                full-width and no-break space.
 * @return array            The value of the filtered super global var.
 */
define('FILTER_STRUCT_FORCE_ARRAY', 1);
define('FILTER_STRUCT_TRIM', 2);
define('FILTER_STRUCT_FULL_TRIM', 4);
function filter_struct_utf8($type, array $default) {
    static $func = __FUNCTION__;
    static $trim = "[\\x0-\x20\x7f]";
    static $ftrim = "[\\x0-\x20\x7f\xc2\xa0\xe3\x80\x80]";
    static $recursive_static = false;
    if (!$recursive = $recursive_static) {
        $types = array(
            INPUT_GET => $_GET,
            INPUT_POST => $_POST,
            INPUT_COOKIE => $_COOKIE,
            INPUT_REQUEST => $_REQUEST,
        );
        if (!isset($types[(int)$type])) {
            throw new LogicException('unknown super global var type');
        }
        $var = $types[(int)$type];
        $recursive_static = true;
    } else {
        $var = $type;
    }
    $ret = array();
    foreach ($default as $key => $value) {
        if ($is_int = is_int($value)) {
            if (!($value | (
                FILTER_STRUCT_FORCE_ARRAY |
                FILTER_STRUCT_FULL_TRIM |
                FILTER_STRUCT_TRIM
            ))) {
                $recursive_static = false;
                throw new LogicException('unknown bitmask');
            }
            if ($value & FILTER_STRUCT_FORCE_ARRAY) {
                $tmp = array();
                if (isset($var[$key])) {
                    foreach ((array)$var[$key] as $k => $v) {
                        if (!preg_match('//u', $k)){
                            continue;
                        }
                        $value &= FILTER_STRUCT_FULL_TRIM | FILTER_STRUCT_TRIM;
                        $tmp += array($k => $value ? $value : '');
                    }
                }
                $value = $tmp;
            }
        }
        if ($isset = isset($var[$key]) and is_array($value)) {
            $ret[$key] = $func($var[$key], $value);
        } elseif (!$isset || is_array($var[$key])) {
            $ret[$key] = null;
        } elseif ($is_int && $value & FILTER_STRUCT_FULL_TRIM) {
            $ret[$key] = preg_replace("/\A{$ftrim}++|{$ftrim}++\z/u", '', $var[$key]);
        } elseif ($is_int && $value & FILTER_STRUCT_TRIM) {
            $ret[$key] = preg_replace("/\A{$trim}++|{$trim}++\z/u", '', $var[$key]);
        } else {
            $ret[$key] = preg_replace('//u', '', $var[$key]);
        }
        if ($ret[$key] === null) {
            $ret[$key] = $is_int ? '' : $value;
        }
    }
    if (!$recursive) {
        $recursive_static = false;
    }
    return $ret;
}
?>
FredLawl 13-May-2013 02:56
It is possible to use this as a way to create public attributes for a class.

<?php
class Foo {

  public function __construct ($array) {

      extract($array, EXTR_REFS);
      foreach ($array as $key => $value) {
          $this->$key = $$key;
          // Do: $this->key = $key; if $key is not a string.
      }

  }

}

$array = array(
    'valueOne'      => 'Test Value 1',
    'valueTwo'      => 'Test Value 2',
    'valueThree'    => 'Test Value 3'
);

$foo = new Foo($array);

// Works
echo $foo->valueOne; // Test Value 1
echo $foo->valueTwo; // Test Value 2

// Does not work!
echo $foo::$valueOne; // Fatal error:  Access to undeclared static property: Test::$valueOne
?>
dotslash.lu at gmail.com 29-Apr-2013 12:55
You can't extract a numeric indexed array(e.g. non-assoc array).
<?php
$a = array(
  1,
  2
);
extract($a);
var_dump(${1});
?>

result:
PHP Notice:  Undefined variable: 1 in /Users/Lutashi/t.php on line 7

Notice: Undefined variable: 1 in /Users/Lutashi/t.php on line 7
NULL
Robc 01-Nov-2011 06:30
When extracting from a row after a database query using for example:

$row = mysql_fetch_array($result, MYSQL_ASSOC)
extract($row);

I find that the resultant variables may not match the variable type in the database.  In particular I have found integers in the database may gettype() to string on the extracted variable.
Rodrigo 15-Jun-2010 09:41
Here's a way to use extract in $_FILES arrays without using register_gloabals on.

I started to use extract a few weeks ago, and my codes hasn't been so clean since then. The use of the arrays $_POST and $_GET is ok, but one missed doublequote causes a lot of trouble.

Besides I teach PHP in a school, and this function has made my examples easier.

<?php
if(isset($_FILES["file"])){
    extract($_FILES);
    extract($file);
    echo $name."<br>";
    echo $tmp_name."<br>";
    echo $size."<br>";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form action="" method="post" enctype="multipart/form-data" name="form1">
  <p>
    <input type="file" name="file">
</p>
  <p>
    <input type="submit" name="Submit" value="Enviar">
</p>
</form>
</body>
</html>

Hope this can help anyone.
auto493097 at hushmail dot com 23-Feb-2010 10:07
I use XDebug with NetbeansIDE to for analyzing and developing PHP Code. When debugging an extract statement no new variables appeared in the variable's list. Although all variables created by extract could be examined by explicit watch items and single variables appeared as soon as an PHP script makes use of them I am not sure weather it is a wrong configuration, a feature or a bug in XDebug.
danbettles at yahoo dot co dot uk 24-Aug-2009 04:04
When using EXTR_PREFIX_ALL - and probably all the other EXTR_PREFIX_* constants - and a numerically-indexed array, extract() will add an underscore ("_") between the prefix and the index.

<?php

extract(array('foo', 'bar'), EXTR_PREFIX_ALL, 'var');

print_r(get_defined_vars());  // Reveals $var_0 = 'foo' and $var_1 = 'bar'
?>
benjaminATwebbutvecklarnaDOTse 16-Mar-2008 07:15
In the meantime, I'm using this:

// extract alternative
# extracts variables where new value is above the threshold or if old value is on or below the threshold (or var is not defined)
# an associative array is obviously the sane thing to pass
#
# I am absolutely certain someone will find obvious problems or errors with this
# I haven't even tried to compare other values than 0 so if you need to do that and surely finds obvious flaws,
# please mail me, I'd really like to know.
# benjaminATwebbutvecklarnaDOTse

// usage example:
# thrextract(mysql_fetch_assoc(mysql_query("SELECT preset_this,preset_that FROM site_preset WHERE ID = $site_id")));
# thrextract(mysql_fetch_assoc(mysql_query("SELECT preset_this,preset_that FROM category_preset WHERE ID = $category_id")));

function thrextract($arr,$thr = 0){
    foreach($arr as $key => $var){
        global $$key;
        if($var > $thr or $$key <= $thr) $$key = $var;
    }
}
benjaminATwebbutvecklarnaDOTse 16-Mar-2008 06:19
Re: anon at anon dot org, about extract() and null values

Personally I've found use extracting multiple resultsets from db where the latter would overwrite the previous when a variable is not null ( and optionally if its not >0 )

It would be useful if $extract_type was extended on top of these two:

EXTR_OVERWRITE
EXTR_SKIP

with something like this:

EXTR_OVERWRITE_NULL
 - If there is a collision, overwrite the existing variable if it is null

EXTR_OVERWRITE_0
 - Same thing but == 0 or null

EXTR_SKIP_NULL
 - If there is a collision, skip the new variable if the existing is not null

EXTR_SKIP_0
 - Same thing but == 0 or null

Those ought to cover a few good cases that aren't covered now.
Hayley Watson 13-Mar-2008 03:18
Dan O'Donnell's suggestion needs a third requirement to work as described:

c) No other variables are defined - especially variables that contain potentially sensitive information.

Without that condition the difference between extract() and assigning variables by hand (and the resulting security implications) should be obvious.

The only valid security step there is (b) - but you should be doing that anyway.
Dan O'Donnell 21-Apr-2007 12:25
Following up on ktwombley at gmail dot com's post:

Presumably one easy way of dealing with this security issue is to use the EXTR_IF_EXISTS flag and make sure

a) your define acceptable input variables beforehand (i.e. as empty variables)
b) Sanitise any user input to avoid unacceptable variable content.

If you do these two things, then I'm not sure I see the difference between extract($_REQUEST,EXTR_IF_EXISTS); and assigning each of the variables by hand.

I'm not talking here about the idea of storing the variables in a database, just the immediately necessary steps to allow you to use extract on REQUEST arrays with relative safety.
Dutchdavey 13-Mar-2007 12:26
I would draw your attention to the user note at the very end of this page regarding PREFIXES. The user points out that php adds a '_' to your prefixes.
ktwombley at gmail dot com 31-Aug-2006 10:05
It's really easy to open gaping security holes using extract() on $_REQUEST, $_GET, etc. You have to be really sure of what you're doing, and use the proper flags on extract() to avoid clobbering important variables.

For instance, the submission by kake26 at gmail dot com will not only perfectly emulate register globals (that's bad), but it'll store it in a database and recall the same variables every time the script runs (essentially allowing an attacker to attack your script every time it runs via one attack). Oops!

To fix it, you'd have to get creative with flags. Maybe you could use EXTR_PREFIX_ALL instead of EXTR_OVERWRITE, for example. Of course, you should also sanitize the form elements to ensure there's no php code in them, and also to make sure any very important variables aren't in the form data. (like the classic $is_admin = true attack)
nicolas zeh 16-Mar-2006 09:24
This function provides exactly the same functionality as extract except that a parameter was added defining the extract target.
This function can be used if your PHP installation does not support the required Flags or more important if you would like to extract arrays to another destination as to $GLOBALS, i.e. other arrays or objects.
The only difference to extract is that extract_to moves the array pointer of $arr to the end as $arr is passed by reference to support the EXTR_REFS flag.

<?php
    if( !defined('EXTR_PREFIX_ALL') ) define('EXTR_PREFIX_ALL', 3);
    if( !defined('EXTR_PREFIX_INVALID') ) define('EXTR_PREFIX_INVALID', 4);
    if( !defined('EXTR_IF_EXISTS') ) define('EXTR_IF_EXISTS', 5);
    if( !defined('EXTR_PREFIX_IF_EXISTS') ) define('EXTR_PREFIX_IF_EXISTS', 6);
    if( !defined('EXTR_REFS') ) define('EXTR_REFS', 256);

    function extract_to( &$arr, &$to, $type=EXTR_OVERWRITE, $prefix=false ){

        if( !is_array( $arr ) ) return trigger_error("extract_to(): First argument should be an array", E_USER_WARNING );

        if( is_array( $to ) ) $t=0;
        else if( is_object( $to ) ) $t=1;
        else return trigger_error("extract_to(): Second argument should be an array or object", E_USER_WARNING );

        if( $type==EXTR_PREFIX_SAME || $type==EXTR_PREFIX_ALL || $type==EXTR_PREFIX_INVALID || $type==EXTR_PREFIX_IF_EXISTS )
            if( $prefix===false ) return trigger_error("extract_to(): Prefix expected to be specified", E_USER_WARNING );
            else $prefix .= '_';

        $i=0;
        foreach( $arr as $key=>$val ){

            $nkey = $key;
            $isset = $t==1 ? isset( $to[$key] ) : isset( $to->$key );

            if( ( $type==EXTR_SKIP && $isset )
                || ( $type==EXTR_IF_EXISTS && !$isset ) )
                    continue;

            else if( ( $type==EXTR_PREFIX_SAME && $isset )
                || ( $type==EXTR_PREFIX_ALL )
                || ( $type==EXTR_PREFIX_INVALID && !preg_match( '#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $key ) ) )
                    $nkey = $prefix.$key;

            else if( $type==EXTR_PREFIX_IF_EXISTS )
                if( $isset ) $nkey = $prefix.$key;
                else continue;

            if( !preg_match( '#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $nkey ) ) continue;

            if( $t==1 )
                if( $type & EXTR_REFS ) $to->$nkey = &$arr[$key];
                else $to->$nkey = $val;
            else
                if( $type & EXTR_REFS ) $to[$nkey] = &$arr[$key];
                else $to[$nkey] = $val;

            $i++;
        }

        return $i;
    }

    // e.g.:
    extract_to( $myarray, $myobject, EXTR_IF_EXISTS );
?>
owk dot ch199_ph at gadz dot org 08-Mar-2006 04:21
And if you want with PHP 5 an easy way to extract $V by reference, try this :
<?php
    foreach ($V as $k => &$v) {
        $$k =& $v;
    }
?>
It can be used to create special kind of "free args" functions that let you choose when you call them the way you send variables, and which ones. They are moreover very fast to call thanks to references :
<?php
    function free_args (&$V) {
        foreach ($V as $k => &$v) {
            $$k =& $v;
        }
        unset ($k);  unset ($v);  unset ($V);

        // be careful that if you need to extract $k, $v or $V variables you should find other names for them in the lines above (ie. $__k, $__v and $__V)
    }

    $huge_text = '...';

    $a = array ('arg1' => 'val1', 'arg2' => &$huge_text); // in this call, only $arg2 will be a true reference in the function
    free_args ($a);
?>
Be warned that you can't write : "<?php free_args (array ('arg1' => 'val1')); ?>" because the array can't be referenced by the function, as it's not yet created when the function starts.
moslehi<atsign>gmail<d0t>c0m 20-Jan-2006 01:32
Experimentally I found that calling extract() also shows the number of keys if the key is set and is not numeric ! Maybe there was a better definition than mine  . Please have a look to this scripts :

<?PHP
$var["i"] = "a";
$var["j"] = "b";
$var["k"] = 1;
echo extract($var); // returns 3
?>

<?PHP
$var2["i"] = "a";
$var2[2] = "b";
$var2[] = 1;
echo extract($var2); // returns 1
?>

(Arash Moslehi)
Csaba at alum dot mit dot edu 27-Nov-2005 11:41
Sometimes you may want to extract only a named subset of the key/value pairs in an array.  This keeps things more orderly and could prevent an unrelated variable from getting clobbered from an errant key.  For example,

$things = 'unsaid';
$REQUEST = array(He=>This, said=>1, my=>is, info=>2, had=>a,
                 very=>3, important=>test, things=>4);
$aVarToExtract = array(my, important, info);
extract (array_intersect_key ($REQUEST, array_flip($aVarToExtract)));

will extract
$my = 'is';
$important = 'test';
$info = 2;

but will leave certain
$things = 'unsaid'

Csaba Gabor from Vienna
NB.  Of course the composite request coming in from a web page is in $_REQUEST.
anon at anon dot org 30-May-2005 12:02
A warning about extract() and null values.

This might be an actual Zend2 Engine bug, but it's bad programming practice, so I'm sharing it here instead.

I often work in envrionments where E_STRICT (which would prevent errors like this) isn't on, and I don't have access to change it. I also use a very simple template class that in a nutshell works like this:

$t = new Template('somefile.php');
$t->title = $title;
$t->body = $body;
$t->display();

display() more or less looks like this:

function display(){
    extract(get_object_vars($this),EXTR_REFS);
    ob_start(); include $this->templateFileName;
    return ob_get_clean();
}

If any of the assigned values are null (let's say that in this case $title wasn't initialized above) it causes the engine to do all sorts of incredibly whacky stuff like certifiably lose track of variables in an incredibly inconsistent way. I traced the problem down to the fact that it's using the EXTR_REFS flag. I assume that in PHP's internal variable storage or reference counting mechanism, that trying to extract null references makes it lose track or count of something or rather.

In a nutshell, if you start getting wierd behavior when using extract() make sure that the array or object you are trying to get variables out of doesn't contain null keys or values!
kake26 at gmail dot com 30-Apr-2005 08:59
The following is a neat use for extract to store and manipulate large amounts of form data from. I basically loop through the $_POST and implode it seperating the key and value pairs by a space. Then store it in a db, the reversing function basically explodes the string to a array. Then converts the indexed array to a associative array then uses extract to seal the deal and make it easily available within a program. My main reason for sharing these are the fact I make some big web applications that store allot of forum data in a DB and these functions make it very easy to quickly and easily store and recall the data. I've contributed it because I spent many hours creating this code and recall going "I wish someone had previously submitted it to the page notes". Would have saved me allot of time and agony and I'm sure I'm not the only person that could really benefit from it, so I decided to share.

<?php
$stack = array();
foreach ($_POST as $key => $value) {
array_push($stack, $key, $value);
}
// store it
$block = implode(" ",$stack); // yeilds a space delimited string
// insert query to store string in DB here, like the one below
$query = "INSERT INTO `sometable` VALUES('".$seluser."','".addslashes($block)."');";
$result = mysql_query($query) or die("Query failed for block insert: " . mysql_error());
// note $seluser in my case is a user ID associated with that block
// in one of my web apps
?>

The nice thing is with the above we can quickly create a string of key and value pairs from the data the script got. Without really caring what their names are. You know how if register globals are on you say $someformvar rather than $_POST["someformvar"]; , basically the code below reads this previous created block returns it to that state. Sort of like presistant register globals.

<?php
// insert query to grab the previously stored string here
$query = "SELECT * FROM `sometable` WHERE `blockid` = '".addslashes($bid)."';";
$result = mysql_query($query) or die("Query failed read: " . mysql_error());
$sql = mysql_fetch_array($result, MYSQL_ASSOC);
$array = eplode(" ",$sql["data"]);
for ($i = 0; $i < sizeof($array); $i+=2) {
$myassoc[$array[$i]] = isset($array[$i+1])?$array[$i+1]:NULL;
}
extract($myassoc, EXTR_OVERWRITE);
// now you're key and value pairs from $_POST have been restored
// instead of $_POST
?>
pg dot perfection at gmail dot com 14-Mar-2005 02:33
Here is a little example of how an extraction method should look like when it needs to work recursive (work on nested_arrays too)...

Note that this is only an example, it can be done more easily, and more advanced too.

<?php
/**
 * A nested version of the extract () function.
 *
 * @param    array    $array        The array which to extract the variables from
 * @param    int        $type        The type to use to overwrite (follows the same as extract () on PHP 5.0.3
 * @param    string    $prefix        The prefix to be used for a variable when necessary
 */
function extract_nested (&$array, $type = EXTR_OVERWRITE, $prefix = '')
{
    /**
     *  Is the array really an array?
     */
    if (!is_array ($array))
    {
        return trigger_error ('extract_nested (): First argument should be an array', E_USER_WARNING);
    }

    /**
     *  If the prefix is set, check if the prefix matches an acceptable regex pattern
     * (the one used for variables)
     */
    if (!empty ($prefix) && !preg_match ('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $prefix))
    {
        return trigger_error ('extract_nested (): Third argument should start with a letter or an underscore', E_USER_WARNING);
    }

    /**
     * Check if a prefix is necessary. If so and it is empty return an error.
     */
    if (($type == EXTR_PREFIX_SAME || $type == EXTR_PREFIX_ALL || $type == EXTR_PREFIX_IF_EXISTS) && empty ($prefix))
    {
        return trigger_error ('extract_nested (): Prefix expected to be specified', E_USER_WARNING);
    }

    /**
     * Make sure the prefix is oke
     */
    $prefix = $prefix . '_';

    /**
     *  Loop thru the array
     */
    foreach ($array as $key => $val)
    {
        /**
         *  If the key isn't an array extract it as we need to do
         */
        if (!is_array ($array[$key]))
        {
            switch ($type)
            {
                default:
                case EXTR_OVERWRITE:
                    $GLOBALS[$key] = $val;
                break;
                case EXTR_SKIP:
                    $GLOBALS[$key] = isset ($GLOBALS[$key]) ? $GLOBALS[$key] : $val;
                break;
                case EXTR_PREFIX_SAME:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                    else
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_PREFIX_ALL:
                    $GLOBALS[$prefix . $key] = $val;
                break;
                case EXTR_PREFIX_INVALID:
                    if (!preg_match ('#^[a-zA-Z_\x7f-\xff]$#', $key{0}))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                    else
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_IF_EXISTS:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_PREFIX_IF_EXISTS:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                break;
                case EXTR_REFS:
                    $GLOBALS[$key] =& $array[$key];
                break;
            }
        }
        /**
         *  The key is an array... use the function on that index
         */
        else
        {
            extract_nested ($array[$key], $type, $prefix);
        }
    }
}
?>
Michael Newton 02-Mar-2005 05:23
They say "If the result is not a valid variable name, it is not imported into the symbol table."

What they should say is that if _any_ of the results have invalid names, _none_ of the variables get extracted.

Under 4.3.10 on Windows 2000, I was pulling some mySQL records, but needed to convert two fields into IP addresses:
<?
extract(mysql_fetch_assoc(mysql_query('SELECT * FROM foo')));
extract(mysql_fetch_assoc(mysql_query('SELECT INET_NTOA(bar) AS bar, INET_NTOA(baz) FROM foo')));
?>

I had forgotten the second AS modifier in the SQL query.  Because it couldn't extract a variable called INET_NTOA(baz) into the symbol table, it didn't do either of them.

(BTW I don't normally stack functions up like that!  Just to make a short example!)
21-Feb-2005 07:31
To make this perfectly clear (hopefully), an underscore is always added when the string is prefixed.
extract(array("color" => "blue"),EXTR_PREFIX_ALL,'');// note: prefix is empty
is the same as
$color='_blue';
Aaron Stone 17-Nov-2004 10:44
If you are working porting an older application, and taking the advice above, extracting only _SERVER, _SESSING, _COOKIE, _POST, _GET, you have forgotten to extract _FILES. Putting _FILES last and using EXTR_SKIP doesn't work because the name of the file upload box is already set as a variable containing only the temporary name of the uploaded file from one of the earlier extracts (I haven't tested to see which one specifically, however). A workaround is to put _FILES last and use EXTR_OVERWRITE. This allows extract to replace that temp-name-only variable with the full array of file upload information.
Adam Monsen <adamm at wazamatta dot com> 02-Oct-2004 05:03
As shown in the example, if your 'prefix' is used, a single underscore is added to the name of the extracted variable. Meaning, a prefix of 'p' becomes a prefix of 'p_', so 'blarg' prefixed would be 'p_blarg'.

If you're not sure what variables you've created through extraction, you can call get_defined_vars() to see all defined variables in the current scope.


Comprueba si un valor existe en un array

  • « extract
  • key_exists »
  • PHP Manual
  • Funciones de Arrays
  • Comprueba si un valor existe en un array

in_array

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

in_array — Comprueba si un valor existe en un array

Descripción

in_array ( mixed $needle , array $haystack , bool $strict = false ) : bool

Busca la aguja (needle) en el pajar (haystack) usando una comparación flexible a menos que esté establecido strict.

Parámetros

needle

El valor a buscar.

Nota:

Si needle es un string, la comparación se realiza considerando las mayúsculas/minúsculas.

haystack

El array.

strict

Si el tercer parámetro strict está establecido a true, la función in_array() también comprobará los tipos de needle en haystack.

Valores devueltos

Devuelve true si needle se encuentra en el array, false de lo contrario.

Ejemplos

Ejemplo #1 Ejemplo de in_array()

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Existe Irix";
}
if (in_array("mac", $os)) {
    echo "Existe mac";
}
?>

La segunda condición falla porque in_array() considera las mayúsculas-minúsculas, así que el programa anterior mostrará:

Existe Irix

Ejemplo #2 Ejemplo de in_array() en modo estricto

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
    echo "Se encontró '12.4' con comprobación estricta\n";
}

if (in_array(1.13, $a, true)) {
    echo "Se encontró 1.13 con comprobación estricta\n";
}
?>

El resultado del ejemplo sería:

Se encontró 1.13 con comprobación estricta

Ejemplo #3 in_array() con un array como aguja

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "Se encontró 'ph'\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "Se encontró 'fi'\n";
}

if (in_array('o', $a)) {
    echo "Se encontró 'o'\n";
}
?>

El resultado del ejemplo sería:

  Se encontró 'ph'
  Se encontró 'o'

Ver también

  • array_search() - Busca un valor determinado en un array y devuelve la primera clave correspondiente en caso de éxito
  • isset() - Determina si una variable está definida y no es null
  • array_key_exists() - Verifica si el índice o clave dada existe en el array

User Contributed Notes

ethraza at gmail dot com 04-Dec-2020 02:53
A function to check an array of values within another array.

<?php
/**
 * Return TRUE if any value in neddles exists in haystack (values or keys) or FALSE.
 */
function array_in_array_exists($aNeedles, $aHaystack_values, $aHaystack_keys = null) {
    $needles = (is_string($aNeedles))? explode(',', $aNeedles) : $aNeedles;

    if (is_array($aHaystack_values)) {
        $search_func = 'in_array';
        $haystack = $aHaystack_values;
    } else {
        $search_func = 'array_key_exists';
        $haystack = $aHaystack_Keys;
    }

    return !empty(array_filter($needles, function($e) use ($search_func, $haystack) {
            return call_user_func($search_func, $e, $haystack);
    } ));
}

// Usage example:
var_dump( array_in_array_exists(array('000', '123'), array('123','456')) );
?>
bool(true)

Second element '123' of needles was found as first element of haystack, so it return TRUE.
reiji_nakama at yahoo dot com 22-Sep-2020 03:21
The top voted notes talked about creating strict comparison function, because in_array is insufficient, because it has very lenient type checking (which is PHP default behaviour).

The thing is, in_array is already sufficient. Because as a good programmer, you should never have an array which contains {true, false, 0, 1, '0', '1', null, '', 'hello world'}; all in one array anyway.

It's better to fix how you store data and retrieve data from user, rather than fixing in_array() which is not broken.
fermar21 at gmail dot com 25-May-2020 02:51
If you need to find if a value in an array is in another array you can use the function:

<?php
function array_in_array($arr_needle,$arr_haystack){
    $retorno = false;
    foreach ($arr_needle as $value) {
        if(in_array($value, $arr_haystack)){
            $retorno = true;
        }
    }
    return $retorno;
}
?>
Camille Dugas 06-Nov-2019 03:09
<?php

class Method {

    /** @var int current number of inMultiArray() loop */
    private static $currentMultiArrayExec = 0;

    /**
     * Checks if an element is found in an array or one of its subarray.
     * The verification layer of this method is limited to the parameter boundary xdebug.max_nesting_level of your php.ini.
     * @param mixed $element
     * @param array $array
     * @param bool $strict
     * @return bool
     */
    public static function inMultiArray($element, array $array, bool $strict = true) : bool {
        self::$currentMultiArrayExec++;

        if(self::$currentMultiArrayExec >= ini_get("xdebug.max_nesting_level")) return false;

        foreach($array as $key => $value){
            $bool = $strict ? $element === $key : $element == $key;

            if($bool) return true;

            if(is_array($value)){
                $bool = self::inMultiArray($element, $value, $strict);
            } else {
                $bool = $strict ? $element === $value : $element == $value;
            }

            if($bool) return true;
        }

        self::$currentMultiArrayExec = 0;
        return isset($bool) ? $bool : false;
    }
}

$array = array("foo" => array("foo2", "bar"));
$search = "foo";

if(Method::inMultiArray($search, $array, false)){
    echo $search . " it is found in the array or one of its sub array.";
} else {
    echo $search . " was not found.";
}

# foo it is found in the array or one of its sub array.
loordu 20-Sep-2019 11:16
In PHP array function the in_array() function mainly used to check the item are available or not in array.

In_array() Syntax:

in_array( 'search_item' , $array, boolean)

Where,
     boolean - It is used to check strict validation. And this field is optional one. If you want the strict validation you can use this.

We using in_array() function to performing following following two function. That is ,

1. Non-strict validation
2. Strict validation

1. Non-strict validation:
     This method to validate array with some negotiation. And it allow two parameters.

     For example,
          $array_sample = array (  'key1' => 567 , 'key2' => 579);

          in_array('key1', $array_sample);   // output1:  true
          in_array('577', $array_sample, false);   // output2:  true

      Note: the Example 1, we use only two parameter. Because we can't mention `false` value. Because In default the in_array() take `false` as a boolean value.

      In above example,
             Example 1 : The `key1` is not value in the array.    This is key of the array. So this scenario the in_array accept the search key as a value of the array.
             Example 2: The value `577` is not in the value and key of the array. It is some similar to the value `579`. So this is also accepted.

     So this reason this type is called non-strict function.

2. Strict validation
     This method to validate array without any negotiation. And it have three parameters. If you only mention two parameter the `in_array()` function take as a non-strict validation.

     For example,
          $array_sample = array (  'key1' => 567 , 'key2' => 579);

          in_array('key1', $array_sample , true);   // output1:  false
          in_array('577', $array_sample, true);   // output2:  false

    This is return `true` only the search string is match exactly with the array value with case sensitivity.

Thanks for your time.
artem dot g dot prozorov at gmail dot com 04-Sep-2019 11:43
in_array() may also return NULL if the second argument is NULL and strict types are off.

<?php
var_dump(in_array(1, null));
?>

The output is NULL

If the strict mode is on, then this code would end up with the TypeError
roman dot varuta at gmail dot com 06-Nov-2018 01:53
If array contain at least one true value, in_array() will return true every times if it is not false or null

Use strict = true

<?php

$arr = array(true);

in_array($any, $arr); // Will return true every time except null and false

?>
iammanjil at gmail dot com 25-Oct-2018 08:00
If third parameter is not set to Strict then, the needle is found in haystack eventhought the values are not same. the limit behind the decimal seems to be 6 after which, the haystack and needle match no matter what is behind the 6th.

Wrong Response.
$os = array("652875063.10089021");
if (in_array("652875063.10089021", $os)) {
    echo "In Array";
}

Correct Response
$os = array("652875063.1008902");
if (in_array("652875063.1008901", $os)) {
    echo "In Array";
}
msegit post pl 18-Jul-2018 12:20
You can use my function inArray, to search:
- multidimensional arrays
- for substrings (case [in]sensitive)
- for sub-arrays
- get array of keys of found values
Look at github https://gist.github.com/msegu/80093a65316ded5b69558d5456f80ff9 (here is too long)
Carmen 15-Feb-2018 11:16
Esta función falla con las letras acentuadas y con las eñes. Por tanto, no sirve para los caracteres UTF-8.
El siguiente código falla para na cadena = "María Mañas", no reconoce ni la "í" ni la "ñ":

    function validarNombreYApellidos ($cadena, $selector)
    {
        /* Se admiten las letras (he puesto sólo las mayusculas,
             porque paso la cadena con el nombre o
             el apellido a mayúscula antes de hacer la comparación),
             las vocales acentuadas, la diéresis,
             las eñes, los espacios en blanco y el guión
            (para los apellidos compuestos)*/
        $caracteresPermitidos =
               array ("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", " ", "Á", "É", "Í", "Ó", "Ú", "Ü", "-");

        $correcto = true;

        // ¿La cadena está vacía?
        if (empty ($cadena))
        {
            $correcto = false;
        }
        else
        {
            $nombreOapellido = mb_strtoupper ($cadena, "utf-8");
            $longitudCadena = mb_strlen ($cadena, "utf-8");

            for ($i = 0; ($i < $longitudCadena) && $correcto; $i++)
            {
                if (!in_array ($nombreOapellido [$i],
                                     $caracteresPermitidos))
                {
                    // Se ha encontrado un carácter no permitido
                    $correcto = false;
                }
            }
        }
            return $correcto;
     }
Carmen 15-Feb-2018 11:15
Esta función falla con las letras acentuadas y con las eñes. Por tanto, no sirve para los caracteres UTF-8.
El siguiente código falla para na cadena = "María Mañas", no reconoce ni la "í" ni la "ñ":

    function validarNombreYApellidos ($cadena, $selector)
    {
        /* Se admiten las letras (he puesto sólo las mayusculas,
             porque paso la cadena con el nombre o
             el apellido a mayúscula antes de hacer la comparación),
             las vocales acentuadas, la diéresis,
             las eñes, los espacios en blanco y el guión
            (para los apellidos compuestos)*/
        $caracteresPermitidos =
               array ("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", " ", "Á", "É", "Í", "Ó", "Ú", "Ü", "-");

        $correcto = true;

        // ¿La cadena está vacía?
        if (empty ($cadena))
        {
            $correcto = false;
        }
        else
        {
            $nombreOapellido = mb_strtoupper ($cadena, "utf-8");
            $longitudCadena = mb_strlen ($cadena, "utf-8");

            for ($i = 0; ($i < $longitudCadena) && $correcto; $i++)
            {
                if (!in_array ($nombreOapellido [$i],
                                     $caracteresPermitidos))
                {
                    // Se ha encontrado un carácter no permitido
                    $correcto = false;
                }
            }
        }
            return $correcto;
     }
Geoffrey Hoffman 04-Aug-2017 04:00
Be careful to use the strict parameter with truth comparisons of specific strings like "false":

<?php

$truthy = [true, 'true', 1, '1', 'y', 'Y', 'yes', 'YES'];

if (in_array('false', $truthy)) {
   echo "False is truthy.\n";
} else {
   echo "False is not truthy.\n";
}

if (in_array('false', $truthy, true)) {
    echo "False is truthy.\n";
} else {
    echo "False is not truthy.\n";
}

?>

The above example prints:

False is truthy.
False is not truthy.
stocki dot r at gmail dot com 02-Jun-2017 02:56
Add an extra if() to adrian foeder's comment to make it work properly:

<?php
    ...
    if (!@$ret) {
        $ret = rec_in_array($needle, $element, $alsokeys);
    }
    ...
?>

So this will work, too:

<?php
    $array = array(
        array('a', 'b'),
        array('c', 'd')
    );
    var_dump(rec_in_array('a', $array));
?>
rhuan at rhuan dot com dot br 31-Dec-2016 11:29
This code will search for a value in a multidimensional array with strings or numbers on keys.

function in_multiarray($elem, $array)
{
    while (current($array) !== false) {
        if (current($array) == $elem) {
            return true;
        } elseif (is_array(current($array))) {
            if (in_multiarray($elem, current($array))) {
                return true;
            }
        }
        next($array);
    }
    return false;
}
hoopyfroop at yahoo dot com 11-Nov-2016 02:14
If you search for numbers, in_array will convert any strings in your array to numbers, dropping any letters/characters, forcing a numbers-to-numbers comparison. So if you search for 1234, it will say that '1234abcd' is a match.  Example:

<?php
$test_array = array('test', '1234abcd');
if (in_array(1234, $test_array)) {
    echo '1234 is a match!';
}
?>
tjamadeira at gmail dot com 29-Jan-2016 07:17
This function is for search a needle in a multidimensional haystack:

<?php
/**
 * A special function for search in a multidimensional array a needle
 *
 * @param mixed needle The searched variable
 * @param array haystack The array where search
 * @param bool strict It is or it isn't a strict search?
 *
 * @return bool
 **/
function in_array_r($needle, $haystack, $strict = false){
 foreach($haystack as $item){
   if(is_array($item)){
     if(in_array_r($needle, $item, $strict)){
       return true;
     }
   }else{
     if(($strict ? $needle === $item : $needle == $item)){
       return true;
     }
   }
 }
 return false;
}
?>
splogamurugan at gmail dot com 06-Nov-2015 11:49
var_dump(in_array('invalid', array(0,10,20)));
The above code gives true since the 'invalid' is getting converted to 0 and checked against the array(0,10,20)

but var_dump(in_array('invalid', array(10,20)));  gives 'false' since 0 not there in the array
dazero0 dot ls at gmail dot com 24-Sep-2015 10:43
I would like to add something to beingmrkenny at gmail dot com comparison post. After debugging a system, i discovered a security issue in our system and his post helped me find the problem.

In my additional testing i found out that not matter what you search for in an array, except for 0 and null, you get true as the result if the array contains true as the value.

Examples as php code :

<?php
$a = ['a', 32, true, 'x' => y];
var_dump(in_array(25, $a)); // true, one would expect false
var_dump(in_array('ggg', $a)); // true, one would expect false

var_dump(in_array(0, $a)); // false
var_dump(in_array(null, $a)); // false
?>

Such the best practice in our case is to use strict mode. Which was not so obvious.
Harry Willis 24-Jan-2015 11:39
Kelvin's case-insensitive in_arrayi is fine if you desire loose typing, but mapping strtolower onto the array will (attempt to) cast all array members to string. If you have an array of mixed types, and you wish to preserve the typing, the following will work:

<?php
function in_array_ci($needle, array $haystack, $strict = false) {
    foreach ($haystack as $element) {
        if (gettype($needle) == 'string' && gettype($element) == 'string') {
            if (!strcasecmp($needle, $element)) {
                return true;
            }
        }
        elseif ($strict) {
            if ($needle === $element) {
                return true;
            }
        }
        else {
            if ($needle == $element) {
                return true;
            }
        }
    }

    return false;
}
?>
what loose checking means 20-Jan-2014 05:03
In a high-voted example, an array is given that contains, amongst other things, true, false and null, against which various variables are tested using in_array and loose checking.

It impossible to receive false as a return value from in_array using loose checking if your arrays contains both the constants true and false. You might understandably trip over this (or the inverse - passing boolean true to check against an array of e.g. non-empty strings), but it's certainly not counter intuitive and makes perfect sense.
rolf dot dergham dot public at gmail dot com 13-Jan-2014 01:02
Watch out for this:

<?

print_r( (int) in_array('hello',array( 0 => 0)) );

?>

returns 1

Yes, it seems that is_array thinks that a random string and 0 are the same thing.
Excuse me, that's not loose checking, that's drunken logic.
Or maybe I found a bug?
Valerchik 13-May-2013 07:30
Beware when using this function to validate user input:

$a = array('0' => 'Opt 1', '1' => 'Opt 2', '2' => 'Opt 3');
$v = 'sql injection';
var_dump(in_array($v, array_keys($a)));

This will result : true;

array_keys($a) will cast array keys to int instead of string !
then when in_array will compare it will cast  'sql injection' to int 0 !
Beware of this!
janis dot janovskis at gmail dot com 28-Feb-2012 11:03
Since sometimes in_array returns strange results - see notes above.
I was able to find value in array by this quite a simple function;
<?php
/**
* $find <mixed> value to find
* $array<array> array to search in
*/

function _value_in_array($array, $find){
 $exists = FALSE;
 if(!is_array($array)){
   return;
}
foreach ($array as $key => $value) {
  if($find == $value){
       $exists = TRUE;
  }
}
  return $exists;
}

// Note
// You can't use wildcards and it does not check variable type
?>
beingmrkenny at gmail dot com 27-Oct-2011 03:35
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP's leniency on variable types, but in "real-life" is almost useless.

The solution is to use the strict checking option.

<?php

// Example array

$array = array(
    'egg' => true,
    'cheese' => false,
    'hair' => 765,
    'goblins' => null,
    'ogres' => 'no ogres allowed in this array'
);

// Loose checking -- return values are in comments

// First three make sense, last four do not

in_array(null, $array); // true
in_array(false, $array); // true
in_array(765, $array); // true
in_array(763, $array); // true
in_array('egg', $array); // true
in_array('hhh', $array); // true
in_array(array(), $array); // true

// Strict checking

in_array(null, $array, true); // true
in_array(false, $array, true); // true
in_array(765, $array, true); // true
in_array(763, $array, true); // false
in_array('egg', $array, true); // false
in_array('hhh', $array, true); // false
in_array(array(), $array, true); // false

?>
Lea Hayes 04-Aug-2011 05:40
Determine whether an object field matches needle.

Usage Example:
---------------

<?php
$arr = array( new stdClass(), new stdClass() );
$arr[0]->colour = 'red';
$arr[1]->colour = 'green';
$arr[1]->state  = 'enabled';

if (in_array_field('red', 'colour', $arr))
   echo 'Item exists with colour red.';
if (in_array_field('magenta', 'colour', $arr))
   echo 'Item exists with colour magenta.';
if (in_array_field('enabled', 'state', $arr))
   echo 'Item exists with enabled state.';
?>

Output:
--------
Item exists with colour red.
Item exists with enabled state.

<?php
function in_array_field($needle, $needle_field, $haystack, $strict = false) {
    if ($strict) {
        foreach ($haystack as $item)
            if (isset($item->$needle_field) && $item->$needle_field === $needle)
                return true;
    }
    else {
        foreach ($haystack as $item)
            if (isset($item->$needle_field) && $item->$needle_field == $needle)
                return true;
    }
    return false;
}
?>
ctulek at gmail dot com 30-Aug-2010 11:07
If you have an array like:
$arr = array(0,1,2,3,4,5);

in_array(NULL, $arr) returns true because you have 0 in your array. That is, in_array does not use === for equal check.
bogdan AT bogdanconstantinescu DOT com 21-Apr-2010 08:01
If you found yourself in need of a multidimensional array in_array like function you can use the one below. Works in a fair amount of time

<?php

    function in_multiarray($elem, $array)
    {
        $top = sizeof($array) - 1;
        $bottom = 0;
        while($bottom <= $top)
        {
            if($array[$bottom] == $elem)
                return true;
            else
                if(is_array($array[$bottom]))
                    if(in_multiarray($elem, ($array[$bottom])))
                        return true;

            $bottom++;
        }
        return false;
    }
?>
jv at vip dot ie 13-Feb-2010 04:46
If you're working with very large 2 dimensional arrays (eg 20,000+ elements) it's much faster to do this...

<?php
$needle = 'test for this';

$flipped_haystack = array_flip($haystack);

if ( isset($flipped_haystack[$needle]) )
{
  print "Yes it's there!";
}
?>

I had a script that went from 30+ seconds down to 2 seconds (when hunting through a 50,000 element array 50,000 times).

Remember to only flip it once at the beginning of your code though!
thomas dot sahlin at gmail dot com 05-Oct-2009 12:53
If you're creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it's much faster.

<?php

$slow = array('apple', 'banana', 'orange');

if (in_array('banana', $slow))
    print('Found it!');

$fast = array('apple' => 'apple', 'banana' => 'banana', 'orange' => 'orange');

if (isset($fast['banana']))
    print('Found it!');

?>
john at dwarven dot co dot uk 01-Jul-2009 04:34
I just struggled for a while with this, although it may be obvious to others.

If you have an array with mixed type content such as:

<?php

 $ary = array (
   1,
   "John",
   0,
   "Foo",
   "Bar"
 );

?>

be sure to use the strict checking when searching for a string in the array, or it will match on the 0 int in that array and give a true for all values of needle that are strings strings.

<?php

var_dump( in_array( 2, $ary ) );

// outputs FALSE

var_dump( in_array( 'Not in there', $ary ) );

// outputs TRUE

var_dump( in_array( 'Not in there', $ary, TRUE ) );

// outputs FALSE

?>
Kelvin J 28-Feb-2009 05:04
For a case-insensitive in_array(), you can use array_map() to avoid a foreach statement, e.g.:

<?php
    function in_arrayi($needle, $haystack) {
        return in_array(strtolower($needle), array_map('strtolower', $haystack));
    }
?>
rhill at xenu-directory dot net 17-Jan-2009 01:05
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

<?php

$needle = array(
    'fruit'=>'banana', 'vegetable'=>'carrot'
    );

$haystack = array(
    array('vegetable'=>'carrot', 'fruit'=>'banana'),
    array('fruit'=>'apple', 'vegetable'=>'celery')
    );

echo in_array($needle, $haystack, true) ? 'true' : 'false';
// Output is 'false'

echo in_array($needle, $haystack) ? 'true' : 'false';
// Output is 'true'

?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether 'strict' is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.
crashrox at gmail dot com 21-Jul-2008 08:34
Recursive in array using SPL

<?php
function in_array_recursive($needle, $haystack) {

    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack));

    foreach($it AS $element) {
        if($element == $needle) {
            return true;
        }
    }

    return false;
}
?>
Martijn Wieringa 19-May-2008 02:20
When using numbers as needle, it gets tricky:

Note this behaviour (3rd statement):

in_array(0, array(42)) = FALSE
in_array(0, array('42')) = FALSE
in_array(0, array('Foo')) = TRUE
in_array('0', array('Foo')) = FALSE
sick949 at hotmail dot com 05-Mar-2008 03:43
A first idea for a function that checks if a text is in a specific column of an array.
It does not use in_array function because it doesn't check via columns.
Its a test, could be much better. Do not use it without test.

<?php

function in_array_column($text, $column, $array)
{
    if (!empty($array) && is_array($array))
    {
        for ($i=0; $i < count($array); $i++)
        {
            if ($array[$i][$column]==$text || strcmp($array[$i][$column],$text)==0) return true;
        }
    }
    return false;
}

?>
musik at krapplack dot de 04-Jun-2006 05:52
I needed a version of in_array() that supports wildcards in the haystack. Here it is:

<?php
function my_inArray($needle, $haystack) {
    # this function allows wildcards in the array to be searched
    foreach ($haystack as $value) {
        if (true === fnmatch($value, $needle)) {
            return true;
        }
    }
    return false;
}

$haystack = array('*krapplack.de');
$needle = 'www.krapplack.de';

echo my_inArray($needle, $haystack); # outputs "true"
?>

Unfortunately, fnmatch() is not available on Windows or other non-POSIX compliant systems.

Cheers,
Thomas
adrian foeder 08-Nov-2005 01:21
hope this function may be useful to you, it checks an array recursively (if an array has sub-array-levels) and also the keys, if wanted:

<?php
function rec_in_array($needle, $haystack, $alsokeys=false)
    {
        if(!is_array($haystack)) return false;
        if(in_array($needle, $haystack) || ($alsokeys && in_array($needle, array_keys($haystack)) )) return true;
        else {
            foreach($haystack AS $element) {
                $ret = rec_in_array($needle, $element, $alsokeys);
            }
        }

        return $ret;
    }
?>
Aragorn5551 at gmx dot de 11-Jun-2005 05:26
If you have a multidimensional array filled only with Boolean values like me, you need to use 'strict', otherwise in_array() will return an unexpected result.

Example:

<?php
$error_arr = array('error_one' => FALSE, 'error_two' => FALSE, array('error_three' => FALSE, 'error_four' => FALSE));

if (in_array (TRUE, $error_arr)) {
   echo 'An error occurred';
}
else {
   echo 'No error occurred';
}
?>

This will return 'An error occurred' although theres no TRUE value inside the array in any dimension. With 'strict' the function will return the correct result 'No error occurred'.

Hope this helps somebody, cause it took me some time to figure this out.


Alias de array_key_exists

  • « in_array
  • key »
  • PHP Manual
  • Funciones de Arrays
  • Alias de array_key_exists

key_exists

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

key_exists — Alias de array_key_exists()

Descripción

Esta función es un alias de: array_key_exists().

User Contributed Notes

There are no user contributed notes for this page.


Obtiene una clave de un array

  • « key_exists
  • krsort »
  • PHP Manual
  • Funciones de Arrays
  • Obtiene una clave de un array

key

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

key — Obtiene una clave de un array

Descripción

key ( array $array ) : mixed

key() devuelve el elemento índice de la posición actual del array.

Parámetros

array

El array.

Valores devueltos

La función key() simplemente devuelve la clave del elemento del array que está apuntando actualmente el puntero interno. No desplaza el puntero de ninguna manera. Si el puntero interno señala más allá del final de la lista de elementos o el array está vacío, key() devuelve null.

Historial de cambios

Versión | Descripción
7.0.0 | array ahora siempre se pasa por el valor. Antes de esta versión, se pasaba por referencia si era posible, y por el valor de lo contrario.

Ejemplos

Ejemplo #1 Ejemplo de key()

<?php
$array = array(
    'fruta1' => 'manzana',
    'fruta2' => 'naranja',
    'fruta3' => 'uva',
    'fruta4' => 'manzana',
    'fruta5' => 'manzana');

// Este ciclo muestra todas las claves del array asociativo
// donde el valor equivale a "manzana"
while ($nombre_fruta = current($array)) {
    if ($nombre_fruta == 'manzana') {
        echo key($array).'<br />';
    }
    next($array);
}
?>

El resultado del ejemplo sería:

fruta1<br />
fruta4<br />
fruta5<br />

Ver también

  • current() - Devuelve el elemento actual en un array
  • next() - Avanza el puntero interno de un array
  • foreach

User Contributed Notes

Md Tahazzot 13-Dec-2019 06:02
(Editor note: Or just use the array_keys function)

Make as simple as possible but not simpler like this one :)

$k = array();
for($i = 0; $i < count($arr); $i++){
    $k[$i] = key($arr);
    next($arr);
}
danielmadsv at gmail dot com 24-Mar-2019 01:07
In addition to FatBat's response, if you'd like to find out the highest key in an array (assoc or not) but don't want to arsort() it, take a look at this:

<?php

$arr = [ '3' => 14, '1' => 15, '4' => 92, '15' => 65 ];

$key_of_max = array_search( max($arr) , $arr);

?>
lhardie 23-Apr-2014 04:05
Note that using key($array) in a foreach loop may have unexpected results.

When requiring the key inside a foreach loop, you should use:
foreach($array as $key => $value)

I was incorrectly using:
<?php
foreach($array as $value)
{
  $mykey = key($array);
}
?>

and experiencing errors (the pointer of the array is already moved to the next item, so instead of getting the key for $value, you will get the key to the next value in the array)

CORRECT:
<?php
foreach($array as $key => $value)
{
  $mykey = $key;
}

A noob error, but felt it might help someone else out there.
vinob44 at gmail dot com 23-Oct-2013 11:43
Suppose if the array values are in numbers and numbers contains `0` then the loop will be terminated. To overcome this you can user like this

<?php
$array = array(
    '0' => '5',
    '1' => '2',
    '2' => '0',
    '3' => '3',
    '4' => '1');

// wrong approach

while ($fruit_name = current($array)) {

        echo key($array).'<br />';
       next($array);
}

// the way will be break loop when arra('2'=>0) because its value is '0', while(0) will terminate the loop

// correct approach
while ( ($fruit_name = current($array)) !== FALSE ) {

        echo key($array).'<br />';
       next($array);
}
//this will work properly
?>
FatBat 17-Oct-2011 12:20
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>


Ordena un array por clave en orden inverso

  • « key
  • ksort »
  • PHP Manual
  • Funciones de Arrays
  • Ordena un array por clave en orden inverso

krsort

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

krsort — Ordena un array por clave en orden inverso

Descripción

krsort ( array &$array , int $sort_flags = SORT_REGULAR ) : bool

Ordena un array por clave en orden inverso, manteniendo la correlación entre la clave y los datos. Esto es útil principalmente para arrays asociativos.

Parámetros

array

El array de entrada.

sort_flags

Se puede modificar el comportamiento del ordenado usando el parámetro opcional sort_flags, par más información vea sort().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de krsort()

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

El resultado del ejemplo sería:

d = lemon
c = apple
b = banana
a = orange

Ver también

  • arsort() - Ordena un array en orden inverso y mantiene la asociación de índices
  • ksort() - Ordena un array por clave
  • comparación de funciones de orden de arrays

User Contributed Notes

07-Aug-2005 06:37
To create a natural reverse sorting by keys, use the following function:

<?php
function natkrsort($array)
{
    $keys = array_keys($array);
    natsort($keys);

    foreach ($keys as $k)
    {
        $new_array[$k] = $array[$k];
    }

    $new_array = array_reverse($new_array, true);

    return $new_array;
}
?>
peter at pmkmedia dot com 07-Nov-2003 01:51
Best deal sorting:

This is a function that will sort an array with integer keys (weight) and float values (cost) and delete 'bad deals' - entries that are more costly than other entries that have greater or equal weight.

Input: an array of unsorted weight/cost pairs
Output: none

function BEST_DEALS($myarray)
{   // most weight for least cost:
    // ? Peter Kionga-Kamau, http://www.pmkmedia.com
    // thanks to Nafeh for the reversal trick
    // free for unrestricted use.
    krsort($myarray, SORT_NUMERIC);
    while(list($weight, $cost) = each($myarray))
    {   // delete bad deals, retain best deals:
        if(!$lastweight)
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
        else if($cost >= $lastcost) unset($myarray[$weight]);
        else
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
    }
    ksort($myarray);
}


Ordena un array por clave

  • « krsort
  • list »
  • PHP Manual
  • Funciones de Arrays
  • Ordena un array por clave

ksort

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

ksort — Ordena un array por clave

Descripción

ksort ( array &$array , int $sort_flags = SORT_REGULAR ) : bool

Ordena un array por clave, manteniendo la correlación entre la clave y los datos. Esto es útil principalmente para arrays asociativos.

Parámetros

array

El array de entrada.

sort_flags

Se puede modificar el comportamiento del ordenado usando el parámetro opcional sort_flags, par más información vea sort().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de ksort()

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

El resultado del ejemplo sería:

a = orange
b = banana
c = apple
d = lemon

Ver también

  • asort() - Ordena un array y mantiene la asociación de índices
  • comparación de funciones de orden de arrays

User Contributed Notes

orlov0562 at gmail dot com 07-Jul-2017 01:13
The first thing that I didn't find in description it's that this function return results from MIN value to MAX value, ex: [-5=>'', 0=>'', 5=>'' ]

Also you should know that by default, it has correct sorting for keys that represented as string but has a number as value, ex: ['-5'=>'', '0'=>'', '5'=>'' ]

Few examples with results:

-----------------------------------------

DESCRIPTION: Keys are numbers + default flag (SORT_REGULAR)

$arr = [
    -5 => 'minus five',
    0 => 'zero',
    1 => 'one',
    2 => 'two',
    100 => 'hundred',
];

ksort($arr);
print_r($arr);

RESULT:

Array
(
    [-5] => minus five
    [0] => zero
    [1] => one
    [2] => two
    [100] => hundred
)

-----------------------------------------
DESCRIPTION: Keys are string numbers + default flag (SORT_REGULAR)

$arr = [
    '-5' => 'minus five',
    '0' => 'zero',
    '1' => 'one',
    '2' => 'two',
    '100' => 'hundred',
];

ksort($arr);
print_r($arr);

RESULT:

Array
(
    [-5] => minus five
    [0] => zero
    [1] => one
    [2] => two
    [100] => hundred
)

-----------------------------------------
DESCRIPTION: Keys are string numbers + SORT_STRING flag

$arr = [
    '-5' => 'minus five',
    '0' => 'zero',
    '1' => 'one',
    '2' => 'two',
    '100' => 'hundred',
];

ksort($arr, SORT_STRING);
print_r($arr);

RESULT:

Array
(
    [-5] => minus five
    [0] => zero
    [1] => one
    [100] => hundred
    [2] => two
)

-----------------------------------------

DESCRIPTION: Keys are string numbers + SORT_NUMERIC flag

$arr = [
    '-5' => 'minus five',
    '0' => 'zero',
    '1' => 'one',
    '2' => 'two',
    '100' => 'hundred',
];

ksort($arr, SORT_NUMERIC);
print_r($arr);

RESULT:

Array
(
    [-5] => minus five
    [0] => zero
    [1] => one
    [2] => two
    [100] => hundred
)
bimal at sanjaal dot com 26-May-2014 07:33
An example of reverse sorting a domain name by its name.

<?php
$domains = array(
    'sub.domain.com',
    'sub2.domain.com',
);

foreach($domains as $d => $domain)
{
    $chunks = explode('.', $domain);
    krsort($chunks);

    echo "\r\n<br>", implode('/', $chunks);
}

/**
 * Outputs as:
 *
 * com/domain/sub
 * com/domain/sub2
 */
?>
Anonymous 10-Feb-2014 05:43
@thegrandoverseer

you could also use the build-in php array functions to get exactly what you want to have:

<?php
        $seed_array = array('foo'=>'bar', 'someotherkey'=>'whatev', 'bar'=>'baz', 'baz'=>'foo', 'anotherkey'=>'anotherval');
        $keys_array = array('baz', 'foo', 'bar');

        $return_array = array_intersect_key($seed_array, array_flip($keys_array)) + array_diff_key($seed_array, array_flip($keys_array));

?>
Anonymous 13-Aug-2013 01:11
Note that this function will output the given $fields in the order they were added to the data array and not automatically in numerical key order.

To output in ascending key order, you'll need to ksort the array first (or use appropriate natural order sorting, depending on your keys).

For example:
<?php
$data[2] = 'C';
$data[0] = 'A';
$data[1] = 'B';

fputcsv($fh, $data); // outputs: "C,A,B"

ksort($data);
fputcsv($fh, $data); // outputs: "A,B,C"
?>
centraleffects at yahoo dot com 06-Jun-2013 05:46
I wrote this function to sort meta_value in wordpress. I tried a lot of array sorting but neither of them work. But this is not suitable for multidimensional array. This is intended only for wordpress meta_value

The problem is to sort below( the order should be ascending; alphabetically then numerically like A-Z then 0-9):
500-999 users
25-49 users
 All Sizes
1-4 users
5-9 users
10-24 users
250-499 users
1000-4999
5000-9999

The solution:

function array_sort($arr){
    if(is_array($arr)){
        $numeric = array();
        $string = array();
        foreach($arr as $k => $v)
        {
            if(isset($v["meta_value"])){
                 $str = explode(" ",trim($v["meta_value"]));
                 $firstWord  = explode("-",trim($str[0]));
             }else{
                 $str = $v;
                 $firstWord  = explode("-",trim($str));
             }

            $firstWord = $firstWord[0];

            if(is_numeric($firstWord))
            {
                $numeric[(int)$firstWord] = $v;
            }else{
                $string[$firstWord] = $v;
            }
            unset($firstWord);
        }
        ksort($string,SORT_STRING);
        ksort($numeric,SORT_NUMERIC);

        return array_merge((array)$string, (array)$numeric);
    }

    return false;
}

The usage:
$meta =get_post_meta($post_id,$meta_key);
$sorted = array_sort($meta);

The result:
 All Sizes
1-4 users
5-9 users
10-24 users
25-49 users
250-499 users
500-999 users
1000-4999
5000-9999
stephen [ at ] brooksie-net [ dot ] co [ dot ] uk 17-Apr-2013 05:10
ksort and krsort fail to undestand scientific notation, https://bugs.php.net/bug.php?id=43053, therefore when sorting numeric keys, if the key is of the form 0.00001 php will represent it as 1.0E-5.

These methods will assume this to be a string and therefore not organise your array as you may expect.

When using value of this form for array keys use sprintf('%f', 0.00001) to generate the key, for smaller values the precision needs to be included
e.g. sprintf('%0.10f', 0.00000001)
thegrandoverseer 13-Jul-2012 06:11
I wrote this function to sort the keys of an array using an array of keynames, in order.
<?php
/**
 * function array_reorder_keys
 * reorder the keys of an array in order of specified keynames; all other nodes not in $keynames will come after last $keyname, in normal array order
 * @param array &$array - the array to reorder
 * @param mixed $keynames - a csv or array of keynames, in the order that keys should be reordered
 */
function array_reorder_keys(&$array, $keynames){
    if(empty($array) || !is_array($array) || empty($keynames)) return;
    if(!is_array($keynames)) $keynames = explode(',',$keynames);
    if(!empty($keynames)) $keynames = array_reverse($keynames);
    foreach($keynames as $n){
        if(array_key_exists($n, $array)){
            $newarray = array($n=>$array[$n]); //copy the node before unsetting
            unset($array[$n]); //remove the node
            $array = $newarray + array_filter($array); //combine copy with filtered array
        }
    }
}
$seed_array = array('foo'=>'bar', 'someotherkey'=>'whatev', 'bar'=>'baz', 'baz'=>'foo', 'anotherkey'=>'anotherval');
array_reorder_keys($seed_array, 'baz,foo,bar'); //returns array('baz'=>'foo', 'foo'=>'bar', 'bar'=>'baz', 'someotherkey'=>'whatev', 'anotherkey'=>'anotherval' );
?>
jakub dot lopuszanski at nasza-klasa dot pl 14-Apr-2011 08:48
Note that ksort will NOT help you much if numeric and string keys are mixed together.
<?php
$t = array(
  "a"=>"A",
  0=>"A",
  "b"=>"A",
  1=>"A"
);
var_dump($t);
ksort($t);
var_dump($t);
?>

produces (on PHP 5.3.6-4 with Suhosin-Patch) :

array(4) {
  ["a"]=>
  string(1) "A"
  [0]=>
  string(1) "A"
  ["b"]=>
  string(1) "A"
  [1]=>
  string(1) "A"
}

array(4) {
  ["b"]=>
  string(1) "A"
  [0]=>
  string(1) "A"
  ["a"]=>
  string(1) "A"
  [1]=>
  string(1) "A"
}

note that the second array should be sorted by keys, but is even more messed up than the first one!
DavidG 17-Jun-2010 06:47
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:

<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));

var_dump($people);

$sortArray = array();

foreach($people as $person){
    foreach($person as $key=>$value){
        if(!isset($sortArray[$key])){
            $sortArray[$key] = array();
        }
        $sortArray[$key][] = $value;
    }
}

$orderby = "name"; //change this to whatever key you want from the array

array_multisort($sortArray[$orderby],SORT_DESC,$people);

var_dump($people);
?>

Output from first var_dump:

[0]=&gt;
  array(3) {
    ["name"]=&gt;
    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    string(6) "purple"
  }
}

Output from 2nd var_dump:

array(3) {
  [0]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    string(6) "purple"
  }

There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.
serpro at gmail dot com 13-Mar-2009 02:02
Here is a function to sort an array by the key of his sub-array.

<?php

function sksort(&$array, $subkey="id", $sort_ascending=false) {

    if (count($array))
        $temp_array[key($array)] = array_shift($array);

    foreach($array as $key => $val){
        $offset = 0;
        $found = false;
        foreach($temp_array as $tmp_key => $tmp_val)
        {
            if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
            {
                $temp_array = array_merge(    (array)array_slice($temp_array,0,$offset),
                                            array($key => $val),
                                            array_slice($temp_array,$offset)
                                          );
                $found = true;
            }
            $offset++;
        }
        if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
    }

    if ($sort_ascending) $array = array_reverse($temp_array);

    else $array = $temp_array;
}

?>

Example
<?php
$info = array("peter" => array("age" => 21,
                                           "gender" => "male"
                                           ),
                   "john"  => array("age" => 19,
                                           "gender" => "male"
                                           ),
                   "mary" => array("age" => 20,
                                           "gender" => "female"
                                          )
                  );

sksort($info, "age");
var_dump($info);

sksort($info, "age", true);
var_dump($ifno);
?>

This will be the output of the example:

/*DESCENDING SORT*/
array(3) {
  ["peter"]=>
  array(2) {
    ["age"]=>
    int(21)
    ["gender"]=>
    string(4) "male"
  }
  ["mary"]=>
  array(2) {
    ["age"]=>
    int(20)
    ["gender"]=>
    string(6) "female"
  }
  ["john"]=>
  array(2) {
    ["age"]=>
    int(19)
    ["gender"]=>
    string(4) "male"
  }
}

/*ASCENDING SORT*/
array(3) {
  ["john"]=>
  array(2) {
    ["age"]=>
    int(19)
    ["gender"]=>
    string(4) "male"
  }
  ["mary"]=>
  array(2) {
    ["age"]=>
    int(20)
    ["gender"]=>
    string(6) "female"
  }
  ["peter"]=>
  array(2) {
    ["age"]=>
    int(21)
    ["gender"]=>
    string(4) "male"
  }
}
maik dot riechert at animey dot net 12-Aug-2008 11:32
Be careful when using ksort for mixed type keys!!

$a = array(
    'first' => true,
    0       => 'sally',
);

$b = array(
    0       => 'sally',
    'first' => true,
);

ksort($a);
ksort($b);
var_dump($a);
var_dump($b);

Output is:
array(
    0 => 'sally',
    'first' => true,
)

array(
    'first' => true,
    0 => 'sally',
)

If you want same results for both arrays, use:

ksort($a, SORT_STRING);

The reason for that lays in the compare mechanism which would normally just typecast 'first' to an integer or 0 to a string when comparing it to each other. So you have to use SORT_STRING, otherwise you would lose information when 'first' is converted to int.
ssb45 at cornell dot edu 30-Jun-2005 04:58
The function that justin at booleangate dot org provides works well, but be aware that it is not a drop-in replacement for ksort as is.  While ksort sorts the array by reference and returns a status boolean, natksort returns the sorted array, leaving the original untouched.  Thus, you must use this syntax:

$array = natksort($array);

If you want to use the more natural syntax:

$status = natksort($array);

Then use this modified version:

function natksort(&$array) {
    $keys = array_keys($array);
    natcasesort($keys);

    foreach ($keys as $k) {
        $new_array[$k] = $array[$k];
    }

    $array = $new_array;
    return true;
}
justin at booleangate dot org 18-Jan-2005 01:04
Here's a handy function for natural order sorting on keys.

function natksort($array) {
  // Like ksort but uses natural sort instead
  $keys = array_keys($array);
  natsort($keys);

  foreach ($keys as $k)
    $new_array[$k] = $array[$k];

  return $new_array;
}
09-Mar-2002 07:09
here 2 functions to ksort/uksort an array and all its member arrays

function tksort(&$array)
  {
  ksort($array);
  foreach(array_keys($array) as $k)
    {
    if(gettype($array[$k])=="array")
      {
      tksort($array[$k]);
      }
    }
  }

function utksort(&$array, $function)
  {
  uksort($array, $function);
  foreach(array_keys($array) as $k)
    {
    if(gettype($array[$k])=="array")
      {
      utksort($array[$k], $function);
      }
    }
  }
delvach at mail dot com 06-Nov-2001 01:29
A real quick way to do a case-insensitive sort of an array keyed by strings:

uksort($myArray, "strnatcasecmp");
sbarnum at mac dot com 19-Oct-2001 03:54
ksort on an array with negative integers as keys yields some odd results.  Not sure if this is a bad idea (negative key values) or what.


Asignar variables como si fueran un array

  • « ksort
  • natcasesort »
  • PHP Manual
  • Funciones de Arrays
  • Asignar variables como si fueran un array

list

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

list — Asignar variables como si fueran un array

Descripción

list ( mixed $var1 , mixed ...$... = ? ) : array

Al igual que array(), no es realmente una función, es un constructor del lenguaje. list() se utiliza para asignar una lista de variables en una sola operación.

Nota:

list() solo funciona con arrays numéricos y supone que los índices numéricos empiezan en 0.

Advertencia

En PHP 5, list() asigna los valores empezando desde el parámetro más a la derecha. En PHP 7, list() empieza desde el parámetro más a la izquierda.

Si se emplean variables simples, esto no debería ser un problema. Pero se en emplean arrays con índices, normalmente se espera que el orden de los índices sea el mismo que el escrito en list(), de izquierda a derecha, no siendo este el caso en PHP 5, ya que se asignan en orden inverso.

En términos generales, se aconseja evitar depender de un orden específico de operación debido a que este podría cambiar de nuevo en el futuro.

Advertencia

La modificación del array durante la ejecución de list() (p.ej. usando list($a, $b) = $b) resultará en un comportamiento indefinido.

Parámetros

var1

Una variable.

Valores devueltos

Devuelve el array asignado.

Historial de cambios

Versión | Descripción
7.0.0 | El orden en el que se realizan las operaciones de asignación ha cambiado.
7.0.0 | Las expresiones de list() ya no pueden estar completamente vacías.
7.0.0 | Los strings ya no pueden ser desempaquetados.

Ejemplos

Ejemplo #1 Ejemplos de list()

<?php

$info = array('café', 'marrón', 'cafeína');

// Enumerar todas las variables
list($bebida, $color, $energía) = $info;
echo "El $bebida es $color y la $energía lo hace especial.\n";

// Enumerar algunas de ellas
list($bebida, , $energía) = $info;
echo "El $bebida tiene $energía.\n";

// U omitir solo la tercera
list( , , $energía) = $info;
echo "Necesito $energía!\n";

// list() no funciona con cadenas
list($bar) = "abcde";
var_dump($bar); // NULL
?>

Ejemplo #2 Un ejemplo del uso de list()

<table>
 <tr>
  <th>Nombre del empleado</th>
  <th>Salario</th>
 </tr>

<?php

$resultado = $pdo->query("SELECT id, nombre, salario FROM empleados");
while (list($id, $nombre, $salario) = $resultado->fetch(PDO::FETCH_NUM)) {
    echo " <tr>\n" .
          "  <td><a href=\"info.php?id=$id\">$nombre</a></td>\n" .
          "  <td>$salario</td>\n" .
          " </tr>\n";
}

?>

</table>

Ejemplo #3 Empleo de list() anidados

<?php

list($a, list($b, $c)) = array(1, array(2, 3));

var_dump($a, $b, $c);

?>
int(1)
int(2)
int(3)

Ejemplo #4 Uso de list() con índices de array

<?php

$info = array('café', 'marrón', 'cafeína');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>

Muestra la siguiente salida (nótese el orden de los elementos comparado con el orden escrito en la sintaxis de list()):

array(3) {
  [2]=>
  string(8) "cafeína"
  [1]=>
  string(7) "marrón"
  [0]=>
  string(5) "café"
}

Ejemplo #5 list() y orden de definiciones de índices

El orden en el que están definidos los índices de los arrays que consume list() es irrelevante.

<?php
$foo = array(2 => 'a', 'foo' => 'b', 0 => 'c');
$foo[1] = 'd';
list($x, $y, $z) = $foo;
var_dump($foo, $x, $y, $z);

Da el siguiente resultado (observe el orden de los elementos comparado con el orden en el que están escritos en la sintaxis de list()):

array(4) {
  [2]=>
  string(1) "a"
  ["foo"]=>
  string(1) "b"
  [0]=>
  string(1) "c"
  [1]=>
  string(1) "d"
}
string(1) "c"
string(1) "d"
string(1) "a"

Ver también

  • each() - Devolver el par clave/valor actual de un array y avanzar el cursor del array
  • array() - Crea un array
  • extract() - Importar variables a la tabla de símbolos actual desde un array

User Contributed Notes

samraskul at gmail dot com 27-Feb-2021 08:53
list($a, $b, $c) = ["blue", "money", 32];

shortcut:

[$a, $b, $c] = ["blue", "money", 32];
sergey dot leonidovich dot shevchenko at gmail dot com 12-Feb-2021 01:17
['a' => $x, 'b' => $y] = ['a' => 1, 'b' => 2];

echo $x . '-' . $y; // 1-2
mark at manngo dot net 30-Dec-2020 03:46
For PHP 7.1 on, the documentation states that integer and string keys can be mixed, but that elements with and without keys cannot. Here is an example, using data from getimagesize() with mixed keys:

<?php
    $data=[
        0=> 160,
        1 => 120,
        2 => 2,
        3 => 'width="160" height="120"',
        'mime' => 'image/jpeg'
    ];
    list(0=>$width,1=>$height,2=>$type,3=>$dimensions,'mime'=>$mime)=$data;
?>

Here, the numeric keys also need to be specified, as if the whole array is treated as an associative array.

As noted elsewhere, the list() operator can be written in array format:

<?php
    [0=>$width,1=>$height,2=>$type,3=>$dimensions,'mime'=>$mime]=$data;
?>
fredsaavedra at hotmail dot com 18-Feb-2020 04:03
Easy way to get actual date and time values in variables.

list($day,$month,$year,$hour,$minute,$second) = explode('-',date('d-m-Y-G-i-s'));
echo "$day-$month-$year $hour".":".$minute.":".$second;
vike2000 at gmail dot com 23-Jan-2020 03:49
Setting it like <?php list($var1,$varN) = null ?> does _not_ raise an E_NOTICE (or other error) and afaics effectively equals an https://php.net/function.unset of $var1,$varN.

I note this as contrasting with the fact that PHP triggers an E_NOTICE about "Undefined offset" "if there aren't enough array elements to fill the list()", as attow documented for https://php.net/control-structures.foreach#control-structures.foreach.list and here only noted in https://php.net/function.list#122951 by Mardaneus.

For completeness, a bash(1) (v5.0 or 4.3 on macos10.13) cli test producing the same result for all my PHP-versions (installed via macports.org) follows. It's also tested with php7.3 using bash5.0 on Debian10:
bash --noprofile --norc -c 'for php in php{{53..56},{70..73}};do for literal in "array()" null;do echo -n $php …=$literal:&&$php -n -d error_reporting=E_ALL -r "var_dump(list(\$var)=$literal);";done;done'

# Above produces the same result pairs per version from:
php53 …=array():
Notice: Undefined offset: 0 in Command line code on line 1
array(0) {
}
# ... to:
php73 …=null:NULL
JD 23-Sep-2019 11:24
As of PHP 7.3, lists now support array destructuring - see here: https://www.php.net/manual/en/migration73.new-features.php
Paul Marti 02-Jul-2019 09:45
Since 7.1.0, you can use an array directly without list():

<?php
[$test, $test2] = explode(",", "hello, world");
echo $test . $test2; // hello, world
?>
Mardaneus 17-Jul-2018 08:14
Unless you specify keys when using list() it expects the array being fed into it to start at 0.

So having the following code will result in a notice level warning "Undefined offset: 0" and variables not filling as expected

<?php
list($c1, $c2, $c3) = array [1 =>'a', 2 => 'b', 3 => 'c'];

var_dump($c1); // NULL
var_dump($c2); // string(1) "a"
var_dump($c3); // string(1) "b"

?>
petru at fuxspam dot xtremeweb dot ro 13-Apr-2018 10:11
This is something I haven't seen in documentation.

Since PHP 7.1, you can use short-hand list unpacking using square brackets, just like short-hand array declaration:

<?php

$foo = ['a', 'b', 'c'];

// short-hand array definition
[$a, $b, $c] = $foo;
echo $a; // displays "a"

// it's same like:
list($x, $y, $z) = $foo;
echo $x; // displays "a"

?>
contato at tobias dot ws 28-Mar-2018 07:22
Since PHP 7.1 the [] may now be used as an alternative to the existing list() syntax:

<?php
[$number, $message] = explode('|', '123|Hello World!');
?>
blazej 31-Aug-2017 02:00
From PHP Version 7.1 you can specify keys in list(), or its new shorthand [] syntax. This enables destructuring of arrays with non-integer or non-sequential keys.

<?php
$data = [
    ["id" => 1, "name" => 'Tom'],
    ["id" => 2, "name" => 'Fred'],
];

// list() style
list("id" => $id1, "name" => $name1) = $data[0];

// [] style
["id" => $id1, "name" => $name1] = $data[0];

// list() style
foreach ($data as list("id" => $id, "name" => $name)) {
    // logic here with $id and $name
}

// [] style
foreach ($data as ["id" => $id, "name" => $name]) {
    // logic here with $id and $name
}
grzeniufication 27-May-2017 04:01
<?php
/**
 * It seems you can skip listed values.
 * Here's an example to show what I mean.
 *
 * FYI works just as well with PHP 7.1 shorthand list syntax.
 * Tested against PHP 5.6.30, 7.1.5
 */
$a = [ 1, 2, 3, 4 ];

// this is quite normal use case for list
echo "Unpack all values\n";
list($v1, $v2, $v3, $v4) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

// this is what I mean:
echo "Skip middle\n";
list($v1, , , $v4) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

echo "Skip beginning\n";
list( , , $v3, $v4) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

echo "Skip end\n";
list($v1, $v2, , ) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

echo "Leave middle\n";
list( , $v2, $v3, ) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);
Rhamnia Mohamed 17-May-2017 11:37
Since PHP 7.1, keys can be specified

exemple :
<?php
$array = ['locality' => 'Tunis', 'postal_code' => '1110'];

list('postal_code' => $zipCode, 'locality' => $locality) = $array;

print $zipCode; // will output 1110
print $locality; // will output Tunis
 ?>
carlosv775 at gmail dot com 12-Jan-2017 08:30
In PHP 7.1 we can do the following:

<?php
    [$a, $b, $c] = ['a', 'b', 'c'];
?>

Before, we had to do:

<?php
    list($a, $b, $c) = ['a', 'b',  'c'];
?>
anthony dot ossent at live dot fr 23-Oct-2016 03:04
a simple example of use to swap two variables :

$a = 'hello';
$b = 'world';

list($a, $b) = [$b, $a];

echo $a . ' ' . $b; //display "world hello"

another example :

function getPosition($x, $y, $z)
{
   // ... some operations like $x++...
   return [$x, $y, $z];
}

list($x, $y, $z) = getPosition($x ,$y, $z);
pemapmodder1970 at gmail dot com 05-Feb-2016 04:08
list() can be used with foreach

<?php
$array = [[1, 2], [3, 4], [5, 6]];

foreach($array as list($odd, $even)){
    echo "$odd is odd; $even is even", PHP_EOL;
}
?>

The output:
===
1 is odd; 2 is even
3 is odd; 4 is even
5 is odd; 6 is even
Dean 10-Dec-2015 07:20
UNDOCUMENTED BEHAVIOR:

    list($a,$b,$c) = null;

in fact works like:

    $a = null; $b = null; $c = null;

...So correspondingly:

    list($rows[]) = null;

Will increment count($rows), just as if you had executed $rows[] = null;

Watch out for this (for example) when retrieving entire tables from a database, e.g.

    while (list($rows[]) = $mysqlresult->fetch_row());

This will leave an extra 'null' entry as the last element of $rows.
Colin Guthrie 20-Jul-2015 01:41
If you want use the undefined behaviour as you might expect it e.g. if you want:

  $b = ['a','b']; list($a, $b) = $b;

to result in $a=='a' and $b=='b', then you can just cast $b to an array (even although it already is) to create a copy. e.g.

  $b = ['a','b']; list($a, $b) = (array)$b;

and get the expected results.
grzeniufication 21-Oct-2014 10:35
The example showing that:

$info = array('kawa', 'brazowa', 'kofeina');
list($a[0], $a[1], $a[2]) = $info;
var_dump($a);

outputs:
array(3) {
[2]=>
string(8) "kofeina"
[1]=>
string(5) "brazowa"
[0]=>
string(6) "kawa"
}

One thing to note here is that if you define the array earlier, e.g.:
$a = [0, 0, 0];

the indexes will be kept in the correct order:

array(3) {
  [0]=>
  string(4) "kawa"
  [1]=>
  string(8) "brazowa"
  [2]=>
  string(7) "kofeina"
}

Thought that it was worth mentioning.
john at jbwalker dot com 08-Dec-2013 12:31
The list construct seems to look for a sequential list of indexes rather taking elements in sequence. What that obscure statement means is that if you unset an element, list will not simply jump to the next element and assign that to the variable but will treat the missing element as a null or empty variable:

    $test = array("a","b","c","d");
    unset($test[1]);
    list($a,$b,$c)=$test;
    print "\$a='$a' \$b='$b' \$c='$c'<BR>";

results in:
$a='a' $b='' $c='c'

not:
$a='a' $b='c' $c='d'
megan at voices dot com 10-Sep-2013 03:45
As noted, list() will give an error if the input array is too short. This can be avoided by array_merge()'ing in some default values. For example:

<?php
$parameter = 'name';
list( $a, $b ) = array_merge( explode( '=', $parameter ), array( true ) );
?>

However, you will have to array_merge with an array long enough to ensure there are enough elements (if $parameter is empty, the code above would still error).

An alternate approach would be to use array_pad on the array to ensure its length (if all the defaults you need to add are the same).

<?php
    $parameter = 'bob-12345';
    list( $name, $id, $fav_color, $age ) = array_pad( explode( '-', $parameter ), 4, '' );
    var_dump($name, $id, $fav_color, $age);
/* outputs
string(3) "bob"
string(5) "12345"
string(0) ""
string(0) ""
*/
?>
svennd 23-Dec-2012 07:08
The list() definition won't throw an error if your array is longer then defined list.
<?php

list($a, $b, $c) = array("a", "b", "c", "d");

var_dump($a); // a
var_dump($b); // b
var_dump($c); // c
?>
chris at chlab dot ch 07-Nov-2012 03:00
The example states the following:
<?php
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar);
// output: NULL
?>

If the string is in a variable however, it seems using list() will treat the string as an array:
<?php
$string = "abcde";
list($foo) = $string;
var_dump($foo);
// output: string(1) "a"
?>


Ordenar un array usando un algoritmo de "orden natural" insensible a mayúsculas-minúsculas

  • « list
  • natsort »
  • PHP Manual
  • Funciones de Arrays
  • Ordenar un array usando un algoritmo de "orden natural" insensible a mayúsculas-minúsculas

natcasesort

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

natcasesort — Ordenar un array usando un algoritmo de "orden natural" insensible a mayúsculas-minúsculas

Descripción

natcasesort ( array &$array ) : bool

natcasesort() es la versión insensible a mayúsculas-minúsculas de natsort().

Esta función implementa un algoritmo de ordenación que ordena las cadenas alfanuméricas en la manera en que lo haría un humano mientras mantiene las asociaciones de clave/valor. Es descrito como "ordenación natural".

Nota:

Si dos miembros se comparan como iguales, su orden relativo en el array oredenado será indefinido.

Parámetros

array

El array de entrada.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de natcasesort()

<?php
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "Ordenación estándar\n";
print_r($array1);

natcasesort($array2);
echo "\nOrdenación de orden natural (insensible a maý-mín)\n";
print_r($array2);
?>

El resultado del ejemplo sería:

Ordenación estándar
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img10.png
    [4] => img12.png
    [5] => img2.png
)

Ordenación de orden natural (insensible a maý-mín)
Array
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

Para más información véase: la página de Martin Pool » Natural Order String Comparison.

Ver también

  • natsort() - Ordena un array usando un algoritmo de "orden natural"
  • comparación de funciones de orden de arrays
  • strnatcmp() - Comparación de strings utilizando un algoritmo de "orden natural"
  • strnatcasecmp() - Comparación de strings, insensible a mayúsculas y minúsculas, utilizando un algoritmo de "orden natural"

User Contributed Notes

w-dot-rosenbach-at-netskill-de 14-Dec-2010 09:45
Sorting UTF-8 by arbitrary order:

<?php
mb_internal_encoding("UTF-8");

class utf_8_german
{
  // everything else is sorted at the end
  static $order = '0123456789AaÄäBbCcDdEeFfGgHhIiJjKkLlMm
NnOoÖöPpQqRrSsßTtUuÜüVvWwXxYyZz';
  static $char2order;

  static function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }

    // lazy init mapping
    if (empty(self::$char2order))
    {
      $order = 1;
      $len = mb_strlen(self::$order);
      for ($order=0; $order<$len; ++$order)
      {
        self::$char2order[mb_substr(self::$order, $order, 1)] = $order;
      }
    }

    $len_a = mb_strlen($a);
    $len_b = mb_strlen($b);
    $max=min($len_a, $len_b);
    for($i=0; $i<$max; ++$i)
    {
      $char_a= mb_substr($a, $i, 1);
      $char_b= mb_substr($b, $i, 1);

      if ($char_a == $char_b) continue;
      $order_a = (isset(self::$char2order[$char_a])) ? self::$char2order[$char_a] : 9999;
      $order_b = (isset(self::$char2order[$char_b])) ? self::$char2order[$char_b] : 9999;

      return ($order_a < $order_b) ? -1 : 1;
    }
    return ($len_a < $len_b) ? -1 : 1;
  }
}

// usage example:

$t = array(
  'Birnen', 'Birne', 'Äpfel', 'Apfel',
);

uasort($t, 'utf_8_german::cmp');
echo '$t: <pre>'.htmlspecialchars(print_r($t,true),null,'UTF-8').'</pre>';
?>
shawn at shawnwilkerson dot com 05-May-2009 10:03
I kept getting varied results using natcasesort and sort on mixed arrays -- per the descriptions.

Sometimes simple is better:

A little snippet of code:

<?php                        if($responders->num_rows) {
                            $i=0;
                            while($row= $responders->fetch_assoc()) {
                                $user=getUserName($row['responderID']);
                                $r[$i]= array("sortname"=>strtolower($user),"userName"=>$user, "userID"=>$row['responderID'], "responderID"=>$row['idresponders']);
                                $i++;
                            }
                            sort($r);
                            print_r($r);
                        }

?>

I simply created a lower cased sort field at the front of the result set and then sort by it -- which provides the expected result and leaves the actual needed fields unchanged.

For the curious:  all user information is kept completed in another database (and table) from the content database due to security reasons.  The getUser functions we have written allow us to pull only what is legally allowed without exposing anything else.

This is why a left join or something wasn't used and we have to build a pseudo result array here from both databases.
claude at schlesser dot lu 07-Jan-2009 12:41
Here a function that will natural sort an array by keys with keys that contain special characters.

<?php
function natksort($array)
{
    $original_keys_arr = array();
    $original_values_arr = array();
    $clean_keys_arr = array();

    $i = 0;
    foreach ($array AS $key => $value)
    {
        $original_keys_arr[$i] = $key;
        $original_values_arr[$i] = $value;
        $clean_keys_arr[$i] = strtr($key, "ÄÖÜäöüÉÈÀËëéèàç", "AOUaouEEAEeeeac");
        $i++;
    }

    natcasesort($clean_keys_arr);

    $result_arr = array();

    foreach ($clean_keys_arr AS $key => $value)
    {
        $original_key = $original_keys_arr[$key];
        $original_value = $original_values_arr[$key];
        $result_arr[$original_key] = $original_value;
    }

    return $result_arr;
}
?>

Hope it will be useful to somebody :)
vbAlexDOSMan at Yahoo dot com 12-Sep-2003 01:21
Ulli at Stemmeler dot net:  I remade your function -- it's a little more compact now -- Enjoy...

function ignorecasesort(&$array) {

  /*Make each element it's lowercase self plus itself*/
  /*(e.g. "MyWebSite" would become "mywebsiteMyWebSite"*/
  for ($i = 0; $i < sizeof($array); $array[$i] = strtolower($array[$i]).$array[$i], $i++);

  /*Sort it -- only the lowercase versions will be used*/
  sort($array);

  /*Take each array element, cut it in half, and add the latter half to a new array*/
  /*(e.g. "mywebsiteMyWebSite" would become "MyWebSite")*/
  for ($i = 0; $i < sizeof($array); $i++) {
    $this = $array[$i];
    $array[$i] = substr($this, (strlen($this)/2), strlen($this));
  }
}
dslicer at maine dot rr dot com 02-Jun-2003 06:41
Something that should probably be documented is the fact that both natsort and natcasesort maintain the key-value associations of the array. If you natsort a numerically indexed array, a for loop will not produce the sorted order; a foreach loop, however, will produce the sorted order, but the indices won't be in numeric order. If you want natsort and natcasesort to break the key-value associations, just use array_values on the sorted array, like so:

natcasesort($arr);
$arr = array_values($arr);
tmiller25 at hotmail dot com 25-Apr-2002 07:55
add this loop to the function above if you want items which have the same first characters to be listed in a way that the shorter string comes first.
--------------------
  /* short before longer (e.g. 'abc' should come before 'abcd') */
  for($i=count($array)-1;$i>0;$i--) {
    $str_a = $array[$i  ];
    $str_b = $array[$i-1];
    $cmp_a = strtolower(substr($str_a,0,strlen($str_a)));
    $cmp_b = strtolower(substr($str_b,0,strlen($str_a)));
    if ($cmp_a==$cmp_b && strlen($str_a)<strlen($str_b)) {
      $array[$i]=$str_b; $array[$i-1]=$str_a; $i+=2;
    }
  }
--------------------


Ordena un array usando un algoritmo de "orden natural"

  • « natcasesort
  • next »
  • PHP Manual
  • Funciones de Arrays
  • Ordena un array usando un algoritmo de "orden natural"

natsort

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

natsort — Ordena un array usando un algoritmo de "orden natural"

Descripción

natsort ( array &$array ) : bool

Esta función implementa un algoritmo de ordenación que ordena las cadenas alfanuméricas en la manera en que lo haría un humano mientras mantiene las asociaciones de clave/valor. Es descrito como "ordenación natural". Un ejemplo de la diferencia entre este algoritmo y los algoritmos de ordenación normales de computadora (usados en sort()) se puede ver en el ejemplo de abajo.

Nota:

Si dos miembros se comparan como iguales, su orden relativo en el array oredenado será indefinido.

Parámetros

array

El array de entrada.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
5.2.10 | Las cadenas numéricas rellenadas con ceros (p.ej., '00005') ahora ignoran el relleno de 0.

Ejemplos

Ejemplo #1 Ejemplos de natsort() demostrando su uso básico

<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

asort($array1);
echo "Ordenación estándar\n";
print_r($array1);

natsort($array2);
echo "\nOrdenación de orden natural\n";
print_r($array2);
?>

El resultado del ejemplo sería:

Ordenación estándar
Array
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Ordenación de orden natural
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

Para más información véase: la página de Martin Pool » Natural Order String Comparison.

Ejemplo #2 Ejemplos de natsort() demostrando trampas potenciales

<?php
echo "Números negativos\n";
$negativo = array('-5','3','-2','0','-1000','9','1');
print_r($negativo);
natsort($negativo);
print_r($negativo);

echo "Relleno de ceros\n";
$ceros = array('09', '8', '10', '009', '011', '0');
print_r($ceros);
natsort($ceros);
print_r($ceros);
?>

El resultado del ejemplo sería:

Números negativos
Array
(
    [0] => -5
    [1] => 3
    [2] => -2
    [3] => 0
    [4] => -1000
    [5] => 9
    [6] => 1
)
Array
(
    [2] => -2
    [0] => -5
    [4] => -1000
    [3] => 0
    [6] => 1
    [1] => 3
    [5] => 9
)

Relleno de ceros
Array
(
    [0] => 09
    [1] => 8
    [2] => 10
    [3] => 009
    [4] => 011
    [5] => 0
)
Array
(
    [5] => 0
    [1] => 8
    [3] => 009
    [0] => 09
    [2] => 10
    [4] => 011
)

Ver también

  • natcasesort() - Ordenar un array usando un algoritmo de "orden natural" insensible a mayúsculas-minúsculas
  • comparación de funciones de orden de arrays
  • strnatcmp() - Comparación de strings utilizando un algoritmo de "orden natural"
  • strnatcasecmp() - Comparación de strings, insensible a mayúsculas y minúsculas, utilizando un algoritmo de "orden natural"

User Contributed Notes

Malek Mohamed 24-Jun-2018 06:21
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

natsort($array1);
echo "\n natsort(); \n";
print_r($array1);

sort($array2, SORT_NATURAL);
echo "\n sort() with  SORT_NATURAL Option\n";
print_r($array2);

Ouput:

natsort();
Array
(
    [0] => IMG0.png
    [5] => IMG3.png
    [4] => img1.png
    [3] => img2.png
    [2] => img10.png
    [1] => img12.png
)

sort() with  SORT_NATURAL Option
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img2.png
    [4] => img10.png
    [5] => img12.png
)

as we can see it's  the same values but not the same keys, and also it's same for sort($array1, SORT_NATURAL | SORT_FLAG_CASE); and natcasesort($array2)
dotancohen splat gmail spot com 30-May-2017 06:59
As noted in other notes, natsort() does _not_ always return the expected sort order. It seems especially buggy when decimals or 0 padding is used. I've filed this bug report on the issue:
https://bugs.php.net/bug.php?id=74672
bb7b5b9 at gmail dot com 14-Jan-2016 08:07
This made me waste a lot of my precious youth ... natsort() is buggy if all numbers don't have the same number of decimal places.

(php 5.6.4-4ubuntu6.2)

<?php
$different_decimal_places_in_values = array('D'=>'13.59', '14.6' => '14.6', 'C-' => '14.19');
natsort($a);
var_dump($a);

/*echoes
array(3) {
  'D' =>
  string(5) "13.59"
  '14.6' =>
  string(4) "14.6" <----------- badly ordered
  'C-' =>
  string(5) "14.19"
}*/
?>

While this

<?php
$same_num_decimal_places_in_values = array('D'=>'13.59', '14.6' => '14.60', 'C-' => '14.19'); natsort($a); var_dump($a);

/*echoes
array(3) {
  'D' =>
  string(5) "13.59"
  'C-' =>
  string(5) "14.19"
  '14.6' =>
  string(5) "14.60" <--------- that is the correct position
}
*/

?>
mvs dot php at gmail dot com 20-May-2015 10:12
To naturally sort by array key, the uksort function can be used.

<?php

echo "Sort by keys\n";
$smoothie = array('orange' => 1, 'apple' => 1, 'yogurt' => 4, 'banana' => 4);
print_r($smoothie);
uksort( $smoothie, 'strnatcmp');
print_r($smoothie)

?>

Output:

Sort by keys
Array
(
    [orange] => 1
    [apple]  => 1
    [yogurt] => 4
    [banana] => 4
)
Array
(
    [apple]  => 1
    [banana] => 4
    [orange] => 1
    [yogurt] => 4
)

See http://php.net/manual/en/function.uksort.php for more information about uksort and http://php.net/strnatcmp for usage of strnatcmp.
Johan GENNESSON (php at genjo dot fr) 24-Nov-2010 07:18
Be careful of the new behaviour in 5.2.10 version.
See the following sample:

<?php

$array = array('1 bis', '10 ter', '0 PHP', '0', '01', '01 Ver', '0 ', '1 ', '1');

natsort($array);
echo '<pre>';
print_r($array);
echo '</pre>';
?>

5.2.6-1 will output:
Array
(
    [3] => 0
    [6] => 0
    [2] => 0 OP
    [4] => 01
    [5] => 01 Ver
    [8] => 1
    [7] => 1
    [0] => 1 bis
    [1] => 10 ter
)

5.2.10 will output:
Array
(
    [6] => 0
    [3] => 0
    [8] => 1
    [4] => 01
    [7] => 1
    [5] => 01 Ver
    [0] => 1 bis
    [1] => 10 ter
    [2] => 0 OP
)

Greetings
ale152 16-Mar-2009 02:00
Note: negatives number.
<?php
$a = array(-5,-2,3,9);
natsort($a);
print_r($a);
?>
Will output:
Array ( [1] => -2 [0] => -5 [2] => 3 [3] => 9 )
AJenbo 15-Jan-2009 01:33
natsort might not act like you would expect with zero padding, heres a quick sample.

<?php
$array = array('09', '8', '10', '009', '011');
natsort($array);
?>
/*
Array
(
    [3] => 009
    [4] => 011
    [0] => 09
    [1] => 8
    [2] => 10
)
*/
wyvern at greywyvern dot com 17-Dec-2008 10:53
There's no need to include your own API code to natsort an associative array by key.  PHP's in-built functions (other than natsort) can do the job just fine:

<?php
  uksort($myArray, "strnatcmp");
?>
lacent at gmail dot com 16-Jan-2007 09:42
there is another rnatsort function lower on the page, but it didn't work in the context i needed it in.

reasoning for this:
sorting naturally via the keys of an array, but needing to reverse the order.

    function rnatsort ( &$array = array() )
    {
        $keys    = array_keys($array);
        natsort($keys);
        $total    = count($keys) - 1;
        $temp1    = array();
        $temp2     = array();

        // assigning original keys to an array with a backwards set of keys, to use in krsort();
        foreach ( $keys as $key )
        {
            $temp1[$total] = $key;
            --$total;
        }

        ksort($temp1);

        // setting the new array, with the order from the krsort() and the values of original array.
        foreach ( $temp1 as $key )
        {
            $temp2[$key] = $array[$key];
        }

        $array = $temp2;
    }
@gmail bereikme 01-Sep-2006 08:06
Here's a handy function to sort an array on 1 or more columns using natural sort:
<?php
// Example: $records = columnSort($records, array('name', 'asc', 'addres', 'desc', 'city', 'asc'));

$globalMultisortVar = array();
function columnSort($recs, $cols) {
    global $globalMultisortVar;
    $globalMultisortVar = $cols;
    usort($recs, 'multiStrnatcmp');
    return($recs);
}

function multiStrnatcmp($a, $b) {
    global $globalMultisortVar;
    $cols = $globalMultisortVar;
    $i = 0;
    $result = 0;
    while ($result == 0 && $i < count($cols)) {
        $result = ($cols[$i + 1] == 'desc' ? strnatcmp($b[$cols[$i]], $a[$cols[$i]]) : $result = strnatcmp($a[$cols[$i]], $b[$cols[$i]]));
        $i+=2;
    }
    return $result;
}

?>

Greetings,

  - John
h3 22-Feb-2006 08:59
This function can be very usefull, but in some cases, like if you want to sort a MySQL query result, it's important to keep in mind that MySQL as built'in sorting functions which are way faster than resorting the result using a complex php algorythm, especially with large arrays.

ex; 'SELECT * FROM `table` ORDER BY columnName ASC, columnName2 DESC'
lil at thedreamersmaze dot spam-me-not dot org 31-Jan-2006 08:38
There's one little thing missing in this useful bit of code posted by mbirth at webwriters dot de:

<?php

function natsort2d(&$aryInput) {
  $aryTemp = $aryOut = array();
  foreach ($aryInput as $key=>$value) {
   reset($value);
   $aryTemp[$key]=current($value);
  }
  natsort($aryTemp);
  foreach ($aryTemp as $key=>$value) {
   $aryOut[$key] = $aryInput[$key];
// --------^^^^ add this if you want your keys preserved!
  }
  $aryInput = $aryOut;
}

?>
natcasesort.too 05-Aug-2005 03:17
I got caught out through naive use of this feature - attempting to sort a list of image filenames from a digital camera, where the filenames are leading zero padded (e.g. DSCF0120.jpg) , will not sort correctly.
Maybe the example could be modified to exhibit this behaviour
(e.g. set array to -img0120.jpg','IMG0.png', 'img0012.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png)
If the example hadn't used images I would have coded it correctly first time around!
phpnet at moritz-abraham dot de 02-Sep-2004 02:09
additional to the code posted by justin at redwiredesign dot com (which I found very usefull) here is a function that sorts complex arrays like this:
<?
$array['test0'] = array('main' =>  'a', 'sub' => 'a');
$array['test2'] = array('main' =>  'a', 'sub' => 'b');
$array['test3'] = array('main' =>  'b', 'sub' => 'c');
$array['test1'] = array('main' =>  'a', 'sub' => 'c');
$array['test4'] = array('main' =>  'b', 'sub' => 'a');
$array['test5'] = array('main' =>  'b', 'sub' => 'b');
?>
or
<?
$array[0] = array('main' =>  1, 'sub' => 1);
$array[2] = array('main' =>  1, 'sub' => 2);
$array[3] = array('main' =>  2, 'sub' => 3);
$array[1] = array('main' =>  1, 'sub' => 3);
$array[4] = array('main' =>  2, 'sub' => 1);
$array[5] = array('main' =>  2, 'sub' => 2);
?>
on one or more columns.

the code
<? $array = array_natsort_list($array,'main','sub'); ?>
will result in $array being sortet like this:
test0,test2,test1,test4,test5,test3
or
0,2,1,4,5,3.

you may even submit more values to the function as it uses a variable parameter list. the function starts sorting on the last and the goes on until the first sorting column is reached.

to me it was very usefull for sorting a menu having submenus and even sub-submenus.

i hope it might help you too.

here is the function:
<?
function array_natsort_list($array) {
    // for all arguments without the first starting at end of list
    for ($i=func_num_args();$i>1;$i--) {
        // get column to sort by
        $sort_by = func_get_arg($i-1);
        // clear arrays
        $new_array = array();
        $temporary_array = array();
        // walk through original array
        foreach($array as $original_key => $original_value) {
            // and save only values
            $temporary_array[] = $original_value[$sort_by];
        }
        // sort array on values
        natsort($temporary_array);
        // delete double values
        $temporary_array = array_unique($temporary_array);
        // walk through temporary array
        foreach($temporary_array as $temporary_value) {
            // walk through original array
            foreach($array as $original_key => $original_value) {
                // and search for entries having the right value
                if($temporary_value == $original_value[$sort_by]) {
                    // save in new array
                    $new_array[$original_key] = $original_value;
                }
            }
        }
        // update original array
        $array = $new_array;
    }
    return $array;
}
?>
xlab AT adaptiveNOSPAMarts DOT net 15-Jan-2004 12:51
Under limited testing, natsort() appears to work well for IP addresses. For my needs, it is far less code than the ip2long()/long2ip() conversion I was using before.
mbirth at webwriters dot de 09-Jan-2004 12:31
For those who want to natsort a 2d-array on the first element of each sub-array, the following few lines should do the job.

<?php

function natsort2d(&$aryInput) {
  $aryTemp = $aryOut = array();
  foreach ($aryInput as $key=>$value) {
    reset($value);
    $aryTemp[$key]=current($value);
  }
  natsort($aryTemp);
  foreach ($aryTemp as $key=>$value) {
    $aryOut[] = $aryInput[$key];
  }
  $aryInput = $aryOut;
}

?>
rasmus at flajm dot com 14-Dec-2003 09:30
To make a reverse function, you can simply:

function rnatsort(&$a){
    natsort($a);
    $a = array_reverse($a, true);
}
flash at minet dot net 12-Aug-2003 10:27
About the reverse natsort.. Maybe simpler to do :

function strrnatcmp ($a, $b) {
    return strnatcmp ($b, $a);
}
anonymous at coward dot net 31-May-2003 01:46
Reverse Natsort:

  function rnatsort($a, $b) {
    return -1 * strnatcmp($a, $b);
  }

  usort($arr, "rnatsort");


Avanza el puntero interno de un array

  • « natsort
  • pos »
  • PHP Manual
  • Funciones de Arrays
  • Avanza el puntero interno de un array

next

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

next — Avanza el puntero interno de un array

Descripción

next ( array &$array ) : mixed

next() se comporta como current(), con una diferencia. Avanza el puntero interno un lugar a delante antes de devolver el valor del elemento. Esto significa que devuelve el siguiente valor del array y avanza el puntero interno del array un lugar.

Parámetros

array

El array afectado.

Valores devueltos

Devuelve el valor del array en el siguiente lugar que está apuntado por el puntero interno o false si no hay más elementos.

Advertencia

Esta función puede devolver el valor booleano false, pero también puede devolver un valor no booleano que se evalúa como false. Por favor lea la sección sobre Booleanos para más información. Use el operador === para comprobar el valor devuelto por esta función.

Ejemplos

Ejemplo #1 Ejemplo del uso de next() y similares

<?php
$transport = array('pie', 'bici', 'coche', 'avión');
$mode = current($transport); // $mode = 'pie';
$mode = next($transport);    // $mode = 'bici';
$mode = next($transport);    // $mode = 'coche';
$mode = prev($transport);    // $mode = 'bici';
$mode = end($transport);     // $mode = 'avión';
?>

Notas

Nota: No hay manera de distinguir el inicio de un array de un elemento de tipo false boolean. Para recorrer adecuadamente que puede contener elementos false ver la función each().

Ver también

  • current() - Devuelve el elemento actual en un array
  • end() - Establece el puntero interno de un array a su último elemento
  • prev() - Rebobina el puntero interno del array
  • reset() - Establece el puntero interno de un array a su primer elemento
  • each() - Devolver el par clave/valor actual de un array y avanzar el cursor del array

User Contributed Notes

Mikhail 05-Sep-2019 02:47
This function returns next element in array after your key or false if it last or key doesn't exists in array.

<?php

function nextElement(array $array, $currentKey)
{
    if (!isset($array[$currentKey])) {
        return false;
    }
    $nextElement = false;
    foreach ($array as $key => $item) {
        $nextElement = next($array);
        if ($key == $currentKey) {
            break;
        }
    }

    return $nextElement;
}
andy at andysdrawings dot co dot uk 05-Oct-2018 01:58
brentimus' array_set_pointer function will only work if the array value is unique in the array, and none of the array values are FALSE. It would be more reliable to use key() instead of current(). For similar reasons it's better to check key() after calling next() to determine whether the next() element "exists". Simply checking the value returned by next() will produce a false negative when looking at, for example, the first element of the array: ['one', 0, 'three']

However, it also turns out that the copied array retains the original array's pointer, so array_set_pointer is not actually required here. The following should work:

<?php
function has_next(array &$array) {
    $A_work = $array;  // $A_work is a copy of $array including its internal pointer.
    next($A_work);
    if (key($A_work) === NULL)
        return false;
    else
        return true;
}
?>
notImportant 03-May-2018 01:11
a more readable version of papipo's has_next function:

<?php
function has_next($array) {
    $has_next = is_array($array) && next($array) !== false;

    return $has_next;
}
?>

OR

<?php
function has_next($array) {
    $has_next = false;
    if(is_array($array)) {
        $has_next = next($array) !== false;
    }

    return $has_next;
}
?>
nigra 02-Jan-2018 08:01
This function will return the previous,next neighbors of an array entry within an associative array. If the specified $key points to the last or first element of the array, the first or last keys of the array will be returned consecutively. This is an improved version of the same function posted earlier.

<?php
function array_neighbor($count, $key = null, $arRelated = array(), $cntRelated = 2)
{
    if($count > 0 && isset($key))
    {
        $keyL = $count - 1;
        $keyR = 1;
        $arResult = array();
        for($i = 1; $i <= $cntRelated; $i++)
        {
            if($key == 0)
            {
                if(($i % 2) == 0)
                {
                    $curKey = $count - $keyL;
                    $keyL--;
                }
                else
                {
                    $curKey = $count - $keyR;
                    $keyR++;
                }
            }
            else
            {
                if($arRelated[$i] >= $count - 1)
                {
                    $curKey = 0;
                }
                else
                {
                    $curKey = $arRelated[$i] + 1;
                }
            }
            $arResult[$i] = $curKey;
        }
        return $arResult;
    }
}

$arr = range(0, 4);
$count = count($arr);

foreach($arr as $key => $v)
{
    if($arRelated = array_neighbor($count, $key, $arRelated))
    {
        $arHeighbor[$key]['RELATED'] = $arRelated;
    }
}

echo '<pre>';print_r($arHeighbor); echo '</pre>';
?>
Array
(
    [0] => Array
        (
            [RELATED] => Array
                (
                    [1] => 4
                    [2] => 1
                )

        )

    [1] => Array
        (
            [RELATED] => Array
                (
                    [1] => 0
                    [2] => 2
                )

        )

    [2] => Array
        (
            [RELATED] => Array
                (
                    [1] => 1
                    [2] => 3
                )

        )

    [3] => Array
        (
            [RELATED] => Array
                (
                    [1] => 2
                    [2] => 4
                )

        )

    [4] => Array
        (
            [RELATED] => Array
                (
                    [1] => 3
                    [2] => 0
                )

        )

)
JumpIfBelow 24-Aug-2017 11:57
Now from PHP 7.2, the function "each" is deprecated, so the has_next I've posted is no longer a good idea. There is another to keep it simple and fast:

<?php
function has_next(array $_array)
{
  return next($_array) !== false ?: key($_array) !== null;
}
?>
JumpIfBelow 30-Jul-2015 12:45
After dealing with the fact that next() will either returns FALSE when there is no further element in the array or if the element itself is FALSE, I finally find a way to do a has_next() method, which will never fails. You can ignore and/or downvote my last comment, this it will be deleted.
Here is the code that work :
<?php
    function has_next(array $a){
        return next($a) !== false ?: each($a) !== false;
    }
?>
double at dumpit dot de 08-Dec-2009 01:19
PHP: 5.2.10-2ubuntu6.3 (default apt-get installation on actual, see Date, jaunty 9.10 Ubuntu Distro - G33kWoRDs)

Have a look at your array pointer if you copy an array - the pointer will be copied, too.

For example if you got this construct:
<?php
    $array = array('zero','one','two','three','four','five','six','seven');
    $array2 = $array;
    next($array);
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 0
?>

But if you copy the array after you've setted the pointer, the pointer will be copied, too:
<?php
    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = $array;
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 1
?>

What's more is, that foreach not resetting the pointer after walk through:
<?php

    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = array();
    foreach($array AS $key => $value){
        echo $key;
        $array2[$key] = $value;
    }
    echo var_dump(key($array));
    echo key($array2);

    // will output for foreach:
    // 0 1 2 3 4 5 6 7
    // and for the keys
    // NULL
    // 0
?>

The php-functions seems to reset the pointer on the given position after walk through (i don't know the internal handling - there could be used a copy of the array, too):
<?php

    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = array_values($array);
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 0
?>

There are a lot Methods like array_merge($array) that will neither reset the pointer of $array nor copy the pointer to $array2. Have a look on this.
I Hope this was a little helpfull.
ThinkMedical at Gmail dot com 02-Sep-2008 03:27
regarding references with foreach, you can use them directly. Obviating various posts which provide many lines of 'work arounds'.

$array = array(1,2,3,4,5);

foreach($array as &$value)

or use $key

foreach($array as $key => $value)
{
    $array[$key] = '...';
}
darkside at i dot ua 11-Dec-2007 03:36
This class implements simple operations with array

<?php
class Steps {

    private $all;
    private $count;
    private $curr;

    public function __construct () {

      $this->count = 0;

    }

    public function add ($step) {

      $this->count++;
      $this->all[$this->count] = $step;

    }

    public function setCurrent ($step) {

      reset($this->all);
      for ($i=1; $i<=$this->count; $i++) {
        if ($this->all[$i]==$step) break;
        next($this->all);
      }
      $this->curr = current($this->all);

    }

    public function getCurrent () {

      return $this->curr;

    }

    public function getNext () {

      self::setCurrent($this->curr);
      return next($this->all);

    }

  }
?>

usage example:

<?php
   $steps = new Steps();
   $steps->add('one');
   $steps->add('two');
   $steps->add('three');
   $steps->setCurrent('one');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   $steps->setCurrent('two');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
?>
gg2005 at gmail dot com 06-Feb-2007 01:32
Don't confuse next with continue!

If you're a Perl developer starting with PHP, you might try to use "next" inside a loop to skip to the next iteration...

i.e.,

foreach ($things as $thing) {
  if (something I don't like about $thing) {
   next;
  }
  blah....
}

The php compiler will take next... but it's not going to work.

Do this instead:
foreach ($things as $thing) {
  if (something I don't like about $thing) {
   continue;
  }
  blah....
}
tino at infeon dot com 13-May-2006 08:48
this may be handy and i didnt know where else to post it.. i need a simple function to cycle through an array i eventually made it into a class so i could have multiple cycles.. if you like it or find it usefull please email me and let me know

class Cycle
{
    var $position;
    var $dataArray;
    var $dataArrayCount;

    function Cycle()
    {
        $this->dataArray = func_get_args();
        $this->dataArrayCount = count($this->dataArray);
    }

    function Display()
    {
        $this->position = (!isset($this->position) || $this->position >= ($this->dataArrayCount - 1)) ? 0 : $this->position += 1;
        return $this->dataArray[$this->position];
    }

}

$bgColor = new Cycle('#000000', '#FFFFFF', '#FF0000');

echo $bgcolor->Display();
//returns #000000
echo $bgcolor->Display();
//returns #FFFFFF
echo $bgcolor->Display();
//returns #FF0000
echo $bgcolor->Display();
//returns #000000
brentimus 28-Apr-2005 10:10
Papipo's function below is usefull in concept but does not work.

"Since you do not pass the array by reference, its pointer is only moved inside the function."

This is true, but the array you are manipulating in your has_next() function will have it's pointer set to the first element, not the same position as the original array. What you want to do is pass the array to the has_next() function via reference. While in the has_next() function, make a copy of the array to work on. Find out the current pointer position of the original array and set the pointer on the working copy of the array to the same element. Then you may test to see if the array has a "next" element.

Try the followig insetad:

<?php
function has_next(&$array)
{
    $A_work=$array;  //$A_work is a copy of $array but with its internal pointer set to the first element.
    $PTR=current($array);
    array_set_pointer($A_work, $PTR);

    if(is_array($A_work))
    {
        if(next($A_work)===false)
            return false;
        else
            return true;
    }
    else
        return false;
}

function array_set_pointer(&$array, $value)
{
    reset($array);
    while($val=current($array))
    {
        if($val==$value)
            break;

        next($array);
    }
}
?>
papipo's gmail account 13-Oct-2004 01:47
I need to know if an array has more items, but without moving array's internail pointer. Thats is, a has_next() function:

<?php
function has_next($array) {
    if (is_array($array)) {
        if (next($array) === false) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

$array = array('fruit', 'melon');
if (has_next($array)) {
    echo next($array);
}

// prints 'melon'
?>

Since you do not pass the array by reference, its pointer is only moved inside the function.
Hope that helps.
lukasz at karapuda dot com 18-Aug-2004 10:06
This function will return the previous,next neighbors of an array entry within an associative array. If the specified $key points to the last or first element of the array, the first or last keys of the array will be returned consecutively. This is an improved version of the same function posted earlier.

<?php
function array_neighbor($arr, $key)
{
   $keys = array_keys($arr);
   $keyIndexes = array_flip($keys);

   $return = array();
   if (isset($keys[$keyIndexes[$key]-1])) {
       $return[] = $keys[$keyIndexes[$key]-1];
   }
   else {
       $return[] = $keys[sizeof($keys)-1];
   }

   if (isset($keys[$keyIndexes[$key]+1])) {
       $return[] = $keys[$keyIndexes[$key]+1];
   }
   else {
       $return[] = $keys[0];
   }

   return $return;
}
?>
court shrock 20-May-2004 04:36
This code returns neighbors of the specified key.  The result will be empty if it doesn't have any neighbors.  My approach was to use the order of keys to determine neighbors, which is differnet from just getting the next/previous element in an array.  Feel free to point out stupidities :)

<?php

function array_neighbor($arr, $key)
{
    krsort($arr);
    $keys = array_keys($arr);
    $keyIndexes = array_flip($keys);

    $return = array();
    if (isset($keys[$keyIndexes[$key]-1]))
        $return[] = $keys[$keyIndexes[$key]-1];
    if (isset($keys[$keyIndexes[$key]+1]))
        $return[] = $keys[$keyIndexes[$key]+1];

    return $return;
}

?>
bm at ANTISPAM dot solidwave dot com 16-Apr-2004 09:49
Take care when replacing code using reset()/next() with code using foreach as foreach does not update the array's internal pointer.  This means you cannot, say, use next() to skip an element in foreach loop, or use current() within a function to get a reference to the current element.  You probably have code depending on this internal pointer and replacing it will be more work than you anticipated.

See http://www.php.net/foreach


Alias de current

  • « next
  • prev »
  • PHP Manual
  • Funciones de Arrays
  • Alias de current

pos

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

pos — Alias de current()

Descripción

Esta función es un alias de: current()

User Contributed Notes

There are no user contributed notes for this page.


Rebobina el puntero interno del array

  • « pos
  • range »
  • PHP Manual
  • Funciones de Arrays
  • Rebobina el puntero interno del array

prev

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

prev — Rebobina el puntero interno del array

Descripción

prev ( array &$array ) : mixed

Rebobina el puntero interno del array.

prev() se comporta como next(), a excepción de que rebobina el puntero interno del array una posición en lugar de avanzar.

Parámetros

array

El array de entrada.

Valores devueltos

Devuelve el valor del array en la posición anterior que está apuntado por el puntero interno del array o false si no hay más elementos.

Ejemplos

Ejemplo #1 Ejemplo de uso de prev() and friends

<?php
$transport = array('pie', 'bici', 'coche', 'avión');
$mode = current($transport); // $mode = 'pie';
$mode = next($transport);    // $mode = 'bici';
$mode = next($transport);    // $mode = 'coche';
$mode = prev($transport);    // $mode = 'bici';
$mode = end($transport);     // $mode = 'avión';
?>

Notas

Advertencia

Esta función puede devolver el valor booleano false, pero también puede devolver un valor no booleano que se evalúa como false. Por favor lea la sección sobre Booleanos para más información. Use el operador === para comprobar el valor devuelto por esta función.

Nota: No hay manera de distinguir el inicio de un array de un elemento de tipo false boolean. Para recorrer adecuadamente que puede contener elementos false ver la función each().

Ver también

  • current() - Devuelve el elemento actual en un array
  • end() - Establece el puntero interno de un array a su último elemento
  • next() - Avanza el puntero interno de un array
  • reset() - Establece el puntero interno de un array a su primer elemento
  • each() - Devolver el par clave/valor actual de un array y avanzar el cursor del array

User Contributed Notes

Mikhail 05-Sep-2019 02:56
Function to get element in array, that goes previous your key or false if it not exeists or key doesn't isset in array.

<?php

function previousElement(array $array, $currentKey)
{
    if (!isset($array[$currentKey])) {
        return false;
    }
    end($array);
    do {
        $key = array_search(current($array), $array);
        $previousElement = prev($array);
    }
    while ($key != $currentKey);

    return $previousElement;
}
MicroVB INC 31-Mar-2014 05:09
Some corrections to the previous function.
- When prev() and next() distance is now calculated properly returning the 'closer' one.
- When exact is false, and an item exists with the key searched for, it now returns that entry instead of next/prev closest
- At ends of the array, sometimes when moving past using next() or prev(), it caused results to die. This was corrected.
- Added field to result stating whether the match was 'exact' ('exact'=>true), or nearest ('exact'=>false)

<?php
function nearest($array, $value, $exact=false) {
    // Initialize Variables
    $next = false;
    $prev = false;
    $return = false;

    $arr_begin = false;
    $arr_end = false;

    $exact_match = false;

    if($exact && isset($array[$value])) {
        // If exact match found, and searching for exact (not nearest), return result.
        $return = Array($value=>$array[$value]);
        $exact_match = true;
    } elseif (!$exact && isset($array[$value])) {
        // If exact match found, and searching for nearest, return result.
        $return = Array($value=>$array[$value]);
        $exact_match = true;
    } else {

        if(!isset($array[$value]) && !$exact) {
            // Insert element that doesn't exist so nearest can be found
            $array[$value] = '-';
        }

        // Sort array so injected record is near relative numerics
        ksort($array); // Sort array on key

        // Set start and end keys
        $arr_begin = key($array);
        end($array);
        $arr_end = key($array);
        reset($array);

        // Loop through array until match is found, then set $prev and $next to the respective keys if exist
        while ( !is_null($key = key($array)) ) {
            $val = current($array);
            if($key == $value) {
                if($value <> $arr_begin) {
                    prev($array); // Get entry before this one
                    $prev = key($array);
                }

                next($array);         // Skip current entry as this was what we were looking for nearest to

                if($value <> $arr_end) {
                    next($array); // Get entry after this one
                    $next = key($array);
                }
                break;
            }
            next($array);
        }

        if($prev && $next) {
            if(($value - $prev) < ($next - $value)) {
                // Previous is closer
                $return = Array($prev=>$array[$prev]);
            } else {
                // Next is closer
                $return = Array($next=>$array[$next]);
            }
        } elseif ($prev || $next) {
            if($prev) {
                // Only Previous exists
                $return = Array($prev=>$array[$prev]);
            } elseif ($next) {
                // Only Next exists
                $return = Array($next=>$array[$next]);
            }
        }
    }

    // Return resulting Array().   $return is false if nothing matches the closest conditions, or if exact is specified and key does not exist.
    if($return) {
        return $return+Array('exact'=>$exact_match);
    } else {
        return false;
    }
}
?>

Just to clarify, this function will return either an Array() containing the $key=>$value pair of the result and 'exact'=>(bool) whether the match was exact or not.

To access the $key=>$value pair, can be done as follows :
<?php

    $result = nearest( ... );  // Just here for clarification of the position for the code that follows.

    if($result) {
        // Output the Key
        echo key($result);

        // Output the Value
        echo $result( key($result) );

        // Output if exact match
        if($result['exact']) {
            echo 'This was an EXACT match';
        } else {
            echo 'This result was found with fuzzy logic';
        }

    } else {

        echo 'No result found';

    }

?>
MicroVB INC 31-Mar-2014 01:17
This function searches for the closest element in an array by key value, and returns the key/value pair, or false if not found.

<?php
function nearest($array, $value, $exact=false) {
        // Initialize Variables
    $next = false;
    $prev = false;
    $return = false;

    if(!isset($array[$value]) && !$exact) {
        // Insert element that doesn't exist so nearest can be found
        $array[$value] = '-';
    }

    if($exact && isset($array[$value])) {
                // If exact match found, and searching for exact (not nearest), return result.
        $return = Array($value=>$array[$value]);
    } else {
            // Sort array so injected record is near relative numerics
        ksort($array); // Sort array on key

                // Loop through array until match is found, then set $prev and $next to the respective keys if exist
        while ( !is_null($key = key($array)) ) {
            $val = current($array);
            if($key == $value) {
                prev($array); // Get entry before this one
                $prev = key($array);
                next($array);         // Skip current entry as this was what we were looking for nearest to
                next($array); // Get entry after this one
                $next = key($array);
                break;
            }
            next($array);
        }

        if($prev && $next) {
            if(($long - $prev) > ($next - $long)) {
                                 // Previous is closer
                $return = Array($prev=>$array[$prev]);
            } else {
                                 // Next is closer
                $return = Array($next=>$array[$next]);
            }
        } elseif ($prev || $next) {
            if($prev) {
                                 // Only Previous exists
                $return = Array($prev=>$array[$prev]);
            } elseif ($next) {
                                 // Only Next exists
                $return = Array($next=>$array[$next]);
            }
        }
    }

        // Return resulting Array().   $return is false if nothing matches the closest conditions, or if exact is specified and key does not exist.
    return $return;
}
?>

Example usage (to lookup the closest color in an array)
<?php
$mycolors= Array(
    5001046=>'Abbey',
    1774596=>'Acadia',
    8171681=>'Acapulco',
    6970651=>'Acorn',
    13238245=>'Aero Blue',
    7423635=>'Affair',
    8803850=>'Afghan Tan',
    13943976=>'Akaroa',
    16777215=>'Alabaster',
    16116179=>'Albescent White',
    10176259=>'Alert Tan',
    30371=>'Allports'
);

// Color to search for in Hex
$color = 'C0C0C0';

// Convert Hex to Long to compare with array() keys
$colorlong = base_convert($color,16,10);

// Check for an exact match
$result = nearest($mycolors, $colorlong, true);
if($result) {
    echo "An exact match was found for #" . $color . " which is called '" . $result[key($result)] . "'";
} else {
    echo "No exact match was found";
}

if(!$result) {
    // Check for closest match
    $result = nearest($mycolors, $colorlong, true);
    if($result) {
        // Match found
        echo "The closest match for #" . $color . " is #" . base_convert(key($result),10,16) . " which is called '" . $result[key($result)] . "'";
    } else {
        // No match found
        echo "No match was found for #" . $color;
    }
}
?>
soapergem at gmail dot com 29-May-2009 12:06
Here's a slight revision to xmlich02's backwards iteration example. The problem with his/her example is that it will halt if any of the array elements are boolean false, while this version will not.

<?php

end($ar);
while ( !is_null($key = key($ar)) ) {
    $val = current($ar);
    echo "{$key} => {$val}\n";
    prev($ar);
}

?>


Crear un array que contiene un rango de elementos

  • « prev
  • reset »
  • PHP Manual
  • Funciones de Arrays
  • Crear un array que contiene un rango de elementos

range

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

range — Crear un array que contiene un rango de elementos

Descripción

range ( mixed $start , mixed $end , number $step = 1 ) : array

Crea un array que contiene un rango de elementos.

Parámetros

start

Primer valor de la secuencia.

end

La secuencia finaliza al alcanzar el valor end.

step

Si se proporciona un valor a step, este será usado como el incremento entre los elementos de la secuencia. step debería darse como número positivo. Si no se especifica, el valor predeterminado de step será 1.

Valores devueltos

Devuelve un array de elementos desde start a end, inclusive.

Ejemplos

Ejemplo #1 Ejemplos de range()

<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $número) {
    echo $número;
}

// El parámetro step
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $número) {
    echo $número;
}

// Empleo de las secuencias de caracteres
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letra) {
    echo $letra;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letra) {
    echo $letra;
}
?>

Notas

Nota:

Los valores de las secuencias de caracteres están limitados a una longitud de uno. Si se entra una longitud mayor que uno, solamente se utilizará el primer carácter.

Ver también

  • shuffle() - Mezcla un array
  • array_fill() - Llena un array con valores
  • foreach

User Contributed Notes

ccb_bc at hotmail dot com 10-Jun-2019 05:45
<?php
    function natural_prime_numbers(array $range, bool $print_info = false) : array {
        $start_time = time();
        $primes_numbers = array();
        $print = '';
        $count_range  = count($range);
        foreach($range as $number){
            $values_division_number = array();
            if($number === 0 || $number === 1 || !is_int($number)){ // eliminate 0, 1 and other no integer
                continue;
            }
            if($number != 2 && $number%2 === 0){ // eliminate 2 and pairs numbers
                continue;
            }
            for($i = 1; $i <= $number; $i++){
                $resultado_divisao = $number / $i;
                $values_division_number[$i] = $resultado_divisao;

                if($count_range <= 20){ // $count_range <= 20 (+ performance)
                    $print .= PHP_EOL;
                    $info = 'The number '.$number.' divided by the number '.$i.' is equal to: '.($number / $i);
                    $print .= $info;
                    if($i === $number){
                        $print .= PHP_EOL;
                    }
                }

                array_walk($values_division_number, function($value, $index) use (&$values_division_number, &$number){ // reference change values
                    // eliminate floats and others numbers not are equal 1 and own number
                    if(is_float($value) && $value != $number && $value > 1){
                        unset($values_division_number[$index]);
                    }
                });

                $values_division_number = array_values($values_division_number); // reindex array

                // here we want only array with 2 indexes with the values 1 and own number (rule to a natural prime number)
                if(count($values_division_number) === 2 && $values_division_number[0] === $number && $values_division_number[1] === 1){
                    $primes_numbers[$number] = $number;
                }

            }
        }
        return array(
            'length_prime_numbers' => count($primes_numbers),
            'prime_numbers' => array_values($primes_numbers),
            'print' => $print,
            'total_time_processing' => (time() - $start_time).' seconds.',
        );
    }
    var_dump(natural_prime_numbers(range(0, 11))); // here the range() function ;-)

    // Result:
    // array (size=3)
    //   'length_prime_numbers' => int 5
    //   'prime_numbers' =>
    //     array (size=5)
    //       0 => int 2
    //       1 => int 3
    //       2 => int 5
    //       3 => int 7
    //       4 => int 11
    //   'print' => string '
    // O número 2 dividido pelo número 1 é igual a: 2
    // O número 2 dividido pelo número 2 é igual a: 1

    // O número 3 dividido pelo número 1 é igual a: 3
    // O número 3 dividido pelo número 2 é igual a: 1.5
    // O número 3 dividido pelo número 3 é igual a: 1

    // O número 5 dividido pelo número 1 é igual a: 5
    // O número 5 dividido pelo número 2 é igual a: 2.5
    // O número 5 dividido pelo número 3 é igual a: 1.6666666666667
    // O número 5 dividido pelo número 4 é igual a: 1.25
    // O número 5 dividido pelo '...

    // **************************** //
    //
    // * Remember that the function is recursive, that is: a range of 5000 takes more than 1 minute on a processor Intel® Core™ i5-8250U (3.40 GHz).
    //
    // **************************** //
?>
luca.favorido ATgmailDOT com 28-Jun-2016 07:58
The function "range" is very useful to get an array of characters as range('C','R') does.

At work, I had to extend the function range($a,$b) to work in this special case: with two uppercase strings $a and $b, it should return all the possible strings between $a and $b.
This could be used for example to get the excel column indexes.
e.g. <?php range('A','AD') ==> array('A','B','C',...,'Z','AA','AB','AC','AD') ?>

So I wrote the function getrange($min,$max) that exactly does this.

<?php

function getcolumnrange($min,$max){
      $pointer=strtoupper($min);
      $output=array();
      while(positionalcomparison($pointer,strtoupper($max))<=0){
         array_push($output,$pointer);
         $pointer++;
      }
      return $output;
}

function positionalcomparison($a,$b){
   $a1=stringtointvalue($a); $b1=stringtointvalue($b);
   if($a1>$b1)return 1;
   else if($a1<$b1)return -1;
   else return 0;
}

/*
* e.g. A=1 - B=2 - Z=26 - AA=27 - CZ=104 - DA=105 - ZZ=702 - AAA=703
*/
function stringtointvalue($str){
   $amount=0;
   $strarra=array_reverse(str_split($str));

   for($i=0;$i<strlen($str);$i++){
      $amount+=(ord($strarra[$i])-64)*pow(26,$i);
   }
   return $amount;
}
?>
qz 19-Jan-2016 11:58
If you're looking to fill an array to get a hash with 0-9 numerical values, using
range(0,9);
is a faster solution compared to
array_fill(0, 10, '');
moficer at host dot sk 15-Jan-2016 03:17
php 5.6.16

<?php
var_export(range('Z', 'a'));

/*
array (
  0 => 'Z',
  1 => '[',
  2 => '\\',
  3 => ']',
  4 => '^',
  5 => '_',
  6 => '`',
  7 => 'a',
)
 */
Alien426 29-Oct-2015 02:09
The function will generate an array of integers even if your numerical parameters are enclosed in quotes.
<?php
var_dump( range('1', '2') ); // outputs  array(2) { [0]=> int(1) [1]=> int(2) }
?>

An easy way to get an array of strings is to map strval() to the range:
<?php
var_dump( array_map('strval', range('1', '2')) ); // outputs  array(2) { [0]=> string(1) "1" [1]=> string(1) "2" }
?>
unicod3 at hotmail dot com 15-Oct-2014 05:43
a function to get column index by letter

function getColumnNumber($char){
    $alphabet = range('a','z');
    $alphabet2 = range('a','z');
    $newAlphabet = $alphabet;
    foreach($alphabet as $k => $r)
    {
        foreach($alphabet2 as $row){
            $newAlphabet[] = $r.$row;
        }
    }
    $key = array_search($char, $newAlphabet);
    return ($key !== false) ? $key : null;
}
lsblsb at gmx dot de 30-Apr-2014 03:09
I needed a function, that creates a letter range with arbitrary length.
You specify via the $length parameter, how many entries you need.
Logic is analog to the logic of the column-titles in a calc-sheet.

<?php

/**
  * create a letter range with arbitrary length
  * @param int $length
  * @return array
  */
function createLetterRange($length)
{
    $range = array();
    $letters = range('A', 'Z');
    for($i=0; $i<$length; $i++)
    {
        $position = $i*26;
        foreach($letters as $ii => $letter)
        {
            $position++;
            if($position <= $length)
                $range[] = ($position > 26 ? $range[$i-1] : '').$letter;
        }
    }
    return $range;
}
?>
php at keith tyler dot com 26-Feb-2014 10:22
So with the introduction of single-character ranges to the range() function, the internal function tries to be "smart", and (I am inferring from behavior here) apparently checks the type of the incoming values. If one is numeric, including numeric string, then the other is treated as numeric; if it is a non-numeric string, it is treated as zero.

But.

If you pass in a numeric string in such a way that is is forced to be recognized as type string and not type numeric, range() will function quite differently.

Compare:

<?php
echo implode("",range(9,"Q"));
// prints 9876543210

echo implode("",range("9 ","Q"));  //space after the 9
// prints 9:;<=>?@ABCDEFGHIJKLMNOPQ

echo implode("",range("q","9 "));
// prints qponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:987654
?>

I wouldn't call this a bug, because IMO it is even more useful than the stock usage of the function.
jazzduck AT gmail DOT com 21-Jan-2014 08:32
Despite the line above that says that the $step value should be "given as a positive number," the range() function will in fact correctly handle reversed (decrementing) ranges. For example:

<?php print_r( range( 24, 20 ) ); ?>
Array
(
    [0] => 24
    [1] => 23
    [2] => 22
    [3] => 21
    [4] => 20
)

<?php print_r( range( 20, 11, -3 ) ); ?>
Array
(
    [0] => 20
    [1] => 17
    [2] => 14
    [3] => 11
)

It will actually ignore the sign of the $step argument, and determine whether to increment or decrement based purely on whether $start > $end or $end > $start. For example:

<?php print_r( range( 20, 11, 3 ) ); ?>
Array
(
    [0] => 20
    [1] => 17
    [2] => 14
    [3] => 11
)

<?php print_r( range( 11, 20, -3 ) ); ?>
Array
(
    [0] => 11
    [1] => 14
    [2] => 17
    [3] => 20
)
pyetrosafe at gmail dot com 27-Sep-2013 01:36
To create a simple array or a multidimensional array with defined size and null values??, use this expression:

<?php

$SimpleArray = array_map(function($n) { return null; }, range(1, 3) );
$MultiArray = array_map(function($n) { return array_map(function($n) { return null; }, range(1, 2) ); }, range(1, 3) );

var_dump($SimpleArray);
var_dump($MultiArray);

// And will print:
?>
>>$SimpleArray
array(3) {
  [0]=>  NULL
  [1]=>  NULL
  [2]=>  NULL
}

>>$MultiArray
array(3) {
  [0]=>  array(2) {
    [0]=>    NULL
    [1]=>    NULL
  }
  [1]=>  array(2) {
    [0]=>    NULL
    [1]=>    NULL
  }
  [2]=>  array(2) {
    [0]=>    NULL
    [1]=>    NULL
  }
}

?>
krdr dot mft at gmail dot com 19-Aug-2013 09:48
I've been introduced with range() function not so long ago, and I found that examples about it is somewhat wrong, even inefficient:

<?php
$o = "";
$time_start = microtime(true);
foreach(range(1, 10000) as $val) {
    $o .= $val;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo 'rangein: '.$time.'<br />';

$o = "";
$time_start = microtime(true);
$a = range(1, 10000);
foreach($a as $val) {
    $o .= $val;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo 'rangeout: '.$time.'<br />';

?>

Which gives results:

rangein: 0.0025348663330078
rangeout: 0.0019199848175049

In some cases difference is even bigger and proportional to the range generated. I suppose that results of range() are cached/hashed.

Note: execution order does affects execution times, but difference still exists
Ray.Paseur often uses Gmail 06-Jun-2013 03:16
Interestingly, these two statements produce identical 26-character alphabet arrays.

<?php
$arr = range('A',  'Z');
$arr = range('AA', 'ZZ');
gtisza at gmail dot com 25-Apr-2013 10:27
You might expect range($n, $n-1) to be an empty array (as in e.g. Python) but actually PHP will assume a step of -1 if start is larger than end.
Palz 29-Oct-2012 10:59
To create a range array like

Array
(
    [11] => 1
    [12] => 2
    [13] => 3
    [14] => 4
)

combine two range arrays using array_combine:

array_combine(range(11,14),range(1,4))
ktamas77 at gmail dot com 03-Aug-2012 10:59
if you need zero padding, string prefixes or any other masks, then a simple combination of array_map, inline functions and sprintf is your friend.

<?php

$a = array_map(function($n) { return sprintf('sample_%03d', $n); }, range(50, 59) );

print_r($a);

?>

Will result:

Array
(
    [0] => sample_050
    [1] => sample_051
    [2] => sample_052
    [3] => sample_053
    [4] => sample_054
    [5] => sample_055
    [6] => sample_056
    [7] => sample_057
    [8] => sample_058
    [9] => sample_059
)
me at phpscott dot com 23-May-2012 05:37
So, I needed a quick and dirty way to create a dropdown select for hours, minutes and seconds using 2 digit formatting, and to create those arrays of data, I combined range with array merge..

<?php
$prepend = array('00','01','02','03','04','05','06','07','08','09');
$hours     = array_merge($prepend,range(10, 23));
$minutes     = array_merge($prepend,range(10, 59));
$seconds     = $minutes;
?>

Super simple.
dries at volta dot be 09-Feb-2012 11:30
Ever wanted to generate an array with a range of column names for use in Excel file related parsing?
I've wrote a function that starts at the A column and adds column names up until the column you specified.

<?php

/**
 * This function creates an array with column names up until the column
 * you specified.
*/
function createColumnsArray($end_column, $first_letters = '')
{
  $columns = array();
  $length = strlen($end_column);
  $letters = range('A', 'Z');

  // Iterate over 26 letters.
  foreach ($letters as $letter) {
      // Paste the $first_letters before the next.
      $column = $first_letters . $letter;

      // Add the column to the final array.
      $columns[] = $column;

      // If it was the end column that was added, return the columns.
      if ($column == $end_column)
          return $columns;
  }

  // Add the column children.
  foreach ($columns as $column) {
      // Don't itterate if the $end_column was already set in a previous itteration.
      // Stop iterating if you've reached the maximum character length.
      if (!in_array($end_column, $columns) && strlen($column) < $length) {
          $new_columns = createColumnsArray($end_column, $column);
          // Merge the new columns which were created with the final columns array.
          $columns = array_merge($columns, $new_columns);
      }
  }

  return $columns;
}

?>

Usage:

<?php

// Return an array with all column names from A until and with BI.
createColumnsArray('BI');

?>
Aram Kocharyan 27-Feb-2011 07:58
Here's a function to generate ranges from strings:

<?php

/*  Creates an array of integers based on a given range string of format "int - int"
    Eg. range_str('2 - 5'); */
function range_str($str) {
    preg_match('#(\\d+)\\s*-\\s*(\\d+)#', $str, $matches);
    if ( count($matches) == 3 ) {
        return range($matches[1], $matches[2]);
    }
    return FALSE;
}

// Test
$array = range_str(' 2 - 4 ');
print_r($array);

?>

This outputs:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
)
jay at NOspam dot myd3 dot com 29-Apr-2009 05:54
This is a modified version of thomas' range_string() function. It's simpler, cleaner, and more robust, but it lacks the advanced features his function had, hopefully it will be of assitance to someone.

Examples:

    input: "1, 2, 3, 4, 5, 6" --> output: 1, 2, 3, 4, 5, 6
    input: "1-6" --> output: 1, 2, 3, 4, 5, 6
    input: "1-6" --> output: 1, 2, 3, 4, 5, 6
    input: "1 - -6" --> output: 1, 2, 3, 4, 5, 6
    input: "0 - 0" --> output: 0
    input: "1, 4-6, 2" --> output: 1, 2, 4, 5, 6
    input: "6,3-1" --> output: 1, 2, 3, 6

<?php

define('RANGE_ARRAY_SORT', 1);
define('RANGE_ARRAY', 2);
define('RANGE_STRING_SORT', 3);
define('RANGE_STRING', 4);

function range_string($range_str, $output_type = RANGE_ARRAY_SORT)
{
    // Remove spaces and nother non-essential characters
    $find[]    = "/[^\d,\-]/";
    $replace[] = "";

    // Remove duplicate hyphens
    $find[]    = "/\-+/";
    $replace[] = "-";

    // Remove duplicate commas
    $find[]    = "/\,+/";
    $replace[] = ",";

    $range_str = preg_replace($find, $replace, $range_str);

    // Remove any commas or hypens from the end of the string
    $range_str = trim($range_str,",-");

    $range_out = array();
    $ranges    = explode(",", $range_str);

    foreach($ranges as $range)
    {

        if(is_numeric($range) || strlen($range) == 1)
        {
            // Just a number; add it to the list.
            $range_out[] = (int) $range;
        }
        else if(is_string($range))
        {

            // Is probably a range of values.
           $range_exp = preg_split("/(\D)/",$range,-1,PREG_SPLIT_DELIM_CAPTURE);

            $start = $range_exp[0];
            $end   = $range_exp[2];

            if($start > $end)
            {
                for($i = $start; $i >= $end; $i -= 1)
                {
                    $range_out[] = (int) $i;
                }
            }
            else
            {
                for($i = $start; $i <= $end; $i += 1)
                {
                    $range_out[] = (int) $i;
                }
            }

        }
    }

    switch ($output_type) {
        case RANGE_ARRAY_SORT:
            $range_out = array_unique($range_out);
            sort($range_out);

        case RANGE_ARRAY:
            return $range_out;
            break;

        case RANGE_STRING_SORT:
            $range_out = array_unique($range_out);
            sort($range_out);

        case RANGE_STRING:

        default:
            return implode(", ", $range_out);
            break;
    }
}

// Sample Usage:
$range = range_string("6, 3-1");

?>
ThinkMedical at Gmail dot com 26-Aug-2008 05:11
foreach(range()) whilst efficiant in other languages, such as python, it is not (compared to a for) in php*.

php is a C-inspired language and thus for is entirely in-keeping with the lanuage aethetic to use it

<?php
//efficiant
for($i = $start; $i < $end; $i+=$step)
{
        //do something with array
}

//inefficiant
foreach(range($start, $end, $step) as $i)
{
        //do something with array
}
?>

That the officiant documentation doesnt mention the for loop is strange.

Note however, that in PHP5 foreach is faster than for when iterating without incrementing a variable.

* My tests using microtime and 100 000 iterations consistently (~10 times) show that for is 4x faster than foreach(range()).
captvanhalen at gmail dot com 27-Mar-2008 10:33
Here is a home rolled range() function that uses the step feature for those unfortunate souls who cannot use PHP5:

<?php
function my_range( $start, $end, $step = 1) {

    $range = array();

    foreach (range( $start, $end ) as $index) {

        if (! (($index - $start) % $step) ) {
            $range[] = $index;
        }
    }

    return $range;
}
?>
chris at laflash dot org 09-May-2007 04:47
Quick HTML menus with minimum and maximum sets of years:

<?php
    /*
    ** Quick HTML menus with minimum and maximum sets of years.
    ** @author Chris Charlton <chris@laflash.org>
    ** @license FREE!
    */

    // Years range setup
    $year_built_min = 1900;
    $year_built_max = date("Y");
?>
<select id="yearBuiltMin" size="1">
    <?php // Generate minimum years

        foreach (range($year_built_min, $year_built_max) as $year) { ?>
        <option value="<?php echo($year); ?>"><?php echo($year); ?></option>
        <?php } ?>
</select>

<select id="yearBuiltMax" size="1">
      <?php // Generate max years

        foreach (range($year_built_max, $year_built_min) as $year) { ?>
        <option value="<?php echo($year); ?>"><?php echo($year); ?></option>
        <?php } ?>
</select>
m0sh3 at hotmail dot com 01-Mar-2007 05:46
Here's how i use it to check if array is associative or not:

<?php

if (array_keys($arr)===range(0, sizeof($arr)-1)) {
// not associative array

} else {
// associative array

}

?>
manuel at levante dot de 07-Nov-2006 05:25
<?php
function srange ($s) {
  preg_match_all("/([0-9]{1,2})-?([0-9]{0,2}) ?,?;?/", $s, $a);
  $n = array ();
  foreach ($a[1] as $k => $v) {
    $n  = array_merge ($n, range ($v, (empty($a[2][$k])?$v:$a[2][$k])));
  }
  return ($n);
}

$s = '1-4 6-7 9-10';
print_r(srange($s));
?>

Return:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 6
    [5] => 7
    [6] => 9
    [7] => 10
)
subscription101 at hotmail dot com 08-Jan-2006 06:36
A much simpler way of creating a range of even numbers is by starting with an even number:

<?php

    range(2, 10, 2);

?>
emory underscore smith at hotmail 20-Aug-2005 07:53
since its not stated explicitly above, thought id point out that you arent limited to using integers.

however, be careful when doing so, as you might not get the range you expect!

to illustrate:

<?php
$am = range(500,1600,10);
$fm = range(88.1,107.9,.2);
print_r($am);
print_r($fm);
?>

print_r($am) yields the expected result:

Array
(
    [0] => 500
    [1] => 510
    [2] => 520
    ...
    [109] => 1590
    [110] => 1600
)

print_r($fm), however, falls a bit (1%) short:

Array
(
    [0] => 88.1
    [1] => 88.3
    [2] => 88.5
    ...
    [97] => 107.5
    [98] => 107.7
)

so, if you want to use a non-integral step size params for numeric ranges, be sure to account for fp representation accuracy and error accumulation; a step size of something like pi or 1/10 could spell disaster for a large range. if in doubt, use integral steps and divide ... something like <?php range(88.1,108,.2) ?> might work to recover 107.9, but would not be scalable like, say <?php array_map(create_function('$x','return $x/10;'),range(881,1079,2)) ?>.

-emory
derek at php dot net 08-May-2005 06:13
This should emulate range() a little better.
<?php
function range_wroar($low, $high, $step = 1) {
    $arr = array();
    $step = (abs($step)>0)?abs($step):1;
    $sign = ($low<=$high)?1:-1;
    if(is_numeric($low) && is_numeric($high)) {
        //numeric sequence
        for ($i = (float)$low; $i*$sign <= $high*$sign; $i += $step*$sign)
            $arr[] = $i;
    }    else    {
        //character sequence
        if (is_numeric($low))
            return $this->range($low, 0, $step);
        if (is_numeric($high))
            return $this->range(0, $high, $step);
        $low = ord($low);
        $high = ord($high);
        for ($i = $low; $i*$sign <= $high*$sign; $i += $step*$sign) {

            $arr[] = chr($i);
        }
    }
    return $arr;
}
?>
j dot gizmo at aon dot at 23-Sep-2004 04:23
i figured i'd add some more functionality to the myRange() functions below.
now you can, besides giving a $step parameter,
1. count backwards
2. count with letters
3. give whatever parameter you want, there's nothing (i know of) that will cause an endless loop (try a negative $step for the previous function....)

<?php
function myRange($num1, $num2, $step=1)
{
    if (is_numeric($num1) && is_numeric($num2))
    {
        //we have a numeric range
        $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive
        $dir = ($num1<=$num2 ? 1 : -1); //get the direction
        for($i = (float)$num1; $i*$dir <= $num2*$dir; $i += $step*$dir)
        {
            $temp[] = $i;
        }
    }
    else
    {
        //we have a character range
        $num1=ord((string)$num1); //convert to ascii value
        $num2=ord((string)$num2);
        $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive
        $dir = ($num1<=$num2 ? 1 : -1); //get direction
        for($i = $num1; $i*$dir <= $num2*$dir; $i += $step*$dir)
        {
            $temp[] = chr($i);
        }
    }
    return $temp;
}

print_r(myRange( 1, 3, 0.5 )); //you can use fractional steps
print_r(myRange( "a", "k", 3 )); //or count letters
print_r(myRange( "5", "9" )); //numbers are detected even if hidden in strtings
print_r(myRange( "!", "%", 1/pi() )); //or mess around with senseless parameters

?>


Establece el puntero interno de un array a su primer elemento

  • « range
  • rsort »
  • PHP Manual
  • Funciones de Arrays
  • Establece el puntero interno de un array a su primer elemento

reset

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

reset — Establece el puntero interno de un array a su primer elemento

Descripción

reset ( array &$array ) : mixed

reset() rebobina el puntero interno de un array al primer elemento y devuelve el valor del primer elemento del array.

Parámetros

array

El array de entrada.

Valores devueltos

Devuelve el valor del primer elemento de un array o false si el array está vacío.

Ejemplos

Ejemplo #1 Ejemplo de reset()

<?php

$array = array('paso uno', 'paso dos', 'paso tres', 'paso cuatro');

// Por defecto, el puntero está en el primer elemento
echo current($array) . "<br />\n"; // "paso uno"

// Omite dos pasos
next($array);
next($array);
echo current($array) . "<br />\n"; // "paso tres"

// Resetea el puntero, empieza otra vez en paso uno
reset($array);
echo current($array) . "<br />\n"; // "paso uno"

?>

Ver también

  • current() - Devuelve el elemento actual en un array
  • each() - Devolver el par clave/valor actual de un array y avanzar el cursor del array
  • end() - Establece el puntero interno de un array a su último elemento
  • next() - Avanza el puntero interno de un array
  • prev() - Rebobina el puntero interno del array

User Contributed Notes

Bartek Ferek 30-Aug-2016 11:16
As for taking first key of an array, it's much more efficient to RESET and then KEY, rather then RESET result of ARRAY_KEYS (as sugested by gardnerjohng at gmail dot com).

<?php
reset($someArray);
echo key($someArray);
?>

This will give the same result but is much much faster. Larger arrays, better performance. Tested on 100-elements long array with 16 times faster results.
arne dot slabbinck at duo dot be 01-Oct-2015 03:43
Info:

Following code gives a strict warning in 5.4.45

      return reset(array_keys($result['node']));

"Strict warning: Only variables should be passed by reference"

So should be:

      $keys = array_keys($result['node']);
      return reset($keys);
arne dot ludwig at posteo dot de 18-Sep-2015 09:22
In response to gardnerjohng's note to retrieve the first _key_ of an array:

To retrieve the first _key_ of an array you can use the combination of reset() and key().

<?php
    $properties = array(
        'colour'   => 'grey',
        'flavour'  => 'rubber',
        'name'     => 'Mouse Ball',
        'texture'  => 'rubbery'
    );

    reset($properties);
    echo key($properties); // => 'colour'
?>

I prefer this solution as you don't have to create the keys array. This should (not measured) improve performance on large arrays.
gardnerjohng at gmail dot com 18-Sep-2014 05:54
If you need an easy way to retrieve the first *key* in an array (instead of the value), it can be done like this:

<?php
    $properties = array(
        'colour'   => 'grey',
        'flavour'  => 'rubber',
        'name'     => 'Mouse Ball',
        'texture'  => 'rubbery'
    );

    #    Will output "colour".
    echo reset(array_keys($properties));
?>
Potentially helpful for configuration files that define a sequence of items as an associative array.
Mladen Janjetovic 16-May-2013 10:07
Note that you can't use pointer here. It will reset the iteration counter in this case.
foreach($array as $key=>&$value) {...}

Use standard foreach instead
foreach($array as $key=>$value) {...}
milo at mdlwebsolutions dot com 03-Apr-2012 10:22
GOTCHA: If your first element is false, you don't know whether it was empty or not.

<?php

$a = array();
$b = array(false, true, true);
var_dump(reset($a) === reset($b)); //bool(true)

?>

So don't count on a false return being an empty array.
kendsnyder at gmail dot com 08-Feb-2010 08:12
Don't use `reset()` to get the first value of an associative array. It works great for true arrays but works unexpectedly on Iterator objects. http://bugs.php.net/bug.php?id=38478
m dot lebkowski+php at gmail dot com 03-Aug-2006 01:58
Colin, there`s a better (IMO) way to solve your problem.
<?
  // ...
  foreach($a as $k => &$d){}   // notice the "&"
  // ...
?>
It`s a new feature in PHP5 to use references in foreach loop. This way PHP isn`t making a copy of the array, so the internal pointer won`t be reset.
Colin 06-Jun-2006 08:11
I had a problem with PHP 5.0.5 somehow resetting a sub-array of an array with no apparent reason.  The problem was in doing a foreach() on the parent array PHP was making a copy of the subarrays and in doing so it was resetting the internal pointers of the original array.

The following code demonstrates the resetting of a subarray:

<?
$a = array(
    'a' => array(
        'A', 'B', 'C', 'D',
    ),
    'b' => array(
        'AA', 'BB', 'CC', 'DD',
    ),
);

// Set the pointer of $a to 'b' and the pointer of 'b' to 'CC'
reset($a);
next($a);
next($a['b']);
next($a['b']);
next($a['b']);

var_dump(key($a['b']));
foreach($a as $k => $d)
{
}
var_dump(key($a['b']));
?>

The result of the two var dumps are 3 and 0, respectively.  Clearly the internal pointer of $a['b'] was reset by doing the foreach loop over $a.

Each time the foreach loop iterated over the 'a' and 'b' keys of $a it made a copy of $a['a'] and $a['b'] into $d which resetted the internal pointers of $a['a'] and $a['b'] despite making no obvious changes.

The solution is instead to iterate over the keys of $a.

<?
foreach(array_keys($a) as $k)
{
}
?>

and using $a[$k] (or creating an alias of $a[$k] as $d and dealing with the consequences of using aliases).

For the curious, I was implementing the Iterator interface on a dummy object and calling a global object to do the actual iteration (also to cope with PHP's lack of C-style pointers which when doing a $a = $b on objects would cause the data in $a to be inconsistent with the data in $b when modified).  Being that I had many dummy objects representing different data sets I chose to store each data set as a subarray contained within the global object.  To make this work each dummy object has to store a key (which can freely be duplicated without problems) that it passes to the global object when rewind, key, current, next, and valid were called on the dummy object.

Unfortunately for me, my key required to be more than just a simple string or number (if it was then it could be used to directly index the subarray of data for that object and problem avoided) but was an array of strings.  Instead, I had to iterate over (with a foreach loop) each subarray and compare the key to a variable stored within the subarray.

So by using a foreach loop in this manner and with PHP resetting the pointer of subarrays it ended up causing an infinite loop.

Really, this could be solved by PHP maintaining internal pointers on arrays even after copying.
27-Feb-2006 01:20
I wrote a nice function, which rotates values of array. Very useful for table rows where you have to rotate colors

<?php
function rotate(&$array) {
    $item = current($array);
    if (!next($array)) reset($array);
    return $item;
}
?>
Alexandre Koriakine 18-Nov-2005 02:09
Also it's good to reset this way the multidimentional arrays:

reset($voo2['moder']);
while (list($key, $value) = each ($voo2['moder'])) {

reset($voo2['moder'][$key]);
while (list($key1, $value1) = each ($voo2['moder'][$key])) {
#do what u want
}

}
leaetherstrip at inbox dot NOSPAMru 17-Oct-2004 06:54
Note that reset() will not affect sub-arrays of multidimensional array.

For example,

<?php
    $arr = array(
        1 => array(2,3,4,5,6),
        2 => array(6,7,8,9,10)
    );

    while(list($i,) = each($arr))
    {
        echo "IN \$arr[$i]<br>";

        while(list($sub_i,$entry) = each($arr[$i]))
        {
            echo "\$arr[$i][$sub_i] = $entry<br>";
        }
    }

    reset($arr);

    // Do the same again
    while(list($i,) = each($arr))
    {
        echo "IN \$arr[$i]<br>";

        while(list($sub_i,$entry) = each($arr[$i]))
        {
            echo "\$arr[$i][$sub_i] = $entry<br>";
        }
    }
?>

will print

IN $arr[1]
$arr[1][0] = 2
$arr[1][1] = 3
$arr[1][2] = 4
$arr[1][3] = 5
$arr[1][4] = 6
IN $arr[2]
$arr[2][0] = 6
$arr[2][1] = 7
$arr[2][2] = 8
$arr[2][3] = 9
$arr[2][4] = 10
IN $arr[1]
IN $arr[2]


Ordena un array en orden inverso

  • « reset
  • shuffle »
  • PHP Manual
  • Funciones de Arrays
  • Ordena un array en orden inverso

rsort

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

rsort — Ordena un array en orden inverso

Descripción

rsort ( array &$array , int $sort_flags = SORT_REGULAR ) : bool

Esta función ordena un array en orden inverso (mayor a menor).

Nota:

Si dos miembros se comparan como iguales, su orden relativo en el array oredenado será indefinido.

Parámetros

array

El array de entrada.

sort_flags

Quizá se necesita cambiar el comportamiento de ordenado usando el parámetro opcional sort_flags, para más información ver sort().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de rsort()

<?php
$fruits = array("limón", "naranja", "plátano", "manzana");
rsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

El resultado del ejemplo sería:

0 = plátano
1 = naranja
2 = manzana
3 = limón

Las frutas han sido ordenadas alfábeticamente pero en orden inverso.

Notas

Nota: Esta función asigna nuevas clave a los elemenos del array. Eliminará cualquier clave existente que haya sido asignada, en lugar de reordenar las claves.

Ver también

  • arsort() - Ordena un array en orden inverso y mantiene la asociación de índices
  • krsort() - Ordena un array por clave en orden inverso
  • comparación de funciones de orden de arrays

User Contributed Notes

suniafkhami at gmail dot com 20-Feb-2014 02:40
If you are sorting an array from a database result set, such as MySQL for example, another approach could be to have your database sort the result set by using ORDER BY DESC, which would be the equivalent of using rsort() on the resulting array in PHP.

[Edited by moderator for clarity: googleguy at php dot net]
Alex M 27-Jun-2005 07:39
A cleaner (I think) way to sort a list of files into reversed order based on their modification date.

<?php
   $path = $_SERVER[DOCUMENT_ROOT]."/files/";
   $dh = @opendir($path);

   while (false !== ($file=readdir($dh)))
   {
      if (substr($file,0,1)!=".")
         $files[]=array(filemtime($path.$file),$file);   #2-D array
   }
   closedir($dh);

   if ($files)
   {
      rsort($files); #sorts by filemtime

      #done! Show the files sorted by modification date
      foreach ($files as $file)
         echo "$file[0] $file[1]<br>\n";  #file[0]=Unix timestamp; file[1]=filename
   }
?>
pshirkey at boosthardware dot com 14-Jan-2005 01:06
I needed a function that would sort a list of files into reversed order based on their modification date.

Here's what I came up with:

function display_content($dir,$ext){

    $f = array();
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($folder = readdir($dh)) !== false) {
                if (preg_match("/\s*$ext$/", $folder)) {
                    $fullpath = "$dir/$folder";
                    $mtime = filemtime ($fullpath);

                    $ff = array($mtime => $fullpath);
                    $f = array_merge($f, $ff);

            }
                }

            rsort($f, SORT_NUMERIC);

            while (list($key, $val) = each($f)) {
                $fcontents = file($val, "r");
                while (list($key, $val) = each($fcontents))
                    echo "$val\n";
            }

        }
    }

        closedir($dh);
}

Call it like so:

display_content("folder","extension");
ray at non-aol dot com 02-Nov-2004 07:49
Like sort(), rsort() assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.  This means that it will destroy associative keys.

$animals = array("dog"=>"large",  "cat"=>"medium",  "mouse"=>"small");
print_r($animals);
//Array ( [dog] => large [cat] => medium [mouse] => small )

rsort($animals);
print_r($animals);
//Array ( [0] => small [1] => medium [2] => large )

Use KSORT() or KRSORT() to preserve associative keys.
rnk-php at kleckner dot net 17-Jun-2003 12:37
Apparently rsort does not put arrays with one value back to zero.  If you have an array like: $tmp = array(9 => 'asdf') and then rsort it, $tmp[0] is empty and $tmp[9] stays as is.
slevy1 at pipeline dot com 12-Jun-2001 11:15
I thought rsort was working successfully or on a multi-dimensional array of strings that had first been sorted with usort(). But, I noticed today that the array  was only partially in descending order.  I tried array_reverse on it and that seems to have solved things.


Mezcla un array

  • « rsort
  • sizeof »
  • PHP Manual
  • Funciones de Arrays
  • Mezcla un array

shuffle

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

shuffle — Mezcla un array

Descripción

shuffle ( array &$array ) : bool

Esta función mezcla un array (crea un orden aleatorio de sus elementos). Utiliza un generador de números seudoaleatorios que no es apto para fines criptográficos.

Nota:

Si dos miembros se comparan como iguales, su orden relativo en el array oredenado será indefinido.

Parámetros

array

El array.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de shuffle()

<?php
$números = range(1, 20);
shuffle($números);
foreach ($números as $número) {
    echo "$número ";
}
?>

Notas

Nota: Esta función asigna nuevas clave a los elemenos del array. Eliminará cualquier clave existente que haya sido asignada, en lugar de reordenar las claves.

Ver también

  • array_rand() - Seleccionar una o más claves aleatorias de un array
  • comparación de funciones de orden de arrays

User Contributed Notes

thomas dot sahlin at invented dot se 16-May-2017 08:20
Here's a simple one liner for shuffling associative arrays:

<?php

uksort($myArray, function ($a, $b) {return mt_rand(-10, 10);});

?>
xzero at elite7hackers dot net 30-May-2015 01:09
There is an function which uses native shuffle() but preserves keys, and their order, so at end, only values are shuffled.

<?PHP
/**
 * Array Quake - Give an array good quake so every value will endup with random given space.
 * Keys, and their order are preserved.
 * @author xZero <xzero@elite7hackers.net>
 * @param array $array
 * @return boolean false on failure
 */
function array_quake(&$array) {
    if (is_array($array)) {
        $keys = array_keys($array); // We need this to preserve keys
        $temp = $array;
        $array = NULL;
        shuffle($temp); // Array shuffle
        foreach ($temp as $k => $item) {
            $array[$keys[$k]] = $item;
        }
        return;
    }
    return false;
}

// Example
$numbers = array(
    'ZERO' => 0,
    'ONE' => 1,
    'TWO' => 2,
    'THREE' => 3,
    'FOUR' => 4,
    'FIVE' => 5,
    'SIX' => 6,
    'SEVEN' => 7,
    'EIGHT' => 8,
    'NINE' => 9
);
echo "\nBefore (original):\n";
print_r($numbers);
array_quake($numbers);
echo "\n\nAfter (Array Quake);\n";
print_r($numbers);
echo "\n";
?>

Result example:
Before (original):
Array
(
    [ZERO] => 0
    [ONE] => 1
    [TWO] => 2
    [THREE] => 3
    [FOUR] => 4
    [FIVE] => 5
    [SIX] => 6
    [SEVEN] => 7
    [EIGHT] => 8
    [NINE] => 9
)

After (Array Quake);
Array
(
    [ZERO] => 4
    [ONE] => 2
    [TWO] => 0
    [THREE] => 8
    [FOUR] => 3
    [FIVE] => 6
    [SIX] => 1
    [SEVEN] => 7
    [EIGHT] => 5
    [NINE] => 9
)
peter at removethisplease dot ddcrew dot com 02-Dec-2013 01:55
This seems to do reasonably well as a shuffle() that preserves index assocation:

<?php
function ashuffle (&$arr) {
    uasort($arr, function ($a, $b) {
        return rand(-1, 1);
    });
}
?>

Obviously only works if PHP has closures enabled...
timtrinidad at gmail dot com 08-Aug-2011 12:38
It appears that the suhosin extensions >= 0.9.26 that have the suhosin.mt_srand.ignore and suhosin.srand.ignore settings set to "Off" do not affect shuffle().

In other words, the only way I was able to get pseudo-random and predictable results through shuffle() was to disable the extension.
Eric Anderson 29-Mar-2011 09:33
Copy and paste this script and refresh the page to see the shuffling effect.

<?php
    /**
    * Shuffles and displays cards in a deck
    * @author:     Eric Anderson
    * @filename:   deckofcards.php
    */

    // Create an array of face values
    // and an array of card values
    // then merge them together
    $cards = array_merge(array("J", "Q", "K", "A"), range(2,10)); // 13 cards

    // Shuffle the cards
    shuffle($cards);

    // Create an multidimentional array to hold the 4 suits
    $suits = array(
        'Heart' => array(),
        'Spade' => array(),
        'Diamond' => array(),
        'Club' => array()
        );

    // Add cards to their respective suits
    for($i = 0; $i < count($suits); $i++)
    {
        for($j = 0; $j < count($cards); $j++)
        {
            $suits['Heart'][$j] = $cards[$j]."<span style=color:#FF0000;>&hearts;</span>";
            $suits['Spade'][$j] = $cards[$j]."&spades;";
            $suits['Diamond'][$j] = $cards[$j]."<span style=color:#FF0000;>&diams;</span>";
            $suits['Club'][$j] = $cards[$j]."&clubs;";
        }
    }

    // Create a deck
    $deck = array();

    // Merge the suits into the empty deck array
    $deck = array_merge($deck, $suits);

    // Display the deck to the screen
    echo "<p><b>Deck of cards:</b></p>";
    foreach($deck as $k1 => $v1)
    {
        // Display suit name
        echo "<p>&emsp;$k1's<br />&emsp;{<br />&emsp;&emsp;";
        $acc = 0;

        // Display card value
        foreach($v1 as $k2 => $v2)
        {
            echo "$v2&nbsp";
            $acc++;

            if ($acc == 4)
            {
                echo "<br />&emsp;&emsp;";
                $acc = 0;
            }
        }
        echo "<br />&emsp;}</p>";
    }
?>
andjones at gmail dot com 26-Aug-2010 09:35
Shuffle associative and non-associative array while preserving key, value pairs. Also returns the shuffled array instead of shuffling it in place.

<?php

function shuffle_assoc($list) {
  if (!is_array($list)) return $list;

  $keys = array_keys($list);
  shuffle($keys);
  $random = array();
  foreach ($keys as $key)
    $random[$key] = $list[$key];

  return $random;
}

?>
ezakto at ezakto dot com 24-Jul-2010 11:13
This is a replica of shuffle() but preserving keys (associative and non-associative)

bool kshuffle  (  array &$array  )

<?php

function kshuffle(&$array) {
    if(!is_array($array) || empty($array)) {
        return false;
    }
    $tmp = array();
    foreach($array as $key => $value) {
        $tmp[] = array('k' => $key, 'v' => $value);
    }
    shuffle($tmp);
    $array = array();
    foreach($tmp as $entry) {
        $array[$entry['k']] = $entry['v'];
    }
    return true;
}

$array = array('first' => 0, 'second' => 1, 'third' => 2);
kshuffle($array);
print_r($array); // [second] => 1 [first] => 0 [third] => 2

$array = array('first', 'second', 'third');
kshuffle($array);
print_r($array); // [1] => second [2] => third [0] => first

?>
m0gr14 at gmail dot com 04-Jul-2010 10:39
This function shuffles an associative array recursive.

<?php

/**
* Shuffles an associative array recursive
* @author Mogria <m0gr14@gmail.com>
* @param array $array
* @return array
*
*/

function rec_assoc_shuffle($array)
{
  $ary_keys = array_keys($array);
  $ary_values = array_values($array);
  shuffle($ary_values);
  foreach($ary_keys as $key => $value) {
    if (is_array($ary_values[$key]) AND $ary_values[$key] != NULL) {
      $ary_values[$key] = rec_assoc_shuffle($ary_values[$key]);
    }
    $new[$value] = $ary_values[$key];
  }
  return $new;
}

?>

Example of use:
<?php
$array =
    Array(
        1,
        Array(
            1,
            2,
            3,
            4,
            Array(
                1,
                2,
                3,
                4,
                5
            )
        ),
        2,
        3,
        Array(
            0,
            1,
                Array(
                    1,
                    2,
                    3,
                    4,
                        Array(
                            1,
                            6,
                            5,
                            2,
                            1,
                            3
                        )
                )
        ),
        4,
        5,
        6,
        7
    );
$array = rec_assoc_shuffle($array);
echo '<pre>';
print_r($array);
echo '</pre>';

/*
Returns:
Array
(
    [0] => 6
    [1] => 5
    [2] => Array
        (
            [0] => 1
            [1] => 3
            [2] => Array
                (
                    [0] => 3
                    [1] => 1
                    [2] => 2
                    [3] => 4
                    [4] => 5
                )

            [3] => 2
            [4] => 4
        )

    [3] => 3
    [4] => Array
        (
            [0] => Array
                (
                    [0] => 3
                    [1] => 1
                    [2] => 4
                    [3] => Array
                        (
                            [0] => 5
                            [1] => 1
                            [2] => 3
                            [3] => 6
                            [4] => 1
                            [5] => 2
                        )

                    [4] => 2
                )

            [1] => 1
            [2] => 0
        )

    [5] => 2
    [6] => 1
    [7] => 4
    [8] => 7
)

*/

?>
rick at suggestive dot com 24-Mar-2010 02:19
Many people in SEO need to supply an array and shuffle the results and need the same result each time that page is generated. This is my implementation with a working example:

<?php
function seoShuffle(&$items,$string) {
    mt_srand(strlen($string));
    for ($i = count($items) - 1; $i > 0; $i--){
        $j = @mt_rand(0, $i);
        $tmp = $items[$i];
        $items[$i] = $items[$j];
        $items[$j] = $tmp;
    }
}

$items = array('one','two','three','four','five','six');
$string = 'whatever';

echo '<pre>';
print_r($items);
echo '</pre>';

seoShuffle($items,$string);

echo '<pre>';
print_r($items);
echo '</pre>';
?>
tyler at CompLangs dot com 01-Jan-2010 06:59
Here is a quick function I wrote that generates a random password and uses shuffle() to easily shuffle the order.

<?php
public function randPass($upper = 3, $lower = 3, $numeric = 3, $other = 2) {
    //we need these vars to create a password string
    $passOrder = Array();
    $passWord = '';

    //generate the contents of the password
    for ($i = 0; $i < $upper; $i++) {
        $passOrder[] = chr(rand(65, 90));
    }
    for ($i = 0; $i < $lower; $i++) {
        $passOrder[] = chr(rand(97, 122));
    }
    for ($i = 0; $i < $numeric; $i++) {
        $passOrder[] = chr(rand(48, 57));
    }
    for ($i = 0; $i < $other; $i++) {
        $passOrder[] = chr(rand(33, 47));
    }

    //randomize the order of characters
    shuffle($passOrder);

    //concatenate into a string
    foreach ($passOrder as $char) {
        $passWord .= $char;
    }

    //we're done
    return $passWord;
}
?>
ahmad at ahmadnassri dot com 18-Nov-2009 08:58
shuffle for associative arrays, preserves key=>value pairs.
(Based on (Vladimir Kornea of typetango.com)'s function)

<?php
    function shuffle_assoc(&$array) {
        $keys = array_keys($array);

        shuffle($keys);

        foreach($keys as $key) {
            $new[$key] = $array[$key];
        }

        $array = $new;

        return true;
    }
?>

*note: as of PHP 5.2.10, array_rand's resulting array of keys is no longer shuffled, so we use array_keys + shuffle.
Anonymous 28-Aug-2009 09:18
I needed a simple function two shuffle a two dimensional array. Please note the second level arrays must be indexed using integers, for example $myarray[0]["Name"] and not $myarray["One"]["Name"]. Here is the function:

<?php
function twodshuffle($array)
{
    // Get array length
    $count = count($array);
    // Create a range of indicies
    $indi = range(0,$count-1);
    // Randomize indicies array
    shuffle($indi);
    // Initialize new array
    $newarray = array($count);
    // Holds current index
    $i = 0;
    // Shuffle multidimensional array
    foreach ($indi as $index)
    {
        $newarray[$i] = $array[$index];
        $i++;
    }
    return $newarray;
}
?>

Please note it only works on two dimensional arrays. Here is an example:

<?php
$myarray = array("Google" => array("Name" => "Google", "URL" => "www.google.com", "Usage" => "Googling"), "Yahoo" => array("Name" => "Yahoo", "URL" => "www.yahoo.com", "Usage" => "Yahooing?"), "Ask" => array("Name" => "Ask", "URL" => "www.ask.com", "Usage" => "Asking Jeeves"));

print_r(twodshuffle($myarray));

/* And the result is:
Array ( [0] => Array ( [Name] => Ask [URL] => www.ask.com [Usage] => Asking Jeeves ) [1] => Array ( [Name] => Google [URL] => www.google.com [Usage] => Googling ) [2] => Array ( [Name] => Yahoo [URL] => www.yahoo.com [Usage] => Yahooing? ) )
*/
?>

Hope you find it useful!
aalaap at gmail dot com 08-Jun-2009 05:12
I've been wondering why shuffle() doesn't provide the shuffled array as a return value instead of a bool. I mean, what could possibly go wrong in shuffling elements from an array?

So I use something like this:

<?php
function array_shuffle($array) {
    if (shuffle($array)) {
        return $array;
    } else {
        return FALSE;
    }
}
?>
sivaji2009 at gmail dot com 17-May-2009 02:07
Here i wrote a custom shuffle function which preserves the array index and distributes the array element randomly.

<?php

/*
 * return an array whose elements are shuffled in random order.
 */
function custom_shuffle($my_array = array()) {
  $copy = array();
  while (count($my_array)) {
    // takes a rand array elements by its key
    $element = array_rand($my_array);
    // assign the array and its value to an another array
    $copy[$element] = $my_array[$element];
    //delete the element from source array
    unset($my_array[$element]);
  }
  return $copy;
}

$array = array(
  'a' => 'apple',
  'b' => 'ball',
  'c' => 'cat',
  'd' => 'dog',
  'e' => 'egg',
  'f' => 'fan',
  'g' => 'gun'
);

print_r(custom_shuffle($array));

Array
(
    [c] => cat
    [e] => egg
    [f] => fan
    [a] => apple
    [b] => ball
    [g] => gun
    [d] => dog
)

?>
dirk dot avery a t gmail 30-Apr-2009 08:58
Building on examples by m227 and pineappleclock, here is a function that returns all permutations of each set in the power set of an array of strings (instead of a string).  Thanks for the great examples!

<?php

/*
 Use: $arr = power_perms($in);

 Example:
  $in = array("A","B","C");
  $power_perms = power_perms($in);

 Returns:
  Array
  (
    [0] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )

    [1] => Array
        (
            [0] => A
            [1] => C
            [2] => B
        )

    [2] => Array
        (
            [0] => B
            [1] => A
            [2] => C
        )

    [3] => Array
        (
            [0] => B
            [1] => C
            [2] => A
        )

    [4] => Array
        (
            [0] => C
            [1] => A
            [2] => B
        )

    [5] => Array
        (
            [0] => C
            [1] => B
            [2] => A
        )

    [6] => Array
        (
            [0] => A
            [1] => B
        )

    [7] => Array
        (
            [0] => B
            [1] => A
        )

    [8] => Array
        (
            [0] => B
            [1] => C
        )

    [9] => Array
        (
            [0] => C
            [1] => B
        )

    [10] => Array
        (
            [0] => A
            [1] => C
        )

    [11] => Array
        (
            [0] => C
            [1] => A
        )

    [12] => Array
        (
            [0] => A
        )

    [13] => Array
        (
            [0] => B
        )

    [14] => Array
        (
            [0] => C
        )

  )

*/

function power_perms($arr) {

    $power_set = power_set($arr);
    $result = array();
    foreach($power_set as $set) {
        $perms = perms($set);
        $result = array_merge($result,$perms);
    }
    return $result;
}

function power_set($in,$minLength = 1) {

   $count = count($in);
   $members = pow(2,$count);
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minLength) {
         $return[] = $out;
      }
   }

   //usort($return,"cmp");  //can sort here by length
   return $return;
}

function factorial($int){
   if($int < 2) {
       return 1;
   }

   for($f = 2; $int-1 > 1; $f *= $int--);

   return $f;
}

function perm($arr, $nth = null) {

    if ($nth === null) {
        return perms($arr);
    }

    $result = array();
    $length = count($arr);

    while ($length--) {
        $f = factorial($length);
        $p = floor($nth / $f);
        $result[] = $arr[$p];
        array_delete_by_key($arr, $p);
        $nth -= $p * $f;
    }

    $result = array_merge($result,$arr);
    return $result;
}

function perms($arr) {
    $p = array();
    for ($i=0; $i < factorial(count($arr)); $i++) {
        $p[] = perm($arr, $i);
    }
    return $p;
}

function array_delete_by_key(&$array, $delete_key, $use_old_keys = FALSE) {

    unset($array[$delete_key]);

    if(!$use_old_keys) {
        $array = array_values($array);
    }

    return TRUE;
}
?>
pineappleclock at gmail dot com 22-Jan-2009 10:06
If you want the Power Set (set of all unique subsets) of an array instead of permutations, you can use this simple algorithm:

<?php
/**
* Returns the power set of a one dimensional array,
* a 2-D array.
* array(a,b,c) ->
* array(array(a),array(b),array(c),array(a,b),array(b,c),array(a,b,c))
*/
function powerSet($in,$minLength = 1) {
   $count = count($in);
   $members = pow(2,$count);
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minLength) {
         $return[] = $out;
      }
   }
   return $return;
}
?>
tony at brokerbin dot com 11-Nov-2008 07:26
Here is IMO the simplest and extremely fast way to shuffle an associative array AND keep the key=>value relationship.  However, it ONLY works if there are NO NUMERIC keys AT ALL.  Look into array_merge for the reason why.

<?php

$unshuffled = array('one'=>1,'two'=>2,'three'=>3);

$shuffled = array_merge( array_flip(array_rand($unshuffled,count($unshuffled))),$unshuffled );

?>

peace
Antonio Ognio 06-May-2008 09:42
Another shuffle() implementation that preserves keys, does not use extra memory and perhaps is a bit easier to grasp.

<?php
if (function_exists('shuffle_with_keys')===false) {
  function shuffle_with_keys(&$array) {
    /* Auxiliary array to hold the new order */
    $aux = array();
    /* We work with an array of the keys */
    $keys = array_keys($array);
    /* We shuffle the keys */
    shuffle($keys);
    /* We iterate thru' the new order of the keys */
    foreach($keys as $key) {
      /* We insert the key, value pair in its new order */
      $aux[$key] = $array[$key];
      /* We remove the element from the old array to save memory */
      unset($array[$key]);
    }
    /* The auxiliary array with the new order overwrites the old variable */
    $array = $aux;
  }
}
?>
07-Jun-2006 02:53
Posted below is code that you would expect to work

<?php

$keys = shuffle(array_keys($arr));

foreach ($keys as $key) {

  $arr_elem = $arr[$key];
  // do what you want with the array element

}

?>

This in fact does not work because shuffle returns a boolean true or false. More accurate code using this method would be:

<?php

$keys = array_keys($arr);
shuffle($keys);

foreach ($keys as $key) {

  $arr_elem = $arr[$key];
  // do what you want with the array element

}

?>
bill at SWScripts dot com 22-Sep-2005 09:45
Just a quick note to let people know that shuffle() will work on multidimensional associative arrays provided that the first key is already numeric.

So this array can be shuffled without losing any of the secondary keys or their values:

$array[0]['color'], $array[0]['size'], $array[0]['fabric']
. . .
$array[50]['color'], $array[50]['size'], $array[50]['fabric']

I recently ran up against needing to randomize this array and tried shuffle even though it's not really for associative arrays.

Hope it helps somebody out there.


Alias de count

  • « shuffle
  • sort »
  • PHP Manual
  • Funciones de Arrays
  • Alias de count

sizeof

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

sizeof — Alias de count()

Descripción

Esta función es un alias de: count().

User Contributed Notes

chris at amis dot nl 02-Sep-2013 09:15
I would recommend not using sizeof(). Many programmers expect sizeof() to return the amount of memory allocated. Instead sizeof() -as described above- is an alias for count().

Prevent misinterpretation and use count() instead.
umopdn [at] msn [dawt] com 23-Sep-2008 02:38
a) Always try and use PHP's internal routines to iterate through objects of various types (arrays in most examples below).

Instead of interpreting your code to loop through them, they use their own internal routines which are much faster.

(This is why foreach () will run faster than manual interation)

b) It is _always_ good practice to leave as many static resulting functions outside of loops, having operations that return the exact same piece of data every iteration of the loop is not pretty on resources.

c) I agree with PixEye's remarks on sizeof().  In PHP it is just an alias for the true function count().  It has other meanings logically in other languages rather than the number of elements in an object.  This should be avoided as it may confuse developers transitioning to PHP from other languages.
PixEye 23-Sep-2008 09:09
I am quite surprised about previous posts. Here are my advices:

1/ prefer the count() function instead of sizeOf() as sizeOf() is only an alias of count() and does not mean the same in many other languages based on C (avoid ambiguity).

2/ prefer the powerful forEach() function to iterate over arrays.
communiti.ch 10-Apr-2008 06:55
If your array is "huge"

It is reccomended to set a variable first for this case:

THIS->

$max = sizeof($huge_array);
for($i = 0; $i < $max;$i++)
{
code...
}

IS QUICKER THEN->

for($i = 0; $i < sizeof($huge_array);$i++)
{
code...
}


Ordena un array

  • « sizeof
  • uasort »
  • PHP Manual
  • Funciones de Arrays
  • Ordena un array

sort

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

sort — Ordena un array

Descripción

sort ( array &$array , int $sort_flags = SORT_REGULAR ) : bool

Esta función ordena un array. Los elementos estarán ordenados de menor a mayor cuando la función haya terminado.

Nota:

Si dos miembros se comparan como iguales, su orden relativo en el array oredenado será indefinido.

Parámetros

array

El array de entrada.

sort_flags

El segundo parámetro opcional sort_flags puede ser usado para modificar el modo de ordenación usando estos valores:

Tipos de ordenación:

  • SORT_REGULAR - compara elementos normalmente (no cambia los tipos)
  • SORT_NUMERIC - compara elementos de forma numérica
  • SORT_STRING - compara elementos como cadenas
  • SORT_LOCALE_STRING - compara elementos como cadenas, basándose en la configuración regional en uso. Utiliza la configuración regional, la cual puede cambiarse usando setlocale().
  • SORT_NATURAL - compara elementos como cadenas usando el "orden natural" de la misma forma que natsort().
  • SORT_FLAG_CASE - se puede combinar (OR a nivel de bits) con SORT_STRING o SORT_NATURAL para ordenar cadenas de forma insensible a mayúsculas/minúsculas.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
5.4.0 | Se añadió el soporte para SORT_NATURAL y SORT_FLAG_CASE como sort_flags
5.0.2 | Se añadió SORT_LOCALE_STRING

Ejemplos

Ejemplo #1 Ejemplo de sort()

<?php

$frutas = array("limón", "naranja", "banana", "albaricoque");
sort($frutas);
foreach ($frutas as $clave => $valor) {
    echo "frutas[" . $clave . "] = " . $valor . "\n";
}

?>

El resultado del ejemplo sería:

frutas[0] = albaricoque
frutas[1] = banana
frutas[2] = limón
frutas[3] = naranja

Las frutas han sido ordenadas en orden alfabético.

Ejemplo #2 Ejemplo de sort() usando la ordenación insensible a mayúsculas/minúsculas natural

<?php

$frutas = array(
    "Naranja1", "naranja2", "Naranja3", "naranja20"
);
sort($frutas, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($frutas as $clave => $valor) {
    echo "frutas[" . $clave . "] = " . $valor . "\n";
}

?>

El resultado del ejemplo sería:

frutas[0] = Naranja1
frutas[1] = naranja2
frutas[2] = Naranja3
frutas[3] = naranja20

Las frutas han sido ordenadas de la misma forma que natcasesort().

Notas

Nota: Esta función asigna nuevas clave a los elemenos del array. Eliminará cualquier clave existente que haya sido asignada, en lugar de reordenar las claves.

Nota: Como la mayoría de funciones de ordenación de PHP, sort() utiliza una implementación de » Quicksort. El pivote es elegido en la mitad de la partición resultando en un tiempo óptimo para los arrays ya ordenados. Aunque esto es un detalle de implementación con el que no debería contar.

Advertencia

Se ha de tener cuidado cuando se ordenen arrays con valores de tipos mixtos ya que sort() puede producir resultados impredecibles.

Ver también

  • asort() - Ordena un array y mantiene la asociación de índices
  • comparación de funciones de orden de arrays

User Contributed Notes

aminkhoshzahmat at gmail dot com 01-Jun-2020 07:02
Let's say we have a list of names, and it is not sorted.

<?php

$names = array('Amin', 'amir', 'sarah', 'Somayeh', 'armita', 'Armin');

sort($names); // simple alphabetical sort
print_r($names);
?>
Result is :
Array
(
    [0] => Amin
    [1] => Armin
    [2] => Somayeh // actually it's not sort alphabetically from here!
    [3] => amir         // comparison is based on ASCII values.
    [4] => armita
    [5] => sarah
)

If you want to sort alphabeticaly no matter it is upper or lower case:

<?php

sort($names, SORT_STRING | SORT_FLAG_CASE);
print_r($names);
?>

Result is:
Array
(
    [0] => Amin
    [1] => amir
    [2] => Armin
    [3] => armita
    [4] => sarah
    [5] => Somayeh
)
Md. Abutaleb 25-Feb-2020 12:28
<?php
/*
As I found the sort() function normally works as ascending order based on the following priority :
1. NULL
2. Empty
3. Boolean FALSE
4. String
5. Float
6. Int
7. Array
8. Object

Consider the following array:
*/

$a = ['fruit'=> 'apple', 'A' => 10, 20, 5, 2.5, 5=>'A new value', 'last' => 'value', TRUE, NULL, "", FALSE, array(), new StdClass];
sort($a);
var_dump($a);

#The output is:

array(13) {
  [0]=>NULL
  [1]=> string(0) ""
  [2]=>bool(false)
  [3]=>string(11) "A new value"
  [4]=>string(5) "apple"
  [5]=>string(5) "value"
  [6]=> float(2.5)
  [7]=> int(5)
  [8]=>int(10)
  [9]=>int(20)
  [10]=>array(0) { }
  [11]=> bool(true)
  [12]=>object(stdClass)#1 (0) {}
}

//Hope it will remove your confusion when you're sorting an array with mix type data.
?>
r at rcse dot de 23-Dec-2018 10:15
Here is no word about sorting UTF-8 strings by any collation. This should not be so uncommon?
Abhishek Banerjee 08-Jun-2016 07:39
EDIT: To the original note by "phpdotnet at m4tt dot co dot uk"
Use array_push instead of $new_array[$k] for some reason it was
giving me string indexes.

Simple function to sort an array by a specific key. Maintains index association.

<?php

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            array_push($new_array, $array[$k]);
        }
    }

    return $new_array;
}

$people = array(
    12345 => array(
        'id' => 12345,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    12346 => array(
        'id' => 12346,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    12347 => array(
        'id' => 12347,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname

/*
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
*/

?>
aditycse at gmail dot com 07-Aug-2015 10:34
/*
 * Name : Aditya Mehrotra
 * Email: aditycse@gmail.com
 */
//Example for sorting by values for an alphanumeric array also having case-sensitive data
$exampleArray1 = $exampleArray2 = array(
    0 => 'example1',
    1 => 'Example10',
    2 => 'example12',
    3 => 'Example2',
    4 => 'example3',
    5 => 'EXAMPLE10',
    6 => 'example10'
);

//default sorting
asort($exampleArray1);

// alphanumeric with case-sensitive data sorting by values
asort($exampleArray2, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);

//output of defaut sorting
print_r($exampleArray1);
/*
 * output of default sorting
  Array
  (
  [5] => EXAMPLE10
  [1] => Example10
  [3] => Example2
  [0] => example1
  [6] => example10
  [2] => example12
  [4] => example3
  )
 */

print_r($exampleArray2);
/*
 * output of alphanumeric with case-sensitive data sorting by values
 Array
(
    [0] => example1
    [3] => Example2
    [4] => example3
    [5] => EXAMPLE10
    [1] => Example10
    [6] => example10
    [2] => example12
)
 */
williamprogphp at[pleaseNOTSPAM] yahoo d 20-Dec-2013 12:15
In order to make some multidimensional quick sort implementation, take advantage of this stuff

<?php
        function quickSortMultiDimensional($array, $chave) {
            if( count( $array ) < 2 ) {
                return $array;
            }
            $left = $right = array( );
            reset( $array );
            $pivot_key    = key( $array );
            $pivot    = array_shift( $array );
            foreach( $array as $k => $v ) {
                if( $v[$chave] < $pivot[$chave] )
                        $left[$k][$chave] = $v[$chave];
                else
                        $right[$k][$chave] = $v[$chave];
            }
            return array_merge(
                                    quickSortMultiDimensional($left, $chave),
                                    array($pivot_key => $pivot),
                                    quickSortMultiDimensional($right, $chave)
            );
        }
?>

I make it using the idea from pageconfig dot com

tks for viewing
me[ at ]szczepan[ dot ]info 27-Dec-2012 12:36
Sorting the keys, but keep the values in order is not possible by just ordering, because it would result in a new array. This is also the solution: Create a new array

<?php
$a = array(9=>"a",8=>"c",5=>"d");

$keys = array_keys($a);
sort($keys);
$result = array_combine($keys, array_values($a));

//Result : array(5=>"a",8=>"c",9=>"d");
?>
Walter Tross 16-Dec-2011 02:38
unless you specify the second argument, "regular" comparisons will be used. I quote from the page on comparison operators:
"If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically."
What this means is that "10" < "1a", and "1a" < "2", but "10" > "2". In other words, regular PHP string comparisons are not transitive.
This implies that the output of sort() can in rare cases depend on the order of the input array:
<?php
function echo_sorted($a)
{
   echo "{$a[0]} {$a[1]} {$a[2]}";
   sort($a);
   echo " => {$a[0]} {$a[1]} {$a[2]}\n";
}
// on PHP 5.2.6:
echo_sorted(array( "10", "1a", "2")); // => 10 1a 2
echo_sorted(array( "10", "2", "1a")); // => 1a 2 10
echo_sorted(array( "1a", "10", "2")); // => 2 10 1a
echo_sorted(array( "1a", "2", "10")); // => 1a 2 10
echo_sorted(array( "2", "10", "1a")); // => 2 10 1a
echo_sorted(array( "2", "1a", "10")); // => 10 1a 2
?>
ajanata at gmail dot com 20-Oct-2011 09:13
This took me longer than it should have to figure out, but if you want the behavior of sort($array, SORT_STRING) (that is, re-indexing the array unlike natcasesort) in a case-insensitive manner, it is a simple matter of doing usort($array, strcasecmp).
alex dot hristov dot 88 at gmail dot com 16-Jun-2011 07:26
As some people have mentioned before sorting a multidimentional array can be a bit tricky. it took me quite a while to get it going but it works as a charm:

<?php
//$order has to be either asc or desc
 function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) {
        if(is_array($array) && count($array)>0) {
            foreach(array_keys($array) as $key)
            $temp[$key]=$array[$key][$index];
            if(!$natsort) {
                if ($order=='asc')
                    asort($temp);
                else
                    arsort($temp);
            }
            else
            {
                if ($case_sensitive===true)
                    natsort($temp);
                else
                    natcasesort($temp);
            if($order!='asc')
                $temp=array_reverse($temp,TRUE);
            }
            foreach(array_keys($temp) as $key)
                if (is_numeric($key))
                    $sorted[]=$array[$key];
                else
                    $sorted[$key]=$array[$key];
            return $sorted;
        }
    return $sorted;
}
?>
cmarshall at gmx dot de 17-May-2011 03:10
I read up on various problems re: sort() and German Umlaut chars and my head was soon spinning - bug in sort() or not, solution via locale or not, etc. ... (a total newbie here).

The obvious solution for me was quick and dirty: transform the Umlaut chars (present as HTML codes in my case) to their normal equivalent ('ä' = 'ae', 'ö' = 'oe', 'ü' = 'ue', 'ß' = 'ss' etc.), sort the array, then transform back. However there are cases in which a 'Mueller' is really that and does NOT need to be transformed into 'Müller' afterwards. Hence I for example replace the Umlaut itself with it's normal equivalent plus a char not used in the string otherwise (e.g. '_') so that the transfer back to Umlaut would only take place on certain combinations.

Of course any other char instead of '_' can be used as additional char (influencing the sort result). I know that my solution is rough at the edges and may cause other sort problems but it was sufficient for my purpose.

The array '$dat' in this example was filled with German town names (I actually worked with a multiple array ('$dat[][]') but stripped the code down to this as it's easier to understand):

<?php
// START Pre-sorting (Umlaut -> normal letters)
$max = count($dat);
for($totcnt = 0; $totcnt < $max; $totcnt++){
   $dat[$totcnt]=str_replace('&szlig;','ss_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Auml;','Ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&auml;','ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Ouml;','Oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&ouml;','oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Uuml;','Ue_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&uuml;','ue_',$dat[$totcnt]);
}
// END Pre-sorting (Umlaut -> normal letters)

// START Sorting //
function compare_towns($a, $b)
{
return strnatcmp($a, $b);
}
usort($dat, 'compare_towns');
// END Sorting //

// START Post-sorting (normal letters -> Umlaut)
for($totcnt = 0; $totcnt < $max; $totcnt++){
   $dat[$totcnt]=str_replace('ss_','&szlig;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Ae_','&Auml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('ae_','&auml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Oe_','&Ouml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('oe_','&ouml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Ue_','&Uuml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('ue_','&uuml;',$dat[$totcnt]);
}
// END Post-sorting (normal letters -> Umlaut)
?>
anaz114119 at gmail dot com 24-Dec-2010 02:34
sort from textfile by coloumn
example name||date||time||comments
if you want to sort by date
$column = 2
<?php
function array_sort($array,$column){
 $column = $column-1;
 foreach($array as $line){
 $bits = explode("||",$line);
 $bits ="$bits[$column]**$line";
 $array1[]=$bits;
}
 asort($array1);
 foreach($array1 as $line){
 $bit = explode("**",$line);
 $bit ="$bit[1]";
 $array2[]=$bit;
}
 return$array2;
}
?>
poulou_0 at hotmail dot com 21-Dec-2010 12:59
if you are not interested in high or low case sort

<?php
//where
$sortable_array[$k] = $v2;
//put
$sortable_array[$k] = strtolower($v2);

//and where
$sortable_array[$k] = $v;
//put
$sortable_array[$k] = strtolower($v);
?>
phpdotnet at m4tt dot co dot uk 16-Aug-2010 07:03
Simple function to sort an array by a specific key. Maintains index association.

<?php

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

$people = array(
    12345 => array(
        'id' => 12345,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    12346 => array(
        'id' => 12346,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    12347 => array(
        'id' => 12347,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname

/*
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
*/

?>
eriewave at hotmail dot com 29-Mar-2010 01:16
If you need to sort an array containing some equivalent values and you want the equivalents to end up next to each other in the overall order (similar to a MySQL's ORDER BY output), rather than breaking the function, do this:

<?php

sort($array, ksort($array))

?>

-When the sort() function finds two equivalents, it will sort them arbitrarily by their key #'s as a second parameter.

-Dirk
Brecht Cloetens 23-Nov-2009 03:57
<?php

/**
 * function: array_columns
 * author: Brecht Cloetens
 * params: $a = array() // original array
 *         $c = int() // number of columns
 */
function array_columns(&$a, $c=2)
{
    $m = ceil(count($a)/$c);
    $j = 0;
    for($i=0; $i<$m; $i++) {
        for($k=0; $k<$c; $k++) {
            $key = $i+($m*$k);
            settype($key,'integer');
            if(array_key_exists($key,$a)) {
                $b[$j] = $a[$key];
                $j++;
            }
        }
    }
    $a = $b;
}

$arr = range('a','z');
array_columns($arr,4);
print_r($arr);

?>

Example:
array(1,2,3,4,5) will be converted to array(1,4,2,5,3);

This can be easy if you want to display an array into a specified number of columns.

<table>
    <tr>
        <td>$arr[0] => 1</td>
        <td>$arr[1] => 4</td>
    </tr>
    <tr>
        <td>$arr[2] => 2</td>
        <td>$arr[3] => 5</td>
    </tr>
    <tr>
        <td>$arr[4] => 3</td>
        <td></td>
    </tr>
</table>
petr dot biza at gmail dot com 11-Sep-2009 06:29
Here is a function to sort an array by the key of his sub-array with keep key in top level.

<?php
function sksort(&$array, $subkey="id", $sort_descending=false, $keep_keys_in_sub = false) {
    $temp_array = $array;

    foreach ($temp_array as $key => &$value) {

      $sort = array();
      foreach ($value as $index => $val) {
          $sort[$index] = $val[$subkey];
      }

      asort($sort);

      $keys = array_keys($sort);
      $newValue = array();
      foreach ($keys as $index) {
        if($keep_keys_in_sub)
            $newValue[$index] = $value[$index];
          else
            $newValue[] = $value[$index];
      }

      if($sort_descending)
        $value = array_reverse($newValue, $keep_keys_in_sub);
      else
        $value = $newValue;
    }

    $array = $temp_array;
  }
?>
danm68 at gmail dot com 25-Aug-2009 09:59
sort() used with strings doesn't sort just alphabetically. It sorts all upper-case strings alphabetically first and then sorts lower-case strings alphabetically second.
Just in case anyone was as confused as I was and I've never seen this mentioned anywhere.
stepmuel at ee dot ethz dot ch 09-Dec-2008 08:14
A little shorter way to sort an array of objects; with a callback function.

<?php
function objSort(&$objArray,$indexFunction,$sort_flags=0) {
    $indices = array();
    foreach($objArray as $obj) {
        $indeces[] = $indexFunction($obj);
    }
    return array_multisort($indeces,$objArray,$sort_flags);
}

function getIndex($obj) {
    return $obj->getPosition();
}

objSort($objArray,'getIndex');
?>
www at designdetector dot com 09-Sep-2008 07:43
To sort an array of multiple text fields alphabetically you have to make the text lowercase before sorting the array. Otherwise PHP puts acronyms before words. You can see this in my example code. Simply store the original text field at the end of the array line and call it later from there. You can safely ignore the lowercase version which is added to the start of the array line.

<?php
echo '<pre>ORIGINAL DATA:
<br />';

$data = array(
'Saturn|7|8|9|0||',
'Hello|0|1|2|3||',
'SFX|5|3|2|4||',
'HP|9|0|5|6||'
);

print_r($data);

sort($data);
reset($data);

echo '<br />RAW SORT:
<br />';

print_r($data);

for ($c = 0; $c < count($data); $c++) {
    list ($letter,$g1,$g2,$g3,$g4,$end) = explode ('|', $data[$c]);
    $lowercase = strtolower($letter);
    $data2[$c] = array($lowercase,$g1,$g2,$g3,$g4,$letter);
}

sort($data2);
reset($data2);

echo '<br />LOWERCASE SORT:
<br />';

print_r($data2);

echo '</pre>';
?>
matpatnik at hotmail dot com 23-Jan-2008 03:46
This function will sort entity letters eg:&eacute;

I hope that help someone

function sort_entity($array) {
    $total = count($array);
    for ($i=0;$i<$total;$i++) {
        if ($array[$i]{0} == '&') {
            $array[$i] = $array[$i]{1}.$array[$i];
        } else {
            $array[$i] = $array[$i]{0}.$array[$i];
        }
    }
    sort($array);

    for ($i=0;$i<$total;$i++) {
        $array[$i] = substr($array[$i],1);
    }

    return $array;
}
sinan at sinaneldem dot com 23-Jun-2007 08:29
here is little script which will merge arrays, remove duplicates and sort it by alphabetical order:

<?php

$array1 = array('apple', 'banana','pear');
$array2 = array('grape', 'pear','orange');

function array_unique_merge_sort($array1, $array2){
$array = array_unique(array_merge($array1, $array2));
sort($array);
foreach ($array as $key => $value) {
    $new[$key] = $value;
}
return $new;
}

print_r (array_unique_merge_sort($array1, $array2));

?>

this will print out:

Array ( [0] => apple [1] => banana [2] => grape [3] => orange [4] => pear )
alishahnovin at hotmail dot com 25-May-2007 04:11
I had a multidimensional array, which needed to be sorted by one of the keys. This is what I came up with...

<?php
function msort($array, $id="id") {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if ($item[$id]<$array[$lowest_id][$id]) {
                    $lowest_id = $index;
                }
                $index++;
            }
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        }
        return $temp_array;
    }
?>

Ex:

<?php

//oh no, this is not in the ordered by id!!
$data[] = array("item"=>"item 4", "id"=>4);
$data[] = array("item"=>"item 1", "id"=>1);
$data[] = array("item"=>"item 3", "id"=>3);
$data[] = array("item"=>"item 2", "id"=>2);

var_dump(  msort($data)  ); //just msort it!

/* outputs

array
  0 =>
    array
      'item' => 'item 1' (length=6)
      'id' => 1
  1 =>
    array
      'item' => 'item 2' (length=6)
      'id' => 2
  2 =>
    array
      'item' => 'item 3' (length=6)
      'id' => 3
  3 =>
    array
      'item' => 'item 4' (length=6)
      'id' => 4

*/

?>
joris at mangrove dot nl 01-Feb-2007 05:40
Commenting on note http://www.php.net/manual/en/function.sort.php#62311 :

Sorting an array of objects will not always yield the results you desire.

As pointed out correctly in the note above, sort() sorts the array by value of the first member variable. However, you can not always assume the order of your member variables! You must take into account your class hierarchy!

By default, PHP places the inherited member variables on top, meaning your first member variable is NOT the first variable in your class definition!
However, if you use code analyzers or a compile cache, things can be very different. E.g., in eAccelerator, the inherited member variables are at the end, meaning you get different sort results with caching on or off.

Conclusion:
Never use sort on arrays with values of a type other than scalar or array.
alex [at] vkpb [dot] com 26-Jan-2007 03:36
Sorting of an array by a method of inserts.

<?

       function sortByField($multArray,$sortField,$desc=true){
            $tmpKey='';
            $ResArray=array();

            $maIndex=array_keys($multArray);
            $maSize=count($multArray)-1;

            for($i=0; $i < $maSize ; $i++) {

               $minElement=$i;
               $tempMin=$multArray[$maIndex[$i]][$sortField];
               $tmpKey=$maIndex[$i];

                for($j=$i+1; $j <= $maSize; $j++)
                  if($multArray[$maIndex[$j]][$sortField] < $tempMin ) {
                     $minElement=$j;
                     $tmpKey=$maIndex[$j];
                     $tempMin=$multArray[$maIndex[$j]][$sortField];

                  }
                  $maIndex[$minElement]=$maIndex[$i];
                  $maIndex[$i]=$tmpKey;
            }

           if($desc)
               for($j=0;$j<=$maSize;$j++)
                  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];
           else
              for($j=$maSize;$j>=0;$j--)
                  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];

           return $ResArray;
       }

// make array
$array['aaa']=array("name"=>"vasia","order"=>1);
$array['bbb']=array("name"=>"petia","order"=>2);
$array['ccc']=array("name"=>"kolia","order"=>3);
$array['ddd']=array("name"=>"zenia","order"=>4);

// set sort
$SortOrder=0; // desc by default , 1- asc

var_dump(sortByField($array,'order',$SortOrder));

array
  'ddd' =>
    array
      'name' => 'zenia' (length=5)
      'order' => 4
  'aaa' =>
    array
      'name' => 'vasia' (length=5)
      'order' => 1
  'bbb' =>
    array
      'name' => 'petia' (length=5)
      'order' => 2
  'ccc' =>
    array
      'name' => 'kolia' (length=5)
      'order' => 3

?>
g8z at yahoo dot com 14-Jul-2006 04:28
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

For example:

$a = array();

$a []= array(
    'name'         => 'Sam',
    'age'         => 23,
    'hire_date'    => '2004-01-01'
);
$a []= array(
    'name'        => 'Sam',
    'age'        => 44,
    'hire_date'    => '2003-03-23'
);
$a []= array(
    'name'        => 'Jenny',
    'age'        => 20,
    'hire_date' => '2000-12-31'
);
$a []= array(
    'name'        => 'Samantha',
    'age'        => 50,
    'hire_date' => '2000-12-14'
);

$sticky_fields = array( 'name' );
print_r( stickysort( $a, 'age', DESC_NUM, $sticky_fields ) );

OUTPUT:

Array
(
    [0] => Array
        (
            [name] => Sam
            [age] => 44
            [hire_date] => 2003-03-23
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 23
            [hire_date] => 2004-01-01
        )
    [2] => Array
        (
            [name] => Jenny
            [age] => 20
            [hire_date] => 2000-12-31
        )
    [3] => Array
        (
            [name] => Samantha
            [age] => 50
            [hire_date] => 2000-12-14
        )
)

Here's why this is the correct output - the "name" field is sticky, so it cannot change its sort order. Thus, the "age" field is only sorted as a sub-sort within records where "name" is identical. Thus, the "Sam" records are reversed, because 44 > 23, but Samantha remains at the bottom, even though her age is 50. This is a way of achieving "sub-sorts" and "sub-sub-sorts" (and so on) within records of identical data for specific fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
g8z at yahoo dot com 10-Jul-2006 08:58
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
Emiliyan at ServicesBG dot Com 28-Mar-2006 07:41
#This is a function that will sort an array...
function sort_by($array,  $keyname = null, $sortby) {
   $myarray = $inarray = array();
   # First store the keyvalues in a seperate array
    foreach ($array as $i => $befree) {
        $myarray[$i] = $array[$i][$keyname];
    }
   # Sort the new array by
    switch ($sortby) {
    case 'asc':
    # Sort an array and maintain index association...
    asort($myarray);
    break;
    case 'arsort':
    # Sort an array in reverse order and maintain index association
    arsort($myarray);
    break;
    case 'natcasesor':
    # Sort an array using a case insensitive "natural order" algorithm
    natcasesort($myarray);
    break;
    }
    # Rebuild the old array
    foreach ( $myarray as $key=> $befree) {
       $inarray[$key] = $array[$key];
    }
    return $inarray;
}
sort_by(); example...
$info = sort_by($myarray, 'name', $use = 'asc');
print_r($info);
jesper at snt dot utwente dot nl 24-Feb-2006 01:26
If you sort an array of objects, the first variable in the object will be used for sorting:

<?php
class foo
{
  var $value; //First variable: Used for sorting
  var $id;

  function foo($i, $v)
  {
     $this->id = $i;
     $this->value = $v;
  }

}

for ($i = 0; $i < 10; $i++)
{
  $bar[] = new foo($i,rand(1,10));
}

// This will sort on value
sort($bar);
print_r($bar);
?>

Compare the piece of code above with the following:

<?php
class foo
{
  var $id; //First variable: Used for sorting
  var $value;

  function foo($i, $v)
  {
     $this->id = $i;
     $this->value = $v;
  }

}

for ($i = 0; $i = 10; $i++)
{
  $bar[] = new foo($i,rand(1,10));
}

// This will sort on id
sort($bar);
print_r($bar);
?>

As you can see the location of declaration of the variables matter!
If you want to sort on both or on a combination of variables, use ksort()
nm at thenoodleman dot com 30-Jan-2006 05:18
Faster, more effective function:

array_sort (array, ['asc'/'desc'])

Second parameter specifies whether to order ascending or descending. Default is ascending.

function array_sort($array, $type='asc'){
    $result=array();
    foreach($array as $var => $val){
        $set=false;
        foreach($result as $var2 => $val2){
            if($set==false){
                if($val>$val2 && $type=='desc' || $val<$val2 && $type=='asc'){
                    $temp=array();
                    foreach($result as $var3 => $val3){
                        if($var3==$var2) $set=true;
                        if($set){
                            $temp[$var3]=$val3;
                            unset($result[$var3]);
                        }
                    }
                    $result[$var]=$val;
                    foreach($temp as $var3 => $val3){
                        $result[$var3]=$val3;
                    }
                }
            }
        }
        if(!$set){
            $result[$var]=$val;
        }
    }
    return $result;
}

Works for ordering by integers or strings, no need to specify which.

Example:

$array=array('a' => 50, 'b' => 25, 'c' => 75);
print_r(array_sort($array));

Returns:
Array
(
[b] => 25
[a] => 50
[c] => 75
)
raul at jimi dot com dot mx 01-Dec-2005 09:50
I had an array like this:
$arr=array (1,4,3,6,5);

which returns this:
$arr[0]=1
$arr[1]=4
$arr[2]=3
$arr[3]=6
$arr[4]=5

But lets say i remove [2] which is number 3, i get:

$arr[0]=1
$arr[1]=4
$arr[3]=6
$arr[4]=5

And i want to reindex without doing a sort because i dont want to lose the order of the numbers (like a pop in a stack but in the middle of the list), i do this:

$arr=array_chunk($arr,count($arr));
$arr=$arr[0];

the result is:

$arr[0]=1
$arr[1]=4
$arr[2]=6
$arr[3]=5

This can be applied mostly for tree sorting, when you only have the id and the parent values of the node, and you want to have N levels.
james at miicro dot net 19-Jul-2005 02:49
It's useful to know that if you're using this function on a multidimensional array, php will sort the first key, then the second and so on. This is similar to being able to use SQL to order by field1, field2 etc.

So:

Array (
[0] => Array ( [category] => work [name] => Smith )
[1] => Array ( [category] => play [name] => Johnson )
[2] => Array ( [category] => work [name] => Berger )
)

will become:

Array (
[0] => Array ( [category] => play [name] => Johnson )
[1] => Array ( [category] => work [name] => Berger )
[2] => Array ( [category] => work [name] => Smith )
)

Hope it helps someone.
timc at hlyw dot com 17-Feb-2005 04:04
I dig the multi_sort function(s) from above.  But, they don't work for hash arrays.  I added a keys variable to keep track of the key value as the array gets sorted.  Feed back welcome.

<?php
function array_qsort (&$array, $column=0, $order=SORT_ASC, $first=0, $last= -2)
{
  // $array  - the array to be sorted
  // $column - index (column) on which to sort
  //          can be a string if using an associative array
  // $order  - SORT_ASC (default) for ascending or SORT_DESC for descending
  // $first  - start index (row) for partial array sort
  // $last  - stop  index (row) for partial array sort
  // $keys  - array of key values for hash array sort

  $keys = array_keys($array);
  if($last == -2) $last = count($array) - 1;
  if($last > $first) {
   $alpha = $first;
   $omega = $last;
   $key_alpha = $keys[$alpha];
   $key_omega = $keys[$omega];
   $guess = $array[$key_alpha][$column];
   while($omega >= $alpha) {
     if($order == SORT_ASC) {
       while($array[$key_alpha][$column] < $guess) {$alpha++; $key_alpha = $keys[$alpha]; }
       while($array[$key_omega][$column] > $guess) {$omega--; $key_omega = $keys[$omega]; }
     } else {
       while($array[$key_alpha][$column] > $guess) {$alpha++; $key_alpha = $keys[$alpha]; }
       while($array[$key_omega][$column] < $guess) {$omega--; $key_omega = $keys[$omega]; }
     }
     if($alpha > $omega) break;
     $temporary = $array[$key_alpha];
     $array[$key_alpha] = $array[$key_omega]; $alpha++;
     $key_alpha = $keys[$alpha];
     $array[$key_omega] = $temporary; $omega--;
     $key_omega = $keys[$omega];
   }
   array_qsort ($array, $column, $order, $first, $omega);
   array_qsort ($array, $column, $order, $alpha, $last);
  }
}
?>
anthony at ectrolinux dot com 08-Sep-2004 04:39
In a brief addition to the previous poster's message, the ascending sorting order used by PHP directly corresponds to ISO-8859-1 (ASCII). Therefore the character \48 (numeral 0) would be placed before the character \82 (R), which would be placed before the character \110 (n), and so forth.
arjan321 at hotmail dot com 31-Jan-2003 12:23
Ik you want to sort case insensitive, use the natcasesort()
peek at mailandnews dot com 07-Apr-2001 04:06
I ran into the same problem with case insensitive sorting. Actually I think there should be a SORT_STRING_CASE flag but I tried the following:

usort($listing, 'strcasecmp');

This didn't work (why not?), but you can do a proper case insensitive sort like this:

usort($listing, create_function('$a,$b','return strcasecmp($a,$b);'));


Ordena un array con una función de comparación definida por el usuario y mantiene la asociación de índices

  • « sort
  • uksort »
  • PHP Manual
  • Funciones de Arrays
  • Ordena un array con una función de comparación definida por el usuario y mantiene la asociación de índices

uasort

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

uasort — Ordena un array con una función de comparación definida por el usuario y mantiene la asociación de índices

Descripción

uasort ( array &$array , callable $value_compare_func ) : bool

Esta función ordena un array tal que los índices de array mantienen sus correlaciones con los elementos del array con los que están asociados, usando una función de comparación definida por el usuario.

Se usa pricipalmente cuando se ordenan arrays asociativos donde el orden del elemento mismo es significante.

Nota:

Si dos miembros se comparan como iguales, su orden relativo en el array oredenado será indefinido.

Parámetros

array

El array de entrada.

value_compare_func

Véase usort() y uksort() para ejemplos de funciones de comparación definidas por el usuario.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo básico de uasort()

<?php
// Función de comparación
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Array a ser ordenado
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
print_r($array);

// Ordenar e imprimir el array resultante
uasort($array, 'cmp');
print_r($array);
?>

El resultado del ejemplo sería:

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

Ver también

  • usort() - Ordena un array según sus valores usando una función de comparación definida por el usuario
  • comparación de funciones de orden de arrays

User Contributed Notes

woodongwong at gmail dot com 29-Oct-2020 01:38
PHP version >= 7

<?php

// Comparison function
function cmp($a, $b) {
    return $a <=> $b;
}

// Array to be sorted
$array = ['a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4];
print_r($array);

// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);

?>

PHP version >= 7.4

<?php

// Array to be sorted
$array = ['a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4];
print_r($array);

// Sort and print the resulting array
uasort($array, fn($a, $b) => $a <=> $b);
print_r($array);

?>
lixuss at gmail dot com 14-Mar-2020 05:35
Here is a bug fix for "php at clement dot hk" stable_uasort(&$array, $cmp_function)

The implementation has problems with "0" values, because while() cycle stops on current() returning value "0" which is considered false. The condition must be !== false

Just fix those 3 lines:

while(current($array1) && current($array2)) => while(current($array1)!==false && current($array2)!==false)

while(current($array1)) => while(current($array1)!==false)

while(current($array2)) => while(current($array1)!==false)
bpolaszek at gmail dot com 19-Jun-2018 01:47
Keep in mind that PHP sorting functions are not reliable to handle "stable sorting", even since PHP7+.
It might work on small arrays, but not on "big" ones (100 items are enough for the stable sorting to fail).

<?php
$a = array_fill(0, 100, 'foo');
$b = $a;
var_dump($b === $a); // bool(true)

uasort($a, function () {
    return 0; // Consider all items are the same
});

var_dump($b === $a); // bool(false)
?>

To ensure $b === $a, use a 3rd-party stable sorting function:

http://php.net/manual/en/function.uasort.php#121283
alf at prisguide dot no 28-Jun-2017 11:44
User "php at clement dot hk" already provided a stable uasort function, but I find this wrapper much shorter and easier to understand:

https://github.com/vanderlee/PHP-stable-sort-functions/blob/master/classes/StableSort.php

function stable_uasort(array &$array, $value_compare_func) {
    $index = 0;
    foreach ($array as &$item) {
        $item = array($index++, $item);
    }
    $result = uasort($array, function($a, $b) use($value_compare_func) {
        $result = call_user_func($value_compare_func, $a[1], $b[1]);
        return $result == 0 ? $a[0] - $b[0] : $result;
    });
    foreach ($array as &$item) {
        $item = $item[1];
    }
    return $result;
}
ayaou dot mohammed at gmail dot com 15-Jun-2016 03:05
// Anonumous functions
uasort($collection, array($this, function($a, $b){
     //logic
}));
php at clement dot hk 04-Mar-2014 04:00
If you want to keep the order when two members compare as equal, use this.
<?php

function stable_uasort(&$array, $cmp_function) {
    if(count($array) < 2) {
        return;
    }
    $halfway = count($array) / 2;
    $array1 = array_slice($array, 0, $halfway, TRUE);
    $array2 = array_slice($array, $halfway, NULL, TRUE);

    stable_uasort($array1, $cmp_function);
    stable_uasort($array2, $cmp_function);
    if(call_user_func($cmp_function, end($array1), reset($array2)) < 1) {
        $array = $array1 + $array2;
        return;
    }
    $array = array();
    reset($array1);
    reset($array2);
    while(current($array1) && current($array2)) {
        if(call_user_func($cmp_function, current($array1), current($array2)) < 1) {
            $array[key($array1)] = current($array1);
            next($array1);
        } else {
            $array[key($array2)] = current($array2);
            next($array2);
        }
    }
    while(current($array1)) {
        $array[key($array1)] = current($array1);
        next($array1);
    }
    while(current($array2)) {
        $array[key($array2)] = current($array2);
        next($array2);
    }
    return;
}

function cmp($a, $b) {
    if($a['n'] == $b['n']) {
        return 0;
    }
    return ($a['n'] > $b['n']) ? -1 : 1;
}

$a = $b = array(
    'a' => array("l" => "A", "n" => 1),
    'b' => array("l" => "B", "n" => 2),
    'c' => array("l" => "C", "n" => 1),
    'd' => array("l" => "D", "n" => 2),
    'e' => array("l" => "E", "n" => 2),
);

uasort($a, 'cmp');
print_r($a);

stable_uasort($b, 'cmp');
print_r($b);
?>

returns

Array
(
    [e] => Array
        (
            [l] => E
            [n] => 2
        )

    [b] => Array
        (
            [l] => B
            [n] => 2
        )

    [d] => Array
        (
            [l] => D
            [n] => 2
        )

    [c] => Array
        (
            [l] => C
            [n] => 1
        )

    [a] => Array
        (
            [l] => A
            [n] => 1
        )

)
Array
(
    [b] => Array
        (
            [l] => B
            [n] => 2
        )

    [d] => Array
        (
            [l] => D
            [n] => 2
        )

    [e] => Array
        (
            [l] => E
            [n] => 2
        )

    [a] => Array
        (
            [l] => A
            [n] => 1
        )

    [c] => Array
        (
            [l] => C
            [n] => 1
        )
)

https://bugs.php.net/bug.php?id=53341
Anonymous 15-Aug-2013 10:35
//this fix the problem of if any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).

$pos=0;
foreach($values as $k => $v)
  $tosort[$k]=array($v,$pos++);
uasort($tosort,function($a, $b) {
  if($a[0] != $b[0])return ($a[0] < $b[0]) ? -1 : 1;
    return ($a[1] < $b[1]) ? -1 : 1;}
);
foreach($tosort as $k => $v)
  $values[$k]=$v[0];
iborodikhin at gmail dot com 22-Nov-2012 08:32
To shuffle assoc array preserving keys just do this:
<?php uasort(
    $array,
    function ($a, $b) {
        return mt_rand(0, 1) > 0 ? 1 : -1;
    }
); ?>
Said Dashuk 11-Oct-2011 10:33
My simple and effective solution for sort multi-dimensional array by any key:

<?php
function sort_by_key ($arr,$key) {
    global $key2sort;
    $key2sort = $key;
    uasort($arr, 'sbk');
    return ($arr);
}
function sbk ($a, $b) {global $key2sort; return (strcasecmp ($a[$key2sort],$b[$key2sort]));}
?>
yannick dot battail at gmail dot com 17-Nov-2010 06:37
An Example using anonymous function.
Anonymous functions make some time the code easier to understand.
<?php
$fruits = array('Orange9','Orange11','Orange10','Orange6','Orange15');
uasort ( $fruits , function ($a, $b) {
            return strnatcmp($a,$b); // or other function/code
        }
    );
print_r($fruits);
?>
returns
Array
(
    [3] => Orange6
    [0] => Orange9
    [2] => Orange10
    [1] => Orange11
    [4] => Orange15
)
magikMaker 19-Oct-2010 02:48
a quick reminder on the syntax if you want to use uasort in a Class or Object:

<?php

// procedural:
uasort($collection, 'my_sort_function');

// Object Oriented
uasort($collection, array($this, 'mySortMethod'));

// Objet Oriented with static method
uasort($collection, array('self', 'myStaticSortMethod'));

?>
phire_sk 05-Oct-2010 02:19
I tried using some of the previous built multisorts, but they weren't working as expected.

So, I made my own Class, and it seems to work wonderfully.

Here is the code:

<?php
/************************************
*    Allows sorting multi-dimensional
*    arrays by a specific key and in
*    asc or desc order
**/
class multiSort
{
    var $key;    //key in your array

    //runs the sort, and returns sorted array
    function run ($myarray, $key_to_sort, $type_of_sort = '')
    {
        $this->key = $key_to_sort;

        if ($type_of_sort == 'desc')
            uasort($myarray, array($this, 'myreverse_compare'));
        else
            uasort($myarray, array($this, 'mycompare'));

        return $myarray;
    }

    //for ascending order
    function mycompare($x, $y)
    {
        if ( $x[$this->key] == $y[$this->key] )
            return 0;
        else if ( $x[$this->key] < $y[$this->key] )
            return -1;
        else
            return 1;
    }

    //for descending order
    function myreverse_compare($x, $y)
    {
        if ( $x[$this->key] == $y[$this->key] )
            return 0;
        else if ( $x[$this->key] > $y[$this->key] )
            return -1;
        else
            return 1;
    }
}
?>
paul at webtop-designs dot com 30-Nov-2009 01:40
Just expanding on php arobase kochira period com's method:

If you are looking to sort a multi-D array by a specific column and have entries in both upper and lower case, simply drop the entries to lowercase before doing the strcmp.

<?php
$dirs = array(
  array('name' => 'First Folder', 'path' => 'sompath'),
  array('name' => 'second folder', 'path' => 'sompath2'),
  array('name' => 'Third Folder', 'path' => 'sompath3')
);

function so($a, $b) {
    return (strcmp (strtolower($a['name']), strtolower($b['name'])));
}
?>
php arobase kochira period com 08-Jun-2008 04:13
Difference between uasort() and usort(), the missing example ...

<?php
  $arr = array ( 10 => array('id' => 'dix',  'aa' => '1010'),
                100 => array('id' => 'cent', 'aa' => '100100'),
                  2 => array('id' => 'deux', 'aa' => '22'),
                  7 => array('id' => 'sept', 'aa' => '77'));

  // id sorting
  function so ($a, $b) { return (strcmp ($a['id'],$b['id']));    }
?>

*** uasort($arr, 'so') output:

<?php Array (
    [100] => Array
        (
            [id] => cent
            [aa] => 100100
        )

    [2] => Array
        (
            [id] => deux
            [aa] => 22
        )

    [10] => Array
        (
            [id] => dix
            [aa] => 1010
        )

    [7] => Array
        (
            [id] => sept
            [aa] => 77
        ))?>

*** usort($arr, 'so') output:

<?php Array (
    [0] => Array
        (
            [id] => cent
            [aa] => 100100
        )

    [1] => Array
        (
            [id] => deux
            [aa] => 22
        )

    [2] => Array
        (
            [id] => dix
            [aa] => 1010
        )

    [3] => Array
        (
            [id] => sept
            [aa] => 77
        ))?>
php at eden2 dot com 17-Jul-2003 04:36
Is it just me, or are the examples below misleading, and actually demonstrating situations that would be more appropriate for usort()?

After trying to make sense of the uasort() description, it sounds like it's more for sorting a 1D array like this:

"john" => "$23.12"
"tim" => "$6.50"
"bob" => "$18.54"

and getting back:

"tim" => "$6.50"
"bob" => "$18.54"
"john" => $23.12"

(assuming, of course, that your sort function is lopping off the $ and evaluating as a number -- which would complicate the use of asort() ;)
naholyr at yahoo dot fr 10-Jan-2003 09:35
You can sort a multidimensionnal array by any of its key with this function:

function multi_sort($array, $key)
{
  $cmp_val="((\$a['$key']>\$b['$key'])?1:
    ((\$a['$key']==\$b['$key'])?0:-1))";
  $cmp=create_function('$a, $b', "return $body;");
  uasort($array, $cmp);
  return $array;
}

example:
$myarray = array(
  array("name"=>"kernighan", "language"=>"c"),
  array("name"=>"lerdorf", "language"=>"php"),
  array("name"=>"Stroustrup", "language"=>"c++"),
  array("name"=>"Gosling", "language"=>"java")
);

multi_sort($myarray, "name") returns:
name=Gosling    language=java
name=Kernighan    language=c
name=Lerdorf    language=php
name=Stroustrup    language=c++
dholmes at jccc d0t net 09-Oct-2002 02:27
Here is a little sort function that actually uses a dynamic callback for usort to do it's thing.

It assumes your data is in the form of:
    $data = array(
            array('ID'=>'6','LAST'=>'Holmes','FIRST'=>'Dan'),
            array('ID'=>'1234','LAST'=>'Smith','FIRST'=>'Agent K'),
            array('ID'=>'2','LAST'=>'Smith','FIRST'=>'Agent J'),
            array('ID'=>'4','LAST'=>'Barney','FIRST'=>'Bob'));

Now, you want to sort on one or more cols, don't you?

masort($data, 'LAST,FIRST');
or
masort($data,array('FIRST','ID'));

Of course you could add a bunch to it (like numeric comparison if appropriate, desc/asc, etc) but it works for me.

function masort(&$data, $sortby){
    if(is_array($sortby)){
        $sortby = join(',',$sortby);
    }

    uasort($data,create_function('$a,$b','$skeys = split(\',\',\''.$sortby.'\');
        foreach($skeys as $key){
            if( ($c = strcasecmp($a[$key],$b[$key])) != 0 ){
                return($c);
            }
        }
        return($c); '));
}
Notice that I am splitting the string in the comparison function? While this is certainly slower, it was the only way I would find to "pass" and "array".  If anyone has a better way, please suggest.  Then inside, we (string) compare the values only moving to the next key if the values are the same...and so on, and so on.
stilgar_cpsNOSPAM at zipmail dot NOSPAMcom dot br 05-Sep-2001 02:30
Use example:

$array[0]['Fator1']=7;
$array[0]['Fator2']="Name";
$array[1]['Fator1']=5;
$array[1]['Fator2']="Name";
$array[2]['Fator1']=7;
$array[2]['Fator2']="NameDiferente";
.....

We want to order by Fator1, then Fator2, then:

function Compare($ar1, $ar2)
{
   if ($ar1['Fator1']<$ar2['Fator1'])
      return -1;
   else if ($ar1['Fator1']>$ar2['Fator1'])
      return 1;
   if ($ar1['Fator2']<$ar2['Fator2'])
      return -1;
   else if ($ar1['Fator2']>$ar2['Fator2'])
      return 1;
   return 0;
}

To sort now, we use:

uasort($array, 'Compare');


Ordena un array según sus claves usando una función de comparación definida por el usuario

  • « uasort
  • usort »
  • PHP Manual
  • Funciones de Arrays
  • Ordena un array según sus claves usando una función de comparación definida por el usuario

uksort

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

uksort — Ordena un array según sus claves usando una función de comparación definida por el usuario

Descripción

uksort ( array &$array , callable $key_compare_func ) : bool

uksort() ordenará las claves de un array usando una función de comparación proporcionada por el usuario. Si el array que se desea ordenar necesita ser ordenado por algún criterio no trivial, debería usar esta función.

Nota:

Si dos miembros se comparan como iguales, su orden relativo en el array oredenado será indefinido.

Parámetros

array

El array de entrada.

key_compare_func

La función de comparación debe devolver un entero menor, igual o mayor que cero si el primer argumento se considera que sea respectivamente menor, igual o mayor que el segundo. Observe que antes de PHP 7.0.0 este entero debía estar en el rango de -2147483648 a 2147483647.

callback ( mixed $a, mixed $b ) : int

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de uksort()

<?php
function cmp($a, $b)
{
    $a = preg_replace('@^(un|una|la) @', '', $a);
    $b = preg_replace('@^(un|una|la) @', '', $b);
    return strcasecmp($a, $b);
}

$a = array("Víctor" => 1, "la Tierra" => 2, "una manzana" => 3, "un plátano" => 4);

uksort($a, "cmp");

foreach ($a as $clave => $valor) {
    echo "$clave: $valor\n";
}
?>

El resultado del ejemplo sería:

una manzana: 3
un plátano: 4
la Tierra: 2
Víctor: 1

Ver también

  • usort() - Ordena un array según sus valores usando una función de comparación definida por el usuario
  • comparación de funciones de orden de arrays

User Contributed Notes

smcbride at msn dot com 29-Jan-2021 07:17
This might be obvious to many, but just to help others that are trying to use this in a class.  Inside a class, you can prefix the function with self:: within the uksort(), and it will work.  Also, if it is in another class that is included, you can prefix it with the class name.

class someclass {
     private function ArraySortCMPIP($a, $b) {
          $a = ip2long($a);
          $b = ip2long($b);

          if ($a == $b) return 0;
          return ($a < $b) ? -1 : 1;
     }

     // Output
     public function PrintResults() {
          uksort($this->someIPAddressArray, 'self::ArraySortCMPIP');
          print_r($this->someIPAddressArray);
     }
}
DimeCadmium 22-Jun-2018 06:48
Don't use uksort($array, "strnatcasecmp"); ... use ksort($array, SORT_NATURAL|SORT_FLAG_CASE);
andi at example dot com 24-Feb-2016 10:58
I needed to be able to sort a string that contained numbers eg.

"Slot 1 name"
"Slot 2 name"
"Slot 10 name"

using a normal string compare the "Slot 10 name" would appear before "Slot 2 name" so I wrote little function that will compare a string taking numbers in to consideration. There may be a few edge cases that need to be taken in to consideration.

function strCmpWithNumbers( $a, $b) {
  // Split the string in to words.
  $a = explode(' ',$a);
  $b = explode(' ',$b);
  $loop = 0;
  do {
    // Get the first word from each item
    $ta = Utils::gvfa($a, $loop);
    $tb = Utils::gvfa($b, $loop);

    if (isset($ta)) {
      if (isset($tb)) {
        if (is_numeric($ta)) {
          if ($ta != $tb) {
            return $ta - $tb;
          }
        } else {
          $val = strcasecmp($ta, $tb);
          if ($val != 0) {
            return $val;
          }
        }
      } else {
        return 1; // a is set but b isn't
      }
    } else {
      return isset($b);
    }
    $loop +=1;
  } while (true);
}
Anonymous 05-Oct-2015 01:02
An associative array with known keys can be easily custom sorted using a switch statement in the callback:

NB ksort can be used beforehand to ensure expected results

ksort($array);

uksort($array, function ($a) {
    switch($a) {
        case 'pepperoni':
            return 0;
        case 'beef':
            return 1;
        case 'chicken':
            return 2;
        case 'ham':
            return 3;
        case 'vegetarian':
            return 4;
    }
});
PHPUser 06-Feb-2015 05:32
[Editor's note: the following comment may be factually incorrect]

uksort is only usable in the UK
<?php
if($country=="UK"){
  uksort();
}else{
  echo "You have to live in UK to use uksort().";
}
?>
ingo at example dot test 05-May-2014 01:30
sort with collation, to have umlauts correctly:

uksort($retval, array(Collator::create( 'de_DE' ), 'compare'));
mdsky at web dot de 23-May-2010 11:26
Case insensitive without own function:

uksort($array, "strnatcasecmp");
contacto at hardcode dot com dot ar 29-Jul-2009 06:56
need a case insensitive sort by key function? i did and couldn find it, so:

<?php
function insensitive_uksort($a,$b) {
    return strtolower($a)<strtolower($b);
}
uksort($arr, "insensitive_uksort");
?>
brian dot short at gmail dot com 07-Jul-2009 07:58
If you need to periodically sort by grades (A, A+, D-, etc.), here is a compare function that compares strings by the case-insensitive method, unless it finds a grade, in which case it correctly sorts by putting "plus" grades first, unmarked grades second, and "minus" grades last.

<?php
function cmp($a, $b)
{
   $a = preg_replace('@^(a|an|the) @', '', $a);
   $b = preg_replace('@^(a|an|the) @', '', $b);

   //special code for grades
   if (strpos( $a, "+") !== false || strpos( $b, "+") !== false  ||
       strpos( $a, "-") !== false || strpos( $b, "-") !== false ){

        $substrA = substr($a, 0, 1);
        $substrB = substr($b, 0, 1);

        $modifierA = (strlen($a) == 2) ? substr($a, 1, 1) : "";
        $modifierB = (strlen($b) == 2) ? substr($b, 1, 1) : "";

        if ($substrA == $substrB){
            //figure out plusses and minuses.
            if ($modifierA == "+"){
                return -1;
            } else if ($modifierB == "+"){
                return 1;
            }

            if ($modifierA == "-"){
                return 1;
            } else if ($modifierB == '-'){
                return -1;
            }
        } else {
            return strcasecmp($a, $b);
        }

    }
   return strcasecmp($a, $b);
}

$grades = array(
                 "C+" => 13    ,
                "C" => 10     ,
                "D+" => 8     ,
                "B+" => 7     ,
                "C-" => 6     ,
                "A-" => 5     ,
                "F" => 5      ,
                "B" => 4      ,
                "B-" => 4     ,
                "D" => 3      ,
                "D-" => 3     ,
                "A+" => 1
    );

uksort($grades, "cmp");
?>

result:  Array
(
    [A+] => 1
    [A-] => 5
    [B+] => 7
    [B] => 4
    [B-] => 4
    [C+] => 13
    [C] => 10
    [C-] => 6
    [D+] => 8
    [D] => 3
    [D-] => 3
    [F] => 5
)
Jimomighty 19-Mar-2005 07:30
...

function cmp($a, $b)
{
   if ($a == $b) {
       return 0;
   }
   return ($a < $b) ? -1 : 1;
}

function uksort_tree ( &$array )
{
    // [PHP5] foreach ( $array as &$value )
    foreach ( $array as $key => $value )
    {
       if ( is_array ( $value ) )
       {
            // [PHP5] uksort_tree ( $value );
           uksort_tree ( $array[$key] );
       }
    }

    uksort( $array, "cmp" );
}

uksort_tree( $myEntryArray );

...
aleczapka at gmx dot net 22-Dec-2004 04:35
One remark regarding array_sorter class.
It won't work correctly with eg. dates from mysql like 20041206105350, cause you can't convert such number into integer. To fix it remove intval() from the code. If the variable is a number it will work without converting this to int anyways. Here is the fix.

<?php
....
if ($a == $b)
    return 0;
if ($this->sasc)
    return ($a > $b) ? 1 : -1;
else
    return ($a > $b) ? -1 : 1;
...
?>
jg at delegation dot ca 17-Dec-2004 07:41
To sort dates with uksort:

function datediff($a, $b) {

$a = date('U',$a);
$b = date('U',$b);

if ($a == $b) $r = 0;
else $r = ($a > $b) ? 1: -1;

return $r;
}
aleczapka at gmx dot net 06-Dec-2004 04:27
Here is a small and very fast object to handle sorting of multidimentional arrays by a key.
<?php
/**
* Handles multidimentional array sorting by a key (not recursive)
*
* @author Oliwier Ptak <aleczapka at gmx dot net>
*/
class array_sorter
{
    var $skey = false;
    var $sarray = false;
    var $sasc = true;

    /**
    * Constructor
    *
    * @access public
    * @param mixed $array array to sort
    * @param string $key array key to sort by
    * @param boolean $asc sort order (ascending or descending)
    */
    function array_sorter(&$array, $key, $asc=true)
    {
        $this->sarray = $array;
        $this->skey = $key;
        $this->sasc = $asc;
    }

    /**
    * Sort method
    *
    * @access public
    * @param boolean $remap if true reindex the array to rewrite indexes
    */
    function sortit($remap=true)
    {
        $array = &$this->sarray;
        uksort($array, array($this, "_as_cmp"));
        if ($remap)
        {
            $tmp = array();
            while (list($id, $data) = each($array))
                $tmp[] = $data;
            return $tmp;
        }
        return $array;
    }

    /**
    * Custom sort function
    *
    * @access private
    * @param mixed $a an array entry
    * @param mixed $b an array entry
    */
    function _as_cmp($a, $b)
    {
        //since uksort will pass here only indexes get real values from our array
        if (!is_array($a) && !is_array($b))
        {
            $a = $this->sarray[$a][$this->skey];
            $b = $this->sarray[$b][$this->skey];
        }

        //if string - use string comparision
        if (!ctype_digit($a) && !ctype_digit($b))
        {
            if ($this->sasc)
                return strcasecmp($a, $b);
            else
                return strcasecmp($b, $a);
        }
        else
        {
            if (intval($a) == intval($b))
                return 0;

            if ($this->sasc)
                return (intval($a) > intval($b)) ? -1 : 1;
            else
                return (intval($a) > intval($b)) ? 1 : -1;
        }
    }

}//end of class
?>

Sample $input_array:

Array
(
    [0] => Array
        (
            [id] => 961
            [uid] => 29
            [gid] => 12
            [parent_id] => 147
            [created] => 20041206105350
            [modified] => 20041206110702
        )

    [1] => Array
        (
            [id] => 41
            [uid] => 29
            [gid] => 12
            [parent_id] => 153
            [created] => 20041025154009
            [modified] => 20041206105532
        )

    [2] => Array
        (
            [id] => 703
            [uid] => 29
            [gid] => 12
            [parent_id] => 419
            [created] => 20041025154132
            [modified] => 20041027150259
        )

Example of usage:
<?php
    function multi_sort(&$array, $key, $asc=true)
    {
        $sorter = new array_sorter($array, $key, $asc);
        return $sorter->sortit();
    }
    //sort by parent_id in descending order
    $my_array = multi_sort($input_array, "parent_id", false);
?>

The result array will be:
Array
(

    [0] => Array
        (
            [id] => 703
            [uid] => 29
            [gid] => 12
            [parent_id] => 419
            [created] => 20041025154132
            [modified] => 20041027150259
        )

    [1] => Array
        (
            [id] => 41
            [uid] => 29
            [gid] => 12
            [parent_id] => 153
            [created] => 20041025154009
            [modified] => 20041206105532
        )

    [2] => Array
        (
            [id] => 961
            [uid] => 29
            [gid] => 12
            [parent_id] => 147
            [created] => 20041206105350
            [modified] => 20041206110702
        )
fabriceb at gmx dot net 08-Jul-2004 06:26
(about sorting an array of objects by their properties in a class - inspired by webmaster at zeroweb dot org at usort function)
I'm using classes as an abstraction for querying records in a database and use arrays of objects to store records that have an 1 to n relationship. E.g. a class "family" has family members stored as an array of objects. Each of those objects prepresents a record in a database related to the family (by it's familyId).

To identify members, I'm using their memberId as the key of the array e.g. $family->members[$memberId].
To sort the family members AFTER fetching them with the database query, you can use the functions _objSort and sortMembers which will sort the "members" array by key using it's properties (for space reasons I didn't include the methods used to open the records):
<?php
class familyMember
{
    var $memberId;
    var $familyId;
    var $firstName;
    var $age;
    var $hairColor;
// ...
}

class family
{
    var $familyId;
    var $name;
    var $members = array(); // array of familyMember objects
    var $sortFields = array();
    var $sortDirections = array();
    // ...
    function _objSort(&$a, &$b, $i = 0)
    {
        $field        = $this->sortFields[$i];
        $direction    = $this->sortDirections[$i];

        $diff = strnatcmp($this->details[$a]->$field, $this->details[$b]->$field) * $direction;
        if ($diff == 0 && isset($this->sortFields[++$i]))
        {
            $diff = $this->_objSort($a, $b, $i);
        }

        return $diff;
    }

    function sortMembers($sortFields)
    {
        $i = 0;
        foreach ($sortFields as $field => $direction)
        {
            $this->sortFields[$i] = $field;
            $direction == "DESC" ? $this->sortDirections[$i] = -1 : $this->sortDirections[$i] = 1;
            $i++;
        }

        uksort($this->details, array($this, "_objSort"));

        $this->sortFields = array();
        $this->sortDirections = array();
    }
}
// open a family
$familyId = 5;
$family = new family($familyId);
$family->open(); // this will also fetch all members

// sort members by 3 fields
$family->sortMembers(array("firstName" => "ASC", "age" => "DESC", "hairColor" => "ASC"));
// output all family members
foreach ($family->members as $member)
{
    echo $member->firstName." - ".$member->age." - ".$member->hairColor."<br />";
}
?>

Note that this might not be the fastest thing on earth and it hasn't been tested very much yet but I hope it's useful for someone.
webmaster at kik-it at N0SP4M dot com 09-Feb-2004 10:03
The code below allows you to sort an array_A following array_B keys order, original keys and values remain associated.

<?

//main function
Function SortArrayAKeysLikeArrayBKeys(&$TheArrayToSort){
   uksort($TheArrayToSort,"SortArrayAKeysLikeArrayBKeys_cmp");
}

//the custom compare function
Function SortArrayAKeysLikeArrayBKeys_cmp($a,$b){
  global $TheArrayOrder;
  $PosA=KeyPosInArray($a,$TheArrayOrder);
  $PosB=KeyPosInArray($b,$TheArrayOrder);
  if ($PosA==$PosB){return 0;}else{return ($PosA > $PosB ? 1 : -1);}
}

//where is my key in my array
Function KeyPosInArray($Key,$Array){
   $i=0;
   $Pos=99999999;
   if($Array){
      foreach($Array as $K => $V){
         $i++;
         if($K==$Key){
            $Pos=$i;
            break;
         }
      }
   }
   return $Pos;
}

//the array you want to sort
$AnyArrayToSort['age']='19';
$AnyArrayToSort['ville']='rennes';
$AnyArrayToSort['website']='kik-it.com';
$AnyArrayToSort['region']='bretagne';
$AnyArrayToSort['code_postal']='35200';
$AnyArrayToSort['Nom']='Fred';

//the array with the correct keys/values order
$TheArrayOrder['Nom']='Whatever';
$TheArrayOrder['age']='Anything';
$TheArrayOrder['region']='What u want';
$TheArrayOrder['ville']='Something';
$TheArrayOrder['code_postal']='Nothing';

//before sort
print_r($AnyArrayToSort);
echo "<br>";
//we sort
SortArrayAKeysLikeArrayBKeys($AnyArrayToSort);
echo "<br>";
//after sort
print_r($AnyArrayToSort);
?>

Will print :

Array ( [age] => 19 [ville] => rennes [website] => kik-it.com [region] => bretagne [code_postal] => 35200 [Nom] => Fred )

Array ( [Nom] => Fred [age] => 19 [region] => bretagne [ville] => rennes [code_postal] => 35200 [website] => kik-it.com )

The keys not listed in the $TheArrayOrder will appear at the end of your sorted array (only if Key Pos < 99999999 ;o)
guss at typo dot co dot il 07-Dec-2003 12:18
Regarding the recursive sorting function above:
Genrally speaking, any recursion can be reimplemented using simple iteration. in the specific case, using recursion to compare strings has a huge performance impact while a simple loop would suffice and be faster and more simple.
Recursion is only good if it simplifies your code or your understanding of the concept. the previous example does neither, especially as it does a lot of repetitive things in each iteration, such as asigning the character order constant, rebuilding it into an array and such

For example, the string comparison could be written as such :
function str_compare($a,$b) {
    $order="aA??bBcC&#269;&#268;..."; // longer normally & without that html entities
    $default = strlen($a) - strlen($b);
    $minlen = strlen($a) < strlen($b) ? strlen($a) : strlen($b);
    for ($i = 0; $i < $minlen; $i++) {
        $pos_a=strpos($order,$a[$i]);
        $pos_b=strpos($order,$b[$i]);
        if ($pos_a != $pos_b)
            return $pos_a - $pos_b;
    }
    return $default;
}

Which is much simpler and faster.
Note that the above function will break for characters that are not listed in $order. it should be failry trivial to fix it.
ignatius dot reilly at free dot fr 13-Nov-2003 10:59
To use a more complicated comparison function, one can use a callback to a method of an object instance.
For example the following will take an array $arr whose keys are the same as those of $reference, and reorder $arr so that the keys appear in the same order as in $reference.

class kcmp {
    var $reference ;
    function kcmp( $reference ) {
       $this->reference = $reference ;
    }
    function kcompare( $a, $b ) {
       $keys = array_keys( $this->reference ) ;
       $position_a = array_search( $a, $keys ) ;
       $position_b = array_search( $b, $keys ) ;
       return  $position_a < $position_b ? -1 : 1 ;
    }
}

$reference = array(
    "k2" => "a2",
    "k3" => "a3",
    "k1" => "a1"
) ;
$arr = array(
    "k1" => "b1",
    "k2" => "b2",
    "k3" => "b3"
) ;
print_r( $arr ) ;
uksort( $arr, array( new kcmp( $reference ), "kcompare" ) ) ;
print_r( $arr ) ;


Ordena un array según sus valores usando una función de comparación definida por el usuario

  • « uksort
  • Clases/Objetos »
  • PHP Manual
  • Funciones de Arrays
  • Ordena un array según sus valores usando una función de comparación definida por el usuario

usort

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

usort — Ordena un array según sus valores usando una función de comparación definida por el usuario

Descripción

usort ( array &$array , callable $value_compare_func ) : bool

Esta función ordenará un array según sus valores usando una función de comparación definida por el usuario. Si el array que se desea ordenar necesita ser ordenado por algún criterio no trivial, debería usar esta función.

Nota:

Si dos miembros se comparan como iguales, su orden relativo en el array oredenado será indefinido.

Nota: Esta función asigna nuevas clave a los elemenos del array. Eliminará cualquier clave existente que haya sido asignada, en lugar de reordenar las claves.

Parámetros

array

El array de entrada.

value_compare_func

La función de comparación debe devolver un entero menor, igual o mayor que cero si el primer argumento se considera que sea respectivamente menor, igual o mayor que el segundo. Observe que antes de PHP 7.0.0 este entero debía estar en el rango de -2147483648 a 2147483647.

callback ( mixed $a, mixed $b ) : int
Precaución

La devolución de valores que no sean de tipo integer por parte de la función de comparación, como float, resultará en una conversión interna a integer del valor devuelto por la llamada de retorno. Así, valores como 0.99 y 0.1 serán convertidos al valor de tipo integer 0, lo cual hará que la comparación de tales valores sea igual.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de usort()

<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $clave => $valor) {
    echo "$clave: $valor\n";
}
?>

El resultado del ejemplo sería:

0: 1
1: 2
2: 3
3: 5
4: 6

Nota:

Obviamente, en este caso tan trivial, la función sort() sería más apropiada.

Ejemplo #2 Ejemplo de usort() usando un array multidimensional

<?php
function cmp($a, $b)
{
    return strcmp($a["fruta"], $b["fruta"]);
}

$frutas[0]["fruta"] = "uvas";
$frutas[1]["fruta"] = "limones";
$frutas[2]["fruta"] = "manzanas";

usort($frutas, "cmp");

while (list($clave, $valor) = each($frutas)) {
    echo "\$frutas[$clave]: " . $valor["fruta"] . "\n";
}
?>

Cuando se ordena un array multidimensional, $a y $b contienen referencias al primer índice del array.

El resultado del ejemplo sería:

$frutas[0]: limones
$frutas[1]: manzanas
$frutas[2]: uvas

Ejemplo #3 Ejemplo de usort() usando una función miembro de un objeto

<?php
class ObjPrueba {
    var $nombre;

    function ObjPrueba($nombre)
    {
        $this->nombre = $nombre;
    }

    /* Ésta es la función de comparación estática: */
    static function cmp_obj($a, $b)
    {
        $al = strtolower($a->nombre);
        $bl = strtolower($b->nombre);
        if ($al == $bl) {
            return 0;
        }
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new ObjPrueba("c");
$a[] = new ObjPrueba("b");
$a[] = new ObjPrueba("d");

usort($a, array("ObjPrueba", "cmp_obj"));

foreach ($a as $elemento) {
    echo $elemento->nombre . "\n";
}
?>

El resultado del ejemplo sería:

b
c
d

Ejemplo #4 Ejemplo de usort() usando un cierre para ordenar un array multidimensional

<?php
$array[0] = array('clave_a' => 'z', 'clave_b' => 'c');
$array[1] = array('clave_a' => 'x', 'clave_b' => 'b');
$array[2] = array('clave_a' => 'y', 'clave_b' => 'a');

function build_sorter($clave) {
    return function ($a, $b) use ($clave) {
        return strnatcmp($a[$clave], $b[$clave]);
    };
}

usort($array, build_sorter('clave_b'));

foreach ($array as $item) {
    echo $item['clave_a'] . ', ' . $item['clave_b'] . "\n";
}
?>

El resultado del ejemplo sería:

y, a
x, b
z, c

Ver también

  • uasort() - Ordena un array con una función de comparación definida por el usuario y mantiene la asociación de índices
  • comparación de funciones de orden de arrays

User Contributed Notes

gus dot antoniassi at gmail dot com 10-Jun-2019 01:23
This is a simple way to sort based on a "priority list":

<?php

$order = [1,3,0,2];
$arr =   [
    [ 'id' => 0 ],
    [ 'id' => 1 ],
    [ 'id' => 2 ],
    [ 'id' => 3 ],
];

uasort(
    $arr,
    function ($a, $b) use ($order) {
        return array_search($a['id'], $order) <=> array_search($b['id'], $order);
    }
);

print_r($arr);

?>

This will return:

Array
(
    [1] => Array
        (
            [id] => 1
        )

    [3] => Array
        (
            [id] => 3
        )

    [0] => Array
        (
            [id] => 0
        )

    [2] => Array
        (
            [id] => 2
        )

)

Note that if you have a value in $arr that is not on the $order list, you will need additional checks since the array_search function returns FALSE for undefined indexes.
chris at candm dot org dot uk 19-Jan-2019 01:15
In case anyone is interested, comparative timings over 100000000 runs
Based on comparing integers (500 and 501)
Spaceship:4
()?: operator:10
Subtraction:2

Based on comparing floats (500.1 and 501.3) (caveats noted)
Spaceship:5
()?: operator:9
Subtraction:3

Based on comparing strings ("five" and "four")
Spaceship:7
()?: operator:17
(Subtraction obviously not available)

Note: a dummy run was done with an empty loop and the elapsed time for this was subtracted from each of the above times so that they reflect ONLY the time to do the comparisons. As for significance. unless you are doing very large numbers of comparisons where spaceships are the order of the day, the difference is insignificant.
user dot boba at gmail dot com 13-Sep-2017 05:10
PHP7 spaceship operator very helpful in sorting function callback

http://php.net/manual/en/migration70.new-features.php#migration70.new-features.spaceship-op

<?php

// PHP < 7 example
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// PHP7 example
function cmp($a, $b)
{
    return $a <=> $b;
}
121616591 at qq dot com 02-May-2017 09:49
You can also sort multi-dimensional array for multiple values like as
<?php
$arr = array(
    array('id'=>1, 'age'=>1, 'sex'=>6, 'name'=>'a'),
    array('id'=>2, 'age'=>3, 'sex'=>1, 'name'=>'c'),
    array('id'=>3, 'age'=>3, 'sex'=>1, 'name'=>'b'),
    array('id'=>4, 'age'=>2, 'sex'=>1, 'name'=>'d'),
);

print_r(arrayOrderBy($arr, 'age asc,sex asc,name desc'));

function arrayOrderBy(array &$arr, $order = null) {
    if (is_null($order)) {
        return $arr;
    }
    $orders = explode(',', $order);
    usort($arr, function($a, $b) use($orders) {
        $result = array();
        foreach ($orders as $value) {
            list($field, $sort) = array_map('trim', explode(' ', trim($value)));
            if (!(isset($a[$field]) && isset($b[$field]))) {
                continue;
            }
            if (strcasecmp($sort, 'desc') === 0) {
                $tmp = $a;
                $a = $b;
                $b = $tmp;
            }
            if (is_numeric($a[$field]) && is_numeric($b[$field]) ) {
                $result[] = $a[$field] - $b[$field];
            } else {
                $result[] = strcmp($a[$field], $b[$field]);
            }
        }
        return implode('', $result);
    });
    return $arr;
}
?>

output:
Array
(
    [0] => Array
        (
            [id] => 1
            [age] => 1
            [sex] => 6
            [name] => a
        )

    [1] => Array
        (
            [id] => 4
            [age] => 2
            [sex] => 1
            [name] => d
        )

    [2] => Array
        (
            [id] => 2
            [age] => 3
            [sex] => 1
            [name] => c
        )

    [3] => Array
        (
            [id] => 3
            [age] => 3
            [sex] => 1
            [name] => b
        )

)
inigo dot grimbergen at gmail dot com 14-Jan-2017 06:51
to sort with numeric and empty values  and have the smallest on top:
<?php
    usort($list, function($a, $b) {
        if( $a == null && $b != null ) return 1;
        if( $a != null && $b == null ) return -1;
        return $a > $b ? 1 : -1;
    });
?>
returns
1
2
3
null
null
null
grzeniufication at gmail dot com 16-Dec-2016 07:56
Just wanted to show off the beauty of PHPs spaceship operator in this use case.

<?php // tested on PHP 7.1
$a = [2, 1, 3, 6, 5, 4, 7];
$asc = $desc = $a;
usort($asc, function (int $a, int $b) { return ($a <=> $b); });
usort($desc, function (int $a, int $b) { return -($a <=> $b); });
print_r([ $a, $asc, $desc ]);

/**
 * Getting ahead of myself but... If arrow function syntax was possible:
 * usort($asc, (int $a, int $b) => ($a <=> $b));
 * usort($desc, (int $a, int $b) => -($a <=> $b));
 */
?>
Nsisodia91 at gmail dot com 19-Feb-2016 12:12
You can also sort multi-dimensional array for multiple values like as

<?php
$arr = [
    [
        "name"=> "Sally",
        "nick_name"=> "sal",
        "availability"=> "0",
        "is_fav"=> "0"
    ],
    [
        "name"=> "David",
        "nick_name"=> "dav07",
        "availability"=> "0",
        "is_fav"=> "1"
    ],
    [
        "name"=> "Zen",
        "nick_name"=> "zen",
        "availability"=> "1",
        "is_fav"=> "0"
    ],
    [
        "name"=> "Jackson",
        "nick_name"=> "jack",
        "availability"=> "1",
        "is_fav"=> "1"
    ],
    [
        "name"=> "Rohit",
        "nick_name"=> "rod",
        "availability"=> "0",
        "is_fav"=> "0"
    ],

];

usort($arr,function($a,$b){
    $c = $b['is_fav'] - $a['is_fav'];
    $c .= $b['availability'] - $a['availability'];
    $c .= strcmp($a['nick_name'],$b['nick_name']);
    return $c;
});

print_r($arr);
?>

Output:

Array
(
    [0] => Array
        (
            [name] => Jackson
            [nick_name] => jack
            [availability] => 1
            [is_fav] => 1
        )

    [1] => Array
        (
            [name] => David
            [nick_name] => dav07
            [availability] => 0
            [is_fav] => 1
        )

    [2] => Array
        (
            [name] => Zen
            [nick_name] => zen
            [availability] => 1
            [is_fav] => 0
        )

    [3] => Array
        (
            [name] => Rohit
            [nick_name] => rod
            [availability] => 0
            [is_fav] => 0
        )

    [4] => Array
        (
            [name] => Sally
            [nick_name] => sal
            [availability] => 0
            [is_fav] => 0
        )

)
me at evertpot dot com 16-Jul-2015 11:13
I see many people here (including the official examples) write their callbacks rather clumsily like this:

<?php
function($a, $b) {
  if ($a === $b) {
    return 0;
  } elseif ($a < $b) {
    return -1;
  } else {
    return 1;
  }
}
?>

Or if they are a bit more clever:

<?php
function($a, $b) {

  if ($a === $b) {
    return 0;
  } else {
    return $a < $b ? -1 : 1;
  }
}
?>

But this can by simplified further to:

<?php
function($a, $b) {
  return $a - $b;
}
?>
bob at thecaverlys dot net 03-Dec-2014 03:10
Below is a variation on Example #4 that implements a multi-key natural sort on an associative array and can be called in such a way as to allow reversing the sort order and/or making the comparison case insensitive on a key by key basis.

Test code is included in the file – run it from the command line with: php sortUtils.php

<?php
/**
 *    sortUtils.php
*/

/**
 *    mknatsort() - Multi-Key Natural Sort for associative arrays
 *
 *    Uses the usort() function to perform a natural sort on a multi-dimensional
 *    array on multiple keys. Optionally specifying the sort order for each key
 *    and/or ignoring the case for each key value.
 *
 *    @param array $data_array The array to be sorted.
 *    @param mixed $keys The list of keys to be sorted by. This may be a single
 *        key or an array of keys
 *    @param boolean $reverse Specify whether or not to reverse the sort order. If
 *        there are multiple keys then $reverse may be an array of booleans - one
 *        per key.
 *    @param boolean $ignorecase Specify whether or not to ignore the case when
 *        comparing key values.reverse the sort order. If there are multiple keys
 *        then $ignorecase may be an array of booleans - one per key.
*/
function mknatsort ( &$data_array, $keys, $reverse=false, $ignorecase=false ) {
    // make sure $keys is an array
    if (!is_array($keys)) $keys = array($keys);
    usort($data_array, sortcompare($keys, $reverse, $ignorecase) );
}

function sortcompare($keys, $reverse=false, $ignorecase=false) {
    return function ($a, $b) use ($keys, $reverse, $ignorecase) {
        $cnt=0;
        // check each key in the order specified
        foreach ( $keys as $key ) {
            // check the value for ignorecase and do natural compare accordingly
            $ignore = is_array($ignorecase) ? $ignorecase[$cnt] : $ignorecase;
            $result = $ignore ? strnatcasecmp ($a[$key], $b[$key]) : strnatcmp($a[$key], $b[$key]);
            // check the value for reverse and reverse the sort order accordingly
            $revcmp = is_array($reverse) ? $reverse[$cnt] : $reverse;
            $result = $revcmp ? ($result * -1) : $result;
            // the first key that results in a non-zero comparison determines
            // the order of the elements
            if ( $result != 0 ) break;
            $cnt++;
        }
        return $result;
    };
} // end sortcompare()

// test code that will be skipped if this is included in the web environment
// test with: php sortUtils.php from the command line
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cli') {

    // the following shows several examples of usage and the resulting output.
    $test[] = array('Status'=>'In Progress', 'comment'=>'This looks good.', 'user_name'=>'John Doe', 'date_modified'=>'06/13/2014 11:20 AM', 'role'=>'Senior Account Manager');
    $test[] = array('Status'=>'In Progress', 'comment'=>'This looks good, please approve.', 'user_name'=>'John Doe', 'date_modified'=>'06/13/2014 11:19 AM', 'role'=>'Account Manager');
    $test[] = array('Status'=>'In Progress', 'comment'=>'This looks good.', 'user_name'=>'Jane Smith', 'date_modified'=>'06/13/2014 11:19 AM', 'role'=>'Senior Account Manager');
    $test[] = array('Status'=>'Returned', 'comment'=>'There is not enough informartion.  Please add the following.', 'user_name'=>'John Doe', 'date_modified'=>'06/13/2014 11:15 AM', 'role'=>'Account Manager');
    $test[] = array('Status'=>'In Progress', 'comment'=>'I am currently reviewing this.', 'user_name'=>'John Doe', 'date_modified'=>'06/13/2014 11:14 AM', 'role'=>'Account Manager');
    echo "Original array: ";
    print_r($test);

    echo "Sorted on date_modified: ";
    mknatsort($test, array('date_modified') );
    print_r($test);

    echo "Sorted on role(reversed) & date_modified: ";
    mknatsort($test, array('role','date_modified'),array(true,false) );
    print_r($test);

    echo "Sorted on role & date_modified(reversed): ";
    mknatsort($test, array('role','date_modified'),array(false,true) );
    print_r($test);
}

?>
Gerald Schneider 09-Dec-2013 07:57
usort returns null when the sorting function is not (yet) defined. The function has to be defined before usort is called, afterwards doesn't work.
Hayley Watson 08-Apr-2013 10:30
As the documentation says, the comparison function needs to return an integer that is either "less than, equal to, or greater than zero". There is no requirement to restrict the value returned to -1, 0, 1.

<?php
usort($array, function($a, $b) {
    if($a->integer_property > $b->integer_property) {
        return 1;
    }
    elseif($a->integer_property < $b->integer_property) {
        return -1;
    }
    else {
        return 0;
    }
});
?>

can be simplified to

<?php
usort($array, function($a, $b) {
    return $a->integer_property - $b->integer_property;
});
?>

This of course applies to any comparison function that calculates an integer "score" for each of its arguments to decide which is "greater".
Jian Wu 06-Jul-2012 09:16
The usort function actually moves $b up when the callback function returns both 0 and 1.  If you want to preserve the original order in the array, return 1 when $a == $b instead of 0.  Try this code below to see how usort alters the order of the original array when all values are the same.

<?php
class TestObj {
    private $name;
    private $id;

    function TestObj($name, $id) {
        $this->name = $name;
        $this->id = $id;
    }

    static function cmp_obj($a, $b) {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) {
            return 0; // return 1 if you don't want $b to go in front of $a
        }
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("a", 1);
$a[] = new TestObj("a", 2);
$a[] = new TestObj("a", 3);

var_dump($a);
usort($a, array("TestObj", "cmp_obj"));
var_dump($a);
?>
zuallauz at gmail dot com 29-Mar-2012 09:56
When trying to do some custom sorting with objects and an anonymous function it wasn't entirely clear how this usort function works. I think it probably uses a quicksort in the background. Basically it actually moves the $b variable up or down in respect to the $a variable. It does NOT move the $a variable inside the callback function. This is key to getting your logic right in the comparisons.

If you return -1 that moves the $b variable down the array, return 1 moves $b up the array and return 0 keeps $b in the same place.

To test I cut down my code to sorting a simple array from highest priority to lowest.

<?php
$priorities = array(5, 8, 3, 7, 3);

usort($priorities, function($a, $b)
{
    if ($a == $b)
    {
        echo "a ($a) is same priority as b ($b), keeping the same\n";
        return 0;
    }
    else if ($a > $b)
    {
        echo "a ($a) is higher priority than b ($b), moving b down array\n";
        return -1;
    }
    else {
        echo "b ($b) is higher priority than a ($a), moving b up array\n";
        return 1;
    }
});

echo "Sorted priorities:\n";
var_dump($priorities);
?>

Output:

b (8) is higher priority than a (3), moving b up array
b (5) is higher priority than a (3), moving b up array
b (7) is higher priority than a (3), moving b up array
a (3) is same priority as b (3), keeping the same
a (8) is higher priority than b (3), moving b down array
b (8) is higher priority than a (7), moving b up array
b (8) is higher priority than a (5), moving b up array
b (8) is higher priority than a (3), moving b up array
a (5) is higher priority than b (3), moving b down array
a (7) is higher priority than b (5), moving b down array

Sorted priorities:
array(5) {
  [0]=> int(8)
  [1]=> int(7)
  [2]=> int(5)
  [3]=> int(3)
  [4]=> int(3)
}
andi_mclean at ntlworld dot com 04-Feb-2012 03:58
I needed a sort method that would sort strings but take note of any numbers and would compare them as number. I also want to ignore any non alphanumerical characters.

Eg.
Slot 1 Example
Slot 10 Example
Slot 2 Example

Should infact be
Slot 1 Example
Slot 2 Example
Slot 10 Example

<?php
function sort_with_numbers($a , $b) {
    $a = explode(' ',$a);
    $b = explode(' ',$b);
    $size = min(count($a), count($b));
    for($index =0; $index < $size; ++$index) {
        $a1 = ereg_replace("[^A-Za-z0-9]", "",$a[$index]);
        $b1 = ereg_replace("[^A-Za-z0-9]", "",$b[$index]);
        $equal = 0;
        if (is_numeric($a1) && is_numeric($b1)) {
            $equal = $a1 - $b1;
        } else {
            $equal = strcasecmp($a1,$b1);
        }
        if ($equal < 0) {
            return -1;
        }
        if ($equal > 0) {
            return 1;
        }
    }
    return count($a) - count($b);
}
?>
admin at gosenz dot com 04-Dec-2011 08:58
sort multi-dimentional arrays in class with usort

<?php
class ArraySort
{
    private $arr = array();

    public function __construct($arr)
    {
        $this->arr = $arr;
    }

    public function doSort()
    {
        $cmp = function($a, $b)
        {
            //Do Some Comparation
        }
        if(is_array($this->arr))
        {
            usort($this->arr, $cmp);
        }
        return $this->arr;
    }
}
?>
Gok6tm 13-Sep-2011 06:09
this is a new multisort function for sorting on multiple subfield like it will be in sql : 'ORDER BY field1, field2'
number of sort field is undefined
<?php

$array[] = array('soc' => 3, 'code'=>1);
$array[] = array('soc' => 2, 'code'=>1);
$array[] = array('soc' => 1, 'code'=>1);
$array[] = array('soc' => 1, 'code'=>1);
$array[] = array('soc' => 2, 'code'=>5);
$array[] = array('soc' => 1, 'code'=>2);
$array[] = array('soc' => 3, 'code'=>2);

//usage
print_r(multiSort($array, 'soc', 'code'));

function multiSort() {
    //get args of the function
    $args = func_get_args();
    $c = count($args);
    if ($c < 2) {
        return false;
    }
    //get the array to sort
    $array = array_splice($args, 0, 1);
    $array = $array[0];
    //sort with an anoymous function using args
    usort($array, function($a, $b) use($args) {

        $i = 0;
        $c = count($args);
        $cmp = 0;
        while($cmp == 0 && $i < $c)
        {
            $cmp = strcmp($a[ $args[ $i ] ], $b[ $args[ $i ] ]);
            $i++;
        }

        return $cmp;

    });

    return $array;

}
?>

output:
Array
(
    [0] => Array
        (
            [soc] => 1
            [code] => 1
        )

    [1] => Array
        (
            [soc] => 1
            [code] => 1
        )

    [2] => Array
        (
            [soc] => 1
            [code] => 2
        )

    [3] => Array
        (
            [soc] => 2
            [code] => 1
        )

    [4] => Array
        (
            [soc] => 2
            [code] => 5
        )

    [5] => Array
        (
            [soc] => 3
            [code] => 1
        )

    [6] => Array
        (
            [soc] => 3
            [code] => 2
        )

)
Lea Hayes 12-Jul-2011 05:55
<?php
/**
 * Sort array of objects by field.
 *
 * @param array $objects Array of objects to sort.
 * @param string $on Name of field.
 * @param string $order (ASC|DESC)
 */
function sort_on_field(&$objects, $on, $order = 'ASC') {
    $comparer = ($order === 'DESC')
        ? "return -strcmp(\$a->{$on},\$b->{$on});"
        : "return strcmp(\$a->{$on},\$b->{$on});";
    usort($objects, create_function('$a,$b', $comparer));
}
?>
bcsj 28-Jun-2011 11:12
Sorting a multidimensional array by a subkey seem to be one of the bigger challenges when using usort. At least if one want the key to be dynamic. For anyone interested this code seemed to work rather well for me:

<?php

usort($array,array(new cmp($key), "cmp__"));

class cmp {
    var $key;
    function __construct($key) {
        $this->key = $key;
    }

    function cmp__($a,$b) {
        $key = $this->key;
        if ($a[$key] == $b[$key]) return 0;
        return (($a[$key] > $b[$key]) ? 1 : -1);
    }
}

?>
xaguilars at gmail dot com 06-May-2010 04:03
I'd like to share with the community my function for sorting an array of arrays or objects containing associative data. This could be used, for example, with a MySQL result.

<?php
function sort_by($field, &$arr, $sorting=SORT_ASC, $case_insensitive=true){
    if(is_array($arr) && (count($arr)>0) && ( ( is_array($arr[0]) && isset($arr[0][$field]) ) || ( is_object($arr[0]) && isset($arr[0]->$field) ) ) ){
        if($case_insensitive==true) $strcmp_fn = "strnatcasecmp";
        else $strcmp_fn = "strnatcmp";

        if($sorting==SORT_ASC){
            $fn = create_function('$a,$b', '
                if(is_object($a) && is_object($b)){
                    return '.$strcmp_fn.'($a->'.$field.', $b->'.$field.');
                }else if(is_array($a) && is_array($b)){
                    return '.$strcmp_fn.'($a["'.$field.'"], $b["'.$field.'"]);
                }else return 0;
            ');
        }else{
            $fn = create_function('$a,$b', '
                if(is_object($a) && is_object($b)){
                    return '.$strcmp_fn.'($b->'.$field.', $a->'.$field.');
                }else if(is_array($a) && is_array($b)){
                    return '.$strcmp_fn.'($b["'.$field.'"], $a["'.$field.'"]);
                }else return 0;
            ');
        }
        usort($arr, $fn);
        return true;
    }else{
        return false;
    }
}
?>
Will Shaver 27-Aug-2009 02:31
An even better implementation of osort [than my original, posted on 24-AUG-09 (since deleted)], allowing for multiple properties and directions.  With php 5.3.0 sorting by properties of an object becomes MUCH simpler.  Note that this uses anonymous functions / closures. Might find reviewing the php docs on that useful.  Look below for examples for previous version of php.

<?php
function osort(&$array, $props)
{
    if(!is_array($props))
        $props = array($props => true);

    usort($array, function($a, $b) use ($props) {
        foreach($props as $prop => $ascending)
        {
            if($a->$prop != $b->$prop)
            {
                if($ascending)
                    return $a->$prop > $b->$prop ? 1 : -1;
                else
                    return $b->$prop > $a->$prop ? 1 : -1;
            }
        }
        return -1; //if all props equal
    });
}
?>

Usage:

<?php
osort($items, array("Color" => true, "Size" => false));
//or
osort($items, "Color");
?>
gmail.com - nmcquay 31-Mar-2009 12:25
I wrote a wrapper for usort that lets you use something similar to an SQL ORDER BY clause. It can sort arrays of associative arrays and arrays of objects and I think it would work with some hybrid case.

Example of how the function works:

<?php
$testAry = array(
  array('a' => 1, 'b' => 2, 'c' => 3),
  array('a' => 2, 'b' => 1, 'c' => 3),
  array('a' => 3, 'b' => 2, 'c' => 1),
  array('a' => 1, 'b' => 3, 'c' => 2),
  array('a' => 2, 'b' => 3, 'c' => 1),
  array('a' => 3, 'b' => 1, 'c' => 2)
);

Utility::orderBy($testAry, 'a ASC, b DESC');

//Result:
$testAry = array(
  array('a' => 1, 'b' => 3, 'c' => 2),
  array('a' => 1, 'b' => 2, 'c' => 3),
  array('a' => 2, 'b' => 3, 'c' => 1),
  array('a' => 2, 'b' => 1, 'c' => 3),
  array('a' => 3, 'b' => 2, 'c' => 1),
  array('a' => 3, 'b' => 1, 'c' => 2)
);
?>

To sort an array of objects you would do something like:
Utility::orderBy($objectAry, 'getCreationDate() DESC, getSubOrder() ASC');

This would sort an array of objects that have methods getCreationDate() and getSubOrder().

Here is the function:

<?php
class Utility {
    /*
    * @param array $ary the array we want to sort
    * @param string $clause a string specifying how to sort the array similar to SQL ORDER BY clause
    * @param bool $ascending that default sorts fall back to when no direction is specified
    * @return null
    */
    public static function orderBy(&$ary, $clause, $ascending = true) {
        $clause = str_ireplace('order by', '', $clause);
        $clause = preg_replace('/\s+/', ' ', $clause);
        $keys = explode(',', $clause);
        $dirMap = array('desc' => 1, 'asc' => -1);
        $def = $ascending ? -1 : 1;

        $keyAry = array();
        $dirAry = array();
        foreach($keys as $key) {
            $key = explode(' ', trim($key));
            $keyAry[] = trim($key[0]);
            if(isset($key[1])) {
                $dir = strtolower(trim($key[1]));
                $dirAry[] = $dirMap[$dir] ? $dirMap[$dir] : $def;
            } else {
                $dirAry[] = $def;
            }
        }

        $fnBody = '';
        for($i = count($keyAry) - 1; $i >= 0; $i--) {
            $k = $keyAry[$i];
            $t = $dirAry[$i];
            $f = -1 * $t;
            $aStr = '$a[\''.$k.'\']';
            $bStr = '$b[\''.$k.'\']';
            if(strpos($k, '(') !== false) {
                $aStr = '$a->'.$k;
                $bStr = '$b->'.$k;
            }

            if($fnBody == '') {
                $fnBody .= "if({$aStr} == {$bStr}) { return 0; }\n";
                $fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n";
            } else {
                $fnBody = "if({$aStr} == {$bStr}) {\n" . $fnBody;
                $fnBody .= "}\n";
                $fnBody .= "return ({$aStr} < {$bStr}) ? {$t} : {$f};\n";
            }
        }

        if($fnBody) {
            $sortFn = create_function('$a,$b', $fnBody);
            usort($ary, $sortFn);
        }
    }
}
?>
luke dot semerau at gmail dot com 28-Mar-2009 12:25
If you need to use usort with a key in the calling method, I wrote this as a utility:
<?php

function usort_comparison($obj, $method, $key) {
    $usorter = &new Usort($obj, $method, $key);
    return array($usorter, "sort");
}

class Usort {
    function __construct($obj, $method, $key) {
        $this->obj = $obj;
        $this->method = $method;
        $this->key = $key;
    }
    function sort($a, $b) {
        return call_user_func_array(array($this->obj, $this->method), array($a, $b, $this->key));
    }
}

?>

<?php

require_once("util/usort.php");

class Foo {
    $items = array(FooBar(13), FooBar(2));
    public function sorter() {
        usort($this-items, usort_comparison("Foo", "_cmp", "item"));
    }

    public static function _cmp($a, $b, $key) {
         return strcasecmp($a->$key, $b->$key);
    }

}

class FooBar {
    public $item;
    function __construct($val) {
        $this->item = $val;
    }
}

?>

~ simple example... but in the way I need to use it was the key was used in a switch statement to choose the different member of the object to compare against dynamically (as in, sort by x or y or z)
jalil at measat dot org 28-Dec-2008 05:37
<?php
/*---------------------------------------------------------
* my own home made easy object sort, which
* i cannot find anywhere on the net
* at all, tut. i can find only complicated ones,
* which brings me a headache.
*
* You can enhance it to return all sorts of error
* conditions if you wish,
* i need nothing but a false return upon failure to sort,
* so that is the only error i have here
*
* Example usage:
*
* INPUT                 -       $objects_array
// an array of objects for sorting

* PARAMETERS    -       property
// the property of the object to be sorted

* OUTPUT                -       $engine
// an engine object created by new,
// with your arrays of objects sorted according to your
// selected property
//( the sorting is done upon sort object creation )
*
* Code Examples
*
* $engine = new objSorter($objects_array);
// sorts on FIRST property -  default

* $engine = new objSorter($objects_array,'property');
// sort on ANY specific property
*--------------------------------------------------------*/

class objSorter
{
var $property;
var $sorted;

    function ObjSorter($objects_array,$property=null)
        {
            $sample    = $objects_array[0];
            $vars    = get_object_vars($sample);

        if (isset($property))
            {
            if (isset($sample->$property))
// make sure requested property is correct for the object
                {
                $this->property = $property;
                usort($objects_array, array($this,'_compare'));
                }
            else
                {
                $this->sorted    = false;
                return;
                }
            }
        else
            {
                list($property,$var)     = each($sample);
                $this->property         = $property;
                usort($objects_array, array($this,'_compare'));
            }

        $this->sorted    = ($objects_array);
        }

    function _compare($apple, $orange)
        {
        $property    = $this->property;
        if ($apple->$property == $orange->$property) return 0;
        return ($apple->$property < $orange->$property) ? -1 : 1;
        }
} // end class
?>

USAGE EXAMPLE
DUMP ORIGINAL
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬ 219,078 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬ 677,180 )
user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )

SORTED by age

<?php
$objects                = new ObjSorter($objects_array,'age');
if ($objects->sorted)
{
$objects_array  = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "<br />"; }
}
?>

user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬ 219,078 )
user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬ 677,180 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )

SORTED by richness

<?php
$objects                = new ObjSorter($objects_array,'richness');
if ($objects->sorted)
{
$objects_array  = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "<br />"; }
}
?>

user Object ( [name] => Vejosehona Auva [age] => 20 [richness] => â‚¬ 144,540 )
user Object ( [name] => Fewame Wojuvuzo [age] => 69 [richness] => â‚¬ 198,231 )
user Object ( [name] => Janirevi Fakejorumoa [age] => 19 [richness] => â‚¬ 219,078 )
user Object ( [name] => Korejowi Mezede [age] => 95 [richness] => â‚¬ 3,272 )
user Object ( [name] => Fazurada Aayu [age] => 16 [richness] => â‚¬ 302,352 )
user Object ( [name] => Cepomase Buaesukoyua [age] => 32 [richness] => â‚¬ 677,180 )
user Object ( [name] => Risuku Zagedobu [age] => 48 [richness] => â‚¬ 763,860 )
user Object ( [name] => Yunihe Jopoba [age] => 27 [richness] => â‚¬ 899,970 )
user Object ( [name] => Nugoaivu Jongyi [age] => 84 [richness] => â‚¬ 94,853 )

Simulated wrong property request ( dumb property )

<?php
$objects                = new ObjSorter($objects_array,'dumb property');
if ($objects->sorted)
{
$objects_array  = $objects->sorted;
foreach ($objects_array as $key=>$object) { print_r($object); echo "<br />"; }
}
else echo 'DUMB ERROR';
?>

DUMB ERROR
drorasta 22-Jun-2008 10:16
Here's how you can usort() a multidimensional array (like in example #2 above) within a class:

<?php usort($myArray, array("className", "cmp")); ?>
Sid_M 05-Nov-2007 05:54
The sample function for having the sort function be a class method has a comment identifying the sorting function as static, however the function does not have the static keyword. In PHP 5 (at least as configured on my server), usort will fail, identifying the method as non-static. Preceding the function keyword with the static keyword fixed the problem.
svenxy AT nospam gmx net 16-Oct-2006 01:58
This will sort subnets correctly:

<?php

$zones =
array('192.168.11',
'192.169.12',
'192.168.13',
'192.167.14',
'192.168.15',
'122.168.16',
'192.168.17'
);

function sort_subnets ($a, $b) {
    $a_arr = explode('.', $a);
    $b_arr = explode('.', $b);
    foreach (range(0,3) as $i) {
        if ( $a_arr[$i] < $b_arr[$i] ) {
            return -1;
        }
        elseif ( $a_arr[$i] > $b_arr[$i] ) {
            return 1;
        }
    }
    return -1;
}

usort($zones, 'sort_subnets');
print '<pre>';
print_r($zones);
print '</pre>';

?>
stephen in koto 05-Apr-2006 10:28
For using usort inside a method in an object, where the callback sort method is in the same object, this works:

<?php usort($arr_to_sort, array($this, "sort_terms_by_criteria")); ?>

If you wish to keep elements in their original or reverse order if they are the same length, just don't return zero for items that compare the same. Return a 1 or -1, as appropriate.
sydney at totoche dot org 16-Jan-2006 01:44
Instead of doing  :

<?php $strc = strcmp( strtolower($a[$f]), strtolower($b[$f]) ); ?>

you could do this :

<?php $strc = strcasecmp( $a[$f], $b[$f] ); ?>

which is more efficient and is does case insensitive comparison according to the current locale.
Jeremy Swinborne 20-Jul-2005 01:56
When I query a DB I usually put my record set inside of a multi-dimentional array.  I finally wrote a program that will allow you to sort your record set by column after you put it in an array.

<?php
$test = array();
$test[0]['name'] = 'jeremy';
$test[0]['email'] = 'lala@example.com';
$test[0]['phone'] = '123-123-1234';
$test[0]['trick'] = 'mezopia';

$test[1]['name'] = 'Amanda';
$test[1]['email'] = 'hot@example.com';
$test[1]['phone'] = '123-123-1235';
$test[1]['trick'] = 'youarecool';

$test[2]['name'] = 'john';
$test[2]['email'] = 'wowee@example.com';
$test[2]['phone'] = '123-123-3333';
$test[2]['trick'] = 'goneinanhour';

print_r(columnSort($test, 'name'));

function columnSort($unsorted, $column) {
    $sorted = $unsorted;
    for ($i=0; $i < sizeof($sorted)-1; $i++) {
      for ($j=0; $j<sizeof($sorted)-1-$i; $j++)
        if ($sorted[$j][$column] > $sorted[$j+1][$column]) {
          $tmp = $sorted[$j];
          $sorted[$j] = $sorted[$j+1];
          $sorted[$j+1] = $tmp;
      }
    }
    return $sorted;
}
?>
dmhouse at gmail dot com 19-Jul-2005 02:09
The easiest way to compare two integers is just to take the second away from the first. For example, say you wanted to sort by an integer property of an object. Your comparison function would look like this:

<?php
function compare_counts($a, $b) {
  return $a->count - $b->count;
}
?>

This works because you don't necessarily have to return -1, 0 or 1, the manual states any integer less than, equal to or greater than 0 is OK.
Raveler at telenet dot be 20-May-2004 10:02
The array_alternate_multisort function written by robert below doesn't work. There are several bugs in the code and it doesn't work when sorting by multiple keys because the order of the first key isn't taken into account when sorting by the second key and so on. Also, because robert uses strcasecmp the algorithm doesn't work properly with floats or other variable types. Here's the improved version:

<?php
    function SortArray() {
        $arguments = func_get_args();
        $array = $arguments[0];
        $code = '';
        for ($c = 1; $c < count($arguments); $c += 2) {
            if (in_array($arguments[$c + 1], array("ASC", "DESC"))) {
                $code .= 'if ($a["'.$arguments[$c].'"] != $b["'.$arguments[$c].'"]) {';
                if ($arguments[$c + 1] == "ASC") {
                    $code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? -1 : 1); }';
                }
                else {
                    $code .= 'return ($a["'.$arguments[$c].'"] < $b["'.$arguments[$c].'"] ? 1 : -1); }';
                }
            }
        }
        $code .= 'return 0;';
        $compare = create_function('$a,$b', $code);
        usort($array, $compare);
        return $array;
    }
?>
sreid at sea-to-sky dot net 07-Jan-2004 08:22
As the manual says, "If two members compare as equal, their order in the sorted array is undefined." This means that the sort used is not "stable" and may change the order of elements that compare equal.

Sometimes you really do need a stable sort. For example, if you sort a list by one field, then sort it again by another field, but don't want to lose the ordering from the previous field. In that case it is better to use usort with a comparison function that takes both fields into account, but if you can't do that then use the function below. It is a merge sort, which is guaranteed O(n*log(n)) complexity, which means it stays reasonably fast even when you use larger lists (unlike bubblesort and insertion sort, which are O(n^2)).

<?php
function mergesort(&$array, $cmp_function = 'strcmp') {
    // Arrays of size < 2 require no action.
    if (count($array) < 2) return;
    // Split the array in half
    $halfway = count($array) / 2;
    $array1 = array_slice($array, 0, $halfway);
    $array2 = array_slice($array, $halfway);
    // Recurse to sort the two halves
    mergesort($array1, $cmp_function);
    mergesort($array2, $cmp_function);
    // If all of $array1 is <= all of $array2, just append them.
    if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) {
        $array = array_merge($array1, $array2);
        return;
    }
    // Merge the two sorted arrays into a single sorted array
    $array = array();
    $ptr1 = $ptr2 = 0;
    while ($ptr1 < count($array1) && $ptr2 < count($array2)) {
        if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) {
            $array[] = $array1[$ptr1++];
        }
        else {
            $array[] = $array2[$ptr2++];
        }
    }
    // Merge the remainder
    while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++];
    while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++];
    return;
}
?>
skrebbel at operamail dot com 27-Mar-2003 01:59
here's another recursive multisort, however a clean and fast one that is class-based (but works as well outside classes) and does not uglify your global namespace at all. note that strnatcmp is used, but one could use something else of course.

btw, for arrays in which the rows/columns are 'swapped', use array_multisort().

<?php
class Banana {
    var $aData;//the array we want to sort.
    var $aSortkeys;//the order in which we want the array to be sorted.
    function _sortcmp($a, $b, $i=0) {
        $r = strnatcmp($a[$this->aSortkeys[$i]],$b[$this->aSortkeys[$i]]);
        if($r==0) {
            $i++;
            if ($this->aSortkeys[$i]) $r = $this->_sortcmp($a, $b, $i+1);
        }
        return $r;
    }
    function sort() {
        if(count($this->aSortkeys)) {
            usort($this->aData,array($this,"_sortcmp"));
        }
    }
}
$B = new Banana;
$B->aData = array(
    array("name" => "hank", "headsize" => "big", "age" => 32),
    array("name" => "frank", "headsize" => "huge", "age" => 36)
);
$B->aSortkeys = array("age","name");
$B->sort();

?>
sorry for the ugly indenting, but i couldn't get it any better in this note adder thing.
mkr at binarywerks dot dk 20-Sep-2002 09:29
If you want to sort an array according to another array acting as a priority list, you can use this function.

<?php
function listcmp($a, $b)
{
  global $order;

  foreach($order as $key => $value)
    {
      if($a==$value)
        {
          return 0;
          break;
        }

      if($b==$value)
        {
          return 1;
          break;
        }
    }
}

$order[0] = "first";
$order[1] = "second";
$order[2] = "third";

$array[0] = "second";
$array[1] = "first";
$array[2] = "third";
$array[3] = "fourth";
$array[4] = "second";
$array[5] = "first";
$array[6] = "second";

usort($array, "listcmp");

print_r($array);
?>
prozac at iguanasoft dot com 15-Jul-2002 05:55
Here is a simple example of converting a timestamp date("U") into a date. This sorts by that day and then by string value alphabetically.

I hope it saves someone some time... Happy PHP'in!

<?php
//data to sort
$shared[0]["page_id"] = "2025731470";
$shared[1]["page_id"] = "2025731450";
$shared[2]["page_id"] = "1025731456";
$shared[3]["page_id"] = "1025731460";
$shared[0]["username"] = "larry";
$shared[1]["username"] = "alvin";
$shared[2]["username"] = "garth";
$shared[3]["username"] = "harvy";

//function to convert timestamp to date
function convert_timestamp($timestamp){
    $limit=date("U");
    $limiting=$timestamp-$limit;
    return date ("Ymd", mktime (0,0,$limiting));
}
//comparison function
function cmp ($a, $b) {
    $l=convert_timestamp($a["page_id"]);
    $k=convert_timestamp($b["page_id"]);
    if($k==$l){
        return strcmp($a["username"], $b["username"]);
    }else{
        return strcmp($k, $l);
    }
}

//sort array
usort($shared, "cmp");

//display sorted info
while (list ($key, $value) = each ($shared)) {
    echo "\$shared[$key]: ";
    echo $value["page_id"];
    echo " username: ";
    echo $value["username"];
    echo "<break_tag>";
}
?>

This will output:
$shared[0]: 2025731450   username: alvin
$shared[1]: 2025731470   username: larry
$shared[2]: 1025731456   username: garth
$shared[3]: 1025731460   username: harvy
alex at netflex dot nl 02-Jul-2002 04:10
This function will sort on more then one values, test and have fun

<pre>
<?php

  $array[0]['name'] = "a";
  $array[0]['id'] = 3;

  $array[1]['name'] = "a";
  $array[1]['id'] = 2;

  $array[2]['name'] = "a";
  $array[2]['id'] = 5;

  $array[3]['name'] = "b";
  $array[3]['id'] = 8;

  $array[4]['name'] = "b";
  $array[4]['id'] = 1;

  $array[5]['name'] = "b";
  $array[5]['id'] = 0;

  $array[6]['name'] = "c";
  $array[6]['id'] = 5;

  $array[7]['name'] = "c";
  $array[7]['id'] = 7;

  $array[8]['name'] = "c";
  $array[8]['id'] = 3;

  print_r($array);

  $sort_array[0]['name'] = "name";
  $sort_array[0]['sort'] = "ASC";
  $sort_array[0]['case'] = TRUE;

  $sort_array[1]['name'] = "id";
  $sort_array[1]['case'] = FALSE;

  sortx($array, $sort_array);

  print_r($array);

  function sortx(&$array, $sort = array()) {
    $function = '';
    while (list($key) = each($sort)) {
      if (isset($sort[$key]['case'])&&($sort[$key]['case'] == TRUE)) {
        $function .= 'if (strtolower($a["' . $sort[$key]['name'] . '"])<>strtolower($b["' . $sort[$key]['name'] . '"])) { return (strtolower($a["' . $sort[$key]['name'] . '"]) ';
      } else {
        $function .= 'if ($a["' . $sort[$key]['name'] . '"]<>$b["' . $sort[$key]['name'] . '"]) { return ($a["' . $sort[$key]['name'] . '"] ';
      }
      if (isset($sort[$key]['sort'])&&($sort[$key]['sort'] == "DESC")) {
        $function .= '<';
      } else {
        $function .= '>';
      }
      if (isset($sort[$key]['case'])&&($sort[$key]['case'] == TRUE)) {
        $function .= ' strtolower($b["' . $sort[$key]['name'] . '"])) ? 1 : -1; } else';
      } else {
        $function .= ' $b["' . $sort[$key]['name'] . '"]) ? 1 : -1; } else';
      }
    }
    $function .= ' { return 0; }';
    usort($array, create_function('$a, $b', $function));
  }

?>
</pre>
josh at wintelcom dot net 24-Aug-2001 06:58
This lets you sort an associative multi-dimensional array by multiple key/field names.  Much similiar to the SQL clause ORDER BY.  Enjoy.

<?php
function cmp ($a, $b) {

    // Populate this array with your values...
    // Below is the SQL equivalent of
    // select * from blah ORDER BY date desc, type asc, name asc

    $vals = array(
        'date' => 'd',
        'type' => 'a',
        'name' => 'a'
    );

    while(list($key, $val) = each($vals)) {

        if($val == "d") {
            if ($a["$key"] > $b["$key"]) {
                return -1;
            }
            if ($a["$key"] < $b["$key"]) {
                return 1;
            }
        }

        if($val == "a") {
            if ($a["$key"] < $b["$key"]) {
                return -1;
            }
            if($a["$key"] > $b["$key"]) {
                return 1;
            }
        }

    }

}
?>
franky at iname dot com 17-Jul-2001 03:08
For sort multi-array by specific index

<?php
function cmp ($a, $b)
{
 global $w_o;
 if ($a[$w_o] == $b[$w_o]) return 0;
 return ($a[$w_o] < $b[$w_o]) ? -1 : 1;
}
# the index is the second element of
# each row

$w_o =1;
usort($my_arry_info,"cmp");
?>
bo at erichsen dot com 20-Mar-2001 05:16
when using usort to refer to a function inside a class i have succesfully used:

<?php usort($myarray,array($this,"cmp")); ?>
derek at luddite dot net 18-Sep-2000 11:35
Needed a date sort and I didn't know if one was available so I wrote one. Maybe it'll help someone:

<?php
function DateSort($a,$b,$d="-") {
    if ($a == $b) {
        return 0;
    } else {  //Convert into dates and compare
        list($am,$ad,$ay)=split($d,$a);
        list($bm,$bd,$by)=split($d,$b);
        if (mktime(0,0,0,$am,$ad,$ay) < mktime(0,0,0,$bm,$bd,$by)) {
            return -1;
        } else {
            return 1;
        }
    }
}
?>

$d is the delimeter


Información de Clases/Objetos

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Ejemplos
  • Funciones de Clases/Objetos
    • __autoload — Intenta cargar una clase sin definir
    • class_alias — Crea un alias para una clase
    • class_exists — Verifica si la clase ha sido definida
    • get_called_class — El nombre de la clase enlazada estáticamente en tiempo de ejecución ("Late State Binding")
    • get_class_methods — Obtiene los nombres de los métodos de una clase
    • get_class_vars — Obtener las propiedades predeterminadas de una clase
    • get_class — Devuelve el nombre de la clase de un objeto
    • get_declared_classes — Devuelve una matriz con los nombres de las clases definidas
    • get_declared_interfaces — Devuelve un array con todas las interfaces declaradas
    • get_declared_traits — Devuelve un array de todos los traits declarados
    • get_object_vars — Obtiene las propiedades del objeto dado
    • get_parent_class — Recupera el nombre de la clase padre de un objeto o clase
    • interface_exists — Comprueba si una interfaz ha sido definida
    • is_a — Comprueba si un objeto es de una clase o tiene esta clase como una de sus madres
    • is_subclass_of — Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa
    • method_exists — Comprueba si existe un método de una clase
    • property_exists — Comprueba si el objeto o la clase tienen una propiedad
    • trait_exists — Comprobar si el trait existe

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Estas funciones permiten obtener información sobre clases y objetos. Se puede obtener el nombre de la clase a la que pertenece un objeto, así como sus propiedades y métodos miembro. Al usar estas funciones no sólo se puede averiguar la pertenencia a una clase de un objeto, sino también su vínculo parental (esto es, qué clase es la que extiende la clase del objeto).

Por favor, vea la sección de Objetos del manual para una explicación detallada de cómo están las clases y objetos implementados y de cómo son usados en PHP.

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

En este ejemplo, primero definimos una clase base y una extensión de la misma. La clase base describe una verdura en general, si es comestible o no y cuál es su color. La subclase Espinaca añade un método para cocinarla y otro para averiguar si está cocinada.

Ejemplo #1 classes.inc

<?php

// clase base con propiedades y métodos miembro
class Verdura {

   var $comestible;
   var $color;

   function __construct($comestible, $color="verde")
   {
       $this->comestible = $comestible;
       $this->color = $color;
   }

   function es_comestible()
   {
       return $this->comestible;
   }

   function qué_color()
   {
       return $this->color;
   }

} // fin de la clase Verdura

// ampliar la clase base
class Espinaca extends Verdura {

   var $concinada = false;

   function __construct()
   {
       parent::__construct(true, "verde");
   }

   function cocinarla()
   {
       $this->concinada = true;
   }

   function está_cocinada()
   {
       return $this->concinada;
   }

} // fin de la clase Espinaca

?>

Entonces instanciamos dos objetos de estas clases e imprimimos la información sobre ellos, incluida su linaje de clases. También definimos algunas funciones de utilidad, prinpipalmente para tener una impresión atractiva de las variables.

Ejemplo #2 test_script.php

<pre>
<?php

include "classes.inc";

// funciones de utilidad

function imprimir_vars($obj)
{
foreach (get_object_vars($obj) as $prop => $val) {
    echo "\t$prop = $val\n";
}
}

function imprimir_métodos($obj)
{
$arr = get_class_methods(get_class($obj));
foreach ($arr as $método) {
    echo "\tfunción $método()\n";
}
}

function linaje_de_clases($obj, $clase)
{
if (is_subclass_of($GLOBALS[$obj], $clase)) {
    echo "El objeto $obj pertenece a la clase " . get_class($GLOBALS[$obj]);
    echo ", una subclase de $clase\n";
} else {
    echo "El objeto $obj no pertenece a una subclase de $clase\n";
}
}

// instancias 2 objetos

$vegetariano = new Verdura(true, "blue");
$frondoso = new Espinaca();

// imprimir información sobre los objetos
echo "vegetariano: CLASE " . get_class($vegetariano) . "\n";
echo "frondoso: CLASE " . get_class($frondoso);
echo ", MADRE " . get_parent_class($frondoso) . "\n";

// mostrar las propiedades de vegetariano
echo "\nvegetariano: Propiedades\n";
imprimir_vars($vegetariano);

// y los métodos de frondoso
echo "\nfrondoso: Métodos\n";
imprimir_métodos($frondoso);

echo "\nLinaje:\n";
linaje_de_clases("frondoso", "Espinaca");
linaje_de_clases("frondoso", "Verdura");
?>
</pre>

Una cosa importanete a observar en el ejemplo anterior es que el objeto $frondoso es una instancia de la clase Espinaca que es una subclase de Verdura, por lo tanto, la última parte del script anterior imprimirá:

   [...]
Linaje:
El objeto frondoso no pertenece a una subclase de Espinaca
El objeto frondoso pertenece a la clase Espinaca, una subclase de Verdura

User Contributed Notes

There are no user contributed notes for this page.


Funciones de Clases/Objetos

Tabla de contenidos

  • __autoload — Intenta cargar una clase sin definir
  • class_alias — Crea un alias para una clase
  • class_exists — Verifica si la clase ha sido definida
  • get_called_class — El nombre de la clase enlazada estáticamente en tiempo de ejecución ("Late State Binding")
  • get_class_methods — Obtiene los nombres de los métodos de una clase
  • get_class_vars — Obtener las propiedades predeterminadas de una clase
  • get_class — Devuelve el nombre de la clase de un objeto
  • get_declared_classes — Devuelve una matriz con los nombres de las clases definidas
  • get_declared_interfaces — Devuelve un array con todas las interfaces declaradas
  • get_declared_traits — Devuelve un array de todos los traits declarados
  • get_object_vars — Obtiene las propiedades del objeto dado
  • get_parent_class — Recupera el nombre de la clase padre de un objeto o clase
  • interface_exists — Comprueba si una interfaz ha sido definida
  • is_a — Comprueba si un objeto es de una clase o tiene esta clase como una de sus madres
  • is_subclass_of — Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa
  • method_exists — Comprueba si existe un método de una clase
  • property_exists — Comprueba si el objeto o la clase tienen una propiedad
  • trait_exists — Comprobar si el trait existe

User Contributed Notes

Skydev 05-Jan-2011 11:40
A small function that allows finding all references to the object. Written in 3 minutes and may be buggy (for ex pass object as reference in some places?)

<?php
function find_ref_obj($object, $obj, $path) {
    if (in_array($obj,$GLOBALS['__REF_CHECKED'],true))
        return false;
    $GLOBALS['__REF_CHECKED'][]=$obj;
    $r = array();
    foreach ((array)$obj as $k => $v) {
        if ($v === $object)
            $r[] = $path . "->$k";
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$path . "->$k");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$path . "->$k");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    if (empty($r))
        return false;
    else
        return $r;
}
function find_ref_arr($object, $arr, $path) {
    if (in_array($arr,$GLOBALS['__REF_CHECKED'],true))
        return false;
    $GLOBALS['__REF_CHECKED'][]=$arr;
    $r = array();
    foreach ($arr as $k => $v) {
        if ($v === $object)
            $r[] = $path . "['$k']";
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$path . "['$k']");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$path . "['$k']");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    if (empty($r))
        return false;
    else
        return $r;
}
function find_references($object) {
    $r = array();
    $GLOBALS['__REF_CHECKED']=array();
    foreach ($GLOBALS as $n => $v)
    if ($n!='__REF_CHECKED')
    if ($n!='GLOBALS') {
        if ($v === $object)
            $r[]=$n;
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$n);
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$n);
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    unset($GLOBALS['__REF_CHECKED']);
    return $r;
}

function find_refs($object) {
    return implode(', ',find_references($object));
}
?>
Dennis 01-Jul-2010 04:04
We have an array with many objects in a style like

<?php

$step = new StepModel(1); // if the StepModel id is "1"
$demand = $step->getDemand(); // returns DemandModel
$step2 = $demand->getCustomer(); // returns StepModel
$demand2 = $step2->getDemand(); // returns DemandModel

// [ ... ]

?>

$step and $step2 can be the same objects. So we have an recursive array. Now we need to know if $step == $step2 or $step === $step2. In other words: We need to know the php internal resource ids.

Because there is no function in php api, we made the following function.

Be careful: In our case, all objects have as first attribute ["id":protected]. If your objects are different from this, you need to edit $pattern.

Warning: function is very slow and should only be called if it's necessary for debugging reasons:

<?php

/**
 * returns resource- and object-ids of all objects in an array
 *
 * @param array $array
 * @return array
 */
function getObjectInformation(Array $array)
{
    // start output-buffering
    ob_start();

    // create an var_dump of $array
    var_dump($array);

    // save the dump in var $dump
    $dump = ob_get_contents();

    // clean the output-buffer
    ob_end_clean();

    // delete white-spaces
    $dump = str_replace(' ', '', $dump);

    // define the regex-pattern
    // in our case, all objects look like this:
    //
    // object(ClassName)#1(1){
    // ["id":protected]=>
    // string(1)"1"
    $pattern  = '/object\(([a-zA-Z0-9]+)\)#([0-9]+)\([0-9]+\){\\n';
    $pattern .= '\["id":protected\]=>\\n';
    $pattern .= 'string\([0-9]+\)"([v]?[0-9]+)"/im';

    // search for all matches
    preg_match_all($pattern, $dump, $regs);

    // sort all mathes by class name, object id and then resource id
    array_multisort($regs[1], SORT_ASC, SORT_STRING,
                    $regs[3], SORT_ASC, SORT_NUMERIC,
                    $regs[2], SORT_ASC, SORT_NUMERIC);

    // cache the last match
    $lastMatch = array();

    // the return value
    $return = array();

    // loop through the matches
    for ($i = 0; $i < sizeof($regs[0]); $i ++) {

        // check if the current match was not visited before
        if (0 == sizeof($lastMatch) ||
            $regs[1][$i] != $lastMatch[1] ||
            $regs[2][$i] != $lastMatch[2] ||
            $regs[3][$i] != $lastMatch[3]) {

            // save the match in return value
            array_push($return, array($regs[1][$i],
                                      $regs[2][$i],
                                      $regs[3][$i]));
        }

        // save match in last match cache
        $lastMatch[1] = $regs[1][$i];
        $lastMatch[2] = $regs[2][$i];
        $lastMatch[3] = $regs[3][$i];
    }

    // return all matches
    return $return;
}

?>

I know, it's not that elegant but I hope it's useful for a few people.
ahigerd at timeips dot com 20-Dec-2007 07:02
To access an object member with an illegal character in the name, use this syntax:

$obj->{'illegal-property:name()'}

This is particularly relevant with the dynamically-generated classes used by, for instance, database objects and the SoapClient class.
pascal dot poncet at netconsult dot com 13-Oct-2005 07:21
Subject: using "sql_calc_found_rows" in a MySQL query while exploiting result in a PHP db class object.

Hello,

There is a nice function in MySQL that allows to know how many records would have been returned if no "where" clause were set : SQL_CALC_FOUND_ROWS.

If you have create a db object to collect the returned lines, you will be a little perplex when trying to call the result of this function.

Why ?
Simply because the returned field's name is "found_rows()" and obviously it's not possible to call something like :

<?php $result->found_rows() ?>

...as it will try to acces a method, not a property !

Then, the only way to get the right result seems to be the use of a class function, like :

<?php
  $db->query("select found_rows()");
  $count=current(get_object_vars(current($db->result)));
?>

Of course, if somebody found an other way to solve it, like a special syntax (see the one used with curled arrays in a string), I'm really open to discuss.

Good luck,
Pascal
ia [AT] zoznam [DOT] sk 02-Aug-2005 10:55
as for zabmilenko's solution:
wouldn't it be better to create it this way?

<?php
// The base class for all db classes
class DB {
 protected $connectId;
}

// Class for MySQL, which extends base class
class MySQL extends DB {
 function connect () {
  $this->connectId = mysql_connect (...);
 }
}

// Class for PostgreSQL, which extends base class
class pgSQL extends DB {
 function connect () {
  $this->connectId = pg_connect (...);
 }
}

// and then call constructor like this:
$dbName = "MySQL";
$db = new $dbName ( ... );
// ... which creates an object of class MySQL
?>
zabmilenko at hotmail dot com 27-Jun-2005 12:08
((PHP5))

I wanted to dynamically choose an extender for a class.  This took awhile of playing with it but I came up with a solution.  Note that I can't verify how safe it is, but it appears to work for me.  Perhaps someone else can shed light on the details:

<?php

class A { var $value = "Class A\n"; }
class B { var $value = "Class B\n"; }

// Uncomment which extender you want.  You can use variables as well.
// define('__EXTENDER__', 'A');
   define('__EXTENDER__', 'B');

// Use eval to create a wrapper class.
eval('class EXTENDER extends '. __EXTENDER__ . ' { }');

class C extends EXTENDER
{
  function __construct()
  {
     echo $this->value;
  }
}

$t = new C;

?>

Outputs:   Class B

Practical application:  I have a database abstraction system that has individual classes for mysql, pgsql, et al.  I want to be able to create a global db class that extends one of the individual db classes depending on the application configuration.

I know that there are probably much better ways of doing this but I haven't reached that level when it comes to classes.
cjones 03-Mar-2005 01:27
If anyone is interested in looking for a way to dynamically load existing objects into a class, here is what I found very useful.

//---------------------------------------------------------
// Dynamically load External Objects into a class

  function objRef ( &$obj ) {
    eval("\$this->obj_".get_class($obj)." = \$obj;");
  }
//---------------------------------------------------------
// Reference by using: $this->obj_[object Name]->[var|f{}]

Example:

class date {  function date ( ) { $this->date = "March 3rd"; } }
class time {  function time ( ) { $this->time = "12:30pm"; } }

class show {
    function objRef ( &$obj ){
        eval("\$this->obj_".get_class($obj)." = \$obj;");
    }
   function test ( $var ){
       echo "$var".$this->obj_date->date." @ ".$this->obj_time->time;
   }
}

$date = new date;
$time = new time;
$show = new show;
    $show->objRef($date);
    $show->objRef($time);
    $show->test("Time Now => ");

// Output: Time Now => March 3rd @ 12:30pm

I found the prefix 'obj_' before the class name useful because it helped me to automatically identify external object references when scanning through my scripts. You can omit this if you want. Hope this helps someone.
http://sc.tri-bit.com/ StoneCypher 02-Mar-2005 10:25
to covertka at muohio dot edu and pillepop2003 at yahoo dot de:

There's a much easier solution to getting a class' name for working with a factory function.  Let's assume you're doing something like this:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {
      case 'stuff'      : return new Stuff($instancedata);
      case 'otherstuff' : return new Otherstuff($instancedata);
    }

  }

?>

Now, consider the named parameter idiom and remember that PHP uses hashes for everything; as a result make the following changes:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {

      case 'stuff'      : return array('typeis'=>'stuff',      'instance'=>new Stuff($instancedata));
      case 'otherstuff' : return array('typeis'=>'otherstuff', 'instance'=>new Otherstuff($instancedata));

    }

  }

?>

Nice 'n simple.  It seems that what the original poster wanted was something like C++ static data members; unfortunately as PHP4 has no static variables at all, there would need to be significant language change to support static-like behavior.  If you move to PHP5, the static keyword solves your problem cleanly.
covertka at muohio dot edu 02-Jan-2005 05:27
To pillepop2003 at yahoo dot de:

I have the same issue.  I have a base class that manages database tasks for a number of child classes.  One of the functions in the base class is a find() method that returns instances of the child classes.  Since find() is usually called as a static method, it needs to know the name of the child class.  As you've found, this appears to be impossible to get in an easy fashion.

The only way I've found to get the child class name is to use the debug_traceback() function.  This requires me to have a find() method in every child class, but it does work.

Here's an example:

<?php
  require_once("Application.php");

  class parentClass {
    function find() {
      $className = NULL;
      foreach (debug_backtrace() as $bt) {
        if ($bt['function'] == __FUNCTION__) {
          $className = $bt['class'];
        }
      }

      // here should be some code to find the proper id, let's assume it was id 1
      $id = 1;
      return new $className($id);
    }
  }

  class foo extends parentClass {
    function __construct($id) {
      $this->id = id;
    }

    function find() {
      return parent::find();
    }
  }

  class bar extends parentClass {
    function __construct($id) {
      $this->id = id;
    }

    function find() {
      return parent::find();
    }
  }

  $a = foo::find();
  printf("Type for \$a: %s<br/>\n", get_class($a));
  $b = bar::find();
  printf("Type for \$b: %s<br/>\n", get_class($b));
?>
iparanoid at gmx dot de 04-Aug-2004 11:17
To pillepop2003 at yahoo dot de:

It seems to me if there really is no nice way to get the class name in an un-instanciated class, there is a workaround in PHP5 though using static/class variables.

Example:

<?php

class myFoo
{
    static $__ClassName = __CLASS__;

    static function getClassName()
    {
        return myFoo::$__ClassName;
    }
};

class myFooExtended extends myFoo
{
    function __construct()
    {
        myFooExtended::$__ClassName = __CLASS__;
    };
};

?>

However, you'll need to have at least instanciated an object of the class myFooExtended before calling getClassName or introduce some other initialization (the class variable will need to be set at some point to __CLASS__ in the sub-class).
greg at doutromundo dot com 05-Jul-2004 07:58
As programmers, you're probably more organized than me, but, I do try and maintain some order in my classes and codes and separate them in "packages" as in java.
This helped me keep them organized but caused havok when trying to use them, so what I did was to create a class that handles the loading of classes (which I instanciate in all pages) along with my error handling class all bundled up. This way, I can load my classes with a command similar to
$baseClass->loadClass("package","className"[,"constructor"]);

the function responsible for this has some checking to see if they are loaded and stuff like that...

function loadClass($packageName,$className,$constructor=""){
  // if you dont have a constructor declare any function inside
  // the class
  if ($constructor==""){
    $constructor=$className;
  }
  if(!is_callable(array($className,$constructor))){
    if (defined("CLASS_DIR")){
      $pkg = CLASS_DIR.$packageName."/";
        if (is_dir($pkg)){
          // we have a directory with the package name
          $cls = $pkg.$className.".class.php";
          if(is_file($cls)){
            // we have a file
            include_once($cls);
          }else{
            die("Class <b>$className</b> could not be found in package <b>$packageName</b> , please check your instalation");
          }
        }else{
          die("Package <b>$packageName</b> could not be found, please check your instalation");
        }
      }
    }
}

Just remember to define CLASS_DIR as the physical path for the directories where you packages are...

Hope this comes in handy...

Here's an example of a diretory strucutre...
/var/www/classes/   <- this would be CLASS_DIR
in there I have:
package1/
     name.class.php
     name2.class.php
....

The loadClass would look like: loadClass("package1","name");

Cute and easy
ettinger at consultant dot com 18-Jun-2004 04:59
Re: Looking for an uninstantiated class

# Loads data from a table into a class object
class LFPDataFactory extends LFPObject {
        var $object;
        var $class;
        var $table;
        function LFPDataFactory($args) {
                $this->unpackArgs($args); // assigns locals from $args
                if (in_array(strtolower($this->class), get_declared_classes())) {
                        $this->object = new $this->class;
                        // assemble the columns in the table...
                        // select their values and put them in our new object...
                } else { trigger_error("Class ".$this->class." not found", E_USER_ERROR); }
        }
}
$r = new LFPDataFactory("class=LFPLayout,table=layout");
$new_obj = $r->object; // this is a LFPLayout object.
print_r($new_obj);

This class looks to see if the class exists, then instantiates it -- a declared class is not the same as an instantiated class. As long as LFPLayout exists somewhere in the scripts, get_declared_classes() will find it. Remember strtolower on compare, however.

Why would I do this? Because I have my class layouts the same as their respective tables; the factory then selects the data (making sure that the variables match) and plugs in the data. (I've left out the actual code to do the selection/insertion).
HOC 28-May-2004 09:40
to pillepop2003

Why do u want to know the classname of an non-existant object?

The only possible explanation for this question seems to me u want to know the class before u instantiate the object. Well, this is of no use since u always instantiate a class of ur choice.

When the class is instantiated into an object u can find the class of the object by means of get_class(). This is all u need. In case of inheritance u can use get_class($this) to get the class of the instantiated object. Now u can differentiate according to which class the object belongs to.

e.g.:

<?php
class A{
   function A(){
      $class_of_this = get_class($this);
      echo 'Object is an instance of class '.$class_of_this.' which is the ';
      if(strcmp($class_of_this,'A')==0)
         echo 'parent-class';
      else if(strcmp($class_of_this,'B')==0)
         echo 'child-class';
      echo ".\n";
   }
}

class B extends A{
   function B(){
      $this->A();
   }
}

$object1 = new A();
$object2 = new B();
?>

When u run this code-snippet the output will be:

Object is an instance of class A which is the parent-class.
Object is an instance of class B which is the child-class.
ar at 5mm de 28-Aug-2003 07:59
I missed some kind of function to dynamicly override or extend an Object:

-----------------------------------------
function &extendObj(&$obj, $code) {
    static $num = 0;

    $classname = get_class($obj);
    $newclass = $classname.$num;

    eval('class '.$newclass.' extends '.$classname.' { '.$code.' }');

    $newobj = new $newclass();

    $vars = get_class_vars($classname);
    foreach($vars AS $key=>$value) {
        $newobj->$key = &$obj->$key;
    }

    return $newobj;
}
-----------------------------------------

This creates a new class which extends the old one by the given code parameter, instanciates it and copy all vars from the old obj to the new one.

-----------------------------------------
class testA {
    var $prop = 'a';

    function funcA($val) {
        $this->prop = $val;
    }

    function value() {
        return $this->prop;
    }
}

$obj = new testA();

$newobj = &extendObj(&$obj, 'function addX() { $this->prop .= "x"; }');

$newobj->funcA('abc');
$newobj->addX();
echo $newobj->value();
-----------------------------------------

Results in 'abcx'. You can use the function multiple times and also with class variables. Be carefull, even if $newobj is just a copy of $obj, $obj->value() will return 'abcx', too, because of the & operator: $newobj->$key = &$obj->$key;
zidsu at hotmail dot com 08-Jul-2003 05:24
FYI: if you want to split your class into manageble chunks, what means different files for you, you can put you functoins into includes, and make include() have a return value. Like this:

class Some_class {
  var $value = 3;
  function add_value ($input_param) {
    return include ("path/some_file.php");
  }
}

And your included file:

$input_param += $this->value;
return $input_param;

Then your function call will be:

$instance = new Some_class ();
$instance->add_value (3);

And this will return
6
hopefully :P

Keep in mind though, that the scope in the included file will be identical to the scope the function 'add_value' has.
And if you want to return the outcome, you should also have a return statement made in your include as well.
asommer*at*as-media.com 20-Sep-2002 02:52
Something I found out just now that comes in very handy for my current project:

it is possible to have a class override itself in any method ( including the constructor ) like this:

class a {

..function ha ( ) {
....if ( $some_expr ) {
......$this = new b;
......return $this->ha ( );
....}
....return $something;
..}

}

in this case assuming that class b is already defined and also has the method ha ( )

note that the code after the statement to override itself is still executed but now applies to the new class

i did not find any information about this behaviour anywhere, so i have no clue wether this is supposed to be like this and if it might change... but it opens a few possibilities in flexible scripting!!
einhverfr at not-this-host dot hotmail dot com 14-Sep-2002 12:35
You may find it helpful in complex projects to have namespaces for your classes, and arrange these in a hierarchical manner.   A simple way to do this is to use the filesystem to order your hierarchies and then define a function like this:

function use_namespace($namespace){

require_once("namespaces/$namespace.obj.php");

}

(lack of indentation due to HTML UI for this page)
This requires that all your object libraries end in .obj.php (which I use) but you can modfy it to suit your needs.  To call it you could, for exmaple call:

use_namespace("example");
or if foo is part of example you can call:
use_namespace("example/foo");
justin at quadmyre dot com 19-Aug-2002 09:38
If you want to be able to call an instance of a class from within another class, all you need to do is store a reference to the external class as a property of the local class (can use the constructor to pass this to the class), then call the external method like this:

$this->classref->memberfunction($vars);

or if the double '->' is too freaky for you, how about:

$ref=&$this->classref;
$ref->memberfunction($vars);

This is handy if you write something like a general SQL class that you want member functions in other classes to be able to use, but want to keep namespaces separate. Hope that helps someone.

Justin

Example:

<?php

class class1 {
    function test($var) {
        $result = $var + 2;
        return $result;
    }
}

class class2{
    var $ref_to_class=''; # to be pointer to other class

    function class1(&$ref){ #constructor
        $this->ref_to_class=$ref; #save ref to other class as property of this class
    }

    function test2($var){
        $val = $this->ref_to_class->test($var); #call other class using ref
        return $val;
    }
}

$obj1=new class1;
# obj1 is instantiated.
$obj2=new class2($obj1);
# pass ref to obj1 when instantiating obj2

$var=5;
$result=obj2->test2($var);
# call method in obj2, which calls method in obj1
echo ($result);

?>
gateschris at yahoo dot com 08-Mar-2001 01:59
[Editor's note: If you are trying to do overriding, then you can just interrogate (perhaps in the method itself) about what class (get_class()) the object belongs to, or if it is a subclass of a particular root class.

You can alway refer to the parent overriden method, see the "Classes and Objects" page of the manual and comments/editor's notes therein.]

There is no function to determine if a member belongs to a base class or current class eg:

<?php
class foo {
 function foo () { }
 function a () { }
}

class bar extends foo {
 function bar () { }
 function a () { }
}

lala = new Bar();
?>
------------------
how do we find programmatically if member a now belongs to class Bar or Foo.


Intenta cargar una clase sin definir

  • « Funciones de Clases/Objetos
  • class_alias »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Intenta cargar una clase sin definir

__autoload

(PHP 5, PHP 7)

__autoload — Intenta cargar una clase sin definir

Advertencia

Esta característica ha sido declarada OBSOLETA a partir de PHP 7.2.0. Su uso está totalmente desaconsejado.

Descripción

__autoload ( string $class ) : void

Puede definir esta función para habilitar la carga de clases.

Parámetros

class

Nombre de la clase a cargar

Valores devueltos

No devuelve ningún valor.

Ver también

  • spl_autoload_register() - Registrar las funciones dadas como implementación de __autoload()

User Contributed Notes

sham dot hrm at gmail dot com 14-Mar-2021 06:18
We you create an object of the class and If the PHP engine doesn't find the class file included in the script then __autoload() magic method will automatically trigger.

You can implement it as given below example:

<?PHP
function __autoload($ClassName)
{
    include($ClassName.".php");
}
$obj = new Base;
?>
ohcc at 163 dot com 29-Nov-2017 05:51
In PHP 7.2, this code will trigger a "
Deprecated: __autoload() is deprecated, use spl_autoload_register() instead in path\to\file.php on line *" error although the spl_autoload_register function really really exists.
<?php
    if(!function_exists('spl_autoload_register')){
        function __autoload($class){
            // blah blah blah
        }
    }
?>
dagirovdjamal at gmail dot com 02-Aug-2017 09:13
Simple autoload :

function __autoload($class_name){
            require 'class/' . $class_name . '.php';
}
Jose G 04-Dec-2014 08:29
You should use include() or require() inside __autoload()
instead of include_once() or require_once().

If you reach __autoload(), then you know the file with the class definition has not been loaded yet.

include() and require() are more efficient than include_once() and require_once().
romi 29-Jun-2014 11:16
<?php
    if(!function_exists('classAutoLoader')){
        function classAutoLoader($class){
            $class=strtolower($class);
            $classFile=$_SERVER['DOCUMENT_ROOT'].'/include/class/'.$class.'.class.php';
            if(is_file($classFile)&&!class_exists($class)) include $classFile;
        }//You have to give the class name and not the class's path for the first parameter in the class_exists()
    }
    spl_autoload_register('classAutoLoader');
?>
Ben 26-Mar-2014 05:56
Guys, this document ( i mean __autoload() ) not mentioned one special situation: if you both use __autoload() and spl_autoload_register(), the __autoload() function will never to be called. Although spl_autoload_register() documentation explained why, i decide to wrote this in case some one get confused and waste all day to figure out why.

Here is some code to verify above:

<?php
function __autoload($class) {
}

function my_loader() {
}

function your_loader() {
}

var_dump ( spl_autoload_functions () );
echo '<br/>';

spl_autoload_register ( 'my_loader' );
spl_autoload_register ( 'your_loader' );

var_dump ( spl_autoload_functions () );
ohcc at 163 dot com 08-Dec-2013 07:12
It is highly recommended not to use the __autoload() function any more. Now the spl_autoload_register() function is what you should consider.Sorry for the mistake in line 6 of my previous note. And below is the corrected PHP code.
<?php
    if(!function_exists('classAutoLoader')){
        function classAutoLoader($class){
            $class=strtolower($class);
            $classFile=$_SERVER['DOCUMENT_ROOT'].'/include/class/'.$class.'.class.php';
            if(is_file($classFile)&&!class_exists($class)) include $classFile;
        }
    }
    spl_autoload_register('classAutoLoader');
?>
ohcc at 163 dot com 07-Dec-2013 06:28
It is highly recommended not to use the __autoload() function any more. Now the spl_autoload_register() function is what you should consider.
<?php
    if(!function_exists('classAutoLoader')){
        function classAutoLoader($class){
            $class=strtolower($class);
            $classFile=$_SERVER['DOCUMENT_ROOT'].'/include/class/'.$class.'.class.php';
            if(is_file($classFile)&&!class_exists($classFile)) include $classFile;
        }
    }
    spl_autoload_register('classAutoLoader');
?>
eragroove at gmail dot com 10-Jul-2013 05:48
If you can keep file name and class name as same, it will be good programming practice. It helps to __autoload function to load file without checking any condition.

function __autoload($class){
  require_once( $class.".php");
}
wojciech.fornal@gmail,com 07-Jun-2013 11:56
keyboardSmasher

You may or may not be right as the file name doesn't necessarily have to reflect a class name it contains (but it's usually considered a good practice). It isn't always a straightforward mapping (look at some PHP frameworks and autoload implementations).

File myBar.php may contain the class:

class Bar {
}

or it even contain the class:

class Foo {
}

Best regards
keyboardSmasher 16-Apr-2013 07:45
qeremy, your code is incorrect.

<?php
include_once("./myClass.php");
include_once("./myFoo.php");
include_once("./myBar.php");

$obj = new myClass();
$foo = new Foo();
$bar = new Bar();
?>

<?php
$foo = new Foo();
$bar = new Bar();
?>

should be:

<?php
$foo = new myFoo();
$bar = new myBar();
?>
qeremy 08-Mar-2012 03:01
Even I have never been using this function, just a simple example in order to explain it;

./myClass.php
<?php
class myClass {
    public function __construct() {
        echo "myClass init'ed successfuly!!!";
    }
}
?>

./index.php
<?php
// we've writen this code where we need
function __autoload($classname) {
    $filename = "./". $classname .".php";
    include_once($filename);
}

// we've called a class ***
$obj = new myClass();
?>

*** At this line, our "./myClass.php" will be included! This is the magic that we're wondering... And you get this result "myClass init'ed successfuly!!!".

So, if you call a class that named as myClass then a file will be included myClass.php if it exists (if not you get an include error normally). If you call Foo, Foo.php will be included, and so on...

And you don't need some code like this anymore;

<?php
include_once("./myClass.php");
include_once("./myFoo.php");
include_once("./myBar.php");

$obj = new myClass();
$foo = new Foo();
$bar = new Bar();
?>

Your class files will be included "automatically" when you call (init) them without these functions: "include, include_once, require, require_once".


Crea un alias para una clase

  • « __autoload
  • class_exists »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Crea un alias para una clase

class_alias

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

class_alias — Crea un alias para una clase

Descripción

class_alias ( string $original , string $alias , bool $autoload = true ) : bool

Crea un alias dado por alias basado en la clase original definida por el usuario. La clase apodada es exactamente la misma que la clase original.

Parámetros

original

La clase original.

alias

El nombre del alias para la clase.

autoload

Si se realiza la autocarga si la clase original no se encuentra.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de class_alias()

<?php

class foo { }

class_alias('foo', 'bar');

$a = new foo;
$b = new bar;

// los objetos son los mismos
var_dump($a == $b, $a === $b);
var_dump($a instanceof $b);

// las clases son las mismas
var_dump($a instanceof foo);
var_dump($a instanceof bar);

var_dump($b instanceof foo);
var_dump($b instanceof bar);

?>

El resultado del ejemplo sería:

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

Ver también

  • get_parent_class() - Recupera el nombre de la clase padre de un objeto o clase
  • is_subclass_of() - Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa

User Contributed Notes

Anonymous 16-Oct-2020 06:48
Check is alias:
<?php
/**
 * @param string $class Class name
 * @return bool
 */
function is_alias(string $class): bool
{
    return $class !== (new ReflectionClass($class))->name;
}
?>
Get class aliases:
<?php
/**
 * @param string $class Class name
 * @param bool $throw Throw exception at error?
 * @return string[]|null Aliases or null at error in silent mode
 * @throws InvalidArgumentException Class not exists or it's alias
 */
function get_class_aliases(string $class, bool $throw = false): ?array
{
    /**
     * @var array An array of defined classes: keys - classes, values - aliases
     */
    static $classes = [];
    // check: class exists
    if (! class_exists($class, true)) {
        if ($throw) {
            throw new InvalidArgumentException('Class ' . $class . ' not exists');
        }
        return null;
    }
    // refresh list
    $newClasses = array_diff(get_declared_classes(), array_keys($classes));
    if ($newClasses) {
        $abc = range('a', 'z');
        foreach ($newClasses as $newClass) {
            // fast check first char: class_alias() convert alias to lower case
            if (in_array($newClass[0], $abc, true)) {
                $realClass = (new ReflectionClass($newClass))->getName();
                $classes[$newClass] = $newClass !== $realClass ? $realClass : null;
            } else {
                $classes[$newClass] = null;
            }
        }
        unset($abc, $newClasses);
    }
    // check: is alias?
    if (! empty($classes[$class])) {
        if ($throw) {
            throw new InvalidArgumentException($class . ' is alias for class ' . $classes[$class]);
        }
        return null;
    }
    // find aliases
    return array_keys($classes, $class, true);
}
?>
Usage:
<?php
class Foo {}
class_alias('Foo', 'Bar');
class_alias('Bar', 'Baz');
$aliases = get_class_aliases('Foo', true); // ['bar', 'baz']
?>
info at ensostudio dot ru 03-Oct-2020 07:30
Note: this function set alias for user classes, you can't use something like this
<?php
class_alias('ArrayObject', 'ArrObj');
?>
elliseproduction at gmail dot com 29-Apr-2020 12:09
You can add a alias inside a class :

<?php

class foo{

    function __construct(){

        echo('yes!');

    }
}

class bar {

    function __construct(){

        class_alias('foo', 'fooAlias');

    }

    function test(){

        new fooAlias;

    }

}

$bar=new bar;

$bar->test(); // yes!
Hayley Watson 12-Jun-2018 01:55
The alias really is an alias for the existing class. It's not a new class of any kind - whether by inheritance or otherwise; it doesn't just look and behave exactly like the existing class; it really is the same class.

<?php

class foo
{
    public static $count = 0;
}

class_alias('foo', 'bar');

bar::$count++;

echo foo::$count; // Output: 1

echo get_class(new Bar); // Output: foo
?>
Note in the last line there that aliases are just as case-insensitive as "genuine" class names.
sofe2038 at gmail dot com 07-Jan-2017 04:06
Doesn't work with coupled classes when used along with autoloading.

For example, in these classes where each class is autoloaded in a separate class file:

Foo.php:

<?php
interface Foo{
  public function fx(Bar $bar);
}
?>

Bar2.php:

<?php
class Bar2 implements Foo{
  public function fx(Bar2 $bar){
    // some implementation code here
  }
}
?>

Bar.php:

<?php
class_alias("Bar2", "Bar");
?>

When used with an autoloader like this:

<?php
spl_autoload_register(function($class){
  require($class . ".php");
});
new Bar;
?>

Results in fatal error:

    Declaration of Bar2::fx(Bar2 $bar) must be compatible with Foo::fx(Bar $bar) in ~/Bar2.php on line 2
sofe2038 at gmail dot com 07-Jan-2017 04:06
Doesn't work with coupled classes when used along with autoloading.

For example, in these classes where each class is autoloaded in a separate class file:

Foo.php:

<?php
interface Foo{
  public function fx(Bar $bar);
}
?>

Bar2.php:

<?php
class Bar2 implements Foo{
  public function fx(Bar2 $bar){
    // some implementation code here
  }
}
?>

Bar.php:

<?php
class_alias("Bar2", "Bar");
?>

When used with an autoloader like this:

<?php
spl_autoload_register(function($class){
  require($class . ".php");
});
new Bar;
?>

Results in fatal error:

    Declaration of Bar2::fx(Bar2 $bar) must be compatible with Foo::fx(Bar $bar) in ~/Bar2.php on line 2
robsonvnasc at gmail dot com 22-Sep-2016 03:30
It also works with Traits!

<?php
trait Foo {}
class_alias("Foo","Bar");
echo trait_exists("Bar") ? 'yes' : 'no';
?>
//yes
stanislav dot eckert at vizson dot de 14-Sep-2015 07:00
class_alias() creates aliases only for user defined classes, not for classes supplied by PHP (PHP will show the warning "First argument of class_alias() must be a name of user defined class"). To create aliases for every kind of classes, use namespaces:

<?php

// Does not work
class_alias("ZipArchive", "myZip");

// Creates class alias "myZip" of class "ZipArchive"
use \ZipArchive as myZip;

?>
petar dot karan dot pk at gmail dot com 06-Feb-2014 02:19
If you need the same function in PHP version < 5.3 you can use this

<?php
function class_alias($original,$alias) {
    $newclass = create_function('','class '.$alias.' extends '.$original.' {}');
    $newclass();
}
?>
mweierophinney at gmail dot com 06-Mar-2013 02:05
class_alias() gives you the ability to do conditional imports.

Whereas the following will not work:

<?php
namespace Component;

if (version_compare(PHP_VERSION, '5.4.0', 'gte')) {
    use My\ArrayObject;
} else {
    use ArrayObject;
}

class Container extends ArrayObject
{
}
?>

the following, using class_alias, will:

<?php
namespace Component;

if (version_compare(PHP_VERSION, '5.4.0', 'lt')) {
    class_alias('My\ArrayObject', 'Component\ArrayObject');
} else {
    class_alias('ArrayObject', 'Component\ArrayObject');
}

class Container extends ArrayObject
{
}
?>

The semantics are slightly different (I'm now indicating that Container extends from an ArrayObject implementation in the same namespace), but the overall idea is the same: conditional imports.
sergey dot karavay at gmail dot com 25-Feb-2013 11:08
At first, you might wonder that:
<?php class A {}; class_alias('A', 'B'); ?>

is equivalent to:
<?php class A {}; class B extends A {}; ?>

class_alias is NOT equivalent to class extending! Private methods/properties are unseen in child classes, but in alias classes they are.
Anonymous 12-Feb-2013 05:42
Like class_alias but for functions:

<?php
function function_alias ($original, $alias) {

  $args = func_get_args();
  assert('count($args) == 2', 'function_alias() require exactly two arguments');
  assert('is_string($original) && is_string($alias)', 'function_alias() require string arguments');

  // valid function name - http://php.net/manual/en/functions.user-defined.php
  assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][\\\\\\\\a-zA-Z0-9_\x7f-\xff]*$/\', $original) > 0',
    "'$original' is not a valid function name");
  assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][\\\\\\\\a-zA-Z0-9_\x7f-\xff]*$/\', $alias) > 0',
    "'$alias' is not a valid function name");

  $aliasNamespace = substr($alias, 0, strrpos($alias, '\\') !== false ? strrpos($alias, '\\') : 0);
  $aliasName = substr($alias, strrpos($alias, '\\') !== false ? strrpos($alias, '\\') + 1 : 0);
  $serializedOriginal = var_export($original, true);

  eval("
    namespace $aliasNamespace {
      function $aliasName () {
        return call_user_func_array($serializedOriginal, func_get_args());
      }
    }
  ");

}

?>

Until hopefully function_alias is added to php...
adam at adamhahn dot com 06-Sep-2011 12:13
Something to note,

If the $original class has not yet been defined or loaded, the auto loader will be invoked in order to try and load it.

If the class for which you are trying to create an alias does not exist, or can not be loaded with the auto loader, you will generate a PHP Warning.
programmer-comfreek at hotmail dot com 15-Aug-2011 09:38
If you defined the class 'original' in a namespace, you will have to specify the namespace(s), too:
<?php
namespace ns1\ns2\ns3;

class A {}

class_alias('ns1\ns2\ns3\A', 'B');
/* or if you want B to exist in ns1\ns2\ns3 */
class_alias('ns1\ns2\ns3\A', 'ns1\ns2\ns3\B');
?>
nicolas dot grekas+php at gmail dot com 31-Dec-2010 01:09
At first, you might wonder that:
<?php class A {}; class_alias('A', 'B'); ?>

is equivalent to:
<?php class A {}; class B extends A {}; ?>

BUT when derivation creates a new class name - that means, you can then instantiate a new kind of objects - aliasing is just what it says: a synonym, so objects instantiated with the aliased name are of the exact same kind of objects instantiated with the non-aliased name.

See this code for example:
<?php
class A {};
class B1 extends A {};
class_alias('A', 'B2');

$b1 = new B1; echo get_class($b1); // prints B1
$b2 = new B2; echo get_class($b2); // prints A !
?>
nicolas dot grekas+php at gmail dot com 30-Dec-2010 02:41
class_alias also works for interfaces!

<?php
interface foo {}
class_alias('foo', 'bar');
echo interface_exists('bar') ? 'yes!' : 'no'; // prints yes!
?>


Verifica si la clase ha sido definida

  • « class_alias
  • get_called_class »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Verifica si la clase ha sido definida

class_exists

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

class_exists — Verifica si la clase ha sido definida

Descripción

class_exists ( string $class_name , bool $autoload = true ) : bool

Esta función verifica si la clase dada ha sido definida o no.

Parámetros

class_name

El nombre de la clase. El nombre es coincidido de manera insensible a mayúsculas y minúsculas.

autoload

Indica si ha de llamarse __autoload o no de forma predeterminada.

Valores devueltos

Devuelve true si class_name es una clase definida, false de lo contrario.

Historial de cambios

Versión | Descripción
5.0.2 | Ya no devuelve true para interfaces definidas. En ese caso se debe usar interface_exists().

Ejemplos

Ejemplo #1 Ejemplo de class_exists()

<?php
// Verificar que la clase exista antes de usarla
if (class_exists('MiClase')) {
    $mi_clase = new MiClase();
}

?>

Ejemplo #2 Ejemplo del parámetro autoload

<?php
function __autoload($clase)
{
    include($clase . '.php');

    // Verificar si la sentencia include declaró la clase
    if (!class_exists($clase, false)) {
        trigger_error("No es posible cargar la clase: $clase", E_USER_WARNING);
    }
}

if (class_exists('MiClase')) {
    $mi_clase = new MiClase();
}

?>

Ver también

  • function_exists() - Devuelve true si la función dada ha sido definida
  • interface_exists() - Comprueba si una interfaz ha sido definida
  • get_declared_classes() - Devuelve una matriz con los nombres de las clases definidas

User Contributed Notes

info at ensostudio dot ru 16-Sep-2020 06:54
Note: class_exists() check only classes!
<?php
interface DemoInterface {};
var_dump(class_exists('DemoInterface')); // false
trait DemoTrait {};
var_dump(class_exists('DemoTrait')); // false
class DemoClass {};
var_dump(class_exists('DemoClass')); // true
?>

Common function:
<?php
/**
  * Checks if the class/trait/interface has been defined.
  *
  * @param string $name The case-insensitive name of class/trait/interface
  * @param bool $autoload Whether to call spl_autoload()
  * @return bool
  */
function structure_exists(string $name, bool $autoload = true): bool
{
       return class_exists($name, $autoload)
              || interface_exists($name, $autoload)
              || trait_exists($name, $autoload);
}
?>
rn at alpha9marketing dot com 06-Apr-2014 05:55
Beware: class_exists is case-INsensitive, as is class instantiation.

php > var_dump(class_exists("DomNode"));
bool(true)
php > var_dump(class_exists("DOMNode"));
bool(true)
php > var_dump(class_exists("DOMNodE"));
bool(true)
php > $x = new DOMNOdE();
php > var_dump(get_class($x));
string(7) "DOMNode"

(tested with PHP 5.5.10 on Linux)

This can cause some headaches in correlating class names to file names, especially on a case-sensitive file system.
spam at wikicms dot org 09-Dec-2013 02:43
Hi guys!
Be careful  and don't forget about second boolean argument $autoload (TRUE by default) when check exists class after spl_autoload_register. Propose short example
file second.php
<?php
class Second {}
?>
file index.php
<?php
class First
{
    function first($class, $bool) {
        spl_autoload_register( function($class) {
            require strtolower($class) . '.php';
        });
        echo class_exists($class, $bool)?'Exist!!!!':'Not exist!';
    }
}

new First($class = 'Second', $bool = true); //Exist!!!!
new First($class = 'Second', $bool = false); //Not exist!
?>
Because __autoload executing much earlier than boolean returned, imho..
giunta dot gaetano at gmail dot com 31-Oct-2013 05:28
If you are using aliasing to import namespaced classes, take care that class_exists will not work using the short, aliased class name - apparently whenever a class name is used as string, only the full-namespace version can be used

use a\namespaced\classname as coolclass;

class_exists( 'coolclass' ) => false
toocoolone at gmail dot com 14-Feb-2012 06:47
I'm running PHP 5.3.4 on Windows 7 and had some difficulty autoloading classes using class_exists(). In my case, when I checked for the class and it didn't exist, class_exists automatically threw a system Exception. I was also throwing my own exception resulting in an uncaught exception.

<?php
/**
 * Set my include path here
 */
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
/**
 * Assuming I have my own custom exception handler (MyException) let's
 * try to see if a file exists.
 */
try {
    if( ! file_exists( 'myfile.php' ) ) {
        throw new MyException('Doh!');
    }
    include( 'myfile.php' );
}
catch( MyException $e ) {
    echo $e->getMessage();
}
/**
 * The above code either includes myfile.php or throws the new MyException
 * as expected. No problem right? The same should be true of class_exists(),
 * right? So then...
 */
$classname = 'NonExistentClass';
try {
    if( ! class_exists( $classname ) ) {
        throw new MyException('Double Doh!');
    }
    $var = new $classname();
}
catch( MyException $e ) {
    echo $e->getMessage();
}
/**
* Should throw a new instance of MyException. But instead I get an
* uncaught LogicException blah blah blah for the default Exception
* class AND MyException. I only catch MyException so we've got on
* uncaught resulting in the dreaded LogicException error.
*/
?>

By registering an additional autoload handler function that did nothing, I was able to stop throwing the extra Exception and only throw my own.

<?php
/**
 * Set my include path here
 */
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
spl_autoload_register( 'myAutoLoad' ); // Add these two and no worries...
function myAutoLoad() {}
/**
 * By registering the additional custom autoload function that does nothing
 * class_exists() returns only boolean and does NOT throw an uncaught Exception
 */
?>

Found this buried in some search results. I don't remember the page URL but if it would have been here it might have saved me some time!
Klaus 28-Apr-2010 04:21
If you recursively load several classes inside an autoload function (or mix manual loading and autoloading), be aware that class_exists() (as well as get_declared_classes()) does not know about classes previously loaded during the *current* autoload invocation.

Apparently, the internal list of declared classes is only updated after the autoload function is completed.
azrael dot com at gmail dot com 11-Dec-2008 04:14
If spl_autoload_register() had been called, then function will try autoload class if it does not exists.

Use instead
<?php
in_array($class_name, get_declared_classes());
?>
richard at richard-sumilang dot com 27-Mar-2008 12:56
[ >= PHP 5.3]

If you are checking if a class exists that is in a specific namespace then you have to pass in the full path to the class:

echo (class_exists("com::richardsumilang::common::MyClass")) ? "Yes" : "No";
anonymous at somewhere dot tld 17-Jul-2003 12:20
If you have a directory of classes you want to create. (Modules in my instance)... you can do it like that

<?php
if (is_dir($this->MODULE_PATH) && $dh = opendir($this->MODULE_PATH)) {
   while (($file = readdir($dh)) !== false) {
      if (preg_match("/(Mod[a-zA-Z0-9]+).php/", $file, $matches)>0) {
         // include and create the class
         require_once($this->MODULE_PATH."/".$file);
         $modules[] = new $matches[1]();
      }
   }
} else {
   exit;
}
?>

//---
Here the rule is that all modules are on the form
ModModulename.php and that the class has the same name as the file.
The $modules array has all the classes initialized after this code


El nombre de la clase enlazada estáticamente en tiempo de ejecución ("Late State Binding")

  • « class_exists
  • get_class_methods »
  • PHP Manual
  • Funciones de Clases/Objetos
  • El nombre de la clase enlazada estáticamente en tiempo de ejecución ("Late State Binding")

get_called_class

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

get_called_class — El nombre de la clase enlazada estáticamente en tiempo de ejecución ("Late State Binding")

Descripción

get_called_class ( ) : string

Obtiene el nombre de la clase desde la que se llama al método estático.

Valores devueltos

Devuelve el nombre de la clase. Devuelve false si la llamada se hizo desde fuera de la clase.

Ejemplos

Ejemplo #1 Usar get_called_class()

<?php

class foo {
    static public function prueba() {
        var_dump(get_called_class());
    }
}

class bar extends foo {
}

foo::prueba();
bar::prueba();

?>

El resultado del ejemplo sería:

string(3) "foo"
string(3) "bar"

Ver también

  • get_parent_class() - Recupera el nombre de la clase padre de un objeto o clase
  • get_class() - Devuelve el nombre de la clase de un objeto
  • is_subclass_of() - Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa

User Contributed Notes

amcolin at 126 dot com 24-Mar-2020 07:08
namespace root;
class Factor {
    protected static $instance = null;

    private function __construct() {

    }

    public static function getInstance() {
        if (!self::$instance) {
            $name           = get_called_class();
            self::$instance = new $name();
        }

        return self::$instance;
    }
}

namespace admin\test;

use root\Factor;

class Single extends Factor {
    public function abc() {
        return 'abc';
    }
}

namespace index;

use admin\test\Single;

class Index {
    public function get() {
        return Single::getInstance();
    }
}

$index = new Index();
var_dump($index->get());

The result is:

object(admin\test\Single)#2 (0) {
}
fantomx1 at gmail dot com 12-Sep-2017 03:57
When calling dynamic method statically in php 5.6 (under 7) it allows it, but it doesnt work, it incorrectly evaluates class that called our subject class, therefore containing method must be static.
Safak Ozpinar 24-Sep-2014 07:00
As of PHP 5.5 you can also use "static::class" to get the name of the called class.

<?php
class Bar {
    public static function test() {
        var_dump(static::class);
    }
}

class Foo extends Bar {

}

Foo::test();
Bar::test();
?>

Output:

string(3) "Foo"
string(3) "Bar"
luc at s dot illi dot be 05-Feb-2013 03:09
get_called_class() in closure-scopes:

<?PHP
    ABSTRACT CLASS Base
    {
        protected static $stub = ['baz'];

        //final public function boot()
        static public function boot()
        {
            print __METHOD__.'-> '.get_called_class().PHP_EOL;

            array_walk(static::$stub, function()
            {
                print __METHOD__.'-> '.get_called_class().PHP_EOL;
            });
        }

        public function __construct()
        {
            self::boot();
            print __METHOD__.'-> '.get_called_class().PHP_EOL;

            array_walk(static::$stub, function()
            {
                print __METHOD__.'-> '.get_called_class().PHP_EOL;
            });
        }
    }

    CLASS Sub EXTENDS Base
    {
    }

    // static boot
        Base::boot(); print PHP_EOL;
            // Base::boot        -> Base
            // Base::{closure}    -> Base

        Sub::boot(); print PHP_EOL;
            // Base::boot        -> Sub
            // Base::{closure}    -> Base

        new sub;
            // Base::boot        -> Sub
            // Base::{closure}    -> Base
            // Base->__construct    -> Sub
            // Base->{closure}    -> Sub

    // instance boot
        new sub;
            // Base->boot        -> Sub
            // Base->{closure}    -> Sub
            // Base->__construct    -> Sub
            // Base->{closure}    -> Sub
?>
uebele 06-Apr-2011 09:14
SEE: http://php.net/manual/en/language.oop5.late-static-bindings.php

I think it is worth mentioning on this page, that many uses of the value returned by get_called_function() could be handled with the new use of the old keyword static, as in
<?php
static::$foo;
?>

versus
<?php
$that=get_called_class();
$that::$foo;
?>

I had been using $that:: as my conventional replacement for self:: until my googling landed me the url above.  I have replaced all uses of $that with static with success both as
<?php
static::$foo; //and...
new static();
?>

Since static:: is listed with the limitation: "Another difference is that static:: can only refer to static properties." one may still need to use a $that:: to call static functions; though I have not yet needed this semantic.
Abhi Beckert 28-Oct-2009 08:41
Beware that this does not behave as expected if your method is not declared as static! For example:

<?php

class foo {
  static public function test() {
    var_dump(get_called_class());
  }

  public function testTwo() {
    var_dump(get_called_class());
  }
}

class bar extends foo {
}

class abc {
  function test() {
    foo::test();
    bar::test();
  }

  function testTwo() {
    foo::testTwo();
    bar::testTwo();
  }
}

echo "basic\n";
foo::test();
bar::test();

echo "basic without static declaration\n";
foo::testTwo();
bar::testTwo();

echo "in a class\n";
$abc = new abc();
$abc->test();

echo "in a class without static declaration\n";
$abc->testTwo();

?>

The result is:

basic
string 'foo'
string 'bar'

basic without static declaration
string 'foo'
string 'bar'

in a class
string 'foo'
string 'bar'

in a class without static declaration
string 'abc'
string 'abc'
php at itronic dot at 07-Aug-2009 06:53
If you call a static getInstance() function to create a instance of a class from another class, this function have to be static, if it is not static the original name of the caller class and not of the current class get returned.

example:

<?php

class a {
  function getXName() {
     return x::getClassName();
  }
  function getXStaticName() {
     return x::getStaticClassName();
  }

}

class b extends a {
}

class x {
  public function getClassName() {
    return get_called_class();
  }
  public static function getStaticClassName() {
    return get_called_class();
  }
}

$a = new a();

$b = new b();

echo $a->getXName(); // will return "a"
echo $b->getXName(); // will return "b"

echo $a->getXStaticName(); // will return "x"
echo $b->getXStaticName(); // will return "x"

?>
a dot cudbard-bell at sussex dot ac dot uk 21-Feb-2009 10:03
Here's a simple way of getting the inheritance tree of a class, no matter which class the function was actually defined in. Will work as a static function method too.

<?php
class A {
    public function get_class_tree(){
        $cur_class = get_called_class();
        do {
            echo $cur_class;
        }
        while($cur_class = get_parent_class($cur_class));
    }
}

class B {

}

class C {

}

$foo = new C();
$foo->get_class_tree();

?>

CBA
danbettles at yahoo dot co dot uk 08-Oct-2008 12:00
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using get_called_class.

<?php

abstract class Singleton {

    protected function __construct() {
    }

    final public static function getInstance() {
        static $aoInstance = array();

        $calledClassName = get_called_class();

        if (! isset ($aoInstance[$calledClassName])) {
            $aoInstance[$calledClassName] = new $calledClassName();
        }

        return $aoInstance[$calledClassName];
    }

    final private function __clone() {
    }
}

class DatabaseConnection extends Singleton {

    protected $connection;

    protected function __construct() {
        // @todo Connect to the database
    }

    public function __destruct() {
        // @todo Drop the connection to the database
    }
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn = DatabaseConnection::getInstance();  // Returns single instance
?>


Obtiene los nombres de los métodos de una clase

  • « get_called_class
  • get_class_vars »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Obtiene los nombres de los métodos de una clase

get_class_methods

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

get_class_methods — Obtiene los nombres de los métodos de una clase

Descripción

get_class_methods ( mixed $class_name ) : array

Obtiene los nombres de los métodos de una clase.

Parámetros

class_name

El nombre de la clase o una instancia de objeto

Valores devueltos

Devuelve un array con los nombres de los métodos definidos para la clase especificada por class_name. Es caso de error devuelve null.

Ejemplos

Ejemplo #1 Ejemplo de get_class_methods()

<?php

class miclase {
    // constructor
    function __construct()
    {
        return(true);
    }

    // método 1
    function mifunc1()
    {
        return(true);
    }

    // método 2
    function mifunc2()
    {
        return(true);
    }
}

$métodos_clase = get_class_methods('miclase');
// o
$métodos_clase = get_class_methods(new miclase());

foreach ($métodos_clase as $nombre_método) {
    echo "$nombre_método\n";
}

?>

El resultado del ejemplo sería:

miclase
mifunc1
mifunc2

Ver también

  • get_class() - Devuelve el nombre de la clase de un objeto
  • get_class_vars() - Obtener las propiedades predeterminadas de una clase
  • get_object_vars() - Obtiene las propiedades del objeto dado

User Contributed Notes

iarias at loyalia dot es 21-Feb-2018 12:19
If you only need the methods declared by the class, and not the parent classes ones, you can do something like:

$declared_methods = array_diff(get_class_methods($class), get_class_methods(get_parent_class($class)));
polarglow06 at gmail dot com 18-Nov-2015 06:09
I have created a very simple test runner using this function

function get_bar($text) {
    $bar = "";
    for($i=1; $i<=strlen($text); $i++) {
        $bar .= "=";
    }
    return $bar;
}
class Tester {
    function __construct() {
        $this->run_tests();
    }
    // run the tests
    function run_tests() {
        print("Tester by Minhajul Anwar \n");
        $class = get_class($this);
        $test_methods = preg_grep('/^test/', get_class_methods($this));
        foreach($test_methods as $method) {
            $start_rep = "test: $class::$method";
            $bar = get_bar($start_rep);
            print("\n$start_rep\n$bar\n");
            $this->$method();
            print("\n");
        }
    }
}

now you just need to write your test class with tegst methods prefixed by 'test', and then just instantiate object of that test class of your, all those tests methods will get run automatically
The drawback is: your test methods must not accept any arguments

an example:
require '../autoload.php';
register_autoload_paths(realpath('./'));

class Test_Test extends Tester {
    function test_something() {
        print("method got executed");
    }
    function testAnotherThing() {
    print("another test method");
    }
}

$Test = new Test_Test();
fschmengler at sgh-it dot eu 08-Jan-2010 04:40
It should be noted that the returned methods are dependant on the current scope. See this example:

<?php
class C
{
    private function privateMethod()
    {

    }
    public function publicMethod()
    {

    }
    public function __construct()
    {
        echo '$this:';
        var_dump(get_class_methods($this));
        echo 'C (inside class):';
        var_dump(get_class_methods('C'));
    }
}
$c = new C;
echo '$c:';
var_dump(get_class_methods($c));
echo 'C (outside class):';
var_dump(get_class_methods('C'));
?>

Output:

$this:
array
  0 => string 'privateMethod' (length=13)
  1 => string 'publicMethod' (length=12)
  2 => string '__construct' (length=11)

C (inside class):
array
  0 => string 'privateMethod' (length=13)
  1 => string 'publicMethod' (length=12)
  2 => string '__construct' (length=11)

$c:
array
  0 => string 'publicMethod' (length=12)
  1 => string '__construct' (length=11)

C (outside class):
array
  0 => string 'publicMethod' (length=12)
  1 => string '__construct' (length=11)
php at stock-consulting dot com 06-Feb-2007 02:40
Note that this function will answer both class AND instance methods ("class methods" are called "static" in PHP). Sort of a little "trap" for people who have in-depth experience with the OO terminology :-)
BoD 15-Mar-2006 07:09
!Concerning PHP5 Only!

If you want to get all methods/functions from a class you can do this with the get_class_methods function.
<?php
    $arrMethodNames = get_class_methods ( $ClassNameOrObject);
?>
However the drawback on this function in PHP5 is that you will NOT receive protected and private methods of a class/object if you are calling the method from another class/object context.

If you want to receive all methods of a given Class in another Class you should use the PHP5 Reflection API. The following source allows to retrieve all methods from a derived class in its (abstract) Base Class.

In the example you need to call the base constructor from the derived classes constructor in order to let the base class know the name of the derived class. Use the "__CLASS__" definition for passing the classname of current class to its base class.

<?php

    // Base Class - Abstract
    abstract class A {

        // Array of ReflectionMethod Objects
        // is being set upon instanciation
        // derived Classes don't need to know about this array
        private $arrMethods;

        // Constructor which MUST be called from derived Class Constructor
        protected function __construct ( $strDerivedClassName ) {
            $oRefl = new ReflectionClass ( $strDerivedClassName );
            if ( is_object($oRefl) ) {
                $this->arrMethods = $oRefl->getMethods();
            }
        }

        // Some abstract function
        abstract protected function D ();

        // Some private function
        private function E() {
        }

        // method to print all class/object methods
        // must be callable from derived classes
        // can be protected if only for internal class use
        public function PrintAllMethods () {
            foreach ( $this->arrMethods as $curReflectionMethod ) {
                echo $curReflectionMethod->getName()."<br>";
            }
        }
    }

    // Derived Class
    class B extends A {

        // Constructor for this class
        // MUST call Base Constructor
        public function __construct () {
            // Call Base Constructor
            parent::__construct(__CLASS__);
        }

        // Some public function
        public function A () {
        }

        // some protected function
        protected function B () {
        }

        // some private function
        private function C() {
        }

        // some abstract method from base class implemented
        protected function D () {
        }
    }

    // Create new B Object
    $b = new B();
    // Print all Methods of this Object/Class
    $b->PrintAllMethods();
?>

In this example output will be:

__construct
A
B
C
D
E
PrintAllMethods

As you can see these are all methods from class B and also all methods from Class A respectivly in order of their declaration. Note that only one method "__construct" and only one method "D" are being shown. This is due to overloading (__construct) and implementing (D) in PHP.

In this example any further method-handling methods should be implemented in the base class as these will be available in derived classes as well. Just make sure that you use the right access specifiers for these additional methods ( private, protected, public )

BoD
jazepstein at greenash dot net dot au 16-Oct-2005 06:37
In PHP4, this function converts its return values to lowercase; but in PHP5, it leaves the return values in their original case. This can cause serious problems when trying to write code that dynamically calls a class method, and that works in both PHP4 and PHP5. This code snippet shows one way of achieving compatibility with both versions:

<?php
// Example variables - these would be dynamic in a real application.
$className = 'SomeClass';
$methodName= 'someMethod';
$args = array('arg1', 'arg2');

// Use array_map() and strtolower() to make all values returned by get_class_methods() lowercase. PHP4 does this anyway - now it will happen regardless of the PHP version being used.
$classMethods = array_map(strtolower, get_class_methods($className));

// in_array() can only handle being given an array.
if (!$classMethods) {
  $classMethods = array();
}

if (in_array(strtolower($methodName), $classMethods)) {
  // call some method
  return call_user_func_array(array($className, $methodName), $args);
}
?>
Oli Filth 11-Apr-2005 08:21
As an extension to onesimus's code below for finding inherited methods, in PHP 5 you can use the Reflection API to find which of these are overriden.

e.g.

<?php
function get_overriden_methods($class)
{
    $rClass = new ReflectionClass($class);
    $array = NULL;

    foreach ($rClass->getMethods() as $rMethod)
    {
        try
        {
            // attempt to find method in parent class
            new ReflectionMethod($rClass->getParentClass()->getName(),
                                $rMethod->getName());
            // check whether method is explicitly defined in this class
            if ($rMethod->getDeclaringClass()->getName()
                == $rClass->getName())
            {
                // if so, then it is overriden, so add to array
                $array[] .=  $rMethod->getName();
            }
        }
        catch (exception $e)
        {    /* was not in parent class! */    }
    }

    return $array;
}
?>
kabatak 20-Feb-2005 05:11
In PHP4, if you need to get_class_methods in their original case. You can use this simple function I created.

// Note: this function assumes that you only have 1 class in 1 file

$file = "path/to/myclass.php"

function file_get_class_methods ($file)
{
    $arr = file($file);
    foreach ($arr as $line)
    {
        if (ereg ('function ([_A-Za-z0-9]+)', $line, $regs))
            $arr_methods[] = $regs[1];
    }
    return $arr_methods;
}
epowell at removethis dot visi dot com 11-Oct-2004 08:47
I've figured out how to get around my issue described below, using the Reflection API.

<?
/* Pass the name of the class, not a declared handler */
function get_public_methods($className) {
    /* Init the return array */
    $returnArray = array();

    /* Iterate through each method in the class */
    foreach (get_class_methods($className) as $method) {

        /* Get a reflection object for the class method */
        $reflect = new ReflectionMethod($className, $method);

        /* For private, use isPrivate().  For protected, use isProtected() */
        /* See the Reflection API documentation for more definitions */
        if($reflect->isPublic()) {
            /* The method is one we're looking for, push it onto the return array */
            array_push($returnArray,$method);
        }
    }

    /* return the array to the caller */
    return $returnArray;
}
?>
onesimus at cox dot net 19-Jun-2004 02:32
This function will return only the methods for the object you indicate. It will strip out the inherited methods.

function get_this_class_methods($class){
    $array1 = get_class_methods($class);
    if($parent_class = get_parent_class($class)){
        $array2 = get_class_methods($parent_class);
        $array3 = array_diff($array1, $array2);
    }else{
        $array3 = $array1;
    }
    return($array3);
}
gk at proliberty dot com 01-Jun-2003 04:16
It is important to note that get_class_methods($class) returns not only methods defined by $class but also the inherited methods.

There does not appear to be any PHP function to determine which methods are inherited and which are defined explicitly by a class.
aldo at cerca dot com 21-Apr-2002 10:18
If you use "get_class_methods" to check if a Method is in a Class remember that the function return lowered name of class methods:

class classPippo
{
        function DummyFunct()
        {
                // Do nothing...
        }
}

$aClassMethods = get_class_methods(classPippo);

$sMethodName = 'DummyFunct';

// This not work...

        if (in_array($sMethodName, $aClassMethods))
        classPippo::DummyFunct();

// This work...

        if (in_array(strtolower($sMethodName), $aClassMethods))
        classPippo::DummyFunct();
matt at zevi dot net 21-Mar-2002 04:46
Win32 only:

It's probably worth noting here that you can't get the methods of an object created by the built-in 'COM' class. ie - this won't work:

$word = new COM('Word.Application');
$methods = get_class_methods(get_class($word));
print_r($methods);

Matt


Obtener las propiedades predeterminadas de una clase

  • « get_class_methods
  • get_class »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Obtener las propiedades predeterminadas de una clase

get_class_vars

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

get_class_vars — Obtener las propiedades predeterminadas de una clase

Descripción

get_class_vars ( string $class_name ) : array

Obtiene las propiedades predeterminadas de la clase dada.

Parámetros

class_name

El nombre de la clase

Valores devueltos

Devuelve una matriz asociativa de las propiedades declaradas visibles desde el ámbito actual, con su valor predeterminado. Los elementos del array resultante están en la forma nombre_variable => valor. En caso de error devuelve false.

Historial de cambios

Versión | Descripción
5.0.3 | get_class_vars() devolverá sólo las propiedades que pueden ser accedidas desde el ámbito actual.
5.0.2 | Al llamar a get_class_vars() ahora se expondrán todas las propiedades como una matriz, a diferencia del comportamiento anterior donde las propieades protected y private eran prefijadas con bytes nul.
5.0.1 | Al llamar a get_class_vars() se expondrán todas las propiedades, como cuando se convierte un objeto en una clase.

Ejemplos

Ejemplo #1 Ejemplo de get_class_vars()

<?php

class miclase {

    var $var1; // esta no tiene valor predeterminado...
    var $var2 = "xyz";
    var $var3 = 100;
    private $var4;

    // constructor
    function __construct() {
        // cambiar algunas propiedades
        $this->var1 = "foo";
        $this->var2 = "bar";
        return true;
    }

}

$mi_clase = new miclase();

$vars_clase = get_class_vars(get_class($mi_clase));

foreach ($vars_clase as $nombre => $valor) {
    echo "$nombre : $valor\n";
}

?>

El resultado del ejemplo sería:

var1 :
var2 : xyz
var3 : 100

Ejemplo #2 get_class_vars() y comportamiento de ámbito

<?php
function formato($matriz)
{
    return implode('|', array_keys($matriz)) . "\r\n";
}

class TestCase
{
    public $a    = 1;
    protected $b = 2;
    private $c   = 3;

    public static function expose()
    {
        echo formato(get_class_vars(__CLASS__));
    }
}

TestCase::expose();
echo formato(get_class_vars('TestCase'));
?>

El resultado del ejemplo sería:

// 5.0.0
a| * b| TestCase c
a| * b| TestCase c

// 5.0.1 - 5.0.2
a|b|c
a|b|c

// 5.0.3 +
a|b|c
a

Ver también

  • get_class_methods() - Obtiene los nombres de los métodos de una clase
  • get_object_vars() - Obtiene las propiedades del objeto dado

User Contributed Notes

flobee 16-Nov-2015 12:43
<?php
class someClass {
    public function toArray() {
        $records = array();

        foreach( $this as $key => $value ) {
                $records[$key] = $value;
        }

        return $records;
    }

}
?>
bof at bof dot de 09-Sep-2012 07:02
I needed to get only the class static variables, leaving out instance variables.

<?php
function get_static_vars($class) {
    $result = array();
    foreach (get_class_vars($class) as $name => $default)
        if (isset($class::$$name))
            $result[$name] = $default;
    return $result;
}
?>

That function returns only the public ones. The same pattern can be used inside a class, then it returns private and protected static variables, too:

<?php
static protected function get_static_vars($class = NULL) {
    if (!isset($class)) $class = get_called_class();
    $result = array();
    foreach (get_class_vars($class) as $name => $default)
        if (isset($class::$$name))
            $result[$name] = $default;
    return $result;
}
?>
Mattias Ahlbck 14-Feb-2012 09:39
get_class_vars_assoc()
- Returns an associative array with name of (parent) class(es) as key(s) and corresponding class vars as sub-arrays. My boilerplate for some crude O/R mapping.

Note: vars re-defined in sub-classes are ignored.

<?php

class GrandClass {
    public $grandVar;
    public $in_grand_and_parent;
    public $in_grand_and_child;

    public static function load() {
        print_r(self::get_class_vars_assoc());
    }

    protected static function get_class_vars_assoc() {
        $called = get_called_class();
        //echo "called: $called \n";
        $classVars[$called] = array_keys(get_class_vars($called));

        $parent = get_parent_class($called);
        while ( $parent !== FALSE ) {
            //echo "parent: $parent \n";
            $classVars[$parent] = array_keys(get_class_vars($parent));
            $classVars[$called] = array_diff($classVars[$called],
                                             $classVars[$parent]);
            if ( isset($prevParentVars) ) {
                $prevParentVars = array_diff($prevParentVars,
                                             $classVars[$parent]);
            }

            $prevParentVars = &$classVars[$parent];
            $parent = get_parent_class($parent);
        }

        return $classVars;
    }
}

class ParentClass extends GrandClass {
    public $in_grand_and_parent;
    public $parentVar;
    public $in_parent_and_child;
}

class ChildClass extends ParentClass {
    public $in_grand_and_child;
    public $in_parent_and_child;
    public $childVar;
}

ChildClass::load();

?>

Array
(
    [ChildClass] => Array
        (
            [2] => childVar
        )

    [ParentClass] => Array
        (
            [1] => parentVar
            [2] => in_parent_and_child
        )

    [GrandClass] => Array
        (
            [0] => grandVar
            [1] => in_grand_and_parent
            [2] => in_grand_and_child
        )

)
ciantic 30-Jan-2012 10:06
I propse following for getting Public members, always:
<?PHP
if (!function_exists("get_public_class_vars")) {
    function get_public_class_vars($class) {
        return get_class_vars($class);
    }
}
if (!function_exists("get_public_object_vars")) {
    function get_public_object_vars($object) {
        return get_object_vars($object);
    }
}
?>

This is to mitigate the problem and a feature that get_object_vars($this) returns private members. Running it simply outside the scope will get the public.

Iterating public members only and their defaults are enormously useful in e.g. in serialization classes such as options where each public member is an serializable that is saved and loaded.
pBakhuis at Gmail dot com 07-Oct-2011 03:08
If you need the variables before the class is included this function does not seem to work.
Use a reflection class to get around this.
http://www.php.net/reflectionclass
ken at verango dot com 04-Oct-2010 04:50
All 3 of get_object_vars, get_class_vars and reflection getDefaultProperties will reveal the name of the array.  For serialization I recommend:

<?php
$cName = get_class($this);
$varTemplate= get_class_vars($cName)
foreach ($varTemplate as $name => $defaultVal) {
  $vars[$name] = $this->$name; // gets actual val.
}
?>

No scan the $vars and create serialization string how you wish.

This protects against erroneous prior deserializing in maintaining the integrity of the class template and ignoring unintended object properties.
ianitsky at gmail dot com 10-Nov-2009 11:53
If you need get the child protected/private vars ignoring the parent vars, use like this:

<?php
class childClass extends parentClass {
    private $login;
    private $password;

    public function __set($key, $val) {
        if ($key == 'password')
            $this->$key = md5($val);
        else
            $this->$key = $val;
    }
}
class parentClass {
    public $name;
    public $email;

    function __construct() {
        $reflection = new ReflectionClass($this);
        $vars = array_keys($reflection->getdefaultProperties());
        $reflection = new ReflectionClass(__CLASS__);
        $parent_vars = array_keys($reflection->getdefaultProperties());

        $my_child_vars = array();
        foreach ($vars as $key) {
            if (!in_array($key, $parent_vars)) {
                $my_child_vars[] = $key;
            }
        }

        print_r($my_child_vars);
    }
}

$child_class = new childClass();
?>
harmor 20-Dec-2008 03:53
So I wanted to get a list of the public parameters in a child class using a static function pre-5.3.0 (< 5.3.0).  In 5.3.0+ you would use the new 'static' like you would 'self' to get the late binding.

<?php
class childClass extends parentClass
{
    public $id;
    public $name;

    public static function getFields()
    {
        return self::_getFields(__CLASS__);
    }

}
abstract class parentClass
{
    public $idInParent;
    public $nameInParent;

    abstract public static function getFields();

    final protected static function _getFields($className)
    {
        $rtn = array();
        foreach (array_keys(get_class_vars($className)) as $var) {
            $rtn[] = $var;
        }
        return $rtn;
    }

}

var_dump(childClass::getFields());
?>

Results:
array(4) {
  [0]=>
  string(2) "id"
  [1]=>
  string(4) "name"
  [2]=>
  string(10) "idInParent"
  [3]=>
  string(12) "nameInParent"
}
artktec at art-k-tec dot com 16-Nov-2007 09:18
There seems to be be a function to get constants missing , i.e. get_class_constants() ... so here is a simple function for you all. Hopefully Zend will include this in the next round as a native php call, without using reflection.

<?php
   function GetClassConstants($sClassName) {
      $oClass = new ReflectionClass($sClassName);
      return $oClass->getConstants());
   }
?>
phpnet at stccorp dot net 15-Jun-2007 05:18
This is one of the best php functions. Look at what you can do

class Object
{
   var $updtFields;//keep track of affected values
   function Object($record="") {
       if (is_array($record))
       {
          $this->updtFields = array();
          foreach(array_keys(get_class_vars(get_class($this))) as $k)
          if (isset($record[$k]))
         {
          $this->$k = $record[$k];
          $this->updtFields[] = $k;
         }
      }
   }//end of arrayToObject

   function toDebug($nl='<br>')
   {
       foreach(array_keys(get_class_vars(get_class($this))) as $k)
       echo "$k = [" . $this->$k . "]{$nl}";
    }//end of toDebug
}

Now you can do really cool things. If you have a form like
<form action="" method="post">
  <input type="text" name="name" />
  <input type="text" name="phone" />
  <input type="submit" />
</form>

and you define your class like this
class Person extends Object{
  var $name; //same same as in the form
  var $phone;
}

when you submmit the form, you can get the data like

$person = new Person($_POST);

//everything in just one line,cool!! Also if you use pear db or adodb when you get data from the database you can do the same thing except use the $row that you get from the database. Remember to ask the result is associative mode.

This is my core Object for everthing I do and it works great.
bernd at tiggerswelt dot net 29-Jan-2007 02:52
If you assign a constant value using the self-scope by default to a variable, get_class_vars() will result in a FATAL error.

Example:

<?PHP

  class Foo {
    const Bar = "error";

    public $Foo = self::Bar;
  }

  print_r(get_class_vars("Foo"));

?>

... but using "Foo::Bar" instead "self::Bar" will work ;)
gizmobits at hotmail dot com 03-Mar-2006 07:48
I wanted a simple ToString() function that was automatic and class independent.  I wanted to dump it into any of several classes and get values quickly.  I wanted to leave it there so I could customize it for each class, so an outside function wasn't suitable.  I came up with this and thought it might be useful.  Have fun!

<?php
  function ToString () {
    $s = "";
    $s .= "<table>\n";
    $s .= "<tr><td colspan=2><hr></td></tr>\n";
    foreach (get_class_vars(get_class($this)) as $name => $value) {
      $s .= "<tr><td>$name:</td><td>" . $this->$name . "</td></tr>\n";
    }
    $s .= "<tr><td colspan=2><hr></td></tr>\n";
    $s .= "</table>\n";
    return $s;
  }

?>
php dot net at sharpdreams dot com 25-Oct-2005 06:25
Contrary to multiple comments throughout the manual, get_class_vars() performed within a class can access any public, protected, and private members.

<?php
class Foo {
   public $x;
   protected $y;
   private $z;
   public function __sleep() {
      return( get_class_vars( __CLASS__ ) );
   }
}
?>

works fine (returns x, y, & z). However, given the same class as above,

<?php
print_r( get_class_vars( "Foo" ) );
?>

will NOT return x, y, & z. Instead it will only return the public members (in our case, z).
alan_k at php dot net 21-Jan-2005 07:23
in PHP5 to get all the vars (including private etc.) use:

$reflection = new ReflectionClass($class);
$defaults = $reflection->getdefaultProperties();
rec at NOSPAM dot instantmassacre dot com 23-Jan-2003 04:23
If you want to retrieve the class vars from within the class itself, use $this.

<?php
class Foo {

    var $a;
    var $b;
    var $c;
    var $d;
    var $e;

    function GetClassVars()
    {
        return array_keys(get_class_vars(get_class($this))); // $this
    }

}

$Foo = new Foo;

$class_vars = $Foo->GetClassVars();

foreach ($class_vars as $cvar)
{
    echo $cvar . "<br />\n";
}
?>

Produces, after PHP 4.2.0, the following:

a
b
c
d
e


Devuelve el nombre de la clase de un objeto

  • « get_class_vars
  • get_declared_classes »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Devuelve el nombre de la clase de un objeto

get_class

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

get_class — Devuelve el nombre de la clase de un objeto

Descripción

get_class ( object $object = null ) : string

Obtiene el nombre de la clase del objeto dado por object.

Parámetros

object

El objeto evaluado. Este parámetro puede omitirse cuando se utiliza dentro de una clase.

Valores devueltos

Devuelve el nombre de la clase de la cual object es una instancia. Devuelve false si object no es un objeto.

Si se omite object al usarse dentro de una clase, devolverá el nombre de la clase.

Errores/Excepciones

Si se llama a la función get_class() con algo que no sea un objeto, se producirá un error de nivel E_WARNING.

Historial de cambios

Versión | Descripción
5.3.0 | El valor predeterminado de object ahora es null, por lo que pasar el valor null a object tiene el mismo resultado que no pasar ningún valor.

Ejemplos

Ejemplo #1 Usar get_class()

<?php

class foo {
    function nombre()
    {
        echo "Mi nombre es " , get_class($this) , "\n";
    }
}

// crear un objeto
$bar = new foo();

// llamada externa
echo "Su nombre es " , get_class($bar) , "\n";

// llamada interna
$bar->nombre();

?>

El resultado del ejemplo sería:

Su nombre es foo
Mi nombre es foo

Ejemplo #2 Usar get_class() en superclass

<?php

abstract class bar {
    public function __construct()
    {
        var_dump(get_class($this));
        var_dump(get_class());
    }
}

class foo extends bar {
}

new foo;

?>

El resultado del ejemplo sería:

string(3) "foo"
string(3) "bar"

Ver también

  • get_called_class() - El nombre de la clase enlazada estáticamente en tiempo de ejecución ("Late State Binding")
  • get_parent_class() - Recupera el nombre de la clase padre de un objeto o clase
  • gettype() - Obtener el tipo de una variable
  • is_subclass_of() - Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa

User Contributed Notes

kiril (AT) aternus networks 10-Oct-2017 09:03
If you want the Class Name without the Namespace or if you've got here because basename() returns a dot (.) for the FQCN (Fully Qualified Class Name), here is the solution:

<?php
// FQCN: App\Http\Controllers\CustomerReportController

substr(self::class, (int)strrpos(self::class, '\\') + 1)

// returns: CustomerReportController
?>
Hayley Watson 24-Sep-2017 11:22
Although you can call a class's static methods from an instance of the class as though they were object instance methods, it's nice to know that, since classes are represented in PHP code by their names as strings, the same thing goes for the return value of get_class():

<?php
$t->Faculty();
SomeClass::Faculty(); // $t instanceof SomeClass
"SomeClass"::Faculty();
get_class($t)::Faculty();
?>

The first is legitimate, but the last makes it clear to someone reading it that Faculty() is a static method (because the name of the method certainly doesn't).
dense 17-Dec-2016 01:33
well, if you call  get_class() on an aliased class, you will get the original class name

<?php

class Person {}

class_alias('Person', 'User');

$me = new User;

var_dump( get_class($me) ); // 'Person'

?>
XyQrTw 28-Nov-2016 10:18
To get class name without the Namespace you can use easily this trick :
<?php
namespace My\Long\Namespace;

class MyClass {

    static function getClassName() {
        return basename(__CLASS__);
       // or with get_class();
        return basename(get_class());
    }

}

echo \My\Long\Namespace\MyClass::getClassName(); // Display : MyClass
?>
RQuadling at GMail dot com 19-Dec-2014 03:09
With regard to getting the class name from a namespaced class name, then using basename() seems to do the trick quite nicely.

<?php
namespace Foo\Bar;

abstract class Baz
{
  public function report()
  {
    echo
      '__CLASS__        ', __CLASS__, ' ', basename(__CLASS__), PHP_EOL,
      'get_called_class ', get_called_class(), ' ', basename(get_called_class()), PHP_EOL;
  }
}

class Snafu extends Baz
{
}

(new Snafu)->report();
?>

produces output of ...

__CLASS__        Foo\Bar\Baz   Baz
get_called_class Foo\Bar\Snafu Snafu
jjanak at webperfection dot net 03-Oct-2014 11:06
>= 5.5

::class
fully qualified class name, instead of get_class

<?php
namespace my\library\mvc;

class Dispatcher {}

print Dispatcher::class; // FQN == my\library\mvc\Dispatcher

$disp = new Dispatcher;

print $disp::class; // parse error
Anonymous 18-Sep-2014 08:55
If you want the path to an file if you have i file structure like this

project -> system -> libs -> controller.php
project -> system -> modules -> foo -> foo.php

and foo() in foo.php extends controller() in controller.php like this

<?PHP
namespace system\modules\foo;

class foo extends \system\libs\controller {
    public function __construct() {
        parent::__construct();
    }
}
?>

and you want to know the path to foo.php in controller() this may help you

<?PHP
namespace system\libs;

class controller {
    protected function __construct() {
        $this->getChildPath();
    }
    protected function getChildPath() {
        echo dirname(get_class($this));
    }
}
?>

<?PHP
$f = new foo();  // system\modules\foo
?>
var23rav at gmail dot com 27-Aug-2014 01:52
class A
{
function __construct(){
        //parent::__construct();
        echo $this->m =  'From constructor A: '.get_class();
        echo $this->m =  'From constructor A:- argument = $this: '.get_class($this);

        echo $this->m =  'From constructor A-parent: '.get_parent_class();
        echo $this->m =  'From constructor A-parent:- argument =  $this: '.get_parent_class($this);
    }
}
class B extends A
{
function __construct(){
        parent::__construct();
        echo $this->m =  'From constructor B: '.get_class();
        echo $this->m =  'From constructor B:- argument =  $this: '.get_class($this);

        echo $this->m =  'From constructor B-parent: '.get_parent_class();
        echo $this->m =  'From constructor B-parent:- argument =  $this: '.get_parent_class($this);
    }
}
$b = new B();
//----------------output--------------------

From constructor A: A
From constructor A:- argument = $this: B
From constructor A-parent:
From constructor A-parent:- argument = $this: A
From constructor B: B
From constructor B:- argument = $this: B
From constructor B-parent: A
From constructor B-parent:- argument = $this: A

Use get_class() to get the name of class  ,it will help you get the class name, in case you extend that class with another class and want to get the name of the class to which object is instance of user get_class($object)

when you create an object of class{$b object of B} which has a super class{Class A}.
uses these code IN Super Class {A}
--------------------------------------------
to get class name B{object instance} :  get_class($this)
to get class name A{super class}  : get_class() or get_parent_class($this)
dave at shax dot com 06-Mar-2014 04:36
A lot of people in other comments wanting to get the classname without the namespace. Some weird suggestions of code to do that - not what I would've written! So wanted to add my own way.

<?php
function get_class_name($classname)
{
    if ($pos = strrpos($classname, '\\')) return substr($classname, $pos + 1);
    return $pos;
}
?>

Also did some quick benchmarking, and strrpos() was the fastest too. Micro-optimisations = macro optimisations!

39.0954 ms - preg_match()
28.6305 ms - explode() + end()
20.3314 ms - strrpos()

(For reference, here's the debug code used. c() is a benchmarking function that runs each closure run 10,000 times.)

<?php
c(
    function($class = 'a\b\C') {
        if (preg_match('/\\\\([\w]+)$/', $class, $matches)) return $matches[1];
        return $class;
    },
    function($class = 'a\b\C') {
        $bits = explode('\\', $class);
        return end($bits);
    },
    function($class = 'a\b\C') {
        if ($pos = strrpos($class, '\\')) return substr($class, $pos + 1);
        return $pos;
    }
);
?>
Nanhe Kumar 20-Dec-2013 12:14
<?php
class Parent{
}
class Child extends Parent{
}
$c = new Child();
echo get_class($c) //Child
?>
<?php
class Parent{
  public function getClass(){
     echo get_class();
  }
}
class Child extends Parent{
}
$obj = new Child();
$obj->getClass(); //outputs Parent
?>
<?php
class Parent{
  public function getClass(){
     echo get_class($this);
  }
}
class Child extends Parent{
}
$obj = new Child();
$obj->getClass(); // Parent
?>
emmanuel dot antico at gmail dot com 10-May-2013 07:35
/**
 * Obtains an object class name without namespaces
 */
function get_real_class($obj) {
    $classname = get_class($obj);

    if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
        $classname = $matches[1];
    }

    return $classname;
}
macnimble at gmail dot com 17-Mar-2012 07:24
Need a quick way to parse the name of a class when it's namespaced? Try this:

<?php
namespace Engine;
function parse_classname ($name)
{
  return array(
    'namespace' => array_slice(explode('\\', $name), 0, -1),
    'classname' => join('', array_slice(explode('\\', $name), -1)),
  );
}
final class Kernel
{
  final public function __construct ()
  {
    echo '<pre>', print_r(parse_classname(__CLASS__),1), '</pre>';
    // Or this for a one-line method to get just the classname:
    // echo join('', array_slice(explode('\\', __CLASS__), -1));
  }
}
new Kernel();
?>

Outputs:
Array
(
    [namespace] => Array
        (
            [0] => Engine
        )

    [classname] => Kernel
)
mail dot temc at gmail dot com 06-Dec-2011 02:51
People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance.

Here's a good example that should fix that for ever:

<?php

class Foo {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

class Bar extends Foo {

}

class Quux extends Bar {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

$foo = new Foo();
$bar = new Bar();
$quux = new Quux();

echo "\n--doMethod--\n";

$foo->doMethod();
$bar->doMethod();
$quux->doMethod();

echo "\n--doGetClassThis--\n";

$foo->doGetClassThis();
$bar->doGetClassThis();
$quux->doGetClassThis();

echo "\n--doGetClass--\n";

$foo->doGetClass();
$bar->doGetClass();
$quux->doGetClass();

?>

OUTPUT:

--doMethod--
Foo::doMethod
Foo::doMethod
Quux::doMethod

--doGetClassThis--
Foo::doThat
Bar::doThat
Quux::doThat

--doGetClass--
Foo::doThat
Foo::doThat
Quux::doThat
ozana at omdesign dot cz 28-Nov-2011 07:53
Simplest way how to gets Class without namespace

<?php
namespace a\b\c\d\e\f;

class Foo {

  public function __toString() {
    $class = explode('\\', __CLASS__);
    return end($class);
  }
}

echo new Foo(); // prints Foo
?>
Michael Richey 31-Oct-2011 12:01
Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it's not available.  Unlike other methods listed here, I chose not to prevent use of __construct() or __clone().

<?php
abstract class Singleton {
    protected static $m_pInstance;
    final public static function getInstance(){
        $class = static::getClass();
        if(!isset(static::$m_pInstance[$class])) {
            static::$m_pInstance[$class] = new $class;
        }
        return static::$m_pInstance[$class];
    }
    final public static function getClass(){
        return get_called_class();
    }
}

// I don't remember where I found this, but this is to allow php < 5.3 to use this method.
if (!function_exists('get_called_class')) {
    function get_called_class($bt = false, $l = 1) {
        if (!$bt)
            $bt = debug_backtrace();
        if (!isset($bt[$l]))
            throw new Exception("Cannot find called class -> stack level too deep.");
        if (!isset($bt[$l]['type'])) {
            throw new Exception('type not set');
        }
        else
            switch ($bt[$l]['type']) {
                case '::':
                    $lines = file($bt[$l]['file']);
                    $i = 0;
                    $callerLine = '';
                    do {
                        $i++;
                        $callerLine = $lines[$bt[$l]['line'] - $i] . $callerLine;
                    } while (stripos($callerLine, $bt[$l]['function']) === false);
                    preg_match('/([a-zA-Z0-9\_]+)::' . $bt[$l]['function'] . '/', $callerLine, $matches);
                    if (!isset($matches[1])) {
                        // must be an edge case.
                        throw new Exception("Could not find caller class: originating method call is obscured.");
                    }
                    switch ($matches[1]) {
                        case 'self':
                        case 'parent':
                            return get_called_class($bt, $l + 1);
                        default:
                            return $matches[1];
                    }
                // won't get here.
                case '->': switch ($bt[$l]['function']) {
                        case '__get':
                            // edge case -> get class of calling object
                            if (!is_object($bt[$l]['object']))
                                throw new Exception("Edge case fail. __get called on non object.");
                            return get_class($bt[$l]['object']);
                        default: return $bt[$l]['class'];
                    }

                default: throw new Exception("Unknown backtrace method type");
            }
    }
}

class B extends Singleton {
}

class C extends Singleton {
}

$b = B::getInstance();
echo 'class: '.get_class($b);

echo '<br />';

$c = C::getInstance();
echo echo 'class: '.get_class($c);
?>
This returns:
class: b
class: c
me at nwhiting dot com 06-Dec-2010 08:14
Method for pulling the name of a class with namespaces pre-stripped.

<?php
/**
 * Returns the name of a class using get_class with the namespaces stripped.
 * This will not work inside a class scope as get_class() a workaround for
 * that is using get_class_name(get_class());
 *
 * @param  object|string  $object  Object or Class Name to retrieve name

 * @return  string  Name of class with namespaces stripped
 */
function get_class_name($object = null)
{
    if (!is_object($object) && !is_string($object)) {
        return false;
    }

    $class = explode('\\', (is_string($object) ? $object : get_class($object)));
    return $class[count($class) - 1];
}
?>

And for everyone for Unit Test goodiness!

<?php
namespace testme\here;

class TestClass {

    public function test()
    {
       return get_class_name(get_class());
    }
}

class GetClassNameTest extends \PHPUnit_Framework_TestCase
{
    public function testGetClassName()
    {
        $class  = new TestClass();
        $std  = new \stdClass();
        $this->assertEquals('TestClass', get_class_name($class));
        $this->assertEquals('stdClass', get_class_name($std));
        $this->assertEquals('Test', get_class_name('Test'));
        $this->assertFalse(get_class_name(null));
        $this->assertFalse(get_class_name(array()));
        $this->assertEquals('TestClass', $class->test());
    }
}
?>
Aaron 18-Jun-2010 11:14
This can sometimes be used in place of get_called_class(). I used this function in a parent class to get the name of the class that extends it.
ovidiu.bute [at] gmail.com 05-Apr-2010 10:23
If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex:

namespace Shop;

<?php
class Foo
{
  public function __construct()
  {
     echo "Foo";
  }
}

//Different file

include('inc/Shop.class.php');

$test = new Shop\Foo();
echo get_class($test);//returns Shop\Foo
?>
Lanselot 11-Feb-2009 02:09
Beware if you're omitting the parameter on inherited classes.
It'll return the class name of the method where it's called.

<?php
class A {
    function foo() {
      return get_class();
    }
}
class B extends A {
   function bar() {
      return get_class();
   }
}
$instance = new B();
echo $instance->bar(); //Prints 'B';
echo $instance->foo(); //Prints 'A';
?>
danbettles at yahoo dot co dot uk 08-Oct-2008 11:56
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using the new get_called_class function.  When called in a static method, this function returns the name of the class the call was made against.

<?php

abstract class Singleton {

    protected function __construct() {
    }

    final public static function getInstance() {
        static $aoInstance = array();

        $calledClassName = get_called_class();

        if (! isset ($aoInstance[$calledClassName])) {
            $aoInstance[$calledClassName] = new $calledClassName();
        }

        return $aoInstance[$calledClassName];
    }

    final private function __clone() {
    }
}

class DatabaseConnection extends Singleton {

    protected $connection;

    protected function __construct() {
        // @todo Connect to the database
    }

    public function __destruct() {
        // @todo Drop the connection to the database
    }
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn = DatabaseConnection::getInstance();  // Returns single instance
?>

Full write-up in Oct 2008: http://danbettles.blogspot.com
Edward 21-Aug-2008 03:26
The code in my previous comment was not completely correct. I think this one is.

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;

    protected function __construct() {
    }

    abstract protected function init();

    /**
     * Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
     * If one does exist, then the existing instance is returned.
     */
    public static function getInstance() {
        static $instance;

        $class = self::getClass();

        if ($instance === null) {
            $instance = new $class();
            $instance->init();
        }

        return $instance;
    }

    /**
     * Returns the classname of the child class extending this class
     *
     * @return string The class name
     */
    private static function getClass() {
        $implementing_class = static::$__CLASS__;
        $original_class = __CLASS__;

        if ($implementing_class === $original_class) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }

        return $implementing_class;
    }
}
?>
Edward 20-Aug-2008 05:42
With Late Static Bindings, available as of PHP 5.3.0, it is now possible to implement an abstract Singleton class with minimal overhead in the child classes. Late static bindings are explained here: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

In short, it introduces a new 'static::' keyword, that is evaluated at runtime. In the following code I use it to determine the classname of the child Singleton class.

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;
    protected static $instance;

    protected function __construct() {
        static::$instance = $this;
        $this->init();
    }

    abstract protected function init();

    protected function getInstance() {
        $class = static::getClass();

        if (static::$instance===null) {
            static::$instance = new $class;
        }

        return static::$instance;
    }

    private static function getClass() {
        if (static::$__CLASS__ == __CLASS__) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }

        return static::$__CLASS__;
    }
}
?>

An example Singleton class can then be implemented as follows:

<?
class A extends Singleton {
    protected static $__CLASS__ = __CLASS__; // Provide this in each singleton class.

    protected function someFunction() {
        $instance = static::getInstance();
        // ...
    }
}
?>

Hope this helps you save some time :)
dave dot zap at gmail dot com 29-Apr-2008 09:13
Take care using the backtrace method to find the calling class of a static method, you should step backward through the array and find a match for your getInstance() function. In backtrace the class name you want is not always the last item in the array.

I will not post the whole singleton class here, but have made the following modification to Frederik Krautwald's method (found below)

<?php
$bt = debug_backtrace();
// this method is count($bt)-1) by Frederik will fall over when calling getInstance from within an include file.
//$class = $bt[count($bt) - 1]['class'];

for( $i=count($bt)-1 ; $i > 0 ; $i--)
{
    if($bt[$i]['function'] == 'getInstance')
    {
        $class = $bt[$i]['class'];
        break;
    }
}
?>
Anonymous 12-Apr-2008 02:01
In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not 'know' the name of the calling subclass', so I use a backtrace to determine it. I don't like hacks like this, but as long as PHP doesn't have an alternative, this is what has to be done:

public function table_name() {
        $result = null;
        if (isset($this)) { // object context
            $result = get_class($this);
        }
        else { // class context
            $result = get_class();
            $trace = debug_backtrace();
            foreach ($trace as &$frame) {
                if (!isset($frame['class'])) {
                    break;
                }
                if ($frame['class'] != $result) {
                    if (!is_subclass_of($frame['class'], $result)) {
                        break;
                    }
                    $result = $frame['class'];
                }
            }
        }
        return $result;
    }
andregs at NOSPAM dot gmail dot NOSPAM dot com 21-Feb-2008 01:17
After reading the previous comments, this is the best I've done to get the final class name of a subclass:

<?php

class Singleton
{
   private static $_instances = array();
   protected final function __construct(){}

   /**
    * @param string $classname
    * @return Singleton
    */
   protected static function getInstance()
   {
      $classname = func_get_arg(0);
      if (! isset(self::$_instances[$classname]))
      {
         self::$_instances[$classname] = new $classname();
      }
      return self::$_instances[$classname];
   }

}

class Child extends Singleton
{
   /**
    * @return Child
    */
   public static function getInstance()
   {
      return parent::getInstance(get_class());
   }
}

?>

Subclasses must override "getInstance" and cannot override "__construct".
dodgie74 at NOSPAM dot yahoo dot NOSPAM dot co dot uk 09-Sep-2007 05:40
As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the "self" keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the "self" keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:

<?php
class Base
{
    protected $m_instanceName = '';

    public static function classDisplayName()
    {
        return 'Base Class';
    }

    public function instanceDisplayName()
    {
        //here, we want "self" to refer to the actual class, which might be a derived class that inherits this method, not necessarily this base class
        return $this->m_instanceName . ' - ' . self::classDisplayName();
    }
}

class Derived extends Base
{
    public function Derived( $name )
    {
        $this->m_instanceName = $name;
    }

    public static function classDisplayName()
    {
        return 'Derived Class';
    }
}

$o = new Derived('My Instance');
echo $o->instanceDisplayName();
?>

In the above example, assuming runtime binding (where the keyword "self" refers to the actual class on which the method was invoked rather than the class in which the method is defined) would produce the output:

My Instance - Derived Class

However, assuming compile-time binding (where the keyword "self" refers to the class in which the method is defined), which is how php works, the output would be:

My Instance - Base Class

The oddity here is that "$this" is bound at runtime to the actual class of the object (obviously) but "self" is bound at compile-time, which seems counter-intuitive to me. "self" is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which "self" ought to be useful.

However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to "self" being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the "self" keyword for static methods:

<?php
class Base
{
    protected $m_instanceName = '';

    public static function classDisplayName()
    {
        return 'Base Class';
    }

    public function instanceDisplayName()
    {
        $realClass = get_class($this);
        return $this->m_instanceName . ' - ' . call_user_func(array($realClass, 'classDisplayName'));
    }
}

class Derived extends Base
{
    public function Derived( $name )
    {
        $this->m_instanceName = $name;
    }

    public static function classDisplayName()
    {
        return 'Derived Class';
    }
}

$o = new Derived('My Instance');
echo $o->instanceDisplayName();
?>

Output:
My Instance - Derived Class

I realise that some people might respond "why don't use just just the class name with ' Class' appended instead of the classDisplayName() method", which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.

Apologies if this has been mentioned before.
bramus at bram dot us 20-Aug-2007 08:40
@ Frederik :

<?
$class = $bt[count($bt) - 1]['class'];
?>

should be

<?
$class = $bt[count($bt) - 2]['class'];
?>

;-)
Frederik Krautwald 25-Jun-2007 08:13
Due to PHP 5 engine that permits to get final class in a static called function, and this is a modified version of examples published below.

<?php
abstract class Singleton {
    protected static $_instances = array();

    protected function __construct() {}

    protected static function getInstance() {
        $bt = debug_backtrace();
        $class = $bt[count($bt) - 1]['class'];
        if (!isset(self::$_instances[$class])) {
            self::$_instances[$class] = new $class();
        }
        return self::$_instances[$class];
    }
}
class A extends Singleton {
    public static function getInstance() {
        return parent::getInstance();
    }
}
class B extends Singleton {
    public static function getInstance() {
        return parent::getInstance();
    }
}
class C extends A {
    public static function getInstance() {
        return parent::getInstance();
    }
}

$a = A::getInstance();
$b = B::getInstance();
$c = C::getInstance();

echo "\$a is a " . get_class($a) . "<br />";
echo "\$b is a " . get_class($b) . "<br />";
echo "\$c is a " . get_class($c) . "<br />";
?>

I don't know about if performance would increase if debug_backtrace() is skipped and instead have getInstance() to accept a passed class retrieved by get_class() method as parameter as described in a post below.

By having set getInstance() to protected in the Singleton class, the function is required to be overridden (good OOP practice).

One thing to mention is, that there is no error checking in case $class is null or undefined, which would result in a fatal error. At the moment, though, I can't see how it could happen when the getInstance() is protected, i.e. has to be overridden in a subclass -- but with good coding practice you should always error check.
mightye at gmail dot com 23-Jun-2007 06:20
To: Bryan

In this model it is still workable if your singleton variable is actually an array.  Consider:
<?php
abstract class Singleton {
    protected final static $instances = array();

    protected __construct(){}

    protected function getInstance() {
        $class = get_real_class(); // imaginary function returning the final class name, not the class the code executes from
        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }
}
class A extends Singleton {
}
class B extends Singleton {
}

$a = A::getInstance();
$b = B::getInstance();

echo "\$a is a " . get_class($a) . "<br />";
echo "\$b is a " . get_class($b) . "<br />";
?>
This would output:
$a is a A
$b is a B

The only alternative as described elsewhere is to make getInstance() protected abstract, accept the class name as an argument, and extend this call with a public final method for every sub-class which uses get_class() in its local object scope and passes it to the superclass.

Or else create a singleton factory like this:
<?php
final class SingletonFactory {
    protected static $instances = array();

    protected getInstance($class) {
        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }
}
?>
The downside to this of course to this latter model is that the class itself doesn't get to decide if it is a singleton, the calling code gets to decide this instead, and a class that really wants or *needs* to be a singleton has no way to enforce this, not even by making its constructor protected.

Basically these design patterns, and various other meta manipulations (things which operate on the nature of the object, not on the data the object holds) could benefit greatly from knowing exactly what the final type of this object is, and not having native access to this information obligates work-arounds.
janci 30-Apr-2007 12:00
To yicheng zero-four at gmail dot com: Another, maybe better example where finding out the real class (not the class we are in) in static method should be quite usefull is the Singleton pattern.

There is currently no way how to create an abstract Singleton class that could be used just by extending it without the need to change the extended class. Consider this example:
<?php
abstract class Singleton
{
    protected static $__instance = false;

    public static function getInstance()
    {
        if (self::$__instance == false)
        {
            // This acctually is not what we want, $class will always be 'Singleton' :(
            $class = get_class();
            self::$__instance = new $class();
        }
        return self::$__instance;
    }
}

class Foo extends Singleton
{
    // ...
}

$single_foo = Foo::getInstance();
?>
This piece of code will result in a fatal error saying: Cannot instantiate abstract class Singleton in ... on line 11

The best way I figured out how to avoid this requires simple but still a change of the extended (Foo) class:
<?php
abstract class Singleton
{
    protected static $__instance = false;

    protected static function getInstance($class)
    {
        if (self::$__instance == false)
        {
            if (class_exists($class))
            {
                self::$__instance = new $class();
            }
            else
            {
                throw new Exception('Cannot instantiate undefined class [' . $class . ']', 1);
            }
        }
        return self::$__instance;
    }
}

class Foo extends Singleton
{
    // You have to overload the getInstance method in each extended class:
    public static function getInstance()
    {
        return parent::getInstance(get_class());
    }
}

$single_foo = Foo::getInstance();
?>

This is of course nothing horrible, you will propably need to change something in the extended class anyway (at least the constructor access), but still... it is just not as nice as it possibly could be ;)
yicheng zero-four at gmail dot com 18-Jan-2007 12:22
This a response to luke at liveoakinteractive dot com and davidc at php dot net.  Static methods and variables, by definition, are bound to class types not object instances.  You should not need to dynamically find out what class a static method belongs to, since the context of your code should make it quite obvious.  Your questions reveals that you probably don't quite understand OOP quite yet (it took me a while as well).

Luke, the observed behavior from your particular code snippet makes perfect sense when you think about it.  The method getclass() is defined in BooBoof, so the __CLASS__ macro would be bound to BooBoof and defined in relation to the BooBoof class.  The fact that CooCoof is a subclass of BooBoof just means that it gains a shortcut to BooBoof::getclass().  So, in effect, you are really asking (in a convoluted way): "What is the class to which belongs the method call BooBoof::getclass()?"  The correct solution (if you actually want/need to do this) is to simply implement CooCoof::getclass() { return __CLASS__; } inside of the CooCoof definition, and any childclasses that you want to mimic this behavior.  CooCoof::getclass() will have the expected behavior.
luke at liveoakinteractive dot com 06-Dec-2006 07:03
This note is a response to the earlier post by davidc at php dot net. Unfortunately, the solution posted for getting the class name from a static method does not work with inherited classes.

Observe the following:
<?php
class BooBoof {
  public static function getclass() {
    return __CLASS__;
  }

  public function retrieve_class() {
    return get_class($this);
  }
}

class CooCoof extends BooBoof {
}

echo CooCoof::getclass();
// outputs BooBoof

$coocoof = new CooCoof;
echo $coocoof->retrieve_class();
// outputs CooCoof
?>

__CLASS__ and get_class($this) do not work the same way with inherited classes. I have been thus far unable to determine a reliable way to get the actual class from a static method.
benjaminhill at gmail dot com 27-Apr-2006 10:47
More funkyness:

class Parent {
   function displayTableName() {
      echo get_class($this);
      echo get_class();
   }
}

class Child {
   function __construct() {
      $this->displayTableName();
   }
}

Will return
- Child
- Parent

So when they say "the object isn't required in PHP5" - they don't really mean it.
refrozen dot com 05-Jul-2005 03:01
philip at cornado dot com, it returns the value of the class from which it was called, rather than the instance's name... causing inheritance to result in unexpected returns
MagicalTux at FF.ST 02-Feb-2004 04:11
Note that the constant __CLASS__ is different from get_class($this) :
<?
  class test {
    function whoami() {
      echo "Hello, I'm whoami 1 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
    }
  }
  class test2 extends test {
    function whoami2() {
      echo "Hello, I'm whoami 2 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
      parent::whoami(); // call parent whoami() function
    }
  }
  $test=new test;
  $test->whoami();
  $test2=new test2;
  $test2->whoami();
  $test2->whoami2();
?>

The output is :
Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

Hello, I'm whoami 2 !
Value of __CLASS__ : test2
Value of get_class() : test2

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

In fact, __CLASS__ returns the name of the class the function is in and get_class($this) returns the name of the class which was created.


Devuelve una matriz con los nombres de las clases definidas

  • « get_class
  • get_declared_interfaces »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Devuelve una matriz con los nombres de las clases definidas

get_declared_classes

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

get_declared_classes — Devuelve una matriz con los nombres de las clases definidas

Descripción

get_declared_classes ( ) : array

Obtiene las clases declaradas.

Valores devueltos

Devuelve una matriz con los nombres de las clases declaradas en el script actual.

Nota:

Observe que, dependiendo de qué extensiones tiene compiladas o cargadas en PHP, las clases adicionales podrían no estar presentes. Esto significa que no será capaz de definir sus propias clases usando estos nombres. Hay una lista de clases predefinidas en la sección Clases Predefinidas de los apéndices.

Ejemplos

Ejemplo #1 Ejemplo de get_declared_classes()

<?php
print_r(get_declared_classes());
?>

El resultado del ejemplo sería algo similar a:

Array
(
    [0] => stdClass
    [1] => __PHP_Incomplete_Class
    [2] => Directory
)

Ver también

  • class_exists() - Verifica si la clase ha sido definida
  • get_declared_interfaces() - Devuelve un array con todas las interfaces declaradas
  • get_defined_functions() - Devuelve un array de todas las funciones definidas

User Contributed Notes

brain at code dot com 14-Feb-2014 08:53
get-declared-classes makes no sense at all, if u maybe, later for production, merge class files in one package file.

lets say: package.php
print_r(get_declared_classes());
class declaredHere { }
print_r(get_declared_classes());

so in this case, the declaredHerr class is defined at the first call of print_r();
because PHP-complier runs a hole file and declare Stuff before running the code.

But (Lovely PHP):
print_r(get_declared_classes());
if(true){
class declaredHere { }
}
print_r(get_declared_classes());
Will print the declaredHere class only in the second print_r.

Its not a Bug it a...
yarco dot wang at gmail dot com 24-Nov-2013 07:32
those above comments are too old.
now, whatever the order is, the output will be the same:

<?php
class Test1
{}

print_r(get_declared_classes());

class Test2
{}

print_r(get_declared_classes());

?>

will output the same result.
dcahh at gmx de 29-Feb-2008 09:23
This function considers only classes and subclasses. Not subsubclasses.

In fact I have code that provides an abstract class and then classes using this abstract class. Further I have subclasses to my concrete classes - which is why my subclasses are not listed within the returned array.
dexen + goofy _ pl 25-Sep-2007 11:32
Summary:
 * in PHP 5.1 class names have case preserved
 * contrary, in PHP 4.4 class names are downcased, withe exception of a few build-in ones

The get_declared_classes() funcition returns the list of names with case preserved, as of PHP 5.1 series (prolly 5.0 too, but i have no way to test it right now). Since PHP generally is caseless in regard to names of classes, this may come at a surprise. Also, this could potentially break older code asssuming downcased list.

Take extra care when  checking for existence of a class. Following example is, potentially, error prone: <?php in_array( $className, $classget_declared_classes() ) ?>

A sure-fire (while slower) way would be to iterate over the array and normalize case to, say, lower:

<?php
$exists = FALSE;
$className = strtolower( $className );
foreach ( get_declared_classes() as $c ) {
    if ( $className === strtolower( $c ) ) {
        $exists = TRUE;
        break;
    }
}?>

Optimization of the above snippet is left as a simple excercise to the reader ;)
-- dexen deVries
matt at mattsoft dot net 21-Dec-2005 02:58
classes can't be unloaded. probably not very practical to implement that in a future version. I wouldn't go out of my way to do it if I were zend. you're better off finding a workaround. it's better programming technique to find a way around having to do that anyway.

http://www.zend.com/zend/week/week223.php#Heading10
22-Mar-2005 09:16
Regarding note of 3-21:

<?php

class myclass {}

$class = 'myclass';
$instance = new $class();

?>

This function could also be used to determine the names of classes defined in a particular file by calling it before and after include. It's hardly a pointless function.
matt-php at DONT-SPAM-ME dot bitdifferent dot com 01-Nov-2004 07:41
The array returned by this function will be in the order the classes were defined / included / required and this order does not appear to change.

For example:

<?PHP

//define classone
class classone { }

//define classtwo
class classtwo { }

//This will show X classes (built-ins, extensions etc) with
//classone and classtwo as the last two elements

print_r(get_declared_classes());

//define classthree
class classthree { }

//...and four
class classfour { }

//Shows the same result as before with class three and four appended
print_r(get_declared_classes());

?>

Output:

Array
(
   [0] => stdClass
   [1] .... other defined classes....
   [10] => classone
   [11] => classtwo
 )

and...

Array
(
   [0] => stdClass
   [1] .... other defined classes....
   [10] => classone
   [11] => classtwo
   [12] => classthree
   [13] => classfour
)
Jazeps Basko 07-Feb-2004 11:52
In PHP5, you don't get declared interfaces by calling this function!!!
To get interfaces you should use get_declared_interfaces(). However, to check if an interface is already defined, you should use class_exists()! This is strange, but PHP team does not think so.
smokey 20-Mar-2003 03:06
you cannot remove them. they are "defined", which happens when the class is being loaded from the parser. you just deleted an instance of a class.


Devuelve un array con todas las interfaces declaradas

  • « get_declared_classes
  • get_declared_traits »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Devuelve un array con todas las interfaces declaradas

get_declared_interfaces

(PHP 5, PHP 7, PHP 8)

get_declared_interfaces — Devuelve un array con todas las interfaces declaradas

Descripción

get_declared_interfaces ( ) : array

Obtiene las interfaces declaradas.

Valores devueltos

Devuelve un array con los nombres de las interfaces declaradas en el script actual.

Ejemplos

Ejemplo #1 Ejemplo de get_declared_interfaces()

<?php
print_r(get_declared_interfaces());
?>

El resultado del ejemplo sería algo similar a:

Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)

Ver también

  • interface_exists() - Comprueba si una interfaz ha sido definida
  • get_declared_classes() - Devuelve una matriz con los nombres de las clases definidas
  • class_implements() - Devuelve las interfaces que son implementadas por la clase o interfaz dadas

User Contributed Notes

There are no user contributed notes for this page.


Devuelve un array de todos los traits declarados

  • « get_declared_interfaces
  • get_object_vars »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Devuelve un array de todos los traits declarados

get_declared_traits

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

get_declared_traits — Devuelve un array de todos los traits declarados

Descripción

get_declared_traits ( ) : array

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve un array con los nombres de todos los traits declarados en valores. Devuelve null en caso de error.

Ver también

  • class_uses() - Devolver los "traits" usados por la clase dada
  • trait_exists() - Comprobar si el trait existe

User Contributed Notes

@everaldofilho 14-Jul-2019 04:57
Example of use:

<?php

namespace Example;

// Declare Trait
trait FooTrait
{
}

// Declare Abstract class
abstract class FooAbstract
{
}

// Declare class
class Bar extends FooAbstract
{
    use FooTrait;
}

// Get all traits declareds
$array = get_declared_traits();

var_dump($array);
/**
 * Result:

 * array(1) {
 *  [0] =>
 *  string(23) "Example\FooTrait"
 * }
 */


Obtiene las propiedades del objeto dado

  • « get_declared_traits
  • get_parent_class »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Obtiene las propiedades del objeto dado

get_object_vars

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

get_object_vars — Obtiene las propiedades del objeto dado

Descripción

get_object_vars ( object $object ) : array

Obtiene las propiedades no estáticas accesibles del objeto dado por object según el ámbito.

Parámetros

object

Una instancia de un objeto.

Valores devueltos

Devuelve un array asociativo con las propiedades no estáticas accesibles del objeto especificado por object en el ámbito.

Historial de cambios

Versión | Descripción
5.3.0 | Esta función ahora devuelve null si object no es un objeto. Anteriormente devolvía false

Ejemplos

Ejemplo #1 Uso de get_object_vars()

<?php

class foo {
    private $a;
    public $b = 1;
    public $c;
    private $d;
    static $e;

    public function prueba() {
        var_dump(get_object_vars($this));
    }
}

$prueba = new foo;
var_dump(get_object_vars($prueba));

$prueba->prueba();

?>

El resultado del ejemplo sería:

array(2) {
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
}
array(4) {
  ["a"]=>
  NULL
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
  ["d"]=>
  NULL
}

Ver también

  • get_class_methods() - Obtiene los nombres de los métodos de una clase
  • get_class_vars() - Obtener las propiedades predeterminadas de una clase

User Contributed Notes

niemans at pbsolo dot nl 02-Jan-2021 04:47
You can use an anonymous class to return public variables from inside the class:

public function getPublicVars () {
    $me = new class {
        function getPublicVars($object) {
            return get_object_vars($object);
        }
    };
    return $me->getPublicVars($this);
}

Test script:

class Test {
    protected $protected;
    public    $public;
    private   $private;
    public function getAllVars () {
        return call_user_func('get_object_vars', $this);
    }
    public function getPublicVars () {
        $me = new class {
            function getPublicVars($object) {
                return get_object_vars($object);
            }
        };
        return $me->getPublicVars($this);
    }
}

$test = new Test();
print_r(get_object_vars($test)); // array("public" => NULL)
print_r($test->getAllVars());   // array("protected" => NULL, "public" => NULL, "private" => NULL)
print_r($test->getPublicVars()); // array("public" => NULL)
iluxaorlov at yandex dot ru 23-Sep-2020 01:58
When we use typed properties that was never set and not initialized:

<?php

class Test
{
    public string $notInitialized;
}

$test = new Test();
$vars = get_object_vars($test);
var_dump($vars); // array(0) { }

?>

But:

<?php

class Test
{
    public $notTyped;
    public string $initialized = '';
}

$test = new Test();
$vars = get_object_vars($test);
var_dump($vars); // array(2) { ["notTyped"]=> NULL ["string"]=> string(0) "" }

?>
beat 07-Nov-2014 11:39
If your object contains a reference, beware that you might get references for all object properties in the array values, thus when changing values in the array, they may change the object too (confirmed and not yet fixed PHP bug https://bugs.php.net/bug.php?id=66961 affecting all PHP versions up to at least 5.6.2 and 5.5.18 and 5.4.34).

This 10-years old comment tried reporting this: http://php.net/manual/en/function.get-object-vars.php#40515 but its exemple was incomplete. See bug report for example.
lee dot howarth dot 90 at gmail dot com 13-Apr-2014 10:48
I find this function very helpful, What i wanted to do was to get the object properties of an exception so i could sanitize them for output.

   try
   {
       throw new Exception( 'Test Exception.', 100 );
   }
   catch( Exception $e )
   {
       var_dump( ( object ) get_object_vars( ( object ) ( new ArrayObject( $e ) ) -> getarrayCopy() ) );
   }

Example return:

object(stdClass)#10 (4) { ["message"]=> string(15) "Test Exception." ["code"]=> int(100) ["file"]=> string(29) "C:\xampp\htdocs\dev\index.php" ["line"]=> int(19) }
rabatto1 at web dot de 03-Feb-2014 04:21
function to convert object (with children) to an (associative) array ... recusive

<?php

// ---------------------------------------------------------
// ----- object_to_array_recusive --- function (PHP) ------
// --------------------------------------------------------
// -- arg1:  $object  =  (PHP Object with Children)
// -- arg2:  $assoc   =  (TRUE / FALSE) - optional
// -- arg3:  $empty   =  ('' or NULL) - optional
// --------------------------------------------------------
// ----- return: Array from Object --- (associative) ------
// --------------------------------------------------------

function object_to_array_recusive ( $object, $assoc=1, $empty='' )
{
    $out_arr = array();
    $assoc = (!empty($assoc)) ? TRUE : FALSE;

    if (!empty($object)) {

        $arrObj = is_object($object) ? get_object_vars($object) : $object;

        $i=0;
        foreach ($arrObj as $key => $val) {
            $akey = ($assoc !== FALSE) ? $key : $i;
              if (is_array($val) || is_object($val)) {
                $out_arr[$key] = (empty($val)) ? $empty : object_to_array_recusive($val);
              }
              else {
                $out_arr[$key] = (empty($val)) ? $empty : (string)$val;
              }
        $i++;
        }

    }

    return $out_arr;
}

// --------------------------------------------------------
// --------------------------------------------------------

?>

Example / Usage:

a) return an associative (recusive) array from object

$new_arr1 = object_to_array_recusive($my_object);
// --- or --- object_to_array_recusive($my_object,TRUE);
// --- or --- object_to_array_recusive($my_object,1);

b) return a numeric  (recusive) array from object (set 2nd argument = FALSE)

$new_arr2 = object_to_array_recusive($my_object,FALSE);

you can pre-set the Array-Value of Empty (Sub-) Objects in 3rd argument ($empty)
// --- eg: NULL --- object_to_array_recusive($my_object,1,NULL);
oom at oscarotero dot com 09-Oct-2013 09:37
You can use call_user_func() to return public variables from inside the class:

class Test {
    protected $protected;
    public $public;
    private $private;

    public function getPublicVars () {
        return call_user_func('get_object_vars', $this);
    }
}

$test = new Test();
var_dump($test->getPublicVars()); // array("public" => NULL)
jozef at mostka dot com 03-Sep-2013 06:59
class A{
    private $priA;
    protected $proA;
    public $pubA;
}

class B extends A{
    private $priB;
    protected $proB;
    public $pubB;

    public function getVars(){
        return array_diff_key(get_object_vars($this), get_class_vars(get_parent_class($this)));
    }
}
$b = new B();
var_dump($b->getVars());

array(3) {
  ["priB"]=>
  NULL
  ["proB"]=>
  NULL
  ["pubB"]=>
  NULL
}
kuko at webperfection dot net 16-Apr-2013 11:09
get_object_vars($this)
php5.3 + it returns only public and protected; NOT private vars
@chozilla 11-Feb-2013 12:35
A simple way to call this function within an Object and to only export the *public* params would be to artificially change the scope - for example with a closure in php 5.3:

<?php
class Example
{
    public $publicSetting = 'public';
    protected $protectedSetting = 'protected';
    private $privateSetting = 'private';

    public function showEverything()
    {
        return get_object_vars($this);
    }

    public function showMyPublicsOnly()
    {
        $me = $this;
        $publics = function() use ($me) {
            return get_object_vars($me);
        };
        return $publics();
    }
}
?>
Fabien Haddadi 30-May-2012 09:42
It seems like there's no function that determines all the *static* variables of a class.

I've come out with this one as I needed it in a project:

<?php
function get_class_static_vars($object) {
     return array_diff(get_class_vars(get_class($object)), get_object_vars($object));
}
?>

It relies on an interesting property: the fact that get_object_vars only returns the non-static variables of an object.
Dionisiy 20-Apr-2012 06:21
Note that before PHP 5.3.9 numeric object variables of unserialized object are not public, and get_object_vars() won't return them:
https://bugs.php.net/bug.php?id=61774
elminster2031 at hotmail dot com 07-Jul-2010 12:30
Also note that this is recursive. For example:

<?php
class Sarah{

    private $Father;
    private $Mother;

    public function __construct(){
        $this->Father    =    NULL; //I don't know Sarah's Father
        $this->Mother    =    NULL; //I don't know Sarah's Mother
    }
}
class John_Connor{

    private $Father;
    private $Mother;

    public function __construct(){
        $this->Father    =    $this; //John went back in time and fathered himself
        $this->Mother    =    new Sarah(); //Sarah was his mom and his mate ewww
    }

    public function showParents(){
        return get_object_vars($this);
    }
}

$John    =    new John_Connor();
var_dump($John->showParents());
?>

You will see this outputs:

array(2) {
  ["Father"]=>
  object(John_Connor)#1 (2) {
    ["Father":"John_Connor":private]=>
    object(John_Connor)#1 (2) {
      ["Father":"John_Connor":private]=>
      *RECURSION*
      ["Mother":"John_Connor":private]=>
      object(Sarah)#2 (2) {
        ["Father":"Sarah":private]=>
        NULL
        ["Mother":"Sarah":private]=>
        NULL
      }
    }
    ["Mother":"John_Connor":private]=>
    object(Sarah)#2 (2) {
      ["Father":"Sarah":private]=>
      NULL
      ["Mother":"Sarah":private]=>
      NULL
    }
  }
  ["Mother"]=>
  object(Sarah)#2 (2) {
    ["Father":"Sarah":private]=>
    NULL
    ["Mother":"Sarah":private]=>
    NULL
  }
}
benny at nospam dot com 26-Dec-2009 01:31
Be aware of the fact that this is scope-sensitive. If you're calling this from an objects own method, then private and protected vars will be outputted as well. Call it from outside the object and the result will most likely be what you want to archive.
huzursuz at mailinator dot com 02-Feb-2009 08:44
better version of conv_obj, based on XML... this converts XML to an array... use it by

<?php
$result = xmlobj2arr(simplexml_load_string($xmlContent));

function xmlobj2arr($Data) {
       if (is_object($Data)) {
               foreach (get_object_vars($Data) as $key => $val) {
                       $ret[$key] = xmlobj2arr($val);
               }
               return $ret;
       } elseif (is_array($Data)) {
               foreach ($Data as $key => $val) {
                       $ret[$key] = xmlobj2arr($val);
               }
               return $ret;
       } else {
               return $Data;
       }
}
?>
jon at websandbox dot net 05-Jul-2008 09:00
If you're using the SPL ArrayObject class (or similar, or the ArrayAccess interface), you may have noticed that it's difficult to loop through an object's properties.

get_object_vars does not return the properties of an ArrayObject.  The only workaround I can see is to use get_class_vars.

<?php
$obj = new ArrayObject();
$obj->foo = "bar";
$obj[] = "1";
$obj[] = "2";
foreach($obj as $key => $value) {
 // will iterate over the array, iterating over "1" and "2", but ignoring $obj->foo
}

var_dump($obj); // dumps the array values, ignores $obj->foo

$a = get_object_vars($obj); // returns an empty array

class Fart extends ArrayObject {
    public $foo = "bar";
}

$obj = new Fart();
$a = get_object_vars($obj); // return an empty array
$a = get_class_vars(get_class($obj)); // returns array("foo"=>"bar"), Yay!

/* The above works with subclasses as well */
class Toot extends Fart {
    public $weeble = "wobble";
}

$a = get_class_vars(get_class($obj));
// returns array("weeble" => "wobble", "foo"=>"bar"), Yay again!

?>

So, to iterate over the properties of an ArrayObject, and not the array values:

<?php

$obj = new Toot(); // which is a subclass of ArrayObject
$props = get_class_vars(get_class($obj));
foreach($props as $prop => $defaultValue) {
  $value = $obj->$prop; // now you have the property name and  its value
}

?>
pardini at gmail dot com 08-May-2008 04:38
get_object_vars() has confusing behaviour when called as get_object_vars($this) or similar: since a method inside a class definition can access private vars, apparently so can get_object_vars(), so it returns private vars as well.

A simple workaround is to define a method that in itself calls get_object_vars, like:

<?php
function getPublicObjectVars($obj) {
  return get_object_vars($obj);
}

class Smth {
  private $notShown = 1;
  public $shown = 2;

  function test() {
    $vars = get_object_vars($this); // includes 'notShown'
    $vars = getPublicObjectVars($this); // only 'shown'
  }

}
?>
biga888 AT gmail 19-Nov-2007 12:48
Just thought I would pass this on.

Working with PHP 5.2.4

In Windows this works by reading the vars from the passed in object and copying them to the vars of the current object.

    public function copyMe(User $user) {
        $varArray = get_object_vars($this);
        $copyVarArray = get_object_vars($user);
        foreach ($varArray as $key=>$value) {
            $this->$key = $copyVarArray[$key];
        }
    }

This did not work in Linux, I had to add another function to return the array of vars. Calling get_array_vars on the passed in object would return an empty array.

        public function copyMe(User $user) {
        $varArray = $this->getArray();
        $copyVarArray = $user->getArray();
        foreach ($varArray as $key=>$value) {
            $this->$key = $copyVarArray[$key];
        }
    }

    public function getArray() {
        return get_object_vars($this);
    }
firemouth at gmail dot com 10-Sep-2007 06:48
This is a slight modification of the previous poster's function.  We ran into a problem using this function when we had a JS array nested inside a JS hash.

Something like this...

myHash = new Hash();
myHash[address] = new Array();

When we threw that at this function, it found the first hash as an object, and then using the previous poster's function, it did not consider the array as an "object."  Instead it gave us a std_object type and we were unable to make any use of it.

The modification we made was adding a check for is_array inside both the is_object and is_array checks when you call the function.  This checks for an array inside either an object or a nested array.

function conv_obj($Data){
    if(is_object($Data)){

        foreach(get_object_vars($Data) as $key=>$val){
            if(is_object($val) || is_array($val)){
                $ret[$key]=conv_obj($val);
            }else{
                $ret[$key]=$val;
            }
        }
        return $ret;
    }elseif(is_array($Data)){
        foreach($Data as $key=>$val){
            if(is_object($val) || is_array($val)){
                $ret[$key]=conv_obj($val);
            }else{
                $ret[$key]=$val;
            }
        }
        return $ret;
    }else{
        return $Data;
    }
}
C.H. 15-Aug-2007 06:03
function conv_obj($Data){
     if(is_object($Data)){
         foreach(get_object_vars($Data) as $key=>$val){
             if(is_object($val)){
                 $ret[$key]=conv_obj($val);
             }else{
                 $ret[$key]=$val;
             }
         }
         return $ret;
     }elseif(is_array($Data)){
         foreach($Data as $key=>$val){
             if(is_object($val)){
                 $ret[$key]=conv_obj($val);
             }else{
                 $ret[$key]=$val;
             }
         }
         return $ret;
     }else{
         return $Data;
     }
 }

Very simple function to convert any Subobject to an array.
Created it while working with Soap.
For me as an beginner with PHP, very useful :o)
thinice at gmail dot com 13-Aug-2007 10:46
To add to my previous comment - the error message should have meant same structure.

As my implementation called for cross-class comparison.
Maikel 23-May-2007 11:13
To follow the code of d11wtq (enquiries AT chriscorbyn.co.uk). I did this function to inspect all properties(public, private, protected) of object.

<?php
header("content-type: text/plain");

// Classes to test!
class OtherClass
{
    private $privateVarOtherClass = 11;
}

class MyClass extends OtherClass
{
    protected $protectedVar = "some";
    public $publicVar = "nk";
    private $privateVar = "algo";
    var $oldStyle;
}

// Dangerous function
function get_properties($obj, $values=false)
{
    $obj_dump  = print_r($obj, 1);
    $matches =  array();
    preg_match_all('/^\s+\[(\w+).*\] => (\w*)/m', $obj_dump, $matches);
    if ($values)
    {
        $output = array();
        foreach ($matches[1] as $key => $property)
        {
            $output[$property] = $matches[2][$key];
        }
        return $output;
    }
    else
    {
        return $matches[1];
    }
}

$instance = new MyClass();

echo "Properties\n";
print_r(get_properties($instance));

echo "Properties and values\n";
print_r(get_properties($instance, true));

?>

Note: remember that static properties are not visible to the object. By that not supported to them
thiago dot henrique dot mata at gmail dot com 21-Feb-2007 11:23
<?php
# How to make a function change the private attributes
# from some object without use serialize functions or
# lose the control of the changes.

/**
 * Parent Class to allow the change of privates attributes
 * Look the abstract function __setAttribute.
 *
 * @author Renan de Lima ( renandelima@gmail.com )
 * @author Thiago Mata ( thiago.henrique.mata@gmail.com )
 * @date 2007-02-21
 */
abstract class father
{
    /**
     * Receive the Aray and try to change the attribute value
     *
     * @param array $arrNewValues
     */
    public function __fromDatabase( $arrNewValues )
    {
        $arrToSet = array_intersect_key( $arrNewValues, get_object_vars( $this ) );
        foreach( $arrToSet as $strAttribute => $mixValue )
        {
            $this->__setAttribute( $strAttribute , $mixValue );
        }
    }

    /**
     * Required method to control the attributes of class
     * @param string $strAttribute
     * @param unknown $mixValue
     */
    abstract protected function __setAttribute( $strAttribute, $mixValue );

}

/**
 * Just a example of a child class using the functionality
 *
 * Note: if you don't wanna to allow the change of some attribute
 * by this method you can just make more complex the __setAttribute function.
 *
 * @author Renan de Lima ( renandelima@gmail.com )
 * @author Thiago Mata ( thiago.henrique.mata@gmail.com )
 * @date 2007-02-21
 */
class son extends father
{

    private $atr = 9;

    /**
     * This is the most simple implementation of the method.
     * This way it's allowed to the parent class change any attribute
     * @param string $strAttribute
     * @param unknown $mixValue
     */
    protected function __setAttribute( $strAttribute, $mixValue )
    {
        $this->{ $strAttribute } = $mixValue;
    }

}

$objSon = new son();
$objSon->__fromDatabase( array( 'atr' => 55 ) );
var_dump( $objSon );
?>
ananda dot putra at gmail dot com 01-Mar-2006 03:49
Hi all, I just wrote a function which dumps all the object propreties and its associations recursively into an array. Here it is..
<?php
function object_to_array($obj) {
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        foreach ($_arr as $key => $val) {
                $val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;
                $arr[$key] = $val;
        }
        return $arr;
}
?>

Example:
You have an object like this:
fruitsbasket Object
(
    [Fruits] => Array
        (
            [0] => fruits Object
                (
                    [_name] => Mango
                    [_color] => Green
                    [_weight] => 10
                )

            [1] => fruits Object
                (
                    [_name] => Apple
                    [_color] => Red
                    [_weight] => 15
                )

            [2] => fruits Object
                (
                    [_name] => Grape
                    [_color] => Purple
                    [_weight] => 5
                )

        )

    [total_weight] => 30
)

just do:
<?php
$the_array = object_to_array($the_object);
print_r($the_array);
?>

it will produce an array:
Array
(
    [Fruits] => Array
        (
            [0] => Array
                (
                    [_name] => Mango
                    [_color] => Green
                    [_weight] => 10
                )

            [1] => Array
                (
                    [_name] => Apple
                    [_color] => Red
                    [_weight] => 15
                )

            [2] => Array
                (
                    [_name] => Grape
                    [_color] => Purple
                    [_weight] => 5
                )

        )

    [total_weight] => 30
)

I wish function like this could be usefull for you all. :)
support at sascha minus diebel dot de 23-Dec-2005 02:55
Note that get_object_vars() returns the variables of the object not the class. You need to know if your class is extended from a parent class.
d11wtq (enquiries AT chriscorbyn.co.uk) 17-Nov-2005 03:40
Since there's no apparent means of obtaining all the *private* properties in an object I wrote a little function to do it.  Built in support would be much more efficient since mine uses a preg_  search to do this....

<?php

function get_private_properties($obj, $inside=false)
{
    $obj_dump  = print_r($obj, 1);
    preg_match_all('/^\s+\[(\w+):private\]/m', $obj_dump, $matches);
    if ($inside)
    {
        $output = array();
        foreach ($matches[1] as $property)
        {
            $output[$property] = $obj->$property;
            return $output;
        }
    }
    else return $matches[1];
}

?>

So if you run it with the optional second paramter missing you'll just get an array of the variable names that are private inside the class.  This is the only option if you are not inside the actual object and the object has no private properties inherited.

If you run it with the second parameter set to true you will get an associative array with the properties and their corresponding values.  I'd only advise to do that for singletons since you may get errors if there are any private properites in parents/children.
pascal dot poncet at netconsult dot com 13-Oct-2005 07:20
Subject: using "sql_calc_found_rows" in a MySQL query while exploiting result in a PHP db class object.

Hello,

There is a nice function in MySQL that allows to know how many records would have been returned if no "where" clause were set : SQL_CALC_FOUND_ROWS.

If you have create a db object to collect the returned lines, you will be a little perplex when trying to call the result of this function.

Why ?
Simply because the returned field's name is "found_rows()" and obviously it's not possible to call something like :

<?php $result->found_rows() ?>

...as it will try to acces a method, not a property !

Then, the only way to get the right result seems to be the use of a class function, like :

<?php
  $db->query("select found_rows()");
  $count=current(get_object_vars(current($db->result)));
?>

Of course, if somebody found an other way to solve it, like a special syntax (see the one used with curled arrays in a string), I'm really open to discuss.

Good luck,
Pascal
Marc 23-Aug-2005 06:08
If you want to access all properties (private, protected, public) of a class and his base class(es) from outside the object you can take a look in the code below.
You can even reffrence them.

Example:
<?php

// Dummy class to act as parent class.
class Dummy
{
    private        $d1 = 1;
    protected    $d2 = 2;
    public        $d3 = 3;
}

// The class to test on.
class Test extends Dummy
{
    private        $t1 = 11;
    protected    $t2 = 12;
    public        $t3 = 13;
}

// Instance of the test class.
$test =& new Test();

// The propertynames of the test class and his parent.
$nameD1 = "\0Dummy\0d1";    // class Dummy, private      $d1
$nameD2 = "\0*\0d2";        // class Dummy, protected $d2
$nameD3 = "d3";            // class Dummy, public    $d3

$nameT1 = "\0Test\0t1";        // class Test,  private      $t1
$nameT2 = "\0*\0t2";        // class Test,  protected $t2
$nameT3 = "t3";            // class Test,  public    $t3

// Printing all members (private, protected, public) of test class and parent.
// These are the values at construction.
print("Original object:\n");
print("\t\$d1 = ".$test->$nameD1."\n");
print("\t\$d2 = ".$test->$nameD2."\n");
print("\t\$d3 = ".$test->$nameD3."\n");
print("\t\$t1 = ".$test->$nameT1."\n");
print("\t\$t2 = ".$test->$nameT2."\n");
print("\t\$t3 = ".$test->$nameT3."\n");
print("\n");

// Create new values to use as reffrence.
$varD1 = 31;
$varD2 = 32;
$varD3 = 33;

$varT1 = 41;
$varT2 = 42;
$varT3 = 43;

// Reffrence these to the class properties.
$test->$nameD1 =& $varD1;
$test->$nameD2 =& $varD2;
$test->$nameD3 =& $varD3;

$test->$nameT1 =& $varT1;
$test->$nameT2 =& $varT2;
$test->$nameT3 =& $varT3;

// Printing all members (private, protected, public) of test class and parent.
// The values have changed by assigning reffrence to them.
print("Object Changed by reffrence (1):\n");
print("\t\$d1 = ".$test->$nameD1."\n");
print("\t\$d2 = ".$test->$nameD2."\n");
print("\t\$d3 = ".$test->$nameD3."\n");
print("\t\$t1 = ".$test->$nameT1."\n");
print("\t\$t2 = ".$test->$nameT2."\n");
print("\t\$t3 = ".$test->$nameT3."\n");
print("\n");

// Change the original values.
// This will change the class properties.
$varD1 = 61;
$varD1 = 62;
$varD1 = 63;

$varT1 = 71;
$varT1 = 72;
$varT1 = 73;

// Printing all members (private, protected, public) of test class and parent.
// The values have changed because the variables $varXX have been changed.
print("Object Changed by reffrence (2):\n");
print("\t\$d1 = ".$test->$nameD1."\n");
print("\t\$d2 = ".$test->$nameD2."\n");
print("\t\$d3 = ".$test->$nameD3."\n");
print("\t\$t1 = ".$test->$nameT1."\n");
print("\t\$t2 = ".$test->$nameT2."\n");
print("\t\$t3 = ".$test->$nameT3."\n");
print("\n");

// Printing the object using print_r() shows the changes
// have been done on the object.
print("Object Changed (print_r):\n");
print_r($test);
print("\n");

// If you dont now the class propertynames you can get these by casting the
// object to an array. The array keys are the names
$prop = array_keys((array) $test);
print("Getting all class propertynames (print_r)\n");
print_r($prop);

//Result
/*

Original object:
    $d1 = 1
    $d2 = 2
    $d3 = 3
    $t1 = 11
    $t2 = 12
    $t3 = 13

Object Changed by reffrence (1):
    $d1 = 31
    $d2 = 32
    $d3 = 33
    $t1 = 41
    $t2 = 42
    $t3 = 43

Object Changed by reffrence (2):
    $d1 = 63
    $d2 = 32
    $d3 = 33
    $t1 = 73
    $t2 = 42
    $t3 = 43

Object Changed (print_r):
Test Object
(
    [t1:private] => 73
    [t2:protected] => 42
    [t3] => 43
    [d1:private] => 63
    [d2:protected] => 32
    [d3] => 33
)

Getting all class propertynames (print_r)
Array
(
    [0] => Test

*/

?>
stachnik at gmail dot com 02-Aug-2005 09:00
In PHP5 to get an array with all properties (even the private ones) all you have to do is write a public method that returns an array for your class:

public function getArray()
{
  return get_object_vars($this);
}

and then

$myBeautifulArray = $myBeautifulObject->getArray ();

Have BEAUTIFUL day :)
fmmarzoa at librexpresion dot org 01-Nov-2004 11:53
You can still cast the object to an array to get all its members and see its visibility. Example:

<?php

class Potatoe {
    public $skin;
    protected $meat;
    private $roots;

    function __construct ( $s, $m, $r ) {
        $this->skin = $s;
        $this->meat = $m;
        $this->roots = $r;
    }
}

$Obj = new Potatoe ( 1, 2, 3 );

echo "<pre>\n";
echo "Using get_object_vars:\n";

$vars = get_object_vars ( $Obj );
print_r ( $vars );

echo "\n\nUsing array cast:\n";

$Arr = (array)$Obj;
print_r ( $Arr );

?>

This will returns:

Using get_object_vars:
Array
(
    [skin] => 1
)

Using array cast:
Array
(
    [skin] => 1
    [ * meat] => 2
    [ Potatoe roots] => 3
)

As you can see, you can obtain the visibility for each member from this cast. That which seems to be spaces into array keys are '\0' characters, so the general rule to parse keys seems to be:

Public members: member_name
Protected memebers: \0*\0member_name
Private members: \0Class_name\0member_name

I've wroten a obj2array function that creates entries without visibility for each key, so you can handle them into the array as it were within the object:

<?php

function obj2array ( &$Instance ) {
    $clone = (array) $Instance;
    $rtn = array ();
    $rtn['___SOURCE_KEYS_'] = $clone;

    while ( list ($key, $value) = each ($clone) ) {
        $aux = explode ("\0", $key);
        $newkey = $aux[count($aux)-1];
        $rtn[$newkey] = &$rtn['___SOURCE_KEYS_'][$key];
    }

    return $rtn;
}

?>

I've created also a <i>bless</i> function that works similar to Perl's bless, so you can further recast the array converting it in an object of an specific class:

<?php

function bless ( &$Instance, $Class ) {
    if ( ! (is_array ($Instance) ) ) {
        return NULL;
    }

    // First get source keys if available
    if ( isset ($Instance['___SOURCE_KEYS_'])) {
        $Instance = $Instance['___SOURCE_KEYS_'];
    }

    // Get serialization data from array
    $serdata = serialize ( $Instance );

    list ($array_params, $array_elems) = explode ('{', $serdata, 2);
    list ($array_tag, $array_count) = explode (':', $array_params, 3 );
    $serdata = "O:".strlen ($Class).":\"$Class\":$array_count:{".$array_elems;

    $Instance = unserialize ( $serdata );
    return $Instance;
}
?>

With these ones you can do things like:

<?php

define("SFCMS_DIR", dirname(__FILE__)."/..");
require_once (SFCMS_DIR."/Misc/bless.php");

class Potatoe {
    public $skin;
    protected $meat;
    private $roots;

    function __construct ( $s, $m, $r ) {
        $this->skin = $s;
        $this->meat = $m;
        $this->roots = $r;
    }

    function PrintAll () {
        echo "skin = ".$this->skin."\n";
        echo "meat = ".$this->meat."\n";
        echo "roots = ".$this->roots."\n";
    }
}

$Obj = new Potatoe ( 1, 2, 3 );

echo "<pre>\n";
echo "Using get_object_vars:\n";

$vars = get_object_vars ( $Obj );
print_r ( $vars );

echo "\n\nUsing obj2array func:\n";

$Arr = obj2array($Obj);
print_r ( $Arr );

echo "\n\nSetting all members to 0.\n";
$Arr['skin']=0;
$Arr['meat']=0;
$Arr['roots']=0;

echo "Converting the array into an instance of the original class.\n";
bless ( $Arr, Potatoe );

if ( is_object ($Arr) ) {
    echo "\$Arr is now an object.\n";
    if ( $Arr instanceof Potatoe ) {
        echo "\$Arr is an instance of Potatoe class.\n";
    }
}

$Arr->PrintAll();

?>
27-Oct-2004 08:02
actually, it's not entirely true that php5 will only return public members....php5 will return any variable IT HAS ACCESS TO

In other words, if you do a get_class_variables($this) inside a class, you'll get everything - public, private, the whole shebang...really annoying since you can't check to see what's private/public without using reflection
manicdepressive AT mindless DOT com 05-Mar-2004 07:57
more strange, strange behaviour:

if you are trying to deep-copy an object with get_object_vars(), strange behaviour can accidentally clobber your original object properties.  please read very, very carefully:

get_object_vars() may either return references to *or* deep copies of the object's properties *depending on whether that property has been set with the -> operator*.   (this behaviour probably varies per php platform and os so please confirm for yourself.)

furthermore, consider
  $properties = get_object_vars($obj);
normally, unset()ting a reference does not affect the original, i.e. $ref = NULL; is not the same as unset($ref); per the references documentation.  However, if you have this strange references version and you unset() an array element of $properties, it will *SET THE OBJECT PROPERTY TO NULL*, which is not how references normally work.

even stranger behaviour comes into effect that i can only express with an example.  please test this with your version and OS and proceed very carefully:
-->
<?php
echo "<pre>\n";

class Lump
{
   var $size = 'average';

   function & copy()
   {  // return a deep copy
      $copy = new Lump();
      $properties = get_object_vars($this);
      foreach( array_keys( $properties ) as $property ){
         $copy->$property = $properties[$property];  // deep, right?
      }
      return $copy;
   }

}

$lump = new Lump();

$lump->size = 'huge';  // <--- this line changes everything
// comment above line out, and see the difference
// also, try substituting another property for 'size'

$properties = get_object_vars($lump);
$properties['size'] = 'small'; // this behavior varies

echo "after changing the properties array:\n";
var_dump( $lump );
// it's either big or small (never huge) depending on
// whether you commented-out the indicated line

//------------- let's try using our copy() method

$original_lump = new Lump();
$original_lump->size = 'huge'; // this line changes the behaviour
$other_lump =& $original_lump->copy();
unset( $other_lump->size );
echo "after unsetting in copy:\n";
var_dump( $original_lump ); // i'm afraid so -- original value clobbered !

echo "</pre>\n";
?>
code till dawn,
   mark meves
christopher AT NOSPAM AT idealab DOT com 30-Dec-2003 03:12
Hmmm.  A bit embarassing...

It turns out the best way to get references to all of your objects member variables is NOT with the functions I provided before, or with get_object_vars.

Just cast the object to array.

$a=(array)$obj;

# The two following statements are now equivalent and identical
$a["member"]=3;
$obj->member=3;

A very powerful tool, for inspectors and what not.
christopher AT NOSPAM AT idealab DOT com 23-Dec-2003 12:49
Please note that you cannot affect the object via the array values...in other words, the returned array does not contain references to the values within the object, but copies.

If you are making an object inspector or editor, this is not good enough.  So I made the following methods:

METHODS:

function &getVar($obj, $name)
{
        $expr="\$prop=&\$obj->$name;";
        eval($expr);
        return $prop;
}

function &getObjectVars($obj)
{
        $result=array();
        $vars=get_object_vars($obj);
        foreach ($vars as $var => $value)
        {
                $result[$var]=&getVar(&$obj, $var);
        }
        return $result;
}

[NOTE:  You must pass in a reference to an object, not an object.  Sorry if this  offends PHP'ers, but the distinction of pass-by-value and copy-on-assignment drives me batty (compared to Python, Java, Smalltalk), so I make all my functions pass by value, and force myself to pass in a reference to keep track of what is happening under the hood.]

EXAMPLE:

class Bob
{
        function Bob()
        {
                $this->thing=13;
                $this->other="whatever";
        }

        var $thing;
        var $other;
}

$obj=&new Bob();

# NOTE:  Passing in a reference!
$props=getObjectVars(&$obj);
$props["thing"]=-11;

var_dump($obj);

RESULTS:

object(bob)(2) {
  ["thing"]=>
  &int(-11)
  ["other"]=>
  &string(8) "whatever"
}
jordi at laigu dot net 06-Nov-2003 05:21
In case your object contains again OBJECTS or ARRAYS:

function makeAssoc($res) {
  if (is_object($res)) $res = get_object_vars($res);
  while (list($key, $value) = each($res)) {
    if (is_object($value) || is_array($value)) {
      $res[$key] = makeAssoc($value);
    }
  }
  return $res;
}

Thanks to mark at dreamzpace dot com
markus at emedia-solutions-wolf dot de 06-Mar-2003 12:01
Hi,

I figured out that in prior version to 4.2 the returned array only contains attributes directly in this class, excluding the derived ones from parentclasses.
info at phpken dot de 21-Nov-2002 06:34
hello,

this example will look like all values of vars was set in your class. write a method like the name: dumpClass and then fill in follow code:

$vars = get_object_vars($this);

echo "<b>class vars</b>";

foreach( $vars as $name => $value ) {
    echo "<li>".$name." : ".$value;
}

look at: get_object_vars($this);

andreas v.l
mark at dreamzpace dot com 13-Sep-2002 10:44
In case your object contains again objects (and so on), this function might be useful:

function makeAssoc($res) {
  $res = get_object_vars($res);
  while (list($key, $value) = each($res)) {
    if (is_object($value)) {
      $res[$key] = makeAssoc($value);
    }
  }
  return $res;
}
nick_eby at bonzidev dot com 09-Jul-2002 12:13
Furthermore, variables not declared in the class but set on a given object, will be returned by get_object_vars().

Example, ver. 4.2.1:
<?
class MyTest {
        var $classVar1 = 'Class Var 1';
        var $classVar2;
        var $classVar3;

        function MyTest()
        {
                $this->classVar2 = 'class var 2';
        }
}

$test = new MyTest();
// This var isn't declared in the class
$test->newObjVar = 'foobar';

echo "<pre>";
print_r(get_object_vars($test));
echo "</pre>";
?>

The output is:
Array
(

    [classVar1] => Class Var 1
    [classVar2] => class var 2
    [classVar3] =>
    [newObjVar] => foobar
)

Prior to version 4.2, classVar3 would not be output as it was never assigned a value.
michael at tapinternet dot com 13-Jun-2002 03:32
It seems that get_object_vars will now return properties of an object even if they have no value  - meaning only defined by var $foo in the class declaration.  This is noted behaviour in 4.2.1 which is different from previous versions and hitherto undocumented on this page.
florian at XCLUDETHISgsf dot de 29-Jan-2002 10:02
There is a strange behaviour, not sure whether it is a bug:

if I call
<?
$single_object = $data_array_of_objects[0];
$array_of_objectvars = get_object_vars($single_object);
     foreach($array_of_objectvars as $key => $val) {
     echo(" $key => $val<br>");
     }
?>
I get only _ONE_ line with the $key = first variable name of the object and $val = the values of _ALL_ variables of the object including the first separated by a space.

NOW:
if I call
<?
$single_object = $data_array_of_objects[0];
$array_of_objectvars = get_object_vars($single_object);
     foreach($array_of_objectvars as $key => $val) {
     echo(" $key => $val<br>");
     }
     echo($data_array_of_objects[0]->objectvar1."<br>");
     echo($data_array_of_objects[0]->objectvar2."<br>");
?>

I get a list of $key = $ val as expected, before the other echos' are printed.
It seems to me that get_object_vars works differently when you access a variable in those objects explicitly (as in the echos)


Recupera el nombre de la clase padre de un objeto o clase

  • « get_object_vars
  • interface_exists »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Recupera el nombre de la clase padre de un objeto o clase

get_parent_class

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

get_parent_class — Recupera el nombre de la clase padre de un objeto o clase

Descripción

get_parent_class ( mixed $object = ? ) : string

Recupera el nombre de la clase padre de un objeto o clase.

Parámetros

object

El objeto evaluádo o nombre de la clase. Este parámetro es opcional si se invoca desde el método del objeto.

Valores devueltos

Devuelve el nombre de la clase padre de la clase de la cuál object es una instancia o el nombre.

Nota:

Si el objeto no tiene padre o la clase dada no existe devolverá false.

Si se llama sin parámetro fuera del objeto, esta función devolverá false.

Historial de cambios

Versión | Descripción
5.1.0 | Si se llamaba sin parámetro fuera del objeto, está función devolvía null con una advertencia, pero ahora devuelve false.

Ejemplos

Ejemplo #1 Usar get_parent_class()

<?php

class papá {
    function papá()
    {
    // implementar algo lógico
    }
}

class hijo extends papá {
    function hijo()
    {
        echo "Soy hijo de " , get_parent_class($this) , "\n";
    }
}

class hijo2 extends papá {
    function hijo2()
    {
        echo "Yo también soy hijo de " , get_parent_class('hijo2') , "\n";
    }
}

$foo = new hijo();
$bar = new hijo2();

?>

El resultado del ejemplo sería:

I'm dad's son
I'm dad's son too

Ver también

  • get_class() - Devuelve el nombre de la clase de un objeto
  • is_subclass_of() - Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa
  • class_parents() - Devuelve las clases padre de la clase dada.

User Contributed Notes

jake at qzdesign dot co dot uk 17-Oct-2019 10:47
Note that from PHP 5.5 you can also use `parent::class` from within a method, e.g.

<?php
    function child()
    {
        echo "I'm ", parent::class, "'s son\n";
    }
?>

Looks a bit tidier and technically probably more optimal, as it avoids a function call lookup.
yukal dot alexander at gmail dot com 24-Nov-2018 07:28
An output of the entire inheritance chain using closures, recursion, and OOP

class ParentClass {
    public static function getChain() {
        $chain = null;
        return $function = function($className='') use (& $chain, & $function) {
            if (empty($className))
                $className = static::class;

            if (empty($chain))
                $chain = $className;

            $parent = get_parent_class($className);

            if ($parent !== false) {
                $chain .= " > {$parent}";
                return $function($parent);
            }

            return $chain;
        };
    }
}

class Child extends ParentClass {}
class SubChild extends Child {}
class Sub2 extends SubChild {}
class Sub3 extends Sub2 {}
class Sub4 extends Sub3 {}
class Sub5 extends Sub4 {}
class Sub6 extends Sub5 {}
class Sub7 extends Sub6 {}

printf("%s\n", Sub7::getChain()());

$getChain = Sub7::getChain();
printf("%s\n", $getChain('Sub3'));

Output is:
Sub7 > Sub6 > Sub5 > Sub4 > Sub3 > Sub2 > SubChild > Child > ParentClass
Sub3 > Sub2 > SubChild > Child > ParentClass
falundir at gmail dot com 13-Apr-2012 10:27
You can use this function to find common parent of multiple objects or classes.

<?php
/**
 * Returns name of the first (in class hierarchy) common parent class of all provided objects or classes.
 * Returns FALSE when common class is not found.
 *
 * @param mixed $objects Array that can contain objects or class names.
 * @return mixed
 */
function get_first_common_parent($objects) {
    $common_ancestors = null;
    foreach($objects as $object) {
        if (is_object($object)) {
            $class_name = get_class($object);
        } else {
            $class_name = $object;
        }

        $parent_class_names = array();
        $parent_class_name = $class_name;
        do {
            $parent_class_names[] = $parent_class_name;
        } while($parent_class_name = get_parent_class($parent_class_name));

        if ($common_ancestors === null) {
            $common_ancestors = $parent_class_names;
        } else {
            $common_ancestors = array_intersect($common_ancestors, $parent_class_names);
        }
    }

    return reset($common_ancestors);
}
?>

Example:

<?php
class A {
}

    class B extends A {
    }

        class D extends B {
        }

        class E extends B {
        }

    class C extends A {
    }

        class F extends C {
        }

            class G extends F {
            }

class H {
}

//returns "A"
get_first_common_parent(array('G', 'E'));

//returns "F"
get_first_common_parent(array(new G(), 'F'));

//returns false (no common parent)
get_first_common_parent(array('C', 'H'));

//returns false (non-existent class provided)
get_first_common_parent(array(new B(), 'X'));
?>
levu 20-Apr-2011 08:36
I wrote a simple function doing the reverse thing: get the children:

<?php
function get_child($instance, $classname) {
    $class = $classname;
    $t = get_class($instance);
    while (($p = get_parent_class($t)) !== false) {
        if ($p == $class) {
            return $t;
        }
        $t = $p;
    }
    return false;
}

abstract class A {
    function someFunction() {
        return get_child($this, __CLASS__);
    }
}

class B extends A {

}

class C extends B {

}

$c = new C();
echo $c->someFunction(); //displays B

?>
ssb45 at cornell dot edu 14-May-2008 08:32
"'If called without parameter outside object' What on earth does that mean?"

There are two places this could be called:
1. From within a member function of an object.  In this case, it may be called with no parameters and will return the parent class of the object owning the member function.  (If the parameter is included, then it will return the parent class of the specified class as normal.)

2. From outside an object (i.e., global or function scope).  In this case, PHP doesn't know what class you're talking about if you don't include a parameter, so it returns FALSE.  (But, of course, it works if you specify the class with the parameter.)
matt-php at DONT-SPAM-ME dot bitdifferent dot com 01-Nov-2004 07:52
PHP (4 at least, dunno about 5) stores classnames in lower case, so:

<?PHP

class Foo
{
}

class Bar extends Foo
{
}

echo get_parent_class('Bar');

echo "\n";

echo get_parent_class('bar');

?>

will output:

foo
foo
radu dot rendec at ines dot ro 07-Apr-2004 06:44
If the argument obj is a string and the class is not defined, then the function returns FALSE.

If the argument obj is an object created from a class with no ancestors (or a string representing a class with no ancestors), then the function returns FALSE.


Comprueba si una interfaz ha sido definida

  • « get_parent_class
  • is_a »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Comprueba si una interfaz ha sido definida

interface_exists

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

interface_exists — Comprueba si una interfaz ha sido definida

Descripción

interface_exists ( string $interface_name , bool $autoload = true ) : bool

Comprueba si la interfaz dada ha sido definida.

Parámetros

interface_name

El nombre de la interfaz

autoload

Si llamar a __autoload o no por defecto.

Valores devueltos

Devuelve true si la interfaz dada por interface_name ha sido definida, false si no.

Ejemplos

Ejemplo #1 Ejemplo de interface_exists()

<?php
// Comprobar si la interfaz existe antes de intentar usarla
if (interface_exists('MiInterfaz')) {
    class MiClase implements MiInterfaz
    {
        // Métodos
    }
}

?>

Ver también

  • get_declared_interfaces() - Devuelve un array con todas las interfaces declaradas
  • class_implements() - Devuelve las interfaces que son implementadas por la clase o interfaz dadas
  • class_exists() - Verifica si la clase ha sido definida

User Contributed Notes

CoR 28-Nov-2015 02:30
Class and Interface share SAME namespace!

class k{}

interface k {}    // Fatal error: Cannot redeclare class k
maxim at inbox dot ru 01-Oct-2012 10:40
If you want to check for included interface and you already register spl autoloader - it will crash. Becassue autoloader trying to load `string` and he doesnt matter is it class or not.
Iv found several ways :
1 - unregister AL - -> check for Ifaces - -> register Autoloader

2 - $ifaces = array_flip(get_declared_interfaces());
 if($ifaces["MyIface"]) // empty // isset .

Interfaces are not bad, you can build correct geomentry of system , with validation by funcs / vars / const .
Also they are good to storage variables <?php
 ROOT::THEMES ; ROOT::LOC ; ?> . Much faster then Define, but you cant put algorithms inside, only complite strings / __file__ / etc.
nils dot rocine at gmail dot com 26-Oct-2011 06:35
A little note on namespaces that may be obvious to some, but was not obvious to me.

Although you can make the below statement when the statement is in the same namespace as the interface/class declaration MyInterface...
<?php
$foo instanceof MyInterface
?>

Making use of the interface_exists, or class_exists functions, you must enter the full namespaced interface name like so (even if the function call is from the same namespace.)
<?php
interface_exists(__NAMESPACE__ . '\MyInterface', false);
?>
andrey at php dot net 24-Oct-2004 04:40
As far as I remember interface_exists() was added in 5.0.2 . In 5.0.0 and 5.0.1 class_exists() used to return TRUE when asked for a existing interface. Starting 5.0.2 class_exists() doesn't do that anymore.


Comprueba si un objeto es de una clase o tiene esta clase como una de sus madres

  • « interface_exists
  • is_subclass_of »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Comprueba si un objeto es de una clase o tiene esta clase como una de sus madres

is_a

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

is_a — Comprueba si un objeto es de una clase o tiene esta clase como una de sus madres

Descripción

is_a ( mixed $object , string $class_name , bool $allow_string = false ) : bool

Comprueba si el objeto dado por object es de esta clase o tiene esta clase como una de sus madres.

Parámetros

object

Un nombre de clase o una instancia de objeto.

class_name

El nombre de la clase

allow_string

Si este parámetro se establece a false, no se permite una cadena de nombre de la clase como object. Esto también evita llamar al autocargador si la clase no existe.

Valores devueltos

Devuelve true si el objeto es de esta clase o tiene esta clase como una de sus madres, false si no.

Historial de cambios

Versión | Descripción
5.3.9 | Se añadió el parámetro allow_string
5.3.0 | Esta función ya no está obsoleta, y por lo tanto ya no lanza advertencias de tipo E_STRICT.
5.0.0 | Esta funcion se volvió obsoleta en favor del operador instanceof. Llamar a esta función resultará en una advertencia de tipo E_STRICT.

Ejemplos

Ejemplo #1 Ejemplo de is_a()

<?php
// definir una clase
class FábricaTrastos
{
  var $oink = 'moo';
}

// crear un nuevo objeto
$WF = new FábricaTrastos();

if (is_a($WF, 'FábricaTrastos')) {
  echo "Sí, \$WF es todavía un FábricaTrastos\n";
}
?>

Ejemplo #2 Usar el operador instanceof en PHP 5

<?php
if ($WF instanceof FábricaTrastos) {
    echo 'Sí, $WF es un FábricaTrastos';
}
?>

Ver también

  • get_class() - Devuelve el nombre de la clase de un objeto
  • get_parent_class() - Recupera el nombre de la clase padre de un objeto o clase
  • is_subclass_of() - Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa

User Contributed Notes

dkrupyanskiy[at]gmail 10-Jan-2018 09:36
Looks like the function signature given in description is wrong. Actually it can take a string  as a first parameter in the case if $allow_string is set to true.

It took some time to find out how the last parameter should be used. Please consider the following example

<?php

class Foo{}

spl_autoload_register(
    function($classname){
        printf('autoload has been triggered for %s%s', $classname, PHP_EOL);
    }
);

var_dump(is_a('UndefinedClassName', Foo::class, true));

?>
Ronald Locke 30-Sep-2016 02:19
Please note that you have to fully qualify the class name in the second parameter.

A use statement will not resolve namespace dependencies in that is_a() function.

<?php
namespace foo\bar;

class A {};
class B extends A {};
?>

<?php
namespace har\var;

use foo\bar\A;
$foo = new foo\bar\B();

is_a($foo, 'A'); // returns false;
is_a($foo, 'foo\bar\A'); // returns true;
?>

Just adding that note here because all examples are without namespaces.
portugal {at} jawira {dot} com 12-Jun-2015 09:32
I just want to point out that you can replace "is_a()" function with the "instanceof" operator, BUT you must use a variable to pass the class name string.

This will work:
<?php
$object = new \stdClass();
$class_name = '\stdClass';

var_dump(is_a($object, $class_name));     // bool(true)
var_dump(is_a($object, '\stdClass'));     // bool(true)
var_dump($object instanceof $class_name); // bool(true)
?>

While this don't:
<?php
$object = new \stdClass();
var_dump($object instanceof '\stdClass'); // Parse error: syntax error, unexpected ''\stdClass'' (T_CONSTANT_ENCAPSED_STRING)
?>
eitan at mosenkis dot net 12-Jan-2012 01:09
As of PHP 5.3.9, is_a() seems to return false when passed a string for the first argument. Instead, use is_subclass_of() and, if necessary for your purposes, also check if the two arguments are equal, since is_subclass_of('foo', 'foo') will return false, while is_a('foo', 'foo') used to return true.
Aron Budinszky 07-Sep-2011 04:21
Be careful! Starting in PHP 5.3.7 the behavior of is_a() has changed slightly: when calling is_a() with a first argument that is not an object, __autoload() is triggered!

In practice, this means that calling is_a('23', 'User'); will trigger __autoload() on "23". Previously, the above statement simply returned 'false'.

More info can be found here:
https://bugs.php.net/bug.php?id=55475

Whether this change is considered a bug and whether it will be reverted or kept in future versions is yet to be determined, but nevertheless it is how it is, for now...
p dot scheit at zweipol dot net 16-Jan-2007 01:44
At least in PHP 5.1.6 this works as well with Interfaces.

<?php
interface test {
  public function A();
}

class TestImplementor implements test {
  public function A () {
    print "A";
  }
}

$testImpl = new TestImplementor();

var_dump(is_a($testImpl,'test'));
?>

will return true
cesoid at yahoo dot com 05-Oct-2005 07:01
is_a returns TRUE for instances of children of the class.

For example:

class Animal
{}

class Dog extends Animal
{}

$test = new Dog();

In this example is_a($test, "Animal") would evaluate to TRUE as well as is_a($test, "Dog").

This seemed intuitive to me, but did not seem to be documented.


Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa

  • « is_a
  • method_exists »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa

is_subclass_of

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

is_subclass_of — Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa

Descripción

is_subclass_of ( mixed $object , string $class_name , bool $allow_string = true ) : bool

Comprueba si el object dado tiene la clase class_name como uno de sus padres o si la implementa.

Parámetros

object

Un nombre de clase o una instancia de objeto. No se genera ningún error si la clase no existe.

class_name

El nombre de clase

allow_string

Si se define este parámetro como false, no se permite el uso del nombre de la clase como object. Esto también previene llamar el autoloader si la clase no existe.

Valores devueltos

Esta función devuelve true si el objeto object pertenece a una clase que sea subclase de class_name, false en caso contrario.

Historial de cambios

Versión | Descripción
5.3.9 | Se añadió el parámetro allow_string
5.3.7 | Se añadió el soporte para class_name para trabajar con interfaces
5.0.3 | Es posible especificar también el parámetro object como una cadena (el nombre de la clase)

Ejemplos

Ejemplo #1 Ejemplo de is_subclass_of()

<?php
// definir una clase
class FabricaWidget
{
  var $oink = 'moo';
}

// definir una clase hija
class Hijo_FabricaWidget extends FabricaWidget
{
  var $oink = 'oink';
}

// crear un nuevo objeto
$FW = new FabricaWidget();
$HFW = new Hijo_FabricaWidget();

if (is_subclass_of($HFW, 'FabricaWidget')) {
  echo "si, \$HFW es una sub-clase de FabricaWidget\n";
} else {
  echo "no, \$HFW no es una sub-clase de FabricaWidget\n";
}

if (is_subclass_of($FW, 'FabricaWidget')) {
  echo "si, \$FW es una sub-clase de FabricaWidget\n";
} else {
  echo "no, \$FW no es una sub-clase de FabricaWidget\n";
}

// usable sólo desde PHP 5.0.3
if (is_subclass_of('Hijo_FabricaWidget', 'FabricaWidget')) {
  echo "si, Hijo_FabricaWidget es una sub-clase de FabricaWidget\n";
} else {
  echo "no, Hijo_FabricaWidget no es una sub-clase de FabricaWidget\n";
}
?>

El resultado del ejemplo sería:

si, $HFW es una sub-clase de FabricaWidget
no, $FW no es una sub-clase de FabricaWidget
si, Hijo_FabricaWidget es una sub-clase de FabricaWidget

Ejemplo #2 Ejemplo de is_subclass_of() usando una interfaz

<?php
// Definir la interfaz
interface MiInterfaz
{
  public function MiFunción();
}

// Definir la implementación de la clase de la interfaz
class MiClase implements MiInterfaz
{
  public function MiFunción()
  {
    return "¡MiClase implementa MiInterfaz!";
  }
}

// Instanciar el objeto
$mi_objeto = new MiClase;

// Funciona desde 5.3.7

// Una prueba usando la instancia del objeto de la clase
if (is_subclass_of($mi_objeto, 'MiInterfaz')) {
  echo "Sí, \$mi_objeto es una subclase de MiInterfaz\n";
} else {
  echo "No, \$mi_objeto no es una subclase de MiInterfaz\n";
}

// Una prueba usando una cadena del nombre de la clase
if (is_subclass_of('MiClase', 'MiInterfaz')) {
  echo "Sí, MiClase es una subclase de MiInterfaz\n";
} else {
  echo "No, MiClase no es una subclase de MiInterfaz\n";
}
?>

El resultado del ejemplo sería:

Sí, $mi_objeto es una subclase de MiInterfaz
Sí, MiClase es una subclase de MiInterfaz

Notas

Nota:

Esta función cargará cualquier autocargador registrado si la clase todavía no existe.

Ver también

  • get_class() - Devuelve el nombre de la clase de un objeto
  • get_parent_class() - Recupera el nombre de la clase padre de un objeto o clase
  • is_a() - Comprueba si un objeto es de una clase o tiene esta clase como una de sus madres
  • class_parents() - Devuelve las clases padre de la clase dada.

User Contributed Notes

alan at jynxy.net 21-Jun-2018 06:56
The $allow_string parameter is not very clearly documented. When true, it simply allows the first parameter to be the name of a class, instead of an object whose class we are interested in.

Some usage examples:

class parent_class {
    // objects and methods ...
}

$possible_child_object = new possible_child_class(); // might be an extension of parent_class

$result = is_subclass_of($possible_child_object, 'parent_class'); //  valid
$result = is_subclass_of($possible_child_object, 'parent_class', false); //  valid
$result = is_subclass_of('possible_child_class', 'parent_class', true); // valid
$result = is_subclass_of('possible_child_class', 'parent_class', false); // not valid
nicholas at aquarionics dot com 17-Mar-2009 01:02
This might be useful to someone, so:

If you're using Autoload, you should be aware that this will attempt to autoload $classname if it isn't already loaded. I discovered this when I had something using is_subclass_of inside an error thrown by autoload, which then recursed until it ran out of memory.
Damien Bezborodov 16-Mar-2009 04:55
If you need something similar to is_subclass_of() to determine if a class implements an interface before instantiating it, use reflection:

<?php

interface A_Interface {}
class A implements A_Interface {}

$reflectionA = new ReflectionClass('A');
var_dump(
    $reflectionA->implementsInterface('A_Interface')
);

?>
bool(true)
kostyl_kostyl gav-gav mail point ru 07-Mar-2009 03:08
<?php
interface I {
}
class A implements I {
}
class B extends A  {
}
if (is_subclass_of('A', 'I')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
if (is_subclass_of('B', 'I')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
if (is_subclass_of('B', 'A')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
?>

result:
bad <- you must to describe intermediate class B to be good
good
good
jm 30-Sep-2008 08:02
It would appear that is_subclass_of is case insensitive unlike get_class in php5.
i.e.

<?php
class fooBar {}
class bar extends fooBar {}

assert(get_class(new fooBar()) == "fooBar");
assert(is_subclass_of(new bar(), "foobar") == true);
?>

i run across this while migrating some code from php4 to php5 and the code would only half-the-time break.
Ondra Zizka 13-Oct-2006 05:31
For PHP4:

<?php
/** Returns whether specified class is subclass of the other class. */
function is_subclass($sClass, $sExpectedParentClass){
    do if( $sExpectedParentClass === $sClass ) return true;
    while( false != ($sClass = get_parent_class($sClass)) );
    return false;
}
// Test:
class A {} class B extends A {} class C extends B {} echo (int) is_subclass('C', 'A');
?>
gunniboyh at web dot de 20-May-2006 06:16
is_subclass_of() works also with classes between the class of obj and the superclass.

example:
<?php
class A {};
class B extends A {};
class C extends B {};

$foo=new C();
echo ((is_subclass_of($foo,'A')) ? 'true' : 'false');
?>

echoes 'true' .


Comprueba si existe un método de una clase

  • « is_subclass_of
  • property_exists »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Comprueba si existe un método de una clase

method_exists

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

method_exists — Comprueba si existe un método de una clase

Descripción

method_exists ( mixed $object , string $method_name ) : bool

Comprueba si existe el método de la clase en el objeto dado por object.

Parámetros

object

Una instancia o un nombre de clase

method_name

El nombre del método

Valores devueltos

Devuelve true si el método dado por method_name ha sido definido para el objeto dado por object, false si no.

Notas

Nota:

Esta función cargará cualquier autocargador registrado si la clase todavía no existe.

Ejemplos

Ejemplo #1 Ejemplo de method_exists()

<?php
$directorio = new Directory('.');
var_dump(method_exists($directorio,'read'));
?>

El resultado del ejemplo sería:

bool(true)

Ejemplo #2 Ejemplo de method_exists() estático

<?php
var_dump(method_exists('Directory','read'));
?>

El resultado del ejemplo sería:

bool(true)

Ver también

  • function_exists() - Devuelve true si la función dada ha sido definida
  • is_callable() - Verificar que los contenidos de una variable puedan ser llamados como una función
  • class_exists() - Verifica si la clase ha sido definida

User Contributed Notes

El 02-Dec-2019 08:39
Undocumented change since 7.4.0 is released:

<?php
class Foo
{
    private function privateMethodTest()
    {

    }
}

class Bar extends Foo
{

}

var_dump(method_exists(Bar::class, 'privateMethodTest'));
// PHP 7.4: bool(false)
// PHP 7.3: bool(true)

var_dump(is_callable(Bar::class, 'privateMethodTest'));
// PHP 7.3: bool(true)
// PHP 7.4: bool(true)
jave [at] issomewhereontheweb [com] 01-Jun-2016 05:15
The function does not care about class existance, so you can use it to check an existance of a method even when class was not declared e.g.
<?php
if( method_exists('THIS_WAS_NOT_DECLARED', 'some_method') )
   echo "it does exist!";
else
   echo "nope, it is not there...";
?>
...raises no errors/warnings... outputs "nope, it is not there..." if class does not exist at all or if it does but the method doesn't.
w3dk 04-Apr-2015 10:38
A couple of the older comments (specifically "jp at function dot fi" and "spam at majiclab dot com") state that is_callable() does not respect a methods visibility when checked outside of that class. ie. That private/protected methods are seen as callable when tested publicly. However, this was a bug (#29210) in early versions of PHP 5 and was fixed (according to the changelog) in PHP 5.0.5 (and/or PHP 5.1.0).

Bug #29210 - Function: is_callable - no support for private and protected classes
http://bugs.php.net/29210

Changelog - Fixed bug #29210 (Function: is_callable - no support for private and protected classes). (Dmitry)
http://php.net/ChangeLog-5.php#5.1.0
charleston olaes at gmail no spaces 10-Oct-2014 04:31
I was wondering if caching the the methods in an array would have a faster lookup. So I ran a very simple benchmark using xdebug_time_index() with 10000 iterations on each statement.

using PHP 5.3.13 btw

<?php
// using an actual instance of an object shows 0.10398316383362 secs
method_exist($object, $method);
?>

<?php
// using a string shows 0.12779307365417 secs
method_exist('ClassName', $method);
?>

<?php
$array = array(/*method names with numeric index*/);
// shows 0.10288906097412 secs
in_array($method, $array);
?>

<?php
$assoc = array( /*method name as key and value*/ );
// shows 0.017536878585815 secs
isset( $assoc[$method] );
?>

From the looks of the results, there is very little difference in method_exist and in_array. Isset seems to the fastest and using a string as the first parameter is the slowest.

Please note that the test was done on multiple methods, not just one, the code presented above is to show the results, not the actual test code that ran. Also, this was tested just out of curiosity and I didn't set up a specific environment or used any profiling tools, and it was not meant to be an official benchmark in anyway.
konzertheld at thedomainistheusersname dot de 15-Feb-2013 05:32
Note that prepending the namespace (if any) is required even if the calling class is in the same namespace:

<?php
namespace test;
class foo {
 public function lookup() {
  // will return false
  return method_exists('bar', 'nonsense_method');
 }
}

class bar {
 public function nonsense_method() {
  // will return true
  return method_exists('test\foo', 'lookup');
 }
}
?>
Niels 11-May-2011 12:45
Just to mention it: both method_exists() and is_callable() return true for inherited methods:

<?php
class ParentClass {

   function doParent() { }
}

class ChildClass extends ParentClass { }

$p = new ParentClass();
$c = new ChildClass();

// all return true
var_dump(method_exists($p, 'doParent'));
var_dump(method_exists($c, 'doParent'));

var_dump(is_callable(array($p, 'doParent')));
var_dump(is_callable(array($c, 'doParent')));
?>
mail at bartrail dot de 25-Apr-2011 10:06
Using method_exists inside an object's __call() method can be very usefull if you want to avoid to get a fatal error because of a limit in function nesting or if you are calling methods that dont exist but need to continue in your application:

<?php
class Something
{

    /**
     * Call a method dynamically
     *
     * @param string $method
     * @param array $args
     * @return mixed
     */
    public function __call($method, $args)
    {
        if(method_exists($this, $method)) {
          return call_user_func_array(array($this, $method), $args);
        }else{
          throw new Exception(sprintf('The required method "%s" does not exist for %s', $method, get_class($this)));
        }
    }

}
?>
phoenix at todofixthis dot com 21-Dec-2010 09:13
As noted [elsewhere] method_exists() does not care about the existence of __call(), whereas is_callable() does:

<?php
class Test {
  public function explicit(  ) {
      // ...
  }

  public function __call( $meth, $args ) {
      // ...
  }
}

$Tester = new Test();

var_export(method_exists($Tester, 'anything')); // false
var_export(is_callable(array($Tester, 'anything'))); // true
?>
uramihsayibok, gmail, com 06-Aug-2010 10:09
It wasn't spelled out but could be inferred: method_exists() also works on interfaces.

<?php

var_dump(method_exists("Iterator", "current"));
// bool(true)

?>
Anonymous 08-May-2010 05:20
If you want to check in a class itself if a method is known you may do so with magic variable __CLASS__

<?php

class A{
  __construct($method){
      return method_exists(__CLASS__,$method);
  }

  private function foo(){

  }
}

$test = new A('foo');
//should return true

?>

You might also use the method describe below with <?php in_array() ?> trick but I consider this one here easier and more readable and well, the way it is intended toi be done ;)
admin ( at ) djokodonev dot com 16-Oct-2009 04:30
Hi,

Here is a useful function that  you can use to check classes methods access e.g whether it is public, private or static or both..

here it goes:

<?php
// Example class
class myClass {

    private $private1;

    static $static1;

    public $public1;

    public function publ() {

    }

    private function priv() {

    }

    private static function privstatic() {

    }

    public static function publstatic() {

    }

    static function mytest() {

    }
}

// The function uses the reflection class that is built into PHP!!!
// The purpose is to determine the type of a certain method that exi
function is_class_method($type="public", $method, $class) {
   // $type = mb_strtolower($type);
    $refl = new ReflectionMethod($class, $method);
    switch($type) {
        case "static":
        return $refl->isStatic();
        break;
        case "public":
        return $refl->isPublic();
        break;
        case "private":
        return $refl->isPrivate();
        break;
    }
}
var_dump(is_class_method("static", "privstatic", "myClass")); // true - the method is  private and also static..
var_dump(is_class_method("private", "privstatic", "myClass")); // true - the method is  private and also static..
var_dump(is_class_method("private", "publstatic", "myClass")); // False the methos is public and also static not private
 // you get the idea.. I hope this helps someone..
?>
florin from syneto net 07-Oct-2009 07:34
This function is case-insensitive (as is PHP) and here is the proof:
<?php
class A {
    public function FUNC() { echo '*****'; }
}

$a = new A();
$a->func(); // *****
var_dump(method_exists($a, 'func')); // bool(true)
?>
jp at function dot fi 30-Apr-2006 02:29
As mentioned before, is_callable and method_exists report all methods callable even if they are private/protected and thus actually not callable. So instead of those functions you may use following work-around which reports methods as supposed to.

<?php
class Foo1 {
  public function bar() {
    echo "I'm private Foo1::bar()";
  }
}

class Foo2 {
  private function bar() {
    echo "I'm public Foo2::bar()";
  }
}

$f1=new Foo1;
$f2=new Foo2;

if(is_callable(array($f1,"bar"))) {
    echo "Foo1::bar() is callable";
} else {
    echo "Foo1::bar() isn't callable";
}
if(is_callable(array($f2,"bar"))) {
    echo "Foo2::bar() is callable";
} else {
    echo "Foo2::bar() isn't callable";
}
if(in_array("bar",get_class_methods($f1))) {
    echo "Foo1::bar() is callable";
} else {
    echo "Foo1::bar() isn't callable";
}
if(in_array("bar",get_class_methods($f2))) {
    echo "Foo2::bar() is callable";
} else {
    echo "Foo2::bar() isn't callable";
}

?>

output
Foo1::bar() is callable (correct)
Foo2::bar() is callable (incorrect)
Foo1::bar() is callable (correct)
Foo2::bar() isn't callable (correct)

?>
seufert at gmail dot com 26-Apr-2006 06:27
Just a note that the behaviour of this function changed between version 5.0.x and 5.1.x when using static member functions

Using this code:
<?php
class a {
    static function test() {return "A";}
}
if(method_exists('a','test'))
    print call_user_func(array('a','test'));
else
    print "Nothing";
?>
PHP 5.1.x returns "A"
PHP 5.0.x returns "Nothing"

Im not sure of a workaround for PHP 5.0.x yet.
spam at majiclab dot com 31-Jan-2006 08:33
Both method_exists() and is_callable() return private and protected functions, which, as mentioned below, causes problems for PHP5/OO programming.  You can use get_class_methods() with either an $instance of a class or the 'ClassName' to get only public functions.
daniel at softel dot jp 09-Jan-2006 07:34
Note that in PHP5, method_exists() will sucessfully find *private* methods. This has some OO/data-hiding ramifications.
jpgiot at nospam ifrance.com 06-May-2004 07:42
a little difference :

to find a method of an object (instance of a class)

<?php
if (method_exists($myinstance,'themethod'))
    echo 'ok';
?>

to find a method of a class (using the class name, not the instance of the class!)

<?php
if (is_callable(array('theclassname','themethod')))
    echo 'ok';
?>
Thomas@ThBeckmann 31-Jan-2003 01:47
Though, as Bejamin noted, it's not possible to use the class name in method_exists within the class definition, get_class_methods delivers the method names for a given class name even inside the class. Thus another workaround for the mentioned problem is to use in_array(<method_name>, get_class_methods(<class_name>))
benjamin_ansbach at web dot de 27-Dec-2002 12:49
if you want to check for a method "inside" of a class use:

method_exists($this, 'function_name')

i was a bit confused 'cause i thought i'm only able to check for a method when i got an object like $object_name = new class_name() with:

method_exists($object_name, 'method_name')

small example for those who didn't understood what i mean ( maybe caused by bad english :) ):

<?php

class a {

    function a() {

        if(method_exists($this, 'test'))
            echo 'a::test() exists!';
        else
            echo 'a::test() doesn\'t exists';

    }

    function test() {

        return true;

    }

}

$b = new a();

?>

the output will be: a::test() exists!

maybe this will help someone
j dot metzger at steptown dot com 16-Jan-2002 03:42
call_user_method uses the same mechanism as a normal method call. So you can get the returned values as well in this way.

$pagetext=call_user_method($method,$object_call);

All information is then in $pagetext.


Comprueba si el objeto o la clase tienen una propiedad

  • « method_exists
  • trait_exists »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Comprueba si el objeto o la clase tienen una propiedad

property_exists

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

property_exists — Comprueba si el objeto o la clase tienen una propiedad

Descripción

property_exists ( mixed $class , string $property ) : bool

Esta función comprueba si la propiedad dada por property existe en la clase especificada.

Nota:

A diferencia de isset(), property_exists() devuelve true incluso si la propiedad tiene el valor null.

Parámetros

class

El nombre de la clase o un objeto de la clase a comprobar

property

El nombre de la propiedad

Valores devueltos

Devuelve true si la propiedad existe, false si no existe, o null en caso de error.

Notas

Nota:

Esta función cargará cualquier autocargador registrado si la clase todavía no existe.

Nota:

La función property_exists() no puede detectar propiedades que son accesibles de forma mágica usando el método mágico __get.

Historial de cambios

Versión | Descripción
5.3.0 | Esta función comprueba la existencia de una propiedad independientemente de su accesibilidad.

Ejemplos

Ejemplo #1 Un ejemplo de property_exists()

<?php

class miClase {
    public $mía;
    private $xpto;
    static protected $prueba;

    static function prueba() {
        var_dump(property_exists('miClase', 'xpto')); //true
    }
}

var_dump(property_exists('miClase', 'mía'));   //true
var_dump(property_exists(new miClase, 'mía')); //true
var_dump(property_exists('miClase', 'xpto'));   //true, desde PHP 5.3.0
var_dump(property_exists('miClase', 'bar'));    //false
var_dump(property_exists('miClase', 'prueba'));   //true, desde PHP 5.3.0
miClase::prueba();

?>

Ver también

  • method_exists() - Comprueba si existe un método de una clase

User Contributed Notes

rnealxp at yahoo dot com 11-May-2020 06:56
For class constants, use defined() to check for their existence since property_exists() cannot be used.
<?php
class A{
    private static $c = 'C';
    const B = 'B';
}
if(property_exists('A','c')===true){
    echo 'y';
}else{
    echo 'n';
} //output: y
if(property_exists('A','B')===true){
    echo 'y';
}else{
    echo 'n';
} //output: n
if(defined('A::B')===true){
    echo 'y';
}else{
    echo 'n';
} //output: y
?>
@fitorec 14-Jul-2019 02:12
<?php

abstract class P {
  private $priv;
  static protected $static_prop;
  static function exists($prop = 'priv') {
      var_dump(property_exists(new static, $prop)); //true
  }
}

class S extends P {
  static protected $new_prop;
}
S::exists('new_prop');       // True
S::exists('static_prop');    // True
S::exists('priv');           // True
David Spector 03-Sep-2018 12:37
Just to clarify, property_exists only works for static properties. There is no corresponding const_exists function in PHP to do something similar for const names.
falundir at gmail dot com 16-Feb-2017 08:42
If you want to test if declared *public* property was unset, you can use the following code:

<?php
class A {
    public $declared;
}

$a = new A();
$is_defined = array_key_exists('declared', (array)$a); //=>true

unset($a->declared);
$is_defined = array_key_exists('declared', (array)$a); //=>false
?>
Daniel dot Peder at infoset dot com 23-Nov-2016 09:24
declared properties cannot be unset
any set property does exist, even being set to null, regardless how it was set

<?php

class demo_property_exists {

    public $my_public;
    protected $my_protected;
    private $my_private;

    function __construct() {
        $this->dumper('before-constructed');
        $this->my_constructed_int = 123;
        $this->my_constructed_null = null;
        $this->dumper('after-constructed');
    }

    public function dumper($name) {
        printf("\n[%s] dump:\n", $name);

        foreach ($this->my_checklist() as $prop) {
            printf("[%s]:\t", $prop);
            var_dump(property_exists($this, $prop));
        }
    }

    public function unset_all() {
        foreach ($this->my_checklist() as $prop) {
            unset($this->$prop);
        }
    }

    private function my_checklist() {
        return array('my_public', 'my_protected', 'my_private', 'my_constructed_int', 'my_constructed_null', 'my_assigned_int', 'my_assigned_null',);
    }

}

$object = new demo_property_exists();
$object->dumper('before-assigned');
$object->my_assigned_int = 456;
$object->my_assigned_null = null;
$object->dumper('after-assigned');
$object->unset_all();
$object->dumper('after-unset');

/*
results:

[before-constructed] dump:
[my_public]:    bool(true)
[my_protected]: bool(true)
[my_private]:   bool(true)
[my_constructed_int]:   bool(false)
[my_constructed_null]:  bool(false)
[my_assigned_int]:      bool(false)
[my_assigned_null]:     bool(false)

[after-constructed] dump:
[my_public]:    bool(true)
[my_protected]: bool(true)
[my_private]:   bool(true)
[my_constructed_int]:   bool(true)
[my_constructed_null]:  bool(true)
[my_assigned_int]:      bool(false)
[my_assigned_null]:     bool(false)

[before-assigned] dump:
[my_public]:    bool(true)
[my_protected]: bool(true)
[my_private]:   bool(true)
[my_constructed_int]:   bool(true)
[my_constructed_null]:  bool(true)
[my_assigned_int]:      bool(false)
[my_assigned_null]:     bool(false)

[after-assigned] dump:
[my_public]:    bool(true)
[my_protected]: bool(true)
[my_private]:   bool(true)
[my_constructed_int]:   bool(true)
[my_constructed_null]:  bool(true)
[my_assigned_int]:      bool(true)
[my_assigned_null]:     bool(true)

[after-unset] dump:
[my_public]:    bool(true)
[my_protected]: bool(true)
[my_private]:   bool(true)
[my_constructed_int]:   bool(false)
[my_constructed_null]:  bool(false)
[my_assigned_int]:      bool(false)
[my_assigned_null]:     bool(false)

*/
saurabh dot agarwal89 at gmail dot com 27-May-2015 11:17
$a = array('a','b'=>'c');
print_r((object) $a);
var_dump( property_exists((object) $a,'0'));
var_dump( property_exists((object) $a,'b'));

OUTPUT:
stdClass Object
(
    [0] => a
    [b] => c
)
bool(false)
bool(true)
g dot gentile at parentesigraffe dot com 05-Mar-2015 09:02
The function behaves differently depending on whether the property has been present in the class declaration, or has been added dynamically, if the variable has been unset()

<?php

class TestClass {

    public $declared = null;

}

$testObject = new TestClass;

var_dump(property_exists("TestClass", "dynamic")); // boolean false, as expected
var_dump(property_exists($testObject, "dynamic")); // boolean false, same as above

$testObject->dynamic = null;
var_dump(property_exists($testObject, "dynamic")); // boolean true

unset($testObject->dynamic);
var_dump(property_exists($testObject, "dynamic")); // boolean false, again.

var_dump(property_exists($testObject, "declared")); // boolean true, as espected

unset($testObject->declared);
var_dump(property_exists($testObject, "declared")); // boolean true, even if has been unset()
ewisuri [gmail] 15-Feb-2014 04:37
As of PHP 5.3.0, calling property_exists from a parent class sees private properties in sub-classes.

<?php
class P {
    public function test_prop($prop) { return property_exists($this, $prop); }
}

class Child extends P {
    private $prop1;
}

$child = new Child();
var_dump($child->test_prop('prop1')); //true, as of PHP 5.3.0
Nanhe Kumar 17-Jan-2014 10:39
<?php

class Student {

    protected $_name;
    protected $_email;

    public function __call($name, $arguments) {
        $action = substr($name, 0, 3);
        switch ($action) {
            case 'get':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    return $this->{$property};
                }else{
                    echo "Undefined Property";
                }
                break;
            case 'set':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    $this->{$property} = $arguments[0];
                }else{
                    echo "Undefined Property";
                }

                break;
            default :
                return FALSE;
        }
    }

}

$s = new Student();
$s->setName('Nanhe Kumar');
$s->setEmail('nanhe.kumar@gmail.com');
echo $s->getName(); //Nanhe Kumar
echo $s->getEmail(); // nanhe.kumar@gmail.com
$s->setAge(10); //Undefined Property
?>
Stefan W 03-Sep-2013 01:23
If you are in a namespaced file, and you want to pass the class name as a string, you will have to include the full namespace for the class name - even from inside the same namespace:

<?
namespace MyNS;

class A {
    public $foo;
}

property_exists("A", "foo");          // false
property_exists("\\MyNS\\A", "foo");  // true
?>


Comprobar si el trait existe

  • « property_exists
  • Classkit »
  • PHP Manual
  • Funciones de Clases/Objetos
  • Comprobar si el trait existe

trait_exists

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

trait_exists — Comprobar si el trait existe

Descripción

trait_exists ( string $traitname , bool $autoload = ? ) : bool

Parámetros

traitname

Nombre del trait a comprobar

autoload

Si aplicar la autocarga si no está ya cargado.

Valores devueltos

Devuelve true si el trait existe, false si no, null en caso de error.

User Contributed Notes

astinus dot eberhard at gmail dot com 10-Mar-2017 03:35
Traits are compatible with class autoload mechanism - in fact, if you look at source code of trait_exists function, you will find similar peace of code (see Zend/zend_builtin_functions.c)
valerio dot bozzolan at gmail dot com 28-Jan-2016 06:38
What is the default value of $autoload? And in which way traits are autoloaded? Is there something as spl_autoload() for traits?
Lubaev.K 19-Jun-2013 02:20
<?php
trait World {

    private static $instance;
    protected $tmp;

    public static function World()
    {
        self::$instance = new static();
        self::$instance->tmp = get_called_class().' '.__TRAIT__;

        return self::$instance;
    }

}

if ( trait_exists( 'World' ) ) {

    class Hello {
        use World;

        public function text( $str )
        {
            return $this->tmp.$str;
        }
    }

}

echo Hello::World()->text('!!!'); // Hello World!!!


Classkit

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Funciones de Classkit
    • classkit_import — Importar nuevas definiciones de métodos de clase desde un archivo
    • classkit_method_add — Añade dinámicamente un nuevo método una clase dada
    • classkit_method_copy — Copia un método de una clase a otra
    • classkit_method_redefine — Cambia dinámicamente el código del método dado
    • classkit_method_remove — Elimina dinámicamente el método dado
    • classkit_method_rename — Cambia dinámicamente el nombre del método dado

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Estas funciones permiten la manipulación dinámica de clases de PHP en tiempo de ejecución.

Nota:

Esta extensión ha sido reemplazada por runkit, la cual no está limitada solamente a la manipulación de clases, sino también a la manipulación de funciones.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

Esta extensión se considera no mantenida y abandonada. Sin embargo, el código fuente para esta extensión sigue estando disponible en PECL SVN aquí: » https://svn.php.net/viewvc/pecl/classkit.

User Contributed Notes

There are no user contributed notes for this page.


Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles sólo cuando la extensión haya sido compilada con PHP, o bien sea cargada dinámicamente en ejecución.

CLASSKIT_ACC_PRIVATE (int)
Marca el método como private
CLASSKIT_ACC_PROTECTED (int)
Marca el método como protected
CLASSKIT_ACC_PUBLIC (int)
Marca el método como public

User Contributed Notes

There are no user contributed notes for this page.


Funciones de Classkit

Tabla de contenidos

  • classkit_import — Importar nuevas definiciones de métodos de clase desde un archivo
  • classkit_method_add — Añade dinámicamente un nuevo método una clase dada
  • classkit_method_copy — Copia un método de una clase a otra
  • classkit_method_redefine — Cambia dinámicamente el código del método dado
  • classkit_method_remove — Elimina dinámicamente el método dado
  • classkit_method_rename — Cambia dinámicamente el nombre del método dado

User Contributed Notes

There are no user contributed notes for this page.


Importar nuevas definiciones de métodos de clase desde un archivo

  • « Funciones de Classkit
  • classkit_method_add »
  • PHP Manual
  • Funciones de Classkit
  • Importar nuevas definiciones de métodos de clase desde un archivo

classkit_import

(PECL classkit >= 0.3)

classkit_import — Importar nuevas definiciones de métodos de clase desde un archivo

Descripción

classkit_import ( string $filename ) : array

Nota: Esta función no puede ser utilizada para manipular el actual método en ejecución (o extendido).

Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Parámetros

filename

El nombre de archivo de las definiciones del método de clase a importar

Valores devueltos

Matriz asociativa de los métodos importados

Ejemplos

Ejemplo #1 Ejemplo de classkit_import()

<?php
// file: nuevaclase.php
class Ejemplo {
    function foo() {
        return "bar!\n";
    }
}
?>
<?php
// se necesita nuevaclase.php (ver arriba)
class Ejemplo {
    function foo() {
        return "foo!\n";
    }
}

$e = new Ejemplo();

// imprimir el original
echo $e->foo();

// importar el método de remplazo
classkit_import('nuevaclase.php');

// imprimir el importado
echo $e->foo();

?>

El resultado del ejemplo sería:

foo!
bar!

Ver también

  • classkit_method_add() - Añade dinámicamente un nuevo método una clase dada
  • classkit_method_copy() - Copia un método de una clase a otra

User Contributed Notes

There are no user contributed notes for this page.


Añade dinámicamente un nuevo método una clase dada

  • « classkit_import
  • classkit_method_copy »
  • PHP Manual
  • Funciones de Classkit
  • Añade dinámicamente un nuevo método una clase dada

classkit_method_add

(PECL classkit >= 0.1)

classkit_method_add — Añade dinámicamente un nuevo método una clase dada

Descripción

classkit_method_add ( string $classname , string $methodname , string $args , string $code , int $flags = CLASSKIT_ACC_PUBLIC ) : bool
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Parámetros

classname

La clase en la que este método será añadido

methodname

El nombre del método a añadir

args

Lista de argumentos separados por coma para el método recién creado

code

El código a ser evaluado cuando methodname es llamado

flags

El tipo de método a crear, puede ser CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED o CLASSKIT_ACC_PRIVATE

Nota:

Este parámetro se usa sólo a partir de PHP 5, ya que, antes de esta versión, todos los métodos eran públicos.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de classkit_method_add()

<?php
class Ejemplo {
    function foo() {
        echo "foo!\n";
    }
}

// crear un objeto de Ejemplo
$e = new Example();

// Añadir un nuevo método público
classkit_method_add(
    'Ejemplo',
    'sumar',
    '$num1, $num2',
    'return $num1 + $num2;',
    CLASSKIT_ACC_PUBLIC
);

// sumar 12 + 4
echo $e->sumar(12, 4);
?>

El resultado del ejemplo sería:

16

Ver también

  • classkit_method_copy() - Copia un método de una clase a otra
  • classkit_method_redefine() - Cambia dinámicamente el código del método dado
  • classkit_method_remove() - Elimina dinámicamente el método dado
  • classkit_method_rename() - Cambia dinámicamente el nombre del método dado
  • create_function() - Crear una función anónima (estilo lambda)

User Contributed Notes

Lester 03-Apr-2008 09:54
If you creates methods by using classkit_method_add(), they are not visible in get_class_methods().

class A
{
       public function foo()
       {
            return "foo!\n";
       }
}

classkit_method_redefine('A','bar','','return "bar !\n";',CLASSKIT_ACC_PUBLIC);

print_r(get_class_methods('A'));
// writes only "foo"


Copia un método de una clase a otra

  • « classkit_method_add
  • classkit_method_redefine »
  • PHP Manual
  • Funciones de Classkit
  • Copia un método de una clase a otra

classkit_method_copy

(PECL classkit >= 0.2)

classkit_method_copy — Copia un método de una clase a otra

Descripción

classkit_method_copy ( string $dClass , string $dMethod , string $sClass , string $sMethod = ? ) : bool
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Parámetros

dClass

Clase destino para copiar el método

dMethod

Nombre del método destino

sClass

Clase origen del método a copiar

sMethod

Nombre del método a copiar desde la clase origen. Si se omite este parámetro, se asume el valor de dMethod.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de classkit_method_copy()

<?php
class Foo {
    function ejemplo() {
        return "foo!\n";
    }
}

class Bar {
    // inicialmente sin métodos
}

// copiar el método ejemplo() desde la clase Foo a la clase Bar class, como baz()
classkit_method_copy('Bar', 'baz', 'Foo', 'ejemplo');

// imprimir la función copiada
echo Bar::baz();
?>

El resultado del ejemplo sería:

foo!

Ver también

  • classkit_method_add() - Añade dinámicamente un nuevo método una clase dada
  • classkit_method_redefine() - Cambia dinámicamente el código del método dado
  • classkit_method_remove() - Elimina dinámicamente el método dado
  • classkit_method_rename() - Cambia dinámicamente el nombre del método dado

User Contributed Notes

There are no user contributed notes for this page.


Cambia dinámicamente el código del método dado

  • « classkit_method_copy
  • classkit_method_remove »
  • PHP Manual
  • Funciones de Classkit
  • Cambia dinámicamente el código del método dado

classkit_method_redefine

(PECL classkit >= 0.1)

classkit_method_redefine — Cambia dinámicamente el código del método dado

Descripción

classkit_method_redefine ( string $classname , string $methodname , string $args , string $code , int $flags = CLASSKIT_ACC_PUBLIC ) : bool

Nota: Esta función no puede ser utilizada para manipular el actual método en ejecución (o extendido).

Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Parámetros

classname

La clase el la que se va a redefinir el método

methodname

El nombre del método a redefinir

args

Lista de argumentos separados por coma para el método redefinido

code

El nuevo código a ser evaluado cuando methodname es llamado

flags

El método redefinido puede ser CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED o CLASSKIT_ACC_PRIVATE

Nota:

Este parámetro sólo se usa a partir de PHP 5, ya que, antes de esta versión, todos los métodos eran públicos.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de classkit_method_redefine()

<?php
class Ejemplo {
    function foo() {
        return "foo!\n";
    }
}

// crear un objeto de Ejemplo
$e = new Ejemplo();

// imprimir Ejemplo::foo() (antes de redefinir)
echo "Antes: " . $e->foo();

// Redefinir el método 'foo'
classkit_method_redefine(
    'Ejemplo',
    'foo',
    '',
    'return "bar!\n";',
    CLASSKIT_ACC_PUBLIC
);

// imprimir Ejemplo::foo() (después de redefinir)
echo "Después: " . $e->foo();
?>

El resultado del ejemplo sería:

Antes: foo!
Después: bar!

Ver también

  • classkit_method_add() - Añade dinámicamente un nuevo método una clase dada
  • classkit_method_copy() - Copia un método de una clase a otra
  • classkit_method_remove() - Elimina dinámicamente el método dado
  • classkit_method_rename() - Cambia dinámicamente el nombre del método dado

User Contributed Notes

fdrean 03-Sep-2016 12:22
This could lead to revolution in cli mode now that developers can load new code without restarting process.


Elimina dinámicamente el método dado

  • « classkit_method_redefine
  • classkit_method_rename »
  • PHP Manual
  • Funciones de Classkit
  • Elimina dinámicamente el método dado

classkit_method_remove

(PECL classkit >= 0.1)

classkit_method_remove — Elimina dinámicamente el método dado

Descripción

classkit_method_remove ( string $classname , string $methodname ) : bool

Nota: Esta función no puede ser utilizada para manipular el actual método en ejecución (o extendido).

Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Parámetros

classname

La clase en la que se va a eliminar el método

methodname

El nombre del método a eliminar

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de classkit_method_remove()

<?php
class Ejemplo {
    function foo() {
        return "foo!\n";
    }

    function bar() {
        return "bar!\n";
    }
}

// Eliminar el método 'foo'
classkit_method_remove(
    'Ejemplo',
    'foo'
);

echo implode(' ', get_class_methods('Ejemplo'));

?>

El resultado del ejemplo sería:

bar

Ver también

  • classkit_method_add() - Añade dinámicamente un nuevo método una clase dada
  • classkit_method_copy() - Copia un método de una clase a otra
  • classkit_method_redefine() - Cambia dinámicamente el código del método dado
  • classkit_method_rename() - Cambia dinámicamente el nombre del método dado

User Contributed Notes

There are no user contributed notes for this page.


Cambia dinámicamente el nombre del método dado

  • « classkit_method_remove
  • Ctype »
  • PHP Manual
  • Funciones de Classkit
  • Cambia dinámicamente el nombre del método dado

classkit_method_rename

(PECL classkit >= 0.1)

classkit_method_rename — Cambia dinámicamente el nombre del método dado

Descripción

classkit_method_rename ( string $classname , string $methodname , string $newname ) : bool

Nota: Esta función no puede ser utilizada para manipular el actual método en ejecución (o extendido).

Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Parámetros

classname

La clase en la que se va a renombrar el método

methodname

El nombre del método a renombrar

newname

El nuevo nombre a dar al método renombrado

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de classkit_method_rename()

<?php
class Ejemplo {
    function foo() {
        return "foo!\n";
    }
}

// Renombrar el método 'foo' a 'bar'
classkit_method_rename(
    'Ejemplo',
    'foo',
    'bar'
);

// imprimir la funcón renombrada
echo Ejemplo::bar();
?>

El resultado del ejemplo sería:

foo!

Ver también

  • classkit_method_add() - Añade dinámicamente un nuevo método una clase dada
  • classkit_method_copy() - Copia un método de una clase a otra
  • classkit_method_redefine() - Cambia dinámicamente el código del método dado
  • classkit_method_remove() - Elimina dinámicamente el método dado

User Contributed Notes

There are no user contributed notes for this page.


Comprobación del tipo de carácter

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Funciones de Ctype
    • ctype_alnum — Chequear posibles caracteres alfanuméricos
    • ctype_alpha — Chequear posibles caracteres alfabéticos
    • ctype_cntrl — Chequear posibles caracteres de control
    • ctype_digit — Chequear posibles caracteres numéricos
    • ctype_graph — Chequear posibles caracteres imprimibles, con excepción de los espacios
    • ctype_lower — Chequear posibles caracteres en minúscula
    • ctype_print — Chequear posibles caracteres imprimibles
    • ctype_punct — Chequear posibles caracteres imprimibles que no son ni espacios en blanco ni caracteres alfanuméricos
    • ctype_space — Chequear posibles caracteres de espacio en blanco
    • ctype_upper — Chequear posibles caracteres en mayúscula
    • ctype_xdigit — Chequear posibles caracteres que representen un dígito hexadecimal

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Las funciones proporcionadas con esta extensión comprueban si un carácter o string caen dentro de una cierta clase de caracteres según la configuración regional en uso (véase también setlocale()).

Cuando estas funciones se invocan con un argumento de tipo integer, se comportan exactamente como sus homólogas en C de ctype.h. Esto significa que si se pasa un valor de tipo integer menor que 256 se usará el valor ASCII del mismo para ver si encaja en el rango especificado (los dígitos están en el rango 0x30-0x39). Si el número está entre -128 y -1 inclusive, se añadirá 256 y la comprobación se hará sobre el resultado.

Cuando se invocan con un argumento de tipo string, comprobarán cada carácter de la cadena y sólo devolverá true si cada carácter de la cadena coincide con el criterio solicitado. Cuando se invocan con un string vacío, el resultado será siempre true en PHP < 5.1 y false desde 5.1.

Pasar cualquier cosa que no sea un valor de tipo string o integer devolverá inmediatamente false.

Se debería observar que siempre son preferibles las funciones de ctype a las expresiones regulares, e incluso a algunas funciones str_* y is_* equivalentes. Esto es así por el hecho de que ctype usa una biblioteca nativa de C y por lo tanto procesa significativamente más rápido.

Nota:

Estas funciones no están relacionadas con la biblioteca "ctypes" de Python de ningún modo. El nombre de la extensión proviene del fichero de cabecera ctype.h de C donde están definidas sus equivalentes.

Esta extensión también es anterior a "ctypes" de Python, por lo que cualquier confusión causada por este nombramiento apenas es por nuestra culpa...

User Contributed Notes

flashinno at gmail dot com 16-Jan-2015 08:12
pcre from the ver. 5.3 is a part of core PHP, any function exported from .so can't work wih faster than core function


Requerimientos

Nada excepto las funciones de la biblioteca C estándar que están siempre disponibles.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

El soporte de ctype se puede desactivar con --disable-ctype.

La versión de PHP para Windows tiene soporte nativo para esta extensión. No se requiere cargar extensiones adicionales para utilizar estas funciones.

User Contributed Notes

sparc at fastmail dot fm 28-Dec-2016 08:42
Or pkg install php56-ctype if you have PHP 5.6 in FreeBSD
php at darkain dot com 02-Oct-2016 09:41
On FreeBSD, this library is NOT included automatically. It must be manually installed. This can be done with the following command:

pkg install php70-ctype


Funciones de Ctype

Tabla de contenidos

  • ctype_alnum — Chequear posibles caracteres alfanuméricos
  • ctype_alpha — Chequear posibles caracteres alfabéticos
  • ctype_cntrl — Chequear posibles caracteres de control
  • ctype_digit — Chequear posibles caracteres numéricos
  • ctype_graph — Chequear posibles caracteres imprimibles, con excepción de los espacios
  • ctype_lower — Chequear posibles caracteres en minúscula
  • ctype_print — Chequear posibles caracteres imprimibles
  • ctype_punct — Chequear posibles caracteres imprimibles que no son ni espacios en blanco ni caracteres alfanuméricos
  • ctype_space — Chequear posibles caracteres de espacio en blanco
  • ctype_upper — Chequear posibles caracteres en mayúscula
  • ctype_xdigit — Chequear posibles caracteres que representen un dígito hexadecimal

User Contributed Notes

There are no user contributed notes for this page.


Chequear posibles caracteres alfanuméricos

  • « Funciones de Ctype
  • ctype_alpha »
  • PHP Manual
  • Funciones de Ctype
  • Chequear posibles caracteres alfanuméricos

ctype_alnum

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

ctype_alnum — Chequear posibles caracteres alfanuméricos

Descripción

ctype_alnum ( string $text ) : bool

Chequea si todos los caracteres en la string entregada, texto, son alfanuméricos.

Parámetros

text

La cadena de prueba.

Valores devueltos

Devuelve true si cada caracter de texto es o bien uno letra o un dígito, false de lo contrario.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_alnum() (usando la localización predeterminada)

<?php
$cadenas = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($cadenas as $caso_prueba) {
    if (ctype_alnum($caso_prueba)) {
        echo "La cadena $caso_prueba consiste completamente de letras o dígitos.\n";
    } else {
        echo "La cadena $caso_prueba no consiste completamente de letras o dígitos.\n";
    }
}
?>

El resultado del ejemplo sería:

La cadena AbCd1zyZ9 consiste completamente de letras o dígitos.
La cadena foo!#$bar no consiste completamente de letras o dígitos.

Notas

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_alpha() - Chequear posibles caracteres alfabéticos
  • ctype_digit() - Chequear posibles caracteres numéricos
  • setlocale() - Establecer la información del localismo

User Contributed Notes

marcelocamargo at linuxmail dot org 04-Jan-2016 04:42
It is also important to note that the behavior of `ctype_alnum` differs according to the operating system. For UNIX-based operating system, if you pass a value that is not a string (or an overloaded object), independently of the value, it will always result in false. However, if we do the same on Windows, using, for example, -1 as literal (a minus and a number greater than 0), we'll have true as result.

<?php var_dump(ctype_alnum(-1));
// UNIX: bool(false)
// Windows: bool(true)
Anonymous 28-Jan-2013 05:12
Quicktip: If ctype is not enabled by default on your server, replace ctype_alnum($var) with preg_match('/^[a-zA-Z0-9]+$/', $var).
Rory 07-Dec-2009 04:42
Just for the record, Gentoo doesn't include this function by default. You'll have to recompile PHP with the "ctype" USE flag.
thinice at gmail dot com 22-Jul-2009 02:46
ctype_alnum() is a godsend for quick and easy username/data filtering when used in conjunction with str_replace().

Let's say your usernames have dash(-) and underscore(_) allowable and alphanumeric digits as well.

Instead of a regex you can trade a bit of performance for simplicity:

<?php
$sUser = 'my_username01';
$aValid = array('-', '_');

if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
    echo 'Your username is not properly formatted.';
}
?>


Chequear posibles caracteres alfabéticos

  • « ctype_alnum
  • ctype_cntrl »
  • PHP Manual
  • Funciones de Ctype
  • Chequear posibles caracteres alfabéticos

ctype_alpha

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

ctype_alpha — Chequear posibles caracteres alfabéticos

Descripción

ctype_alpha ( string $text ) : bool

Verifica si todos los caracteres en la string entregada,texto, son alfabéticos. En la localización C estándar las letras se limitan a [A-Za-z] y ctype_alpha() es equivalente a (ctype_upper($texto) || ctype_lower($texto)) si $texto es un caracter sencillo, aunque otros idiomas usan letras que no son consideradas como mayúsculas ni minúsculas.

Parámetros

text

El string de prueba.

Valores devueltos

Devuelve true si cada caracter de texto es una letra de la localización actual, false de lo contrario.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_alpha() (usando la localización predeterminada)

<?php
$cadenas = array('KjgWZC', 'arf12');
foreach ($cadenas as $caso_prueba) {
    if (ctype_alpha($caso_prueba)) {
        echo "La cadena $caso_prueba consiste completamente de letras.\n";
    } else {
        echo "La cadena $caso_prueba no consiste completamente de letras.\n";
    }
}
?>

El resultado del ejemplo sería:

La cadena KjgWZC consiste completamente de letras.
La cadena arf12 no consiste completamente de letras.

Notas

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_upper() - Chequear posibles caracteres en mayúscula
  • ctype_lower() - Chequear posibles caracteres en minúscula
  • setlocale() - Establecer la información del localismo

User Contributed Notes

Tyrunur 27-May-2009 02:12
It works if you set the locale correctly:

<?php

setLocale(LC_CTYPE, 'FR_fr.UTF-8');

?>

with this change you will get "yes" "yes"


Chequear posibles caracteres de control

  • « ctype_alpha
  • ctype_digit »
  • PHP Manual
  • Funciones de Ctype
  • Chequear posibles caracteres de control

ctype_cntrl

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

ctype_cntrl — Chequear posibles caracteres de control

Descripción

ctype_cntrl ( string $text ) : bool

Verifica si todos los caracteres en la string entregada, text, son caracteres de control. Los caracteres de control son, por ejemplo, la alimentación de línea, el tabulador, escape.

Parámetros

text

El string de prueba.

Valores devueltos

Devuelve true si cada caracter de texto es un caracter de control de la localización actual, false de lo contrario.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_cntrl()

<?php
$cadenas = array('cadena1' => "\n\r\t", 'cadena2' => 'arf12');
foreach ($cadenas as $nombre => $caso_prueba) {
    if (ctype_cntrl($caso_prueba)) {
        echo "La cadena '$nombre' consiste completamente de caracteres de control.\n";
    } else {
        echo "La cadena '$nombre' no consiste completamente de caracteres de control.\n";
    }
}
?>

El resultado del ejemplo sería:

La cadena 'cadena1' consiste completamente de caracteres de control.
La cadena 'cadena2' no consiste completamente de caracteres de control.

Notas

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_print() - Chequear posibles caracteres imprimibles

User Contributed Notes

Tor 09-Mar-2013 10:02
Returns true if bytes are in the range of \x00-\x1f or \x7f (del). Returns false if bytes are in the range of \x20-\x7e or \x80-\xff.


Chequear posibles caracteres numéricos

  • « ctype_cntrl
  • ctype_graph »
  • PHP Manual
  • Funciones de Ctype
  • Chequear posibles caracteres numéricos

ctype_digit

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

ctype_digit — Chequear posibles caracteres numéricos

Descripción

ctype_digit ( string $text ) : bool

Verifica si todos los caracteres en la string entregada, text, son numéricos.

Parámetros

text

La cadena probada.

Valores devueltos

Devuelve true si cada caracter del texto es un dígito decimal, o false de lo contrario.

Historial de cambios

Versión | Descripción
5.1.0 | En versiones anteriores a PHP 5.1.0, esta función devolvía true cuando text era una cadena vacía.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_digit()

<?php
$cadenas = array('1820.20', '10002', 'wsl!12');
foreach ($cadenas as $caso_prueba) {
    if (ctype_digit($caso_prueba)) {
        echo "La cadena $caso_prueba consiste completamente de dígitos.\n";
    } else {
        echo "La cadena $caso_prueba no consiste completamente de dígitos.\n";
    }
}
?>

El resultado del ejemplo sería:

La cadena 1820.20 no consiste completamente de dígitos.
La cadena 10002 consiste completamente de dígitos.
La cadena wsl!12 no consiste completamente de dígitos.

Ejemplo #2 Un ejemplo de ctype_digit() comparando strings con integers

<?php

$numeric_string = '42';
$integer        = 42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 es el caracter *)

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>

Notas

Nota:

Esta función espera un string para ser útil, por ejemplo si pasamos un integer no puede devolver el resultado esperado. Sin embargo, nótese también los formularios HTML resultarán en strings numéricos y no en integers. Ver también la sección del manual tipos.

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_alnum() - Chequear posibles caracteres alfanuméricos
  • ctype_xdigit() - Chequear posibles caracteres que representen un dígito hexadecimal
  • is_numeric() - Comprueba si una variable es un número o un string numérico
  • is_int() - Comprueba si el tipo de una variable es integer
  • is_string() - Comprueba si una variable es de tipo string

User Contributed Notes

divinity76 at gmail dot com 13-Feb-2021 08:54
an alternative if you want to check if it's a valid integer:

<?php
if(false!==filter_var($v, FILTER_VALIDATE_INT)){
    // it's a valid int!
    $v=(int)$v;
}else{
    // it's not a valid int
}
?>

or if you want to check that it's a positive integer (>= 0):
<?php
if(false!==filter_var($v, FILTER_VALIDATE_INT, ["options"=>["min_range"=>0]])){
    // it's a valid positive integer!
    $v = (int)$v;
}else{
    // it's not a valid positive integer
}

?>
brcontainer at yahoo dot com dot br 07-Oct-2018 03:00
ctype_digit don't support negative value in string:

<?php
var_dump( ctype_digit('-10') ); //return bool(false)
?>

Improved (and simplified) Tim Boormans code:

<?php
/**
 * Check input for existing only of digits (numbers)
 * @author Guilherme Nascimento <brcontainer@yahoo.com.br>
 * @param $digit
 * @return bool
 */
function is_digit($digit)
{
    return preg_match('#^-?\d+$#', $digit) && is_int((int) $digit);
}
zorrosNOSPAMwordsman at NOSPAM dot gmail dot com 11-May-2016 12:34
If you want to verify whether or not a variable contains only digits, you can type cast it to a string and back to int and see if the result is identical. Like so:

<?php

// (bool) TRUE if only digits, FALSE otherwise
$isOnlyDigits = (string) (int) $input === (string) $input;

?>

I haven't benchmarked it, but I'm guessing it's significantly faster then regular expressions.
smicheal2 at gmail dot com 07-Oct-2015 01:21
Please note that ctype_digit() will say true for strings such as '00001', which are not technically valid representations of integers, while saying false to strings such as '-1', which are. It's basically a faster version of the regex /^\d+$/. As the name says, it answers the question "does this string contain only digits" literally. It does not answer "is this a valid representation of an integer". If that's what you want, use is_int(filter_var($val, FILTER_VALIDATE_INT)) instead.
error17191 at gmail dot com 03-Oct-2015 01:41
I just wanted to clarify a flaw in the function is_digit() suggested by "info at directwebsolutions dot nl " ..
It returns true in case of negative integers and false in case of strings that contain negative integers .
 example:
is_digit(-10); // returns ture
is_digit('-10'); // returns false
rlerne at gmail dot com 25-Apr-2013 06:04
Interesting to note that you must pass a STRING to this function, other values won't be typecasted (I figured it would even though above explicitly says string $text).

I.E.

<?PHP
$val = 42; //Answer to life
$x = ctype_digit($val);
?>

Will return false, even though, when typecasted to string, it would be true.

<?PHP
$val = '42';
$x = ctype_digit($val);
?>

Returns True.

Could do this too:

<?PHP
$val = 42;
$x = ctype_digit((string) $val);
?>

Which will also return true, as it should.
info at directwebsolutions dot nl 19-May-2012 09:16
All basic PHP functions which i tried returned unexpected results. I would just like to check whether some variable only contains numbers. For example: when i spread my script to the public i cannot require users to only use numbers as string or as integer. For those situation i wrote my own function which handles all inconveniences of other functions and which is not depending on regular expressions. Some people strongly believe that regular functions slow down your script.

The reason to write this function:
1. is_numeric() accepts values like: +0123.45e6 (but you would expect it would not)
2. is_int() does not accept HTML form fields (like: 123) because they are treated as strings (like: "123").
3. ctype_digit() excepts all numbers to be strings (like: "123") and does not validate real integers (like: 123).
4. Probably some functions would parse a boolean (like: true or false) as 0 or 1 and validate it in that manner.

My function only accepts numbers regardless whether they are in string or in integer format.
<?php
    /**
     * Check input for existing only of digits (numbers)
     * @author Tim Boormans <info@directwebsolutions.nl>
     * @param $digit
     * @return bool
     */
    function is_digit($digit) {
        if(is_int($digit)) {
            return true;
        } elseif(is_string($digit)) {
            return ctype_digit($digit);
        } else {
            // booleans, floats and others
            return false;
        }
    }
?>
Skippy 25-Oct-2011 01:44
If you need to check for integers instead of just digits you can supply your own function such as this:

<?php
function ctype_int($text)
{
    return preg_match('/^-?[0-9]+$/', (string)$text) ? true : false;
}
?>
mdsky at web dot de 21-May-2010 12:44
is_numeric gives true by f. ex. 1e3 or 0xf5 too. So it's not the same as ctype_digit, which just gives true when only values from 0 to 9 are entered.
John Saman 05-Feb-2010 05:38
Using is_numeric function is quite faster than ctype_digit.

is_numeric took 0.237 Seconds for one million runs. while ctype_digit took 0.470 Seconds.
strrev xc tod noxeh ta ellij 14-Dec-2009 08:41
ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII '0'-'9') and false for the rest.

ctype_digit(5) -> false
ctype_digit(48) -> true
ctype_digit(255) -> false
ctype_digit(256) -> true

(Note: the PHP type must be an int; if you pass strings it works as expected)
Peter de Pijd 18-Jul-2009 03:53
Note that an empty string is also false:
ctype_digit("") // false
a_p_leeming at hotmail dot com 24-May-2009 06:17
Also note that

<?php ctype_digit("-1");   //false ?>
raul dot 3k at gmail dot com 09-Apr-2009 08:21
The ctype_digit can be used in a simple form to validate a field:
<?php
$field = $_POST["field"];
if(!ctype_digit($field)){
  echo "It's not a digit";
}
?>

Note:
Digits is 0-9


Chequear posibles caracteres imprimibles, con excepción de los espacios

  • « ctype_digit
  • ctype_lower »
  • PHP Manual
  • Funciones de Ctype
  • Chequear posibles caracteres imprimibles, con excepción de los espacios

ctype_graph

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

ctype_graph — Chequear posibles caracteres imprimibles, con excepción de los espacios

Descripción

ctype_graph ( string $text ) : bool

Verifica si todos los caracteres en la string entregada, text, generan una salida visible.

Parámetros

text

La cadena de prueba.

Valores devueltos

Devuelve true si cada caracter del texto es imprimible y genera alguna salida visible (no incluye los espacios), o false de lo contrario.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_graph()

<?php
$cadenas = array('cadena1' => "asdf\n\r\t", 'cadena2' => 'arf12', 'cadena3' => 'LKA#@%.54');
foreach ($cadenas as $nombre => $caso_prueba) {
    if (ctype_graph($caso_prueba)) {
        echo "La cadena '$nombre' consiste completamente de caracteres (visiblemente) imprimibles.\n";
    } else {
        echo "La cadena '$nombre' no consiste completamente de caracteres (visiblemente) imprimibles.\n";
    }
}
?>

El resultado del ejemplo sería:

La cadena 'cadena1' no consiste completamente de caracteres (visiblemente) imprimibles.
La cadena 'cadena2' consiste completamente de caracteres (visiblemente) imprimibles.
La cadena 'cadena3' consiste completamente de caracteres (visiblemente) imprimibles.

Notas

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_alnum() - Chequear posibles caracteres alfanuméricos
  • ctype_print() - Chequear posibles caracteres imprimibles
  • ctype_punct() - Chequear posibles caracteres imprimibles que no son ni espacios en blanco ni caracteres alfanuméricos

User Contributed Notes

There are no user contributed notes for this page.


Chequear posibles caracteres en minúscula

  • « ctype_graph
  • ctype_print »
  • PHP Manual
  • Funciones de Ctype
  • Chequear posibles caracteres en minúscula

ctype_lower

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

ctype_lower — Chequear posibles caracteres en minúscula

Descripción

ctype_lower ( string $text ) : bool

Verifica si todos los caracteres en la string entregada, text, son letras minúsculas.

Parámetros

text

La cadena de prueba.

Valores devueltos

Devuelve true si cada caracter del texto es una letra minúscula en la localidad actual.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_lower() (usando la localidad predeterminada)

<?php
$cadenas = array('aac123', 'qiutoas', 'QASsdks');
foreach ($cadenas as $caso_prueba) {
    if (ctype_lower($caso_prueba)) {
        echo "La cadena $caso_prueba consiste completamente de letras minúsculas.\n";
    } else {
        echo "La cadena $caso_prueba no consiste completamente de letras minúsculas.\n";
    }
}
?>

El resultado del ejemplo sería:

La cadena aac123 no consiste completamente de letras minúsculas.
La cadena qiutoas consiste completamente de letras minúsculas.
La cadena QASsdks no consiste completamente de letras minúsculas.

Notas

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_alpha() - Chequear posibles caracteres alfabéticos
  • ctype_upper() - Chequear posibles caracteres en mayúscula
  • setlocale() - Establecer la información del localismo

User Contributed Notes

There are no user contributed notes for this page.


Chequear posibles caracteres imprimibles

  • « ctype_lower
  • ctype_punct »
  • PHP Manual
  • Funciones de Ctype
  • Chequear posibles caracteres imprimibles

ctype_print

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

ctype_print — Chequear posibles caracteres imprimibles

Descripción

ctype_print ( string $text ) : bool

verifica si todos los caracteres en la string entregada, text, son imprimibles.

Parámetros

text

La cadena de prueba.

Valores devueltos

Devuelve true si cada caracter del texto genera realmente alguna salida (incluyendo los espacios). Devuelve false si el texto incluye caracteres de control o caracteres que no producen ninguna salida ni realizan función de control alguna después de todo.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_print()

<?php
$cadenas = array('cadena1' => "asdf\n\r\t", 'cadena2' => 'arf12', 'cadena3' => 'LKA#@%.54');
foreach ($cadenas as $nombre => $caso_prueba) {
    if (ctype_print($caso_prueba)) {
        echo "La cadena '$nombre' consiste completamente de caracteres imprimibles.\n";
    } else {
        echo "La cadena '$nombre' no consiste completamente de caracteres imprimibles.\n";
    }
}
?>

El resultado del ejemplo sería:

La cadena 'cadena1' no consiste completamente de caracteres imprimibles.
La cadena 'cadena2' consiste completamente de caracteres imprimibles.
La cadena 'cadena3' consiste completamente de caracteres imprimibles.

Notas

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_cntrl() - Chequear posibles caracteres de control
  • ctype_graph() - Chequear posibles caracteres imprimibles, con excepción de los espacios
  • ctype_punct() - Chequear posibles caracteres imprimibles que no son ni espacios en blanco ni caracteres alfanuméricos

User Contributed Notes

ClayDragon 02-Sep-2018 09:20
As mentioned above, only ASCII characters from 32 to 126 are considered printable, all others, including UTF-8 encoded characters are always considered unprintable, no matter what your locale settings are. Therefore, e.g. German "ä", the Euro sign "€" or the British pound symbol "£" will never be printable. If you need to check any characters for "printability" beyond the standard ASCII range, use a regular expression or write a specific function yourself.

See also this discussion: https://grokbase.com/t/php/php-i18n/102tkqe6rk/ctype-print-returns-false-for-british-pound-symbol-and-non-ascii-symbols
Anonymous 12-Jun-2012 05:59
Only ascii 32 thru 126 (inclusive) are considered printable. Tab (ascii 7), carriage return (ascii 13), linefeed (ascii 10) etc may produce output but are not considered printable.


Chequear posibles caracteres imprimibles que no son ni espacios en blanco ni caracteres alfanuméricos

  • « ctype_print
  • ctype_space »
  • PHP Manual
  • Funciones de Ctype
  • Chequear posibles caracteres imprimibles que no son ni espacios en blanco ni caracteres alfanuméricos

ctype_punct

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

ctype_punct — Chequear posibles caracteres imprimibles que no son ni espacios en blanco ni caracteres alfanuméricos

Descripción

ctype_punct ( string $text ) : bool

Verifica si todos los caracteres en la string entregada, text, son caracteres de puntuación.

Parámetros

text

La cadena de prueba.

Valores devueltos

Devuelve true si cada caracter del text es imprimible, pero no es una letra, dígito o espacio en blanco; o false de lo contrario.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_punct()

<?php
$cadenas = array('ABasdk!@!$#', '!@ # $', '*&$()');
foreach ($cadenas as $caso_prueba) {
    if (ctype_punct($caso_prueba)) {
        echo "La cadena $caso_prueba consiste completamente de signos de puntuación.\n";
    } else {
        echo "La cadena $caso_prueba no consiste completamente de signos de puntuación.\n";
    }
}
?>

El resultado del ejemplo sería:

La cadena ABasdk!@!$# no consiste completamente de signos de puntuación.
La cadena !@ # $ no consiste completamente de signos de puntuación.
La cadena *&$() consiste completamente de signos de puntuación.

Notas

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_cntrl() - Chequear posibles caracteres de control
  • ctype_graph() - Chequear posibles caracteres imprimibles, con excepción de los espacios

User Contributed Notes

There are no user contributed notes for this page.


Chequear posibles caracteres de espacio en blanco

  • « ctype_punct
  • ctype_upper »
  • PHP Manual
  • Funciones de Ctype
  • Chequear posibles caracteres de espacio en blanco

ctype_space

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

ctype_space — Chequear posibles caracteres de espacio en blanco

Descripción

ctype_space ( string $text ) : bool

Verifica si todos los caracteres en la string entregada, text, crean espacios en blanco.

Parámetros

text

El string de prueba.

Valores devueltos

Devuelve true si cada caracter del text genera cierto tipo de espacio en blanco, o false de lo contrario. Junto con el caracter regular de espacio en blanco, también se consideran espacios a los caracteres de tabulación, tabulación vertical, avance de línea, retorno de carro y avance de formulario.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_space()

<?php
$strings = array(
    'string1' => "\n\r\t",
    'string2' => "\narf12",
    'string3' => '\n\r\t' // note las comillas simples
);
foreach ($strings as $name => $testcase) {
    if (ctype_space($testcase)) {
        echo "The string '$name' consists of whitespace characters only.\n";
    } else {
        echo "The string '$name' contains non-whitespace characters.\n";
    }
}
?>

El resultado del ejemplo sería:

The string 'string1' consists of whitespace characters only.
The string 'string2' contains non-whitespace characters.
The string 'string3' contains non-whitespace characters.

Notas

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_cntrl() - Chequear posibles caracteres de control
  • ctype_graph() - Chequear posibles caracteres imprimibles, con excepción de los espacios
  • ctype_punct() - Chequear posibles caracteres imprimibles que no son ni espacios en blanco ni caracteres alfanuméricos

User Contributed Notes

vlabots at gmail dot com 18-Jun-2014 07:03
thanks to gardnerjohng, but a had some problems with non-breaking spaces in this function.

I added 2 more cases for this:
case 0xC2
case 0xA0

After this modification non-breaking spaces in my test code were successfully detected.
gardnerjohng at hotmail dot com 14-Sep-2009 09:00
A function I wrote last night was fairly flexible in terms of detecting whitespace, and even took into account the pesky non-breaking spaces / zero-width spaces further up the Unicode alphabet.

The benefit here was being able to isolate and identify specific Unicode indices based on their subrange.

<?php
    //    Returns TRUE if the ASCII value of $string matches a registered whitespace character.
    //    *    This includes non-breaking spaces, zero-width spaces, and any unicode values below 32.
    //    *    $string: Character to identify. If string extends past one character, the value
    //        is truncated and only the initial character is examined.
    function is_whitespace($string){
        //    Return FALSE if passed an empty string.
        if($string == "") return FALSE;

        $char    =    ord($string);

        //    Control Characters
        if($char < 33)                        return TRUE;
        if($char > 8191 && $char < 8208)    return TRUE;
        if($char > 8231 && $char < 8240)    return TRUE;

        //    Additional Characters
        switch($char){
            case 160:    // Non-Breaking Space
            case 8287:    // Medium Mathematical Space
                return TRUE;
                break;
        }
        return FALSE;
    }
?>


Chequear posibles caracteres en mayúscula

  • « ctype_space
  • ctype_xdigit »
  • PHP Manual
  • Funciones de Ctype
  • Chequear posibles caracteres en mayúscula

ctype_upper

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

ctype_upper — Chequear posibles caracteres en mayúscula

Descripción

ctype_upper ( string $text ) : bool

Verifica si todos los caracteres en la string entregada, text, son caracteres en mayúsculas.

Parámetros

text

La cadena de prueba.

Valores devueltos

Devuelve true si cada caracter del text es una letra mayúscula en la localidad actual.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_upper() (usando la localidad predeterminada)

<?php
$cadenas = array('AKLWC139', 'LMNSDO', 'akwSKWsm');
foreach ($cadenas as $caso_prueba) {
    if (ctype_upper($caso_prueba)) {
        echo "La cadena $caso_prueba consiste completamente de letras mayúsculas.\n";
    } else {
        echo "La cadena $caso_prueba no consiste completamente de letras mayúsculas.\n";
    }
}
?>

El resultado del ejemplo sería:

La cadena AKLWC139 no consiste completamente de signos de letras mayúsculas.
La cadena LMNSDO consiste completamente de signos de letras mayúsculas.
La cadena akwSKWsm no consiste completamente de signos de letras mayúsculas.

Notas

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_alpha() - Chequear posibles caracteres alfabéticos
  • ctype_lower() - Chequear posibles caracteres en minúscula
  • setlocale() - Establecer la información del localismo

User Contributed Notes

Anonymous 06-Jan-2016 07:25
// after screwing around with function.ctype-upper
// I found this simple solution

if (strtolower($string) != $string)// its so simple!
{
  echo "uppercase letters found in $string";
}

source: http://stackoverflow.com/questions/4426327/how-to-detect-if-string-contains-1-uppercase-letter-in-php
chris at theothernews dot co dot nz 11-Jun-2014 02:32
Underscores in the string will result in false, so you have to remove them first.


Chequear posibles caracteres que representen un dígito hexadecimal

  • « ctype_upper
  • Filter »
  • PHP Manual
  • Funciones de Ctype
  • Chequear posibles caracteres que representen un dígito hexadecimal

ctype_xdigit

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

ctype_xdigit — Chequear posibles caracteres que representen un dígito hexadecimal

Descripción

ctype_xdigit ( string $text ) : bool

Verifica si todos los caracteres de la string entregada, text, son 'dígitos' hexadecimales.

Parámetros

text

La cadena de prueba.

Valores devueltos

Devuelve true si cada caracter del text es un 'dígito' hexadecimal, lo que quiere decir un dígito decimal o un caracter del rango [A-Fa-f]; false de lo contrario.

Ejemplos

Ejemplo #1 Un ejemplo de ctype_xdigit()

<?php
$cadenas = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($cadenas as $caso_prueba) {
    if (ctype_xdigit($caso_prueba)) {
        echo "La cadena $caso_prueba consiste completamente de dígitos hexadecimales.\n";
    } else {
        echo "La cadena $caso_prueba no consiste completamente de dígitos hexadecimales.\n";
    }
}
?>

El resultado del ejemplo sería:

La cadena AB10BC99 consiste completamente de dígitos hexadecimales.
La cadena AR1012 no consiste completamente de dígitos hexadecimales.
La cadena ab12bc99 consiste completamente de dígitos hexadecimales.

Notas

Nota:

Si se proporciona un integer entre -128 y 255 inclusive, se interpreta como el valor ASCII de un simple caráter (a los valores negativos se le añade 256 para permitir caracteres en el rango ASCII Extendido). Cualquier otro entero se interpreta como una cadena que contiene los dígitos decimales del entero.

Ver también

  • ctype_digit() - Chequear posibles caracteres numéricos

User Contributed Notes

tom at hgmail dot com 14-Jan-2006 12:36
This function shows its usefulness on a web site where a user is asked to entered a hexidecimal color code for a color. To prevent breaking W3C standard and having them enter in "neon-green" or the wrong type of code like 355511235.

In conjunction with strlen()  you could create a function like this:

function check_valid_colorhex($colorCode) {
    // If user accidentally passed along the # sign, strip it off
    $colorCode = ltrim($colorCode, '#');

    if (
          ctype_xdigit($colorCode) &&
          (strlen($colorCode) == 6 || strlen($colorCode) == 3))
               return true;

    else return false;
}


Filtrado de datos

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Tipos de filtros
    • Filtros de validación
    • Filtros de saneamiento
    • Otros filtros
    • Opciones de filtrado
  • Constantes predefinidas
  • Ejemplos
    • Validación
    • Saneamiento
  • Funciones de Filter
    • filter_has_var — Comprueba si existe una variable de un tipo concreto existe
    • filter_id — Indica el ID del nombre de filtro que se indique
    • filter_input_array — Obtiene variables externas y opcionalmente las filtra
    • filter_input — Toma una variable externa concreta por su nombre y opcionalmente la filtra
    • filter_list — Devuelve una lista de todos los filtros soportados
    • filter_var_array — Retorna múltiple variables y opcionalmente las filtra
    • filter_var — Filtra una variable con el filtro que se indique

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Esta extensión filtra los datos bien sea para validarlos o para sanearlos. Es especialmente útil cuando los datos de origen contienen datos desconocidos (o externos), como entradas facilitadas por el usuario. Por ejemplo, estos datos pueden venir de un formulario HTML.

Principalmente hay dos tipos de filtrado: validación y saneamiento.

La validación se usa para validar o comprobar si los datos cumplen ciertos requisitos. Por ejemplo, pasándole FILTER_VALIDATE_EMAIL determinará si los datos son una dirección de correo válida, pero no realizará ningún cambio en los datos.

El saneamiento limpiará los datos, de modo que los modificará eliminando los caracteres no deseados. Por ejemplo, pasándole FILTER_SANITIZE_EMAIL eliminará los caracteres que no son apropiados para una dirección de correo electrónico. Sin embargo, no valida los datos.

Las banderas se usan opcionalmente tanto con la validación como con el saneamiento para adaptar el comportamiento según las necesidades. Por ejemplo, al pasarle FILTER_FLAG_PATH_REQUIRED mientras se filtra un URL, se obliga a que esté presente una ruta (como /foo en http://example.org/foo).

User Contributed Notes

There are no user contributed notes for this page.


Instalación

La extensión de filtrado está activada por defecto desde PHP 5.2.0. Anteriormente a esto se usaba una extensión PECL, sin embargo, esta extensión no se actualiza más ni se recomienda su uso.

User Contributed Notes

There are no user contributed notes for this page.


Configuración en tiempo de ejecución

El comportamiento de estas funciones se ve afectado por la configuración de php.ini.

Opciones de configuración de filtros
Nombre | Por defecto | Cambiable | Historial de cambios
filter.default | "unsafe_raw" | PHP_INI_PERDIR | PHP_INI_ALL en filter <= 0.9.4. Disponible desde PHP 5.2.0.
filter.default_flags | NULL | PHP_INI_PERDIR | PHP_INI_ALL en filter <= 0.9.4. Disponible desde PHP 5.2.0.
Para más detalles y definiciones de los modos de PHP_INI_*, vea Dónde se puede realizar un ajuste de configuración.

He aquí una breve explicación de las directivas de configuración.

filter.default string

Filtra todos los datos de $_GET, $_POST, $_COOKIE, $_REQUEST y $_SERVER. Es posible acceder a los datos originales a través de filter_input().

Acepta el nombre del filtro que se desea usar por defecto. Véase la lista de filtros existentes para obtener el nombre de los filtros disponibles.

Nota:

Tenga cuidado con los flags por omisión para los filtros predeterminados. De forma explícita debería establecerse en el valor que desee. Por ejemplo, para configurar el filtro predeterminado para que se comporte exactamente igual que htmlspecialchars() necesita establecer los flags por omisión a 0, como se muestra a continuación.

Ejemplo #1 Configuring the default filter to act like htmlspecialchars

filter.default = full_special_chars
filter.default_flags = 0

filter.default_flags integer

Flags por omisión a aplicar cuando el filtro por defecto está establecido. Esto es establecido a FILTER_FLAG_NO_ENCODE_QUOTES por omisión por razones de compatibilidad con versiones anteriores. Véase la lista de flags existentes para una lista de todos los nombres de flags.

User Contributed Notes

warbaby67 at gmail dot com 14-Dec-2010 10:04
filter.default sets the default FILTER by name.
filter.default_flags sets default FLAGS for the default filter.

The values for filter.default should be a string "name" of a valid FILTER:

"int"      FILTER_VALIDATE_INT
"boolean"  FILTER_VALIDATE_BOOLEAN

The irony of the entire list I typed being blocked by the SPAM filter is not lost on me.  Perhaps I'm not the first.


Tipos de filtros

Tabla de contenidos

  • Filtros de validación
  • Filtros de saneamiento
  • Otros filtros
  • Opciones de filtrado

User Contributed Notes

There are no user contributed notes for this page.


Filtros de validación

Listado de filtros para validación
ID | Nombre | Opciones | Banderas | Descripción
FILTER_VALIDATE_BOOLEAN | "boolean" | default | FILTER_NULL_ON_FAILURE | Devuelve true para "1", "true", "on" y "yes". Devuelve false en caso contrario. Si FILTER_NULL_ON_FAILURE está declarado, se devolverá false sólo para "0", "false", "off", "no", y "", y null para cualquier valor no booleano.
FILTER_VALIDATE_EMAIL | "validate_email" | default |  | Valida una dirección de correo electrónico. En general, se valildan direcciones de correo electrónico con la sintaxis de RFC 822, con la excepción de no admitir el plegamiento de comentarios y espacios en blanco.
FILTER_VALIDATE_FLOAT | "float" | default, decimal | FILTER_FLAG_ALLOW_THOUSAND | Valida si el valor es un float.
FILTER_VALIDATE_INT | "int" | default, min_range, max_range | FILTER_FLAG_ALLOW_OCTAL, FILTER_FLAG_ALLOW_HEX | Valida un valor como integer, opcionalmente desde el rango especificado, y lo convierte a int en case de éxito.
FILTER_VALIDATE_IP | "validate_ip" | default | FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE | Valida si es valor es una dirección IP, opcionalmente se puede indicar que sea sólo IPv4 o IPv6 o que no sea de rangos privados o reservados.
FILTER_VALIDATE_MAC | "validate_mac_address" | default |  | Valida una dirección MAC.
FILTER_VALIDATE_REGEXP | "validate_regexp" | default, regexp |  | Valida el valor contra regexp, una expresión regular Perl-compatible.
FILTER_VALIDATE_URL | "validate_url" | default | FILTER_FLAG_PATH_REQUIRED, FILTER_FLAG_QUERY_REQUIRED | Valida si su valor es una URL (de acuerdo con » http://www.faqs.org/rfcs/rfc2396), opcionalmente con componentes necesarios. Se ha de tener cuidado ya que un URL válida podría no especificar el protocolo HTTP http://, por lo que podrían ser necesarias validaciones posteriores para determinar que el URL utiliza un protocolo esperado, p.ej., ssh:// o mailto:. Nótese que esta función sólo buscará para ser validadas URLs ASCII; los nombres de dominio internacionales (que contienen no-ASCII caracteres) fallarán en la validación.

Nota:

A partir de PHP 5.4.11, los números +0 y -0 se validan tanto como integer y como float (empleando FILTER_VALIDATE_FLOAT y FILTER_VALIDATE_INT). Antes de PHP 5.4.11 solamente se validaban como float (empleando FILTER_VALIDATE_FLOAT).

Cuando default está establecido a option, se utilizará el valor de default si el valor no es validado.

Historial de cambios

Versión | Descripción
5.5.0 | Se añadió FILTER_VALIDATE_MAC

User Contributed Notes

andrew dot purkett at gmail dot com 13-May-2020 05:20
Please note that the FILTER_FLAG_NO_PRIV_RANGE flag does not exclude IPv4 private addresses in the IPv6 namespace, such as ::ffff:169.254.169.254.
carlosv775 at gmail dot com 05-May-2020 07:47
Looks like FILTER_VALIDATE_DOMAIN isn't available on PHP < 7:

https://3v4l.org/eOPLM
MR Yekta 02-Apr-2020 10:17
since php 7.4
you can use these 3 beautiful conditions for from validation for validation less, great or in range

<?php
/**
 * less_than_equal_to
 */
$x = 50;
if (filter_var($x, FILTER_VALIDATE_FLOAT, ["options" => ["max_range" => 100]]) !== false) {
    echo "result : $x is less than OR equal to 100";
} else {
    echo "result : $x is NOT less than OR equal to 100";
}
?>
result : 50 is less than OR equal to 100

<?php
/**
 * greater_than_equal_to
 */
$x = 50;
if (filter_var($x, FILTER_VALIDATE_FLOAT, ["options" => ["min_range" => 100]]) !== false) {
    echo "result : $x is greater than OR equal to 100";
} else {
    echo "result : $x is NOT greater than OR equal to 100";
}
?>
result : 50 is NOT greater than OR equal to 100

<?php
/**
 * less_than_equal_to && greater_than_equal_to
 */
$x = 50;
if (filter_var($x, FILTER_VALIDATE_FLOAT, ["options" => ["min_range" => 0 , "max_range"=> 100]]) !== false) {
    echo "result : $x is in range of 0 to 100";
} else {
    echo "result : $x in NOT range of 0 to 100";
}
?>
result : 50 is in range of 0 to 100
Vee W. 12-Aug-2019 10:09
`FILTER_FLAG_EMAIL_UNICODE` was added in PHP 7.1
gee2711 at googlemail dot com 30-Jan-2018 06:36
FILTER_FLAG_QUERY_REQUIRED is failing URLs that are encoded e.g.

http://example.com/page.php?q=growing+big

Fails whilst

http://example.com/page.php?q=big

So anything more than one word encoded fails.

Tested on PHP version 7.1
luca at accomazzi dot net 04-May-2017 02:47
A word to the wise regarding floats.

$t = '312041.25 &euro; instead of 896.70 &euro;';
echo filter_var ($t, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

will return
312041.25896.70
which is likely not what you were expecting. In 2007 someone suggested it's not acceptable (see https://bugs.php.net/bug.php?id=40156&edit=2) but it was flagged "not a bug" because these kind of filters are only supposed to filter out illegal characters.
Of course if you were to use FILTER_VALIDATE_FLOAT it would just return that the input is not valid.
kizge 30-Jun-2016 08:18
FILTER_VALIDATE_INT first casts its value to string which produces unexpected result for bool and float (https://bugs.php.net/bug.php?id=72490):

<?php

// Prints int(1).
var_dump(filter_var(true, FILTER_VALIDATE_INT));

// ...but this prints bool(false).
var_dump(filter_var(false, FILTER_VALIDATE_INT));

// --------

// Prints bool(false).
var_dump(filter_var(1.1, FILTER_VALIDATE_INT));

// ...but this prints int(0).
var_dump(filter_var(0.0, FILTER_VALIDATE_INT));

// ...but this again is bool(false).
var_dump(filter_var('0.0', FILTER_VALIDATE_INT));

// Also bool(false).
var_dump(filter_var('-0.0', FILTER_VALIDATE_INT));

?>

Live sample: https://3v4l.org/CZW0W

The docs are not clear on how exactly this casting affects the result for certain input values.
sebastian dot piskorski at gmail dot com 05-Jan-2016 12:48
FILTER_VALIDATE_EMAIL not only doesn't support whitespace folding and comments. It only checks Addr-spec part of email address. Otherwise it should mark such address as valid: 'Test Example <test@example.com>' because it is valid according to RFC 822.

Also address "test@localhost" should be valid. Which is mentioned in another note.

You can test it with this code:
<?php

$emails = array(
    'Test Example <test@example.com>',
    'test@localhost',
    'test@localhost.com'
);

foreach ($emails as $email) {
    echo (filter_var($email, FILTER_VALIDATE_EMAIL)) ?
        "[+] Email '$email' is valid\n" :
        "[-] Email '$email' is NOT valid\n";
}
?>

Output for PHP 5.3.21 - 7.0.1 :
[-] Email 'Test Example <test@example.com>' is NOT valid
[-] Email 'test@localhost' is NOT valid
[+] Email 'test@localhost.com' is valid
rsnell at usgs dot gov 25-Nov-2015 05:18
Note that if using FILTER_NULL_ON_FAILURE as a flag with the FILTER_VALIDATE_BOOLEAN id then NULL is no longer returned if the variable name is not set in the external variable array. It will instead return FALSE. In the description is says that when using the FILTER_NULL_ON_FAILURE flag that ' FALSE is returned only for "0", "false", "off", "no", and ""' an makes no mention of this additional state that can also return false. The behavior is mentioned on the filter_input documentation page under Return Values but that is not overly helpful if one is just looking here.

If FILTER_NULL_ON_FAILURE is not used then NULL is returned when the variable name is not set in the external variable array, TRUE is returned for "1", "true", "on" and "yes" and FALSE is returned for everything else.
Lech 05-Sep-2015 08:41
The description for FILTER_VALIDATE_URL seems incorrect/misleading. "Beware a valid URL may not specify the HTTP protocol" implies a valid URL cannot specify the HTTP protocol. I think "Beware a valid URL need not specify..." would be better.
Wrinkled Cheese 09-Jun-2015 03:33
When validating a URL, as documented, the protocol is not validated.  However, it is required to be present.

For example:

I don't expect a protocol to be present.  To validate expected input I have to add a "protocol" as a prefix, and return true or false, and further validate the input.

$r = filter_var(''this.doesnt.matter.so.why.is.it.required://'.$host, FILTER_VALIDATE_URL);
return ($r != '' && $r !== false) ? true : false;
Darth Killer 02-Jun-2015 08:54
Contrary to what documentation implies, the FILTER_NULL_ON_FAILURE seem to affect any validation filter, not just FILTER_VALIDATE_BOOLEAN. I've been using that since PHP 5.2, and as of PHP 5.6.8 it still works. I have no clue if it's a blug or if it is as intended, in which case the documentation needs to be fixed.

When the flag is used on a validation filter other than FILTER_VALIDATE_BOOLEAN, as expected the filter will return NULL instead of FALSE upon failure. This is quite useful when filtering a POST form with filter_input_array(), where you don't want to check what field is invalid and what field is missing. Just check if NULL is among the returned elements and you're done.

<?php
$definition = array(
   'login' => array(
      'filter' => FILTER_VALIDATE_STRING,
      'flags' => FILTER_NULL_ON_FAILURE
   ),
   'pwd' => FILTER_UNSAFE_RAW
);
$form_data = filter_input_array(INPUT_POST, $definition);
if(in_array(null, $form_data, true)) {
   // invalid form
} else {
   // valid form, let's proceed
}
?>

Of course, if you want more precise error messages that approach won't work. But it's still good to know, i believe.
Luuk 25-May-2015 10:23
@2:
$value = " 0 ";
$filtered = filter_var($value, FILTER_VALIDATE_INT);
if($filtered || $filtered === 0)
{
    // validated as an int
}

I think next code is better:

$value = "0";
if(filter_var($value, FILTER_VALIDATE_INT) !== false)
{
  .....
Anonymous 22-May-2015 08:02
FILTER_VALIDATE_FLOAT, decimal option mean decimal notation['.', ','].
maruerru at gmail dot com 26-Mar-2015 11:09
Often I see some code like the following:
$value = "12";
if( filter_var($value, FILTER_VALIDATE_INT) )
{
    // validated as an int
}

The above works as intended, except when $value is "0". In the above case it will be interpreted as FALSE.

For the correct behavior,  you have not only to check if it is equal (==) to false, but also identic (===) to FALSE:
$value = " 0 ";
if( filter_var($value, FILTER_VALIDATE_INT)  === FALSE )
{
    // validated as an int
}

I hope, I could help.
bryanwayb at gmail dot com 22-Mar-2015 04:18
It's good to remember that using filter_var is primarily for filtering input values when doing boolean logic comparisons. Take the following:

$value = "12";
if(filter_var($value, FILTER_VALIDATE_INT))
{
    // validated as an int
}

The above works as intended, except when $value = "0". In which case filter_var returns a 0, aka false when used as a boolean.

For the correct behavior, do a zero check.

$value = " 0 ";
$filtered = filter_var($value, FILTER_VALIDATE_INT);
if($filtered || $filtered === 0)
{
    // validated as an int
}
Bastien 24-Sep-2013 08:05
Rejection of so-called partial domains because of "missing" dot is not following section 2.3.5 of RFC 5321.

It says FQDNs are permitted, and com, org, or va are (well, may be) valids FQDNs. It depends on DNS, not on syntax.

Some TDLs (although few of them) have MX RRs, the for example "abuse@va" is correct.
rowan dot collins at gmail dot com 17-Mar-2013 08:22
Regarding "partial" addresses with no . in the domain part, a comment in the source code (in ext/filter/logical_filters.c) justifies this rejection thus:

     * The regex below is based on a regex by Michael Rushton.
     * However, it is not identical.  I changed it to only consider routeable
     * addresses as valid.  Michael's regex considers a@b a valid address
     * which conflicts with section 2.3.5 of RFC 5321 which states that:
     *
     *   Only resolvable, fully-qualified domain names (FQDNs) are permitted
     *   when domain names are used in SMTP.  In other words, names that can
     *   be resolved to MX RRs or address (i.e., A or AAAA) RRs (as discussed
     *   in Section 5) are permitted, as are CNAME RRs whose targets can be
     *   resolved, in turn, to MX or address RRs.  Local nicknames or
     *   unqualified names MUST NOT be used.
boy at relaxnow dot nl 19-Oct-2012 02:06
FILTER_VALIDATE_URL does not work with URNs, examples of valid URIs according to RFC3986 and if they are accepted by FILTER_VALIDATE_URL:

[PASS] ftp://ftp.is.co.za.example.org/rfc/rfc1808.txt
[PASS] gopher://spinaltap.micro.umn.example.edu/00/Weather/California/Los%20Angeles
[PASS] http://www.math.uio.no.example.net/faq/compression-faq/part1.html
[PASS] mailto:mduerst@ifi.unizh.example.gov
[PASS] news:comp.infosystems.www.servers.unix
[PASS] telnet://melvyl.ucop.example.edu/
[PASS] http://www.ietf.org/rfc/rfc2396.txt
[PASS] ldap://[2001:db8::7]/c=GB?objectClass?one
[PASS] mailto:John.Doe@example.com
[PASS] news:comp.infosystems.www.servers.unix
[FAIL] tel:+1-816-555-1212
[PASS] telnet://192.0.2.16:80/
[FAIL] urn:oasis:names:specification:docbook:dtd:xml:4.1.2
bee kay two at em ee dot com 06-May-2012 04:45
Notably missing is a way to validate text entry as printable,
printable multiline,
or printable and safe (tag free)

FILTER_VALIDATE_TEXT, which validates no special characters
perhaps with FILTER_FLAG_ALLOW_NEWLINE
and FILTER_FLAG_NOTAG to disallow tag starters
php at sethsyberg dot com 07-Apr-2011 01:00
When validating floats, you must use the Identical/Not identical operators for proper validation of zeros:

This will not work as expected:
<?php
$x = 0;
if (!filter_var($x, FILTER_VALIDATE_FLOAT)) {
    echo "$x is a valid float";
} else {
    echo "$x is NOT a valid float";
}
?>

This will work as expected:
<?php
$x = 0;
if (filter_var($x, FILTER_VALIDATE_FLOAT)!== false) {
    echo "$x is a valid float";
} else {
    echo "$x is NOT a valid float";
}
?>
php dot net at piskvor dot org 11-Feb-2011 08:57
FILTER_VALIDATE_EMAIL is discarding valid e-mail addresses containing IDN. Since there are real, live IDNs on the Internet, that means the filtered output is too strict, leading to false negatives.

Punycode-encoded IDN addresses pass the filter correctly; so before checking for validity, it is necessary to convert the e-mail address to punycode.
Clifton 05-Jan-2011 08:00
FILTER_VALIDATE_EMAIL does NOT allow incomplete e-mail addresses to be validated as mentioned by Tomas.

Using the following code:

<?php
$email = "clifton@example"; //Note the .com missing
echo "PHP Version: ".phpversion().'<br>';
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo $email.'<br>';
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}else{
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}
?>

Returns:
PHP Version: 5.2.14 //On MY server, may be different depending on which version you have installed.
bool(false)

While the following code:

<?php
$email = "clifton@example.com"; //Note the .com added
echo "PHP Version: ".phpversion().'<br>';
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo $email.'<br>';
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}else{
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}
?>

Returns:
PHP Version: 5.2.14 //On MY server, may be different depending on which version you have installed.
clifton@example.com
string(16) "clifton@example.com"

This feature is only available for PHP Versions (PHP 5 >= 5.2.0) according to documentation. So make sure your version is correct.

Cheers,
Clifton


Filtros de saneamiento

Lista de filtros de saneamiento
ID | Nombre | Banderas | Descripción
FILTER_SANITIZE_EMAIL | "email" |  | Elimina todos los caracteres menos letras, dígitos y !#$%&'*+-=?^_`{|}~@.[].
FILTER_SANITIZE_ENCODED | "encoded" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH | String URL-encode, opcionalmente elimina o codifica caracteres especiales.
FILTER_SANITIZE_MAGIC_QUOTES | "magic_quotes" |  | Aplica addslashes().
FILTER_SANITIZE_NUMBER_FLOAT | "number_float" | FILTER_FLAG_ALLOW_FRACTION, FILTER_FLAG_ALLOW_THOUSAND, FILTER_FLAG_ALLOW_SCIENTIFIC | Elimina todos los caracteres a excepción de los dígitos, +- y, opcionalmente, .,eE.
FILTER_SANITIZE_NUMBER_INT | "number_int" |  | Elimina todos los caracteres excepto dígitos y los signos de suma y resta.
FILTER_SANITIZE_SPECIAL_CHARS | "special_chars" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_HIGH | Escapa caracteres HTML '"<>& y caracteres con valores ASCII menores que 32, opcionalmente elimina o codifica caracteres especiales.
FILTER_SANITIZE_FULL_SPECIAL_CHARS | "full_special_chars" | FILTER_FLAG_NO_ENCODE_QUOTES, | Equivalente a llamar a htmlspecialchars() con ENT_QUOTES establecido. Las comillas de codificación pueden ser desactivadas mediante el establecimiento de FILTER_FLAG_NO_ENCODE_QUOTES. Al igual que htmlspecialchars(), este filtro tiene en cuenta el default_charset y si en una secuencia de bytes se detecta que contiene un carácter no válido en el conjunto de caracteres actual entonces el string completo es rechazado lo que resulta en un string de longitud 0. Cuando se utiliza este filtro como un filtro predeterminado, vea la advertiencia de abajo sobre establecer las banderas predeterminadas a 0.
FILTER_SANITIZE_STRING | "string" | FILTER_FLAG_NO_ENCODE_QUOTES, FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Elimina etiquetas, opcionalmente elimina o codifica caracteres especiales.
FILTER_SANITIZE_STRIPPED | "stripped" |  | Alias del filtro "string".
FILTER_SANITIZE_URL | "url" |  | Elimina todos los caracteres excepto letras, dígitos y $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=.
FILTER_UNSAFE_RAW | "unsafe_raw" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | No hace nada, opcionalmente eliminar o codificar caracteres. Este filtro es un alias de FILTER_DEFAULT.

Advertencia

Cuando se utiliza uno de estos tres filtros como un filtro predetermindo a través de fichero ini o de la configuración del servidor web, las banderas predeterminadas son establecidas a FILTER_FLAG_NO_ENCODE_QUOTES. Se necesita establecer explícitamente filter.default_flags a 0 para tener la codificación de comillas por omisión. Como esto:

Ejemplo #1 Configurar el filtro predeterminado para que actúe como htmlspecialchars

filter.default = full_special_chars
filter.default_flags = 0

Historial de cambios

Versión | Descripción
5.2.11/5.3.1 | Las barras (/) son eliminadas por FILTER_SANITIZE_EMAIL. Antes se mantenían.

User Contributed Notes

ipse at sergiosantos dot me 02-Dec-2020 04:49
Although it's specifically mentioned in the above documentation, because many seem to find this unintuitive it's worth pointing out that FILTER_SANITIZE_NUMBER_FLOAT will remove the decimal character unless you specify FILTER_FLAG_ALLOW_FRACTION:

<?php
$number_string = '12.34';

echo filter_var( $number_string, FILTER_SANITIZE_NUMBER_FLOAT ); // 1234

echo filter_var( $number_string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ); // 12.34
?>
Anonymous 20-Jul-2020 05:29
<?php
 /*
     filter all ascii and save juste 0-9 a-Z and @ . _
*/

echo alphanum('abcdefghABCDEFGH0123456789/!:;@._');
// return abcdefghABCDEFGH0123456789@._

function alphanum( $string , $x=''){
        $h=strlen($string);
        for($a=0; $a<$h; $a++) {
            $i = ord($string[$a]);
            if(
                ($i==46) || // .
                ($i==64) || // @
                ($i==95) || // _
                ($i > 47 && $i < 58) || //0123456789
                ($i > 64 && $i < 91) || //ABCDEFGH..Z
                ($i > 96 && $i < 123)   //abcdefgh..z
             ) { $x .= $string[$a]; }
        }
        return $x;
    }

?>
Rodrigo Guariento 13-Feb-2020 11:55
To get ONLY numbers from a string use this code:
    echo preg_replace('/[^0-9]/', '', '123456-789');
anonymous 31-Jan-2020 12:55
In the "FILTER_SANITIZE_URL" section where it says, "Remove all characters except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=." is there a reason why there is a double backslash (\\)? Shouldn't there only be one backslash if it's saying that backslashes are allowed?
darren at daz-web dot com 12-Nov-2018 12:31
For those looking for a simple way around filtering POST forms that have textarea elements in them. If you also need tab for example you can extend quite easily.

<?php
//create an array of all relevant textareas
$textareas = array("ta1");

foreach($_POST as $k => $v)
    {
        $v = trim($v);//so we are sure it is whitespace free at both ends

        //preserve newline for textarea answers
        if(in_array($k,$textareas))$v=str_replace("\n","[NEWLINE]",$v);

        //sanitise string
        $v = filter_var($v, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_BACKTICK);

        //now replace the placeholder with the original newline
        $_POST[$k] = str_replace("[NEWLINE]","\n",$v);
    }

//simple form for testing submital

?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Filter test</title>
</head>

<body>

<form action="" method="post">
    <p>
        <textarea name="ta1" cols="30" rows="10"><?php echo $_POST['ta1']; ?></textarea>
    </p>
    <p>
        <input type="text" name="txt1" size="30" value="<?php echo $_POST['txt1']; ?>" />
    </p>
    <p>
        <input type="submit" />
    </p>
    </form>

</body>

</html>
AntonioPrimera 04-Aug-2016 01:12
Please be aware that when using filter_var() with FILTER_SANITIZE_NUMBER_FLOAT and FILTER_SANITIZE_NUMBER_INT the result will be a string, even if the input value is actually a float or an int.

Use FILTER_VALIDATE_FLOAT and FILTER_VALIDATE_INT, which will convert the result to the expected type.
Ruth 03-Jun-2016 02:59
This is an example for a form having a group of checkboxes besides a lot of other inputs:

$args = array(
    'details' => array(
        'name' => 'details[]',
        'filter' => FILTER_SANITIZE_STRING,
        'flags'  => FILTER_REQUIRE_ARRAY
    )
    // ,
    // a lot of other stuff here (all the form’s elements)
);
$myInputs = filter_input_array( INPUT_GET, $args, true );

where the checkboxes are (their form is in a page that reloads itself):

<label>
    <input type="checkbox" name="details[]" value=“A” <?php if (in_array( “A”, $myInputs['details'] )) { echo 'checked'; } ?>>
    Show A
</label>
<label>
    <input type="checkbox" name="details[]" value=“B” <?php if (in_array( “B”, $myInputs['details'] )) { echo 'checked'; } ?>>
    Show B
</label>
<label>
    <input type="checkbox" name="details[]" value=“C” <?php if (in_array( “C”, $myInputs['details'] )) { echo 'checked'; } ?>>
    Show C
</label>
<label>
    <input type="checkbox" name="details[]" value=“D” <?php if (in_array( “D”, $myInputs['details'] )) { echo 'checked'; } ?>>
    Show D
</label>
Willscrlt 10-Mar-2016 10:11
To include multiple flags, simply separate the flags with vertical pipe symbols.

For example, if you want to use filter_var() to sanitize $string with FILTER_SANITIZE_STRING and pass in FILTER_FLAG_STRIP_HIGH and FILTER_FLAG_STRIP_LOW, just call it like this:

$string = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW);

The same goes for passing a flags field in an options array in the case of using callbacks.

$var = filter_var($string, FILTER_SANITIZE_SPECIAL_CHARS,
array('flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_ENCODE_HIGH));

Thanks to the Brain Goo blog at popmartian.com/tipsntricks/for this info.
Anonymous 22-Oct-2015 03:56
FILTER_SANITIZE_STRING doesn't behavior the same as strip_tags function.    strip_tags allows less than symbol inferred from context, FILTER_SANITIZE_STRING strips regardless.
<?php
$smaller = "not a tag < 5";
echo strip_tags($smaller);    // -> not a tag < 5
echo filter_var ( $smaller, FILTER_SANITIZE_STRING); // -> not a tag
?>
david dot drakulovski at gmail dot com 25-Feb-2014 07:54
Here is a simpler and a better presented ASCII list for the <32 or 127> filters
(if wikipedia confused the hell out of you):

http://www.danshort.com/ASCIImap/
galvao at galvao dot eti dot br 02-Mar-2013 06:04
Just to clarify, since this may be unknown for a lot of people:

ASCII characters above 127 are known as "Extended" and they represent characters such as greek letters and accented letters in latin alphabets, used in languages such as pt_BR.

A good ASCII quick reference (aside from the already mentioned Wikipedia article) can be found at: http://www.asciicodes.com/
Anonymous 15-Feb-2013 07:42
Support for FILTER_SANITIZE_FULL_SPECIAL_CHARS was added from version 5.3.3
googlybash24 at aol dot com 19-Sep-2012 05:39
Remember to trim() the $_POST before your filters are applied:

<?php

// We trim the $_POST data before any spaces get encoded to "%20"

// Trim array values using this function "trim_value"
function trim_value(&$value)
{
    $value = trim($value);    // this removes whitespace and related characters from the beginning and end of the string
}
array_filter($_POST, 'trim_value');    // the data in $_POST is trimmed

$postfilter =    // set up the filters to be used with the trimmed post array
    array(
            'user_tasks'                        =>    array('filter' => FILTER_SANITIZE_STRING, 'flags' => !FILTER_FLAG_STRIP_LOW),    // removes tags. formatting code is encoded -- add nl2br() when displaying
            'username'                            =>    array('filter' => FILTER_SANITIZE_ENCODED, 'flags' => FILTER_FLAG_STRIP_LOW),    // we are using this in the url
            'mod_title'                            =>    array('filter' => FILTER_SANITIZE_ENCODED, 'flags' => FILTER_FLAG_STRIP_LOW),    // we are using this in the url
        );

$revised_post_array = filter_var_array($_POST, $postfilter);    // must be referenced via a variable which is now an array that takes the place of $_POST[]
echo (nl2br($revised_post_array['user_tasks']));    //-- use nl2br() upon output like so, for the ['user_tasks'] array value so that the newlines are formatted, since this is our HTML <textarea> field and we want to maintain newlines
?>
googlybash24 at aol dot com 13-Sep-2012 08:39
This should help with most simple "textarea" fields in post forms.

Removing user html tags while maintaining text formatting such as newlines and carriage returns involves using the FILTER_SANITIZE_STRING filter ID with the flag !FILTER_FLAG_STRIP_LOW. The formatting text (the low ASCII values under decimal 32) are encoded because of the included FILTER_FLAG_ENCODE_LOW flag, but you are now preventing these from being removed. When you want to display the value on the page back in its intended format, use nl2br() so the encoded newlines are formatted properly on the page.

This example cleans $_POST data from a textarea field with the name "user_tasks" on a previous html form, stripping tags but maintaining formatting (at least for newlines):

<?php
$postfilter =
    array(
            'user_tasks'    =>    array('filter' => FILTER_SANITIZE_STRING, 'flags' => !FILTER_FLAG_STRIP_LOW),    // removes tags. formatting code is encoded -- add nl2br() when displaying
        );

$revised_post_array = filter_input_array(INPUT_POST, $postfilter);    // must be referenced via a variable which is now an array that takes the place of $_POST[]
echo (nl2br($revised_post_array['user_tasks']));    // here we use nl2br() for the displayed value, for the ['user_tasks'] array value so that the newlines are formatted
?>
adellemfrank at hotmail dot com 09-Jul-2012 07:07
A good list of which ASCII characters are < 32 and > 127 can be found at: http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
scamber256 at hotmail dot de 06-Aug-2011 02:37
Just a hint I tested,

You can obtain all the chars <32 (so newline and c.return), by using not operator > !FILTER_FLAG_STRIP_LOW as the last argument.

Example:
filter_input(INPUT_GET,'test',FILTER_SANITIZE_STRING,!FILTER_FLAG_STRIP_LOW);

The filter keeps working as before removing anything else as before apart from FILTER_FLAG_STRIP_LOW.
Just filter those "bad" chars <32 manually you don't want.
Dmitry Snytkine 11-Apr-2011 04:17
Beware that FILTER_FLAG_STRIP_LOW strips NEWLINE and TAG and CARRIAGE RETURN chars. If you have a form that accepts user input in plaintext format, all the submitted text will lose all the line breaks, making it appear all on one line. This basically renders this filter useless for parsing user-submitted text, even in plain text.
marcus at synchromedia dot co dot uk 27-Nov-2009 01:07
It's not entirely clear what the LOW and HIGH ranges are. LOW is characters below 32, HIGH is those above 127, i.e. outside the ASCII range.

<?php
$a = "\tcafé\n";
//This will remove the tab and the line break
echo filter_var($a, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
//This will remove the é.
echo filter_var($a, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
?>


Otros filtros

Lista de filtros varios
ID | Nombre | Opciones | Banderas | Descripción
FILTER_CALLBACK | "callback" | Función o método callable |  | Llamadas a funciones definidas por el usuario para filtrar datos.

User Contributed Notes

shaman_master at list dot ru 20-Jun-2020 04:46
NOTE: dont wrap PHP function in closure as writed in "top" comment
<?php
$str = filter_input(INPUT_GET, 'str', FILTER_CALLBACK, ['options' => 'trim']);
?>
commonpike 24-Sep-2018 09:56
Some useful custom filters:

<?php

    function sanitizeOptions($array,$default) {
        return function($value = null) use ($array,$default) {
            if (in_array($value, $array)) return $value;
            return $default;
        };
    }

    function sanitizeKey($value) {
        return strtolower(preg_replace('/[^a-zA-Z0-9-_\.]/','', $value));
    }

    /*usage */

    filter_var($format, FILTER_CALLBACK, array(
           "options" => sanitizeOptions(['html','json','blob'],'json')
        ));

    filter_var($format,FILTER_CALLBACK, array(
           "options" =>  'sanitizeKey'
        ));

?>
johnk at riceball dot com 18-Feb-2018 03:12
Here's how to create callable functions with parameters.  These are functions that return closures.  When you call them, you supply the known parameters, and it returns a function that will accept the value from filter_input() or filter_input_array().

<?php

function filter_sanitize_int_range_generator($low, $high) {
        return function($value = null) use ($low, $high) {
                $v = intval($value);
                if ($v < $low) return false;
                if ($v > $high) return false;
                return $v;
        };
}

function filter_sanitize_string_in_array_generator($array) {
        return function($value = null) use ($array) {
                if (!is_string($value)) return false;
                if (in_array($value, $array)) return $value;
                return false;
        };
}

echo "TESTING RANGE\n";
$fun = filter_sanitize_int_range_generator(1,10);
var_dump($fun(5)); // 5
var_dump((filter_sanitize_int_range_generator(1,10))(0)); // false
var_dump((filter_sanitize_int_range_generator(1,10))(1)); // 1
var_dump((filter_sanitize_int_range_generator(1,10))(10)); // 10
var_dump((filter_sanitize_int_range_generator(1,10))(11)); // false
var_dump($fun()); // false

echo "TESTING IN ARRAY\n";
$fun = filter_sanitize_string_in_array_generator(['cat','dog','bird']);
var_dump($fun('cat')); // cat
var_dump($fun('dog')); // dog
var_dump($fun('bird')); // bird
var_dump($fun('fish')); // false
var_dump($fun()); // false

// use it like this
filter_input(INPUT_GET, 'month', FILTER_CALLBACK, array( "callable" => filter_sanitize_int_range_generator(1,12) ) );
Vufi 28-Jan-2016 07:50
Are you also struggling with how to send arguments into the FILTER_CALLBACK.

Lets say you like to have a collection of custom filters that you can use in filter_var, filter_var_array and so on, but you want be able to call the new filters with different arguments, as you can in filter_var.

The easiest way to do this is to make a new class with all your custom filters. Then construct the class with your arguments inside filter_var argument array and enter the method in your class you like to run after.

If you send the argument as an array it is easy to make default values. But you can pass as many arguments you want and in any type, with this solution.

Example:
<?php
/**
 * Class CustomFilters
 * Custom filters for filter_var, filter_var_array, filter_input, filter_input_array
 */
class CustomFilters {
    private $options = array();

    public function __construct(array $options=array()){
        $this->options = $options;
    }

    /**
     * Returns the default options merged with the construction options
     * @param array $defaults
     * @return array
     */
    private function get_options(array $defaults){
        return array_merge($defaults, $this->options);
    }

    /**
     * Checks if a value is in a range
     * @param mixed $val Value provided by filter_var
     * @return mixed
     */
    public function FILTER_STEP_RANGE($val){
        $options = $this->get_options(
            // default options
            array(
                "min_range" => 1,
                "max_range" => 10,
                "step"      => 1,
                "default"   => null,    // Value to return on fail
                "strict"    => false,   // Check value for correct type
                "cast"      => false    // Cast the value in a certain type
            )
        );

        if(in_array( $val, range($options["min_range"], $options["max_range"], $options["step"]), $options["strict"])){

            // Return default if the value cant be cast as the right type
            if( $options["cast"] && !settype($val, $options["cast"])) {
                return $options["default"];
            }

            return $val;
        }else{
            return $options["default"];
        }
    }

    /**
     * Checks if a value is in array
     * @param mixed $val Value provided by filter_var
     * @return mixed
     */
    public function FILTER_ENUM($val){
        $options = $this->get_options(
        // default options
            array(
                "values"  => array(),
                "strict"    => false, // Value to return on fail
                "default"   => null,  // Check value for correct type
                "cast"      => false  // Cast the value in a certain type
            )
        );

        if(in_array($val, $options["values"], $options["strict"])){

            // Return default if the value cant be cast as the right type
            if( $options["cast"] && !settype($val, $options["cast"])){
                return $options["default"];
            }

            return $val;
        }else{
            return $options["default"];
        }
    }
}

$data = array(
    "range1" => "200",
    "range2" => 25,
    "enum" => "yes"
);

$args = array(
    "range1" => array(
        "filter" => FILTER_CALLBACK,
        "options" => array(
            new CustomFilters(array( "min_range" => 10, "max_range" => 600, "step" => 10, "default" => 120,
                "cast" => "integer")),
            'FILTER_STEP_RANGE'
            )
        ),

    "range2" => array(
        "filter" => FILTER_CALLBACK,
        "options" => array(
            new CustomFilters(array( "min_range" => 0, "max_range" => 1, "step" => .1, "default" => .5,
                "cast" => "float")),
            'FILTER_STEP_RANGE'
        )
    ),
    "enum" => array(
        "filter" => FILTER_CALLBACK,
        "options" => array(
            new CustomFilters(array( "values" => array("yes", "no", "Yes","No"), "cast" => "string")),
            'FILTER_ENUM'
        )
    )
);

var_dump( filter_var_array($data, $args) );
?>

Returns:
array(3) {
  ["range1"] => int(200)
  ["range2"] => float(0.5)
  ["enum"] => string(3) "yes"
}
christof at himalayasystemsNOSPAM dot be 11-Aug-2015 10:47
The supplied callback function may also be a class method. (since 5.4.0 ?)
To use a method you need to set the options param to an array with two values: the first is the object and the second is the method name.

<?php
/**
 * @property-read $language
 */
class GetInputStore {
    private $allowed_languages = array('en', 'fr', 'de', 'nl' /*, ... */);
    private $language;

    public function __construct(){
        $this->language = filter_input(INPUT_GET, 'language', FILTER_CALLBACK, array('options' => array($this, 'get_language_code')));
    }

    public function __get($name){
         switch($name){
             case 'language' : return $this->language;
             default : throw new Exception("The GetInputStore class doesn't support GET param \"$name\"");
         }
    }

    private function get_language_code($code){
        if(in_array($code, $this->allowed_languages)){
            return $code;
        } else {
            return 'en';
        }
    }
}
?>
thatindividual dot zhang at gmail dot com 23-Sep-2014 07:05
Here is an example, since I cannot find one through out php.net"

<?php

/**
 * Strip whitespace (or other non-printable characters) from the beginning and end of a string
 * @param string $value
 */
function trimString($value)
{
    return trim($value);
}

$loginname = filter_input(INPUT_POST, 'loginname', FILTER_CALLBACK, array('options' => 'trimString'));


Opciones de filtrado

Lista de opciones de los filtros
ID | Usado con | Descripción
FILTER_FLAG_STRIP_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Elimina caracteres que tienen un valor numérico <32.
FILTER_FLAG_STRIP_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Elimina caracteres que tienen un valor numérico >127.
FILTER_FLAG_ALLOW_FRACTION | FILTER_SANITIZE_NUMBER_FLOAT | Permite usar un punto (.) como separador de decimales en los números.
FILTER_FLAG_ALLOW_THOUSAND | FILTER_SANITIZE_NUMBER_FLOAT, FILTER_VALIDATE_FLOAT | Permite usar una coma (,) como separador de miles en los números.
FILTER_FLAG_ALLOW_SCIENTIFIC | FILTER_SANITIZE_NUMBER_FLOAT | Permite usar una e o E para la notación científica de números.
FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_SANITIZE_STRING | Si se indica esta opción, las comillas simples (') y las dobles (") no se codificarán.
FILTER_FLAG_ENCODE_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Codifica todos los caracteres con valor numérico <32.
FILTER_FLAG_ENCODE_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Codifica todos los caracteres con valor numérico >127.
FILTER_FLAG_ENCODE_AMP | FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Codifica ampersands (&).
FILTER_NULL_ON_FAILURE | FILTER_VALIDATE_BOOLEAN | Devuelve null para valores boolean que no se reconozcan.
FILTER_FLAG_ALLOW_OCTAL | FILTER_VALIDATE_INT | Permite datos de entrada que comiencen por un cero (0) como número octal. Esto obliga a que los siguientes dígitos sean únicamente 0-7.
FILTER_FLAG_ALLOW_HEX | FILTER_VALIDATE_INT | Permite datos de entrada que comiencen por 0x o 0X como número hexadecimal. Esto obliga a que los siguientes dígitos sean únicamente a-fA-F0-9.
FILTER_FLAG_IPV4 | FILTER_VALIDATE_IP | Permite direcciones IP en formato IPv4.
FILTER_FLAG_IPV6 | FILTER_VALIDATE_IP | Permite direcciones IP en formato IPv6.
FILTER_FLAG_NO_PRIV_RANGE | FILTER_VALIDATE_IP | Falla si se intenta validar alguna de los siguientes rangos privados de IPv4: 10.0.0.0/8, 172.16.0.0/12 y 192.168.0.0/16. Falla si se intenta validad direcciones IPv6 que empiecen por FD o FC.
FILTER_FLAG_NO_RES_RANGE | FILTER_VALIDATE_IP | Falla si se intenta validad alguno de los siguientes rangos IPv4 reservados: 0.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24 y 224.0.0.0/4. Este flag no se aplica a direcciones IPv6.
FILTER_FLAG_PATH_REQUIRED | FILTER_VALIDATE_URL | Requiere que el URL contenga parte de la ruta.
FILTER_FLAG_QUERY_REQUIRED | FILTER_VALIDATE_URL | Requiere que el URL contenga un query string.
FILTER_REQUIRE_SCALAR |  | Requiere que el valor sea escalar.
FILTER_REQUIRE_ARRAY |  | Requiere que el valor sea un array.
FILTER_FORCE_ARRAY |  | Si el valor es un escalar, es tratado como un array con el valor escalar cómo único elemento.

User Contributed Notes

shaman_master at list dot ru 18-Jun-2020 04:01
Missing constant of default flag: FILTER_FLAG_NONE


Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles sólo cuando la extensión haya sido compilada con PHP, o bien sea cargada dinámicamente en ejecución.

INPUT_POST (integer)
Variables POST.
INPUT_GET (integer)
Variables GET.
INPUT_COOKIE (integer)
Variables COOKIE.
INPUT_ENV (integer)
Variables ENV.
INPUT_SERVER (integer)
Variables SERVER.
INPUT_SESSION (integer)
Variables SESSION. (no implementado aún)
INPUT_REQUEST (integer)
Variables REQUEST. (no implementada aún)
FILTER_FLAG_NONE (integer)
Sin banderas.
FILTER_REQUIRE_SCALAR (integer)
Bandera usada para requerir un escalar como entrada.
FILTER_REQUIRE_ARRAY (integer)
Requerir un array como entrada.
FILTER_FORCE_ARRAY (integer)
Devolver siempre un array.
FILTER_NULL_ON_FAILURE (integer)
Usar NULL en vez de FALSE en caso de fallo.
FILTER_VALIDATE_INT (integer)
ID del filtro "int".
FILTER_VALIDATE_BOOLEAN (integer)
ID del filtro "boolean".
FILTER_VALIDATE_FLOAT (integer)
ID del filtro "float".
FILTER_VALIDATE_REGEXP (integer)
ID del filtro "validate_regexp".
FILTER_VALIDATE_URL (integer)
ID del filtro "validate_url".
FILTER_VALIDATE_EMAIL (integer)
ID del filtro "validate_email".
FILTER_VALIDATE_IP (integer)
ID del filtro "validate_ip".
FILTER_VALIDATE_MAC (integer)
ID del filtro "validate_mac_address". (Disponible a partir de PHP 5.5.0)
FILTER_DEFAULT (integer)
ID del filtro ("unsafe_raw"). Equivale a FILTER_UNSAFE_RAW.
FILTER_UNSAFE_RAW (integer)
ID del filtro "unsafe_raw".
FILTER_SANITIZE_STRING (integer)
ID del filtro "string".
FILTER_SANITIZE_STRIPPED (integer)
ID del filtro "stripped".
FILTER_SANITIZE_ENCODED (integer)
ID del filtro "encoded".
FILTER_SANITIZE_SPECIAL_CHARS (integer)
ID del filtro "special_chars".
FILTER_SANITIZE_EMAIL (integer)
ID del filtro "email".
FILTER_SANITIZE_URL (integer)
ID del filtro "url".
FILTER_SANITIZE_NUMBER_INT (integer)
ID del filtro "number_int".
FILTER_SANITIZE_NUMBER_FLOAT (integer)
ID del filtro "number_float".
FILTER_SANITIZE_MAGIC_QUOTES (integer)
ID del filtro "magic_quotes".
FILTER_CALLBACK (integer)
ID del filtro "callback".
FILTER_FLAG_ALLOW_OCTAL (integer)
Permitir la notación octal (0[0-7]+) en el filtro "int".
FILTER_FLAG_ALLOW_HEX (integer)
Permitir la notación hexadecimal (0x[0-9a-fA-F]+) en el filtro "int".
FILTER_FLAG_STRIP_LOW (integer)
Eliminar caracteres con un valor ASCII inferior a 32.
FILTER_FLAG_STRIP_HIGH (integer)
Eliminar caracteres con un valor ASCII superior a 127.
FILTER_FLAG_ENCODE_LOW (integer)
Codificar caracteres con un valor ASCII inferior a 32.
FILTER_FLAG_ENCODE_HIGH (integer)
Codificar caracteres con un valor ASCII superior a 127.
FILTER_FLAG_ENCODE_AMP (integer)
Codificar el signo &.
FILTER_FLAG_NO_ENCODE_QUOTES (integer)
No codificar ' ni ".
FILTER_FLAG_EMPTY_STRING_NULL (integer)
(No usada por ahora.)
FILTER_FLAG_ALLOW_FRACTION (integer)
Permitir la parte decimal en el filtro "number_float".
FILTER_FLAG_ALLOW_THOUSAND (integer)
Permitir el separador de miles (,) en el filtro "number_float".
FILTER_FLAG_ALLOW_SCIENTIFIC (integer)
Permitir la notación científica (e, E) en el filtro "number_float".
FILTER_FLAG_PATH_REQUIRED (integer)
Requerir la ruta en el filtro "validate_url".
FILTER_FLAG_QUERY_REQUIRED (integer)
Requerir la consulta en el filtro "validate_url".
FILTER_FLAG_IPV4 (integer)
Permitir solamente direcciones IPv4 en el filtro "validate_ip".
FILTER_FLAG_IPV6 (integer)
Permitir solamente direcciones IPv6 en el filtro "validate_ip".
FILTER_FLAG_NO_RES_RANGE (integer)
Prohibir direcciones reservadas en el filtro "validate_ip".
FILTER_FLAG_NO_PRIV_RANGE (integer)
Prohibir direcciones privadas en el filtro "validate_ip".

User Contributed Notes

jcastromail at yahoo dot es 07-Jan-2021 06:46
INPUT_REQUEST was implemented in PHP < 8 (it was equal to 99) but it was removed in PHP 8.0

While INPUT_SESSION,FILTER_SANITIZE_MAGIC_QUOTES,FILTER_FLAG_SCHEME_REQUIRED,FILTER_FLAG_HOST_REQUIRED and a few others were removed in PHP 8.0.
shaman_master at list dot ru 17-Jun-2020 11:48
Note: FILTER_NULL_ON_FAILURE, FILTER_REQUIRE_SCALAR, FILTER_REQUIRE_ARRAY and FILTER_FORCE_ARRAY dont have prefix "FILTER_FLAG_" but they are FLAGS!
sixd at php dot net 23-Dec-2010 10:37
Rasmus added FILTER_SANITIZE_FULL_SPECIAL_CHARS to PHP 5.3.3.  See
http://svn.php.net/viewvc/php/php-src/branches/PHP_5_3/
ext/filter/filter.c?r1=297245&r2=297244&pathrev=297245
His earlier commit to the PHP source code trunk commented that this "Added the full htmlspecialchars() functionality which includes utf-8 validation as a default filter."


Ejemplos

Tabla de contenidos

  • Validación
  • Saneamiento

User Contributed Notes

There are no user contributed notes for this page.


Validación

Ejemplo #1 Validación de direcciones de correo con filter_var()

<?php
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "Esta dirección de correo ($email_a) es válida.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "Esta dirección de correo ($email_b) es válida.";
}
?>

El resultado del ejemplo sería:

Esta dirección de correo (joe@example.com) es válida.

Ejemplo #2 Validación de direcciones IP con filter_var()

<?php
$ip_a = '127.0.0.1';
$ip_b = '42.42';

if (filter_var($ip_a, FILTER_VALIDATE_IP)) {
    echo "Esta dirección IP (ip_a) es válida.";
}
if (filter_var($ip_b, FILTER_VALIDATE_IP)) {
    echo "Esta dirección IP (ip_b) es válida.";
}
?>

El resultado del ejemplo sería:

Esta dirección IP (ip_b) es válida.

Ejemplo #3 Pasando opciones a filter_var()

<?php
$int_a = '1';
$int_b = '-1';
$int_c = '4';
$options = array(
    'options' => array(
                      'min_range' => 0,
                      'max_range' => 3,
                      )
);
if (filter_var($int_a, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "Este entero (int_a) es válido (entre 0 y 3).\n";
}
if (filter_var($int_b, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "Este entero (int_b) es válido (entre 0 y 3).\n";
}
if (filter_var($int_c, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "Este entero (int_c) es válido (entre 0 y 3).\n";
}

$options['options']['default'] = 1;
if (($int_c = filter_var($int_c, FILTER_VALIDATE_INT, $options)) !== FALSE) {
    echo "Este entero (int_c) es válido (entre 0 y 3) y es $int_c.";
}
?>

El resultado del ejemplo sería:

Este entero (int_a) es válido (entre 0 y 3).
Este entero (int_c) es válido (entre 0 y 3) y es 1.

User Contributed Notes

dows 04-May-2018 08:26
It considers umlauts-domains as invalid.

test@täst.de -> false
täst@test.de -> false
Anonymous 21-Nov-2017 07:34
the problem listed before with the e-mail address: gnix@lineone.netsteve.gynes@lane4.co.uk being flagged as valid seems to not be a problem anymore, at least not on 5.6.30


Saneamiento

Ejemplo #1 Saneando y validando direcciones de correo

<?php
$a = 'joe@example.org';
$b = 'bogus - at - example dot org';
$c = '(bogus@example.org)';

$sanitized_a = filter_var($a, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_a, FILTER_VALIDATE_EMAIL)) {
    echo "Esta dirección de correo saneada (a) es válida.\n";
}

$sanitized_b = filter_var($b, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_b, FILTER_VALIDATE_EMAIL)) {
    echo "Esta dirección de correo saneada (b) es válida.\n";
} else {
    echo "Esta dirección de correo saneada (b) no es válida.\n";
}

$sanitized_c = filter_var($c, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_c, FILTER_VALIDATE_EMAIL)) {
    echo "Esta dirección de correo saneada (c) es válida.\n";
    echo "Antes: $c\n";
    echo "Después:  $sanitized_c\n";
}
?>

El resultado del ejemplo sería:

Esta dirección de correo saneada (a) es válida.
Esta dirección de correo saneada (b) no es válida.
Esta dirección de correo saneada (c) es válida.
Antes: (bogus@example.org)
Después: bogus@example.org

Ejemplo #2 Configuración de un filtro por omisión

filter.default = full_special_chars
filter.default_flags = 0

User Contributed Notes

Chris 14-Apr-2015 07:42
While it may seem to be good practice to set the defaults in php.ini you should not assume that the end users server has the same settings as your server. Because of this you should not presume that default filtering will work out of the box for the end user.

You should ensure that all filters are declared at the site of use regardless of your own default settings. A move to a new host even for your own personal application may break due to different settings.
zeeshan dot karamat dot abbas at gmail dot com 05-Feb-2015 01:59
If we omit using a filter then PHP by default puts a filter which is FILTER_DEFAULT which will use default filter. Now the question is what is a default filter. A default filter is unsafe_raw which will allow the unsafe raw data passed on to the server. This value is available in php.ini file. It is suggested that a developer should update this value inside php.ini file as under:
filter.default = full_special_chars
filter.default_flags = 0

Whereas in php.ini file above values are by default, set as under:
;filter.default = unsafe_raw
;filter.default_flags =

Above semicolons are commented out lines so surely one needs to remove those semicolons to apply the changes made. If we do not do above things then what will happen. In that case PHP will use default filter which would surely be FILTER_UNSAFE_RAW and one can see that unsafe raw data can then be passed onto server which can make the life a hacker easier.


Funciones de Filter

Tabla de contenidos

  • filter_has_var — Comprueba si existe una variable de un tipo concreto existe
  • filter_id — Indica el ID del nombre de filtro que se indique
  • filter_input_array — Obtiene variables externas y opcionalmente las filtra
  • filter_input — Toma una variable externa concreta por su nombre y opcionalmente la filtra
  • filter_list — Devuelve una lista de todos los filtros soportados
  • filter_var_array — Retorna múltiple variables y opcionalmente las filtra
  • filter_var — Filtra una variable con el filtro que se indique

User Contributed Notes

fumble1 at web dot de 12-Aug-2007 10:54
I recommend you to use the FILTER_REQUIRE_SCALAR (or FILTER_REQUIRE_ARRAY) flags, since you can use array-brackets both to access string offsets and array-element -- however, not only this can lead to unexpected behaviour. Look at this example:

<?php
$image = basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW));
// further checks
?>

/script.php?src[0]=foobar will cause a warning. :-(
Hence my recommendation:

<?php
$image = basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_REQUIRE_SCALAR | FILTER_FLAG_STRIP_LOW));
// further checks
?>
Richard Davey rich at corephp dot co dot uk 13-Jun-2007 11:15
There is an undocumented filter flag for FILTER_VALIDATE_BOOLEAN. The documentation implies that it will return NULL if the value doesn't match the allowed true/false values. However this doesn't happen unless you give it the FILTER_NULL_ON_FAILURE flag like this:

<?php
$value = 'car';
$result = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
?>

In the above $result will equal NULL. Without the extra flag it would equal FALSE, which isn't usually a desired result for this specific filter.
ckroll at rightmedia dot com 08-May-2007 08:02
Beware, the FILTER_SANITIZE_STRING flag functions much like strip_tags, so < will get filtered from input regardless of it's actually part of a tag.  We were getting unexepected results with a graphic library we wrote when trying to print < on a dynamic button.  The url came in something like ?string=%3C (<) but after filter ran it was empty.  To get around this, you could use FILTER_UNSAFE_RAW on that one param.
user 02-Feb-2007 12:15
Below is some code using filter API to restrict access to LAN by IPv4 private address range.

These notes may save someone else a little time:

filter_input_array() is useless for running multiple filters on the same key.
No way to chain or negate filters.

<?php

/* Merciful comment! */
function FILTER_NEGATE_HACK($_){ return (bool)!$_; }

function client_is_private_ipv4(){
  return (filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) &&
            FILTER_NEGATE_HACK(filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE));
}

if (! client_is_private_ipv4())
  exit('This application is restricted to local network users');

?>
vojtech at x dot cz 21-Dec-2006 06:38
Also notice that filter functions are using only the original variable values passed to the script even if you change the value in super global variable ($_GET, $_POST, ...) later in the script.

<?php
echo filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'something'
$_GET['var'] = 'changed';
echo filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'changed'
?>

In fact, external data are duplicated in SAPI before the script is processed and filter functions don't use super globals anymore (as explained in Filter tutorial bellow, section 'How does it work?').
vojtech at x dot cz 21-Dec-2006 05:13
Just to note that "server and env support may not work in all sapi, for filter 0.11.0 or php 5.2.0" as mentioned in Filter tutorial bellow.

The workaround is obvious:
Instead of
<?php
$var = filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_DEFAULT);
?>
use
<?php
$var = filter_var(isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : NULL, FILTER_DEFAULT);
?>


Comprueba si existe una variable de un tipo concreto existe

  • « Funciones de Filter
  • filter_id »
  • PHP Manual
  • Funciones de Filter
  • Comprueba si existe una variable de un tipo concreto existe

filter_has_var

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

filter_has_var — Comprueba si existe una variable de un tipo concreto existe

Descripción

filter_has_var ( int $type , string $variable_name ) : bool

Parámetros

type

Una de estas posibilidades: INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER o INPUT_ENV.

variable_name

Nombre de la variable a comprobar.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

User Contributed Notes

dezlov 30-Jul-2015 01:12
For people who are wondering whether "magic_quotes_gpc" has any affect on "filter_input" operation, here is an extract from a PHP source file:

* As the input filter acts on input data before the magic quotes function mangles data, all access through the filter() function will not have any quotes or slashes added - it will be the pure data as send by the browser.

So when using this function, there is no need to strip the slashes when "magic_quotes_gpc" is enabled.
nanhe dot kumar at gmail dot com 06-Mar-2013 02:15
Through this example i think you can better understand

    if ( !filter_has_var(INPUT_GET, 'email') ) {
        echo "Email Not Found";
    }else{
        echo "Email Found";
    }
    Output

    localhost/nanhe/test.php?email=1 //Email Found
    localhost/nanhe/test.php?email //Email Found
    http://localhost/nanhe/test.php //Email Not Found

Consider on second example

http://localhost/nanhe/test.php
$_GET['email']="info@nanhe.in";
if ( !filter_has_var(INPUT_GET, 'email') ) {
        echo "Email Not Found";
    }else{
        echo "Email Found";
    }
But output will be Email Not Found
drm at melp dot nl 16-Jan-2009 01:54
Please note that the function does not check the live array, it actually checks the content received by php:

<?php
$_GET['test'] = 1;
echo filter_has_var(INPUT_GET, 'test') ? 'Yes' : 'No';
?>

would say "No", unless the parameter was actually in the querystring.

Also, if the input var is empty, it will say Yes.


Indica el ID del nombre de filtro que se indique

  • « filter_has_var
  • filter_input_array »
  • PHP Manual
  • Funciones de Filter
  • Indica el ID del nombre de filtro que se indique

filter_id

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

filter_id — Indica el ID del nombre de filtro que se indique

Descripción

filter_id ( string $filtername ) : int

Parámetros

filtername

Nombre del filtro a obtener el ID.

Valores devueltos

ID del filtro en caso de éxito o false si el filtro no existe.

Ver también

  • filter_list() - Devuelve una lista de todos los filtros soportados

User Contributed Notes

w0n4b3 at gmail dot com 23-Jun-2011 02:47
[To get a list of filters and their IDs:]

<?php
$filters = filter_list();
foreach($filters as $filter_name) {
    echo $filter_name .": ".filter_id($filter_name) ."<br>";
}
?>
Will result in:
boolean: 258
float: 259
validate_regexp: 272
validate_url: 273
validate_email: 274
validate_ip: 275
string: 513
stripped: 513
encoded: 514
special_chars: 515
unsafe_raw: 516
email: 517
url: 518
number_int: 519
number_float: 520
magic_quotes: 521
callback: 1024


Obtiene variables externas y opcionalmente las filtra

  • « filter_id
  • filter_input »
  • PHP Manual
  • Funciones de Filter
  • Obtiene variables externas y opcionalmente las filtra

filter_input_array

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

filter_input_array — Obtiene variables externas y opcionalmente las filtra

Descripción

filter_input_array ( int $type , mixed $definition = ? , bool $add_empty = true ) : mixed

Esta función es útil para recuperar muchos valores sin necesidad de hacer repetidas llamadas a filter_input().

Parámetros

type

Una de las siguientes: INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER o INPUT_ENV.

definition

Un array definiendo los argumentos. Una clave válida será aquella que contiene un string con el nombre de una variable y un valor válido aquel que o bien es un tipo filter type o un array especificando opcionalmente el filtro, flags y opciones. Si el valor es un array, las claves válidas serán: filter que especifica el tipo filter type, flags que define cualquier flag que deba aplicarse a los filtros, y options que establece cualquier opción que se deba aplicar al filtro. Para entender mejor su funcionamiento, vea el ejemplo inferior.

Este parámetro puede ser también un entero que indique una constante de filtro. Entonces todos los valores en el array de entrada son filtrados por ese filtro.

add_empty

Añade claves faltantes como null al valor devuelto.

Valores devueltos

En caso de éxito, un array con los valores de las variables que se han pedido o false en caso de fallo. Un valor del array puede ser false si el filtro falla o null si la variable no está creada. O, si se usa el flag FILTER_NULL_ON_FAILURE y la variable no está definida retorna false y null si el filtro falla.

Ejemplos

Ejemplo #1 Un ejemplo con filter_input_array()

<?php
error_reporting(E_ALL | E_STRICT);
/* Los datos vienen realmente por POST
$_POST = array(
    'id_producto'    => 'libgd<script>',
    'componente'     => '10',
    'version'      => '2.0.33',
    'test_escalar'    => array('2', '23', '10', '12'),
    'test_array'     => '2',
);
*/

$args = array(
    'id_producto'   => FILTER_SANITIZE_ENCODED,
    'componente'    => array('filter'    => FILTER_VALIDATE_INT,
                            'flags'     => FILTER_REQUIRE_ARRAY,
                            'options'   => array('min_range' => 1, 'max_range' => 10)
                           ),
    'version'     => FILTER_SANITIZE_ENCODED,
    'no_existe' => FILTER_VALIDATE_INT,
    'test_escalar'   => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_SCALAR,
                           ),
    'test_array'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_ARRAY,
                           )

);

$mis_entradas = filter_input_array(INPUT_POST, $args);

var_dump($mis_entradas);
echo "\n";
?>

El resultado del ejemplo sería:

array(6) {
  ["id_producto"]=>
  array(1) {
    [0]=>
    string(17) "libgd%3Cscript%3E"
  }
  ["componente"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["version"]=>
  array(1) {
    [0]=>
    string(6) "2.0.33"
  }
  ["no_existe"]=>
  NULL
  ["test_escalar"]=>
  bool(false)
  ["test_array"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Historial de cambios

Versión | Descripción
5.4.0 | Se añadió el parámetro add_empty.

Notas

Nota:

No existe la clave REQUEST_TIME en la matriz INPUT_SERVER porque este valor se inserta posteriormente en $_SERVER.

Ver también

  • filter_input() - Toma una variable externa concreta por su nombre y opcionalmente la filtra
  • filter_var_array() - Retorna múltiple variables y opcionalmente las filtra
  • Tipos de filtros

User Contributed Notes

sdupuis at blax dot ca 21-Jan-2014 09:36
Note that although you can provide a default filter for the entire input array there is no way to provide a flag for that filter without building the entire definition array yourself.

So here is a small function that can alleviate this hassle!

<?php
function filter_input_array_with_default_flags($type, $filter, $flags, $add_empty = true) {
    $loopThrough = array();
    switch ($type) {
        case INPUT_GET : $loopThrough = $_GET; break;
        case INPUT_POST : $loopThrough = $_POST; break;
        case INPUT_COOKIE : $loopThrough = $_COOKIE; break;
        case INPUT_SERVER : $loopThrough = $_SERVER; break;
        case INPUT_ENV : $loopThrough = $_ENV; break;
    }

    $args = array();
    foreach ($loopThrough as $key=>$value) {
        $args[$key] = array('filter'=>$filter, 'flags'=>$flags);
    }

    return filter_input_array($type, $args, $add_empty);
}
?>
CertaiN 10-Jan-2014 04:40
[New Version]

Example Usage:
<?php
$_GET['A']['a'] = '  CORRECT(including some spaces)    ';
$_GET['A']['b'] = '  CORRECT(including some spaces)    ';
$_GET['A']['c'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['A']['d']['invalid_structure'] = 'INVALID';

$_GET['B']['a'] = '  CORRECT(including some spaces)    ';
$_GET['B']['b'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['B']['c']['invalid_structure'] = 'INVALID';
$_GET['B']["Invalid UTF-8 sequence: \xe3\xe3\xe3"] = 'INVALID';

$_GET['C']['a'] = '  CORRECT(including some spaces)    ';
$_GET['C']['b'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['C']['c']['invalid_structure'] = 'INVALID';
$_GET['C']["Invalid UTF-8 sequence: \xe3\xe3\xe3"] = 'INVALID';

$_GET['unneeded_item'] = 'UNNEEDED';

var_dump(filter_struct_utf8(INPUT_GET, array(
    'A' => array(
        'a' => '',
        'b' => FILTER_STRUCT_TRIM,
        'c' => '',
        'd' => '',
    ),
    'B' => FILTER_STRUCT_FORCE_ARRAY,
    'C' => FILTER_STRUCT_FORCE_ARRAY | FILTER_STRUCT_TRIM,
)));
?>

Example Result:
array(3) {
  ["A"]=>
  array(4) {
    ["a"]=>
    string(36) "  CORRECT(including some spaces)    "
    ["b"]=>
    string(30) "CORRECT(including some spaces)"
    ["c"]=>
    string(0) ""
    ["d"]=>
    string(0) ""
  }
  ["B"]=>
  array(3) {
    ["a"]=>
    string(36) "  CORRECT(including some spaces)    "
    ["b"]=>
    string(0) ""
    ["c"]=>
    string(0) ""
  }
  ["C"]=>
  array(3) {
    ["a"]=>
    string(30) "CORRECT(including some spaces)"
    ["b"]=>
    string(0) ""
    ["c"]=>
    string(0) ""
  }
}
CertaiN 10-Jan-2014 04:39
[New Version]
This function is very useful for filtering complicated array structure.
Also, Some integer bitmasks and invalid UTF-8 sequence detection are available.

Code:
<?php
/**
 * @param  integer $type    Constant like INPUT_XXX.
 * @param  array   $default Default structure of the specified super global var.
 *                          Following bitmasks are available:
 *  + FILTER_STRUCT_FORCE_ARRAY - Force 1 dimensional array.
 *  + FILTER_STRUCT_TRIM        - Trim by ASCII control chars.
 *  + FILTER_STRUCT_FULL_TRIM   - Trim by ASCII control chars,
 *                                full-width and no-break space.
 * @return array            The value of the filtered super global var.
 */
define('FILTER_STRUCT_FORCE_ARRAY', 1);
define('FILTER_STRUCT_TRIM', 2);
define('FILTER_STRUCT_FULL_TRIM', 4);
function filter_struct_utf8($type, array $default) {
    static $func = __FUNCTION__;
    static $trim = "[\\x0-\x20\x7f]";
    static $ftrim = "[\\x0-\x20\x7f\xc2\xa0\xe3\x80\x80]";
    static $recursive_static = false;
    if (!$recursive = $recursive_static) {
        $types = array(
            INPUT_GET => $_GET,
            INPUT_POST => $_POST,
            INPUT_COOKIE => $_COOKIE,
            INPUT_REQUEST => $_REQUEST,
        );
        if (!isset($types[(int)$type])) {
            throw new LogicException('unknown super global var type');
        }
        $var = $types[(int)$type];
        $recursive_static = true;
    } else {
        $var = $type;
    }
    $ret = array();
    foreach ($default as $key => $value) {
        if ($is_int = is_int($value)) {
            if (!($value | (
                FILTER_STRUCT_FORCE_ARRAY |
                FILTER_STRUCT_FULL_TRIM |
                FILTER_STRUCT_TRIM
            ))) {
                $recursive_static = false;
                throw new LogicException('unknown bitmask');
            }
            if ($value & FILTER_STRUCT_FORCE_ARRAY) {
                $tmp = array();
                if (isset($var[$key])) {
                    foreach ((array)$var[$key] as $k => $v) {
                        if (!preg_match('//u', $k)){
                            continue;
                        }
                        $value &= FILTER_STRUCT_FULL_TRIM | FILTER_STRUCT_TRIM;
                        $tmp += array($k => $value ? $value : '');
                    }
                }
                $value = $tmp;
            }
        }
        if ($isset = isset($var[$key]) and is_array($value)) {
            $ret[$key] = $func($var[$key], $value);
        } elseif (!$isset || is_array($var[$key])) {
            $ret[$key] = null;
        } elseif ($is_int && $value & FILTER_STRUCT_FULL_TRIM) {
            $ret[$key] = preg_replace("/\A{$ftrim}++|{$ftrim}++\z/u", '', $var[$key]);
        } elseif ($is_int && $value & FILTER_STRUCT_TRIM) {
            $ret[$key] = preg_replace("/\A{$trim}++|{$trim}++\z/u", '', $var[$key]);
        } else {
            $ret[$key] = preg_replace('//u', '', $var[$key]);
        }
        if ($ret[$key] === null) {
            $ret[$key] = $is_int ? '' : $value;
        }
    }
    if (!$recursive) {
        $recursive_static = false;
    }
    return $ret;
}
?>
CertaiN 29-Jul-2013 10:22
This function is very useful for filtering complicated array structure.

Code:
<?php
function filter_request($var, $default_structure) {

    $ret = array();

    foreach ($default_structure as $key => $value) {
        if (!isset($var[$key])) {
            $ret[$key] = $value;
        } elseif (is_array($value)) {
            $ret[$key] = filter_request($var[$key], $value);
        } elseif (is_array($var[$key])) {
            $ret[$key] = $value;
        } else {
            $ret[$key] = $var[$key];
        }
    }

    return $ret;

}
?>

Sample Usage:
<?php
$_GET['a']['wrong_structure'] = 'foo';
$_GET['b']['c'] = 'CORRECT';
$_GET['b']['d']['wrong_structure'] = 'bar';
$_GET['unneeded_item'] = 'baz';

var_dump(filter_request($_GET, array(
    'a' => 'DEFAULT',
    'b' => array(
        'c' => 'DEFAULT',
        'd' => 'DEFAULT',
    ),
)));
?>

Sample Result:
array(2) {
  ["a"]=>
  string(21) "DEFAULT"
  ["b"]=>
  array(2) {
    ["c"]=>
    string(12) "CORRECT"
    ["d"]=>
    string(21) "DEFAULT"
  }
}
Anonymous 22-Apr-2010 12:12
Beware: if none of the arguments is set, this function returns NULL, not an array of NULL values.

/* No POST vars set in request
$_POST = array();
*/

$args = array('some_post_var' => FILTER_VALIDATE_INT);
$myinputs = filter_input_array(INPUT_POST, $args);
var_dump($myinputs);

Expected Output: array(1) { ["some_post_var"]=> NULL }

Actual Output: NULL
ville at N0SPAM dot zydo dot com 13-Mar-2010 03:18
While filtering input arrays, be careful of what flags you set besides FILTER_REQUIRE_ARRAY. For example, setting the flags like so:

<?php
$filter = array(
'myInputArr' => array('filter' => FILTER_SANITIZE_STRING,
                      'flags' => array('FILTER_FLAG_STRIP_LOW', 'FILTER_REQUIRE_ARRAY'))
);

$form_inputs = filter_input_array(INPUT_POST, $filter);
?>

.. will result in a blank $form_inputs['myInputArr'] regardless of what $_POST['myInputArr'] contains.
kibblewhite at live dot com 26-Jan-2009 07:35
If you are trying to handling multiple form inputs with same name, then you must assign the `'flags'  => FILTER_REQUIRE_ARRAY` to the definitions entry.

Example, you have a html form as such:
<form>
 <input name="t1[]" value="Some string One" />
 <input name="t1[]" value="Another String Two" />
</form>

Your definitions array will look a little like this:
$args = array(
  't1'    => array(
      'name' => 't1',
      'filter' => FILTER_SANITIZE_STRING,
      'flags'  => FILTER_REQUIRE_ARRAY)
);
kdeloach at gmail dot com 12-Aug-2008 12:42
@iam4webwork

This is not specific to filter_input.  If you have an element in HTML called names[], it can be accessed by calling $_POST['names'].
Kevin 08-Jul-2008 06:37
Looks like filter_input_array isn't aware of changes to the input arrays that were made before calling filter_input_array. Instead, it always looks at the originally submitted input arrays.

So this will not work:

$_POST['my_float_field'] = str_replace(',','.',$_POST['my_float_field']);
$args = array('my_float_field',FILTER_VALIDATE_FLOAT);
$result = filter_input_array(INPUT_POST, $args);
phpnotes dot 20 dot zsh at spamgourmet dot com 10-Sep-2007 10:32
The above example will actually output "NULL" because of the undefined variable doesnotexist - see http://bugs.php.net/bug.php?id=42608.
Sinured 22-Aug-2007 10:10
extract() is a very convenient way of copying all those variables to the local scope. (see http://www.php.net/extract)
iam4webwork at NOSPAM dot hotmail dot com 08-Jun-2007 01:02
The above example raises other questions such as how one would validate an html array.  In the input form each input tag that refers to an html array would be named for example testarray[].  However, after the form is submitted, the syntax for validating the values is different from  the expected $_POST['testarray[]']. Instead one has to drop the braces and validate as follows, assuming that testarray[] is supposed to be an html array of numerical values:

Valid test:

echo '*';
echo filter_input(
INPUT_POST,
'testarray',
FILTER_VALIDATE_INT,
FILTER_REQUIRE_ARRAY
);
echo '*';

But the following is an invalid test that results in 2 consequtive asterisks only!

echo '*';
echo filter_input(INPUT_POST,
'testarray[]',
FILTER_VALIDATE_INT,
FILTER_REQUIRE_ARRAY
);
echo '*';

So, there is a naming inconsistency going on, as after the form is submitted, one has to forget about the original name of the submitted array by dropping its braces. Maybe when the PECL/Filter extension is reviewed again, the great ones might consider making the syntax a little more forgiving.


Toma una variable externa concreta por su nombre y opcionalmente la filtra

  • « filter_input_array
  • filter_list »
  • PHP Manual
  • Funciones de Filter
  • Toma una variable externa concreta por su nombre y opcionalmente la filtra

filter_input

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

filter_input — Toma una variable externa concreta por su nombre y opcionalmente la filtra

Descripción

filter_input ( int $type , string $variable_name , int $filter = FILTER_DEFAULT , mixed $options = ? ) : mixed

Parámetros

type

Uno de los siguientes: INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER o INPUT_ENV.

variable_name

Nombre de la variable a escoger.

filter

El ID del filtro a aplicar. La página Tipos de filtros del manual enumera los filtros disponibles.

Si se omite, se utilizará FILTER_DEFAULT, que es equivalente a FILTER_UNSAFE_RAW. Esto resultará en que no se realice ningún tipo de filtro de forma predeterminada.

options

Array asociativo de opciones o disyunción lógica de flags. Si el filtro acepta opciones, se pueden añadir flags en el array asociativo bajo la clave "flags".

Valores devueltos

En caso de éxito, valor de la variable pedida, false si el filtro falla o null si la variable variable_name no está definida. Si se usa el flag FILTER_NULL_ON_FAILURE, retorna false si la variable no está definida y null si el filtro falla.

Ejemplos

Ejemplo #1 Un ejemplo de filter_input()

<?php
$buscar_html = filter_input(INPUT_GET, 'buscar', FILTER_SANITIZE_SPECIAL_CHARS);
$buscar_url = filter_input(INPUT_GET, 'buscar', FILTER_SANITIZE_ENCODED);
echo "Has buscado $buscar_html.\n";
echo "<a href='?buscar=$buscar_url'>Buscar de nuevo</a>";
?>

El resultado del ejemplo sería algo similar a:

Has buscado Yo & hijo.
<a href='?buscar=Yo%20%26%20hijo'>Buscar de nuevo</a>

Ver también

  • filter_var() - Filtra una variable con el filtro que se indique
  • filter_input_array() - Obtiene variables externas y opcionalmente las filtra
  • filter_var_array() - Retorna múltiple variables y opcionalmente las filtra
  • Tipos de filtros

User Contributed Notes

Enrique 08-Sep-2018 09:21
Para obtener el IP de cliente en sustitución de $_SERVER("REMOTE_ADDR") no se puede usar filter_input(INPUT_SERVER,'REMOTE_ADDR',FILTER_VALIDATE_IP) pues devuelve null, la formula que funciona es:

$REMOTE_ADDR = filter_input(INPUT_ENV, 'REMOTE_ADDR', FILTER_VALIDATE_IP);
DoubleT 17-Aug-2018 07:44
Discovered interesting behavior when modifying super-globals directly.
$_GET['p'] = 1;
filter_input(INPUT_GET,'p'); //value is NULL

Is this expected?
John Smith 21-Nov-2014 04:48
1. The description of the options parameter is misleading. In order to pass the options (e.g. default, min_range and max_range) you must pass an associative array with a key called "options", which itself is an associative array containing option name => option value pairs.

2. The return values section does not mention that if you specify the "default" option then the function will return the specified default value instead of returning FALSE or NULL (when filter fails or variable is absent).
rimelek at rimelek dot hu 20-Oct-2014 08:44
If your $_POST contains an array value:
<?php
$_POST  = array(
    'var' => array('more', 'than', 'one', 'values')
);
?>
you should use FILTER_REQUIRE_ARRAY option:
<?php
var_dump(filter_input(INPUT_POST, 'var', FILTER_DEFAULT , FILTER_REQUIRE_ARRAY));
?>
Otherwise it returns false.
viaujoc at videotron dot ca 04-Oct-2014 04:14
filter_input() does not seem to support multiple values for a single variable name.

Here is the code comparing the behavior of bare $_GET superglobal vs filter_input(INPUT_GET,...):
<?php
print("Bare \$_GET:\n");
var_dump($_GET);
print("filter_input():\n");
var_dump(filter_input(INPUT_GET,"var"));
?>

When calling: /..../script.php?var=123 (there is only one value for variable 'var')
Output is:
Bare $_GET:
array(1) {
  ["var"]=>
  string(3) "123"
}
filter_input():
string(3) "123"

When calling: /..../script.php?var[]=123&var[]=999 (there are two  values for variable 'var')
Output is:
Bare $_GET:
array(1) {
  ["var"]=>
  array(2) {
    [0]=>
    string(3) "123"
    [1]=>
    string(3) "999"
  }
}
filter_input():
bool(false)

As expected, $_GET['var'] became an array. But filter_input() seems to be unable to process multiple values and returns false.
CertaiN 23-May-2014 01:22
This function provides us the extremely simple solution for type filtering.

Without this function...
<?php
if (!isset($_GET['a'])) {
    $a = null;
} elseif (!is_string($_GET['a'])) {
    $a = false;
} else {
    $a = $_GET['a'];
}
$b = isset($_GET['b']) && is_string($_GET['b']) ? $_GET['b'] : '';
?>

With this function...
<?php
$a = filter_input(INPUT_GET, 'a');
$b = (string)filter_input(INPUT_GET, 'b');
?>

Yes, FILTER_REQUIRE_SCALAR seems to be set as a default option.
It's very helpful for eliminating E_NOTICE, E_WARNING and E_ERROR.
This fact should be documented.
descartavel1+php at gmail dot com 21-Apr-2014 06:50
contrary to what is stated here on the comments on thow to use the options for filters, there is no range option or default... in fact, there is not much option AT ALL. It is not mentioned in the manual anywhere, and the provided code on that comment does nothing with php-5.4.4..

<?php
get(GET, 'p', FILTER_VALIDATE_INT, array('options'=>array('default'=>5, 'min_range'=>0, 'max_range'=>9)) );
// ?p=30 => 30
// ?p="123" => 123
// ?p=-23 => -23
// ?p=asdf => null
?>
Stefan Weinzierl 16-Feb-2014 04:31
Here is an example how to work with the options-parameter. Notice the 'options' in the 'options'-Parameter!

<?php
$options=array('options'=>array('default'=>5, 'min_range'=>0, 'max_range'=>9));

$priority=filter_input(INPUT_GET, 'priority', FILTER_VALIDATE_INT, $options);
?>

$priority will be 5 if the priority-Parameter isn't set or out the given range.
akshay dot leadindia at gmail dot com 29-Aug-2013 02:17
The beauty of using this instead of directly using filter_var( $_GET['search'] ) is that you don't need to check if( isset( $_GET['search'] ) ) as if you pass that to filter_var and the key is not set then it will result in a warning. This function simplifies this and will return the relevant result to you (as per your options set) if the key has not been set in the user input.

If the type of filter you are using also supports a 'default' argument then this function will also stuff your missing input key with that value, again saving your efforts
west {:a7} jsausa {:d0t}~ com 28-Nov-2012 08:30
It's worth noting that the names for variables in filter input obey the same rules as variable naming in PHP (must start with an underscore or letter).  We were allowing users to build custom forms but hashing the names to prevent them from putting arbitrary content into the dom.  Turns out the hash function occasionally produced entirely numeric values for the field name... which doesn't work with filter_input but worked fine if you read directly from $_GET, $_POST, or $_REQUEST.  A workaround is to always prefix an underscore to the field name.
chris at chlab dot ch 20-Mar-2012 09:46
To use a class method for a callback function, as usual, provide an array with an instance of the class and the method name.
Example:

<?php
class myValidator
{
  public function username($value)
  {
    // return username or boolean false
  }
}

$myValidator = new myValidator;
$options = array('options' => array($myValidator, 'username'));
$username = filter_input(INPUT_GET, 'username', FILTER_CALLBACK, $options);
var_dump($username);
?>
ss23 at ss23 dot geek dot nz 28-Jul-2010 11:37
Note that this function doesn't (or at least doesn't seem to) actually filter based on the current values of $_GET etc. Instead, it seems to filter based off the original values.
<?php
$_GET['search'] = 'foo'; // This has no effect on the filter_input

$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>

If you need to set a default input value and filter that, use filter_var on your required input variable instead
travismowens at gmail dot com 28-Jul-2010 09:21
I wouldn't recommend people use this function to store their data in a database.  It's best not to encode data when storing it, it's better to store it raw and convert in upon the time of need.

One main reason for this is because if you have a short CHAR(16) field and the text contains encoded characters (quotes, ampersand) you can easily take a 12 character entry which obviously fits, but because of encoding it no longer fits.

Also, while not as common, if you need to use this data in another place, such as a non webpage (perhaps in a desktop app, or to a cell phone SMS or to a pager) the HTML encoded data will appear raw, and now you have to decode the data.

In summary, the best way to architect your system, is to store data as raw, and encode it only the moment you need to.  So this means in your PHP upon doing a SQL query, instead of merely doing an   echo $row['title']  you need to run htmlentities() on your echos, or better yet, an abstract function.
Maksym Karazeev 03-Mar-2009 01:13
Just a tip.

Note how to setup default filter for filter_var_array

When I tried to use filter_var_array and didn't mentioned all array indexes in definition it filtered it with some filter and broke values so using this tip corrected everything

<?php
$def = array_map(create_function('', 'return array("filter"=>FILTER_UNSAFE_RAW);'), $input);
?>
anthony dot parsons at manx dot net 23-Aug-2007 02:10
FastCGI seems to cause strange side-effects with unexpected null values when using INPUT_SERVER and INPUT_ENV with this function. You can use this code to see if it affects your server:
<?php
var_dump($_SERVER);
foreach ( array_keys($_SERVER) as $b ) {
    var_dump($b, filter_input(INPUT_SERVER, $b));
}
echo '<hr>';
var_dump($_ENV);
foreach ( array_keys($_ENV) as $b ) {
    var_dump($b, filter_input(INPUT_ENV, $b));
}
?>
If you want to be on the safe side, using the superglobal $_SERVER and $_ENV variables will always work. You can still use the filter_* functions for Get/Post/Cookie without a problem, which is the important part!


Devuelve una lista de todos los filtros soportados

  • « filter_input
  • filter_var_array »
  • PHP Manual
  • Funciones de Filter
  • Devuelve una lista de todos los filtros soportados

filter_list

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

filter_list — Devuelve una lista de todos los filtros soportados

Descripción

filter_list ( ) : array

Valores devueltos

Retorna un array con los nombres de todos los filtros soportados; el array estará vacío si no hay filtros. Los índices de este array no son los IDs de los filtros, estos se obtienen a partir del nombre y la función filter_id().

Ejemplos

Ejemplo #1 Ejemplo de filter_list()

<?php
print_r(filter_list());
?>

El resultado del ejemplo sería algo similar a:

Array
(
    [0] => int
    [1] => boolean
    [2] => float
    [3] => validate_regexp
    [4] => validate_url
    [5] => validate_email
    [6] => validate_ip
    [7] => string
    [8] => stripped
    [9] => encoded
    [10] => special_chars
    [11] => unsafe_raw
    [12] => email
    [13] => url
    [14] => number_int
    [15] => number_float
    [16] => magic_quotes
    [17] => callback
)

User Contributed Notes

shaman_master at list dot ru 18-Mar-2020 09:13
2 strings, but it's faster (-2 calls) and not the longest
<?php
$filters = filter_list();
$filters =  array_combine($filters, array_map('filter_id',  $filters));
?>
also I use id's as values: $filters[$filter] - get filter id by name
El diablo 07-Mar-2018 08:43
Get filter_list() with filter_id() as key.

<?php
print_r(array_flip(array_map('filter_id', array_combine(filter_list(), filter_list()))));
?>

Array
(
    [257] => int
    [258] => boolean
    [259] => float
    [272] => validate_regexp
    [277] => validate_domain
    [273] => validate_url
    [274] => validate_email
    [275] => validate_ip
    [276] => validate_mac
    [513] => stripped
    [514] => encoded
    [515] => special_chars
    [522] => full_special_chars
    [516] => unsafe_raw
    [517] => email
    [518] => url
    [519] => number_int
    [520] => number_float
    [521] => magic_quotes
    [1024] => callback
)
larry at weblabsperth dot com dot au 05-Sep-2016 09:42
Output a table of Filter IDs as Integers with corresponding Constant IDs:

<?php

echo '<table>';
echo '<tr>';
echo '<th>Filter Name</th>';
echo '<th>Filter Int ID</th>';
echo '<th>Filter Const ID</th>';
echo '</tr>';

foreach (filter_list() as $id =>$filter) {
    $const = 'FILTER_';
    switch($filter) {
        case 'int':
        case 'boolean':
        case 'float':
            $const .= 'VALIDATE_' . $filter;
        break;

        case 'string':
        case 'stripped':
        case 'encoded':
        case 'special_chars':
        case 'full_special_chars':
        case 'unsafe_raw':
        case 'email':
        case 'url':
        case 'number_int':
        case 'number_float':
        case 'magic_quotes':
            $const .= 'SANITIZE_' . $filter;
        break;
    }

    if (substr($filter,0,8)=='validate' || $filter=='callback')
        $const .= $filter;

    echo '<tr><td>' . $filter . '</td><td align="center">' . filter_id($filter) . '</td><td>' . strtoupper($const) . '</td></tr>';
}

echo '</table>';

?>
vb dot jyoti at gmail dot com 13-Aug-2008 11:57
<?php
echo "<pre>";
print_r(filter_list());
echo "</pre>";
foreach (filter_list() as $key => $value)
{
echo "<br>".$key."=".$value.'='.filter_id($value);
}
?>

0=int=257
1=boolean=258
2=float=259
3=validate_regexp=272
4=validate_url=273
5=validate_email=274
6=validate_ip=275
7=string=513
8=stripped=513
9=encoded=514
10=special_chars=515
11=unsafe_raw=516
12=email=517
13=url=518
14=number_int=519
15=number_float=520
16=magic_quotes=521
17=callback=1024


Retorna múltiple variables y opcionalmente las filtra

  • « filter_list
  • filter_var »
  • PHP Manual
  • Funciones de Filter
  • Retorna múltiple variables y opcionalmente las filtra

filter_var_array

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

filter_var_array — Retorna múltiple variables y opcionalmente las filtra

Descripción

filter_var_array ( array $data , mixed $definition = ? , bool $add_empty = true ) : mixed

Esta función es útil para recuperar muchos valores sin llamar repetidamente a filter_var().

Parámetros

data

Un array asociativo de claves en formato strings que contiene los datos a filtrar.

definition

Un array definiendo los argumentos. Una clave válida será aquella que contiene un string con el nombre de una variable y un valor válido aquel que o bien es un tipo filter type o un array especificando opcionalmente el filtro, flags y opciones. Si el valor es un array, las claves válidas serán: filter que especifica el tipo filter type, flags que define cualquier flag que deba aplicarse a los filtros, y options que establece cualquier opción que se deba aplicar al filtro. Para entender mejor su funcionamiento, vea el ejemplo inferior.

Este parámetro puede ser tambien un integer indicando una constante de filtro.. Entonces, todos los valores en el array de entrada son filtrados por este filtro.

add_empty

Añade claves faltantes como null al valor devuelto.

Valores devueltos

En caso de éxito un array que contiene los valores de las variables que se han pedido o false en caso de fallo. El valor del array será false si el filtro falla o null si la variable no está definida.

Ejemplos

Ejemplo #1 Ejemplo de filter_var_array()

<?php
error_reporting(E_ALL | E_STRICT);
$data = array(
    'id_producto'    => 'libgd<script>',
    'componente'     => '10',
    'versiones'      => '2.0.33',
    'test_escalar'    => array('2', '23', '10', '12'),
    'test_array'     => '2',
);

$args = array(
    'id_producto'   => FILTER_SANITIZE_ENCODED,
    'componente'    => array('filter'    => FILTER_VALIDATE_INT,
                            'flags'     => FILTER_FORCE_ARRAY,
                            'options'   => array('min_range' => 1, 'max_range' => 10)
                           ),
    'versiones'     => FILTER_SANITIZE_ENCODED,
    'no_existe' => FILTER_VALIDATE_INT,
    'test_scalar'   => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_SCALAR,
                           ),
    'test_array'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_FORCE_ARRAY,
                           )

);

$myinputs = filter_var_array($data, $args);

var_dump($myinputs);
echo "\n";
?>

El resultado del ejemplo sería:

array(6) {
  ["id_producto"]=>
  string(17) "libgd%3Cscript%3E"
  ["componente"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versiones"]=>
  string(6) "2.0.33"
  ["no_existe"]=>
  NULL
  ["test_escalar"]=>
  bool(false)
  ["test_array"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Historial de cambios

Versión | Descripción
5.4.0 | Se añadió el parámetro add_empty.

Ver también

  • filter_input_array() - Obtiene variables externas y opcionalmente las filtra
  • filter_var() - Filtra una variable con el filtro que se indique
  • filter_input() - Toma una variable externa concreta por su nombre y opcionalmente la filtra
  • Tipos de filtros

User Contributed Notes

Vee W. 19-Jun-2019 04:37
$emails = [
    'a' => 'email1@domain.com',
    'b' => '<email2>@domain.com',
];

$result = filter_var_array($emails, FILTER_SANITIZE_EMAIL);
print_r($result);

// the result will be...
// array('a' => 'email1@domain.com', 'b' => 'email2@domain.com')
tongcheong77 at gmail dot com 12-Jul-2017 05:44
an update to previous post.

using regular expressions along with another filter in filter var array

$data = array(

  'regxp' =>  "`\tcafé\n`"

  );

$args = array(

  'regxp'  =>  array(

  'filter'=>FILTER_VALIDATE_REGEXP | FILTER_SANITIZE_STRING,
  'flags'=>FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_BACKTICK,
  'options'=>array('regexp'=>"/t(.*)/"),

  ));

$output=filter_var_array($data,$args);

var_dump($output); // array(1) { ["regxp"]=> string(3) "caf" }

-bruce tong
tongcheong77 at gmail dot com 10-Jul-2017 06:10
for those who would like to know how to use regular expressions with filter var array. taken from w3 schools.

$data = array(

  'regxp' =>  'michael'

  );

$args = array(

  'regxp'  =>  array(

  'filter'=>FILTER_VALIDATE_REGEXP | FILTER_SANITIZE_STRING,
  'options'=>array('regexp'=>"/^michael$/"),

  ));

$output=filter_var_array($data,$args);

var_dump($output); // array(1) { ["regxp"]=> string(7) "michael" }

- bruce tong
eguvenc at gmail dot com 06-Jun-2009 03:45
<?php
//an example of simply sanitize an array..

$data = array(
                '<b>bold</b>',
                '<script>javascript</script>',
                'P*}i@893746%%%p*.i.*}}|.dw<?php echo "echo works!!";?>');

$myinputs = filter_var_array($data,FILTER_SANITIZE_STRING);

var_dump($myinputs);

//OUTPUT:
//formarray(3) { [0]=> string(4) "bold" [1]=> string(10) "javascript" [2]=> string(26) "P*}i@893746%%%p*.i.*}}|.dw" }
?>


Filtra una variable con el filtro que se indique

  • « filter_var_array
  • Manejo de Funciones »
  • PHP Manual
  • Funciones de Filter
  • Filtra una variable con el filtro que se indique

filter_var

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

filter_var — Filtra una variable con el filtro que se indique

Descripción

filter_var ( mixed $variable , int $filter = FILTER_DEFAULT , mixed $options = ? ) : mixed

Parámetros

variable

Valor a filtrar

filter

El ID del filtro a aplicar. La página Tipos de filtros del manual enumera los filtros disponibles.

Si se omite, se utilizará FILTER_DEFAULT, que es equivalente a FILTER_UNSAFE_RAW. Esto resultará en que no se realice ningún tipo de filtro de forma predeterminada.

options

Array asociativo de opciones o disyunción lógica de flags. Si un filtro acepta opciones, se pueden indicar flags en el campo "flags" del array. Para el filtro "callback" debería pasarse el tipo callable. La llamada de la función de retorno (callback) debe aceptar un argumento, el valor a ser filtrado y debe retornar el valor tras su filtrado/saneamiento.

<?php
// Para filtros que acepten opciones, usar este formato
$opciones = array(
    'options' => array(
        'default' => 3, // valor a retornar si el filtro falla
        // más opciones aquí
        'min_range' => 0
    ),
    'flags' => FILTER_FLAG_ALLOW_OCTAL,
);
$var = filter_var('0755', FILTER_VALIDATE_INT, $opciones);

// Para filtros que únicamente acepten flags, se pueden pasar directametne
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

// Para filtros que únicamente acepten flags, también pueden pasarse como
// array
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
                  array('flags' => FILTER_NULL_ON_FAILURE));

// Filtro "callback2
function foo($value)
{
    // Formato esperado: Apellido, Nombre
    if (strpos($value, ", ") === false) return false;
    list($surname, $givennames) = explode(", ", $value, 2);
    $empty = (empty($surname) || empty($givennames));
    $notstrings = (!is_string($surname) || !is_string($givennames));
    if ($empty || $notstrings) {
        return false;
    } else {
        return $value;
    }
}
$var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));
?>

Valores devueltos

Retorna los datos filtrados o false si el filtro falla.

Ejemplos

Ejemplo #1 Un ejemplo de filter_var()

<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
?>

El resultado del ejemplo sería:

string(15) "bob@example.com"
bool(false)

Ver también

  • filter_var_array() - Retorna múltiple variables y opcionalmente las filtra
  • filter_input() - Toma una variable externa concreta por su nombre y opcionalmente la filtra
  • filter_input_array() - Obtiene variables externas y opcionalmente las filtra
  • Tipos de filtros

User Contributed Notes

marcelo dot espindola at gmail dot com 20-Dec-2020 03:56
To remove multiple consecutive spaces replacing just one:

preg_replace('/\s\s+/', ' ', $value);
Robert Vlach 08-Apr-2020 06:33
I won't recommend using this function to validate email addresses on a normal website. The problem is that in accordance with RFC 3696 (Application Techniques for Checking and Transformation of Names) the following email addresses would be considered as valid:

customer/department=shipping@example.com
$A12345@example.com
!def!xyz%abc@example.com
_somename@example.com
"Abc@def"@example.com

Hardly something I would accept in a live web app in 2020 :-/
yactouat at hotmail dot com 18-May-2019 02:47
While getting familiar with filter_var( $var, FILTER_VALIDATE_INT ), I found interesting that 0 will be filtered out and therefore wont be considered as an int. Hope that helps someone not to be stuck ;)

N.B.: if you need to accept 0's, you could use is_int()
Steve 15-Oct-2018 01:47
The note from "hek" about HTML5 having patterns thus alleviating the need to filter in PHP is completely wrong:  You still must filter input on the server side.  The HTML5 form inputs are client-side, meaning they are completely under the user's control.  Only when you receive the data in PHP is it server-side and under your control.  Once the data is under your control, then you must filter/sanitize it properly.

This is true regardless of server-side language.  I would encourage the moderators to remove the note from "hek" because it will mislead people with horrible consequences.

Steve
Anonymous 06-Sep-2018 07:31
Replying to Andi:

This is NOT a valid URL, as the characters are not encoded

http://example.com/"><script>alert(document.cookie)</script>

This is a valid URL:

http://example.com/%22%3E%3Cscript%3Ealert%28document.cookie%29%3C%2Fscript%3E
mpyw628 at gmail dot com 22-Jul-2018 10:40
I wrote a JavaScript email validator fully compatible with PHP's filter_var() implementation.

mpyw/FILTER_VALIDATE_EMAIL.js: Email validation compatible with PHP's filter_var($value, FILTER_VALIDATE_EMAIL)
https://github.com/mpyw/FILTER_VALIDATE_EMAIL.js
ccbsschucko at gmail dot com 15-Jun-2018 12:59
<?php
    class Sanitizer {
        /**
        * @param str => $email = email a ser sanitizado
        */
        public static function email($email){
            return filter_var($email, FILTER_SANITIZE_EMAIL);
        }

        /**
        * @param str => $valor = valor a ser sanitizado
        * @param bol => $allow_accents = permitir acentos
        * @param bol => $allow_spaces = permitir espaços
        */
        public static function alfabetico($valor, bool $allow_accents = true, bool $allow_spaces = false){
            $valor = str_replace(array('"', "'", '`', '´', '¨'), '', trim($valor));
            if(!$allow_accents && !$allow_spaces){
                return preg_replace('#[^A-Za-z]#', '', $valor);
            }
            if($allow_accents && !$allow_spaces){
                return preg_replace('#[^A-Za-zà-zÀ-Z]#', '', $valor);
            }
            if(!$allow_accents && $allow_spaces){
                return preg_replace('#[^A-Za-z ]#', '', $valor);
            }
            if($allow_accents && $allow_spaces){
                return preg_replace('#[^A-Za-zà-zÀ-Z ]#', '', $valor);
            }
        }

        /**
        * @param str => $valor = valor a ser sanitizado
        */
        public static function alfanumerico($valor, bool $allow_accents = true, bool $allow_spaces = false){
            $valor = str_replace(array('"', "'", '`', '´', '¨'), '', trim($valor));
            if(!$allow_accents && !$allow_spaces){
                return preg_replace('#[^A-Za-z0-9]#', '', $valor);
            }
            if($allow_accents && !$allow_spaces){
                return preg_replace('#[^A-Za-zà-zÀ-Z0-9]#', '', $valor);
            }
            if(!$allow_accents && $allow_spaces){
                return preg_replace('#[^A-Za-z0-9 ]#', '', $valor);
            }
            if($allow_accents && $allow_spaces){
                return preg_replace('#[^A-Za-zà-zÀ-Z0-9 ]#', '', $valor);
            }
        }

        /**
        * @param str => $valor = valor a ser sanitizado
        */
        public static function numerico($valor){
            return preg_replace('/\D/', '', $valor);
        }

        /**
        * @param str => $valor = valor a ser sanitizado
        */
        public static function integer($valor){
            return (int)$valor;
        }

        /**
        * @param str => $valor = valor a ser sanitizado
        */
        public static function float($valor){
            return (float)$valor;
        }

        /**
        * @param str => $valor = valor a ser sanitizado
        */
        public static function money($valor){
            $valor = preg_replace('/\D/', '', $valor);
            if(strlen($valor) < 3){
                $valor = substr($valor, 0, strlen($valor)).'.00';
                return (float)$valor;
            }
            if(strlen($valor) > 2){
                $valor = substr($valor, 0, (strlen($valor)-2)).'.'.substr($valor, (strlen($valor)-2));
                return (float)$valor;
            }
        }

        /**
        * @param str => $valor = valor a ser sanitizado
        */
        public static function url($valor){
            $valor = strip_tags(str_replace(array('"', "'", '`', '´', '¨'), '', trim($valor)));
            return filter_var($valor, FILTER_SANITIZE_URL);
        }
    }
    // ex:
    var_dump(Sanitizer::numerico('bgusybd458ad8964sdfsd'));
    // 4588964
?>
crisp at tweakers dot net 09-Jan-2018 10:31
Note that only using FILTER_VALIDATE_URL to validate url's input may result in XSS:

$url = 'javascript://%0Aalert(document.cookie)';

if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED)) {
    echo '<a href="' . $url . '">click</a>';
}

You should at least additionally check the actually used scheme.
divinity76 at gmail dot com 22-Jun-2017 11:00
note that FILTER_VALIDATE_BOOLEAN tries to be smart, recognizing words like Yes, No, Off, On, both string and native types of true and false, and is not case-sensitive when validating strings.

<?php
$vals=array('on','On','ON','off','Off','OFF','yes','Yes','YES',
'no','No','NO',0,1,'0','1','true',
'True','TRUE','false','False','FALSE',true,false,'foo','bar');
foreach($vals as $val){
    echo var_export($val,true).': ';   var_dump(filter_var($val,FILTER_VALIDATE_BOOLEAN,FILTER_NULL_ON_FAILURE));
}
?>

outputs:
'on': bool(true)
'On': bool(true)
'ON': bool(true)
'off': bool(false)
'Off': bool(false)
'OFF': bool(false)
'yes': bool(true)
'Yes': bool(true)
'YES': bool(true)
'no': bool(false)
'No': bool(false)
'NO': bool(false)
0: bool(false)
1: bool(true)
'0': bool(false)
'1': bool(true)
'true': bool(true)
'True': bool(true)
'TRUE': bool(true)
'false': bool(false)
'False': bool(false)
'FALSE': bool(false)
true: bool(true)
false: bool(false)
'foo': NULL
'bar': NULL
alice at deviant dot email 02-May-2016 12:19
Many people, myself included, have found that the FILTER_VALIDATE_EMAIL does not actually properly work.

Below is a wrapper that I believe validates every legal routable address.

<?php

/*******************************************
 *
 * These are the function
 *
 *  check_username is called by check_email
 *  - it compensates for bugs in the php
 *    filter_var function.
 *  - returns boolean
 *
 *  check_email is the function to use.
 *  First argument is string, address to
 *    check
 *  Second argument is optional boolean,
 *    whether or not to use DNS to validate
 *    the domain name. Defaults to true
 *  Returns boolean
 *
 */

function check_username($uname) {
  //Only UTF-8 addresses are legal
  if (iconv('UTF-8', 'UTF-8', $input) != $input) {
      return FALSE;
  }
  //replace all characters above U+007F with letter U for simplicity of checking
  $uname = preg_replace('/[\x{007F}-\x{FFFF}]/u', 'U', $uname);

  //remove comments - only legal in format (comment) at beginning or end of username
  $s[] = '/^\([^\)]*\)/'; $s[] = '/\([^\)]*\)$/';
  $uname = preg_replace($s, '', $uname);
  //make sure we have something left
  if(strlen(trim($uname)) == 0) {
    return FALSE;
  }
  // check for legal dot usage
  if(substr_count($uname, '..') > 0) {
    return FALSE;
  }
  // convert \\ and \" to an A for simplicity
  $s[] = '/[\\\][\\\]/';
  $s[] = '/\\\"/';
  $uname = preg_replace($s, 'A', $uname);
  // check for illegal use of quotes
  if(preg_match('/[^.]+"[^.]+/', $uname)) {
    return FALSE;
  }
  // compensate for characters legal when in quotes
  $uname = preg_replace_callback('/"(.*)"/', function ($m) {
    $s[]="/[ \(\),\:;<>@\[\] ]/";
    return preg_replace($s,'Q',$m[1]);
    }, $uname);
  // check what we have left with filter_var
  return filter_var($uname . '@example.org', FILTER_VALIDATE_EMAIL);
}

function check_email($email, $dns_check=true) {
  $array = explode('@', $email);
  if(count($array) < 2) {
    return FALSE;
  }
  $domain = end($array);
  array_pop($array);
  if(function_exists('idn_to_ascii')) {
    //php filter no workie with unicode characters
    $domain = idn_to_ascii($domain);
  }
  $ipcheck = preg_replace(array('/^\[ipv6\:/i', '/^\[/', '/\]$/'), '', $domain);
  if(filter_var($ipcheck, FILTER_VALIDATE_IP)) {
    // it's an IP address
    if(! filter_var($ipcheck, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
      return FALSE;
    }
  } else {
    // it's a domain name
    //   php bug - FILTER_VALIDATE_EMAIL doesn't like naked TLD
    if(! filter_var('user@a.' . $domain, FILTER_VALIDATE_EMAIL)) {
      return FALSE;
    }
    if($dns_check) {
      if(! dns_get_record($domain)) {
        return FALSE;
      }
    }
  }
  //now check legal username
  return check_username(implode('@', $array));
}
?>
It evaluates the address in two parts, first evaluating the host and if that legal it then evaluates the user name.

If there is a DNS problem *and* the default $dns_check value of true is used, valid will fail. If it is an international domain name, you have to have the php-intl package installed.

Enjoy.
buttflattery at gmail dot com 18-Jan-2016 03:15
FILTER_VALIDATE_URL validates a url like http://www.
amy at anvilzephyr dot com 10-Jan-2016 08:14
It might be wise to trim or sanitize (FILTER_SANITIZE_EMAIL) your email variable before validating to remove spaces:
filter_var(trim($email), FILTER_VALIDATE_EMAIL)
Ant 14-Dec-2015 02:20
Note: filter_var with filter=FILTER_VALIDATE_URL used parse_url function
dan at spiral8 dot net 08-Dec-2015 02:23
Here's a simple test using filter_var with FILTER_VALIDATE_URL.
(If you're using file_get_contents after this you will run into a problem, I was using: PHP 5.5.12 (cli))

<?php
$url = 'a://google.com';

$result = filter_var($url, FILTER_VALIDATE_URL);

if($result){
    echo 'Valid URL'.PHP_EOL;
}

var_dump($result);
?>

The result is:
Valid URL
string(14) "a://google.com"
yoanlin93 at gmail dot com 22-Nov-2015 06:34
Some boolean conversions:

<?php
var_dump(filter_var('oops', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// NULL

var_dump(filter_var('false', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)

var_dump(filter_var('true', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(true)

var_dump(filter_var(0, FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)

var_dump(filter_var(1, FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(true)

var_dump(filter_var('TRUE', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(true)

var_dump(filter_var('', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)

var_dump(filter_var('FALSE', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)
Anonymous 04-Nov-2015 11:20
FILTER_VALIDATE_URL allows:

filter_var('javascript://comment%0Aalert(1)', FILTER_VALIDATE_URL);

Where the %0A (URL encoded newline), in certain contexts, will split the comment from the JS code.

This can result in an XSS vulnerability.
joe at bloe dot com 13-Jul-2014 03:04
"(comment)localpart@example.com"
is an invalid E-Mail address per RFC5322 (Appendix A.6.3):
"Also, the comments and white space throughout addresses, dates, and message identifiers are all part of the obsolete syntax."
george at NOSPAM dot crownvalleysoftware dot com 30-Apr-2014 10:08
In the options, "logical disjunction" means "or" - for example:
filter_var($somestring ,FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
Tom 18-Nov-2013 10:23
It is important to note that though the data type of the first parameter of the function is stated as "mixed", this is only one half of the truth.

While it accepts any data type, the first parameter will always be cast to string before being validated or sanitized.

It seems that this function was designed strictly to be used on user input strings. For example: from an online-form. When using it for anything other than that, you may see issues. So read the documentation very carefully!

Especially note that there is an (to date) unresolved issue (#49510) concerning the Boolean filter while using the FILTER_NULL_ON_FAILURE flag. Note that both (string) FALSE and FALSE are not recognized as boolean values and will return NULL (not FALSE as you might expect).

I thus personally suggest that (to date) the best way to take the filter_var()-functions beyond their original purpose (and allow future extension and customization) is to wrap them in your own classes. This will allow you to work-around unexpected behavior on non-string input and add your custom checks, or back-port filters or sanitizers that may be added in later versions of PHP.
(Especially since PHP currently still lacks filters and sanitizers for some of the more exotic HTML5 input types, like "color". Thus there actually is a chance that we may see a need for custom filters or backports at some point in the future.)
CertaiN 01-Aug-2013 10:35
E-mail validator function that supports IPv6 and checking length.
This also supports Japanese old feature phone E-mail address by sending second argument $strict as FALSE.

<?php

function validate_email($email, $strict = true) {
    $dot_string = $strict ?
        '(?:[A-Za-z0-9!#$%&*+=?^_`{|}~\'\\/-]|(?<!\\.|\\A)\\.(?!\\.|@))' :
        '(?:[A-Za-z0-9!#$%&*+=?^_`{|}~\'\\/.-])'
    ;
    $quoted_string = '(?:\\\\\\\\|\\\\"|\\\\?[A-Za-z0-9!#$%&*+=?^_`{|}~()<>[\\]:;@,. \'\\/-])';
    $ipv4_part = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
    $ipv6_part = '(?:[A-fa-f0-9]{1,4})';
    $fqdn_part = '(?:[A-Za-z](?:[A-Za-z0-9-]{0,61}?[A-Za-z0-9])?)';
    $ipv4 = "(?:(?:{$ipv4_part}\\.){3}{$ipv4_part})";
    $ipv6 = '(?:' .
        "(?:(?:{$ipv6_part}:){7}(?:{$ipv6_part}|:))" . '|' .
        "(?:(?:{$ipv6_part}:){6}(?::{$ipv6_part}|:{$ipv4}|:))" . '|' .
        "(?:(?:{$ipv6_part}:){5}(?:(?::{$ipv6_part}){1,2}|:{$ipv4}|:))" . '|' .
        "(?:(?:{$ipv6_part}:){4}(?:(?::{$ipv6_part}){1,3}|(?::{$ipv6_part})?:{$ipv4}|:))" . '|' .
        "(?:(?:{$ipv6_part}:){3}(?:(?::{$ipv6_part}){1,4}|(?::{$ipv6_part}){0,2}:{$ipv4}|:))" . '|' .
        "(?:(?:{$ipv6_part}:){2}(?:(?::{$ipv6_part}){1,5}|(?::{$ipv6_part}){0,3}:{$ipv4}|:))" . '|' .
        "(?:(?:{$ipv6_part}:){1}(?:(?::{$ipv6_part}){1,6}|(?::{$ipv6_part}){0,4}:{$ipv4}|:))" . '|' .
        "(?::(?:(?::{$ipv6_part}){1,7}|(?::{$ipv6_part}){0,5}:{$ipv4}|:))" .
    ')';
    $fqdn = "(?:(?:{$fqdn_part}\\.)+?{$fqdn_part})";
    $local = "({$dot_string}++|(\"){$quoted_string}++\")";
    $domain = "({$fqdn}|\\[{$ipv4}]|\\[{$ipv6}]|\\[{$fqdn}])";
    $pattern = "/\\A{$local}@{$domain}\\z/";
    return preg_match($pattern, $email, $matches) &&
        (
            !empty($matches[2]) && !isset($matches[1][66]) && !isset($matches[0][256]) ||
            !isset($matches[1][64]) && !isset($matches[0][254])
        )
    ;
}

?>
gt at kani dot hu 21-Jun-2013 02:31
I found some addresses that FILTER_VALIDATE_EMAIL rejects, but RFC5321 permits:
<?php
foreach (array(
        'localpart.ending.with.dot.@example.com',
        '(comment)localpart@example.com',
        '"this is v@lid!"@example.com',
        '"much.more unusual"@example.com',
        'postbox@com',
        'admin@mailserver1',
        '"()<>[]:,;@\\"\\\\!#$%&\'*+-/=?^_`{}| ~.a"@example.org',
        '" "@example.org',
    ) as $address) {
    echo "<p>$address is <b>".(filter_var($address, FILTER_VALIDATE_EMAIL) ? '' : 'not')." valid</b></p>";
}
?>
Results:

localpart.ending.with.dot.@example.com is not valid
(comment)localpart@example.com is not valid
"this is v@lid!"@example.com is not valid
"much.more unusual"@example.com is not valid
postbox@com is not valid
admin@mailserver1 is not valid
"()<>[]:,;@\"\\!#$%&'*+-/=?^_`{}| ~.a"@example.org is not valid
" "@example.org is not valid

The documentation does not saying that FILTER_VALIDATE_EMAIL should pass the RFC5321, however you can meet with these examples (especially with the first one). So this is a note, not a bug report.
drew_mirage at hotmail dot com 18-Jun-2013 07:14
One key thing to remember about filtering integers is that the value for the option max_range must be less than or equal to the value of PHP_INT_MAX.

filter_var($someVariable, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => SOME_VALUE_GREATER_THAN_PHP_INT_MAX)));

This will fail even if $someVariable is a valid integer in the expected range.

This can show up when you are attempting to validate a potential key for an unsigned MySQL INT type (whose maximum value is 4294967295) on a 32-bit system, where the value of PHP_INT_MAX is 2147483647.
cabrinosimone at gmail dot com 02-Apr-2013 03:19
Pay attention that the function will not validate "not latin" domains.

if (filter_var('??????@??.??', FILTER_VALIDATE_EMAIL)) {
    echo 'VALID';
} else {
    echo 'NOT VALID';
}
alex4home at gmail dot com 10-Jan-2013 12:18
Keep in mind that FILTER_VALIDATE_EMAIL will validate the email address according to standards.
However, giving the fact that organizations are free to restrict the forms of their own email addresses, using ONLY this filter can you a lot of bounces.

gmail, yahoo, hotmail, aol have special rules

For example :
<?php

$email_a = '0hot\'mail_check@hotmail.com';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_a) email address is considered valid.";
   //reported as valid
}

//there can be no  "0hotmail_check@hotmail.com"
//because hotmail will say "Your email address needs to start with a letter. Please try again." even if you remove the '
?>
marcus at synchromedia dot co dot uk 03-Sep-2012 09:13
It's very likely that you actually want to detect all reserved ranges, not just private IPs, and there's another constant for them that should be bitwise-OR'd with it.
<?php
function is_private_ip($ip) {
    return !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
}
?>
Martin L 27-Jul-2012 10:35
FILTER_SANITIZE_EMAIL header injection test.

<?php
$InjString = "\r\n|\n|%0A|%0D|bcc:|to:|cc:|Content-Type:|Mime-Type:|";
echo filter_var($InjString, FILTER_SANITIZE_EMAIL);
?>

||%0A|%0D|bcc|to|cc|Content-Type|Mime-Type|
Andi, info at pragmamx dot org 23-May-2012 06:07
And this is also a valid url

http://example.com/"><script>alert(document.cookie)</script>
keevitaja at gmail dot com 28-Jan-2012 08:05
please note FILTER_VALIDATE_URL passes following url

http://example.ee/sdsf"f
joelhy 06-Jul-2011 02:44
For those looking for private ip checking, there it is:
<?php
 function is_private_ip($ip)
{
     return !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);
}
?>
php at maisqi dot com 27-May-2011 07:11
FILTER_VALIDATE_URL does not support internationalized domain name (IDN). Valid or not, no domain name with Unicode chars on it will pass validation.

We can circumvent this with a home grown solutions, but C code is C code, so I've gone for the code bellow, which builds on filter_var().

<?php
$res = filter_var ($uri, FILTER_VALIDATE_URL);
if ($res) return $res;
// Check if it has unicode chars.
$l = mb_strlen ($uri);
if ($l !== strlen ($uri)) {
    // Replace wide chars by “X”.
    $s = str_repeat (' ', $l);
    for ($i = 0; $i < $l; ++$i) {
        $ch = mb_substr ($uri, $i, 1);
        $s [$i] = strlen ($ch) > 1 ? 'X' : $ch;
    }
    // Re-check now.
    $res = filter_var ($s, FILTER_VALIDATE_URL);
    if ($res) {    $uri = $res; return 1;    }
}
?>

The logic is simple. A non-ascii char is more than one byte long. We replace every one of those chars by "X" and check again.

An alternative will be to punycode the URI before calling filter_var(), but PHP lacks native support for punycode. I think my approach is effective. Please e-mail me if you think otherwise or see room for improvement.
drtebi at yahoo 24-Nov-2009 11:55
Notice that filter_var with FILTER_VALIDATE_EMAIL does not work if you are trying to get a String from an XML document e.g. via xpath.

I often use XML files as configuration files and use a function that returns a string from the config file via xpath. While this worked fine before 5.2.11, it doesn't anymore (and shouldn't, since it's an XML Element, not a String).

To overcome this problem, $variable can be type-casted:

<?php
$variable = fancyXmlGetFunction('from');
filter_var((String) $variable, FILTER_VALIDATE_EMAIL);
?>
jon dot bertsch at ucop dot edu 24-Mar-2009 07:49
Here's an actual example of the filter syntax with a flag since there doesn't appear to be a one liner for this anywhere:

'hours' => array('filter'=>FILTER_SANITIZE_NUMBER_FLOAT, 'flags' => FILTER_FLAG_ALLOW_FRACTION, 'options'=> '.')
dyer85 at gmail dot com 03-Nov-2008 02:00
Note that when using FILTER_VALIDATE_INT along with the FILTER_FLAG_ALLOW_HEX flag, the string "2f", for example, is not validated successfully, because you must use the "0x" prefix, otherwise, it treats the data as base 10.

The range options are also smart enough to recognize when the boundaries are exceeded in different bases.

Here's an example:

<?php

$foo = '256';
$bar = '0x100';
var_dump(validate_int($foo)); // false, too large
var_dump(validate_int($bar)); // false, too large

function validate_int($input)
{
  return filter_var(
    $input,
    FILTER_VALIDATE_INT,

    // We must pass an associative array
    // to include the range check options.
    array(
      'flags'   => FILTER_FLAG_ALLOW_HEX,
      'options' => array('min_range' => 1, 'max_range' => 0xff)
    )
  );
}

?>
dale dot liszka at gmail dot com 09-Jul-2008 10:15
Here is how to use multiple flags (for those who learn better by example, like me):

<?php
echo "|asdf".chr(9).chr(128)."_123|";
echo "\n";
// "bitwise conjunction" means logic OR / bitwise |
echo filter_var("|asdf".chr(9).chr(128)."_123\n|" ,FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);

/*
Results:
|asdf    ?_123|
|asdf_123|
*/
?>
dale dot liszka at gmail dot com 09-Jul-2008 09:54
Using the FILTER_CALLBACK requires an array to be passed as the options:

<?php
function toDash($x){
   return str_replace("_","-",$x);
}

echo filter_var("asdf_123",FILTER_CALLBACK,array("options"=>"toDash"));
// returns 'asdf-123'
?>
John 26-Jul-2007 12:35
I managed to get this to work with PHP 5.1.6 on CentOS 5 with minor difficulty.

1) Download the PECL filter package
2) Extract the tarball
3) phpize the directory
4) ./configure
5) make
6) filter-0.11.0/logical_filters.c:25:31: error: ext/pcre/php_pcre.h: No such file or directory
7) find / -name php_pcre.h
8) Make sure php-devel is installed
9) Edit filter-0.11.0/logical_filters.c and replace "ext/pcre/php_pcre.h" with the absolute path of php_pcre.h
10) make
11) make install
12) add "extension=filter.so" to php.ini
13) Restart Apache


Manejo de Funciones

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Funciones de Manejo de Funciones
    • call_user_func_array — Llamar a una llamada de retorno con un array de parámetros
    • call_user_func — Llamar a una llamada de retorno dada por el primer parámetro
    • create_function — Crear una función anónima (estilo lambda)
    • forward_static_call_array — Llamar a un método estático y pasar los argumentos como matriz
    • forward_static_call — Llamar a un método estático
    • func_get_arg — Devuelve un elemento de una lista de argumentos
    • func_get_args — Devuelve un array que se compone de una lista de argumentos de función
    • func_num_args — Devuelve el número de argumentos pasados a la función
    • function_exists — Devuelve true si la función dada ha sido definida
    • get_defined_functions — Devuelve un array de todas las funciones definidas
    • register_shutdown_function — Registrar una función para que sea ejecutada al cierre
    • register_tick_function — Registrar una función para que sea ejecutada en cada tick
    • unregister_tick_function — Dejar de registrar una función para su ejecución en cada tick

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Todas estas funciones tratan varias operaciones involucradas al trabajar con funciones.

User Contributed Notes

There are no user contributed notes for this page.


Funciones de Manejo de Funciones

Tabla de contenidos

  • call_user_func_array — Llamar a una llamada de retorno con un array de parámetros
  • call_user_func — Llamar a una llamada de retorno dada por el primer parámetro
  • create_function — Crear una función anónima (estilo lambda)
  • forward_static_call_array — Llamar a un método estático y pasar los argumentos como matriz
  • forward_static_call — Llamar a un método estático
  • func_get_arg — Devuelve un elemento de una lista de argumentos
  • func_get_args — Devuelve un array que se compone de una lista de argumentos de función
  • func_num_args — Devuelve el número de argumentos pasados a la función
  • function_exists — Devuelve true si la función dada ha sido definida
  • get_defined_functions — Devuelve un array de todas las funciones definidas
  • register_shutdown_function — Registrar una función para que sea ejecutada al cierre
  • register_tick_function — Registrar una función para que sea ejecutada en cada tick
  • unregister_tick_function — Dejar de registrar una función para su ejecución en cada tick

User Contributed Notes

php dot spamguard at pulseforce dot com 27-Jan-2009 06:31
PHP is great in how it allows you to send a variable-length argument list to a function by using the func_* functions. However, unfortunately (and this has been brought up numerous time in PHP bug reports/feature requests), it doesn't support passing arguments by reference which would have greatly simplified processing multiple variables at once by simply doing: somefunction($a, $b, $c) and having them processed, without having to do any additional assignment.

However, I've discovered a way to leverage several features of PHP and created a very good example that shows how you can process multiple variables in one fell swoop!

The usage is (with my example function/class):
"list($a, $b, $c, $d, $e) = TextEscape::escape_multi($a, $b, $c, $d, $e);"

If PHP had ACTUALLY been capable of passing variables by reference when using variable-length argument lists, that could have been reduced to:
"TextEscape::escape_multi($a, $b, $c, $d, $e);"

It's extremely close though, both in simplicity and speed. Just be VERY sure to ALWAYS have the SAME NUMBER AND ORDER of arguments on both sides of that statement.

The use of a static class was just to make the code cleaner and easier to look at. This can be applied to any functions!

Now, onto the code, enjoy the sheer brilliance and enjoy modifying multiple variables at once in just ONE statement! ;-)

<?php

class TextEscape
{
    public static function escape_string($sString)
    {
        /* can be anything, using htmlspecialchars() in this example */
        return htmlspecialchars($sString);
    }

    public static function escape_multi()
    {
        /* get all variables passed to the function */
        $aVariables = func_get_args();

        /* loop through the array, escaping each variable */
        foreach ($aVariables as $iKey => $sValue)
        {
            $aVariables[$iKey] = TextEscape::escape_string($sValue);
        }

        /* return the escaped values */
        return $aVariables;
    }
}

// Create test variables
$a = "A<bar";
$b = "B>bar";
$c = "C<bar";
$d = "D>bar";
$e = "E<bar";

// Variables Before:
// Array
// (
//    [0] => A<bar
//    [1] => B>bar
//    [2] => C<bar
//    [3] => D>bar
//    [4] => E<bar
// )
print_r(array($a, $b, $c, $d, $e));

// Process every variable at once,
// we're exploiting both how list() and
// variable-length argument lists work
// to make the usage this smooth! ;-)
list($a, $b, $c, $d, $e) = TextEscape::escape_multi($a, $b, $c, $d, $e);

// Variables After:
// Array
// (
//    [0] => A&lt;bar
//    [1] => B&gt;bar
//    [2] => C&lt;bar
//    [3] => D&gt;bar
//    [4] => E&lt;bar
// )
print_r(array($a, $b, $c, $d, $e));

?>

That's the CLEAN LOOKING version of the code, which illustrates exactly what is HAPPENING.

I also made a speedfreak edition of the function, but didn't want to post it as the main example since it's harder to read.

But it's faster, much faster! It passes by reference where it can and loops in a more efficient way.

Just replace the above function with this one, the outcome is the same but the speed is better:

<?php

class TextEscape
{
    public static function escape_string(&$sString) // CHANGED: we now pass by reference to the actual text processing function
    {
        /* can be anything, using htmlspecialchars() in this example */
        $sString = htmlspecialchars($sString);
    }

    public static function escape_multi()
    {
        /* get all variables passed to the function */
        $aVariables = func_get_args();

        /* loop through the array, escaping each variable */
        for ($i=(count($aVariables)-1); $i>=0; $i--) // CHANGED: a more efficient for-loop is used instead of a foreach; and for anyone wondering about the counter declaration, this is a common optimization trick which makes it so that the size of the array only has to be checked ONCE, by initializing the counter to the index of the last element (which is size of array minus 1) and then iterating downwards until we reach 0 (the first element)
        {
            TextEscape::escape_string($aVariables[$i]); // CHANGED: this has been changed to modify the variable by reference instead
        }

        /* return the escaped values */
        return $aVariables;
    }
}

?>

Enjoy!
Michael T. McGrew 12-May-2005 09:56
An interesting way to use functions is by putting other things than PHP in them, i.e. HTML CSS. This can be useful if you will be using a format for many pages. Yes, the include function can be used also, but by defining them in functions can make them more portable in a way and keep you from having to make many include files. You could use include() when one will be putting big portions of PHP, HTML, and/or CSS and will be using them in many pages. Then you could use PHP, HTML, and/or CSS in a function when it is smaller portions of code and only want it to be on a few pages.

I have been using include() for HTML and CSS in my early days of PHP coding, but I will be using functions for that a lot more now.

<?php function a() {  ?>
<style type="text/css">
table {
border: 1px dashed black;
background: #95EAFE;
text-align:left;
width:610px;
}
.linkbar {
font-family:sans-serif;
line-height:40px;
top:1px;
text-align:center;
width:200px;
height:10px;
}
</style>
<?php }  ?>

Now doing:
<?php a(); ?>
will return all of the CSS just as if you had wrote it on the actual page, or used include() . The same thing goes for HTML code inside a function. The possibilities are endless...
michael dot bommarito at gmail dot com 30-Jan-2005 11:28
I've developed an easy-to-use hack using these functions to emulate overloaded functions.  It's especially handy for constructors and/or C++ style templating.

Here's a little example to get you going.  This does the trick for most circumstances, and if you need more intelligent parsing, it's not too hard to implement with regex or a more suitable classification scheme.

N.B. Note the lack of whitespace between variable types in case strings.

class Matrix {

...

function Matrix() {
  $args = func_get_args();
  $argmatch = implode(",", array_map('gettype', $args));

  switch( $argmatch ) {
    case 'integer,integer':
      //initialize m x n matrix
      break;

    case 'integer,integer,integer':
      //initialize m x n matrix with constant c
      break;

    case 'integer,integer,float':
      //initialize m x n matrix with constant c
      break;

    case 'array':
      //initialize from array (2D....)
      break;

    case 'array,integer':
      //intialize from array (1D packed with m rows)
      break;

    default:
      //(void) overload?
      //error handling?
      break;
  }
}

...

}
php-note-2003-june-18 at ryandesign dot com 18-Jun-2003 08:22
Xavier's example is rather complicated, and his task would be much more simply accomplished by using classes. Define a base class to do the basic functions open, dump, and close, and create extension classes to override whatever behavior.

class foo {
  function open() {
    // Default functionality for open()
  }
  function dump() {
    // Default functionality for dump()
  }
  function close() {
    // Default functionality for close()
  }
}

class bar extends foo {
  function open() {
    // Override functionality of open()
  }
  // dump() and close() remain as in class foo
}
xmontero at dsitelecom dot com 23-Aug-2002 02:49
You can do some kind of overloading functions in PHP using "function_exists".

Let's suppose you want a script to call plugins that are php files and you want the plugins to "override" behaviours that if not overriden are used by default.

You might for example write a "mySQL table viewer" which displays a table and it "opens a table", "dumps the header", "dumps row-by-row" and then "closes the table".

Let's suppose you want a plugin for "Stocks" which prints negative stocks in red, so you want to override the "dumping row-by-row" to do that behaviour. Instead you do not want to have all the "default behaviour" repeated in the plugin.

You may then do the following:

1) Define a default plugin (ex: "default.php"

2) Write all your functions in default.php to open, dump and close, but add them a suffix:

open_table_default()
dump_header_default()
dump_row_default()
close_table_default()

3) Call your functions with a wrapper: Insetad of this:
open_table() or open_table_default() write this:

plugincall("open_table");

4) Then write a function called plugincall which uses function_exists() to see if you call one or the other function:

function plugincall($desired_function_name)
{

if( function_exists( $desired_function_name))
{
    //Call the plugin
    //Note the $ before the name
    $desired_function_name()
}
else
{
  $desired_function_name = $desired_function_name . "_default";
  if( function_exists($desired_function_name))
  {
      //Call the default
      //Note the $ before the name
      $desired_function_name()
  }
  else
  {
      // Nor the plugin nor the default were defined
  }
}

So, now, if the require_once(plugin.php) contains a function called "open_table()", it will be used. Instaed, "open_table_default()" will be used.

It's not like overloading functions, but it is very useful to write scripts ampliable by other programmers: If they write a function, it is used, if not, the default is used.

See ya!
Xavier Montero.


Llamar a una llamada de retorno con un array de parámetros

  • « Funciones de Manejo de Funciones
  • call_user_func »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Llamar a una llamada de retorno con un array de parámetros

call_user_func_array

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

call_user_func_array — Llamar a una llamada de retorno con un array de parámetros

Descripción

call_user_func_array ( callable $callback , array $param_arr ) : mixed

Llama a la llamada de retorno dada por el primer parámetro callback con los parámetros de param_arr.

Parámetros

callback

La función llamable (callable) a llamar.

param_arr

Los parámetros a pasar a la llamada de retorno, como matriz indexada.

Valores devueltos

Devuelve el valor devuelto por la llamada de retorno, o false en caso de error.

Historial de cambios

Versión | Descripción
5.3.0 | La interpretación de palabras clave orientadas a objetos como parent y self ha cambiado. Anteriormente al llamarlas usando la sintaxis de dobles dos puntos emitiría una advertencia E_STRICT porque eran interpretadas como estáticas.

Ejemplos

Ejemplo #1 Ejemplo de call_user_func_array()

<?php
function foobar($arg, $arg2) {
    echo __FUNCTION__, " obtuvo $arg y $arg2\n";
}
class foo {
    function bar($arg, $arg2) {
        echo __METHOD__, " obtuvo $arg y $arg2\n";
    }
}

// Llamar a la función foobar() con 2 argumentos
call_user_func_array("foobar", array("uno", "dos"));

// Llamar al método $foo->bar() con 2 argumentos
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("tres", "cuatro"));
?>

El resultado del ejemplo sería algo similar a:

foobar obtuvo uno y dos
foo::bar obtuvo tres y cuatro

Ejemplo #2 call_user_func_array() usando un nombre de espacio de nombres

<?php

namespace Foobar;

class Foo {
    static public function prueba($nombre) {
        print "¡Hola {$nombre}!\n";
    }
}

// A partir de PHP 5.3.0
call_user_func_array(__NAMESPACE__ .'\Foo::prueba', array('Gema'));

// A partir de PHP 5.3.0
call_user_func_array(array(__NAMESPACE__ .'\Foo', 'prueba'), array('Pedro'));

?>

El resultado del ejemplo sería algo similar a:

¡Hola Gema!
¡Hola Pedro!

Ejemplo #3 Usar una función lambda

<?php

$func = function($arg1, $arg2) {
    return $arg1 * $arg2;
};

var_dump(call_user_func_array($func, array(2, 4))); /* A partir de PHP 5.3.0 */

?>

El resultado del ejemplo sería:

int(8)

Notas

Nota:

Antes de PHP 5.4, las variables referenciadas de param_arr son pasadas a la función por referencia, sin tener en cuenta si la función espera que el parámetro respectivo sea pasado por referencia. Esta forma de paso por referncia en tiempo de llamda no emite un aviso de obsolescencia, pero, no obstante, está obsoleta, y ha sido eliminada en PHP 5.4. Además, esto no se aplica a funciones internas, para las que la firma de la funcion es aceptada. Pasar por valor cuando la función espera un parámetro por referencia resulta en una advertencia, y call_user_func() devolverá false (existe, sin embargo, una excepción para valores pasados con cuenta de referencia = 1, como en los literales, ya que pueden convertirse en referencias sin efectos dañinos — aunque también sin escribir que esos valores tengan ningún efecto —; sin embargo, no confíe en este comportamiento, ya que la cuenta de referencia es un detalle de implementación y la solidez de este comportamiento es cuestinable).

Nota:

Las funciones de retorno de llamada que se registran con funciones como call_user_func() y call_user_func_array() no se llamarán si se produce una excepción en la función de retorno previa.

Ver también

  • call_user_func() - Llamar a una llamada de retorno dada por el primer parámetro
  • ReflectionFunction::invokeArgs() - Invoca a la función con argumentos
  • ReflectionMethod::invokeArgs() - Invoca un método con argumentos

User Contributed Notes

simopelle04 at gmail dot com 18-Jan-2021 09:27
Since PHP 5.6 you can use the spread operator (argument unpacking) instead of call_user_func_array().

    public function __call($name, $arguments) {
        if(method_exists($this->foo, $name))
            return call_user_func_array(array($this->foo, $name), $arguments);    //calls function from inside $this->foo
        else
            throw new BadMethodCallException('Call to undefined method ' . static::class . "::$name()", 0);    //the method does not exist on $this->foo
    }

is the same as

    public function __call($name, $arguments) {
        if(method_exists($this->foo, $name))
            return $this->foo->$name(...$arguments);    //calls function from inside $this->foo
        else
            throw new BadMethodCallException('Call to undefined method ' . static::class . "::$name()", 0);    //the method does not exist on $this->foo
    }
Anonymous 21-Nov-2019 12:10
<?php

namespace Foobar;

class Foo {

    public $email;
    public $name;
    public $age;

    public function setEmail($email) {
        $this->email = $email;
    }
    public function setName($name) {
        $this->name = $name;
    }
    public function setAge($age) {
        $this->age = $age;
    }
}

function getFields() {
    return [
        "age" => 112,
        "email" => "lol@lol.fr",
        "name" => "lol"
    ];
}

$foo = new Foo();

$callables = ["email" => $email,"name" => $name,"age" => $age] = getFields();

foreach ($callables as $func => $value) {
    call_user_func(array($foo,sprintf("set%s",ucfirst($func))),$value));
}

var_dump($foo);
Aurelien Marchand 24-Oct-2019 03:24
In response to  admin at torntech dot com and as shown on https://gist.github.com/nikic/6390366, there is no good reason to use argument unpacking anymore for PHP 7.0.17, 7.1.3, 7.2.7

7.0.17
cufa with 0 args took 0.081735849380493
unpack with 0 args took 0.072259902954102
cufa with 100 args took 0.39941906929016
unpack with 100 args took 0.419842004776

7.1.3
cufa with 0 args took 0.074923992156982
unpack with 0 args took 0.07165002822876
cufa with 100 args took 0.37423300743103
unpack with 100 args took 0.41387891769409

7.2.7
cufa with 0 args took 0.064092874526978
unpack with 0 args took 0.048593997955322
cufa with 100 args took 0.35412693023682
unpack with 100 args took 0.36837601661682
ben at benhunt dot com 29-Nov-2018 04:23
If you're thinking call_user_func_array has changed the array of multiple parameters to a string, remember that it does not pass the array through to the called function as a single argument (array), but creates one argument for each element in the array.
zonkiie 01-Jul-2017 04:38
An implementation where parameters are submitted by their name.
This function calls class functions, class methods, functions and anonymous functions.

/**
    * Calls a method, function or closure. Parameters are supplied by their names instead of their position.
    * @param $call_arg like $callback in call_user_func_array()
    * Case1: {object, method}
    * Case2: {class, function}
    * Case3: "class::function"
    * Case4: "function"
    * Case5: closure
    * @param array $param_array A key-value array with the parameters
    * @return result of the method, function or closure
    * @throws \Exception when wrong arguments are given or required parameters are not given.
    */
function call_user_function_named_param($call_arg, array $param_array)
{
    $Func = null;
    $Method = null;
    $Object = null;
    $Class = null;
    // The cases. f means function name
    // Case1: f({object, method}, params)
    // Case2: f({class, function}, params)
    if(is_array($call_arg) && count($call_arg) == 2)
    {
        if(is_object($call_arg[0]))
        {
            $Object = $call_arg[0];
            $Class = get_class($Object);
        }
        else if(is_string($call_arg[0]))
        {
            $Class = $call_arg[0];
        }
        if(is_string($call_arg[1]))
        {
            $Method = $call_arg[1];
        }
    }
    // Case3: f("class::function", params)
    else if(is_string($call_arg) && strpos($call_arg, "::") !== FALSE)
    {
        list($Class, $Method) = explode("::", $call_arg);
    }
    // Case4: f("function", params)
    else if(is_string($call_arg) && strpos($call_arg, "::") === FALSE)
    {
        $Method = $call_arg;
    }
    // Case5: f(closure, params)
    else if(is_object($call_arg) && $call_arg instanceof \Closure)
    {
        $Method = $call_arg;
    }
    else throw new \Exception("Case not allowed! Invalid Data supplied!");
    if($Class) $Func = new \ReflectionMethod($Class, $Method);
    else $Func = new \ReflectionFunction($Method);
    $params = array();
    foreach($Func->getParameters() as $Param)
    {
        if($Param->isDefaultValueAvailable()) $params[$Param->getPosition()] = $Param->getDefaultValue();
        if(array_key_exists($Param->name, $param_array)) $params[$Param->getPosition()] = $param_array[$Param->name];
        if(!$Param->isOptional() && !isset($params[$Param->getPosition()])) die("No Defaultvalue available and no Value supplied!\r\n");
    }
    if($Func instanceof \ReflectionFunction) return $Func->invokeArgs($params);
    if($Func->isStatic()) return $Func->invokeArgs(null, $params);
    else return $Func->invokeArgs($Object, $params);
}

//Test code:

function func($arg1, $arg2 = "Jane")
{
    return $arg1 . "," . $arg2;
}

class tc1
{
    public static function func1($Arg1, $Arg2 = "HH")
    {
        return $Arg1 . " " . $Arg2;
    }
}

$func2 = function($a1, $a2)
{
   return "a1:" . $a1 . ", a2:" . $a2;
};

$ret = call_user_function_named_param('func', array("arg1"=>"Hello", "arg2"=>"Joe"));
echo "Call Return:" . print_r($ret, true) . PHP_EOL;
$ret = call_user_function_named_param(array(new tc1(), 'func1'), array("Arg1"=>"Hello", "Arg2"=>"Joe"));
echo "Call2 Return:" . print_r($ret, true) . PHP_EOL;
$ret = call_user_function_named_param($func2, array("a1"=>"Hello", "a2"=>"Joe"));
echo "Call3 Return:" . print_r($ret, true) . PHP_EOL;
gmail@asmqb7 08-Jan-2017 04:31
Note that call_user_func() will completely trash debug_backtrace().

Solution:

<?php

your_function(...call_user_func())

?>

Note the 3 dots (array unpacking syntax).
jim at commercebyte dot com 02-Jan-2017 05:42
Before PHP 7.1.0, if you call a function without passing required arguments, a warning was generated, and the missing arguments defaulted to NULL.
In PHP 7.1.0, an ArgumentCountError is being thrown instead. (A little bit of nuisance IMHO, because it causes compatibility issues).
When you use <? call_user_func_array()  ?>, same behavior applies - the exception is thrown if you missed arguments.
Here's a quick and dirty fix for it:
<?
function call_user_func_array_i($callbk,$args) {
    while(true) {
        try {
            return call_user_func_array($callbk,$args);
        } catch(ArgumentCountError $e) {
            $args[] = NULL;
        }
    }
}
?>
Replace your calls to <? call_user_func_array() ?> with <? call_user_func_array_i() ?>, and the good old behavior is back (except that it doesn't issue a warning, but you probably didn't need it anyway).
wriver4 at gmail dot com 02-Jul-2016 03:05
Kris dot Craig at gmail dot com dispatch table does not work currently, but this does.
<?php
define("YOUR_MOTHER", 1);
define("YOUR_FATHER", 2);
define("YOUR_BROTHER", 3);
define("YOUR_SISTER", 4);

class MyFamily
{

    static $dispatch = array(
        YOUR_MOTHER => "mom",
        YOUR_FATHER => "getPrisonInmate",
        YOUR_BROTHER => "replaceName",
        YOUR_SISTER => "lazyGirl");
    static $args = array(
        YOUR_MOTHER => array(),
        YOUR_FATHER => array(
            "55170-054",
            TRUE,
            3),
        YOUR_BROTHER => array(),
        YOUR_SISTER => array());

    function getDispatch($fromwhere)
    {
        return call_user_func_array(array(
            get_class(),
            self::$dispatch[$fromwhere]), self::$args[$fromwhere]);
    }

    function mom()
    {
        return "Mommy loves you!";
    }

    function getPrisonInmate($PrisonerID, $GoodBehavior, $remaining,
            $notes = null)
    {
        //Check prison records for his ID, then....

        if ($GoodBehavior)
        {
            $parole = "APPROVED";
        }
        else
        {
            $parole = "DENIED";
        }

        return "Your father (#$PrisonerID) has $remaining years left in his sentence.  His most recent parole application has been:  $parole";
    }

    function replaceName()
    {
        return "Her name is Sally now.";
    }

    function lazyGirl()
    {
        print "Your sister needs to get out more....";

        //sleep(pow(60, 2) * 18);  //You can sleep later!

        die("Nah, I'm too tired.");
    }

}
print "Status on family member: ".MyFamily::GetDispatch(YOUR_FATHER).'<br><br>';
james dot patrick at lifeshop dot vn 14-Oct-2015 04:00
I've found the solution to resolve my need while writing the str_replace function for processing the multi array as first two arguments of str_replace built-in function(although its pass each array of argument 1 & 2)

<?php
// custom the str_replace function
function p_str_replace($argFind, $agrReplace, $theString) {
  $needle_replace = $theString; // handle the string need to be replace
  array_walk($argFind, function($val, $key) use(&$needle_replace, $agrReplace) {
    $needle_replace = call_user_func_array('str_replace', array($val, $agrReplace[$key], $needle_replace));
  });
  return $needle_replace;
}

// test
$the_str = array(
  'coa' => ':col: :op1: :val: AND :col: :op2: :val:'
);
$ope = array('>=', '<=');
$colsdata = array('date_start', '2015-10-14');

echo p_str_replace(array(
          array(':col:', ':val:'),
          array(':op1:', ':op2:')
        ), array(
            $colsdata,
            $ope
        ), $the_str['coa']);

echo '-------------------------------' . "\n";

// more complexity
$complex = '(:col: :op1: :val: AND :col: :op2: :val:) AND (:col2: :op1: :val2: AND :col2: :op1: :val2:)';

echo p_str_replace(array(
  array(':col:', ':val:'),
  array(':col2:', ':val2:'),
  array(':op1:', ':op2:')
), array(
  array('date_start', '2015-10-01'),
  array('date_end', '2015-10-14'),
  array('>', '<')
), $complex);

?>

Sorry about my bad English :)
Hope this help someone.
Anonymous 11-Aug-2015 09:51
$param_arr may be empty, though it can't be null.

<?php
function foo( $first = 'default1', $second = 'default2' ) {
    echo "first: '$first', second: '$second'\n";
}
call_user_func_array( 'foo', array( 'one', 'two' ) );
call_user_func_array( 'foo', array( 'only one' ) );
call_user_func_array( 'foo', array() );
call_user_func_array( 'foo', null );
?>

Output:
first: 'one', second: 'two'
first: 'only one', second: 'default2'
first: 'default1', second: 'default2'
/* error message or nothing printed depending on version */
admin at torntech dot com 15-Jul-2015 02:06
As of PHP 5.6 you can utilize argument unpacking as an alternative to call_user_func_array, and is often 3 to 4 times faster.

<?php
function foo ($a, $b) {
     return $a + $b;
}

$func = 'foo';
$values = array(1, 2);
call_user_func_array($func, $values);
//returns 3

$func(...$values);
//returns 3
?>

Benchmarks from https://gist.github.com/nikic/6390366
cufa   with 0 args took 0.43453288078308
switch with 0 args took 0.24134302139282
unpack with 0 args took 0.12418699264526
cufa   with 5 args took 0.73408579826355
switch with 5 args took 0.49595499038696
unpack with 5 args took 0.18640494346619
cufa   with 100 args took 5.0327250957489
switch with 100 args took 5.291127204895
unpack with 100 args took 1.2362589836121
stanislav dot eckert at vizson dot de 10-Aug-2014 12:48
Please note, that when calling call_user_func_array() to redirect parameters between inherited classes, you should not use $this, because $this always refers to the class which has been instantiated. The following code even seems to crash PHP (PHP does not report error but the process simply terminates), because the the parameters are redirected only one level up (to class foo_bar2):

<?php

    class foo_bar1
    {
        public function __construct()
        {
            echo __CLASS__ . PHP_EOL;

            if (func_num_args() > 0)
            {
                $constructorArgs = func_get_args();
                call_user_func_array(array($this, 'parent::__construct'), $constructorArgs);
            }
            else
            {
                parent::__construct();
            }
        }
    }

    class foo_bar2 extends foo_bar1
    {
        public function __construct()
        {
            echo __CLASS__ . PHP_EOL;

            if (func_num_args() > 0)
            {
                $constructorArgs = func_get_args();
                call_user_func_array(array($this, 'parent::__construct'), $constructorArgs);
            }
            else
            {
                parent::__construct();
            }
        }
    }

    class foo_bar3 extends foo_bar2
    {
        public function __construct()
        {
            echo __CLASS__ . PHP_EOL;

            if (func_num_args() > 0)
            {
                $constructorArgs = func_get_args();
                call_user_func_array(array($this, 'parent::__construct'), $constructorArgs);
            }
            else
            {
                parent::__construct();
            }
        }
    }

    $f = new foo_bar3("abc");

?>

Instead, use the direct name of the class as string or, better, the magic constant __CLASS__ in call_user_func_array(), like:

    call_user_func_array(array(__CLASS__, 'parent::__construct'), $constructorArgs);

Then the parameters will be correctly redirected to the lowest base class.
jaxxed 10-Jul-2012 04:42
For anyone looking for the means to test for the first parameter before passing to this function, look at the is_callable (http://php.net/manual/en/function.is-callable.php) variable handler.

<?php

$handler = array( 'MyClass', 'MyMethod');
$params = array(1,2,3,4);

if ( is_callable($handler) ) { call_user_func_array( $handler , $params ); }

?>
Brad Proctor 06-Nov-2010 09:07
This function is relatively slow (as of PHP 5.3.3) and if you are calling a method with a known number of parameters it is much faster to call it this way:

$class->{$method}($param1, $param2);

vs

call_user_func_array (array($class, $method), array($param1, $param2));

But if you don't know how many parameters...

The wrapper function below is slightly faster, but the problem now is that you are making two function calls.  One to the wrapper and one to the function.

However, If you are able to take this code out of the function and use it inline it is nearly twice as fast (in most cases) as calling call_user_func_array natively.

<?php
function wrap_call_user_func_array($c, $a, $p) {
    switch(count($p)) {
        case 0: $c->{$a}(); break;
        case 1: $c->{$a}($p[0]); break;
        case 2: $c->{$a}($p[0], $p[1]); break;
        case 3: $c->{$a}($p[0], $p[1], $p[2]); break;
        case 4: $c->{$a}($p[0], $p[1], $p[2], $p[3]); break;
        case 5: $c->{$a}($p[0], $p[1], $p[2], $p[3], $p[4]); break;
        default: call_user_func_array(array($c, $a), $p);  break;
    }
}
?>
Kris dot Craig at gmail dot com 16-Jun-2010 03:28
Many people have wondered how to effectively implement dispatch tables in PHP.  Here's my answer to that (if you'll forgive my creative flair):

<?php

/*
 * Using dispatch tables in PHP.
 *
 * --Kris Craig
 */

define( "YOUR_MOTHER",  1 );
define( "YOUR_FATHER",  2 );
define( "YOUR_BROTHER", 3 );
define( "YOUR_SISTER",  4 );

class MyFamily
{
    static $dispatch = array( YOUR_MOTHER => "Mom", YOUR_FATHER => "GetPrisonInmate", YOUR_BROTHER => "ReplaceName", YOUR_SISTER => "LazyGirl" );
    static $args = array( YOUR_MOTHER => array(), YOUR_FATHER => array( "55170-054", TRUE ), YOUR_BROTHER => array(), YOUR_SISTER => array() );

    function GetDispatch( $fromwhere )
    {
        return call_user_func_array( array( self, self::$dispatch[$fromwhere] ), self::$args[$fromwhere] );
    }

    function Mom()
    {
        return "Mommy loves you!";
    }

    function GetPrisonInmate( $PrisonerID, $GoodBehavior )
    {
        //Check prison records for his ID, then....

        if ( $GoodBehavior )
        {
            $parole = "APPROVED";
        }
        else
        {
            $parole = "DENIED";
        }

        return "Your father (#$PrisonerID) has $remaining years left in his sentence.  His most recent parole application has been:  $parole";
    }

    function ReplaceName()
    {
        return "Her name is Sally now.";
    }

    function LazyGirl()
    {
        print "Your sister needs to get out more....";

        //sleep( pow( 60, 2 ) * 18 );  //You can sleep later!

        die( "Nah, I'm too tired." );
    }
}

print "Status on family member: " . MyFamily::GetDispatch( YOUR_FATHER );

?>
noone at example dot com 21-Apr-2010 03:03
For those of you that have to consider performance: it takes about 3 times as long to call the function this way than via a straight statement, so whenever it is feasible to avoid this method it's a wise idea to do so.

Note that eval() is about 10 times slower than a straight statement to call a function with arguments, so this is definitely a better option than using eval() even if you only consider performance.
aj at ajbrown dot org 22-Dec-2009 07:30
Just a heads up, the second parameter MUST be an array if it's specified,  but that doesn't seem to be enforced until ~5.3.

I just pulled my hair out with an old installation of CakePHP because it was passing NULL instead of an empty array.
mrextreme at freemail dot hu 07-Dec-2009 08:34
If you are using PHP < 5.3 and want to call the parent class' __construct() with a variable parameter list, use this:

<?php
public function __construct()
{
    $vArgs = func_get_args(); // you can't just put func_get_args() into a function as a parameter
    call_user_func_array(array('parent', '__construct'), $vArgs);
}
?>
dmitry dot revenko at businessmedia dot ru 25-Sep-2009 05:28
Just hope this note helps someone (I killed the whole day on issue).

If you use something like this in PHP < 5.3:
<?php call_user_func_array(array($this, 'parent::func'), $args); ?>
Such a script will cause segmentation fault in your webserver.

In 5.3 you should write it:
<?php call_user_func_array('parent::func', $args); ?>
Damin 13-Jun-2009 12:06
Those having the passing by reference issue can use this simple hack.
I´m really not sure WHY this works, but it does, and it does not make use of EVAL or other questionable functions.
<?php
    function executeHook($name, $type='hooks'){
        $args = func_get_args();
        array_shift($args);
        array_shift($args);
        //Rather stupid Hack for the call_user_func_array();
        $Args = array();
        foreach($args as $k => &$arg){
            $Args[$k] = &$arg;
        }
        //End Hack
        $hooks = &$this->$type;
        if(!isset($hooks[$name])) return false;
        $hook = $hooks[$name];
        call_user_func_array($hook, $Args);
    }
?>

All it´s doing is copying the args ($args) into a new array ($Args) by reference, which i would think would be identical to the original array in every way (that matters).

Note the code here is an example of usage. The actual hack is denoted by comments.
If someone knows a better alternative, by all means, i would love to see it.
Freek (at) Gruntjes.net 07-Apr-2009 01:53
I just noticed that when you use this function with parameters that need to be passed by reference it will not work.

<?php
function refFunc(&$var)
{
  $var .= 'bar';
}

$var = 'foo';
?>

call_user_func_array('refFunc', array($var));
echo $var;

will output 'foo' and not  'foobar'. Witch is logical since you are declaring a new variable with array($var) however not so obvious.
thiago dot henrique dot mata at gmail dot com 22-Jul-2008 02:17
<?php
Class Delegate
{
    private $arrInstances = array();

    protected function addObject( $oElement )
    {
        // add one element on the end of the stack  //
        $this->arrInstances[] = $oElement;
    }

    public function __call( $strMethod, $arrParams )
    {
        // for each element in instance //
        foreach( $this->arrInstances as $oElement )
        {
            // get the class of the element //
            $strClass = get_class( $oElement );
            // get all methods of the class  //
            $arrMethods = get_class_methods( $strClass );
            // case the method exists into this class  //
            if( in_array( $strMethod , $arrMethods ) )
            {
                // prepare caller //
                $arrCaller = Array( $strClass , $strMethod );
                // return the result of the method into the object  //
                return call_user_func_array( $arrCaller, $arrParams );
            }
        }
        // any object has the method //
        // throw a exception //
        throw new Exception( " Method " . $strMethod . " not exist in this class " . get_class( $this ) . "." );
    }
}

class Log
{
    public function sayHi()
    {
        print "hi!" . "<br/>\n";
    }

    public function sayMyName()
    {
        print "log" . "<br/>\n";
    }
}

class Other
{
    public function sayHello()
    {
        print "hello there!" . "<br/>\n";
    }

    public function sayMyName()
    {
        print "other" . "<br/>\n";
    }
}

class Example extends Delegate
{
    public function __construct()
    {
        $this->addObject( new Log() );
        $this->addObject( new Other() );
    }
}

$oExample = new Example();
$oExample->sayHi();
$oExample->sayHello();
$oExample->sayMyName();

/*
    hi!<br/>
    hello there!<br/>
    log<br/>
*/
?>
dnhuff at acm.org 07-Jun-2008 11:57
It appears that when PHP executes something like:

$a = array(1,2,3);
$b =& $a[1];

both $b and $a[1] are converted into references to a common value -- makes sense until you transfer that to a call_user_func:

call_user_func_array('foo', $a);

suddenly, inside foo, the second parameter is passed by reference!

And you can't call this wrong, only another subtly of references.

Note it appears that ksort($a) will remove the reference as well as put the elements in key order so you (probably) get what you expect. (see below on the use of a foreach ($a as &v).)
aeolianmeson at 8n54tvv dot blitzeclipse dot com 27-May-2008 08:48
There's a possibility that call_user_func_array(), call_user_func(), and Exception::getTrace() will cause a trace entry to not have the 'file' or 'line' elements.

Dustin Oprea
richard_harrison at rjharrison dot org 11-Apr-2007 02:31
If you are thinking of using call_user_func_array to instantiate an object (see comments below using Reflection) then since v5.1.3 you can use the Reflection::newInstanceArgs() method.

<?php

// arguments you wish to pass to constructor of new object
$args = array('a', 'b');

// class name of new object
$className = 'myCommand';

// make a reflection object
$reflectionObj = new ReflectionClass($className);

// use Reflection to create a new instance, using the $args
$command = $reflectionObj->newInstanceArgs($args);

// this is the same as: new myCommand('a', 'b');
?>
levi at alliancesoftware dot com dot au 08-Feb-2007 02:50
Regarding the comments below about calling parent constructors:

PHP5 with E_STRICT no longer allows calls as below:

<?php
// Causes an error with E_STRICT
call_user_func_array(array('parent', '__construct'), $args);
?>

It gives an error because you are trying to call a nonstatic function as if it was static. The correct syntax is

<?php
// Works fine
call_user_func_array(array($this, 'parent::__construct'), $args);
?>
15-May-2006 02:43
For those wishing to implement call-by-name functionality in PHP, such as implemented e.g. in DB apis, here's a quick-n-dirty version for PHP 5 and up
<?php
/**
 * Call a user function using named instead of positional parameters.
 * If some of the named parameters are not present in the original function, they
 * will be silently discarded.
 * Does no special processing for call-by-ref functions...
 * @param string $function name of function to be called
 * @param array $params array containing parameters to be passed to the function using their name (ie array key)
 */
function call_user_func_named($function, $params)
{
    // make sure we do not throw exception if function not found: raise error instead...
    // (oh boy, we do like php 4 better than 5, don't we...)
    if (!function_exists($function))
    {
        trigger_error('call to unexisting function '.$function, E_USER_ERROR);
        return NULL;
    }
    $reflect = new ReflectionFunction($function);
    $real_params = array();
    foreach ($reflect->getParameters() as $i => $param)
    {
        $pname = $param->getName();
        if ($param->isPassedByReference())
        {
            /// @todo shall we raise some warning?
        }
        if (array_key_exists($pname, $params))
        {
            $real_params[] = $params[$pname];
        }
        else if ($param->isDefaultValueAvailable()) {
            $real_params[] = $param->getDefaultValue();
        }
        else
        {
            // missing required parameter: mark an error and exit
            //return new Exception('call to '.$function.' missing parameter nr. '.$i+1);
            trigger_error(sprintf('call to %s missing parameter nr. %d', $function, $i+1), E_USER_ERROR);
            return NULL;
        }
    }
    return call_user_func_array($function, $real_params);
}
?>
eugene at artprime dot ru 23-Dec-2005 02:59
<?php
  return call_user_func_array(
    array(new ReflectionClass($className), 'newInstance'),
    $functionParameters
  );
?>

Look here: http://www.zend.com/zend/week/week182.php#Heading1
crocodile2u at yandex dot ru 20-Dec-2005 05:06
Here is another version of createObjArray() function written here earlier by taylor.

Believing that using 'eval()' is at least "dirty", I came to the following solution (with a help of panchous - at phpclub dot ru forums ). This solution utilizes the new Reflection API.

<?php
function & createObjArray($type, $args = array()) {
    $reflection = new ReflectionClass($type);
    $output     = call_user_func_array(array(&$reflection, 'newInstance'), $args);
    return $output;
}
?>
Egor 15-Nov-2005 09:35
Note that, despite the name, this does work on builtin functions (and object methods with the array(&$obj, $method) syntax), not just user-defined functions and methods.
rrant (at) gmail (dot) com 10-Nov-2005 03:50
Just an extra for the post of amer at o2 dot pl:

If you need to call the PARENT method:
call_user_func_array(array('parent', 'method'), $args);

With that, if you need to call a constructor and/or add some extra code to the instantiation process:

<?php
function __construct() {
    // Get the arguments
    $args = func_get_args();
    // Initialize parent with arguments
    call_user_func_array(array('parent', '__construct'), $args);
    // ... Your Code Here ...
}
?>

Note that your constructor pass all the arguments to the parent constructor and it doesn't matter how many arguments you pass.

This is pretty useful for constructors with a variable number of arguments.
taylor 02-Jun-2005 05:51
I came up with a better solution to the problem that I solve below with createObjArray that maintains parameter type:

<?php

function createObjArray($type,$args=array()) {
     $paramstr = '';
     for ($i = 0; $i < count($args); $i++) {
           $paramstr .= '$args['.$i.'],';
     }
     $paramstr = rtrim($paramstr,',');

     return eval("return new $type($paramstr);");
}

?>

Would be good to add error checking, but it works.
amer at o2 dot pl 20-Jan-2005 02:44
PLS notice that "patripaq at hotmail dot com" 's code will be valid if B EXTENDS A...
<?php
class B extends A{
...
}
?>
there>>"What I wanted to do is create an object that can manage any number and any kind of parameters."

BUT IT IS NOT A POINT AT ALL

If you need to call just function with parameters:
call_user_func_array('Foo',$args);

If you need to call CLASS method (NOT object):
call_user_func_array(array('class', 'Foo'),$args);

If you need to call OBJECT method:
call_user_func_array(array(&$Object, 'Foo'),$args);

If you need to call method of object of object:
call_user_func_array(array(&$Object->Object, 'Foo'),$args);

If you need to call object method from within the very same object (NOT CLASS!):
call_user_func_array(array(&$this, 'Foo'),args);

The call_user_func_array ITSELF can manage any number and any kind of parameters. It can handle ANY FUNCTION too as it is defined and that maybe partipaq wanted to manage.

What You actually need is object composition not inheritance. Make an instance from arguments.
<?php
...
class B{
   function __construct() {
      $args = func_get_args(); // Get arguments
      $this->OBJ = new A($args);
      call_user_func_array(array(&$this->OBJ, 'A'), $args );
   }
}
?>
Then there can be any number and any type of created object B parameters
james at gogo dot co dot nz 21-Nov-2004 05:19
Be aware the call_user_func_array always returns by value, as demonstrated here...

<?php
    function &foo(&$a)
    {
      return $a;
    }

    $b = 2;
    $c =& call_user_func_array('foo', array(&$b));
    $c++;
    echo $b . ' ' . $c;
?>

outputs "2 3", rather than the expected "3 3".

Here is a function you can use in place of call_user_func_array which returns a reference to the result of the function call.

<?php
    function &ref_call_user_func_array($callable, $args)
    {
        if(is_scalar($callable))
        {
            // $callable is the name of a function
            $call = $callable;
        }
        else
        {
            if(is_object($callable[0]))
            {
                // $callable is an object and a method name
                $call = "\$callable[0]->{$callable[1]}";
            }
            else
            {
                // $callable is a class name and a static method
                $call = "{$callable[0]}::{$callable[1]}";
            }
        }

        // Note because the keys in $args might be strings
        // we do this in a slightly round about way.
        $argumentString = array();
        $argumentKeys = array_keys($args);
        foreach($argumentKeys as $argK)
        {
            $argumentString[] = "\$args[$argumentKeys[$argK]]";
        }
        $argumentString = implode($argumentString, ', ');
        // Note also that eval doesn't return references, so we
        // work around it in this way...
        eval("\$result =& {$call}({$argumentString});");
        return $result;
    }
?>
hong dot nguyen at k-edge dot com 02-Apr-2004 09:37
call_user_func_array can pass parameters as reference:

<?php
call_user_func_array(array(&$obj,$method),array(&$arg1,$arg2,$arg3))
?>

Use it as work-around for "Call-time pass-by-reference has been deprecated".
adamh at densi dot com 31-Jul-2003 11:58
call_user_func_array() is nifty for calling PHP functions which use variable argument length. For example:

<?php
$array = array(
 array("foo", "bar"),
 array("bat", "rat"),
);

$values = call_user_func_array("array_merge", $array);

var_dump($values);
?>

/* output:
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "bat"
  [3]=>
  string(3) "rat"
}
*/

The neat feature is that $array could have any number of arrays inside it.


Llamar a una llamada de retorno dada por el primer parámetro

  • « call_user_func_array
  • create_function »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Llamar a una llamada de retorno dada por el primer parámetro

call_user_func

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

call_user_func — Llamar a una llamada de retorno dada por el primer parámetro

Descripción

call_user_func ( callable $callback , mixed $parameter = ? , mixed $... = ? ) : mixed

Llama a la llamada de retorno dada por el primer parámetro callback y pasa los parámetros restantes como argumentos.

Parámetros

callback

La función llamable (callable) a llamar.

parameter

Cero o más parámetros a pasar a la llamda de retorno.

Nota:

Observe que los parámetros para call_user_func() no son pasados por referencia.

Ejemplo #1 Ejemplo de call_user_func() y referencias

<?php
error_reporting(E_ALL);
function incrementar(&$var)
{
    $var++;
}

$a = 0;
call_user_func('incrementar', $a);
echo $a."\n";

// En su lugar se puede usar esto
call_user_func_array('incrementar', array(&$a));
echo $a."\n";
?>

El resultado del ejemplo sería:

0
1

Valores devueltos

Devuelve el valor devuelto por la llamada de retorno, o false en caso de error.

Historial de cambios

Versión | Descripción
5.3.0 | La interpretación de palabras clave orientadas a objetos como parent y self ha cambiado. Anteriormente al llamarlas usando la sintaxis de dobles dos puntos emitiría una advertencia E_STRICT porque eran interpretadas como estáticas.

Ejemplos

Ejemplo #2 Ejemplo de call_user_func()

<?php
function barbero($tipo)
{
    echo "Usted quiere un corte de pelo al estilo $tipo, sin problemas\n";
}
call_user_func('barbero', "seta");
call_user_func('barbero', "rapado");
?>

El resultado del ejemplo sería:

Usted quiere un corte de pelo al estilo seta, sin problemas
Usted quiere un corte de pelo al estilo rapado, sin problemas

Ejemplo #3 call_user_func() usando un nombre de espacios de nombres

<?php

namespace Foobar;

class Foo {
    static public function prueba() {
        print "¡Hola mundo!\n";
    }
}

call_user_func(__NAMESPACE__ .'\Foo::prueba'); // A partir de PHP 5.3.0
call_user_func(array(__NAMESPACE__ .'\Foo', 'prueba')); // A partir de PHP 5.3.0

?>

El resultado del ejemplo sería:

¡Hola mundo!
¡Hola mundo!

Ejemplo #4 Usar un método de clase con call_user_func()

<?php

class miclase {
    static function saludar()
    {
        echo "¡Hola!\n";
    }
}

$nombreclase = "miclase";

call_user_func(array($nombreclase, 'saludar'));
call_user_func($nombreclase .'::saludar'); // A partir de 5.2.3

$miobjeto = new miclase();

call_user_func(array($miobjeto, 'saludar'));

?>

El resultado del ejemplo sería:

¡Hola!
¡Hola!
¡Hola!

Ejemplo #5 Usar una función lambda con call_user_func()

<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'prueba'); /* A partir de PHP 5.3.0 */
?>

El resultado del ejemplo sería:

[prueba]

Notas

Nota:

Las funciones de retorno de llamada que se registran con funciones como call_user_func() y call_user_func_array() no se llamarán si se produce una excepción en la función de retorno previa.

Ver también

  • call_user_func_array() - Llamar a una llamada de retorno con un array de parámetros
  • is_callable() - Verificar que los contenidos de una variable puedan ser llamados como una función
  • ReflectionFunction::invoke() - Invoca una función
  • ReflectionMethod::invoke() - Invoca un método

User Contributed Notes

James at enfsolar dot com 11-Dec-2019 12:08
<?php

class MyClass{

    public function hello($str)

    {

        echo 'hello ' . $str;

    }

}

$obj = new MyClass();

[$obj, 'hello']('World'); // the array can be called as a function
luciano_closs at hotmail dot com 13-Dec-2018 11:42
Actually, as PHP 7.0, when you want to call a static method, you must call:

<?php

namespace Foobar;

class Foo {
   static public some() {
      echo 'Hello World!';
   }
}

call_user_func( array( __NAMESPACE__ . '\\Foo', 'some' ) );

?>

This will output:

Hello World!
slinstj at gmail dot com 09-May-2018 02:00
Updating "insta at citiesunlimited dot com"'s benchmarking for PHP 7.1.17 we have an INVERSION of results between using variables and call_user_func():

// RESULTS

Variable functions took 0.0020599365234375 seconds.
call_user_func took 0.00094509124755859 seconds.
eval took 0.024421215057373 seconds.

So, call_user_func() is now actually the way to go in PHP 7.1+.

<?php

function fa () { return 1; }
function fb () { return 1; }
function fc () { return 1; }

$calla = 'fa';
$callb = 'fb';
$callc = 'fc';

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += $calla();
    $x += $callb();
    $x += $callc();
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "Variable functions took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += call_user_func('fa', '');
    $x += call_user_func('fb', '');
    $x += call_user_func('fc', '');
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "call_user_func took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    eval( '$x += ' . $calla . '();' );
    eval( '$x += ' . $callb . '();' );
    eval( '$x += ' . $callc . '();' );
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "eval took " . (microtime( true ) - $time) . " seconds.<br />" );

?>
fab2s at marsatak dot org 02-Mar-2017 12:35
@insta at citiesunlimited dot com & @Maresa

call_user_func() alleged slowness is quite over estimated when it comes to real use cases. we are talking about loosing fraction of a second every million calls, which by the way would take less than half a sec to execute in the worst case.

I don't know of many processes that would actually suffer from this kind of overhead.

Iterations: 100 000
Averaged over: 10
PHP 5.6.30 (cli) (built: Jan 18 2017 19:47:28)
Overall Average
+------------------------+----------+-----------+--------+
| Invocation             | Time (s) | Delta (s) | %      |
+------------------------+----------+-----------+--------+
| directFunction         | 0.0089   | -0.0211   | -70.19 |
| directStatic           | 0.0098   | -0.0202   | -67.39 |
| directLambda           | 0.0109   | -0.0191   | -63.52 |
| directInstance         | 0.0116   | -0.0184   | -61.31 |
| directClosure          | 0.0150   | -0.0150   | -50.15 |
| Invoke                 | 0.0282   | -0.0018   | -6.13  |
| call_user_func         | 0.0300   |           |        |
| ClosureFactory         | 0.0316   | +0.0016   | +5.20  |
| assignedClosureFactory | 0.0328   | +0.0028   | +9.28  |
| call_user_func_array   | 0.0399   | +0.0099   | +33.02 |
| InvokeCallUserFunc     | 0.0418   | +0.0118   | +39.17 |
| directImplementation   | 0.0475   | +0.0175   | +58.28 |
+------------------------+----------+-----------+--------+

Iterations: 100 000
Averaged over: 10
PHP 7.1.2 (cli) (built: Feb 14 2017 21:24:45)
Overall Average
+------------------------+----------+-----------+--------+
| Invocation             | Time (s) | Delta (s) | %      |
+------------------------+----------+-----------+--------+
| directFunction         | 0.0043   | -0.0096   | -68.92 |
| directStatic           | 0.0050   | -0.0089   | -64.04 |
| directInstance         | 0.0058   | -0.0081   | -58.22 |
| directLambda           | 0.0063   | -0.0075   | -54.44 |
| directClosure          | 0.0081   | -0.0058   | -41.57 |
| call_user_func         | 0.0139   |           |        |
| call_user_func_array   | 0.0147   | +0.0008   | +5.84  |
| Invoke                 | 0.0187   | +0.0048   | +34.61 |
| ClosureFactory         | 0.0207   | +0.0069   | +49.43 |
| assignedClosureFactory | 0.0219   | +0.0080   | +57.75 |
| directImplementation   | 0.0232   | +0.0094   | +67.53 |
| InvokeCallUserFunc     | 0.0264   | +0.0126   | +90.67 |
+------------------------+----------+-----------+--------+

If you want more details : https://github.com/fab2s/call_user_func
fab2s at marsatak dot org 02-Mar-2017 12:18
The "Example #1 call_user_func() example and references" has become misleading since it will throw an exception starting from at least php 5.6.30:
<?php
//  Parameter 1 to increment() expected to be a reference, value given
?>

The crash occurs when call_user_func() is called as it does not provide increment() with a reference.

Also note that :

<?php
call_user_func('increment', &$a);
?>

will also  throw an exception :
<?php
// Call-time pass-by-reference has been removed
?>
developer at nabtron dot com 28-Dec-2016 11:30
We can achieve the same dynamically without call_user_func like this

<?php

class myclass {
    public function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

$myobject = new myclass();
$var = "say_hello";

(new myclass)->{$var}();
call_user_func(array(new myclass(), $var));
jcastro at eftec dot cl 07-Jun-2016 09:29
Lets say that $a1 is an object and fn is a function then:

echo $a1->fn('hello world');
echo $a1->{"fn"}('hello world');
echo call_user_func(array($a1, 'fn'),'hello world');

Are three valid ways to do the same.
blakerenton09 at yahoo dot com 06-Jun-2011 04:45
call_user_func may also be used to call a closure or anonymous function that has been passed into a user-defined function.

<?php
function Benchmark()
{
    foreach(func_get_args() as $function)
    {
        $st = microtime(true);
        call_user_func($function);
        $et = microtime(true);
        echo sprintf("Time: %f", $et - $st) . '<br />';
    }
}

Benchmark(function()
{
    for ( $i = 0; $i <= 10000; $i++ )
    { }
},
function()
{
    $i = 0;
    while ( $i <= 10000 )
    {
        $i++;
    }
});
?>

Returns:
Time: 0.001652
Time: 0.001458
romainbessuges at gmail dot com 09-May-2011 05:50
I made a wrapper for call_user_func_array which is really simple and convenient. It takes advantage of the __invoke() magic method :

<?php
class Func {

    public static function fromFunction($name){
        return new Func($name);
    }

    public static function fromClassMethod($class, $name){
        return new Func(array($class, $name));
    }

    public static function fromObjectMethod($object, $name){
        return new Func(array($object, $name));
    }

    public $function;

    public function  __construct($function) {
        $this->function = $function;
    }

    public function __invoke(){
        return call_user_func_array($this->function, func_get_args());
    }
}
?>

Example :

<?php
$func = Func::fromObjectMethod($myArrayObject, "offsetGet");

echo $func(3);
?>
gskluzacek dot nospam at gmail dot com 11-Sep-2010 10:38
if you simply want to dynamically call a method on an object it is not necessary to use call_user_function but instead you can do the following:

<?php

$method_name = "AMethodName";

$obj = new ClassName();

$obj->{$method_name}();

?>

I've used the above so I know it works.

Regards,
-- Greg
moisadoru at gmail dot com 13-May-2010 08:49
Actually, when calling a static method of some class, the params are sent by reference:
<?php
class Foo {
    private $x = 0;
    public function getX(){
        return $this->x;
    }
    public function setX($val){
        $this->x = $val;
    }
}

class Bar {
    static function incStatic(Foo $f){
        $f->setX($f->getX()+1);
        global $foo;
        if($f === $foo) echo '<span style="color: blue">' . __METHOD__ . '() objects are equal</span><br />';
        else  echo '<span style="color: red">' . __METHOD__ . '() objects are not equal</span><br />';
    }
    public function incNonStatic(Foo $f){
        $f->setX($f->getX()+1);
        if($f === $foo) echo '<span style="color: blue">' . __METHOD__ . '() objects are equal</span><br />';
        else  echo '<span style="color: red">' . __METHOD__ . '() objects are not equal</span><br />';
    }
}

function inc(Foo $f){
    $f->setX($f->getX()+1);
    if($f === $foo) echo '<span style="color: blue">' . __FUNCTION__ . '() objects are equal</span><br />';
    else  echo '<span style="color: red">' . __FUNCTION__ . '() objects are not equal</span><br />';
}

$foo = new Foo;
$bar = new Bar;

call_user_func('inc', $foo);
call_user_func('Bar::incStatic', $foo);
call_user_func(array($bar, 'incNonStatic'), $foo);
?>

The results on PHP 5.2.6 (macosx 10.5):

inc() objects are not equal
Bar::incStatic() objects are equal
Bar::incNonStatic() objects are not equal

Hope it helps sombody.
Nitrogen 04-Oct-2009 04:08
A good use for call_user_func(); is for recursive functions.
If you're distributing code, you will often come across users who will rename functions and break the code..
Use this: call_user_func(__FUNCTION__, ... ); inside a function to call itself with whatever parameters you want.

<?php
// example, an extremely simplified factorial calculator..
// it's quite obvious when someone renames the function, it'll spit out an error because it wants to call itself.
function Factorial($i=1) {
  return($i==1?1:$i*Factorial($i-1));
}

// you can give this function whatever name you want, it'll always work, of course if you initially call it using the name you gave it.
function qwertyuiop($i=1) {
  return($i==1?1:$i*call_user_func(__FUNCTION__,$i-1));
}
?>

Just that I didn't see any reference to recursive functions when user_call_func(); really helps.
edgar dot klerks at gmail dot com 17-Mar-2009 07:18
An entirely OO solution to add dynamicly methods to classes, I used in a project:
<?php
class ProductPart {

        protected $data;
        protected $plugins = array();
        function __construct($data){

                $this->data = $data;

        }
        public function register(ProductPlugin $plugin){

                if(!in_array($plugin, $this->plugins)){

                        $this->plugins[$plugin->toString()] = $plugin;
                } else {
                        throw new Exception('Function allready defined');
                }
        }
        public function unregister(ProductPlugin $plugin){
                if(isset($this->plugins[$plugin->toString()])){
                        unset($this->plugins[$plugin->toString()]);
                } else {
                        throw new Exception('No such function');
                }

        }

        protected function __call($method, $args) {
              if(isset($this->plugins[$method])){
                array_unshift(&$args, $this->data);
                array_unshift(&$args, $this);
                return $this->plugins[$method]->run($args[0], $args[1], $args[2]);

              } else {
                throw new Exception('No such function');
              }
        }
} ?>

I simplified the class somewhat for clearity.

With this class, you can dynamicly add and remove classes by calling register or unregister. Register will store the object in an associative array by calling toString (as defined by ProductPlugin) and saving the method under the returned string in the array. (In this case the name of the method the class adds.)

When a method is called, which isn't standard in the object, _call will lookup the called method in the array. If found, __call run the method of the plugin with the provided arguments. I restricted the user provided argument to 1, because I want to force the user to use associative arrays.

Because I chose an array to store my classes, removing a function is quite simple. However the unregister function isn't optimal, I better pass a string instead of a plugin object. I didn't test it yet on performance.

The ProductPlugin class:

<?php

abstract class ProductPlugin {
        protected $name = null;
        abstract public function run($obj, $data, $args);
        public function __construct($data = null) {

                if($this->name === null){
                        throw new Exception('Name must be defined');
                }
                $this->init($data);
        }
        protected function init($data){

        }
        public function toString(){
                return $this->name;
        }
}

?>

And at last some demonstration code:

<?php
$bla = new ProductPart(array('HelloWorld' => 'Hello world'));
$hello = new helloPlugin();
$bla->register($hello);
$bla->HelloWorld();
$bla->unregister($hello);
$bla->HelloWorld();

?>
dead,screamer@seznam,cz 21-Dec-2008 08:50
<?php call_user_func()?> and <?php call_user_func_array()?> hide some errors (notices, warnings and maybe errors), even if is display_errors turned on and error_Reporting is set to E_ALL|E_STRICT
Maxdamantus 03-Nov-2007 10:26
Note that the parser can interpret variables in function syntax, which means you can pass all variables normally (eg: reference).

<?php
function myfunction($string, &$int){
    echo $string."\n";
    $int++;
}
$function_name = "myfunction";
$x = 1336;
$function_name("Hello World", $x);
echo $x;
?>
---
Hello World
1337
Knightnet 07-Sep-2007 05:31
You don't need to use this function to call a variable class function. Instead you can do the following:

$this->{$fnname}();

The example works in PHP 5 from within the class. It is the {} that do the trick.

Regards,
Julian.
Typer85 at gmail dot com 12-Sep-2006 03:57
I would just like to say at first that I prefer variable function calls over the use of this function.

However I found that at some times, the use of this function is needed in situtations where variable function calls can not be used. And in those same situations, the use of this function is also better than using eval.

The situation I ran into is this:

I wanted to call object methods dynamically from within the object but with arguments given for possible parameters that the method I will call requires.

The parameters themselves are dynamic, meaning I have no prior knowledge of how many their are, their values, or if they even exist.

Also because object methods are dynamic, meaning I have no prior knowledge which object method will actually be called, I can not simply use variable function calls, call the method and pass any parameters.

So what I simply do is call the object method with an array of parameters, something that, to the best of my knowledge, can not be done with variable function calls, since variable function calls, even though they themeselves are dynamic, passing parameters to them is not.
rlansky at webroot dot com 14-Jul-2006 04:17
Based on the previous posts, it appears that using call_user_func can be serveral times slower than using variable substitution. I think these results are somewhat misleading.

I set up a similar test in which a static method of an object was called repeatedly in a loop. I got similar results to those seen; when calling the method using call_user_func the execution was twice that of calling the method directly. However, I then started adding some "meat" to the method in question. In my case, I found that what was constant was not the percentage change, but rather that there is a fixed cost to using call_user_func.

In my case, this fixed cost was 2 microseconds per call. When executing a method that performs no operations, this is a large percentage of the execution time for that method. However, when using this on a method that actually performs some work, the 2 microsecond cost is almost impossible to measure.

It seems to me that if you want to use call_user_func to call a very fast executing method, and you need to do this thousands of times, then you may want to reconsider. However, if you are using this to call methods that are not executed thousands of times, the small fixed cost of using php call_user_func is probably not an issue.
Maresa 13-Apr-2006 03:41
I tested the same code that insta at citiesunlimited dot com pasted on the following machines:

www1 machine:
OS:  FreeBSD 5.2.1-RELEASE
CPU: 2 x Intel(R) Xeon(TM) CPU 2.66GHz (2657.82-MHz 686-class CPU) with Hyperthreading
MEM: 1073217536 (1023 MB)
PHP 5.1.2 (cli)
PHP 4.4.1 (Web)

www2 machine:
OS:  Linux version 2.6.14-gentoo-r5 Gentoo 3.4.3-r1, ssp-3.4.3-0, pie-8.7.7)
CPU: 2 x Dual Core AMD Opteron(tm) Processor 265 stepping 02 1808.357 MHz
MEM: 2060388k total
PHP 5.1.2 (cli)
PHP Version 4.4.0-pl1-gentoo (web)

dev machine:
OS:  Linux version 2.6.15-gentoo-r1 Gentoo 3.3.5.20050130-r1, ssp-3.3.5.20050130-1, pie-8.7.7.1
CPU: Intel(R) Pentium(R) 4 CPU 2.00GHz stepping 04
MEM: 516384k total,
PHP 4.4.0-pl1-gentoo (cli)
PHP Version 4.4.0-pl1-gentoo (web)

The result are as follows:

www1 - CLI
Variable functions took 0.012186050415 seconds.
call_user_func took 0.0300550460815 seconds.
eval took 0.17235994339 seconds.

www1 - Web
Variable functions took 0.017616 seconds.
call_user_func took 0.034926 seconds.
eval took 0.149618 seconds

www2 - CLI
Variable functions took 0.0065491199493408 seconds.
call_user_func took 0.019452095031738 seconds.
eval took 0.10734891891479 seconds.

www2 - Web
Variable functions took 0.01565 seconds.
call_user_func took 0.02613 seconds.
eval took 0.132258 seconds.

dev - CLI
Variable functions took 0.025176 seconds.
call_user_func took 0.047402 seconds.
eval took 0.168196 seconds.

dev - Web
Variable functions took 0.025465 seconds.
call_user_func took 0.049713 seconds.
eval took 0.20154 seconds.

On www1 - CLI, eval is about 14 times slower than calling function by using variable.
On www1 - Web, eval is about 8.5 times slower (hmm interesting. Perhaps PHP4 is faster calculating eval than PHP5)

On www2 - CLI, eval is about 16 times slower than calling function by using variable.
On www2 - Web, eval is about 8.5 times slower (about same result as www1)

On dev - CLI, eval is about 6.6 times slower than calling function by using variable.
On dev - Web, eval is about 8 times slower (about same result as www1)

On the dev machine, CLI and web version of PHP is the same. and their speed difference between calling function using variable or eval does not differ that much compare to PHP5 VS PHP5
insta at citiesunlimited dot com 06-Feb-2006 12:15
I benchmarked the comparison in speed between variable functions, call_user_func, and eval.  My results are below:

Variable functions took 0.125958204269 seconds.
call_user_func took 0.485446929932 seconds.
eval took 2.78526711464 seconds.

This was run on a Compaq Proliant server, 180MHz Pentium Pro 256MB RAM.  Code is as follows:

<?php

function fa () { return 1; }
function fb () { return 1; }
function fc () { return 1; }

$calla = 'fa';
$callb = 'fb';
$callc = 'fc';

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += $calla();
    $x += $callb();
    $x += $callc();
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "Variable functions took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += call_user_func('fa', '');
    $x += call_user_func('fb', '');
    $x += call_user_func('fc', '');
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "call_user_func took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    eval( '$x += ' . $calla . '();' );
    eval( '$x += ' . $callb . '();' );
    eval( '$x += ' . $callc . '();' );
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "eval took " . (microtime( true ) - $time) . " seconds.<br />" );

?>
Marco 05-Oct-2005 01:42
>phil at gettcomm dot com
>22-May-2002 04:51
>if you need to get a reference back from a method, you can work around
>call_user_func()'s shortcomings like this:
>
Naaa! Having back a reference is a real problem, but it can be solved by mean of eval(), instead of using call_user_func:

<?php
  class Node {
    var $name;
    var $child;
    function Node ( $name ) { $this->name = $name; }
    function &getChild () { return $this->child; }
  }
  $p = new Node ( 'Father' );
  $c = new Node ( 'Child' );
  $p->child = &$c;

  eval ( "\\$cref = &\\$p->getChild ();" );
  $cref->name = 'Another Child';

  // Prints out 'Another Child'
  echo "****** After eval c = " . $c->name . "\\n\\n";

?>
info at webseiteselberpflegen dot de 18-May-2005 01:00
It seems like call_user_func() can not be used to create Objects via the new Command.

The Following example dosen't work:

<?php
  include_once(class_".$type.".php");
  $object = new call_user_func ('bdv_'.$type);
?>

But this works:

<?php
    include_once(class_".$type.".php");
    $constr = 'bdv_'.$type;
    $object = new $constr();
?>
24-Feb-2005 07:46
<?php
/*
    A very simple event handler dispose and change the latest one I did
*/

class Duke
{
//public:
    var $m_pRaiser;
    var $m_strRaiserFun;
    var $m_objArgs;
//public:
    function Duke(  $pRaiser,
            $strRaiserFun,
            $objArgs )
    {
        $this ->m_pRaiser      = $pRaiser;
        $this ->m_strRaiserFun = $strRaiserFun;
        $this ->m_objArgs      = $objArgs;

    }//end of constructor

}//end of class Duke

class A
{
//protected:
    function OnEventHandler( $sender, $args )//virtual
    {
        $sender ->SayHello();
    }//end of OnEventHandler( $sender, $args )

//public:
    function OnEvent( $pDuke = null )
    {
        if( $pDuke == null )
        {
            call_user_func( array( &$this, "OnEventHandler" ), $this, null );
            return;
        }

        call_user_func( array( $pDuke ->m_pRaiser, $pDuke ->m_strRaiserFun ), $pDuke ->m_pRaiser, $pDuke ->m_objArgs );

    }//end of  OnEvent( $pDuke )

    function SayHello()//virtual
    {
        echo "A::SayHello" . "<br>";
    }//end of SayHello()

}//end of class A

class B extends A
{
//public:
    function SayHello()//override
    {
        echo "B::SayHello" . "<br>";
    }//end of SayHello()

}//end of class B

//////////////////////////////////////////////////////////////////////
//Main import to test
//
$a = &new A();
$b = &new B();

$pDuke = &new Duke( $b, "OnEventHandler", null );

$b ->OnEvent();
$b ->OnEvent( $pDuke );
?>
zxy at estec-jp dot com 24-Feb-2005 02:57
A simple event handler dispose released by useful callback in PHP 4.x

<?php
class Duke
{
//public:
    var $m_pRaiser;
    var $m_strRaiserFun;
    var $m_objArgs;
//public:
    function Duke(  $pRaiser,
            $strRaiserFun,
            $objArgs )
    {
        $this ->m_pRaiser      = $pRaiser;
        $this ->m_strRaiserFun = $strRaiserFun;
        $this ->m_objArgs      = $objArgs;

    }//end of constructor

}//end of class Duke

class A
{
//protected:
    function OnEventHandler( $sender, $args )//virtual
    {
        $sender ->SayHello();
    }//end of OnEventHandler( $sender, $args )

//public:
    function OnEvent( $pDuke )
    {
        call_user_func( array( $pDuke ->m_pRaiser, $pDuke ->m_strRaiserFun ), $pDuke ->m_pRaiser, $pDuke ->m_objArgs );
    }//end of  OnEvent( $pDuke )

    function SayHello()//virtual
    {
        echo "A::SayHello" . "<br>";
    }//end of SayHello()

}//end of class A

class B extends A
{
//public:
    function SayHello()//override
    {
        echo "B::SayHello" . "<br>";
    }//end of SayHello()

}//end of class B

///////////////////////////////////////////////////////////
//Main import to test
//
$a = &new A();
$b = &new B();

$pDuke = &new Duke( $b, "SayHello", null );
$b ->OnEvent( $pDuke );
?>
arjini at mac dot com 29-Mar-2004 05:04
Some of the wierder examples below confused me, and made me think that the following would work (but it does!).

<?php

class barber{
    function shop($one,$two,$three,$four='quartet'){
        echo $one.','.$two.','.$three.','.$four;
    }
}

$bsq = new barber;
call_user_func(array(&$bsq,'shop'),'one','two','three');

/* Output = one,two,three,quartet */

class bigBarber{
    var $quartet;
    function bigBarber(){
        $this->quartet = 'four';
    }
    function shop($one,$two,$three,$five='quintet'){
        echo $one.','.$two.','.$three.','.$this->quartet.','.$five;
    }
}

$bbsq = new bigBarber();
call_user_func(array(&$bbsq,'shop'),'one','two','three');

/* Output = one,two,three,four,quintet */

?>
Kris Koskelin 22-Jan-2004 03:21
I was trying to use this function to call a method of an already-instantiated object.  I needed to do this with the object itself, not simply call the class' method.

To accomplish this, I really avoided this particular function altogether like this:

<?php
if ( method_exists($my_obj, $action) ){
     return $my_obj->{$action}();
}
?>

I hope someone else finds this useful.  Note that doing this allows you to pass params to the function more-or-less in the same way you would to any other class method.
Michele.Manzato at verona.miz.it 29-Sep-2003 08:49
With overload()ed classes call_user_func_* calls real class methods only. If the method does not exist then PHP does not try with the "__call()" magic method (at least until PHP 4.3.3). See this:

<?php
class A
{
    function A() {}

    function __call($method, $args, &$ret) {
        echo "__call(): You called '{$method}()'<br>\n";
        return true;
    }

    function regular() {
        echo "You called 'regular()'<br>\n";
    }
};
overload("A");

$a = new A;

$a->regular();                          // Works, calls regular()
call_user_func(array(&$a, "regular"));  // Works, calls regular()

$a->hello();                            // Works, calls __call()
call_user_func(array(&$a, "hello"));    // Does NOT work!
?>
Carl 28-Jul-2003 11:53
I had a problem where I wanted to parameterize a callback. The end called was in an external class, but I needed to save some state for the callback that didn't make sense to keep in the original object, as it might change from call to call...

<?php
class foo
{
    function foo()
    {
        $str = "Hello There";

        $str2 = "Carl";

        $that =& new holder($str);

        call_user_func(array(&$that, 'callback'), $str2);
    }
}

class holder
{
    function holder($aParam)
    {
        $this->param = $aParam;
    }

    function callback($aStr)
    {
        echo "A=$this->param, B=$aStr\n";
    }
}
?>
dougqh at hotmail dot com 07-Mar-2002 05:16
The previous note I posted had an error in the source code.  That has been corrected in this note.

Note, that returning by reference does not work properly when the function
is called using call_user_func.

This example illustrates the problem...

<?php
$globalVar = 0;

function &staticFunction()
{
   global $globalVar;

   return $globalVar;
}

$result =& call_user_func( "staticFunction" );

$result = 3;

print "result:" . $result . "<br/>\n";
print "globalVar: " . $globalVar . "<br/>\n";

$result2 =& staticFunction();

$result2 = 3;

print "result2: " . $result2 . "<br/>\n";
print "globalVar: " . $globalVar . "<br/>\n";
?>

The above code results in the following output ...
Note that $result is not a reference to $globalVar.

result:0
globalVar: 0
result2: 3
globalVar: 3

Also, the use of call_user_method is now deprecated in favor of passing
array( &$object, $method ) as the function to call_user_func.  This is
reported when error reporting is set to E_ALL in the latest versions of
PHP.
danyloco at yahoo dot com 17-Jul-2001 04:31
I was trying to call multiple functions within a class, and after a brain frying experience this is what came out... hope it helps:

<?php
class Foo {
 function hey1($id){echo "In hey1";}
 function hey2($id){echo "In hey2";}
 #... and so forth ...
 function runtest($id) {
   #the fun part :)
   for($i=1; $i<=2; $i++) {
     $fp = "hey".$i;
     $this->$fp($id);
}
}
}
?>

It worked like a charm :).


Crear una función anónima (estilo lambda)

  • « call_user_func
  • forward_static_call_array »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Crear una función anónima (estilo lambda)

create_function

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

create_function — Crear una función anónima (estilo lambda)

Descripción

create_function ( string $args , string $code ) : string

Crea una función anónima desde los parámetros pasados, y devuelve un nombre único para ella.

Precaución

Esta función realiza internamente un eval() y como tal tiene los mismos problemas de seguridad que eval(). Además posee características malas de rendimiento y uso de memoria.

Si se usa 5.3.0 o superior, se debería usar en su lugar una función anónima nativa.

Parámetros

Normalmente estos parámetros serán pasados como una cadena entre comillas simples. La razón de usar comillas simples es proteger a los nombres de las variables de ser analizados, de otro modo, si se usan comillas dobles habrá necesidad de escapar los nombres de las variables, p.ej. \$avar.

args

Los argumentos de la función.

code

El código de la función.

Valores devueltos

Devuelve un nombre de función único como cadena, o false en caso de error.

Ejemplos

Ejemplo #1 Crear una función anónima con create_function()

Se puede usar esta función para, por ejemplo, crear una función desde información reunida en tiempo de ejecución:

<?php
$nuevafunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "Nueva función anónima: $nuevafunc\n";
echo $nuevafunc(2, M_E) . "\n";
// imprime
// Nueva función anónima: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
?>

O quizás para tener una función gestora general que pueda aplicar un conjunto de operaciones a una lista de parámetros:

Ejemplo #2 Hacer una función de proceso general con create_function()

<?php
function procesar($var1, $var2, $farr)
{
    foreach ($farr as $f) {
        echo $f($var1, $var2) . "\n";
    }
}

// crear un puñado de funciones matemáticas
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }';
$farr = array(
    create_function('$x,$y', 'return "algo de trigonometría: ".(sin($x) + $x*cos($y));'),
    create_function('$x,$y', 'return "una hipotenusa: ".sqrt($x*$x + $y*$y);'),
    create_function('$a,$b', $f1),
    create_function('$a,$b', $f2),
    create_function('$a,$b', $f3)
    );

echo "\nUsar la primera matriz de funciones anónimas\n";
echo "parámetros: 2.3445, M_PI\n";
procesar(2.3445, M_PI, $farr);

// ahora hacer un puñado de funciones de proceso de cadenas
$garr = array(
    create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '.
    'y \"$b\"\n** ¡Para mí se parecen! (mirando los 3 primeros caracteres)";'),
    create_function('$a,$b', '; return "CRCs: " . crc32($a) . ", ".crc32($b);'),
    create_function('$a,$b', '; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";')
    );
echo "\nUsar la segunda matriz de funciones anónimas\n";
procesar("Cuando los pájaros cantan", "Cuando es de noche", $garr);
?>

El resultado del ejemplo sería:

Usar la primera matriz de funciones anónimas
parámetros: 2.3445, M_PI
algo de trigonometría: -1.6291725057799
una hipotenusa: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a)/b = 0.27122299212594

Usar la segunda matriz de funciones anónimas
** "Cuando es de noche" y "Cuando los pájaros cantan"
** ¡Para mí se parecen! (mirando los 3 primeros caracteres)
CRCs: -725381282, 342550513
similar(a,b) = 11(45.833333333333%)

Pero quizás el uso más común de las funciones estilo lambda (anónimas) sea el de crear funciones de llamada de retorno, por ejemplo cuando se usa array_walk() o usort()

Ejemplo #3 Usar funciones anónimas como funciones de llamada de retorno

<?php
$av = array("el ", "un ", "ese ", "este ");
array_walk($av, create_function('&$v,$k', '$v = $v . "mango";'));
print_r($av);
?>

El resultado del ejemplo sería:

Array
(
  [0] => el mango
  [1] => un mango
  [2] => ese mango
  [3] => este mango
)

una matriz de cadenas ordenada de más corta a más larga

<?php

$sv = array("pequeña", "más larga", "una gran cadena", "esto es una 'señora' cadena");
print_r($sv);

?>

El resultado del ejemplo sería:

Array
(
  [0] => pequeña
  [1] => más larga
  [2] => una gran cadena
  [3] => esto es una 'señora' cadena
)

ordenarla de más larga a más corta

<?php

usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);

?>

El resultado del ejemplo sería:

Array
(
  [0] => esto es una 'señora' cadena
  [1] => una gran cadena
  [2] => más larga
  [3] => pequeña
)

Ver también

  • Funciones anónimas

User Contributed Notes

tomas dot vot at gmail dot com 16-Dec-2018 01:17
If you need to upgrade more than one `create_function` to anonymous function, I'm working on a tool that makes dev's life much easier and adaptable for new versions of anything in PHP.

It's tested on 30+ various (and really weird :)) cases, like:

    -$callback = create_function('$a', 'return "<cas:proxy>$a</cas:proxy>";');
    +$callback = function ($a) {
    +    return "<cas:proxy>{$a}</cas:proxy>";
    +};

Includes concat (.), string quotes and inclined function calls:

    -$func = create_function('$atts, $content = null','return "<div class=\"' . $class_list . '\">" . do_shortcode($content) . "</div>";' );
    +$func = function ($atts, $content = null) use ($class_list) {
    +    return "<div class=\"{$class_list}\">" . do_shortcode($content) . "</div>";
    +};

Do you want to automate the hard work?

1. Instal Rector

    composer require rector/rector --dev

2. Create config

    # rector.yml
    services:
        Rector\Php\Rector\FuncCall\CreateFunctionToAnonymousFunctionRector: ~

3. Upgrade your Code

    vendor/bin/rector process src --config rector.yml --dry-run
    vendor/bin/rector process src --config rector.yml
tamagochi_man 09-Oct-2018 07:44
Whilst it was correct 11 years ago, the statement of Dan D is not so correct any more? Anonymous functions are now objects of a class Closure and are safely collected by garbage collector.
kexianbin at diyism dot com 10-Jun-2014 04:52
I use this create_closure() in my work to seperate callbacks into Classes:
<?php
function create_closure($fun, $args, $uses)
         {$params=explode(',', $args.','.$uses);
          $str_params='';
          foreach ($params as $v)
                  {$v=trim($v, ' &$');
                   $str_params.='\''.$v.'\'=>&$'.$v.', ';
                  }
          return "return function({$args}) use ({$uses}) {{$fun}(array({$str_params}));};";
         }
?>

example:
<?php
$loop->addPeriodicTimer(1, eval(create_closure('pop_message', '$timer', '$cache_key, $n, &$response, &$redis_client')));

function pop_message($params)
         {extract($params, EXTR_REFS);
          $redis_client->ZRANGE($cache_key, 0, $n)
                            ->then(//normal
                                   function($data) use ($cache_key, $n, &$timer, &$response, &$redis_client)
                                   {//...
                                   },
                                   //exception
                                   function ($e) use (&$timer, &$response, &$redis_client)
                                   {//...
                                   }
                                  );
         }
?>
coleyeder at gmail dot com 01-Oct-2013 04:29
Default values works:

<?php

$f = create_function('$a,$b=3', 'var_dump($a, $b);');
$f(1);

// output:

// int(1)
// int(3)

?>
CertaiN 19-Sep-2013 11:49
Best wapper:

<?php

function create_lambda($args, $code) {
    static $func;
    if (!isset($func[$args][$code])) {
        $func[$args][$code] = create_function($args, $code);
    }
    return $func[$args][$code];
}
ionix at NOSPAM dot post dot com 05-Sep-2013 04:56
I experimented a bit in creating a lambda function using a variable amount of arguments. While I couldn't find an efficient way to create a random bit of code, I was able to get it to behave as a front end for existing functions (as well as user-defined of course).

The code required me to use the dreaded eval() function to get it to use a variable amount of parameters, so be sure that all input is thoroughly cleaned if derived from the user.

<?php

    function run_function( $function )
    {
        // Get Arguments, Unset Exisitng Parameter
        $params = func_get_args();
        unset( $params[0] );

        if( ( $count = count( $params ) ) > 0 )
        {
            $args = '$a';
            $inc = 'b';

            // Create Argument String - Formats as '$a, $b, $c' Per Number of Arguments
            for( $x = 1; $x < $count; $x++ )
            {
                $args .= ', $' . $inc;
                $inc++;
            }

            // Create Lambda Function and Format Paramters
            $lambda = create_function( $args, 'return ' . $function . '(' . $args . ');' );
            $params = "'" . implode('\', \'', $params) . "'";

            // Build and Evaluate Function with Parameters
            $eval = '$return = $lambda(' . $params . ');';
            eval($eval);

            return $return;
        }
        else
        {
            return false;
        }
    }
?>

For most applications you would be better off calling the function normally. Perhaps this little proof of concept may find some use if adapted to work by someone who requires it.
CertaiN 25-Aug-2013 06:20
How to save memory-space:

<?php

function create_lambda($args, $code) {
    static $list = array();
    $i = "{$args}\0{$code}";
    if (!isset($list[$i])) {
        $list[$i] = create_function($args, $code);
    }
    return $list[$i];
}
kak dot serpom dot po dot yaitsam at gmail dot com 27-Jun-2012 12:17
Try this to boost performance of your scripts (increase maxCacheSize):

<?php
runkit_function_copy('create_function', 'create_function_native');
runkit_function_redefine('create_function', '$arg,$body', 'return __create_function($arg,$body);');

function __create_function($arg, $body) {
    static $cache = array();
    static $maxCacheSize = 64;
    static $sorter;

    if ($sorter === NULL) {
        $sorter = function($a, $b) {
            if ($a->hits == $b->hits) {
                return 0;
            }

            return ($a->hits < $b->hits) ? 1 : -1;
        };
    }

    $crc = crc32($arg . "\\x00" . $body);

    if (isset($cache[$crc])) {
        ++$cache[$crc][1];
        return $cache[$crc][0];
    }

    if (sizeof($cache) >= $maxCacheSize) {
        uasort($cache, $sorter);
        array_pop($cache);
    }

    $cache[$crc] = array($cb = eval('return function('.$arg.'){'.$body.'};'), 0);
    return $cb;
}
?>
131 dot php at cloudyks dot org 01-Jun-2012 10:54
For those who want to create closure with create_function, don't bother, you can't.
Use create_closure instead :p

<?php
//same thing as create_function, but returns a closure..( 5.4)
function create_closure($args, $body){
  return eval("return function($args){ {$body}  };");
}
?>
Dave H 24-Mar-2011 06:47
The following function is very useful for creating an alias of a user function.
For built-in functions, it is less useful because default values are not available, so function aliases for built-in functions must have all parameters supplied, whether optional or not.

<?php
function create_function_alias($function_name, $alias_name)
{
    if(function_exists($alias_name))
        return false;
    $rf = new ReflectionFunction($function_name);
    $fproto = $alias_name.'(';
    $fcall = $function_name.'(';
    $need_comma = false;

    foreach($rf->getParameters() as $param)
    {
        if($need_comma)
        {
            $fproto .= ',';
            $fcall .= ',';
        }

        $fproto .= '$'.$param->getName();
        $fcall .= '$'.$param->getName();

        if($param->isOptional() && $param->isDefaultValueAvailable())
        {
            $val = $param->getDefaultValue();
            if(is_string($val))
                $val = "'$val'";
            $fproto .= ' = '.$val;
        }
        $need_comma = true;
    }
    $fproto .= ')';
    $fcall .= ')';

    $f = "function $fproto".PHP_EOL;
    $f .= '{return '.$fcall.';}';

    eval($f);
    return true;
}
?>
phenno7 [a_t] yahoo dot com 15-Sep-2010 01:53
The function takes as arguments the tree array, the category id on which i want the retrieval, and the depth level for which i would like the subcategories ids returned.

this saves me a LOT of time on large adjacency list trees.

<?php
$ctg_tree = array(
'1'=>array('parent_id'=>0,
           'children'=>array(
          '2'=>array('parent_id'=>1,
                      'children'=>array(
                      '3'=>array('parent_id'=>2))),
           '4'=>array('parent_id'=>1,
                      'children'=>array(
                      '5'=>array('parent_id'=>4),
                      '6'=>array('parent_id'=>4))))));

function getSubCategories($ctg_tree, $id, $level = null) {

        $getBranchIds =
create_function(
'$tree, $ctg_id, $level = null, $arr = null,'.
' $push = false, $getBranchIds','
            if(!$arr) {
                $arr = array();
            }
            if(intval($level) && $push){
                $level--;
            }

            foreach($tree as $key=>$ctg) {
                if($push) {
                    $arr[] = $key;
                }
                if($ctg_id == $key) {
                    $start = true;
                    $push = true;
                }
if(count($ctg[\'children\']) && (intval($level) || $level === null)) {
$getBranchIds(
$ctg[\'children\'],$ctg_id,$level,&$arr,$push,$getBranchIds
);
                }
                if($start) return $arr;
            }

            return $arr;');

return $getBranchIds(
$ctg_tree, $id, $level, null, false, $getBranchIds
);
    }

print_r(getSubCategories($ctg_tree, 4, 1));
?>

Array
(
    [0] => 5
    [1] => 6
)

print_r(getSubCategories($ctg_tree, 1, 1));

Array
(
    [0] => 2
    [1] => 4
)

<?php
print_r(getSubCategories($ctg_tree, 1));
?>

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 5
    [4] => 6
)
Its Will 01-Sep-2010 08:27
If you create a function that will only be used from an object context (i.e. you want a dynamic method that can then call methods from the original object, still maintaining access to the object's runtime values) then you can use the following functions I have created (ob_lambda_func and ob_lambda) to enable the dynamic function to easily call *public* methods on the object, in their runtime contexts:

<?php
/* the OB Lambda functions allow a lambda function to call a method from its callee's object */
if(!function_exists('ob_lambda_func')){
function ob_lambda_func($method, $args) {
   if((phpversion()+0)<5.1 || (substr(phpversion(),2)+0)<1.1)
       die("\nError: This script requires PHP v5.1.1+!\n");
   $bt=debug_backtrace();
   foreach($bt as $xsp) {
       if(isset($xsp['object'])) {
           if(!method_exists($xsp['object'], $method)) continue;
           return call_user_func_array(array($xsp['object'], $method), $args);
       }
   }
   if(!function_exists($method))
       die("\nOB: Internal Error! ($method)");
   return call_user_func_array($method, $args);
}}
if(!function_exists('ob_lambda')){
function ob_lambda($method) {
   return create_function('','$args=func_get_args(); return ob_lambda_func('.var_export($method, true).',$args);');
}}

/* Usage:
 *   For each callable method, store the results of ob_lambda('method_name')
 *   When a lambda function you call wants to access one of these methods,
 *    you need to pass it the result of ob_lambda for that method, the easiest
 *    way is to have one of the lambda functions arguments accept the result
 *       i.e.:  $myFunc=ob_lambda('myMethod');
 *              $lf1=create_function('$func', '$func( ... args ... )');
 *              $lf1($myFunc);
 *    because create_function prepends a \0 to the function name, it is difficult
 *    to pass the result of ob_lambda to the target function without using an argument
 */
/* here is an example -- lambda function Foo::test can call Foo::Bar and Foo::Baz, and these  */
class Foo {
    private $bar, $baz, $test;
    private $runtimeValue=0;
    function __construct() {
        $this->runtimeValue=rand();
        $this->bar=ob_lambda('Bar');
        $this->baz=ob_lambda('Baz');
        $this->test=create_function(
            '$bar, $baz',
            '$bar("Hello, World!"); $baz();'
        );
    }
    function Test() {
        $fn=$this->test;
        $fn($this->bar, $this->baz);
    }
    function Bar($a) {
        echo "$a: Bar ($this->runtimeValue)\n";
    }
    function Baz() {
        echo "and another! Baz ($this->runtimeValue)\n";
    }
}

$foo=new Foo();
// Foo::Bar("Testing Other Method"); <-- this causes fatal error
//  (using $this when not in object context)
$foo->Test();

?>

This snippet (with test) shows how the lambda function $foo->test can call Foo::Bar and Foo::Baz without an explicit reference to the original object. The methods are run from their object context, and so can access the runtime-modified variable $foo->runtimeValue, which is set to a random number on construction.
The function definition for $foo->test is the following:
function ($bar, $baz) {
    $bar("Hello, World!");
    $baz;
}
As you can see, it is clean and simple, with no obvious artifacts from the use of OB Lambda

The expected output should be:
Hello, World!: Bar (440048505)
and another! Baz (440048505)

Or any other random number in place of 440048505
Make sure, before you change your code, that your target server has PHP 5.1.1+, or these functions won't work and will return an error!
Hope this helps anyone as much as it has me! :)
julius _email _me _at grantzau _dot _com 16-Jul-2010 09:59
To avoid memory problems, when creating a dynamic function within loops, register it as a global variable, and check if it has already been set;

<?php
global $my_func;
if (!isset($my_func))
{
    $my_func = create_function($args, $code);
}

$my_func();
?>

That way you don't end up creating the same function twice (or a couple of million of times, as it happened to me...)
v dot churakov at i2d dot ru 20-Feb-2010 04:56
<?

function is_function( &$mixed )
{
    if ( is_object( $mixed ) ) {
        return ( $mixed instanceof Closure );
    } elseif( is_string( $mixed ) ) {
        return function_exists( $mixed );
    } else {
        return false;
    }
}

function myfunc(){}

$test = 123;
echo  is_function( $test ); //will return false

$test = 'isset';
echo  is_function( $test ); //will return false... it's not work with reserved :( ...

$test = 'myfunc';
echo  is_function( $test ); //will return true

$test = create_function( '', 'echo 123;' );
echo  is_function( $test ); //will return true

$test = function () { echo 123; };
echo  is_function( $test ); //will return true

?>
edgar at goodforall dot eu 02-Jul-2009 07:45
Just a little toy I thought up, I would like to share. Creates an anonymous function, which let you use a class  as a function.

In php 5.3 there is support for real functors  (trough __invoke):

<?php
function createFunctor($className){
        $content = "
                static \$class;
                if(!\$class){
                        \$class = new $className;
                }
                return \$class->run(\$args);
        ";
        $f = create_function('$args', $content);
        return $f;

}
class test {
        public function run($args){
                print $args;
        }
}
$test = createFunctor('test');
$test('hello world');
?>
Stefan Scheld 23-Sep-2008 07:48
Workaround is as follows:

<?php
class Foo {
    function setHandler($handlerName, $handlerCode) {
        $this->handlerFunctions[$handlerName] = create_function('&$self, $dataArr', $handlerCode);
// NOTE: $this not allowed here, using $self as replacement
    }

    function executeHandler($handlerName, $dataArr) {
        if($this->handlerFunctions[$handlerName]) {
                $this->handlerFunctions[$handlerName](&$this, $dataArr);
            }
     }

    function getConstantInfo($what) {
        return($what);
    }
}

$bla = new Foo;

$bla->setHandler("load", 'echo($self->getConstantInfo("name")."\n");');
$bla->executeHandler("load", array("foo" => "bar"));
?>
neo at nowhere dot com 28-Aug-2008 01:56
In response to kkaiser at revolution-records dot net's note, even tho PHP will allow you to use
<?
$myfunc = create_function('$this', $code);
?>
You can NOT use a reference to "$this" inside of the anonymous function, as PHP will complain that you are using a reference to "$this" in a non-object context.

Currently, I have not found a work-around for this...
Alan FUNG 07-Aug-2008 12:24
$f = create_function('','echo "function defined by create_function";');
$f();

result:
function defined by create_function

You may define no return in function body while you are using create_function.
Rene Saarsoo 06-Feb-2008 02:31
Here has been some discussion about the "memory leak" create_function() can create.

What create_function() actually does, is creating an ordinary function with name chr(0).lambda_n where n is some number:

<?php
$f = create_function('', 'return 1;');

function lambda_1() { return 2; }

$g = "lambda_1";
echo $g(); // outputs: 2

$h = chr(0)."lambda_1";
echo $h(); // outputs: 1
?>
colin dot mckinnon at gmail dot com 20-Aug-2007 05:51
In response to koyama at hoge dot org (14-Dec-2000):

This does NOT create a new method - try adding this at the end:

<?php
if (function_exists($h->lamda)) {
   print "Its a function\n";
} else {
   print "No it isnt";
}
?>

It creates a function which $h->lamda points to.

Under PHP4 you could simply add an argument $this which meant it *behaved* like a method (though it existed in global scope) but with PHP5, you can't have a variable named $this in a function (which is rather irksome).

(and methinks the ant-bot challenge is taking the mickey - min(three, four)?  !).
TSE-WebDesign 18-Aug-2007 09:55
Here's how to call a runtime-created function from another runtime-created function:
<?php
        $get_func = create_function('$func', 'return substr($func,1);');
        $get_value = create_function('$index','return pow($index,$index);');
        $another_func = create_function('$a', '$func="\x00"."'.$get_func($get_value).'";return $func($a);');
        echo $another_func(2); # result is 4
?>
kkaiser at revolution-records dot net 13-Apr-2007 01:10
In the process of migrating a PHP4 codebase to PHP5, I ran into a peculiar problem. In the library, every class was derived from a generic class called 'class_container'. 'class_container' contained an array called runtime_functions and a method called class_function that was as follows:

<?php
function class_function($name,$params,$code) {

  $this->runtime_functions[$name] = create_function($params,$code);

}
?>

In a subclass of class_container, there was a function that utilized class_function() to store some custom lambda functions that were self-referential:

<?php
function myfunc($name,$code) {

  $this->class_function($name,'$theobj','$this=&$theobj;'.$code);

}
?>

In PHP4, this worked just fine. The idea was to write blocks of code at the subclass level, such as "echo $this->id;", then simply $MYOBJ->myfunc("go","echo $this->id;"); and later call it like $MYOBJ->runtime_functions["go"]();

It essentially worked exactly like binding anonymous functions to objects in Javascript.

Note how the "$this" keyword had to be manually redefined for the $code block to work.

In PHP5, however, you can't redeclare $this without getting a fatal error, so the code had to be updated to:

<?php
function myfunc($name,$code) {

  $this->class_function($name,'$this',$code);

}
?>

Apparently create_function() allows you to set $this via a function argument, allowing you to bind anonymous functions to instantiated objects. Thought it might be useful to somebody.
Dan D 23-Oct-2006 07:22
Beware when using anonymous functions in PHP as you would in languages like Python, Ruby, Lisp or Javascript.  As was stated previously, the allocated memory is never released; they are not objects in PHP -- they are just dynamically named global functions -- so they don't have scope and are not subject to garbage collection.

So, if you're developing anything remotely reusable (OO or otherwise), I would avoid them like the plague.  They're slow, inefficient and there's no telling if your implementation will end up in a large loop.  Mine ended up in an iteration over ~1 million records and quickly exhasted my 500MB-per-process limit.
Phlyst 06-Oct-2006 05:10
In reply to info at adaniels dot nl:

You may not be able to use __FUNCTION__ in a lambda (thanks for pointing it out; I was having that problem just now), but you can use $GLOBALS to work around it if you're assigning the function to a variable. I reimplemented array_walk_recursive() in PHP4 like this:

<?php
$array_walk_recursive = create_function('&$array, $callback',
    'foreach($array as $element) {
        if(is_array($element)) {
            $funky = $GLOBALS["array_walk_recursive"];
            $funky($element, $callback);
        }
        else {
            $callback($element);
        }
    }');
?>
Josh J 27-Sep-2006 12:45
In regards to the recursion issue by info at adaniels dot nl

Anon function recursion by referencing the function variable in the correct scope.
<?php
$fn2 = create_function('$a', 'echo $a; if ($a < 10) call_user_func($GLOBALS["fn2"], ++$a);');
$fn2(1);
?>
info at adaniels dot nl 10-May-2006 03:42
Note that using __FUNCTION__ in a an anonymous function, will always result '__lambda_func'.

<?php
    $fn = create_function('', 'echo __FUNCTION__;');
    $fn();
    // Result: __lambda_func
    echo $fn;
    // Result: ºlambda_2 (the actual first character cannot be displayed)
?>

This means that a anonymous function can't be used recursively. The following code (recursively counting to 10) results in an error:
<?php
    $fn2 = create_function('$a', 'echo $a; if ($a < 10) call_user_func(__FUNCTION__, $a++);');
    $fn2(1);
    // Warning: call_user_func(__lambda_func) [function.call-user-func]: First argument is expected to be a valid callback in T:/test/test.php(21) : runtime-created function on line 1
?>
josh at janrain dot com 03-Mar-2006 10:21
Beware! This is merely a convenience function that generates a unique name for a regular function. It is *not* a closure or even an anonymous function. It is just a regular function that gets named for you.
Joshua E Cook 19-Jan-2006 04:43
Functions created by create_function() cannot return a value by reference.  The function below creates a function that can.  The arguments are the same as create_function().  Note that these arguments are passed, unmodified, to eval(), so be sure that data passed in is sanitized.

<?php
/**
 * create_ref_function
 * Create an anonymous (lambda-style) function
 * which returns a reference
 * see http://php.net/create_function
 */
function
create_ref_function( $args, $code )
{
    static $n = 0;

    $functionName = sprintf('ref_lambda_%d',++$n);

    $declaration = sprintf('function &%s(%s) {%s}',$functionName,$args,$body);

    eval($declaration);

    return $functionName;
}
?>
boards at gmail dot com 31-Dec-2005 11:18
If you were checking to see if a function is made properly, this would be a better way of checking:

<?php
$fnc = @create_function('$arg1,$arg2,$arg3', 'return true;');
# make that function whatever you want
if (empty($fnc)) {
  die('Could not create function $fnc.');
}

# although, the follow will NOT work
if (empty(create_function('$arg', 'return $arg;'))) {
  die('Could not create anonymous function.');
}
# you would get an error regarding not being able to use a
# return value in writeable context (i.e. a return value is
# a const in C, and the function empty() doesn't use a
# const void* parameter
?>
david [at] davelee.com.au 13-Apr-2005 02:15
<?php
# dynamically create html helper functions which take the args
# $string_contents, $optional_hash_of_options
# and return the contents wrapped in a tag

$html_funcs = Array(
    'table',
    'tr',
    'th',
    'td',
    'div',
    'span',
    'pre',
    'strong',
    'em'
);
$args = '$html, $options=Array()';
$code = '
  $o = "";
  foreach ($options as $a => $b) {
    $o .= " $a=\"$b\"";
  }
  return "<$tag$o>$html</$tag>";
';
foreach ($html_funcs as $key => $tag) {
    ${$tag} = create_function($args, "\$tag = '$tag'; $code");
}

# usage example:

print $table(
  $tr($th('heading').$td('this is the cell content')),
  Array('style'=>'border: 1px solid silver;')
);
?>
MagicalTux at FF.ST 09-Mar-2004 10:25
neo at gothic-chat d0t de wrote :
Beware of memory-leaks, the garbage-collection seems to 'oversee' dynamically created functions!

Not really...

In fact, PHP can not "unassign" functions. So if you create a function, it won't be deleted until the end of the script, even if you unset the variable containing its name.

If you need to change a part of a function everytime you run a loop, think of a way to make a more general function or try using eval :) (functions are made to be re-used. If you need to run your own piece of code once, eval is much better).
neo at gothic-chat d0t de 20-Jan-2004 08:54
Beware of memory-leaks, the garbage-collection seems to 'oversee' dynamically created functions!

I used a function like this to replace special characters in links with their htmlentities:
<?php
$text = preg_replace_callback (
    "/(<(frame src|a href|form action)=\")([^\"]+)(\"[^>]*>)/i",
    create_function (
        '$matches',
        'return $matches[1] . htmlentities ($matches[3]) . $matches[4];'
    ),
    $text);
?>

After 1000 calls, the process used about 5MB more than before. In my situation this boosted up the memory-size of one PHP-process up to over 100MB!

In such cases, better store the function in a global variable.
nospam at fiderallalla dot de 08-Aug-2003 06:39
Sometimes it may be useful to create functions in a dynamic environment
(f. e. in a daemon-like php script).

Normally declaring a function must be done once, which results in the problem,
that in this special case modifying a function wouldn't have an effect until the script is reloaded.

Maybe this code snipplet is useful 4 u.

File: "functions.inc"

<?php
function test($str) {
    echo $str;
}
?>

Dynamic FunctionHandler:

<?php
$FileName = "functions.inc";
$FileHandle = fopen($FileName,"r");
$FileContent = fread($FileHandle,filesize($FileName));
fclose($FileHandle);

preg_match_all("#function\ ?([a-zA-Z0-9-_]*)\ ?\((.*?)\)\ ?\{(.*?)\}#mixse",$FileContent,$Matches);
if ( is_array($Matches) && isset($Matches[0]) && count($Matches[0]) > 0  ) {
     foreach ( $Matches[0] as $key=>$val ) {
        $$Matches[1][$key] = create_function($Matches[2][$key],$Matches[3][$key]);
    }
}
?>

The Test:
<?php echo $test("test"); ?>
.. will echo "test";

Hans Kuhlen
DB on music_ml at yahoo dot com dot ar 02-Apr-2003 04:58
[EDIT by danbrown AT php DOT net: Combined user-corrected post with previous (incorrect) post.]

You can't refer to a class variable from an anonymous function inside a class method using $this.  Anonymous functions don't inherit the method scope.  You'll have to do this:

<?php
class AnyClass {

 var $classVar = 'some regular expression pattern';

 function classMethod() {

   $_anonymFunc = create_function( '$arg1, $arg2', 'if ( eregi($arg2, $arg1) ) { return true; } else { return false; } ' );

   $willWork = $_anonymFunc('some string', $classVar);

 }

}
?>
ben-php at bacarisse dot btinternet dot co dot uk 26-Jul-2001 01:33
A nice technique for building complex search patterns on lists, files or whatever is to build function combining functions like this:

<?php
function _not_($f) {
  return create_function('$x',
    "return !$f(\$x);");
}

function _and_($f, $g) {
  return create_function('$x',
    "return $f(\$x) && $g(\$x);");
}
?>

(similarly for _or_ and others...).  Once you've built your matching primitives you can then build more complex matches into your script.

Unfortunately, as explained in (closed) bug #10721, the function names returned by create_function have a null byte at the front and this causes a parse error.

You can fix the definition like this:

<?php
function _not_($f) {
  $f = substr($f, 1);
  return create_function('$x',
    "return !call_user_func(chr(0).'$f', \$x)");
}
?>

The expression that re-builds the function name avoid the null being literally in the parsed string.  If there is a better fix, please let me know.
x-empt[a_t]ispep.cx 05-Jul-2001 11:41
Create_function enables the ability to change the scope of functions.  You might have a class where it needs to define a GLOBAL function.  This is possible, like:

<?php
        class blah {
                function blah() {
                        $z=create_function('$arg1string','return "function-z-".$arg1string;');
                        $GLOBALS['z']=$z;
                }
        }
        $blah_object=new blah;

        $result=$GLOBALS['z']('Argument 1 String');
        echo $result;
?>

Making a function escape it's defined scope can be useful in many situations.
maxim at maxim dot cx 27-Apr-2001 03:26
for those who want to assign it's own name to a function consider this code:

<?php
$fname = 'hello';

$func = sprintf('
    function %s($v="") {
        Return "$v<BR>";
    }
',
$fname
);

eval($func);
echo $fname('Please print it.... please....');
?>

what it does is,
: Creats a function as a string;
: Replaces the function name with $fname value;
: Converts the string into a REAL php code with eval()
: Calls the function using the variable function as declared before ($fname);

Simple, isn't it?

Can work well as an abstraction layer for portability and/or compatibility purposes

Maxim Maletsky
maxim@maxim.cx // PHPBeginner.com
mrben at free dot fr 20-Feb-2001 08:33
Here is another tricky but usefull techynote, good for adding "plugin" to a existing class :

<?php

class Hoge {
    var $lamda;
    var $text;

    function set($lamda)
    {
        $this->lamda = $lamda;
    }

    function callLamda()
    {
        $func = $this->lamda;
        return $func($this);
    }

    function get()
    {
        return $this->text;
    }
}

$newfunc = create_function('&$class', 'echo $class->get();' );

$h = new Hoge;
$h->text = "Hi there !";
$h->set($newfunc);
$h->callLamda();

?>
koyama at hoge dot org 14-Dec-2000 04:22
How do you use function which is created by create_function() as class method?

<?php
class Hoge {
  var $lamda;
  function set($lamda) {
    $this->lamda = $lamda;
  }
  function callLamda() {
    $func = $this->lamda;
    return $func();
  }
}

$newfunc = create_function('', 'echo "hoge<br>\n";');

$h = new Hoge;
$h->set( $newfunc );
$h->callLamda();
?>

It works fine. :-)


Llamar a un método estático y pasar los argumentos como matriz

  • « create_function
  • forward_static_call »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Llamar a un método estático y pasar los argumentos como matriz

forward_static_call_array

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

forward_static_call_array — Llamar a un método estático y pasar los argumentos como matriz

Descripción

forward_static_call_array ( callable $function , array $parameters ) : mixed

Llama a una función o método definido por el usuario, dado por el parámetro function. Esta función debe ser llamada dentro del contexto de un método, no se puede usar fuera de una clase. Usa el Enlace estático en tiempo de ejecución. Todos los argumentos del método a llamar se pasan como valores, y como matriz, similar a call_user_func_array().

Parámetros

function

La función o método a ser llamado. Este parámetro puede ser un array, con el nombre de la clase y del método, o un string, con el nombre de una función.

parameter

Un parámetro, reuniendo todos los parámetros del método en una matriz.

Nota:

Observe que los parámetros para forward_static_call_array() no son pasados por referencia.

Valores devueltos

Devuelve el resultado de la función, o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de forward_static_call_array()

<?php

class A
{
    const NOMBRE = 'A';
    public static function prueba() {
        $args = func_get_args();
        echo static::NOMBRE, " ".join(',', $args)." \n";
    }
}

class B extends A
{
    const NOMBRE = 'B';

    public static function prueba() {
        echo self::NOMBRE, "\n";
        forward_static_call_array(array('A', 'prueba'), array('más', 'args'));
        forward_static_call_array( 'prueba', array('otro', 'args'));
    }
}

B::prueba('foo');

function prueba() {
        $args = func_get_args();
        echo "C ".join(',', $args)." \n";
    }

?>

El resultado del ejemplo sería:

B
B más,args
C otro,args

Ver también

  • forward_static_call() - Llamar a un método estático
  • call_user_func() - Llamar a una llamada de retorno dada por el primer parámetro
  • call_user_func_array() - Llamar a una llamada de retorno con un array de parámetros
  • is_callable() - Verificar que los contenidos de una variable puedan ser llamados como una función

User Contributed Notes

israfilov93 at gmal dot com 15-Aug-2018 07:04
one of academic example, when forward_static_call() can be useful

<?php

class A
{
    public static function test()
    {
        var_dump('we were here');
        return static::class;
    }
}

class B extends A
{
    public static function test()
    {
        return self::class;
    }
}

class C extends B
{
    public static function test()
    {
        $grandParent = get_parent_class(parent::class); // $grandParent is A
        return forward_static_call([$grandParent, __FUNCTION__]); // calls A::test()
    }
}

// prints
// string(12) "we were here"
// string(1) "C"
var_dump(C::test());
nino dot skopac at gmail dot com 30-Jul-2016 02:49
Regarding namespaces:

Be sure to include fully namespaced class path:

<?php
forward_static_call_array(
    array('NAMESPACE\CLASS_NAME', 'STATIC_METHOD'),
    $params
);


Llamar a un método estático

  • « forward_static_call_array
  • func_get_arg »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Llamar a un método estático

forward_static_call

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

forward_static_call — Llamar a un método estático

Descripción

forward_static_call ( callable $function , mixed $parameter = ? , mixed $... = ? ) : mixed

Llama a una función o método definido por el usuario, dado por el parámetro function, con los siguientes argumentos. Esta función debe ser llamada dentro del contexto de un método, no se puede usar fuera de una clase. Usa el Enlace estático en tiempo de ejecución.

Parámetros

function

La función o método a ser llamado. Este parámetro puede ser una matriz, con el nombre de la clase y del método, o una cadena, con el nombre una función.

parameter

Cero o más parámetros a ser pasados a la función.

Valores devueltos

Devuelve el resultado de la función, o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de forward_static_call()

<?php

class A
{
    const NOMBRE = 'A';
    public static function prueba() {
        $args = func_get_args();
        echo static::NOMBRE, " ".join(',', $args)." \n";
    }
}

class B extends A
{
    const NOMBRE = 'B';

    public static function prueba() {
        echo self::NOMBRE, "\n";
        forward_static_call(array('A', 'prueba'), 'más', 'args');
        forward_static_call( 'prueba', 'otro', 'args');
    }
}

B::prueba('foo');

function prueba() {
        $args = func_get_args();
        echo "C ".join(',', $args)." \n";
    }

?>

El resultado del ejemplo sería:

B
B más,args
C otro,args

Ver también

  • forward_static_call_array() - Llamar a un método estático y pasar los argumentos como matriz
  • call_user_func_array() - Llamar a una llamada de retorno con un array de parámetros
  • call_user_func() - Llamar a una llamada de retorno dada por el primer parámetro
  • is_callable() - Verificar que los contenidos de una variable puedan ser llamados como una función

User Contributed Notes

jhibbard at gmail dot com 19-Jun-2012 07:55
Example usage via calls outside of the class and within an object:

<?php
/**
 * @author Jonathon Hibbard
 */
class foo {
  # used to verify we're actually setting something..
  private static $value = '';

  /**
   * Simple setter for the static method setValue...
   */
  public static function set($method_identifier, $value_to_pass = '') {
    # make sure we have the right method format...
    # another semi-useful example is like this (useful for REST-like requests...): str_replace(" ", "", ucwords(str_replace("_", " ",  $method_identifier)));
    $static_method = 'set' . ucfirst(strtolower(trim($method_identifier)));

    if(method_exists(__CLASS__, $static_method)) {
      //Note:  this will not work and will throw PHP Parse error:  syntax error, unexpected '::'
      //__CLASS__::$static_method($value_to_pass);

      foo::$static_method($value_to_pass);

      echo "\tCalling forward_static_call with pure string and value param:\n";
      forward_static_call(__CLASS__ . "::" . $static_method, $value_to_pass);

      echo "\tCalling forward_static_call with class, method array and value param:\n";
      forward_static_call(array(__CLASS__, $static_method), $value_to_pass);
    }
  }

  /**
   * Set self::$value to something?
   */
  public static function setValue($value_recieved = '') {
    echo "\t\tsetValue called with param of " . var_export($value_recieved, true) . "!\n";

    echo "\t\tSetting Private 'value'...\n";

    self::$value = $value_recieved;

    echo "\t\tChecking the Private 'value':\n";
    if(!empty(self::$value)) {
      echo "\t\t\tPrivate 'value' was set to '" . self::$value . "' as expected!\n";
    } else {
      echo "\t\t\tPrivate 'value' was not set!\n";
    }

    # Reset...
    self::$value = '';
  }

  /**
   * Create an object and test calling the static method from within this realm...
   */
  public function __construct() {
    echo "\tCalling from within constructor..\n";
    foo::set('value','Something else from within the instance!');
  }
}

echo "\n============ Calling by static method first ============\n";
foo::set('value','Something from outside of the foo class!');

echo "\n============ Calling by static method without a value next ============\n";
foo::set('value');

echo "\n============ Calling by createing an instance next ============\n";
new foo();
?>
arthur dot techarts at gmail dot com 12-Jul-2011 07:39
Example to understand this function and difference with call_user_func:

<?php
class Beer {
    const NAME = 'Beer!';
    public static function printed(){
        echo 'static Beer:NAME = '. static::NAME . PHP_EOL;
    }
}

class Ale extends Beer {
    const NAME = 'Ale!';
    public static function printed(){
        forward_static_call(array('parent','printed'));
        call_user_func(array('parent','printed'));

        forward_static_call(array('Beer','printed'));
        call_user_func(array('Beer','printed'));
    }
}

Ale::printed();
echo '</pre>';
?>


Devuelve un elemento de una lista de argumentos

  • « forward_static_call
  • func_get_args »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Devuelve un elemento de una lista de argumentos

func_get_arg

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

func_get_arg — Devuelve un elemento de una lista de argumentos

Descripción

func_get_arg ( int $arg_num ) : mixed

Obtiene el argumento especificado de una lista de argumentos de una función definida por el usuario.

Esta función se puede usar junto con func_get_args() y func_num_args() para permitir a las funciones de usuario aceptar listas de argumentos de longitud variable.

Parámetros

arg_num

El índice del argumento. Los argumentos de las funciones se empiezan a contar desde cero.

Valores devueltos

Devuelve el argumento especificado, o false en caso de error.

Historial de cambios

Versión | Descripción
5.3.0 | Esta función ahora se puede usar en listas de parámetros.
5.3.0 | Si esta función es llamada desde el ámbito último de un archivo que ha sido incluido mediante una llamada a include o require desde dentro de una función en el archivo de llamada, ahora genera una advertencia y devuelve false.

Errores/Excepciones

Genera una advertencia si se llama desde fuera de una función definida por el usuario, o si arg_num es mayor que el número de argumentos pasados actualmente.

Ejemplos

Ejemplo #1 Ejemplo de func_get_arg()

<?php
function foo()
{
     $númargs = func_num_args();
     echo "Número de argumentos: $númargs<br />\n";
     if ($númargs >= 2) {
         echo "El segundo argumento es: " . func_get_arg(1) . "<br />\n";
     }
}

foo (1, 2, 3);
?>

Ejemplo #2 Ejemplo de func_get_arg() antes y después de PHP 5.3

prueba.php
<?php
function foo() {
    include './fga.inc';
}

foo('Primer argumento', 'Segundo argumento');
?>

fga.inc
<?php

$arg = func_get_arg(1);
var_export($arg);

?>

Salida anterior a PHP 5.3:

'Segundo argumento'

Salida en PHP 5.3 y posterior:

Warning: func_get_arg():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fga.inc on line 3
false

Ejemplo #3 func_get_arg() ejemplo de argumentos byref (pasa un objeto como referencia) y byval (pasa un objeto como valor)

<?php
function byVal($arg) {
    echo 'Pasó como     : ', var_export(func_get_arg(0)), PHP_EOL;
    $arg = 'baz';
    echo 'Tras el cambio: ', var_export(func_get_arg(0)), PHP_EOL;
}

function byRef(&$arg) {
    echo 'Pasó como     : ', var_export(func_get_arg(0)), PHP_EOL;
    $arg = 'baz';
    echo 'Tras el cambio: ', var_export(func_get_arg(0)), PHP_EOL;
}

$arg = 'bar';
byVal($arg);
byRef($arg);
?>

El resultado del ejemplo sería:

Pasó como : 'bar'
Tras el cambio: 'bar'
Pasó como : 'bar'
Tras el cambio: 'baz'

Notas

Nota:

Como esta función depende del ámbito actual para determinar los detalles del parámetro, no puede ser usada como parámetro de función en versiones anteriores a 5.3.0. Si se require pasar el valor, los resultados deben ser asignados a una variable y esta variable debería pasarse como parámetro.

Nota:

Si los argumentos se pasan por referencia, cualquier cambio en ellos se verá reflejado en los valores devueltos por esta función. A partir de PHP 7, los valores actuales también serán devueltos si los argumentos son pasados por valor.

Nota: Esta función solamente devuelve una copia de los argumentos pasados, y no rinde cuentas de los argumentos predeterminados (no pasados).

Ver también

  • La sintaxis de ... en PHP 5.6+
  • func_get_args()
  • func_num_args()

User Contributed Notes

gordon at abetz-rouse dot com dot au 23-Mar-2020 11:30
This function may work differently from php5 to php7, in the latter it seems to reference the variable, while in php5 it returns the original argument.
I have confirmed with the versions below, but this will require further confirmation as to whether this is a 5 versus 7 issue.

function test( $test ){

    $test = '123';

    echo func_get_arg(0);

}

test( '321' );

//in php 5.5.9, this script will write '321'
//in php 7.0.33, this script will write '123'
beta3designs [at] gmail [dot] com 06-Jul-2009 06:34
This functions seems so powerful... just when i saw it i thought about writing a fast average of n numbers function so here it is, it is very simple... example usage included.

<?php

//Calculate the average of the numbers given

function avg(){
    $sum = 0;
    for($i = 0; $i < func_num_args(); $i++){
        $sum += func_get_arg($i);
    }
    $avg = $sum / func_num_args();
    return $avg;
}

echo sprintf("%.2f",avg(2,1,2,1,3,4,5,1,3,6));
?>
mw atto lanfear dotto com 07-Dec-2004 02:56
func_get_arg() does not appear to be allowed to be used as a function argument itself within class constructors in PHP 5.0.2 (wonk-ay!!!):

<?php

class ABC
{
    function __construct()
    {
        foreach (func_get_args() as $name => $value)
        {
    echo <<<EOT
    <br/>
    $name : $value <br/>
    <br/>

EOT;
        }
    }
}

class DEF extends ABC
{
    function __construct()
    {
        parent::__construct(func_get_arg(0),
                                    func_get_arg(1),
                                    func_get_arg(2));
    }
}

$def = new DEF(123123, "asdfasdf", "blahblahblah");

?>

The above script generates:

Fatal error: func_get_arg(): Can't be used as a function parameter in c:\Inetpub\wwwroot\phpwasrc\chapter10\xxx.php on line 23

There are, however, no problems when passing these as parameters to regular functions.
anders at ingemann dot fakestuff dot de 03-Jun-2004 06:16
I actually think that there is need for such "do absolutely everything" functions. I use them mostly as tools for rapid prototyping.
And there is a method with which you may be able to pass several strings to a function: ereg();
Another use for such functions is to create little code snippets for other people out there. They won't have to edit the function any longer if they do not use a parameter. They just don't name it when calling the function.
This results in allrounder functions that are very robust in their use.Normally you just have a little code snippet (e.g. ip-blocking snippets). Through this type of programming you have whole functions.
mightye (at) mightye (dot) org 12-Mar-2004 09:45
func_get_arg() returns a *copy* of the argument, to my knowledge there is no way to retrieve references to a variable number of arguments.

I have a module system in my game at http://lotgd.net where I'd like to be able to pass a variable number of arguments to functions in a module, and pass them by reference if the module asks for it by reference, but you can't accept optional parameters as references, nor can you retrieve the reference on a variable number of arguments.  Looks like my modules will have to do with out the ability to accept parameters to their functions by reference.


Devuelve un array que se compone de una lista de argumentos de función

  • « func_get_arg
  • func_num_args »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Devuelve un array que se compone de una lista de argumentos de función

func_get_args

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

func_get_args — Devuelve un array que se compone de una lista de argumentos de función

Descripción

func_get_args ( ) : array

Obtiene un array de la lista de argumentos de una función.

Esta función se puede usar junto con func_get_arg() y func_num_args() para permitir a las funciones definidas por el usuario aceptar una lista de argumentos de longitud variable.

Valores devueltos

Devuelve un array en el que cada elemento es una copia del miembro correspondiente de la lista de argumentos de la función definida por el usuario.

Historial de cambios

Versión | Descripción
5.3.0 | Esta función ahora se puede usar en listas de parámetros.
5.3.0 | Si esta función es llamada desde el ámbito último de un archivo que ha sido incluido mediante una llamada a include o require desde dentro de una función en el archivo de llamada, ahora genera una advertencia y devuelve false.

Errores/Excepciones

Genera una advertencia si se llama desde fuera de una función definida por el usuario.

Ejemplos

Ejemplo #1 Ejemplo de func_get_args()

<?php
function foo()
{
    $númargs = func_num_args();
    echo "Número de argumentos: $númargs \n";
    if ($númargs >= 2) {
        echo "El segundo argumento es: " . func_get_arg(1) . "\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $númargs; $i++) {
        echo "El argumento $i es: " . $arg_list[$i] . "\n";
    }
}

foo(1, 2, 3);
?>

El resultado del ejemplo sería:

Número de argumentos: 3
El segundo argumento es: 2
El argumento 0 es: 1
El argumento 1 es: 2
El argumento 2 es: 3

Ejemplo #2 Ejemplo de func_get_args() antes y después de PHP 5.3

prueba.php
<?php
function foo() {
    include './fga.inc';
}

foo('Primer argumento', 'Segundo argumento');
?>

fga.inc
<?php

$args = func_get_args();
var_export($args);

?>

Salida antes de PHP 5.3:

array (
  0 => 'Primer argumento',
  1 => 'Segundo argumento',
)

Salida en PHP 5.3 y posterior:

Warning: func_get_args():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fga.inc on line 3
false

Ejemplo #3 func_get_args() ejemplo de argumentos byref (pasa un objeto como referencia) y byval (pasa un objeto como valor)

<?php
function byVal($arg) {
    echo 'Pasó como     : ', var_export(func_get_args()), PHP_EOL;
    $arg = 'baz';
    echo 'Tras el cambio  : ', var_export(func_get_args()), PHP_EOL;
}

function byRef(&$arg) {
    echo 'Pasó como     : ', var_export(func_get_args()), PHP_EOL;
    $arg = 'baz';
    echo 'Tras el cambio  : ', var_export(func_get_args()), PHP_EOL;
}

$arg = 'bar';
byVal($arg);
byRef($arg);
?>

Salida del ejemplo anterior en PHP 7:

Pasó como : array (
0 => 'bar',
)
Tras el cambio : array (
0 => 'baz',
)
Pasó como : array (
0 => 'bar',
)
Tras el cambio : array (
0 => 'baz',
)

Salida del ejemplo anterior en PHP 5:

Pasó como : array (
0 => 'bar',
)
Tras el cambio : array (
0 => 'bar',
)
Pasó como : array (
0 => 'bar',
)
Tras el cambio : array (
0 => 'baz',
)

Notas

Nota:

Como esta función depende del ámbito actual para determinar los detalles del parámetro, no puede ser usada como parámetro de función en versiones anteriores a 5.3.0. Si se require pasar el valor, los resultados deben ser asignados a una variable y esta variable debería pasarse como parámetro.

Nota:

Si los argumentos se pasan por referencia, cualquier cambio en ellos se verá reflejado en los valores devueltos por esta función. A partir de PHP 7, los valores actuales también serán devueltos si los argumentos son pasados por valor.

Nota: Esta función solamente devuelve una copia de los argumentos pasados, y no rinde cuentas de los argumentos predeterminados (no pasados).

Ver también

  • La sintaxis de ... en PHP 5.6+
  • func_get_arg()
  • func_num_args()
  • ReflectionFunctionAbstract::getParameters()

User Contributed Notes

cobrattila at gmail dot com 20-Nov-2019 04:17
If you want to get the arguments by reference, instead of func_get_args() you can simply use

<?php
function args_byref(&...$args) {
    // Modify the $args array here
}
?>

Credits should go to Markus Malkusch for pointing this out on Stackoverflow.
https://stackoverflow.com/a/29181826/1426064
foxkeys at gmail dot com 17-Mar-2016 06:18
Merge func_get_args() with function defaults
<?php
class utils {
  /**
   * @param mixed[] $args
   * @param ReflectionMethod $reflectionMethod
   *
   * @return array
   */
  public static function mergeArgsWithDefaults( $args, \ReflectionMethod $reflectionMethod ) {
    foreach ( array_slice( $reflectionMethod->getParameters(), count( $args ) ) as $param ) {
      /**
       * @var ReflectionParameter $param
       */
      $args[] = $param->getDefaultValue();
    }
    return $args;
  }
}

class  sampleParent {
  const USER_FILE_TYPE_FILE = 'FILE';
  public function select( $idUserFile = null, $idUserFileType = self::USER_FILE_TYPE_FILE ) {
    echo '[$idUserFile=>' . $idUserFile . ', $idUserFileType=>' . $idUserFileType, ']<br/>' . PHP_EOL;
  }
}

class sample extends sampleParent {
  const USER_FILE_TYPE_IMG = 'IMG';
  public function select( $idUserFile = null, $idUserFileType = self::USER_FILE_TYPE_IMG ) {
    return call_user_func_array( 'parent::select', \utils::mergeArgsWithDefaults( func_get_args(), new ReflectionMethod( __CLASS__, __FUNCTION__ ) ) );
  }
}

$sample1 = new sampleParent();
$sample1->select();//Prints "" / self::USER_FILE_TYPE_FILE
$sample1->select(1);//Prints 1 / self::USER_FILE_TYPE_FILE
$sample1->select(2, 'test 1');//Prints 2 / "test 1"
echo '<br/>' . PHP_EOL;
$sample2 = new sample();
$sample2->select();//Prints "" / self::USER_FILE_TYPE_IMG
$sample2->select(3);//Prints 3 / self::USER_FILE_TYPE_IMG
$sample2->select(4, 'test 2');//Prints 4 / "test 2"
?>
maarten at ba dot be 13-Sep-2012 11:58
it seems that this function only returns a copy and loses it's byref information, use this dirty non-efficient workaround instead:

at the moment of writing it currently returns all of them as references, instead of only the ones who are passed that way...

<?php
function func_get_args_byref() {
        $trace = debug_backtrace();
        return $trace[1]['args'];
}
?>
OpenTechnologist 30-Dec-2011 07:54
please note that optional parameters are not seen/passed by func_get_args(), as well as func_get_arg().

ex:

<?php
function testfunc($optional = 'this argument is optional..') {
    $args = func_get_args();
    var_dump($args);
    echo $optional;
}
?>

test case #1:
testfunc('argument no longer optional..');

result for #1:
array(1) {
    [0]=>  string(20) "argument no longer optional.."
}
argument no longer optional..

test case #2:
testfunc('argument no longer optional..','this is an extra argument');

result for #2:
array(2) {
    [0]=>  string(29) "argument no longer optional.."
    [1]=>  string(25) "this is an extra argument"
}
argument no longer optional..

test case #3: -- RESULTS IN AN EMPTY ARRAY
testfunc();

result for #3:
array(0) {
}
this argument is optional..
mitko at edabg dot com 06-Apr-2009 03:48
<?php
/*
This example demonstrate how to use unknown variable arguments by reference.
func_get_args() don't return arguments by reference, but
debug_backtrace() "args" is by reference.
In PHP 5 this have no particular sense, because calling with arguments by reference
is depreciated and produce warning.
*/

class foo {

    var $bar = "default bar";

    function foo(/*variable arguments*/) {
// func_get_args returns copy of arguments
//        $args = func_get_args();
// debug_backtrace returns arguments by reference
        $stack = debug_backtrace();
        $args = array();
        if (isset($stack[0]["args"]))
            for($i=0; $i < count($stack[0]["args"]); $i++)
                $args[$i] = & $stack[0]["args"][$i];
        call_user_func_array(array(&$this, 'bar'), $args);
    }

    function bar($bar = NULL) {
        if (isset($bar))
            $this->bar = & $bar;
    }
}

$global_bar = "bar global";
$foo = & new foo();
echo "foo->bar:    ".$foo->bar."</br>\n";
$foo->bar = "new bar";
echo "global_bar:  ".$global_bar."</br>\n";
/*
Result:
foo->bar:    default bar</br>
global_bar:  bar global</br>
*/

$foo = & new foo(&$global_bar);
echo "foo->bar:    ".$foo->bar."</br>\n";
$foo->bar = "new bar";
echo "global_bar:  ".$global_bar."</br>\n";
/*
Result:
foo->bar:    bar global</br>
global_bar:  new bar</br>
*/

?>
anderson at francotecnologia dot com 26-Aug-2008 11:25
How to create a polymorphic/"overloaded" function

<?php
function select()
{
    $t = '';
    $args = func_get_args();
    foreach ($args as &$a) {
        $t .= gettype($a) . '|';
        $a = mysql_real_escape_string($a);
    }
    if ($t != '') {
        $t = substr($t, 0, - 1);
    }
    $sql = '';
    switch ($t) {
        case 'integer':
            // search by ID
            $sql = "id = {$args[0]}";
            break;
        case 'string':
            // search by name
            $sql = "name LIKE '%{$args[0]}%'";
            break;
        case 'string|integer':
            // search by name AND status
            $sql = "name LIKE '%{$args[0]}%' AND status = {$args[1]}";
            break;
        case 'string|integer|integer':
            // search by name with limit
            $sql = "name LIKE '%{$args[0]}%' LIMIT {$args[1]},{$args[2]}";
            break;
        default:
            // :P
            $sql = '1 = 2';
    }
    return mysql_query('SELECT * FROM table WHERE ' . $sql);
}
$res = select(29); // by ID
$res = select('Anderson'); // by name
$res = select('Anderson', 1); // by name and status
$res = select('Anderson', 0, 5); // by name with limit
?>
ario [a] mail [dot] utexas [dot] edu 07-May-2007 02:50
"Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable."

This means that the following code generates an error:

<?php

function foo($list)
{
  echo implode(', ', $list);
}

function foo2()
{
  foo(func_get_args());
}

foo2(1, 2, 3);

?>

However, you can easily get around this by doing the following:

<?php

function foo($list)
{
  echo implode(', ', $list);
}

function foo2()
{
  foo($args = func_get_args());
}

foo2(1, 2, 3);

?>

This captures the context from foo2(), making this legal.  You get the expected output:

"1, 2, 3"
T.M. 04-Nov-2004 07:24
Simple function to calculate average value using dynamic arguments:
<?php
function average(){
    return array_sum(func_get_args())/func_num_args();
}
print average(10, 15, 20, 25); // 17.5
?>
daveNO at ovumSPAMdesign dot com 17-Sep-2001 11:29
<?php
// How to simulate named parameters in PHP.
// By Dave Benjamin <dave@ovumdesign.com>

// Turns the array returned by func_get_args() into an array of name/value
// pairs that can be processed by extract().
function varargs($args) {
    $count = count($args);
    for ($i = 0; $i < $count; $i += 2) {
        $result[$args[$i]] = $args[$i + 1];
    }

    return $result;
}

// Example
function test(&$ref1, &$ref2) {
    // Default arguments go here.
    $foo = "oof";

    // Do some magic.
    extract(varargs(func_get_args()));

    echo nl2br("\n\$var1 = $var1");
    echo nl2br("\n\$var2 = $var2");
    echo nl2br("\n\$foo = $foo\n\n");

    // Modify some variables that were passed by reference.
    // Note that func_get_args() doesn't pass references, so they
    // need to be explicitly declared in the function definition.
    $ref1 = 42;
    $ref2 = 84;
}

$a = 5;
$b = 6;

echo nl2br("Before calling test(): \$a = $a\n");
echo nl2br("Before calling test(): \$b = $b\n");

// Try removing the 'foo, "bar"' from the following line.
test($a, $b, var1, "abc", var2, "def", foo, "bar");

echo nl2br("After calling test(): \$a = $a\n");
echo nl2br("After calling test(): \$b = $b\n");
?>
04-Jun-2001 07:44
You can pass a variable number of arguments to a function whilst keeping references intact by using an array. The disadvantage of course, is that the called function needs to be aware that it's arguments are in an array.

<?php
// Prints "hello mutated world"
function mutator($args=null) {
$n=count($args);
while($i<$n) $args[$i++] = "mutated";
}
$a = "hello";
$b = "strange";
$c = "world";
mutator(array($a, &$b, $c));
echo "$a $b $c";
?>


Devuelve el número de argumentos pasados a la función

  • « func_get_args
  • function_exists »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Devuelve el número de argumentos pasados a la función

func_num_args

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

func_num_args — Devuelve el número de argumentos pasados a la función

Descripción

func_num_args ( ) : int

Obtiene el número de argumentos pasados a la función.

Esta función se puede usar junto con func_get_arg() y func_get_args() para permitir a las funciones definidas por el usuario aceptar listas de argumentos de longitud variable.

Valores devueltos

Devuelve el número de argumentos pasados a la función actual definida por el usuario.

Historial de cambios

Versión | Descripción
5.3.0 | Esta función ahora se puede usar en listas de parámetros.
5.3.0 | Si esta función es llamada desde el ámbito último de un fichero que ha sido incluido mediante una llamada a include o require desde dentro de una función en el fichero de llamada, ahora genera una advertencia y devuelve -1.

Errores/Excepciones

Genera una advertencia si se llama desde fuera de una función definida por el usuario.

Ejemplos

Ejemplo #1 Ejemplo de func_num_args()

<?php
function foo()
{
    $númargs = func_num_args();
    echo "Número de argumentos: $númargs\n";
}

foo(1, 2, 3);
?>

El resultado del ejemplo sería:

Número de argumentos: 3

Ejemplo #2 Ejemplo de func_num_args() antes y después de PHP 5.3

prueba.php
<?php
function foo() {
    include './fna.php';
}

foo('Primer argumento', 'Segundo argumento');
?>

fna.php
<?php

$núm_args = func_num_args();
var_export($núm_args);

?>

Salida antes de PHP 5.3:

2

La salida en PHP 5.3 y posterior será algo similar a:

Warning: func_num_args():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fna.inc on line 3
-1

Notas

Nota:

Como esta función depende del ámbito actual para determinar los detalles del parámetro, no puede ser usada como parámetro de función en versiones anteriores a 5.3.0. Si se require pasar el valor, los resultados deben ser asignados a una variable y esta variable debería pasarse como parámetro.

Ver también

  • La sintaxis ... en PHP 5.6+
  • func_get_arg()
  • func_get_args()
  • ReflectionFunctionAbstract::getNumberOfParameters()

User Contributed Notes

tongcheong77 at gmail dot com 20-Jun-2017 06:12
If you are using PHP 7 and func_num_args is in your base class which you extended, you can pass your arguments with the 'spat' operator.

class Sql {

public function doGetWhere(...$args) {

$num_args = func_num_args();
      $args_list = func_get_args();

      echo '<pre>';
      var_dump($args_list);
      echo '<pre>';
  }
}

class Member extends Sql {

public function getWhere(...$args) {

   $this->doGetWhere(...$args);

      }
}

$member = new Member();
$member->getWhere('first_name','last_name','userlevel','email','where','email','=',$sub_email);

However, take note that if you 'new up' the 'Sql' class in your 'Member' class above, instead of extending it, you will not need to pass your arguments as a variable. Just my two cents. -Bruce tong
luisguillermo dot quevedovelez at gmail dot com 13-Mar-2012 07:32
I had defined a function function_name(){ ...} as a drupal callback.
I try to get how many params where passed

I got a Error and my Site falls down

I've replaced func_get_args() instead func_num_args() and my Site was restored.

I conclude you can not use  func_num_args() in callbacks.

Hope it helps.
Dennis Robinson from basnetworks dot net 29-Jun-2009 09:29
This function comes in handy, and I believe is the only solution, when you have an optional parameter that can take any type of data.

For example:

<?php

// $data can be of any type, including null
function my_function($name, $data = null)
{
    if ($data !== null)
    {
        // Do something with $data
        // If you call my_function('something'), this WILL NOT be reached
        // If you call my_function('something', null), this WILL NOT be reached
    }
}

?>

The problem with the above function is that you will never be able to use null as the value for $data.  To fix this, use func_num_args() like so:

<?php

// $data can be of any type, including null
function my_function($name, $data = null)
{
    if (func_num_args() >= 2)
    {
        // Do something with $data
        // If you call my_function('something'), this WILL NOT be reached
        // If you call my_function('something', null), this WILL be reached
    }
}

?>

This solution works because func_num_args() reports exactly how many arguments were passed when the function was called.  It does not take into account when default argument values are used.
jared at ws-db dot com 06-Sep-2005 09:46
Just a note for anyone wondering. This function doesn't include params that have a default value, unless you pass one in to overwrite the default param value. Not sure if that makes sense, so here's an example:

<?php
function helloWorld($ArgA, $ArgB="HelloWorld!") {
  return func_num_args();
}

// The following will return 1
$Returns1 = helloWorld("HelloWorld!");

// The following will return 2
$Returns2 = helloWorld("HelloWorld!", "HowdyWorld!");
?>
andy at arakka dot co dot th 11-May-2005 07:16
func_num_args() can be used in conjunction with named arguments, also. For example:

<?php
function DebugShow( $label, $value ) {
  echo "# " . $label ;
  if ( func_num_args() > 1 ) echo " = " . $value ;
  echo "<br>";
}
?>
ashley at dcs dot warwick dot ac dot uk 17-Apr-2002 04:40
If you want to pass the parameters on intact to another function, use func_get_args and call_user_func_array (careful - this one is only available in recent PHP versions).  For example:

<?php
/* Print an HTML tag.  This accepts a variable number of arguments:
   the first should be the name of the tag, followed by pairs of
   arguments that describe keys and values.  The values are printed
   with surrounding double quote characters.  */
function printTag() {
  $numArgs = func_num_args();
  if ($numArgs < 1) die("printTag given no arguments");

  echo "<" . func_get_arg(0);
  for ($i = 1; $i < $numArgs; $i+=2) {
    echo " " . func_get_arg($i);
    if ($i+1 < $numArgs)
      echo "=\"" . func_get_arg($i+1) . "\"";
  }
  echo ">";

}

/* Print an HTML tag with a newline on the end */
function printTagNL() {
  $args = func_get_args();
  call_user_func_array("printTag", $args);
  echo "\n";
}

printTagNL("input", "type", "hidden", "name", "SORTORDER", "value", $columnNo);
?>
thalis at NOSPAMcs dot pitt dot edu 29-Mar-2002 12:05
The idea of func_get_args() is to construct functions of variable number of parameters like

<?php
function var_param_func(){
    if(func_num_args()==0){
        //do one thing
    }
    if(func_num_args()==1)
        //do another thing
        //get the args with func_get_args()
    }
}
?>


Devuelve true si la función dada ha sido definida

  • « func_num_args
  • get_defined_functions »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Devuelve true si la función dada ha sido definida

function_exists

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

function_exists — Devuelve true si la función dada ha sido definida

Descripción

function_exists ( string $function_name ) : bool

Comprueba la lista de funciones definidas, las incluidas (internas) y las definidas por el usuario, para function_name.

Parámetros

function_name

El nombre de la función, como cadena.

Valores devueltos

Devuelve true si function_name existe y es una función, si no, false.

Nota:

Esta función devolverá false para construcciones, tales como include_once y echo.

Ejemplos

Ejemplo #1 Ejemplo de function_exists()

<?php
if (function_exists('imap_open')) {
    echo "Las funciones de IMAP están disponibles.<br />\n";
} else {
    echo "Las funciones de IMAP no están disponibles.<br />\n";
}
?>

Notas

Nota:

Un nombre de función puede existir incluso si la función misma no es utilizabla a causa de las opciones de configuración o de compilación (siendo un ejemplo las funciones de image).

Ver también

  • method_exists() - Comprueba si existe un método de una clase
  • is_callable() - Verificar que los contenidos de una variable puedan ser llamados como una función
  • get_defined_functions() - Devuelve un array de todas las funciones definidas
  • class_exists() - Verifica si la clase ha sido definida
  • extension_loaded() - Encontrar si una extensión está cargada

User Contributed Notes

ayyappan dot ashok at gmail dot com 31-Mar-2016 10:03
PHP supports nested function based on certain criteria.

Please look over the code.

function Media(){ }

function Audio()
{
    echo "Plugged Audo 5.1:<br/>";
    function Volume()
    {
    echo "Volume controls:<br/>";
    function Equalizer()
    {
        echo "Equalize Bands:<br/>";
    }
   }
}
//Call to nested functions
Audio();
Volume();
Equalizer();

if(function_exists('Volume')):
echo "TRUE";
else:
echo "FALSE";
endif;

Case 1:  //Result :Works Well
--------
Audio();
Volume();
Equalizer();

Case 2:  //Results Notice Error. Root function Audio must be called first.
--------
Volume();

Case 3:  //Results Error. Root function Volume must be called.
--------
Audio();
Equalizer();

Note :
The nested function should be called based on their order used.
In our example when Audio is not called and instantly when we try to call Volume puts under error.

Even though there is an possibility to use nested functions in PHP. It looks overhead to do so. Better to avoid in logical ground of script.

Tested on PHP 5.5.32
michael at squiloople dot com 01-Sep-2015 08:28
It should be noted that the function_exists check is not relative to the root namespace. This means that the namespace should be appended to the check:

<?php

  namespace test;

  if (!function_exists(__NAMESPACE__ . '\example'))
  {

    function example()
    {

    }

  }

?>
BruceB 21-Aug-2015 03:55
This is not going to go down as you might expect it should (even if you play smart and require/include_once):

<?php
if(function_exists('my_function'))
{
   throw new Exception("'my_function' is already defined!");
}

function my_function()
{
   // Do the work here
}
?>

This, however does work:

<?php
if( ! function_exists('my_function'))
{
   function my_function()
   {
      // Do the work here
   }
}
else
{
   throw new Exception("'my_function' is already defined!");
}
?>

Does it have anything to do with PHP parse/execute phases or global/local scope or those curly brackets or something else, I have no idea, but the latter ugly son works, while the former bombs out claiming that 'my_function' is already defined.

Thought this might save someone a few minutes of debugging time...
b dot g dot dariush at gmail dot com 07-Feb-2014 05:50
function_exists() does not cache its query internally.

by executing the following code

        $funcs = \array_shift(\get_defined_functions());
        $l = new \core\utiles\loadTime;
        $times = 0;
        $l->start();
        for($index = 0; $index<count($funcs); $index++)
        {
            foreach($funcs as $func)
            {
                $times++;
                if(\function_exists($func)) ;
            }
        }
        $s = $l->stop();
        echo "<span style='color:green'>$times</span> took : $s";
        # the output would be
         $> 2365444 took : 0.70324

By executing the

        $funcs = \array_shift(\get_defined_functions());
        $l = new \core\utiles\loadTime;
        $times = 0;
        $l->start();
        static $func_check = array();
        for($index = 0; $index<count($funcs); $index++)
        {
            foreach($funcs as $func)
            {
                $times++;
                if(!isset($func_check[$func]))
                {
                    if(\function_exists($func)) ;
                    $func_check[$func] = 1;
                }
                else $func_check[$func];
            }
        }
        $s = $l->stop();
        echo "<span style='color:green'>$times</span> took : $s";
        # the output would be
        $> 2365444 took : 0.53446

There is a 0.16878 seconds improvement, when you use static array to cache methods existence.
kitchin 25-Sep-2012 12:49
You can use this function to conditionally define functions, see: http://php.net/manual/en/functions.user-defined.php

For instance Wordpress uses it to make functions "pluggable." If a plugin has already defined a pluggable function, then the WP code knows not to try to redefine it.

But function_exists() will always return true unless you wrap any later function definition in a conditional clause, like if(){...}. This is a subtle matter in PHP parsing. Some examples:

<?php
if (function_exists('foo')) {
  print "foo defined\\n";
} else {
  print "foo not defined\\n";
}
function foo() {}

if (function_exists('bar')) {
  print "bar defined\\n";
} else {
  print "defining bar\\n";
  function bar() {}
}
print "calling bar\\n";
bar(); // ok to call function conditionally defined earlier

print "calling baz\\n";
baz(); // ok to call function unconditionally defined later
function baz() {}

qux(); // NOT ok to call function conditionally defined later
if (!function_exists('qux')) {
  function qux() {}
}
?>
Prints:
  foo defined
  defining bar
  calling bar
  calling baz
  PHP Fatal error: Call to undefined function qux()

Any oddities are probably due to the order in which you include/require files.
admin at gk-root dot com 22-Mar-2012 02:51
// If you want to chack if the function is enabled or disable in php.ini you can use this function:

<?php
function func_enabled($func) {
    $disabled = explode(',', ini_get('disable_functions'));
    foreach ($disabled as $disableFunction) {
        $is_disabled[] = trim($disableFunction);
    }
    if (in_array($func,$is_disabled)) {
        $it_is_disabled["m"] = $func.'() has been disabled for security reasons in php.ini';
        $it_is_disabled["s"] = 0;
    } else {
        $it_is_disabled["m"] = $func.'() is allow to use';
        $it_is_disabled["s"] = 1;
    }
    return $it_is_disabled;
}
?>

// An example of how to use:

<?php
$if_is_disabled = func_enabled('exec'); // return Arrey
echo $if_is_disabled["m"]; // return text value
echo '<br/>';
echo $if_is_disabled["s"]; // return 1 or 0
?>
zach at bygeekz dot com 20-Sep-2008 06:20
to php at fluidthoughts dot com

you aren't comparing against false, that if compares against true, so it's going to return that, as false != true
true being 1, True, (bool)True, etc.
false being 0, False, Null, etc
<?php

$foo=null;
if ($foo) { echo 'yay'; } //does not echo yay, because null is not True

$foo=false;
if ($foo) { echo 'yay'; } //does not echo yay, because false is not True

$foo=null;
if (!$foo) { echo 'yay'; } //echoes yay!

$foo=false;
if (!$foo) { echo 'yay'; } //echoes yay!

?>

This..
<?php
    if (!function_exists('')) {
                echo "empty string function doesnt exist as compared as negative\n";
        }

        if (!function_exists(NULL)) {
                echo "NULL function doesnt exist as compared as negative\n";
        }
?>
Works.

Alternatively, to enter upon existance..

Use your code. Since they dont exist, it wont enter..
php at fluidthoughts dot com 19-Mar-2008 10:18
function_exists returns false on NULL and empty string:

<?php
        if (function_exists('')) {
                echo "empty string function exists\n";
        }

        if (function_exists(NULL)) {
                echo "NULL function exists\n";
        }
?>

Neither of the echo statements happen when I run this.
webmaster at mamo-net dot de 22-Sep-2007 05:43
If you use suhosin.executor.func.blacklist instead of disabled_functions in your php.ini, function_exists will return true for a disabled function. I used this to have the same beahviour with suhosin.executor.func.blacklist and disabled_functions:

<?php
function suhosin_function_exists($func) {
    if (extension_loaded('suhosin')) {
        $suhosin = @ini_get("suhosin.executor.func.blacklist");
        if (empty($suhosin) == false) {
            $suhosin = explode(',', $suhosin);
            $suhosin = array_map('trim', $suhosin);
            $suhosin = array_map('strtolower', $suhosin);
            return (function_exists($func) == true && array_search($func, $suhosin) === false);
        }
    }
    return function_exists($func);
}
?>
White-Gandalf 13-Sep-2007 07:26
I stumbled over the same problem as "eddiec" (users not able or not willing to use "_once"-suffixes).

A possible alternative explanation for the behavior:

If a file is included, it is possibly parsed every include-time.(?)
While parsing, every function in global scope is tried to register. THIS gets wrong, when multiple times included, and it produces an error.

If functions are defined within block scopes, their registration seems to be delayed until execution of such a block. Thus, not the function "function_exists" functions wrong, but simply the philosophy of the interpreter produces such results.

Thus, the same effect can be achieved by simply putting block braces around the contents of an include_once file:

if (function_exists('function_in_question')) return;
{
    function function_in_question(...)
    {
        ...
    }
    ...other stuff
}

...which is equivalent to...

if (!function_exists('function_in_question'))
{
    function function_in_question(...)
    {
        ...
    }
    ...other stuff
}
dieter at edarta dot be 16-Feb-2007 03:09
to brooklynphil at hotmail dot com:

Your post is misleading, namely the 3rd and last speedtest you describe is an unfair comparison:

<?php
is_callable('test','test');
?>

The value of the 2nd parameter $syntax_only is 'test' and this evaluates to boolean true. In other words, this is exactly the same as calling the function like this:

<?php
is_callable('test',true);
?>

Of course this will be faster because is_callable only does a very basic syntaxcheck. From the documentation: 'It will only reject simple variables that are not strings, or an array that does not have a valid structure to be used as a callback.'

If you omit this erroneous 3rd test, then according to your examples function_exists is 2 to 4 times faster.

I hope you can see that loop-testing functions is not so simple. :)

rtfm
eddiec at stararcher dot com 09-Feb-2007 09:58
Note that function_exists will return TRUE in the following situation, presumably because the function "testfunc" was defined when the script was PARSED/ITERPRETED, before the function_exists call was made at RUNTIME:

<?php
if (function_exists('testfunc')) return;
function testfunc() { }
?>

So, this construction is not useful for preventing testfunc from being multiply defined if the script is muliply included or required.

However, the following construction DOES work to prevent multiple defines of testfunc:

<?php
if (!function_exists('testfunc')) {
  function testfunc() { }
}
?>

CONTRAST this with similar uses of defined() which is completely runtime evaluated.  These both work:

<?php
if (defined('testfunc_defined')) return;
define('testfunc_defined', 1);
function testfunc() { }
?>

AND...

<?php
if (!defined('testfunc_defined')) {
define('testfunc_defined', 1);
function testfunc() { }
}
brooklynphil at hotmail dot com 30-Jan-2007 11:02
to bob at thethirdshift dot net
regarding is_callable vs function_exists.

using your code
is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0443360805511 seconds
Did 10000 function_exists in 0.0111110210419 seconds

then we replace
is_callable(array('test','test'));
with
$callarray = array('test','test'); // place this outside for-loop
is_callable($callarray);

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0314660072327 seconds
Did 10000 function_exists in 0.0120670795441 seconds

then we replace
is_callable(array('test','test'));
with
is_callable('test','test');

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.00991606712341 seconds
Did 10000 function_exists in 0.0113790035248 seconds

I hope you can see that loop-testing functions is not so simple. :)
Dan 17-Jul-2006 08:49
I would like to comment on the following post:

A note of caution: function_exists() appears to be case-insensitive (at least as of PHP 4.3.8).  e.g.:

<?php
   function MyCasedFunction() {
       return true;
   }

   // Will return true, even though casing is "wrong"
   if (function_exists("mYcAsEdFuNcTiOn"))
       echo "I see it!";
?>

I believe that function calls itself are case insensitve, so this function is returning a valid truth. PHP doesn't care about cases.
andi at splitbrain dot org 07-Jul-2006 03:48
function_exists will return false for functions disabled with the disable_functions ini directive. However those functions are still declared so trying to define them yourself will fail.

<?php
if(!function_exists('readfile')){
  function readfile($file){
    $handle=@fopen($cache,"r");
    echo @fread($handle,filesize($file));
    @fclose($handle);
  }
}
?>

The above will issue a "Cannot redeclare readfile()" fatal error if readfile was disabled with disable_functions.
neelam_ab2003 at yahoo dot co dot in 11-May-2006 12:06
<?php
/*PHP doesn't Support nested functions. I have tried following in PHP_VERSION - 5.1.2*/

function A(){}

function B(){
    function C(){
        function D(){}
    }
}

IsFunctionExist('A');
IsFunctionExist('B');
IsFunctionExist('C');
IsFunctionExist('D');

function IsFunctionExist($funcName){
    echo function_exists($funcName)?" $funcName exist <br>":" $funcName doesn't exist <br>";
}
?>

/*O U T P U T
A exist
B exist
C doesn't exist
D doesn't exist
*/
chaumo 16-Jul-2005 05:46
to avoid direct calls this can be better than function_exists
in the parent file:
<?php
define("IN_MODULE",true);
?>
and in the target file:
<?php
if(!defined("IN_MODULE")) die("Can't access the file directly");
?>
fili at fili dot nl 08-Jun-2005 09:24
To prevent direct calls to included files i use the following technique.

In the main file create an empty function with a random name. Like so:

<?php
function hjudejdjiwe() { return true; }
?>

Then check for the existence of this function within your include:

<?php
if (!function_exists('hjudejdjiwe')) { die('!'); }
?>

Simple but effective.
bob at thethirdshift dot net 23-Jun-2004 09:55
I, too, was wondering whether is_callable or function exists is faster when checking class methods.  So, I setup the following test:

<?php
function doTimes($start, $end)
  {
    $start_time = explode (" ", $start);
    $start_time = $start_time[1] + $start_time[0];
    $end_time = explode (" ", $end);
    $end_time = $end_time[1] + $end_time[0];
    $time = $end_time - $start_time;
    return $time;
  }

class test
  {
      function test()
      {
          return true;
      }
  }

$callableIsTrue = false;
$startIsCallable = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(is_callable(array('test', 'test'))) { $callableIsTrue = true; }
  }
$endIsCallable = microtime();

$existsIsTrue = false;
$startExists = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(function_exists('test::test')) { $existsIsTrue = true; }
  }
$endExists = microtime();

$timeIsCallable = doTimes($startIsCallable, $endIsCallable);
$timeExists     = doTimes($startExists, $endExists);

echo "<b>is_callable = ".($callableIsTrue ? "TRUE" : "FALSE")."</b>, \n";
echo "<b>function_exists = ".($existsIsTrue ? "TRUE" : "FALSE")."</b><br>\n";

echo "<br>Did 10000 is_callables in ".$timeIsCallable." seconds";
echo "<br>Did 10000 function_exists in ".$timeExists." seconds";
?>

This gives the output :

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0640790462494 seconds
Did 10000 function_exists in 0.0304429531097 seconds

So the fact that function_exists is twice as fast is slightly over shadowed by the fact that it doesn't work on class methods, at least not as far as I can tell.
ckrack at i-z dot de 09-Mar-2004 12:22
i was wondering whether is_callable or function exists is faster when checking class methods.

is_callable(array('foo', 'bar'));
function_exists('foo::bar');

my results when doing each operation 10000 times with a simple test class were the following:

is_callable: 0.28671383857727 seconds
function_exists: 0.14569997787476 seconds

(following tests have proved this to be true).

thus you can see, function_exists is twice as fast as is_callable.
breadman 29-Jul-2003 05:17
Functions within a function are better off as anonymous returns from create_function(), unless you want to be able to call it elsewhere.

However, I have used this in skinning:  I use alert_box() to display certain errors, like a faulty SQL query.  This simply calls display_alert(), which is defined in my skin scripts.  However, alert_box() is sometimes called before I know which skin to load, so it has its own functionality which it uses if function_exists('display_alert') returns false.
dshearin at excite dot com 08-Jul-2003 03:15
This can be used to conditionally define a user function. In this sense, it can act as a sort of inline include_once().

For example, suppose you have a function A that calls function B. B is only used inside function A and is never called from anywhere else in the script. It's logical (and perfectly legal in PHP) to define B inside of A's definition, like so:

<?php
function A($inputArray)
{
   if (!function_exists('B'))
   {
      function B($item)
      {
           // Do something with $item
         // and return result
          return $result;
      }
   }
   foreach ($inputArray as $nextItem) $outputArray[] = B($nextItem);
   return $outputArray;
}
?>

Without the function_exists test, you would get a fatal error the second time you called A, as PHP would think you were trying to redefine B (not legal in PHP). The placement of the test is also important. Since the if block is executed sequentially, like any other block of code, it must come before any call to the function defined within.


Devuelve un array de todas las funciones definidas

  • « function_exists
  • register_shutdown_function »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Devuelve un array de todas las funciones definidas

get_defined_functions

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

get_defined_functions — Devuelve un array de todas las funciones definidas

Descripción

get_defined_functions ( bool $exclude_disabled = false ) : array

Obtiene un array de todas las funciones definidas.

Parámetros

exclude_disabled

Si deberían excluirse las funciones inhabilitadas del valor devuelto.

Valores devueltos

Devuelve un array multidimensional que contiene una lista de todas las funciones definidas, tanto de las incluidas (internas) como las definidas por el usuario. Las funciones internas serán accesibles mediante $arr["internal"], y las definidas por el usuario usando $arr["user"] (véase el ejemplo de abajo).

Historial de cambios

Versión | Descripción
PHP 7.0.15, PHP 7.1.1 | Se ha añadido el parámetro exclude_disabled.

Ejemplos

Ejemplo #1 Ejemplo de get_defined_functions()

<?php
function mifila($id, $data)
{
    return "<tr><th>$id</th><td>$data</td></tr>\n";
}

$arr = get_defined_functions();

print_r($arr);
?>

El resultado del ejemplo sería algo similar a:

Array
(
    [internal] => Array
        (
            [0] => zend_version
            [1] => func_num_args
            [2] => func_get_arg
            [3] => func_get_args
            [4] => strlen
            [5] => strcmp
            [6] => strncmp
            ...
            [750] => bcscale
            [751] => bccomp
        )

    [user] => Array
        (
            [0] => mifila
        )

)

Ver también

  • function_exists() - Devuelve true si la función dada ha sido definida
  • get_defined_vars() - Devuelve una matriz con todas las variables definidas
  • get_defined_constants() - Devuelve un array asociativo con los nombres de todas las constantes y sus valores
  • get_declared_classes() - Devuelve una matriz con los nombres de las clases definidas

User Contributed Notes

Muneeb Aslam 27-Oct-2015 12:30
This is rather a simple non-confusing script to get the function names linked to its manual page on php.net. Hope it helps someone. Commented script is self explainatory

<?php

    /*declare a variable to php manual of functions.
    change the $lng to the region you want it for,
    i-e en/es/de etc etc */
    $lng = "es";
    $url = "http://www.php.net/manual/".$lng."/function.";

    // get defined functions in a variable (it will be a 2D array)
    $functions = get_defined_functions();

    // Run nested foreach to get the function names
    foreach($functions as $function){
        foreach ($function as $functionName){

            /* Since php manual is using hyphens instead of underscores
            for functions, we will convert underscores to hyphen whereever
            there is one. */
            if(strpos($functionName,"_") !== false){
                $functionForURL = str_replace("_","-",$functionName);
            } else {
                $functionForURL = $functionName;
            }

            /* echo the link */
            echo "<a href='".$url.$functionForURL.".php'>".$functionName."</a><br />";
        }
    }

?>
Muneeb Aslam 26-Oct-2015 07:46
We can also get the function names with this simple foreach

<?php

    //Since its a two dimensional array
    $functions = get_defined_functions();

    //We can use nested foreach to get the function names
    foreach($functions as $function){
         foreach($function as $thisFunc){
             echo $thisFunc . "<br />";
         }
     }

?>
kkuczok at gmail dot com 22-May-2013 08:14
You can list all arguments using ReflectionFunction class. It's not necessary to parse selected files/files as suggested by Nguyet.Duc.

http://php.net/manual/pl/class.reflectionfunction.php

Example:
<?php
function foo(&$bar, $big, $small = 1) {}
function bar($foo) {}
function noparams() {}
function byrefandopt(&$the = 'one') {}

$functions = get_defined_functions();
$functions_list = array();
foreach ($functions['user'] as $func) {
        $f = new ReflectionFunction($func);
        $args = array();
        foreach ($f->getParameters() as $param) {
                $tmparg = '';
                if ($param->isPassedByReference()) $tmparg = '&';
                if ($param->isOptional()) {
                        $tmparg = '[' . $tmparg . '$' . $param->getName() . ' = ' . $param->getDefaultValue() . ']';
                } else {
                        $tmparg.= '&' . $param->getName();
                }
                $args[] = $tmparg;
                unset ($tmparg);
        }
        $functions_list[] = 'function ' . $func . ' ( ' . implode(', ', $args) . ' )' . PHP_EOL;
}
print_r($functions_list);
?>

Output:
Array
(
    [0] => function foo ( &&bar, &big, [$small = 1] )

    [1] => function bar ( &foo )

    [2] => function noparams (  )

    [3] => function byrefandopt ( [&$the = one] )

)
Nguyet.Duc 30-Jul-2011 01:22
get_defined_functions() just returns a list of function names without function arguments. Here is the code to list user-defined function names plus arguments:

<?php
    $content = file_get_contents('example.php');
    preg_match_all("/(function )(\S*\(\S*\))/", $content, $matches);
    foreach($matches[2] as $match) {
        $function[] = "// " . trim($match) . "<br />\n";
    }
    natcasesort($function);
    $functionlist .= "/* Functions in this file */<br />\n";
    $functionlist .= "/**************************/<br />\n\n";
    $functionlist .= implode('', $function);
    echo $functionlist;
?>

Output:

/* Functions in this file */
/**************************/
// add_data($data)
// add_files($list)
// archive($name)
// bzip_file($name)
rob at webdimension dot co dot uk 01-Apr-2011 08:48
A quick way of using this function:

<?php
// ALL USER DEFINED FUNCTIONS
$arr = get_defined_functions();
foreach ($arr['user'] as $key => $value){
echo $value.'<br />';
}
// ALL USER DEFINED FUNCTIONS

// ALL INTERNAL FUNCTIONS
$arr = get_defined_functions();
foreach ($arr['internal'] as $key => $value){
echo $value.'<br />';
}
// ALL INTERNAL FUNCTIONS
?>
ChaosKaizer 10-Jul-2008 07:13
for user defined function

<?php
/**
 * @param string $function_name The user function name, as a string.
 * @return Returns TRUE if function_name  exists and is a function, FALSE otherwise.
 */
function user_func_exists($function_name = 'do_action') {

    $func = get_defined_functions();

    $user_func = array_flip($func['user']);

    unset($func);

    return ( isset($user_func[$function_name]) );
}
?>
strrev xc.noxeh@ellij 04-Jun-2008 05:31
Please note that functions created with create_function() are not returned.
(However that might change in a later version)
spudinski at gmail dot com 01-Apr-2008 06:13
To search for a function.
<html>
<head>
<title>List of all Internal functions</title>
<style type="text/css">
body {
    background-color: #FFFFFF;
    color: #222222;
    font-size: 11px;
    font-family: arial, tahoma;
}
table {
    color: #222222;
    font-size: 11px;
    font-family: arial, tahoma;
}
tr.found {
    background-color: #66EE00;
    font-weight: bold;
}
a:link {
    color: #222222;
}
a:visited {
    color: #CCCCCC;
}
a:active {
    color: #444444;
}
a:hover {
    text-decoration: underline;
}
</style>
</head>
<body>
<p>
    <form method="GET">
    Search: <input type="text" name="search"><br>
    <input type="submit">
    </form>
</p>
<?php
    if (!empty($_GET['search'])) {
        echo '<p>' . '<a href="#' . $_GET['search'] . '">' .
        'Goto ' . $_GET['search'] . '</a>' .
        '<script type="text/javascript">
            window.onload = function() {
                document.location += "#' . $_GET['search'] . '";
                return true;
            }
        </script>
        </p>';
    }
?>
<p>
    <table>
<?php
    $country = 'us';
    $functions = get_defined_functions();
    $functions = $functions['internal'];
    $num = 0;
    foreach($functions as $function) {
        $num++;
        echo '<tr ' . (($_GET['search'] == $function) ? 'class="found"' : '') . '><td>' .
        number_format($num) . '</td><td>' . '<a name="' . $function . '" href="http://' . $country . '.php.net/' .
        $function . '">' . $function . '</a>' . '</td></tr>';
    }
?>
    </table>
</p>
</body>
</html>
berchentreff at berchentreff dot de 31-Mar-2006 05:46
look at here, list all the defined function on your php-Version and give as well formatted output width links onto the php-manual:

<html><head>
<style type="text/css"><!--
li{font-family:Verdana,Arail,sans-serif;width:500px;margin-top:7px;}
a{padding:4px;}
a.a1{font-size:12px;background-color:#CCCCCC;color:#663300;}
a.a1:hover{background-color:#663300;color:#CCCCCC;}
a.a1:visited{background-color:#fff;color:#999;}
a.a1:visited:hover{background-color:#fff;color:#999;}
a.a0{font-size:12px;background-color:#CCCCFF;color:#663399;}
a.a0:hover{background-color:#663399;color:#CCCCFF;}
a.a0:visited{background-color:#ffC;color:#999;}
a.a0:visited:hover{background-color:#ffC;color:#999;}
--></style>
</head><body style="background-color:#999;">
<?php
$arr = get_defined_functions();

foreach($arr as $zeile){
sort($zeile);$s=0;
foreach($zeile as $bzeile){
$s=($s)?0:1;
echo "<li><a class='a".$s."'  href='http://de.php.net/".$bzeile."'>".$bzeile."</a></li>";}
}
?>
</body>
</html>
mIHATESPAMduskis at bates dot edu 21-Nov-2002 02:47
At least with PHP 4.2.3 on a GNU/Linux/Apache platform, get_defined_functions() returns user-defined functions as all-lower case strings regardless of how the functions are capitalized when they are defined.

Threw me for a loop.
peten at spam dot me dot not dot frontiernet dot net 02-Jun-2002 10:28
Here's a useful trick with the get_defined_functions function - show all available functions with a link to the documentation (you can even change the mirror it goes to):

<?php
  // the php mirror
  $php_host = "http://us2.php.net/";

  // the number of cols in our table
  $num_cols = 3;

  $ar = get_defined_functions();
  $int_funct = $ar[internal];
  sort($int_funct);
  $count = count($int_funct);
?>
<html>
 <head>
  <title>
   Available PHP Functions
  </title>
 </head>
 <body>
  <p>
   <?php print $count; ?> functions
    available on
    <?php
      print $_SERVER[SERVER_NAME];
     ?>
   (<a href="<?php print $php_host;?>"
    target="phpwin">php</a>
    version
    <?php print phpversion(); ?>)
  </p>
  <table align="center" border="2">
   <tr>
<?php
  for($i=0;$i<$count;$i++) {
    $doc = $php_host
     . "manual/en/function."
     . strtr($int_funct[$i], "_", "-")
     . ".php";
    print "    <td><a href=\"" . $doc
     . "\" target=\"phpwin\">"
     . $int_funct[$i]
     . "</a></td>\n";
    if(($i > 1)
     && (($i+$num_cols)%$num_cols==($num_cols-1)))
      print "   </tr>\n   <tr>\n";
    }
  for($i=($num_cols-($count%$num_cols));$i>0;$i--)
    print "    <td>&nbsp;</td>\n";
?>
  </table>
 </body>
</html>


Registrar una función para que sea ejecutada al cierre

  • « get_defined_functions
  • register_tick_function »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Registrar una función para que sea ejecutada al cierre

register_shutdown_function

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

register_shutdown_function — Registrar una función para que sea ejecutada al cierre

Descripción

register_shutdown_function ( callable $callback , mixed $parameter = ? , mixed $... = ? ) : void

Registra una llamada de retorno dada por callback para ser ejecutada después de que finalice la ejecución del script o se llame a exit().

Se pueden hacer múltiples llamadas a register_shutdown_function(), y cada una será llamada en el mismo orden en el que fueron registradas. Si se llama a exit() dentro de una función de cierre registrada, el procesamiento se detendrá completamente y no se llamarán a otras funciones de cierre registradas.

Parámetros

callback

La llamada de retorno de cierre a registrar.

Las llamadas de retorno de cierre se ejecutan como parte de una petición, por lo que es posible enviar salidas desde ellas y acceder a los buffers de salida.

parameter

Es posible pasar parámetros a la función de cierre pasando parámetros adicionales.

...

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

Se generará un error de nivel E_WARNING si no es posible llamar a la llamada de retorno.

Ejemplos

Ejemplo #1 Ejemplo de register_shutdown_function()

<?php
function cierre()
{
    // Esta es nuestra función de cierre,
    // aquí podemos hacer las últimas operaciones
    // antes de que el script sea completado.

    echo 'Script ejecutado con éxito', PHP_EOL;
}

register_shutdown_function('cierre');
?>

Notas

Nota:

El directorio de trabajo del script se puede cambiar dentro de la función de cierre bajo algunos servidores web, p.ej. Apache.

Nota:

Las funciones de cierre no serán ejecutadas si el proceso es terminado por señales SIGTERM o SIGKILL. Pese a que no es posible interceptar una señal SIGKILL, es posible utilizar pcntl_signal() para registrar un manejador para SIGTERM que utilice exit() para terminar limpiamente.

Ver también

  • auto_append_file
  • exit() - Imprime un mensaje y termina el script actual
  • La sección sobre manejo de conexiones

User Contributed Notes

ohcc at 163 dot com 09-Jun-2020 04:06
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';
Anonymous 16-Mar-2019 10:08
warning: in addition to SIGTERM and SIGKILL, the shutdown functions won't run in response to SIGINT either. (observed on php 7.1.16 on windows 7 SP1 x64 + cygwin  and php 7.2.15 on Ubuntu 18.04)
marcelotpcruz at gmail dot com 28-Nov-2018 09:58
I elaborated following functions, so you can close your connection if you can't count on fastcgi_finish_request.

You'll use puts instead of echo, so you can close the connection whenever you want as long as you don't touch echo when you use those functions.
It works it compression and is easy to adapt:

function connsettings($name, $val=null){
    static $settings = array();

    if(!isset($settings[$name]))
        $settings[$name] = false;
    if($val !== null)
        $settings[$name] = $val;

    return $settings[$name];
};//Just saving compression and init var to check if it's true or false

function puts(){
//Using args so it works like echo with comma ands dots
    $numargs = func_num_args();
    $arg_list = func_get_args();
    $string = '';

    if($numargs === 0)
        return;
    else if($numargs > 1)
        for($i = 0; $i < $numargs; $i++)
            $string .= $arg_list[$i];
    else
        $string = $arg_list[0];

    if(connsettings('init') === false)
    {
        // buffer all upcoming output - make sure we care about compression:
        if(ob_start("ob_gzhandler"))
            connsettings('compression', true);
        else
            ob_start();

        connsettings('init', true);
        register_shutdown_function('puts', null, true);
    }
    echo $string;
}
function close(){
    if(!headers_sent())//it may work without this verification when no compression but may lead to uncomplete data
    {
        // send headers to tell the browser to close the connection
        ob_end_flush(); // Order here matter, it won't work if it goes after Content-Length
        if(connsettings('compression') === false)
            header("Content-Encoding: none");
        header('Content-Length: ' . ob_get_length());
        header('Connection: close');
        // flush all output
        //ob_end_flush();
        ob_flush();
        flush();
        // close current session
        if (session_id()) session_write_close();
        set_time_limit(0);
        ignore_user_abort(true);
    }
}
raat1979 at gmail dot com 08-Feb-2017 07:31
I wanted to set the exit code for a CLI application from a shutdown function by using a class property,

Unfortunataly (as per manual)  "If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called."

As a result if I call exit in my shutdown function I will break other shutdown functions (like one that logs fatal errors to syslog)

However! (as per manual)  "Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered."

As luck would have it you are also able to register a shutdown function from within a shutdown function (at least in PHP 7.0.15 and 5.6.30)

in other words if you register a shutdown function inside a shutdown function it is appended to the shutdown function queue.

<?php
class SomeApplication{
    private $exitCode = null;

    public function __construct(){
        register_shutdown_function(function(){
        echo "some registered shutdown function";
            register_shutdown_function(function(){
                echo "last registered shutdown function";
                // one might even consider another register shutdown_function if one expects other shutdown functions to do the same...
                exit($this->exitCode === null ? 0 : $this->exitCode);
            });
        });
    }
}
?>
xcl_rockman at qq dot com 25-Sep-2015 06:02
for static call
register_shutdown_function(function () {
                demo::shutdownFunc();
});
m dot agkopian at gmail dot com 30-Apr-2014 10:29
Use this small snippet inside your bootstrap in order to always have a way to know reliably what was the last page of your site that the user have visited, without having to use $_SERVER['HTTP_REFERER'].

<?php
session_start();

// Get current page
$current_page = htmlspecialchars($_SERVER['SCRIPT_NAME'], ENT_QUOTES, 'UTF-8');
$current_page .= $_SERVER['QUERY_STRING'] ? '?'.htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES, 'UTF-8') : '';

// Set previous page at the end
register_shutdown_function(function ($current_page) {
    $_SESSION['previous_page'] = $current_page;
}, $current_page);
?>
Tim 01-Nov-2013 04:35
register_shutdown_function seems to be immune to whatever value was set with set_time_limit or the max_execution_time value defined in php.ini.
<?php
function asdf() {
    echo microtime(true) . '<br>';
    sleep(1);
    echo microtime(true) . '<br>';
    sleep(1);
    echo microtime(true) . '<br>';
}
register_shutdown_function('asdf');
set_time_limit(1);

while(true) {}
?>
The output is three lines.
matteosistisette at gmail dot com 13-Apr-2013 05:42
In PHP 5.1.6 things don't work as described here.

The truth is that connection_status() just always returns 0 whether or not the client has aborted (e.g. the user hit the stop button), and that (consistently with this) the registered shutdown function will only be called on exit, but NOT when the connection is aborted from the user.

That is, PHP does NOT detect when the connection is aborted.
alexyam at live dot com 08-Apr-2012 03:50
When using php-fpm, fastcgi_finish_request() should be used instead of register_shutdown_function() and exit()

For example, under nginx and php-fpm 5.3+, this will make browsers wait 10 seconds to show output:

<?php
    echo "You have to wait 10 seconds to see this.<br>";
    register_shutdown_function('shutdown');
    exit;
    function shutdown(){
        sleep(10);
        echo "Because exit() doesn't terminate php-fpm calls immediately.<br>";
    }
?>

This doesn't:

<?php
    echo "You can see this from the browser immediately.<br>";
    fastcgi_finish_request();
    sleep(10);
    echo "You can't see this form the browser.";
?>
david dot schueler at tel-billig dot de 11-Nov-2010 04:51
I had a problem when forking a child process and accessing the variables by using the "global" keyword in the shutdown function.
So i used another way for getting the variables to the shutdown function: I passed them by reference.

Example:
<?php
function shutdown_function (&$test) {
    echo __FUNCTION__.'(): $test = '.$test."\n";
}

$test = 1;
register_shutdown_function('shutdown_function', &$test);
echo '$test = '.$test."\n";

// do some stuff and change the variable values
$test = 2;

// now the shutdown function gets called
exit(0);
?>

Maybe tis helps someone. (I'm using PHP 5.2.11)
emanueledelgrande ad email dot it 19-Sep-2010 07:53
A lot of useful services may be delegated to this useful trigger.
It is very effective because it is executed at the end of the script but before any object destruction, so all instantiations are still alive.

Here's a simple shutdown events manager class which allows to manage either functions or static/dynamic methods, with an indefinite number of arguments without using any reflection, availing on a internal handling through func_get_args() and call_user_func_array() specific functions:

<?php
// managing the shutdown callback events:
class shutdownScheduler {
    private $callbacks; // array to store user callbacks

    public function __construct() {
        $this->callbacks = array();
        register_shutdown_function(array($this, 'callRegisteredShutdown'));
    }
    public function registerShutdownEvent() {
        $callback = func_get_args();

        if (empty($callback)) {
            trigger_error('No callback passed to '.__FUNCTION__.' method', E_USER_ERROR);
            return false;
        }
        if (!is_callable($callback[0])) {
            trigger_error('Invalid callback passed to the '.__FUNCTION__.' method', E_USER_ERROR);
            return false;
        }
        $this->callbacks[] = $callback;
        return true;
    }
    public function callRegisteredShutdown() {
        foreach ($this->callbacks as $arguments) {
            $callback = array_shift($arguments);
            call_user_func_array($callback, $arguments);
        }
    }
    // test methods:
    public function dynamicTest() {
        echo '_REQUEST array is '.count($_REQUEST).' elements long.<br />';
    }
    public static function staticTest() {
        echo '_SERVER array is '.count($_SERVER).' elements long.<br />';
    }
}
?>

A simple application:

<?php
// a generic function
function say($a = 'a generic greeting', $b = '') {
    echo "Saying {$a} {$b}<br />";
}

$scheduler = new shutdownScheduler();

// schedule a global scope function:
$scheduler->registerShutdownEvent('say', 'hello!');

// try to schedule a dyamic method:
$scheduler->registerShutdownEvent(array($scheduler, 'dynamicTest'));
// try with a static call:
$scheduler->registerShutdownEvent('scheduler::staticTest');

?>

It is easy to guess how to extend this example in a more complex context in which user defined functions and methods should be handled according to the priority depending on specific variables.

Hope it may help somebody.
Happy coding!
clover at fromru dot com 01-Jun-2010 02:17
If you register function that needs to be running last (for example, close database connection) - just register another shutdown function from shutdown function:
<?php
function test1(){
  register_shutdown_function('test_last');
}

function test2(){/*...*/}
function test3(){/*...*/}
function test_last(){/*...*/}

register_shutdown_function('test1');
register_shutdown_function('test2');
register_shutdown_function('test3');
?>

the script will call functions in correct order: test1, test2, test3, test_last
sander @ unity-x 12-May-2010 03:42
simple method to disconnect the client and continue processing:

<?php
function endOutput($endMessage){
    ignore_user_abort(true);
    set_time_limit(0);
    header("Connection: close");
    header("Content-Length: ".strlen($endMessage));
    echo $endMessage;
    echo str_repeat("\r\n", 10); // just to be sure
    flush();
}

// Must be called before any output
endOutput("thank you for visiting, have a nice day');

sleep(100);
mail("you@yourmail.com", "ping", "i'm here");
?>
jawsper at aximax dot nl 20-Apr-2010 05:21
Something found out during testing:

the ini auto_append_file will be included BEFORE the registered function(s) will be called.
ravenswd at gmail dot com 21-Dec-2009 01:43
You may get the idea to call debug_backtrace or debug_print_backtrace from inside a shutdown function, to trace where a fatal error occurred. Unfortunately, these functions will not work inside a shutdown function.
Ant P. 02-Oct-2009 12:13
As of PHP 5.3.0, the last note about unpredictable working directory also applies to FastCGI, when previously it didn't.
Anonymous 17-Sep-2009 05:29
Note that if the handler function is private static it will never be called! It must be public!
Filip Dalge 16-Aug-2009 08:35
The following function register_close_function should reproduce the former php behavior of closing the connection before executing the shutdown handler, based on the code posted by sts at mail dot xubion dot hu. It does not work on any machine.

<?php
function register_close_function($func) {
  register_close_function::$func = $func;
  register_shutdown_function(array("register_close_function", "close"));
  ob_start();
}
class register_close_function {
  // just a container
  static $func;
  function close() {
    header("Connection: close");
    $size = ob_get_length();
    header("Content-Length: $size");
    ob_end_flush();
    flush();
    call_user_func(register_close_function::$func);
  }
}
?>
pgl at yoyo dot org 02-Aug-2009 02:25
You definitely need to be careful about using relative paths in after the shutdown function has been called, but the current working directory doesn't (necessarily) get changed to the web server's ServerRoot - I've tested on two different servers and they both have their CWD changed to '/' (which isn't the ServerRoot).

This demonstrates the behaviour:

<?php
function echocwd() { echo 'cwd: ', getcwd(), "\n"; }

register_shutdown_function('echocwd');
echocwd() and exit;
?>

Outputs:

cwd: /path/to/my/site/docroot/test
cwd: /

NB: CLI scripts are unaffected, and keep their CWD as the directory the script was called from.
cFreed at orange dot fr 14-Mar-2009 09:36
May be obvious for most people, but I spent time to clearly understand something which is only INDIRECTLY mentioned by the manual, so I hope this useful for someones.

Pay attention to the function prototype: the $function argument is a callback one (follow the link for more information).
This means that you must write this argument differently depending on the $function context:
. function-name, as a string, when it is a built-in or user-defined function
. array(class-name, method-name), when it is an object method
SonOfTron 05-Oct-2008 06:24
You can achieve similar results by using auto_append_file in the php.ini or .htaccess file:
(php.ini)
auto_append_file = /my-auto-append-file.php
(.htaccess)
php_value auto_append_file /my-auto-append-file.php
RLK 14-Sep-2008 02:26
Contrary to the the note that "headers are always sent" and some of the comments below - You CAN use header() inside of a shutdown function as you would anywhere else; when headers_sent() is false. You can do custom fatal handling this way:

<?php
ini_set('display_errors',0);
register_shutdown_function('shutdown');

$obj = new stdClass();
$obj->method();

function shutdown()
{
  if(!is_null($e = error_get_last()))
  {
    header('content-type: text/plain');
    print "this is not html:\n\n". print_r($e,true);
  }
}
?>
Fuzika 13-Aug-2007 05:27
Sinured's example of how to use a static method did not work for me.
But this did:

<?php
register_shutdown_function(array('theClass','theStaticMethod'));
?>

Hope this helps someone.

[EDIT by danbrown AT php DOT net: This example did not work for the author of this note because it is written for PHP 5.  The author was using PHP 4.]
Sinured 10-Aug-2007 06:26
You can use a static method of a class as a shutdown function without passing an instance. I think that doesn't make too much sense, however it's possible.

<?php
register_shutdown_function('someClass::someMethod');
?>

If this method is *NOT* static, then PHP will complain about an invalid callback instead of just emitting an E_STRICT error.
buraks78 at gmail dot com 01-Jul-2007 05:51
Read the post regarding the change of working directory to ServerRoot carefully. This means that require_once "path/to/script" (or similar constructs) with relative paths will not work in shutdown functions.
Ldkronos 25-Jan-2007 09:55
It's already been discussed on the zlib page ( http://www.php.net/zlib ), but hasn't been mention here...

When zlib compression is enabled, register_shutdown_function doesn't work properly. Anything output from your shutdown function will not be readable by the browser. Firefox just ignores it. IE6 will show you a blank page.

The workaround that worked for me is to add the following to the top of the script.
ini_set('zlib.output_compression', 0);
dweingart at pobox dot com 13-Mar-2006 08:53
I have discovered a change in behavior from PHP 5.0.4 to PHP 5.1.2 when using a shutdown function in conjunction with an output buffering callback.

In PHP 5.0.4 (and earlier versions I believe) the shutdown function is called after the output buffering callback.

In PHP 5.1.2 (not sure when the change occurred) the shutdown function is called before the output buffering callback.

Test code:
<?php
function ob_callback($buf) {
    $buf .= '<li>' . __FUNCTION__ .'</li>';
    return $buf;
}

function shutdown_func() {
    echo '<li>' . __FUNCTION__ .'</li>';
}

ob_start('ob_callback');
register_shutdown_function('shutdown_func');
echo '<ol>';
?>

PHP 5.0.4:

1. ob_callback
2. shutdown_func

PHP 5.1.2:

1. shutdown_func
2. ob_callback
me at thomaskeller dot biz 11-Mar-2006 02:27
Well, it might be obvious, but one should remember that one cannot send any HTTP header in the shutdown callback.

Something like

<?php

function redirect()
{
     header("Location: myuri.php");
}

register_shutdown_function("redirect");

// do something useful here

?>

doesn't work and PHP sends out the popular "headers already sent" warning.

I tried to set a redirection target somewhere in the script, but wanted to make sure that it was only set/executed at the very end of the script, since my custom redirect function also cleaned any output buffers at that point. Well, no luck here =)
kenneth dot kalmer at gmail dot com 27-Jan-2006 09:26
I performed two tests on the register_shutdown_function() to see under what conditions it was called, and if a can call a static method from a class. Here are the results:

<?php
/**
 * Tests the shutdown function being able to call a static methods
 */
class Shutdown
{
    public static function Method ($mixed = 0)
    {
        // we need absolute
        $ap = dirname (__FILE__);
        $mixed = time () . " - $mixed\n";
        file_put_contents ("$ap/shutdown.log", $mixed, FILE_APPEND);
    }
}
// 3. Throw an exception
register_shutdown_function (array ('Shutdown', 'Method'), 'throw');
throw new Exception ('bla bla');

// 2. Use the exit command
//register_shutdown_function (array ('Shutdown', 'Method'), 'exit');
//exit ('exiting here...')

// 1. Exit normally
//register_shutdown_function (array ('Shutdown', 'Method'));
?>

To test simply leave one of the three test lines uncommented and execute. Executing bottom-up yielded:

1138382480 - 0
1138382503 - exit
1138382564 - throw

HTH
sezer yalcin 26-Dec-2005 09:11
re:codeslinger at compsalot dot com

fork() is actually creating 2 processes from one. So there is no surprise register_shutdown_function will be executed per each process.

I think you have reported this as a bug and now in php 5.1.0 when you exit from child process, it does not execute it. Well, what are you going to do if you have something to register for forked process?

I hope php will be more stable near soon!

codeslinger at compsalot dot com
03-Feb-2005 09:22
Here is a nice little surprise to keep in mind...

If you register a shutdown function for your main program.  And then you fork() a child.

Guess What?
When the child exits it will run the code that was intended for the main program.  This can be a really bad thing  ;-)

Happily there is a simple work-around.  All you need to do is to create a global variable such as:

$IamaChild = [TRUE | FALSE];

and have your shutdown function check the value...
http://livejournal.com/~sinde1/ 02-Dec-2005 04:49
If you want to do something with files in function, that registered in register_shutdown_function(), use ABSOLUTE paths to files instead of relative. Because when script processing is complete current working directory chages to ServerRoot (see httpd.conf)
Niels Ganser <php dot comment at depoll dot de> 22-Sep-2005 07:58
Just a quick note: from 5.0.5 on objects will be unloaded _before_ your shutdown function is called which means you can't use previously initiated objects (such as mysqli).

See bug 33772 for more information.
codeslinger at compsalot dot com 03-Feb-2005 09:22
Here is a nice little surprise to keep in mind...

If you register a shutdown function for your main program.  And then you fork() a child.

Guess What?
When the child exits it will run the code that was intended for the main program.  This can be a really bad thing  ;-)

Happily there is a simple work-around.  All you need to do is to create a global variable such as:

$IamaChild = [TRUE | FALSE];

and have your shutdown function check the value...
astrolox at lawyersonline dot co dot uk 18-Mar-2004 11:57
When using the register_shutdown_function command in php 4. The registered functions are called in the order that you register them.

This is important to note if you are doing database work using classes that register shutdown functions for themselves.

You must register the shutdown_functions in the order that you want things to shutdown. ( ie the database needs to shutdown last )

Example of what will not work but what you might expect to work :

<?php
class database {

        function database() {
                echo "connect to sql server -- (database :: constructor)<br>\n";
                register_shutdown_function( array( &$this, "phpshutdown" ) );
                $this->connected = 1;
        }

        function do_sql( $sql ) {
                if ( $this->connected == 1 ) {
                        echo "performing sql -- (database :: do_sql)<br>\n";
                } else {
                        echo " ERROR -- CAN NOT PERFORM SQL -- NOT CONNECTED TO SERVER -- (database :: do_sql)<br>\n";
                }
        }

        function phpshutdown() {
                echo "close connection to sql server -- <b>(database :: shutdown)</b><br>\n";
                $this->connected = 0;
        }
}

class table {

        function table( &$database, $name ) {
                $this->database =& $database;
                $this->name = $name;
                echo "read table data using database class -- name=$this->name -- (table :: constructor)<br>\n";
                register_shutdown_function( array( &$this, "phpshutdown" ) );
                $this->database->do_sql( "read table data" );
        }

        function phpshutdown() {
                echo "save changes to database -- name=$this->name -- <b>(table :: shutdown)</b><br>\n";
                $this->database->do_sql( "save table data" );
        }
}

$db =& new database();

$shoppingcard =& new table( &$db, "cart " );
?>

Output of the above example is :-

connect to sql server -- (database :: constructor)
read table data using database class -- name=cart -- (table :: constructor)
performing sql -- (database :: do_sql)
close connection to sql server -- (database :: shutdown)
save changes to database -- name=cart -- (table :: shutdown)
ERROR -- CAN NOT PERFORM SQL -- NOT CONNECTED TO SERVER -- (database :: do_sql)
Jim Smith 15-Mar-2004 04:17
I was trying to figure out how to pass parameters to the register_shutdown_function() since you cannot register a function with parameters and passing through globals is not appropriate. E.g. what I was trying to do was  <? register_shutdown_function("anotherfunction('parameter')") ?>
Turns out, the trick is to use create_function() to create a "function" that calls the desired function with static parameters.

<?php
$funtext="mail('u@ho.com','mail test','sent after shutdown');";
register_shutdown_function(create_function('',$funtext));
?>

Here's another example showing in-line logging and a post-execution version:

Before: in-process logging

<?php
function logit($message) {
   $oF=fopen('TEST.log', 'a');
   fwrite($oF,"$message\n");
   fclose($oF);
   sleep(5);  // so you can see the delay
}
print "loging";
logit("traditional execution");
print "logged";
exit;
?>
After:

<?php
function logit($message) {
   $forlater=create_function('',"loglater('$message');");
   register_shutdown_function($forlater);
}
function loglater($message) {
   $oF=fopen('TEST.log', 'a');
   fwrite($oF,"$message\n");
   fclose($oF);
   sleep(5);  // so you can see the delay
}
print "loging";
logit("delayed execution");
print "logged";
exit;
?>

In the 'before' example, the file is written (and the delay occurs) before the "logged" appears. In the 'after' example, the file is written after execution terminates.

Maybe it would be nice to add a parameter to the register_shutdown_function that does this automatically?
sts at mail dot xubion dot hu 15-Mar-2004 02:56
If you need the old (<4.1) behavior of register_shutdown_function you can achieve the same with "Connection: close" and "Content-Length: xxxx" headers if you know the exact size of the sent data (which can be easily caught with output buffering).
An example:
<?php
header("Connection: close");
ob_start();
phpinfo();
$size=ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
sleep(13);
error_log("do something in the background");
?>

The same will work with registered functions.
According to http spec, browsers should close the connection when they got the amount of data specified in Content-Length header. At least it works fine for me in IE6 and Opera7.
James Wyse (James [at] tastyspoon.com) 12-Feb-2004 08:49
Just a note to say that if your function uses paths relative to the script you are running (ie. for reading files, "../dir/" etc) then your function may not work correctly when registered as a shutdown function. I'm not sure where the 'working dir' IS when running a shutdown function but I find it best to use absolute paths ("/home/www/dir/").
phpmanual at NO_SPHAMnetebb dot com 15-Nov-2003 08:31
Given this code:

<?php
class CallbackClass {
    function CallbackFunction() {
        // refers to $this
    }

    function StaticFunction() {
        // doesn't refer to $this
    }
}

function NonClassFunction() {
}
?>

there appear to be 3 ways to set a callback function in PHP (using register_shutdown_function() as an example):

1: register_shutdown_function('NonClassFunction');

2: register_shutdown_function(array('CallbackClass', 'StaticFunction'));

3: $o =& new CallbackClass();
   register_shutdown_function(array($o, 'CallbackFunction'));

The following may also prove useful:

<?php
class CallbackClass {
    function CallbackClass() {
        register_shutdown_function(array(&$this, 'CallbackFunction')); // the & is important
    }

    function CallbackFunction() {
        // refers to $this
    }
}
?>
jules at sitepointAASASZZ dot com 01-Jul-2003 12:41
If your script exceeds the maximum execution time, and terminates thusly:

Fatal error: Maximum execution time of 20 seconds exceeded in - on line 12

The registered shutdown functions will still be executed.

I figured it was important that this be made clear!
php at spandex dot deleteme dot nildram dot co dot uk 28-Apr-2003 01:43
I've had immense trouble getting any of the examples of emulated destructors to work.  They always seemed to have a copy of the object just after initialisation.  Many people mention that the register_shutdown_function will take a copy of the object rather than a reference... and this can be cured with an ampersand.  If you look in the PEAR docs for the way they emulate destructors you'll find that you also need one before the "new" statement when you create an instance of your object.  There's an editors note above that mentions this too... but I thought I'd collect it all here in one example that really works.  Honest... I'm using it (PHP 4.3.1):

<?php
class Object {
    var $somevar = "foo";

    function Object() {
        $somevar = "bar";
        register_shutdown_function(array(&$this, 'MyDestructor'));
    }

    function MyDestructor() {
        # Do useful destructor stuff here...
    }
}

# Now create the object as follows and then 'MyDestructor'
# will be called on shutdown and will be able to operate on
# the object as it ended up... not as it started!
$my_object =& new Object;
?>
kwazy at php dot net 29-Jan-2003 07:53
One more note to add about register_shutdown_function and objects.

It is possible to self-register the object from the constructor, but even using the syntax:
register_shutdown_function(array(&$this,'shutdown'))

will only result in the function being called with the object in the "just initialized" state, any changes made to the object after construction will not be there when the script actually exits.

But if you use:

<?php
$obj = new object();
register_shutdown_function(array(&$obj,'shutdown'));
?>

the object method 'shutdown' will be called with the current state of the object intact.

[Editor's note: The explanation for this behavior is really simple.
"$obj = new object()" creates a copy of the object which you can refer with $this in the object's constructor.
To solve this "problem" you should use "$obj = &new object()" which assign the reference to the current object.]
23-Oct-2002 09:35
When using CLI ( and perhaps command line without CLI - I didn't test it) the shutdown function doesn't get called if the process gets a SIGINT or SIGTERM. only the natural exit of PHP calls the shutdown function.
To overcome the problem compile the command line interpreter with --enable-pcntl and add this code:

<?php
function sigint()
{
    exit;
}
pcntl_signal(SIGINT, 'sigint');
pcntl_signal(SIGTERM, 'sigint');
?>

This way when the process recieves one of those signals, it quits normaly, and the shutdown function gets called.
Note: using the pcntl function in web server envoirment is considered problematic, so if you are writing a script that runs both from the command line and from the server, you should put some conditional code around that block that identifies wheater this is a command line envoirment or not.
adam at saki dot com dot au 20-Aug-2002 03:38
When using objects the syntax register_shutdown_function(array($object, 'function')) will take a copy of the object at the time of the call.  This means you cannot do this in the constructor and have it correctly destruct objects.  The alternative is to use register_shutdown_function(array(&$object, 'function')) where the ampersand passes the reference and not the copy.  This appears to work fine.
priebe at mi-corporation dot com 14-Mar-2002 08:25
Note that register_shutdown_function() does not work under Apache on Windows platforms.  Your shutdown function will be called, but the connection will not close until the processing is complete.  Zend tells me that this is due to a difference between Apache for *nix and Apache for Windows.

I'm seeing similar behavior under IIS (using php4isapi).


Registrar una función para que sea ejecutada en cada tick

  • « register_shutdown_function
  • unregister_tick_function »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Registrar una función para que sea ejecutada en cada tick

register_tick_function

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

register_tick_function — Registrar una función para que sea ejecutada en cada tick

Descripción

register_tick_function ( callable $function , mixed $arg = ? , mixed $... = ? ) : bool

Registra la función dada por function para ser ejecutada cuando se llame a un tick.

Parámetros

function

El nombre de la función como cadena, o una matriz que consiste en un objeto y un método.

arg

...

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de register_tick_function()

<?php
declare(ticks=1);

// usar una función como llamada de retorno
register_tick_function('mi_función', true);

// usar un objeto->método
$objeto = new mi_clase();
register_tick_function(array(&$objeto, 'mi_método'), true);
?>

Historial de cambios

Versión | Descripción
5.3.0 | Los ticks ahora están soportados en los módulos de servidores web que usan hilos.

Notas

Advertencia

No debería usarse register_tick_function() con módulos de servidores web que usan hilos con PHP 5.2 o anterior.

Ver también

  • declare
  • unregister_tick_function() - Dejar de registrar una función para su ejecución en cada tick

User Contributed Notes

Peter Featherstone 08-Jun-2017 09:03
Due to an implementation bug, the declare(ticks=1) directive leaked into different compilation units prior to PHP 7.0. This is not how declare() directives, which are per-file or per-scope, are supposed to work.

Therefore there are different implementations between PHP 5.6 and the correct implementation has been added in PHP 7.0. This means the below script will return different results

#index.php

<?php

declare(ticks=1);
$count = 0;

register_tick_function('ticker');
function ticker() {
  global $count;
  $count++;
}

?>

#inc.php

<?php

$baz = "baz";
$qux = "qux";

?>

Running php index.php in the terminal gives:

    PHP 5.6 - 7
    PHP 7.0 - 5
Carlos Granados 04-Jan-2017 05:59
A working example with variable input for validating the asymptotic analysis of your algorithm:

<?php

$n = 1000; // Size of your input

declare(ticks=1);

class Counter {
    private $counter = 0;

    public function increase()
    {
        $this->counter++;
    }

    public function print()
    {
        return $this->counter;
    }
}

$obj = new Counter;

register_tick_function([&$obj, 'increase'], true);

for ($i = 0; $i < 100; $i++)
{
    $a = 3;
}

// unregister_tick_function([&$obj, 'increase']);
// Not sure how to de-register, you can use static methods and members in the Counter instead.

var_dump("Number of basic low level operations: " . $obj->print());

?>
Ahmad Samiei 30-Aug-2013 03:41
put in in your index to find where your code exited. find die o exit

function shutdown_find_exit()
{
var_dump($GLOBALS['dbg_stack']);
}
register_shutdown_function('shutdown_find_exit');
function write_dbg_stack()
{
$GLOBALS['dbg_stack'] = debug_backtrace();
}
register_tick_function('write_dbg_stack');
declare(ticks=1);
rob dot eyre at gmail dot com 22-Jul-2011 05:19
It looks like register_tick_function() can accept an anonymous function, but unregister_tick_function() cannot
Jeremy 21-Jun-2007 11:03
I tried the following on an IIS 6/PHP 5 machine:

<?php

    set_time_limit(0);

    function profiler($return = false)
    {
        static $m = 0;
        if($return) return $m . " bytes";
        if(($mem = memory_get_usage()) > $m) $m = $mem;
    }

    register_tick_function('profiler');
    declare(ticks = 1);

    $numbers = array();
    for($i=0; $i<1000000; $i++)
    {
        print($i . "<br />");
    }

    print(profiler(true));

?>

...and got the following errors:

1) PHP has encountered an Unhandled Exception Code -1073741674 at 0435EC5A
2) PHP has encountered an Access Violation at 02727891
3) PHP has encountered an Access Violation at 02727879
4) PHP has encountered an Access Violation at 00000000

So far the code hasn't crashed the web server, but like the warning says, "register_tick_function() should not be used with threaded web server modules. Ticks are not working in ZTS mode and may crash your web server."

Strangely enough, the code does execute successfully every once in a while.


Dejar de registrar una función para su ejecución en cada tick

  • « register_tick_function
  • Quickhash »
  • PHP Manual
  • Funciones de Manejo de Funciones
  • Dejar de registrar una función para su ejecución en cada tick

unregister_tick_function

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

unregister_tick_function — Dejar de registrar una función para su ejecución en cada tick

Descripción

unregister_tick_function ( string $function_name ) : void

Deja de registrar la función nominada por function_name por lo que ya no se ejecuta más cuando se llame a un tick.

Parámetros

function_name

El nombre de la función, como cadena.

Valores devueltos

No devuelve ningún valor.

Ver también

  • register_tick_function() - Registrar una función para que sea ejecutada en cada tick

User Contributed Notes

ElectricHeart at ya dot ru 04-May-2016 09:14
You can unregister closure-function:

declare(ticks = 1000);
$startTime = microtime(true);
$tick = true;
$closure = function () use ($startTime, &$tick) {
    if (((microtime(true) - $startTime) > 5) && $tick) {
        $tick = false;
        throw new \Exception('Time to run code left');
    }
};

try {
            register_tick_function($closure);
            //do your code
            $result = 1;
            return $result;
        } catch (\Exception $e) {
            throw $e;
        } finally {
            unregister_tick_function($closure);
}
Greg 27-Jul-2012 12:02
It's not so clear, but, at least as of PHP 5.3.13, you cannot use this inside of the handler itself as it will throw an error:

<?php

declare(ticks=2);

function tick_handler()
{
    unregister_tick_function('tick_handler');
}

register_tick_function('tick_handler');

set_time_limit(0);
usleep(500000);

?>

results in:

warning: unregister_tick_function(): Unable to delete tick function executed at the moment in [filename]

So if you want to unregister it must be done outside of the handler.
rob dot eyre at gmail dot com 22-Jul-2011 05:22
Note that unregister_tick_function() can also accept a callback in the form of an array (either static, like array($className, $methodName) or instance, like array(&$this, $methodName)).

It cannot accept an anonymous function, however.


Quickhash

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
  • Constantes predefinidas
  • Ejemplos
  • QuickHashIntSet — La clase QuickHashIntSet
    • QuickHashIntSet::add — Este método añade una nuevas entrada al conjunto
    • QuickHashIntSet::__construct — Crea un nuevo objeto QuickHashIntSet
    • QuickHashIntSet::delete — Este método elimina una entrada de un conjunto
    • QuickHashIntSet::exists — Este método comprueba si una clave es parte de un conjunto
    • QuickHashIntSet::getSize — Devuelve el número de elementos del conjunto
    • QuickHashIntSet::loadFromFile — Este método de fabricación crear un conjunto desde un fichero
    • QuickHashIntSet::loadFromString — Este método de fabricación crea un conjunto desde una cadena de caracteres
    • QuickHashIntSet::saveToFile — Este método almacena un conjunto que está en la memoria en el disco
    • QuickHashIntSet::saveToString — Este método devuelve una versión serializada del conjunto
  • QuickHashIntHash — La clase QuickHashIntHash
    • QuickHashIntHash::add — Este método añade una nueva entrada al hash
    • QuickHashIntHash::__construct — Crea un nuevo objeto QuickHashIntHash
    • QuickHashIntHash::delete — Este método elimina una entrada de un hash
    • QuickHashIntHash::exists — Este método comprueba si la clave es parte del hash
    • QuickHashIntHash::get — Este método recupera un valor a partir del hash por su clave
    • QuickHashIntHash::getSize — Devuelve el número de elementos de un hash
    • QuickHashIntHash::loadFromFile — Este método de fabricación crea un hash desde un fichero
    • QuickHashIntHash::loadFromString — Este método de fabricación crea un hash dedsde una cadena de caracteres
    • QuickHashIntHash::saveToFile — Este método almacena un hash en memoria en disco
    • QuickHashIntHash::saveToString — Este método devuelve una versión serializada del hash
    • QuickHashIntHash::set — Este método actualiza una entrada del hash con un nuevo valor, o añade una nueva si la entrada no existe
    • QuickHashIntHash::update — Este método actualiza una entrada del hash con un nuevo valor
  • QuickHashStringIntHash — La clase QuickHashStringIntHash
    • QuickHashStringIntHash::add — Este método añade una nueva entrada a un hash
    • QuickHashStringIntHash::__construct — Crea un nuevo objeto QuickHashStringIntHash
    • QuickHashStringIntHash::delete — Este método elimina una entrada del hash
    • QuickHashStringIntHash::exists — Este método comprueba si una clave es parte de un hash
    • QuickHashStringIntHash::get — Este método recupera un valor de un hash mediante su clave
    • QuickHashStringIntHash::getSize — Devuelve el número de elementos de un hash
    • QuickHashStringIntHash::loadFromFile — Este método de fabricación crea un hash desde un fichero
    • QuickHashStringIntHash::loadFromString — Este método de fabricación crea un hash desde una cadena de caracteres
    • QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashStringIntHash::saveToString — Este método devuelve una versión serializada del hash
    • QuickHashStringIntHash::set — Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe
    • QuickHashStringIntHash::update — Este método actualiza una entrada de un hash con un nuevo valor
  • QuickHashIntStringHash — La clase QuickHashIntStringHash
    • QuickHashIntStringHash::add — Este método añade una nueva entrada a un hash
    • QuickHashIntStringHash::__construct — Crea un nuevo objeto QuickHashIntStringHash
    • QuickHashIntStringHash::delete — Este método elimina una entrada del hash
    • QuickHashIntStringHash::exists — Este método comprueba si una clave es parte de un hash
    • QuickHashIntStringHash::get — Este método recupera un valor de un hash mediante su clave
    • QuickHashIntStringHash::getSize — Devuelve el número de elementos de un hash
    • QuickHashIntStringHash::loadFromFile — Este método de fabricación crea un hash desde un fichero
    • QuickHashIntStringHash::loadFromString — Este método de fabricación crea un hash desde una cadena de caracteres
    • QuickHashIntStringHash::saveToFile — Este método almacena un hash que esté en memoria en el disco
    • QuickHashIntStringHash::saveToString — Este método devuelve una versión serializada del hash
    • QuickHashIntStringHash::set — Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe
    • QuickHashIntStringHash::update — Este método actualiza una entrada de un hash con un nuevo valor

User Contributed Notes

There are no user contributed notes for this page.


Introducción

La extensión QuickHash contiene un conjunto de clases con establecimiento inflexible de tipos específicas para tratar con conjuntos específicos e implementaciones de hash.

User Contributed Notes

There are no user contributed notes for this page.


Requerimientos

Esta extensión no requiere bibliotecas adicionales.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

Se puede encontrar información para la instalación de esta extensión PECL en el capítulo del manual titulado Instalación de extensiones PECL. Se puede encontrar información adicional, tal como nuevos lanzamientos, descargas, ficheros fuente, información de mantenimiento, y un CHANGELOG, aquí: » https://pecl.php.net/package/quickhash

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

Ejemplo #1 Ejemplo de Quickhash

<?php
$conjunto = new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES );
$conjunto->add( 1 );
$conjunto->add( 3 );

var_dump( $conjunto->exists( 3 ) );
var_dump( $conjunto->exists( 4 ) );

$conjunto->saveToFile( "/tmp/conjunto-prueba.set" );

$conjuntoNuevo = QuickHashIntSet::loadFromFile(
    "/tmp/conjunto-prueba.set"
);

var_dump( $conjuntoNuevo->exists( 3 ) );
var_dump( $conjuntoNuevo->exists( 4 ) );
?>

El resultado del ejemplo sería algo similar a:

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

Ejemplo #2 Ejemplo de Quickhash con ArrayAccess

<?php
$hash = new QuickHashIntHash( 64 );

// Agregar y actualizar entradas hash.
$hash[3] = 145926;
$hash[3] = 1415926;
$hash[2] = 72;

// Comprobar si existen las claves
var_dump( isset( $hash[3] ) );

// Eliminación de entradas hash
unset( $hash[2] );

// Recuperar el valor almacenado para un hash
echo $hash[3], "\n";
?>

El resultado del ejemplo sería algo similar a:

bool(true)
1415926

Ejemplo #3 Ejemplo de Quickhash con Iterator

<?php
$hash = new QuickHashIntHash( 64 );

// Añadir entradas hash
$hash[1] = 145926;
$hash[2] = 1415926;
$hash[3] = 72;
$hash[4] = 712314;
$hash[5] = -4234;

foreach( $hash as $clave => $valor )
{
    echo $clave, ' => ', $valor, "\n";
}
?>

El resultado del ejemplo sería algo similar a:

5 => -4234
4 => 712314
1 => 145926
2 => 1415926
3 => 72

Ejemplo #4 Ejemplo de valores de tipo string de Quickhash

<?php
$hash = new QuickHashIntStringHash( 64 );

// Añadir entradas hash
$hash[1] = "un millón cuatrocientos quince mil novecientos ventiseis";
$hash->add( 2, "uno más" );

foreach( $hash as $clave => $valor )
{
    echo $clave, ' => ', $valor, "\n";
}
?>

El resultado del ejemplo sería algo similar a:

1 => un millón cuatrocientos quince mil novecientos ventiseis
2 => uno más

User Contributed Notes

There are no user contributed notes for this page.


La clase QuickHashIntSet

(PECL quickhash >= Unknown)

Introducción

Esta clase envuelve un conjunto de contiene números enteros.

Se puede iterar sobre los conjuntos con foreach, ya que la interfaz Iterator también está implementada. No se garantiza el orden de los elementos devueltos.

Sinopsis de la Clase

QuickHashIntSet {
/* Constatntes */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Métodos */
public add ( int $key ) : bool
public __construct ( int $size , int $options = ? )
public delete ( int $key ) : bool
public exists ( int $key ) : bool
publicgetSize ( ) : int
public static loadFromFile ( string $filename , int $size = ? , int $options = ? ) : QuickHashIntSet
public static loadFromString ( string $contents , int $size = ? , int $options = ? ) : QuickHashIntSet
public saveToFile ( string $filename ) : void
public saveToString ( ) : string
}

Constantes predefinidas

QuickHashIntSet::CHECK_FOR_DUPES

Si se habilita, la agregación de elementos duplicados a un canjunto (a través de add() o de loadFromFile()) resultará en la eliminación de dichos elementos del conjunto. Esto tomará tiempo extra, por lo que solamente se usa cuando es necesaria.

QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC

Deshabilita es uso del gestor de memoria interno de PHP para las estructuras de conjuntosl Con esta opción habilitada, la asignaciones internas no con respecto a los ajuestes de memory_limit.

QuickHashIntSet::HASHER_NO_HASH

Selecciona el no usar la función de hash, sino que meramente usa un mósulo para buscar el índice de la lista de recipientes. Esto no es más rápido que el uso del hash normal, y se dan más colisiones.

QuickHashIntSet::HASHER_JENKINS1

Esta es la función de hash predeterminada para convertir los hash de tipo integer en índices de lista de recipientes.

QuickHashIntSet::HASHER_JENKINS2

Selecciona un algoritmo de hash alternativo.

Tabla de contenidos

  • QuickHashIntSet::add — Este método añade una nuevas entrada al conjunto
  • QuickHashIntSet::__construct — Crea un nuevo objeto QuickHashIntSet
  • QuickHashIntSet::delete — Este método elimina una entrada de un conjunto
  • QuickHashIntSet::exists — Este método comprueba si una clave es parte de un conjunto
  • QuickHashIntSet::getSize — Devuelve el número de elementos del conjunto
  • QuickHashIntSet::loadFromFile — Este método de fabricación crear un conjunto desde un fichero
  • QuickHashIntSet::loadFromString — Este método de fabricación crea un conjunto desde una cadena de caracteres
  • QuickHashIntSet::saveToFile — Este método almacena un conjunto que está en la memoria en el disco
  • QuickHashIntSet::saveToString — Este método devuelve una versión serializada del conjunto

User Contributed Notes

There are no user contributed notes for this page.


Este método añade una nuevas entrada al conjunto

  • « QuickHashIntSet
  • QuickHashIntSet::__construct »
  • PHP Manual
  • QuickHashIntSet
  • Este método añade una nuevas entrada al conjunto

QuickHashIntSet::add

(PECL quickhash >= Unknown)

QuickHashIntSet::add — Este método añade una nuevas entrada al conjunto

Descripción

public QuickHashIntSet::add ( int $key ) : bool

Este método añade una nueva entrada al conjunto, y devuelve si la entrada fue añadida o no. Las entradas siempre son añadidas de forma predeterminada a menos que se hubiera pasado QuickHashIntSet::CHECK_FOR_DUPES al crear el conjunto.

Parámetros

key

La clave de la entrada a añadir.

Valores devueltos

true cuando la entrasa fue añadida, y false si la entrada no se añadió.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntSet::add()

<?php
echo "sin comprobación de duplicados\n";
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

echo "\ncon comporbación de duplicados\n";
$set = new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
?>

El resultado del ejemplo sería algo similar a:

sin comprobación de duplicados
bool(false)
bool(true)
bool(true)
bool(true)

con comporbación de duplicados
bool(false)
bool(true)
bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo objeto QuickHashIntSet

  • « QuickHashIntSet::add
  • QuickHashIntSet::delete »
  • PHP Manual
  • QuickHashIntSet
  • Crea un nuevo objeto QuickHashIntSet

QuickHashIntSet::__construct

(PECL quickhash >= Unknown)

QuickHashIntSet::__construct — Crea un nuevo objeto QuickHashIntSet

Descripción

public QuickHashIntSet::__construct ( int $size , int $options = ? )

Este constructor crea un nuevo objetos QuickHashIntSet. El tamaño es la cantidad de listas de recipientes a crear. Cuantas más listas existan, menos colisiones ocurrirán. También admite opciones.

Parámetros

size

La cantidad de listas de recipientes a configurar. El número que se pase será automáticamente redondeado hacia la siguiente potencia de dos. También será limitado automáticamente a valores entre 64 y 4194304.

options

Las opciones que se pueden pasar son: QuickHashIntSet::CHECK_FOR_DUPES, que se asegura de que no se añadan entradas duplicadas al conjunto; QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC para no usar el gestor de memoria interna de PHP, y tambíen una de las siguientes: QuickHashIntSet::HASHER_NO_HASH, QuickHashIntSet::HASHER_JENKINS1 o QuickHashIntSet::HASHER_JENKINS2. Estas tres últimas configuran el algoritmo hash a usar. Todas las opcioines se pueden combinar usando máscaras de bits.

Valores devueltos

Devuelve un nuevo objeto QuickHashIntSet.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntSet::__construct()

<?php
var_dump( new QuickHashIntSet( 1024 ) );
var_dump( new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntSet(
        1024,
        QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC | QuickHashIntSet::HASHER_JENKINS2
    )
);
?>

User Contributed Notes

There are no user contributed notes for this page.


Este método elimina una entrada de un conjunto

  • « QuickHashIntSet::__construct
  • QuickHashIntSet::exists »
  • PHP Manual
  • QuickHashIntSet
  • Este método elimina una entrada de un conjunto

QuickHashIntSet::delete

(PECL quickhash >= Unknown)

QuickHashIntSet::delete — Este método elimina una entrada de un conjunto

Descripción

public QuickHashIntSet::delete ( int $key ) : bool

Este método elimina una entrada de un conjunto, y devuelve si la entrada se eliminó o no. Las estructuras de memoria asociadas no serán liberadas inmediatamente, sino cuando el propio conjunto sea liberado.

Parámetros

key

La clave de la entrada a elminiar.

Valores devueltos

true cuando la entrada se eliminó, false si la entrada no se eliminó.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntSet::delete()

<?php
$conjunto = new QuickHashIntSet( 1024 );
var_dump( $conjunto->exists( 4 ) );
var_dump( $conjunto->add( 4 ) );
var_dump( $conjunto->delete( 4 ) );
var_dump( $conjunto->exists( 4 ) );
var_dump( $conjunto->delete( 4 ) );
?>

El resultado del ejemplo sería algo similar a:

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

User Contributed Notes

There are no user contributed notes for this page.


Este método comprueba si una clave es parte de un conjunto

  • « QuickHashIntSet::delete
  • QuickHashIntSet::getSize »
  • PHP Manual
  • QuickHashIntSet
  • Este método comprueba si una clave es parte de un conjunto

QuickHashIntSet::exists

(PECL quickhash >= Unknown)

QuickHashIntSet::exists — Este método comprueba si una clave es parte de un conjunto

Descripción

public QuickHashIntSet::exists ( int $key ) : bool

Este método comprueba si una entrada con la clave proporcionada existe en el. conjunto.

Parámetros

key

La clave de la entrada para comprobar si existe en el conjunto.

Valores devueltos

Devuelve true si la entrada se encuentra en el conjutno, o false si no.

Ejemplos

Ejemplo #1 Ejempl0 de QuickHashIntSet::exists()

<?php
//generar 200000 elementos
$array = range( 0, 199999 );
$existingEntries = array_rand( array_flip( $array ), 180000 );
$testForEntries = array_rand( array_flip( $array ), 1000 );
$foundCount = 0;

echo "Creating set: ", microtime( true ), "\n";
$set = new QuickHashIntSet( 100000 );
echo "Adding elements: ", microtime( true ), "\n";
foreach( $existingEntries as $key )
{
     $set->add( $key );
}

echo "Doing 1000 tests: ", microtime( true ), "\n";
foreach( $testForEntries as $key )
{
     $foundCount += $set->exists( $key );
}
echo "Done, $foundCount found: ", microtime( true ), "\n";
?>

El resultado del ejemplo sería algo similar a:

Creating set: 1263588703.0748
Adding elements: 1263588703.0757
Doing 1000 tests: 1263588703.7851
Done, 898 found: 1263588703.7897

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el número de elementos del conjunto

  • « QuickHashIntSet::exists
  • QuickHashIntSet::loadFromFile »
  • PHP Manual
  • QuickHashIntSet
  • Devuelve el número de elementos del conjunto

QuickHashIntSet::getSize

(PECL quickhash >= Unknown)

QuickHashIntSet::getSize — Devuelve el número de elementos del conjunto

Descripción

publicQuickHashIntSet::getSize ( ) : int

Devuelve el número de elementos del conjunto.

Parámetros

key

La clave de la entrada a añadir.

Valores devueltos

El número de elementos del conjunto.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntSet::getSize()

<?php
$set = new QuickHashIntSet( 8 );
var_dump( $set->add( 2 ) );
var_dump( $set->add( 3 ) );
var_dump( $set->getSize() );
?>

El resultado del ejemplo sería algo similar a:

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.


Este método de fabricación crear un conjunto desde un fichero

  • « QuickHashIntSet::getSize
  • QuickHashIntSet::loadFromString »
  • PHP Manual
  • QuickHashIntSet
  • Este método de fabricación crear un conjunto desde un fichero

QuickHashIntSet::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntSet::loadFromFile — Este método de fabricación crear un conjunto desde un fichero

Descripción

public static QuickHashIntSet::loadFromFile ( string $filename , int $size = ? , int $options = ? ) : QuickHashIntSet

Este método crea un nuevo conjunto desde un fichero de definición del disco. El formato del fichero consiste en número enteros de 32 bits con signo empaquetados juntos en el Endianness que use el sistema donde se ejecute el código.

Parámetros

filename

El nombre de fichero del fichero desde donde leer el conjunto.

size

La cantidad de listas de recipientes a configurar. El número pasado será automáticamente redondeado hacia arriba a la potencia de dos más próxima. También será limitada automáticamente de 4 a 4194304.

options

Las mismas opciones que toma el constructor de la clase; excepto que se ignora la opción 'size'. Ésta se calcula automáticamente para que sea el mismo que el número de entradas del conjunto, redondeado hacia arriba a la potencia de dos más próxima con un límite máximo de 4194304.

Valores devueltos

Devuelve un nuevo objeto QuickHashIntSet.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntSet::loadFromFile()

<?php
$fichero = dirname( __FILE__ ) . "/simple.set";
$set = QuickHashIntSet::loadFromFile(
    $fichero,
    QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $clave )
{
    printf( "La clave %3d (%2x) %s\n",
        $clave, $clave,
        $set->exists( $clave ) ? 'está establecida' : 'no está establecida'
    );
}
?>

El resultado del ejemplo sería algo similar a:

La clave   0 ( 0) no está establecida
La clave   1 ( 1) está establecida
La clave   2 ( 2) está establecida
La clave   3 ( 3) está establecida
La clave   4 ( 4) no está establecida
La clave   5 ( 5) está establecida
La clave   6 ( 6) no está establecida
La clave   7 ( 7) está establecida
La clave   8 ( 8) no está establecida
La clave   9 ( 9) no está establecida
La clave  10 ( a) no está establecida
La clave  11 ( b) está establecida
La clave  12 ( c) ino está establecida
La clave  13 ( d) está establecida
La clave  14 ( e) no está establecida
La clave  15 ( f) no está establecida

User Contributed Notes

There are no user contributed notes for this page.


Este método de fabricación crea un conjunto desde una cadena de caracteres

  • « QuickHashIntSet::loadFromFile
  • QuickHashIntSet::saveToFile »
  • PHP Manual
  • QuickHashIntSet
  • Este método de fabricación crea un conjunto desde una cadena de caracteres

QuickHashIntSet::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntSet::loadFromString — Este método de fabricación crea un conjunto desde una cadena de caracteres

Descripción

public static QuickHashIntSet::loadFromString ( string $contents , int $size = ? , int $options = ? ) : QuickHashIntSet

Este método de fabricación crea un nuevo conjunto desde una definición de una cadena de caracteres. El formato del fichero consiste en número enteros de 32 bits con signo empaquetados juntos en el Endianness que use el sistema donde se ejecute el código.

Parámetros

contents

El string que contiene un formato serializado del conjunto.

size

La cantidad de listas de recipientes a configurar. El número pasado será automáticamente redondeado hacia arriba a la potencia de dos más próxima. También será limitada automáticamente de 4 a 4194304.

options

Las mismas opciones que toma el constructor de la clase; excepto que se ignora la opción 'size'. Ésta se calcula automáticamente para que sea el mismo que el número de entradas del conjunto, redondeado hacia arriba a la potencia de dos más próxima con un límite entre 64 y 4194304.

Valores devueltos

Devuelve un nuevo objeto QuickHashIntSet.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntSet::loadFromString()

<?php
$contenido = file_get_contents( dirname( __FILE__ ) . "/simple.set" );
$conjunto = QuickHashIntSet::loadFromString(
    $contenido,
    QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $clave )
{
    printf( "La clave %3d (%2x) %s\n",
        $clave, $clave,
        $set->exists( $clave ) ? 'está establecida' : 'no está establecida'
    );
}
?>

El resultado del ejemplo sería algo similar a:

La clave   0 ( 0) no está establecida
La clave   1 ( 1) está establecida
La clave   2 ( 2) está establecida
La clave   3 ( 3) está establecida
La clave   4 ( 4) no está establecida
La clave   5 ( 5) está establecida
La clave   6 ( 6) no está establecida
La clave   7 ( 7) está establecida
La clave   8 ( 8) no está establecida
La clave   9 ( 9) no está establecida
La clave  10 ( a) no está establecida
La clave  11 ( b) está establecida
La clave  12 ( c) ino está establecida
La clave  13 ( d) está establecida
La clave  14 ( e) no está establecida
La clave  15 ( f) no está establecida

User Contributed Notes

There are no user contributed notes for this page.


Este método almacena un conjunto que está en la memoria en el disco

  • « QuickHashIntSet::loadFromString
  • QuickHashIntSet::saveToString »
  • PHP Manual
  • QuickHashIntSet
  • Este método almacena un conjunto que está en la memoria en el disco

QuickHashIntSet::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntSet::saveToFile — Este método almacena un conjunto que está en la memoria en el disco

Descripción

public QuickHashIntSet::saveToFile ( string $filename ) : void

Este método almacena un conjunto existente en un fichero del disco, en el mismo formato que puede leer loadFromFile().

Parámetros

filename

El nombre de fichero del fichero donde almacenar el hash.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntSet::saveToFile()

<?php
$conjunto = new QuickHashIntSet( 1024 );
var_dump( $conjunto->exists( 4 ) );
var_dump( $conjunto->add( 4 ) );
var_dump( $conjunto->exists( 4 ) );
var_dump( $conjunto->add( 4 ) );

$conjunto->saveToFile( '/tmp/prueba.set' );
?>

User Contributed Notes

There are no user contributed notes for this page.


Este método devuelve una versión serializada del conjunto

  • « QuickHashIntSet::saveToFile
  • QuickHashIntHash »
  • PHP Manual
  • QuickHashIntSet
  • Este método devuelve una versión serializada del conjunto

QuickHashIntSet::saveToString

(PECL quickhash >= Unknown)

QuickHashIntSet::saveToString — Este método devuelve una versión serializada del conjunto

Descripción

public QuickHashIntSet::saveToString ( ) : string

Este método devuelve una versión serializada del conjunto en el mismo formato que que puede leer loadFromString().

Valores devueltos

Este método de vuelve un string que contiene un formato serializado del conjunto. Cada elementos se almacena como un valor de cuatro bytes en el Endianness que utilice el systema actual.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntSet::saveToString()

<?php
$conjunto = new QuickHashIntSet( 1024 );
var_dump( $conjunto->exists( 4 ) );
var_dump( $conjunto->add( 4 ) );
var_dump( $conjunto->exists( 4 ) );
var_dump( $conjunto->add( 4 ) );

var_dump( $conjunto->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.


La clase QuickHashIntHash

(PECL quickhash >= Unknown)

Introducción

Esta clase envuelve un hash que contiene números enteros, donde los valores también son números enteros. Los hash también están disponibles como implementación de la interfaz ArrayAccess.

También se puede iterar sobre los hash con foreach, ya que la interfaz Iterator también está implementada. No se garantiza el orden de los elementos devueltos.

Sinopsis de la Clase

QuickHashIntHash {
/* Constantes */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Métodos */
public add ( int $key , int $value = ? ) : bool
public __construct ( int $size , int $options = ? )
public delete ( int $key ) : bool
public exists ( int $key ) : bool
public get ( int $key ) : int
public getSize ( ) : int
public static loadFromFile ( string $filename , int $options = ? ) : QuickHashIntHash
public static loadFromString ( string $contents , int $options = ? ) : QuickHashIntHash
public saveToFile ( string $filename ) : void
public saveToString ( ) : string
public set ( int $key , int $value ) : bool
public update ( int $key , int $value ) : bool
}

Constantes predefinidas

QuickHashIntHash::CHECK_FOR_DUPES

Si se habilita, la agregación de elementos duplicados a un canjunto (a través de add() o de loadFromFile()) resultará en la eliminación de dichos elementos del conjunto. Esto tomará tiempo extra, por lo que solamente se usa cuando es necesaria.

QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC

Deshabilita es uso del gestor de memoria interno de PHP para las estructuras de conjuntosl Con esta opción habilitada, la asignaciones internas no con respecto a los ajuestes de memory_limit.

QuickHashIntHash::HASHER_NO_HASH

Selecciona el no usar la función de hash, sino que meramente usa un mósulo para buscar el índice de la lista de recipientes. Esto no es más rápido que el uso del hash normal, y se dan más colisiones.

QuickHashIntHash::HASHER_JENKINS1

Esta es la función de hash predeterminada para convertir los hash de tipo integer en índices de lista de recipientes.

QuickHashIntHash::HASHER_JENKINS2

Selecciona un algoritmo de hash alternativo.

Tabla de contenidos

  • QuickHashIntHash::add — Este método añade una nueva entrada al hash
  • QuickHashIntHash::__construct — Crea un nuevo objeto QuickHashIntHash
  • QuickHashIntHash::delete — Este método elimina una entrada de un hash
  • QuickHashIntHash::exists — Este método comprueba si la clave es parte del hash
  • QuickHashIntHash::get — Este método recupera un valor a partir del hash por su clave
  • QuickHashIntHash::getSize — Devuelve el número de elementos de un hash
  • QuickHashIntHash::loadFromFile — Este método de fabricación crea un hash desde un fichero
  • QuickHashIntHash::loadFromString — Este método de fabricación crea un hash dedsde una cadena de caracteres
  • QuickHashIntHash::saveToFile — Este método almacena un hash en memoria en disco
  • QuickHashIntHash::saveToString — Este método devuelve una versión serializada del hash
  • QuickHashIntHash::set — Este método actualiza una entrada del hash con un nuevo valor, o añade una nueva si la entrada no existe
  • QuickHashIntHash::update — Este método actualiza una entrada del hash con un nuevo valor

User Contributed Notes

There are no user contributed notes for this page.


Este método añade una nueva entrada al hash

  • « QuickHashIntHash
  • QuickHashIntHash::__construct »
  • PHP Manual
  • QuickHashIntHash
  • Este método añade una nueva entrada al hash

QuickHashIntHash::add

(PECL quickhash >= Unknown)

QuickHashIntHash::add — Este método añade una nueva entrada al hash

Descripción

public QuickHashIntHash::add ( int $key , int $value = ? ) : bool

Este método añade una nueva entrada al hash, y devuelve si la entrada se añadió o no. De manera predeterminada, todas las entradas siempre son añadidas a menos que QuickHashIntHash::CHECK_FOR_DUPES fuera pasado al crear el hash.

Parámetros

key

La clave de la entrada a añadir.

value

El valor opcional de la entrada a añadir. Si no se especifica ningún valor, se usará 1.

Valores devueltos

true cuando la entrasa fue añadida, y false si la entrada no se añadió.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntHash::add()

<?php
echo "sin comprobación de duplicados\n";
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 22 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 12 ) );

echo "\ncon comprobación de duplicados\n";
$hash = new QuickHashIntHash( 1024, QuickHashIntHash::CHECK_FOR_DUPES );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 78 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 9 ) );

echo "\nvalor prederminado\n";
var_dump( $hash->add( 5 ) );
var_dump( $hash->get( 5 ) );
?>

El resultado del ejemplo sería algo similar a:

sin comprobación de duplicados
bool(false)
bool(false)
bool(true)
bool(true)
int(22)
bool(true)

con comprobación de duplicados
bool(false)
bool(false)
bool(true)
bool(true)
int(78)
bool(false)

valor prederminado
bool(true)
int(1)

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo objeto QuickHashIntHash

  • « QuickHashIntHash::add
  • QuickHashIntHash::delete »
  • PHP Manual
  • QuickHashIntHash
  • Crea un nuevo objeto QuickHashIntHash

QuickHashIntHash::__construct

(PECL quickhash >= Unknown)

QuickHashIntHash::__construct — Crea un nuevo objeto QuickHashIntHash

Descripción

public QuickHashIntHash::__construct ( int $size , int $options = ? )

Este constructor crea un nuevo objeto QuickHashIntHash. El tamaño es la cantidad de listas de recipientes a crear. Cuantas más listas existan, menos colisiones ocurrirán. También admite opciones.

Parámetros

size

La cantidad de listas de recipientes a configurar. El número que se pase será automáticamente redondeado hacia la siguiente potencia de dos. También será limitado automáticamente a valores entre 64 y 4194304.

options

Las opciones que se pueden pasar son: QuickHashIntHash::CHECK_FOR_DUPES, que se asegura de que no se añadan entradas duplicadas al hash; QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC para no usar el gestor de memoria interna de PHP, y tambíen una de las siguientes: QuickHashIntHash::HASHER_NO_HASH, QuickHashIntHash::HASHER_JENKINS1 o QuickHashIntHash::HASHER_JENKINS2. Estas tres últimas configuran el algoritmo hash a usar. Todas las opcioines se pueden combinar usando máscaras de bits.

Valores devueltos

Devuelve un nuevo objeto QuickHashIntHash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntHash::__construct()

<?php
var_dump( new QuickHashIntHash( 1024 ) );
var_dump( new QuickHashIntHash( 1024, QuickHashIntHash::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntHash(
        1024,
        QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntHash::HASHER_JENKINS2
    )
);
?>

User Contributed Notes

There are no user contributed notes for this page.


Este método elimina una entrada de un hash

  • « QuickHashIntHash::__construct
  • QuickHashIntHash::exists »
  • PHP Manual
  • QuickHashIntHash
  • Este método elimina una entrada de un hash

QuickHashIntHash::delete

(PECL quickhash >= Unknown)

QuickHashIntHash::delete — Este método elimina una entrada de un hash

Descripción

public QuickHashIntHash::delete ( int $key ) : bool

Este método elimina una entrada de un hash, y devuelve si la entrada se eliminó o no. Las estructuras de memoria asociadas no serán liberadas inmediatamente, sino cuando el propio hash sea liberado.

Los elementos no se pueden eliminar del hash cuando se use un iterador. El método no lanzará un excepción, sinon que simplemente devolverá false de la misma forma que con cualquier otro fallo de eliminación.

Parámetros

key

La clave de la entrada a eliminar.

Valores devueltos

true cuando la entrada se eliminó, false si la entrada no se eliminó.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntHash::delete()

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 5 ) );
var_dump( $hash->delete( 4 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->delete( 4 ) );
?>

El resultado del ejemplo sería algo similar a:

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

User Contributed Notes

There are no user contributed notes for this page.


Este método comprueba si la clave es parte del hash

  • « QuickHashIntHash::delete
  • QuickHashIntHash::get »
  • PHP Manual
  • QuickHashIntHash
  • Este método comprueba si la clave es parte del hash

QuickHashIntHash::exists

(PECL quickhash >= Unknown)

QuickHashIntHash::exists — Este método comprueba si la clave es parte del hash

Descripción

public QuickHashIntHash::exists ( int $key ) : bool

Este método comprueba si una entrada con la clave proporcionada existe en el hash.

Parámetros

key

La clave de la entrada para comprobar si existe en el hash.

Valores devueltos

Devuelve true cuando la entrada es encontrada, o false si no se encuentra.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntHash::exists()

<?php
//generar 200000 elementos
$array = range( 0, 199999 );
$existingEntries = array_rand( array_flip( $array ), 180000 );
$testForEntries = array_rand( array_flip( $array ), 1000 );
$foundCount = 0;

echo "Creating hash: ", microtime( true ), "\n";
$hash = new QuickHashIntHash( 100000 );
echo "Adding elements: ", microtime( true ), "\n";
foreach( $existingEntries as $key )
{
     $hash->add( $key, 56 );
}

echo "Doing 1000 tests: ", microtime( true ), "\n";
foreach( $testForEntries as $key )
{
     $foundCount += $hash->exists( $key );
}
echo "Done, $foundCount found: ", microtime( true ), "\n";
?>

El resultado del ejemplo sería algo similar a:

Creating hash: 1263588703.0748
Adding elements: 1263588703.0757
Doing 1000 tests: 1263588703.7851
Done, 898 found: 1263588703.7897

User Contributed Notes

There are no user contributed notes for this page.


Este método recupera un valor a partir del hash por su clave

  • « QuickHashIntHash::exists
  • QuickHashIntHash::getSize »
  • PHP Manual
  • QuickHashIntHash
  • Este método recupera un valor a partir del hash por su clave

QuickHashIntHash::get

(PECL quickhash >= Unknown)

QuickHashIntHash::get — Este método recupera un valor a partir del hash por su clave

Descripción

public QuickHashIntHash::get ( int $key ) : int

Este método recupera un valor a partir del hash por su clave.

Parámetros

key

La clave de la entrada para añadir.

Valores devueltos

El valor si la clave existe, o null si la clave no era parte del hash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntHash::get()

<?php
$hash = new QuickHashIntHash( 8 );
var_dump( $hash->get( 1 ) );

var_dump( $hash->add( 2 ) );
var_dump( $hash->get( 2 ) );

var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->get( 3 ) );
?>

El resultado del ejemplo sería algo similar a:

bool(false)
bool(true)
int(1)
bool(true)
int(5)

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el número de elementos de un hash

  • « QuickHashIntHash::get
  • QuickHashIntHash::loadFromFile »
  • PHP Manual
  • QuickHashIntHash
  • Devuelve el número de elementos de un hash

QuickHashIntHash::getSize

(PECL quickhash >= Unknown)

QuickHashIntHash::getSize — Devuelve el número de elementos de un hash

Descripción

public QuickHashIntHash::getSize ( ) : int

Devuelve el número de elementos de un hash.

Parámetros

key

The key of the entry to add.

Valores devueltos

El número de elementos de un hash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntHash::getSize()

<?php
$hash = new QuickHashIntHash( 8 );
var_dump( $hash->add( 2 ) );
var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->getSize() );
?>

El resultado del ejemplo sería algo similar a:

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.


Este método de fabricación crea un hash desde un fichero

  • « QuickHashIntHash::getSize
  • QuickHashIntHash::loadFromString »
  • PHP Manual
  • QuickHashIntHash
  • Este método de fabricación crea un hash desde un fichero

QuickHashIntHash::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntHash::loadFromFile — Este método de fabricación crea un hash desde un fichero

Descripción

public static QuickHashIntHash::loadFromFile ( string $filename , int $options = ? ) : QuickHashIntHash

Este método de fabricación crea un nuevo hash desde un fichero de definición del disco. El formato del fichero consiste en una signatura 'QH\0x11\0', el número de elementos como un número entero de 32 con signo bits en el Endianness del sistema, seguido de números enteros de 32 con signo empaquetados juntos en el Endianness que use el sistema donde se ejecuta el código. Por cada elemento del hash existen dos números enteros de 32 bits con signo almacenados. El primero de cada elemento es la clave, y el segundo es el valor al que pertenece la clave. Un ejemplo podría ser:

Ejemplo #1 Formato de fichero de IntHash de QuickHash

00000000  51 48 11 00 02 00 00 00  01 00 00 00 01 00 00 00  |QH..............|
00000010  03 00 00 00 09 00 00 00                           |........|
00000018

Ejemplo #2 Formato de fichero de IntHash de QuickHash

signatura de cabecera ('QH'; tipo de clave: 1; tipo de valor: 1; relleno: \0x00)
00000000  51 48 11 00

número de elementos:
00000004  02 00 00 00

data string:
00000000  01 00 00 00 01 00 00 00  03 00 00 00 09 00 00 00

clave/valor 1 (clave = 1, valor = 1)
01 00 00 00  01 00 00 00

clave/valor 2 (clave = 3, valor = 9)
03 00 00 00  09 00 00 00

Parámetros

filename

El nombre de fichero del fichero desde donde leer el hash.

options

Las mismas opciones que toma el constructor de la clase; excepto que se ignora la opción 'size'. Ésta se calcula automáticamente para que sea el mismo que el número de entradas del hash, redondeado hacia arriba a la potencia de dos más próxima con un límite máximo de 4194304.

Valores devueltos

Devuelve un nuevo objeto QuickHashIntHash.

Ejemplos

Ejemplo #3 Ejemplo de QuickHashIntHash::loadFromFile()

<?php
$fichero = dirname( __FILE__ ) . "/simple.hash";
$hash = QuickHashIntHash::loadFromFile(
    $fichero,
    QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $clave )
{
    printf( "La clave %3d (%2x) %s\n",
        $clave, $clave,
        $hash->exists( $clave ) ? 'está establecida' : 'no está establecida'
    );
}
?>

El resultado del ejemplo sería algo similar a:

La clave   0 ( 0) no está establecida
La clave   1 ( 1) está establecida
La clave   2 ( 2) está establecida
La clave   3 ( 3) está establecida
La clave   4 ( 4) no está establecida
La clave   5 ( 5) está establecida
La clave   6 ( 6) no está establecida
La clave   7 ( 7) está establecida
La clave   8 ( 8) no está establecida
La clave   9 ( 9) no está establecida
La clave  10 ( a) no está establecida
La clave  11 ( b) está establecida
La clave  12 ( c) no está establecida
La clave  13 ( d) está establecida
La clave  14 ( e) no está establecida
La clave  15 ( f) no está establecida

User Contributed Notes

There are no user contributed notes for this page.


Este método de fabricación crea un hash dedsde una cadena de caracteres

  • « QuickHashIntHash::loadFromFile
  • QuickHashIntHash::saveToFile »
  • PHP Manual
  • QuickHashIntHash
  • Este método de fabricación crea un hash dedsde una cadena de caracteres

QuickHashIntHash::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntHash::loadFromString — Este método de fabricación crea un hash dedsde una cadena de caracteres

Descripción

public static QuickHashIntHash::loadFromString ( string $contents , int $options = ? ) : QuickHashIntHash

Este método crea un nuevo hash desde una definición de una cadena de caracteres. El formato del fichero consiste en números enteros de 32 con signo empaquetados juntos en el Endianness que use el sistema donde se ejecuta el código. Por cada elemento existen dos números enteros de 32 bits con signo almacenados. El primero de cada elemento es la clave, y el segundo es el valor al que pertenece la clave.

Parámetros

contents

El string que contiene un formato serializado del hash.

options

Las mismas opciones que toma el constructor de la clase; excepto que se ignora la opción 'size'. Ésta se calcula automáticamente para que sea el mismo que el número de entradas del hash, redondeado hacia arriba a la potencia de dos más próxima con un límite máximo de 4194304.

Valores devueltos

Devuelve un nuevo objeto QuickHashIntHash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntHash::loadFromString()

<?php
$contenido = file_get_contents( dirname( __FILE__ ) . "/simple.hash" );
$hash = QuickHashIntHash::loadFromString(
    $contenido,
    QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $clave )
{
    printf( "La clave %3d (%2x) %s\n",
        $clave, $clave,
        $hash->exists( $clave ) ? 'está establecida' : 'no está establecida'
    );
}
?>

El resultado del ejemplo sería algo similar a:

La clave   0 ( 0) no está establecida
La clave   1 ( 1) está establecida
La clave   2 ( 2) está establecida
La clave   3 ( 3) está establecida
La clave   4 ( 4) no está establecida
La clave   5 ( 5) está establecida
La clave   6 ( 6) no está establecida
La clave   7 ( 7) está establecida
La clave   8 ( 8) no está establecida
La clave   9 ( 9) no está establecida
La clave  10 ( a) no está establecida
La clave  11 ( b) está establecida
La clave  12 ( c) no está establecida
La clave  13 ( d) está establecida
La clave  14 ( e) no está establecida
La clave  15 ( f) no está establecida

User Contributed Notes

There are no user contributed notes for this page.


Este método almacena un hash en memoria en disco

  • « QuickHashIntHash::loadFromString
  • QuickHashIntHash::saveToString »
  • PHP Manual
  • QuickHashIntHash
  • Este método almacena un hash en memoria en disco

QuickHashIntHash::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntHash::saveToFile — Este método almacena un hash en memoria en disco

Descripción

public QuickHashIntHash::saveToFile ( string $filename ) : void

Este método almacena un hash existente en un fichero del disco, en el mismo formato que loadFromFile() puede leer.

Parámetros

filename

El nombre de fichero del fichero donde almacenar el hash.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntHash::saveToFile()

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 43 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 52 ) );

$hash->saveToFile( '/tmp/prueba.hash' );
?>

User Contributed Notes

There are no user contributed notes for this page.


Este método devuelve una versión serializada del hash

  • « QuickHashIntHash::saveToFile
  • QuickHashIntHash::set »
  • PHP Manual
  • QuickHashIntHash
  • Este método devuelve una versión serializada del hash

QuickHashIntHash::saveToString

(PECL quickhash >= Unknown)

QuickHashIntHash::saveToString — Este método devuelve una versión serializada del hash

Descripción

public QuickHashIntHash::saveToString ( ) : string

Este método devuelve una versión serializada del hash, en el mismo formato que loadFromString() puede leer.

Valores devueltos

Este método devuelve un string que consitne un formato serializado del hash. Cada elemento se almacena como un valor de cuatro bytes en el Endianness que utilice el sistema en uso.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntHash::saveToString()

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 34 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 55 ) );

var_dump( $hash->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.


Este método actualiza una entrada del hash con un nuevo valor, o añade una nueva si la entrada no existe

  • « QuickHashIntHash::saveToString
  • QuickHashIntHash::update »
  • PHP Manual
  • QuickHashIntHash
  • Este método actualiza una entrada del hash con un nuevo valor, o añade una nueva si la entrada no existe

QuickHashIntHash::set

(PECL quickhash >= Unknown)

QuickHashIntHash::set — Este método actualiza una entrada del hash con un nuevo valor, o añade una nueva si la entrada no existe

Descripción

public QuickHashIntHash::set ( int $key , int $value ) : bool

Este método intenta actualizar una entrada con un nuevo valor. En caso de que la entrada aún no exista, añadirá una nueva entrada en su lugar. Devuelve si la entrada se añadió o se actualizó. Si existen claves duplicadas, únicamente se actualizará el valor del primer elemento encontrado. Use QuickHashIntHash::CHECK_FOR_DUPES durante la creación de un hash para evitar que las claves duplicadas sean parte de un hash.

Parámetros

key

La clave de la entrada a añadir o actualizar.

value

El nuevo valor con el que establecer la entrada.

Valores devueltos

2 si la entrada se encontró y se actualizó, 1 si la entrada se añadió o 0 si ocurrión un error.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntHash::set()

<?php
$hash = new QuickHashIntHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( 46692 ) );
var_dump( $hash->set( 46692, 16091 ) );
var_dump( $hash->get( 46692 ) );

echo "Set->Update\n";
var_dump( $hash->set( 46692, 29906 ) );
var_dump( $hash->get( 46692 ) );
?>

El resultado del ejemplo sería algo similar a:

bool(false)
int(2)
int(16091)
Set->Update
int(1)
int(29906)

User Contributed Notes

There are no user contributed notes for this page.


Este método actualiza una entrada del hash con un nuevo valor

  • « QuickHashIntHash::set
  • QuickHashStringIntHash »
  • PHP Manual
  • QuickHashIntHash
  • Este método actualiza una entrada del hash con un nuevo valor

QuickHashIntHash::update

(PECL quickhash >= Unknown)

QuickHashIntHash::update — Este método actualiza una entrada del hash con un nuevo valor

Descripción

public QuickHashIntHash::update ( int $key , int $value ) : bool

Este método actualiza una entrada con un nuevo valor, y devuelve si la entrada fue actualizada. Si update. Si existen claves duplicadas, únicamente se actualizará el valor del primer elemento encontrado. Use QuickHashIntHash::CHECK_FOR_DUPES durante la creación de un hash para evitar que las claves duplicadas sean parte de un hash.

Parámetros

key

La clave de la entrada a añadir.

value

El nuevo valor con el que actualizar la entrada.

Valores devueltos

true cuando la entrada se encontró y se actualizó, y false si la entrada ya no es parte del hash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntHash::update()

<?php
$hash = new QuickHashIntHash( 1024 );

var_dump( $hash->add( 141421, 173205 ) );
var_dump( $hash->update( 141421, 223606 ) );
var_dump( $hash->get( 141421 ) );
?>

El resultado del ejemplo sería algo similar a:

bool(true)
bool(true)
int(223606)

User Contributed Notes

There are no user contributed notes for this page.


La clase QuickHashStringIntHash

(No hay información de versión disponible, podría estar únicamente en Git)

Introducción

Esta clase envuelve un hash que contiene strings, donde los valores son números enteros. Los hash también están disponibles como implementación de la interfaz ArrayAccess.

También se puede iterar sobre los hash con foreach, ya que la interfaz Iterator también está implementada. No se garantiza el orden de los elementos devueltos.

Sinopsis de la Clase

QuickHashStringIntHash {
/* Constantes */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
/* Métodos */
public add ( string $key , int $value ) : bool
public __construct ( int $size , int $options = 0 )
public delete ( string $key ) : bool
public exists ( string $key ) : bool
public get ( string $key ) : mixed
public getSize ( ) : int
public static loadFromFile ( string $filename , int $size = 0 , int $options = 0 ) : QuickHashStringIntHash
public static loadFromString ( string $contents , int $size = 0 , int $options = 0 ) : QuickHashStringIntHash
public saveToFile ( string $filename ) : void
public saveToString ( ) : string
public set ( string $key , int $value ) : int
public update ( string $key , int $value ) : bool
}

Constantes predefinidas

QuickHashStringIntHash::CHECK_FOR_DUPES

Si se habilita, la agregación de elementos duplicados a un canjunto (a través de add() o de loadFromFile()) resultará en la eliminación de dichos elementos del conjunto. Esto tomará tiempo extra, por lo que solamente se usa cuando es necesaria.

QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC

Deshabilita es uso del gestor de memoria interno de PHP para las estructuras de conjuntosl Con esta opción habilitada, la asignaciones internas no con respecto a los ajuestes de memory_limit.

Tabla de contenidos

  • QuickHashStringIntHash::add — Este método añade una nueva entrada a un hash
  • QuickHashStringIntHash::__construct — Crea un nuevo objeto QuickHashStringIntHash
  • QuickHashStringIntHash::delete — Este método elimina una entrada del hash
  • QuickHashStringIntHash::exists — Este método comprueba si una clave es parte de un hash
  • QuickHashStringIntHash::get — Este método recupera un valor de un hash mediante su clave
  • QuickHashStringIntHash::getSize — Devuelve el número de elementos de un hash
  • QuickHashStringIntHash::loadFromFile — Este método de fabricación crea un hash desde un fichero
  • QuickHashStringIntHash::loadFromString — Este método de fabricación crea un hash desde una cadena de caracteres
  • QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashStringIntHash::saveToString — Este método devuelve una versión serializada del hash
  • QuickHashStringIntHash::set — Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe
  • QuickHashStringIntHash::update — Este método actualiza una entrada de un hash con un nuevo valor

User Contributed Notes

There are no user contributed notes for this page.


Este método añade una nueva entrada a un hash

  • « QuickHashStringIntHash
  • QuickHashStringIntHash::__construct »
  • PHP Manual
  • QuickHashStringIntHash
  • Este método añade una nueva entrada a un hash

QuickHashStringIntHash::add

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::add — Este método añade una nueva entrada a un hash

Descripción

public QuickHashStringIntHash::add ( string $key , int $value ) : bool

Este método añade una nueva entrada a un hash, y devuelve si la entrada fue añadida o no. Las entradas se añaden siempre de forma predeterminada a menos que se pase QuickHashStringIntHash::CHECK_FOR_DUPES en la creación del hash.

Parámetros

key

La clave de la entrada a añadir.

value

El valor de la entrada a añadir.

Valores devueltos

true cuando la entrada fue añadida, y false si la entrada no se pudo añadir.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashStringIntHash::add()

<?php
echo "sin comprobación de duplicados\n";
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 22 ) );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 12 ) );

echo "\ncon comprobación de duplicados\n";
$hash = new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES );
var_dump( $hash );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 78 ) );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 9 ) );
?>

El resultado del ejemplo sería algo similar a:

sin comprobación de duplicados
object(QuickHashStringIntHash)#1 (0) {
}
bool(false)
bool(false)
bool(true)
bool(true)
int(22)
bool(true)

con comprobación de duplicados
object(QuickHashStringIntHash)#2 (0) {
}
bool(false)
bool(false)
bool(true)
bool(true)
int(78)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo objeto QuickHashStringIntHash

  • « QuickHashStringIntHash::add
  • QuickHashStringIntHash::delete »
  • PHP Manual
  • QuickHashStringIntHash
  • Crea un nuevo objeto QuickHashStringIntHash

QuickHashStringIntHash::__construct

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::__construct — Crea un nuevo objeto QuickHashStringIntHash

Descripción

public QuickHashStringIntHash::__construct ( int $size , int $options = 0 )

Este constructor crea un nuevo objeto QuickHashStringIntHash. El tamaño es la cantidad de listas de recipientes a crear. Cuantas más listas existan, menos colisiones ocurrirán. También admite opciones.

Parámetros

size

La cantidad de listas de recipientes a configurar. El número que se pase será automáticamente redondeado hacia la siguiente potencia de dos. También será limitado automáticamente a valores entre 64 y 4194304.

options

Las opciones que se pueden pasar son: QuickHashStringIntHash::CHECK_FOR_DUPES, que se asegura de que no se añadan entradas duplicadas al conjunto y QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC para no usar el gestor de memoria interna de PHP.

Valores devueltos

Devuelve un nuevo objeto QuickHashStringIntHash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashStringIntHash::__construct()

<?php
var_dump( new QuickHashStringIntHash( 1024 ) );
var_dump( new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES ) );
?>

User Contributed Notes

There are no user contributed notes for this page.


Este método elimina una entrada del hash

  • « QuickHashStringIntHash::__construct
  • QuickHashStringIntHash::exists »
  • PHP Manual
  • QuickHashStringIntHash
  • Este método elimina una entrada del hash

QuickHashStringIntHash::delete

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::delete — Este método elimina una entrada del hash

Descripción

public QuickHashStringIntHash::delete ( string $key ) : bool

Este método elimina una entrada del hash, y devuelve si la entrada fue eliminada o no.Las estructuras de memoria asociadas no serán liberadas inmediatamente, sino cuando el propio hash sea liberado.

Los elementos no se pueden eliminar del hash cuando se use un iterador. El método no lanzará una excepción, sino que simplemente devolverá false de la misma forma que con cualquier otro fallo de eliminación.

Parámetros

key

La clave de la entrada a eliminar.

Valores devueltos

true cuando la entrada fue eliminada, y false si la entrada no se pudo eliminar.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashStringIntHash::delete()

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->exists( 'four' ) );
var_dump( $hash->add( 'four', 5 ) );
var_dump( $hash->get( 'four' ) );
var_dump( $hash->delete( 'four' ) );
var_dump( $hash->exists( 'four' ) );
var_dump( $hash->get( 'four' ) );
var_dump( $hash->delete( 'four' ) );
?>

El resultado del ejemplo sería algo similar a:

bool(false)
bool(true)
int(5)
bool(true)
bool(false)
bool(false)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Este método comprueba si una clave es parte de un hash

  • « QuickHashStringIntHash::delete
  • QuickHashStringIntHash::get »
  • PHP Manual
  • QuickHashStringIntHash
  • Este método comprueba si una clave es parte de un hash

QuickHashStringIntHash::exists

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::exists — Este método comprueba si una clave es parte de un hash

Descripción

public QuickHashStringIntHash::exists ( string $key ) : bool

Este método comprueba si una entrada con la clave proporcionada existe en el hash.

Parámetros

key

La clave de la entrada para comprobar si existe en el hash.

Valores devueltos

Devuelve true si la entrada se encuentra en el hash, o false si no.

User Contributed Notes

There are no user contributed notes for this page.


Este método recupera un valor de un hash mediante su clave

  • « QuickHashStringIntHash::exists
  • QuickHashStringIntHash::getSize »
  • PHP Manual
  • QuickHashStringIntHash
  • Este método recupera un valor de un hash mediante su clave

QuickHashStringIntHash::get

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::get — Este método recupera un valor de un hash mediante su clave

Descripción

public QuickHashStringIntHash::get ( string $key ) : mixed

Este método recupera un valor de un hash mediante su clave.

Parámetros

key

La clave de la entrada a añadir.

Valores devueltos

El valor de la clave si ésta existe, o null si la clave no es parte del hash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashStringIntHash::get()

<?php
$hash = new QuickHashStringIntHash( 8 );
var_dump( $hash->get( "one" ) );

var_dump( $hash->add( "two", 2 ) );
var_dump( $hash->get( "two" ) );
?>

El resultado del ejemplo sería algo similar a:

bool(false)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el número de elementos de un hash

  • « QuickHashStringIntHash::get
  • QuickHashStringIntHash::loadFromFile »
  • PHP Manual
  • QuickHashStringIntHash
  • Devuelve el número de elementos de un hash

QuickHashStringIntHash::getSize

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::getSize — Devuelve el número de elementos de un hash

Descripción

public QuickHashStringIntHash::getSize ( ) : int

Devuelve el número de elementos de un hash.

Parámetros

key

La clave de la entrada a añadir.

Valores devueltos

El número de elementos del hash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashStringIntHash::getSize()

<?php
$hash = new QuickHashStringIntHash( 8 );
var_dump( $hash->add( "two", 2 ) );
var_dump( $hash->add( "three", 5 ) );
var_dump( $hash->getSize() );
?>

El resultado del ejemplo sería algo similar a:

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.


Este método de fabricación crea un hash desde un fichero

  • « QuickHashStringIntHash::getSize
  • QuickHashStringIntHash::loadFromString »
  • PHP Manual
  • QuickHashStringIntHash
  • Este método de fabricación crea un hash desde un fichero

QuickHashStringIntHash::loadFromFile

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::loadFromFile — Este método de fabricación crea un hash desde un fichero

Descripción

public static QuickHashStringIntHash::loadFromFile ( string $filename , int $size = 0 , int $options = 0 ) : QuickHashStringIntHash

Este método de fabricación crea un nuevo hash desde un fichero de definición del disco. El formato del fichero consiste en una signatura 'QH\0x12\0', el número de elementos como un número entero de 32 bits con signo en el Endianness del sistema, un número entero de 32 sin signo que contiene el número de datos del elemento a seguir en caracteres. Estos datos del elemento contienen todos los strings. Le sigue otro entero de 32 bits con signo que contiene el número de listas de recipientes. Después de la cabecera y los strings, le siguien los elementos. Están ordenados por lista de recipientes, por lo que a las claves no les tendrá que realizar un hash para poder restablecer el hash. Por cada lista de recipientes, se almacena la siguiente información (todos como enteros de 32 bits): el índeice de la lista de recipientes, el número de elementos de dicha lista, y luego, en parejas de dos enteros de 32 bits sin signo, los elementos, donde el primero es el índice dentro de la lista de cadenas que contiene las claves, y el segundo el valor. Un ejemplo podría ser:

Ejemplo #1 Formato de fichero de StringIntHash de QuickHash

00000000  51 48 21 00 02 00 00 00  09 00 00 00 40 00 00 00  |QH!.........@...|
00000010  4f 4e 45 00 4e 49 4e 45  00 07 00 00 00 01 00 00  |ONE.NINE........|
00000020  00 00 00 00 00 01 00 00  00 2f 00 00 00 01 00 00  |........./......|
00000030  00 04 00 00 00 03 00 00  00                       |.........|
00000039

Ejemplo #2 Formato de fichero de StringIntHash de QuickHash

signatura de la cabecera ('QH'; tipo de clave: 2; tipo de valor: 1; relleno: \0x00)
00000000  51 48 21 00

número de elementos:
00000004  02 00 00 00

longitud de los valores de string (9 caracteres):
00000008  09 00 00 00

número de listas de recipientes (esto normalmente se configura para los hash como
argumento del constructor, 64 en este caso):
0000000C  40 00 00 00

valores de string:
00000010  4f 4e 45 00 4e 49 4e 45  00

lista de recipientes:
  lista de recipientes 1 (con clave 7, y 1 elemento):
    cabecera:
    07 00 00 00 01 00 00 00
    elementos (índice de clave: 0 ('ONE'), valor = 0):
    00 00 00 00 01 00 00 00
  lista de recipientes 2 (con clave 0x2f, y 1 elemento):
    header:
    2f 00 00 00 01 00 00 00
    elementos (índice de clave: 4 ('NINE'), valor = 0):
    04 00 00 00 03 00 00 00

Parámetros

filename

El nombre de fichero del fichero desde donde leer el hash.

size

La cantidad de de listas de recipientes a configurar. El número proporcionado será automáticamente redondeado hacia arriba a la potencia de dos más cercana. Tambíen será automáticamente limitado de 4 a 4194304.

options

Las mismas opciones que toma el constructor de la clase; excepto que se ignora la opción 'size'. Ésta se lee desde el formato de fichero (a diferencia de las clases QuickHashIntHash y QuickHashIntStringHash, donde se calcula automáticamente desde el número de entradas del hash.)

Valores devueltos

Devuelve un nuevo objeto QuickHashStringIntHash.

Ejemplos

Ejemplo #3 Ejemplo de QuickHashStringIntHash::loadFromFile()

<?php
$fichero = dirname( __FILE__ ) . "/simple.hash.string";
$hash = QuickHashStringIntHash::loadFromFile(
    $fichero,
    QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $clave )
{
    $i = 48712 + $clave * 1631;
    $k = base_convert( $i, 10, 36 );
    echo $k, ' => ', $hash->get( $k ), "\n";
}
?>

El resultado del ejemplo sería algo similar a:

11l4 => 48712
12uf => 50343
143q => 51974
15d1 => 53605
16mc => 55236
17vn => 56867
194y => 58498
1ae9 => 60129
1bnk => 61760
1cwv => 63391
1e66 => 65022
1ffh => 66653
1gos => 68284
1hy3 => 69915
1j7e => 71546
1kgp => 73177

User Contributed Notes

There are no user contributed notes for this page.


Este método de fabricación crea un hash desde una cadena de caracteres

  • « QuickHashStringIntHash::loadFromFile
  • QuickHashStringIntHash::saveToFile »
  • PHP Manual
  • QuickHashStringIntHash
  • Este método de fabricación crea un hash desde una cadena de caracteres

QuickHashStringIntHash::loadFromString

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::loadFromString — Este método de fabricación crea un hash desde una cadena de caracteres

Descripción

public static QuickHashStringIntHash::loadFromString ( string $contents , int $size = 0 , int $options = 0 ) : QuickHashStringIntHash

Este método de fabricación cres un nuevo hash desde un fichero de definición de una cadena de caracteres. El formato es el mismo que el usado en "loadFromFile".

Parámetros

contents

La cadena de caracteres que contiene un formato serializado del hash.

size

La cantidad de listas de recipientes a configurar. El número proporcionado será automáticamente redondeado hacia arriba a la siguiente potencia de dos. También será automáticamente limitado de 4 a 4194304.

options

Las mismas opciones que toma el constructor de la clase; excepto que se ignora la opción 'size'. Ésta se calcula automáticamente para que sea el mismo que el número de entradas del hash, redondeado hacia arriba a la potencia de dos más próxima con un límite máximo de 4194304.

Valores devueltos

Deveulve un nuevo objeto QuickHashStringIntHash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashStringIntHash::loadFromString()

<?php
$contenido = file_get_contents( dirname( __FILE__ ) . "/simple.hash.string" );
$hash = QuickHashStringIntHash::loadFromString(
    $contenido,
    QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $clave )
{
    $i = 48712 + $clave * 1631;
    $k = base_convert( $i, 10, 36 );
    echo $k, ' => ', $hash->get( $k ), "\n";
}
?>

El resultado del ejemplo sería algo similar a:

11l4 => 48712
12uf => 50343
143q => 51974
15d1 => 53605
16mc => 55236
17vn => 56867
194y => 58498
1ae9 => 60129
1bnk => 61760
1cwv => 63391
1e66 => 65022
1ffh => 66653
1gos => 68284
1hy3 => 69915
1j7e => 71546
1kgp => 73177

User Contributed Notes

There are no user contributed notes for this page.


This method stores an in-memory hash to disk

  • « QuickHashStringIntHash::loadFromString
  • QuickHashStringIntHash::saveToString »
  • PHP Manual
  • QuickHashStringIntHash
  • This method stores an in-memory hash to disk

QuickHashStringIntHash::saveToFile

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk

Descripción

public QuickHashStringIntHash::saveToFile ( string $filename ) : void

Este método almacena un hash existente en un fichero del disco, en el mismo formato que puede leer loadFromFile().

Parámetros

filename

El nombre de fichero del fichero donde almacenar el hash.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashStringIntHash::saveToFile()

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->add( "fourty three", 42 ) );
var_dump( $hash->add( "fifty two", 52 ) );

$hash->saveToFile( '/tmp/prueba.hash.string' );
?>

User Contributed Notes

There are no user contributed notes for this page.


Este método devuelve una versión serializada del hash

  • « QuickHashStringIntHash::saveToFile
  • QuickHashStringIntHash::set »
  • PHP Manual
  • QuickHashStringIntHash
  • Este método devuelve una versión serializada del hash

QuickHashStringIntHash::saveToString

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::saveToString — Este método devuelve una versión serializada del hash

Descripción

public QuickHashStringIntHash::saveToString ( ) : string

Este método devuelve una verisón serializada del hash en el mismo formato que puede leer loadFromString().

Valores devueltos

Este método devuelve un formato serializado de un hash existente, en el mismo formato que puede leer loadFromString().

Ejemplos

Ejemplo #1 Ejemplo de QuickHashStringIntHash::saveToString()

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->add( "fourty three", 42 ) );
var_dump( $hash->add( "fifty two", 52 ) );

var_dump( $hash->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.


Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe

  • « QuickHashStringIntHash::saveToString
  • QuickHashStringIntHash::update »
  • PHP Manual
  • QuickHashStringIntHash
  • Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe

QuickHashStringIntHash::set

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::set — Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe

Descripción

public QuickHashStringIntHash::set ( string $key , int $value ) : int

Este método intenta actualizar una entrada con un nuevo valor. En caso de que la entrada aún no exista, añadirá una nueva entrada en su lugar. Devuelve si la entrada se añadió o se actualizó. Si existen claves duplicadas, únicamente se actualizará el valor del primer elemento encontrado. Use QuickHashStringIntHash::CHECK_FOR_DUPES durante la creación de un hash para evitar que las claves duplicadas sean parte de un hash.

Parámetros

key

La clave de la entrada a añadir o actualizar.

value

El nuevo valor de la entrada. Si se pasa algo que no sea un string, será convertidoa un string automáticamente, si fuera posible.

Valores devueltos

2 si la entrada se encontró y se actualizó, 1 si la entrada se añadió o 0 si ocurrió un error.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashStringIntHash::set()

<?php
$hash = new QuickHashStringIntHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );
var_dump( $hash->set( "fourty six thousand six hundred ninety two", 16091 ) );
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );

echo "Set->Update\n";
var_dump( $hash->set( "fourty six thousand six hundred ninety two", 29906 ) );
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );
?>

El resultado del ejemplo sería algo similar a:

Set->Add
bool(false)
int(2)
int(16091)
Set->Update
int(1)
int(29906)

User Contributed Notes

There are no user contributed notes for this page.


Este método actualiza una entrada de un hash con un nuevo valor

  • « QuickHashStringIntHash::set
  • QuickHashIntStringHash »
  • PHP Manual
  • QuickHashStringIntHash
  • Este método actualiza una entrada de un hash con un nuevo valor

QuickHashStringIntHash::update

(No hay información de versión disponible, podría estar únicamente en Git)

QuickHashStringIntHash::update — Este método actualiza una entrada de un hash con un nuevo valor

Descripción

public QuickHashStringIntHash::update ( string $key , int $value ) : bool

Este método actualiza una entrada un nuevo valor, y devuelve si la entrada fue actualizada o no. Si existen claves duplicadas, solamente se actualizará el valor del primero elemento encontrado. Use QuickHashStringIntHash::CHECK_FOR_DUPES durante la creación del hash para evitar que las claves duplicadas sean parte de un hash.

Parámetros

key

La clave de la entrada a añadir.

value

El nuevo valor de la entrada. Si se pasa algo que no sea un string, será convertidoa un string automáticamente, si fuera posible.

Valores devueltos

true si la entrada se encontró y se actualizó, y false si la entrada no formaba parte del hash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashStringIntHash::update()

<?php
$hash = new QuickHashStringIntHash( 1024 );

$hash->add( 'six', 314159265 );
$hash->add( "a lot", 314159265 );

echo $hash->get( 'six' ), "\n";
echo $hash->get( 'a lot' ), "\n";

var_dump( $hash->update( 'a lot', 314159266 ) );
var_dump( $hash->update( "a lot plus one", 314159999 ) );

echo $hash->get( 'six' ), "\n";
echo $hash->get( 'a lot' ), "\n";
?>

El resultado del ejemplo sería algo similar a:

314159265
314159265
bool(true)
bool(false)
314159265
314159266

User Contributed Notes

There are no user contributed notes for this page.


La clase QuickHashIntStringHash

(PECL quickhash >= Unknown)

Introducción

Esta clase envuelve un hash que contiene números enteros, donde los valores son strings. Los hash también están disponibles como implementación de la interfaz ArrayAccess.

También se puede iterar sobre los hash con foreach, ya que la interfaz Iterator también está implementada. No se garantiza el orden de los elementos devueltos.

Sinopsis de la Clase

QuickHashIntStringHash {
/* Constantes */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Métodos */
public add ( int $key , string $value ) : bool
public __construct ( int $size , int $options = 0 )
public delete ( int $key ) : bool
public exists ( int $key ) : bool
public get ( int $key ) : mixed
public getSize ( ) : int
public static loadFromFile ( string $filename , int $size = 0 , int $options = 0 ) : QuickHashIntStringHash
public static loadFromString ( string $contents , int $size = 0 , int $options = 0 ) : QuickHashIntStringHash
public saveToFile ( string $filename ) : void
public saveToString ( ) : string
public set ( int $key , string $value ) : int
public update ( int $key , string $value ) : bool
}

Constantes predefinidas

QuickHashIntStringHash::CHECK_FOR_DUPES

Si se habilita, la agregación de elementos duplicados a un canjunto (a través de add() o de loadFromFile()) resultará en la eliminación de dichos elementos del conjunto. Esto tomará tiempo extra, por lo que solamente se usa cuando es necesaria.

QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntStringHash::HASHER_NO_HASH

Deshabilita es uso del gestor de memoria interno de PHP para las estructuras de conjuntosl Con esta opción habilitada, la asignaciones internas no con respecto a los ajuestes de memory_limit.

QuickHashIntStringHash::HASHER_JENKINS1

Esta es la función de hash predeterminada para convertir los hash de tipo integer en índices de lista de recipientes.

QuickHashIntStringHash::HASHER_JENKINS2

Selecciona un algoritmo de hash alternativo.

Tabla de contenidos

  • QuickHashIntStringHash::add — Este método añade una nueva entrada a un hash
  • QuickHashIntStringHash::__construct — Crea un nuevo objeto QuickHashIntStringHash
  • QuickHashIntStringHash::delete — Este método elimina una entrada del hash
  • QuickHashIntStringHash::exists — Este método comprueba si una clave es parte de un hash
  • QuickHashIntStringHash::get — Este método recupera un valor de un hash mediante su clave
  • QuickHashIntStringHash::getSize — Devuelve el número de elementos de un hash
  • QuickHashIntStringHash::loadFromFile — Este método de fabricación crea un hash desde un fichero
  • QuickHashIntStringHash::loadFromString — Este método de fabricación crea un hash desde una cadena de caracteres
  • QuickHashIntStringHash::saveToFile — Este método almacena un hash que esté en memoria en el disco
  • QuickHashIntStringHash::saveToString — Este método devuelve una versión serializada del hash
  • QuickHashIntStringHash::set — Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe
  • QuickHashIntStringHash::update — Este método actualiza una entrada de un hash con un nuevo valor

User Contributed Notes

There are no user contributed notes for this page.


Este método añade una nueva entrada a un hash

  • « QuickHashIntStringHash
  • QuickHashIntStringHash::__construct »
  • PHP Manual
  • QuickHashIntStringHash
  • Este método añade una nueva entrada a un hash

QuickHashIntStringHash::add

(PECL quickhash >= Unknown)

QuickHashIntStringHash::add — Este método añade una nueva entrada a un hash

Descripción

public QuickHashIntStringHash::add ( int $key , string $value ) : bool

Este método añade una nueva entrada a un hash, y devuelve si la entrada fue añadida o no. Las entradas se añaden siempre de forma predeterminada a menos que se pase QuickHashIntStringHash::CHECK_FOR_DUPES en la creación del hash.

Parámetros

key

La clave de la entrada a añadir.

value

El valor de la entrada a añadir. Si se pasa algo que no sea un string, será convertido a un string automáticamente, si fuera posible.

Valores devueltos

true cuando la entrada fue añadida, y false si la entrada no se pudo añadir.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntStringHash::add()

<?php
echo "sin comprobación de duplicados\n";
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "twenty two" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "twelve" ) );

echo "\ncon comprobación de duplicados\n";
$hash = new QuickHashIntStringHash( 1024, QuickHashIntStringHash::CHECK_FOR_DUPES );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "seventy eight" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "nine" ) );
?>

El resultado del ejemplo sería algo similar a:

sin comprobación de duplicados
bool(false)
bool(false)
bool(true)
bool(true)
string(10) "twenty two"
bool(true)

con comprobación de duplicados
bool(false)
bool(false)
bool(true)
bool(true)
string(13) "seventy eight"
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo objeto QuickHashIntStringHash

  • « QuickHashIntStringHash::add
  • QuickHashIntStringHash::delete »
  • PHP Manual
  • QuickHashIntStringHash
  • Crea un nuevo objeto QuickHashIntStringHash

QuickHashIntStringHash::__construct

(PECL quickhash >= Unknown)

QuickHashIntStringHash::__construct — Crea un nuevo objeto QuickHashIntStringHash

Descripción

public QuickHashIntStringHash::__construct ( int $size , int $options = 0 )

Este constructor crea un nuevo objeto QuickHashIntStringHash. El tamaño es la cantidad de listas de recipientes a crear. Cuantas más listas existan, menos colisiones ocurrirán. También admite opciones.

Parámetros

size

La cantidad de listas de recipientes a configurar. El número que se pase será automáticamente redondeado hacia la siguiente potencia de dos. También será limitado automáticamente a valores entre 64 y 4194304.

options

Las opciones que se pueden pasar son: QuickHashIntStringHash::CHECK_FOR_DUPES, que se asegura de que no se añadan entradas duplicadas al conjunto; QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC para no usar el gestor de memoria interna de PHP, y tambíen una de las siguientes: QuickHashIntStringHash::HASHER_NO_HASH, QuickHashIntStringHash::HASHER_JENKINS1 o QuickHashIntStringHash::HASHER_JENKINS2. Estas tres últimas configuran el algoritmo hash a usar. Todas las opcioines se pueden combinar usando máscaras de bits.

Valores devueltos

Devuelve un nuevo objeto QuickHashIntStringHash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntStringHash::__construct()

<?php
var_dump( new QuickHashIntStringHash( 1024 ) );
var_dump( new QuickHashIntStringHash( 1024, QuickHashIntStringHash::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntStringHash(
        1024,
        QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntStringHash::HASHER_JENKINS2
    )
);
?>

User Contributed Notes

There are no user contributed notes for this page.


Este método elimina una entrada del hash

  • « QuickHashIntStringHash::__construct
  • QuickHashIntStringHash::exists »
  • PHP Manual
  • QuickHashIntStringHash
  • Este método elimina una entrada del hash

QuickHashIntStringHash::delete

(PECL quickhash >= Unknown)

QuickHashIntStringHash::delete — Este método elimina una entrada del hash

Descripción

public QuickHashIntStringHash::delete ( int $key ) : bool

Este método elimina una entrada del hash, y devuelve si la entrada fue eliminada o no.Las estructuras de memoria asociadas no serán liberadas inmediatamente, sino cuando el propio hash sea liberado.

Los elementos no se pueden eliminar del hash cuando se use un iterador. El método no lanzará una excepción, sino que simplemente devolverá false de la misma forma que con cualquier otro fallo de eliminación.

Parámetros

key

La clave de la entrada a eliminar.

Valores devueltos

true cuando la entrada fue eliminada, y false si la entrada no se pudo eliminar.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntStringHash::delete()

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "five" ) );
var_dump( $hash->delete( 4 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->delete( 4 ) );
?>

El resultado del ejemplo sería algo similar a:

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

User Contributed Notes

There are no user contributed notes for this page.


Este método comprueba si una clave es parte de un hash

  • « QuickHashIntStringHash::delete
  • QuickHashIntStringHash::get »
  • PHP Manual
  • QuickHashIntStringHash
  • Este método comprueba si una clave es parte de un hash

QuickHashIntStringHash::exists

(PECL quickhash >= Unknown)

QuickHashIntStringHash::exists — Este método comprueba si una clave es parte de un hash

Descripción

public QuickHashIntStringHash::exists ( int $key ) : bool

Este método comprueba si una entrada con la clave proporcionada existe en el hash.

Parámetros

key

La clave de la entrada para comprobar si existe en el hash.

Valores devueltos

Devuelve true si la entrada se encuentra en el hash, o false si no.

User Contributed Notes

There are no user contributed notes for this page.


Este método recupera un valor de un hash mediante su clave

  • « QuickHashIntStringHash::exists
  • QuickHashIntStringHash::getSize »
  • PHP Manual
  • QuickHashIntStringHash
  • Este método recupera un valor de un hash mediante su clave

QuickHashIntStringHash::get

(PECL quickhash >= Unknown)

QuickHashIntStringHash::get — Este método recupera un valor de un hash mediante su clave

Descripción

public QuickHashIntStringHash::get ( int $key ) : mixed

Este método recupera un valor de un hash mediante su clave.

Parámetros

key

La clave de la entrada a añadir.

Valores devueltos

El valor de la clave si ésta existe, o null si la clave no es parte del hash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntStringHash::get()

<?php
$hash = new QuickHashIntStringHash( 8 );
var_dump( $hash->get( 1 ) );

var_dump( $hash->add( 2, "two" ) );
var_dump( $hash->get( 2 ) );

var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->get( 3 ) );
?>

El resultado del ejemplo sería algo similar a:

bool(false)
bool(true)
string(3) "two"
bool(true)
string(1) "5"

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el número de elementos de un hash

  • « QuickHashIntStringHash::get
  • QuickHashIntStringHash::loadFromFile »
  • PHP Manual
  • QuickHashIntStringHash
  • Devuelve el número de elementos de un hash

QuickHashIntStringHash::getSize

(PECL quickhash >= Unknown)

QuickHashIntStringHash::getSize — Devuelve el número de elementos de un hash

Descripción

public QuickHashIntStringHash::getSize ( ) : int

Devuelve el número de elementos de un hash.

Valores devueltos

El número de elementos del hash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntStringHash::getSize()

<?php
$hash = new QuickHashIntStringHash( 8 );
var_dump( $hash->add( 2, "two" ) );
var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->getSize() );
?>

El resultado del ejemplo sería algo similar a:

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.


Este método de fabricación crea un hash desde un fichero

  • « QuickHashIntStringHash::getSize
  • QuickHashIntStringHash::loadFromString »
  • PHP Manual
  • QuickHashIntStringHash
  • Este método de fabricación crea un hash desde un fichero

QuickHashIntStringHash::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntStringHash::loadFromFile — Este método de fabricación crea un hash desde un fichero

Descripción

public static QuickHashIntStringHash::loadFromFile ( string $filename , int $size = 0 , int $options = 0 ) : QuickHashIntStringHash

Este método de fabricación crea un nuevo hash desde un fichero de definición del disco. El formato del fichero consiste en una signatura 'QH\0x12\0', el número de elementos como un número entero de 32 bits con signo en el Endianness del sistema, un número entero de 32 sin signo que contiene el número de datos del elemento a seguir en caracteres. Estos datos del elemento contienen todos los strings. Después de la cabecera y los strings, los elementos siguen en parejas de dos enteros de 32 bits sin signo donde el primero es la clave, y el segundo el índice del string de datos del elemento. Un ejemplo podría ser:

Ejemplo #1 Formato de fichero de IntString de QuickHash

00000000  51 48 12 00 02 00 00 00  09 00 00 00 4f 4e 45 00  |QH..........ONE.|
00000010  4e 49 4e 45 00 01 00 00  00 00 00 00 00 03 00 00  |NINE............|
00000020  00 04 00 00 00                                    |.....|
00000025

Ejemplo #2 Formato de fichero de IntString de QuickHash

signatura de la cabecera ('QH'; tipo de clave: 2; tipo de valor: 1; relleno: \0x00)
00000000  51 48 12 00

número de elementos:
00000004  02 00 00 00

longitud de los valores de string (9 caracteres):
00000008  09 00 00 00

valores de string:
0000000C  4f 4e 45 00 4e 49 4e 45  00

string de datos:
00000015  01 00 00 00 00 00 00 00  03 00 00 00 04 00 00 00

clave/valor 1 (clave = 1, índice del string = 0 ("ONE")):
01 00 00 00  00 00 00 00

clave/valor 2 (clave = 3, índice del string = 4 ("NINE")):
03 00 00 00  04 00 00 00

Parámetros

filename

El nombre de fichero del fichero desde donde leer el hash.

size

La cantidad de de listas de recipientes a configurar. El número proporcionado será automáticamente redondeado hacia arriba a la potencia de dos más cercana. Tambíen será automáticamente limitado de 4 a 4194304.

options

Las mismas opciones que toma el constructor de la clase; excepto que se ignora la opción 'size'. Ésta se calcula automáticamente para que sea el mismo que el número de entradas del hash, redondeado hacia arriba a la potencia de dos más próxima con un límite máximo de 4194304.

Valores devueltos

Devuelve un nuevo objeto QuickHashIntStringHash.

Ejemplos

Ejemplo #3 Ejemplo de QuickHashIntStringHash::loadFromFile()

<?php
$fichero = dirname( __FILE__ ) . "/simple.string.hash";
$hash = QuickHashIntStringHash::loadFromFile(
    $fichero,
    QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $clave )
{
    printf( "La clave %3d (%2x) %s\n",
        $clave, $clave,
        $hash->exists( $clave ) ? 'está establecida' : 'no está establecida'
    );
}
?>

El resultado del ejemplo sería algo similar a:

La clave   0 ( 0) no está establecida
La clave   1 ( 1) está establecida
La clave   2 ( 2) está establecida
La clave   3 ( 3) está establecida
La clave   4 ( 4) no está establecida
La clave   5 ( 5) está establecida
La clave   6 ( 6) no está establecida
La clave   7 ( 7) está establecida
La clave   8 ( 8) no está establecida
La clave   9 ( 9) no está establecida
La clave  10 ( a) no está establecida
La clave  11 ( b) está establecida
La clave  12 ( c) no está establecida
La clave  13 ( d) está establecida
La clave  14 ( e) no está establecida
La clave  15 ( f) no está establecida

User Contributed Notes

There are no user contributed notes for this page.


Este método de fabricación crea un hash desde una cadena de caracteres

  • « QuickHashIntStringHash::loadFromFile
  • QuickHashIntStringHash::saveToFile »
  • PHP Manual
  • QuickHashIntStringHash
  • Este método de fabricación crea un hash desde una cadena de caracteres

QuickHashIntStringHash::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntStringHash::loadFromString — Este método de fabricación crea un hash desde una cadena de caracteres

Descripción

public static QuickHashIntStringHash::loadFromString ( string $contents , int $size = 0 , int $options = 0 ) : QuickHashIntStringHash

Este método de fabricación cres un nuevo hash desde un fichero de definición de una cadena de caracteres. El formato es el mismo que el usado en "loadFromFile".

Parámetros

contents

La cadena de caracteres que contiene un formato serializado del hash.

size

La cantidad de listas de recipientes a configurar. El número proporcionado será automáticamente redondeado hacia arriba a la siguiente potencia de dos. También será automáticamente limitado de 4 a 4194304.

options

Las mismas opciones que toma el constructor de la clase; excepto que se ignora la opción 'size'. Ésta se calcula automáticamente para que sea el mismo que el número de entradas del hash, redondeado hacia arriba a la potencia de dos más próxima con un límite máximo de 4194304.

Valores devueltos

Deveulve un nuevo objeto QuickHashIntStringHash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntStringHash::loadFromString()

<?php
$contenido = file_get_contents( dirname( __FILE__ ) . "/simple.hash" );
$hash = QuickHashIntStringHash::loadFromString(
    $contenido,
    QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $clave )
{
    printf( "La clave %3d (%2x) %s\n",
        $clave, $clave,
        $hash->exists( $clave ) ? 'está establecida' : 'no está establecida'
    );
}
?>

El resultado del ejemplo sería algo similar a:

La clave   0 ( 0) no está establecida
La clave   1 ( 1) está establecida
La clave   2 ( 2) está establecida
La clave   3 ( 3) está establecida
La clave   4 ( 4) no está establecida
La clave   5 ( 5) está establecida
La clave   6 ( 6) no está establecida
La clave   7 ( 7) está establecida
La clave   8 ( 8) no está establecida
La clave   9 ( 9) no está establecida
La clave  10 ( a) no está establecida
La clave  11 ( b) está establecida
La clave  12 ( c) no está establecida
La clave  13 ( d) está establecida
La clave  14 ( e) no está establecida
La clave  15 ( f) no está establecida

User Contributed Notes

There are no user contributed notes for this page.


Este método almacena un hash que esté en memoria en el disco

  • « QuickHashIntStringHash::loadFromString
  • QuickHashIntStringHash::saveToString »
  • PHP Manual
  • QuickHashIntStringHash
  • Este método almacena un hash que esté en memoria en el disco

QuickHashIntStringHash::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntStringHash::saveToFile — Este método almacena un hash que esté en memoria en el disco

Descripción

public QuickHashIntStringHash::saveToFile ( string $filename ) : void

Este método almacena un hash existente en un fichero del disco, en el mismo formato que puede leer loadFromFile().

Parámetros

filename

El nombre de fichero del fichero donde almacenar el hash.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntStringHash::saveToFile()

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "fourty three" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "fifty two" ) );

$hash->saveToFile( '/tmp/prueba.string.hash' );
?>

User Contributed Notes

There are no user contributed notes for this page.


Este método devuelve una versión serializada del hash

  • « QuickHashIntStringHash::saveToFile
  • QuickHashIntStringHash::set »
  • PHP Manual
  • QuickHashIntStringHash
  • Este método devuelve una versión serializada del hash

QuickHashIntStringHash::saveToString

(PECL quickhash >= Unknown)

QuickHashIntStringHash::saveToString — Este método devuelve una versión serializada del hash

Descripción

public QuickHashIntStringHash::saveToString ( ) : string

Este método devuelve una verisón serializada del hash en el mismo formato que puede leer loadFromString().

Valores devueltos

Este método devuelve un string que contiene un formato serializado del hash. Cada elemento se almacena como un valor de cuatro bytes en el Endianness que utilice el sistema en uso.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntStringHash::saveToString()

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "thirty four" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 5, "fifty five" ) );

var_dump( $hash->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.


Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe

  • « QuickHashIntStringHash::saveToString
  • QuickHashIntStringHash::update »
  • PHP Manual
  • QuickHashIntStringHash
  • Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe

QuickHashIntStringHash::set

(PECL quickhash >= Unknown)

QuickHashIntStringHash::set — Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe

Descripción

public QuickHashIntStringHash::set ( int $key , string $value ) : int

Este método intenta actualizar una entrada con un nuevo valor. En caso de que la entrada aún no exista, añadirá una nueva entrada en su lugar. Devuelve si la entrada se añadió o se actualizó. Si existen claves duplicadas, únicamente se actualizará el valor del primer elemento encontrado. Use QuickHashIntStringHash::CHECK_FOR_DUPES durante la creación de un hash para evitar que las claves duplicadas sean parte de un hash.

Parámetros

key

La clave de la entrada a añadir o actualizar.

value

El nuevo valor de la entrada. Si se pasa algo que no sea un string, será convertidoa un string automáticamente, si fuera posible.

Valores devueltos

2 si la entrada se encontró y se actualizó, 1 si la entrada se añadió o 0 si ocurrió un error.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntStringHash::set()

<?php
$hash = new QuickHashIntStringHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( 46692 ) );
var_dump( $hash->set( 46692, "sixteen thousand ninety one" ) );
var_dump( $hash->get( 46692 ) );

echo "Set->Update\n";
var_dump( $hash->set( 46692, "twenty nine thousand nine hundred six" ) );
var_dump( $hash->get( 46692 ) );
?>

El resultado del ejemplo sería algo similar a:

Set->Add
bool(false)
int(2)
string(27) "sixteen thousand ninety one"
Set->Update
int(1)
string(37) "twenty nine thousand nine hundred six"

User Contributed Notes

There are no user contributed notes for this page.


Este método actualiza una entrada de un hash con un nuevo valor

  • « QuickHashIntStringHash::set
  • Reflection »
  • PHP Manual
  • QuickHashIntStringHash
  • Este método actualiza una entrada de un hash con un nuevo valor

QuickHashIntStringHash::update

(PECL quickhash >= Unknown)

QuickHashIntStringHash::update — Este método actualiza una entrada de un hash con un nuevo valor

Descripción

public QuickHashIntStringHash::update ( int $key , string $value ) : bool

Este método actualiza una entrada un nuevo valor, y devuelve si la entrada fue actualizada o no. Si existen claves duplicadas, solamente se actualizará el valor del primero elemento encontrado. Use QuickHashIntStringHash::CHECK_FOR_DUPES durante la creación del hash para evitar que las claves duplicadas sean parte de un hash.

Parámetros

key

La clave de la entrada a añadir.

value

El nuevo valor de la entrada. Si se pasa algo que no sea un string, será convertidoa un string automáticamente, si fuera posible.

Valores devueltos

true si la entrada se encontró y se actualizó, y false si la entrada no formaba parte del hash.

Ejemplos

Ejemplo #1 Ejemplo de QuickHashIntStringHash::update()

<?php
$hash->add( 161803398, "--" );
$hash->add( 314159265, "a lot" );

echo $hash->get( 161803398 ), "\n";
echo $hash->get( 314159265 ), "\n";

var_dump( $hash->update( 314159265, "a lot plus one" ) );
var_dump( $hash->update( 314159999, "a lot plus one" ) );

echo $hash->get( 161803398 ), "\n";
echo $hash->get( 314159265 ), "\n";
?>

El resultado del ejemplo sería algo similar a:

--
a lot
bool(true)
bool(false)
--
a lot plus one

User Contributed Notes

There are no user contributed notes for this page.


Reflection

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Ejemplos
  • Extensión
  • Reflection — Clase Reflection
    • Reflection::export — Exportar
    • Reflection::getModifierNames — Obtener nombres de modificadores
  • ReflectionClass — Clase ReflectionClass
    • ReflectionClass::__construct — Construye un objeto de tipo ReflectionClass
    • ReflectionClass::export — Exporta una clase
    • ReflectionClass::getConstant — Obtener una constante definida
    • ReflectionClass::getConstants — Obtener constantes
    • ReflectionClass::getConstructor — Obtiene el constructor de una clase
    • ReflectionClass::getDefaultProperties — Obtener propiedades predeterminadas
    • ReflectionClass::getDocComment — Obtener los comentarios de documentación
    • ReflectionClass::getEndLine — Consultar línea final
    • ReflectionClass::getExtension — Obtiene un objeto ReflectionExtension para la extensión que definió la clase
    • ReflectionClass::getExtensionName — Obtiene el nombre de la extensión que definió una clase
    • ReflectionClass::getFileName — Obtiene el nombre de fichero en el que está definida la clase
    • ReflectionClass::getInterfaceNames — Obtiene nombres de las interfaces
    • ReflectionClass::getInterfaces — Obtiene las interfaces
    • ReflectionClass::getMethod — Obtiene un objeto ReflectionMethod para un método de una clase
    • ReflectionClass::getMethods — Obtiene un array de métodos
    • ReflectionClass::getModifiers — Obtiene los modificadores de clase
    • ReflectionClass::getName — Obtiene el nombre de la clase
    • ReflectionClass::getNamespaceName — Obtiene el nombre del espacio de nombres
    • ReflectionClass::getParentClass — Obtiene la clase padre
    • ReflectionClass::getProperties — Obtiene las propiedades
    • ReflectionClass::getProperty — Obtiene un objeto ReflectionProperty para una propiedad de una clase
    • ReflectionClass::getReflectionConstant — Gets a ReflectionClassConstant for a class's constant
    • ReflectionClass::getReflectionConstants — Gets class constants
    • ReflectionClass::getShortName — Obtiene el nombre abreviado
    • ReflectionClass::getStartLine — Obtiene el número de linea de inicio
    • ReflectionClass::getStaticProperties — Obtiene las propiedades estáticas
    • ReflectionClass::getStaticPropertyValue — Obtiene el valor de una propiedad estática
    • ReflectionClass::getTraitAliases — Obtiene un array con los alias usados con los traits
    • ReflectionClass::getTraitNames — Devuelve un array con los nombres de los traits usados por esta clase
    • ReflectionClass::getTraits — Obtiene un array con los traits que utiliza esta clase
    • ReflectionClass::hasConstant — Comprueba si una constante está o no definida
    • ReflectionClass::hasMethod — Comprueba si un método está o no definido
    • ReflectionClass::hasProperty — Comprueba si una propiedad está o no definida
    • ReflectionClass::implementsInterface — Comprueba si se implementa una determinada interfaz
    • ReflectionClass::inNamespace — Comprueba si pertenece a un determinado espacio de nombres
    • ReflectionClass::isAbstract — Comprueba si la clase es abstracta
    • ReflectionClass::isAnonymous — Checks if class is anonymous
    • ReflectionClass::isCloneable — Comprueba si la clase es o no clonable
    • ReflectionClass::isFinal — Comprueba si la clase inal
    • ReflectionClass::isInstance — Comprueba si un objeto es instancia de la clase
    • ReflectionClass::isInstantiable — Comprueba si una clase es instanciable
    • ReflectionClass::isInterface — Comprueba una la clase es una interfaz
    • ReflectionClass::isInternal — Comprueba si una clase está definida internamente por una extensión o por el núcleo
    • ReflectionClass::isIterable — Check whether this class is iterable
    • ReflectionClass::isIterateable — Comprueba si es iterable
    • ReflectionClass::isSubclassOf — Comprueba si es una subclase
    • ReflectionClass::isTrait — Comprueba si es un trait
    • ReflectionClass::isUserDefined — Comprueba si es una clase definida por el usuario
    • ReflectionClass::newInstance — Crea una nueva instancia de clase a partir de la lista de parámetros dados
    • ReflectionClass::newInstanceArgs — Crea una nueva instancia de clase a partir de los argumentos dados
    • ReflectionClass::newInstanceWithoutConstructor — Crea una nueva clase sin invocar al constructor
    • ReflectionClass::setStaticPropertyValue — Establece el valor de una propiedad estática
    • ReflectionClass::__toString — Devuelve la representación en forma de string del objeto ReflectionClass
  • ReflectionClassConstant — The ReflectionClassConstant class
    • ReflectionClassConstant::__construct — Constructs a ReflectionClassConstant
    • ReflectionClassConstant::export — Export
    • ReflectionClassConstant::getDeclaringClass — Gets declaring class
    • ReflectionClassConstant::getDocComment — Gets doc comments
    • ReflectionClassConstant::getModifiers — Gets the class constant modifiers
    • ReflectionClassConstant::getName — Get name of the constant
    • ReflectionClassConstant::getValue — Gets value
    • ReflectionClassConstant::isPrivate — Checks if class constant is private
    • ReflectionClassConstant::isProtected — Checks if class constant is protected
    • ReflectionClassConstant::isPublic — Checks if class constant is public
    • ReflectionClassConstant::__toString — Returns the string representation of the ReflectionClassConstant object
  • ReflectionZendExtension — Clase ReflectionZendExtension
    • ReflectionZendExtension::__clone — Clon de controlador
    • ReflectionZendExtension::__construct — Constructor
    • ReflectionZendExtension::export — Exportar
    • ReflectionZendExtension::getAuthor — Consultar autor
    • ReflectionZendExtension::getCopyright — Consultar los derechos de copia
    • ReflectionZendExtension::getName — Obtiene el nombre
    • ReflectionZendExtension::getURL — Obtiene la URL
    • ReflectionZendExtension::getVersion — Obtiene la versión
    • ReflectionZendExtension::__toString — Convierte a texto
  • ReflectionExtension — Clase ReflectionExtension
    • ReflectionExtension::__clone — Clonar
    • ReflectionExtension::__construct — Constructor de los objetos ReflectionExtension
    • ReflectionExtension::export — Exportar
    • ReflectionExtension::getClasses — Obtiene clases
    • ReflectionExtension::getClassNames — Obtiene nombres de las clases
    • ReflectionExtension::getConstants — Obtiene las constantes
    • ReflectionExtension::getDependencies — Obtiene las dependencias
    • ReflectionExtension::getFunctions — Obtiene las funciones de una extensión
    • ReflectionExtension::getINIEntries — Obtiene las entradas INI de la extensión
    • ReflectionExtension::getName — Obtiene el nombre de la extensión
    • ReflectionExtension::getVersion — Obtiene la versión de una extensión
    • ReflectionExtension::info — Imprime información sobre la extensión
    • ReflectionExtension::isPersistent — Indica si la extensión es persistente
    • ReflectionExtension::isTemporary — Indica si la extensión es temporal
    • ReflectionExtension::__toString — Convertir a string
  • ReflectionFunction — Clase ReflectionFunction
    • ReflectionFunction::__construct — Contruye un objeto de tipo ReflectionFunction
    • ReflectionFunction::export — Exporta una función
    • ReflectionFunction::getClosure — Genera dinámicamente una función anónima de esta función
    • ReflectionFunction::invoke — Invoca una función
    • ReflectionFunction::invokeArgs — Invoca a la función con argumentos
    • ReflectionFunction::isDisabled — Comprueba si una función está desactivada
    • ReflectionFunction::__toString — Convertir a string
  • ReflectionFunctionAbstract — Clase ReflectionFunctionAbstract
    • ReflectionFunctionAbstract::__clone — Clona una función
    • ReflectionFunctionAbstract::getClosureScopeClass — Devuelve el ámbito asociado al cierre
    • ReflectionFunctionAbstract::getClosureThis — Devuelve una función anónima que apunta a esta función
    • ReflectionFunctionAbstract::getDocComment — Obtiene comentarios de documentación
    • ReflectionFunctionAbstract::getEndLine — Obtiene número de linea final
    • ReflectionFunctionAbstract::getExtension — Obtiene información sobre la extensión
    • ReflectionFunctionAbstract::getExtensionName — Obtiene el nombre de la extensión
    • ReflectionFunctionAbstract::getFileName — Obtiene el nombre del fichero
    • ReflectionFunctionAbstract::getName — Obtiene el nombre de la función
    • ReflectionFunctionAbstract::getNamespaceName — Obtiene el nombre del espacio de nombres
    • ReflectionFunctionAbstract::getNumberOfParameters — Obtiene el número total de parámetros
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters — Obtiene el número de parámetros obligatorios
    • ReflectionFunctionAbstract::getParameters — Obtiene los parámetros
    • ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function
    • ReflectionFunctionAbstract::getShortName — Obtiene el nombre abreviado de la función
    • ReflectionFunctionAbstract::getStartLine — Obtiene el número de la línea de inicio
    • ReflectionFunctionAbstract::getStaticVariables — Obtiene las variable estáticas
    • ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type
    • ReflectionFunctionAbstract::inNamespace — Comprueba si pertenece a un espacio de nombres
    • ReflectionFunctionAbstract::isClosure — Comprobar si es un cierre
    • ReflectionFunctionAbstract::isDeprecated — Comprueba si está obsoleta
    • ReflectionFunctionAbstract::isGenerator — Devuelve si la función es un generador
    • ReflectionFunctionAbstract::isInternal — Comprueba si la función es interna
    • ReflectionFunctionAbstract::isUserDefined — Comprueba si es una función definida por un usuario
    • ReflectionFunctionAbstract::isVariadic — Comprueba si la función es varíadica
    • ReflectionFunctionAbstract::returnsReference — Comprueba si devuelve una referencia
    • ReflectionFunctionAbstract::__toString — Convertir a texto
  • ReflectionMethod — La clase ReflectionMethod
    • ReflectionMethod::__construct — Construye un objeto ReflectionMethod
    • ReflectionMethod::export — Exporta un objeto de tipo ReflectionMethod
    • ReflectionMethod::getClosure — Devuelve un cierre creado dinámicamente para este método
    • ReflectionMethod::getDeclaringClass — Obtiene la clase en la que se ha declarado el método
    • ReflectionMethod::getModifiers — Obtiene los modificadores del método
    • ReflectionMethod::getPrototype — Obtiene el prototipo del método (si lo hubiera)
    • ReflectionMethod::invoke — Invoca un método
    • ReflectionMethod::invokeArgs — Invoca un método con argumentos
    • ReflectionMethod::isAbstract — Comprueba si el método es abstracto
    • ReflectionMethod::isConstructor — Comprueba si el método es un constructor
    • ReflectionMethod::isDestructor — Comprueba si el método es un destructor
    • ReflectionMethod::isFinal — Comprueba si el método es final
    • ReflectionMethod::isPrivate — Comprueba si el método es privado
    • ReflectionMethod::isProtected — Comprueba si el método está protegido
    • ReflectionMethod::isPublic — Comprueba si el método es público
    • ReflectionMethod::isStatic — Comprueba si el método es estático
    • ReflectionMethod::setAccessible — Asigna la accesibilidad del método
    • ReflectionMethod::__toString — Devuelve la representación en forma de texto de este objeto
  • ReflectionNamedType — The ReflectionNamedType class
    • ReflectionNamedType::getName — Get the text of the type hint
    • ReflectionNamedType::isBuiltin — Checks if it is a built-in type
  • ReflectionObject — Clase ReflectionObject
    • ReflectionObject::__construct — Construye un ReflectionObject
    • ReflectionObject::export — Exportación
  • ReflectionParameter — La clase ReflectionParameter
    • ReflectionParameter::allowsNull — Comprueba si null es permitido
    • ReflectionParameter::canBePassedByValue — Devuelve si este parámetro de puede pasar por valor
    • ReflectionParameter::__clone — Clon
    • ReflectionParameter::__construct — Construct
    • ReflectionParameter::export — Exportar
    • ReflectionParameter::getClass — Obtener la clase con declaraciones de tipos
    • ReflectionParameter::getDeclaringClass — Obtiene declaración de la clase
    • ReflectionParameter::getDeclaringFunction — Obtiene declaración de función
    • ReflectionParameter::getDefaultValue — Obtiene el valor del parámetro por defecto
    • ReflectionParameter::getDefaultValueConstantName — Devuelve el nombre de la consntante del valor predeterminado si el valor predeterminado es constante o null
    • ReflectionParameter::getName — Obtener el nombre del parámetro
    • ReflectionParameter::getPosition — Obtiene la posición del parámetro
    • ReflectionParameter::getType — Gets a parameter's type
    • ReflectionParameter::hasType — Checks if parameter has a type
    • ReflectionParameter::isArray — Comprueba si el parámetro espera un array
    • ReflectionParameter::isCallable — Devuelve si el parámetro DEBE ser de tipo callable
    • ReflectionParameter::isDefaultValueAvailable — Comprueba si el valor por defecto está disponible
    • ReflectionParameter::isDefaultValueConstant — Devuelve si el valor predeterminado de este parámetro es constante
    • ReflectionParameter::isOptional — Comprueba si es opcional
    • ReflectionParameter::isPassedByReference — Comprueba si es pasado por referencia
    • ReflectionParameter::isVariadic — Comprueba si el parámetro es varíadico
    • ReflectionParameter::__toString — A string
  • ReflectionProperty — Clase ReflectionProperty
    • ReflectionProperty::__clone — Clonar
    • ReflectionProperty::__construct — Construir un objeto ReflectionProperty
    • ReflectionProperty::export — Exportar
    • ReflectionProperty::getDeclaringClass — Obtiene la clase en la que se declaró
    • ReflectionProperty::getDefaultValue — Returns the default value declared for a property
    • ReflectionProperty::getDocComment — Obtiene los comentarios de documentación de una propiedad
    • ReflectionProperty::getModifiers — Obtiene los modificadores
    • ReflectionProperty::getName — Obtiene el nombre de la propiedad
    • ReflectionProperty::getType — Gets a property's type
    • ReflectionProperty::getValue — Obtiene el valor
    • ReflectionProperty::hasDefaultValue — Checks if property has a default value declared
    • ReflectionProperty::hasType — Checks if property has a type
    • ReflectionProperty::isDefault — Comprueba si una propiedad es predeterminada
    • ReflectionProperty::isInitialized — Checks whether a property is initialized
    • ReflectionProperty::isPrivate — Comprueba si una propiedad es privada
    • ReflectionProperty::isProtected — Comprueba si la propiedad es protegida
    • ReflectionProperty::isPublic — Comprueba si la propiedad es pública
    • ReflectionProperty::isStatic — Comprueba si la propiedad es estática
    • ReflectionProperty::setAccessible — Hace accesible una propiedad
    • ReflectionProperty::setValue — Establece el valor de la propiedad
    • ReflectionProperty::__toString — Convertir a texto
  • ReflectionType — The ReflectionType class
    • ReflectionType::allowsNull — Checks if null is allowed
    • ReflectionType::__toString — To string
  • ReflectionUnionType — The ReflectionUnionType class
    • ReflectionUnionType::getTypes — Returns the types included in the union type
  • ReflectionGenerator — The ReflectionGenerator class
    • ReflectionGenerator::__construct — Constructs a ReflectionGenerator object
    • ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator
    • ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object
    • ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator
    • ReflectionGenerator::getFunction — Gets the function name of the generator
    • ReflectionGenerator::getThis — Gets the $this value of the generator
    • ReflectionGenerator::getTrace — Gets the trace of the executing generator
  • ReflectionReference — The ReflectionReference class
    • ReflectionReference::fromArrayElement — Create a ReflectionReference from an array element
    • ReflectionReference::getId — Get unique ID of a reference
  • Reflector — La interfaz Reflector
    • Reflector::export — Exportar
    • Reflector::__toString — Convertir a String
  • ReflectionException — La clase ReflectionException

User Contributed Notes

There are no user contributed notes for this page.


Introducción

PHP viene con una API de reflexión completa que añade la capacidad para realizar ingeniería inversa de clases, interfaces, funciones, métodos y extensiones. Además, la API de reflexión ofrece varias formas de obtener comentarios de documentación de funciones, clases y métodos.

Tenga en cuenta que ciertas partes de la API interna no contienen el código necesario para trabajar con la extensión Reflection. Por ejemplo, a una clase interna de PHP le pueden faltar datos de reflexión de sus propiedades. Sin embargo, estos pocos casos son considerados como errores, por lo que deberían ser descubiertos y corregidos.

User Contributed Notes

There are no user contributed notes for this page.


Constantes predefinidas

Cada clase describe sus propias constantes.

User Contributed Notes

sadisticnepal3339 at gmail dot com 27-Mar-2018 11:35
PHP user-defined constant can be like this:

define('APP',
[
  'name'=>'Sadish',
  'hobby'=>'Coding',
   'occupation'=>'student'
]);

Here, APP is the user-defined constant which is defined using define() function available in PHP.

Also, Simply anything, like this :
  define('APP','Demo PHP');
 is a user-defined constant, which basically replaces any code available in PHP named as APP with the value 'Demo PHP'.


Ejemplos

Existen muchos ejemplos en la documentación de Reflection, por lo general dentro de la documentación de __construct de cada clase.

Ejemplo #1 Ejemplo de Reflection desde Shell (un terminal)

$ php --rf strlen
$ php --rc finfo
$ php --re json
$ php --ri dom

El resultado del ejemplo sería algo similar a:

Function [ <internal:Core> function strlen ] {

  - Parameters [1] {
    Parameter #0 [ <required> $str ]
  }
}

Class [ <internal:fileinfo> class finfo ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [4] {
    Method [ <internal:fileinfo, ctor> public method finfo ] {

      - Parameters [2] {
        Parameter #0 [ <optional> $options ]
        Parameter #1 [ <optional> $arg ]
      }
    }

    Method [ <internal:fileinfo> public method set_flags ] {

      - Parameters [1] {
        Parameter #0 [ <required> $options ]
      }
    }

    Method [ <internal:fileinfo> public method file ] {

      - Parameters [3] {
        Parameter #0 [ <required> $filename ]
        Parameter #1 [ <optional> $options ]
        Parameter #2 [ <optional> $context ]
      }
    }

    Method [ <internal:fileinfo> public method buffer ] {

      - Parameters [3] {
        Parameter #0 [ <required> $string ]
        Parameter #1 [ <optional> $options ]
        Parameter #2 [ <optional> $context ]
      }
    }
  }
}

Extension [ <persistent> extension #23 json version 1.2.1 ] {

  - Constants [10] {
    Constant [ integer JSON_HEX_TAG ] { 1 }
    Constant [ integer JSON_HEX_AMP ] { 2 }
    Constant [ integer JSON_HEX_APOS ] { 4 }
    Constant [ integer JSON_HEX_QUOT ] { 8 }
    Constant [ integer JSON_FORCE_OBJECT ] { 16 }
    Constant [ integer JSON_ERROR_NONE ] { 0 }
    Constant [ integer JSON_ERROR_DEPTH ] { 1 }
    Constant [ integer JSON_ERROR_STATE_MISMATCH ] { 2 }
    Constant [ integer JSON_ERROR_CTRL_CHAR ] { 3 }
    Constant [ integer JSON_ERROR_SYNTAX ] { 4 }
  }

  - Functions {
    Function [ <internal:json> function json_encode ] {

      - Parameters [2] {
        Parameter #0 [ <required> $value ]
        Parameter #1 [ <optional> $options ]
      }
    }
    Function [ <internal:json> function json_decode ] {

      - Parameters [3] {
        Parameter #0 [ <required> $json ]
        Parameter #1 [ <optional> $assoc ]
        Parameter #2 [ <optional> $depth ]
      }
    }
    Function [ <internal:json> function json_last_error ] {

      - Parameters [0] {
      }
    }
  }
}

dom

DOM/XML => enabled
DOM/XML API Version => 20031129
libxml Version => 2.7.3
HTML Support => enabled
XPath Support => enabled
XPointer Support => enabled
Schema Support => enabled
RelaxNG Support => enabled

User Contributed Notes

paulo dot castro48 at gmail dot com 19-Feb-2017 02:18
Note: This is useful when you're manually parsing php by file before to get work done, wich is impossible to do without getting files externally.
Now you can parse without getting the file contents by using refection objects.
spectrum at bigmir dot net 28-Dec-2010 02:11
Simple table generation using Reflection:

<?php

class A
{
    public    $name = 'Vasiliy';
    public    $text = 'Once upon a time';
}

class B
{
    public    $name = 'Had bought a cat';
    public    $text = 'named Valentine';
}

class grid
{
    public function build(  $dataSource, $headers, $fields  )
    {
        $result = '<table border="1">';
        $result .= $this -> make_head( $headers );

        foreach ($dataSource as $source):
            $class_name = get_class($source);
            if ( $class_name != FALSE ):
                $reflector = new ReflectionClass($source);
                echo 'Class "'. $class_name .'" found.<br />';
                $result .= $this -> make_row( $reflector, $fields, $source );
            endif;
        endforeach;

        $result .= '</table>';
        return $result;
    }

    private function make_head( $headers )
    {
        $result = '<tr>';
        foreach ( $headers as $header):
            $result .= "<th>$header</th>";
        endforeach;
        $result .= '</tr>';
        return $result;
    }

    private function make_row( $reflector, $fields, $source )
    {
        $result = '<tr>';
        foreach ( $fields as $field ):
            if ( $reflector -> hasProperty($field) ):
                $property = $reflector -> getProperty($field);
                $result .= '<td>'. $property -> getValue($source) .'</td>';
            endif;
        endforeach;
        $result .= '</tr>';
        return $result;
    }
}

$A = new A;
$B = new B;
$C = 'Test';

$dataSource = array( $A, $B, $C );
$headers = array( 'H1', 'H2' );
$fields = array( 'name', 'text' );

$grid = new grid;
$table = $grid -> build( $dataSource, $headers, $fields );
echo $table;

?>
Kovin 18-May-2009 02:00
If you want to use method closures and don't have PHP 5.3, perhaps you find useful the following function
<?php
    function get_method_closure($object,$method_name){
        if(method_exists(get_class($object),$method_name)){
            $func            = create_function( '',
                            '
                                $args            = func_get_args();
                                static $object    = NULL;

                                /*
                                * Check if this function is being called to set the static $object, which
                                * containts scope information to invoke the method
                                */
                                if(is_null($object) && count($args) && get_class($args[0])=="'.get_class($object).'"){
                                    $object = $args[0];
                                    return;
                                }

                                if(!is_null($object)){
                                    return call_user_func_array(array($object,"'.$method_name.'"),$args);
                                }else{
                                    return FALSE;
                                }'
                            );

            //Initialize static $object
            $func($object);

            //Return closure
            return $func;
        }else{
            return false;
        }
    }
?>
Here is how you would use it:
<?php
class foo{
    public function bar($foo){
        return strtolower($foo);
    }
}

$foo = new foo();
$f = get_method_closure($foo,'bar');
echo $f("BAR");//Prints 'bar'
?>


Extensión

Si se deseara crear versiones especializadas de las clases que vienen incorporadas (por ejemplo, para crear HTML en color cuando se exportan, parar tener variables de acceso rápido en lugar de usar métodos, o parar crear métodos auxiliares), deberá extender la clase.

Ejemplo #1 Extendiendo las clases incorporadas

<?php
/**
 * Mi clase Reflection_Method
 */
class My_Reflection_Method extends ReflectionMethod
{
    public $visibility = array();

    public function __construct($o, $m)
    {
        parent::__construct($o, $m);
        $this->visibility = Reflection::getModifierNames($this->getModifiers());
    }
}

/**
 * Clase demo #1
 *
 */
class T {
    protected function x() {}
}

/**
 * Clase demo #2
 *
 */
class U extends T {
    function x() {}
}

// Mostrar información
var_dump(new My_Reflection_Method('U', 'x'));
?>

El resultado del ejemplo sería algo similar a:

object(My_Reflection_Method)#1 (3) {
  ["visibility"]=>
  array(1) {
    [0]=>
    string(6) "public"
  }
  ["name"]=>
  string(1) "x"
  ["class"]=>
  string(1) "U"
}
Precaución

Si se sobrescribe el constructor, no hay que olvidar llamar en primer lugar al constructor de la clase padre. Si esto fallara, se lanzará el siguiente error: Fatal error: Internal error: Failed to retrieve the reflection object

User Contributed Notes

khelaz at gmail dot com 28-Apr-2011 11:12
Extending class ReflectionFunction to get source code of function

<?php
class Custom_Reflection_Function extends ReflectionFunction {

    public function getSource() {
        if( !file_exists( $this->getFileName() ) ) return false;

        $start_offset = ( $this->getStartLine() - 1 );
        $end_offset   = ( $this->getEndLine() - $this->getStartLine() ) + 1;

        return join( '', array_slice( file( $this->getFileName() ), $start_offset, $end_offset ) );
    }
}
?>


Clase Reflection

(PHP 5, PHP 7)

Introducción

Clase reflection.

Sinopsis de la Clase

Reflection {
/* Métodos */
public static export ( Reflector $reflector , bool $return = false ) : string
public static getModifierNames ( int $modifiers ) : array
}

Tabla de contenidos

  • Reflection::export — Exportar
  • Reflection::getModifierNames — Obtener nombres de modificadores

User Contributed Notes

apmithani at yahoo dot com 26-Aug-2010 09:05
Here is a code snippet for some of us who are just beginning with reflection. I have a simple class below with two properties and two methods. We will use reflection classes to populate the properties dynamically and then print them:

<?php

class A
{
    public $one = '';
    public $two = '';

    //Constructor
    public function __construct()
    {
        //Constructor
    }

    //print variable one
    public function echoOne()
    {
        echo $this->one."\n";
    }

    //print variable two
    public function echoTwo()
    {
        echo $this->two."\n";
    }
}

//Instantiate the object
$a = new A();

//Instantiate the reflection object
$reflector = new ReflectionClass('A');

//Now get all the properties from class A in to $properties array
$properties = $reflector->getProperties();

$i =1;
//Now go through the $properties array and populate each property
foreach($properties as $property)
{
    //Populating properties
    $a->{$property->getName()}=$i;
    //Invoking the method to print what was populated
    $a->{"echo".ucfirst($property->getName())}()."\n";

    $i++;
}

?>


Exportar

  • « Reflection
  • Reflection::getModifierNames »
  • PHP Manual
  • Reflection
  • Exportar

Reflection::export

(PHP 5, PHP 7)

Reflection::export — Exportar

Descripción

public static Reflection::export ( Reflector $reflector , bool $return = false ) : string

Exporta una reflexión.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

reflector

La reflexión a exportar.

return

Configurarlo a true devolverá la exportación, a diferencia de emitirla. Configurarlo a false (el valor por defecto) hará lo contrario.

Valores devueltos

Si el parámetro return es seteado a true, la exportación se devolverá como un string, de lo contrario se retornará null.

Ver también

  • Reflection::getModifierNames() - Obtener nombres de modificadores

User Contributed Notes

There are no user contributed notes for this page.


Obtener nombres de modificadores

  • « Reflection::export
  • ReflectionClass »
  • PHP Manual
  • Reflection
  • Obtener nombres de modificadores

Reflection::getModifierNames

(PHP 5, PHP 7)

Reflection::getModifierNames — Obtener nombres de modificadores

Descripción

public static Reflection::getModifierNames ( int $modifiers ) : array

Obtiene los nombres de los modificadores.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

modifiers

Modificadores que se desean obtener, a partir de un valor numérico.

Valores devueltos

Un array con nombres de modificadores.

Ver también

  • Reflection::export() - Exportar

User Contributed Notes

There are no user contributed notes for this page.


Clase ReflectionClass

(PHP 5, PHP 7)

Introducción

La clase ReflectionClass devuelve información sobre una clase.

Sinopsis de la Clase

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

Propiedades

name

Nombre de la clase. De sólo lectura, lanza una ReflectionException en el intento de escribir.

Constantes predefinidas

Modificadores ReflectionClass

ReflectionClass::IS_IMPLICIT_ABSTRACT

Indica que la clase es abstract porque esta tiene algunos métodos abstractos.

ReflectionClass::IS_EXPLICIT_ABSTRACT

Indica que la clase es abstract debido a su definición.

ReflectionClass::IS_FINAL

Indica la clase final.

Tabla de contenidos

  • ReflectionClass::__construct — Construye un objeto de tipo ReflectionClass
  • ReflectionClass::export — Exporta una clase
  • ReflectionClass::getConstant — Obtener una constante definida
  • ReflectionClass::getConstants — Obtener constantes
  • ReflectionClass::getConstructor — Obtiene el constructor de una clase
  • ReflectionClass::getDefaultProperties — Obtener propiedades predeterminadas
  • ReflectionClass::getDocComment — Obtener los comentarios de documentación
  • ReflectionClass::getEndLine — Consultar línea final
  • ReflectionClass::getExtension — Obtiene un objeto ReflectionExtension para la extensión que definió la clase
  • ReflectionClass::getExtensionName — Obtiene el nombre de la extensión que definió una clase
  • ReflectionClass::getFileName — Obtiene el nombre de fichero en el que está definida la clase
  • ReflectionClass::getInterfaceNames — Obtiene nombres de las interfaces
  • ReflectionClass::getInterfaces — Obtiene las interfaces
  • ReflectionClass::getMethod — Obtiene un objeto ReflectionMethod para un método de una clase
  • ReflectionClass::getMethods — Obtiene un array de métodos
  • ReflectionClass::getModifiers — Obtiene los modificadores de clase
  • ReflectionClass::getName — Obtiene el nombre de la clase
  • ReflectionClass::getNamespaceName — Obtiene el nombre del espacio de nombres
  • ReflectionClass::getParentClass — Obtiene la clase padre
  • ReflectionClass::getProperties — Obtiene las propiedades
  • ReflectionClass::getProperty — Obtiene un objeto ReflectionProperty para una propiedad de una clase
  • ReflectionClass::getReflectionConstant — Gets a ReflectionClassConstant for a class's constant
  • ReflectionClass::getReflectionConstants — Gets class constants
  • ReflectionClass::getShortName — Obtiene el nombre abreviado
  • ReflectionClass::getStartLine — Obtiene el número de linea de inicio
  • ReflectionClass::getStaticProperties — Obtiene las propiedades estáticas
  • ReflectionClass::getStaticPropertyValue — Obtiene el valor de una propiedad estática
  • ReflectionClass::getTraitAliases — Obtiene un array con los alias usados con los traits
  • ReflectionClass::getTraitNames — Devuelve un array con los nombres de los traits usados por esta clase
  • ReflectionClass::getTraits — Obtiene un array con los traits que utiliza esta clase
  • ReflectionClass::hasConstant — Comprueba si una constante está o no definida
  • ReflectionClass::hasMethod — Comprueba si un método está o no definido
  • ReflectionClass::hasProperty — Comprueba si una propiedad está o no definida
  • ReflectionClass::implementsInterface — Comprueba si se implementa una determinada interfaz
  • ReflectionClass::inNamespace — Comprueba si pertenece a un determinado espacio de nombres
  • ReflectionClass::isAbstract — Comprueba si la clase es abstracta
  • ReflectionClass::isAnonymous — Checks if class is anonymous
  • ReflectionClass::isCloneable — Comprueba si la clase es o no clonable
  • ReflectionClass::isFinal — Comprueba si la clase inal
  • ReflectionClass::isInstance — Comprueba si un objeto es instancia de la clase
  • ReflectionClass::isInstantiable — Comprueba si una clase es instanciable
  • ReflectionClass::isInterface — Comprueba una la clase es una interfaz
  • ReflectionClass::isInternal — Comprueba si una clase está definida internamente por una extensión o por el núcleo
  • ReflectionClass::isIterable — Check whether this class is iterable
  • ReflectionClass::isIterateable — Comprueba si es iterable
  • ReflectionClass::isSubclassOf — Comprueba si es una subclase
  • ReflectionClass::isTrait — Comprueba si es un trait
  • ReflectionClass::isUserDefined — Comprueba si es una clase definida por el usuario
  • ReflectionClass::newInstance — Crea una nueva instancia de clase a partir de la lista de parámetros dados
  • ReflectionClass::newInstanceArgs — Crea una nueva instancia de clase a partir de los argumentos dados
  • ReflectionClass::newInstanceWithoutConstructor — Crea una nueva clase sin invocar al constructor
  • ReflectionClass::setStaticPropertyValue — Establece el valor de una propiedad estática
  • ReflectionClass::__toString — Devuelve la representación en forma de string del objeto ReflectionClass

User Contributed Notes

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

<?php

class test
{
    private $test = "";

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

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

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

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

<?php

class X {

}

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

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

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

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

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

So instead of:

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

You would type:

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


Construye un objeto de tipo ReflectionClass

  • « ReflectionClass
  • ReflectionClass::export »
  • PHP Manual
  • ReflectionClass
  • Construye un objeto de tipo ReflectionClass

ReflectionClass::__construct

(PHP 5, PHP 7)

ReflectionClass::__construct — Construye un objeto de tipo ReflectionClass

Descripción

public ReflectionClass::__construct ( mixed $argument )

Construye un nuevo objeto ReflectionClass.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

argument

O bien un string con el nombre de la clase a reflexionar, o un object.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Funcionamiento básico de ReflectionClass

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

El resultado del ejemplo sería algo similar a:

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

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

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

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

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

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

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

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

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

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

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

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

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

Ver también

  • ReflectionObject::__construct() - Construye un ReflectionObject
  • Constructores

User Contributed Notes

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

So instead of:

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

You would type:

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

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

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

From there, you can than call:

$class = new ReflectionClass($classname);

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

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

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

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

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

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

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

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

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

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

<?php

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

?>

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

<?php

  interface Edible
  {
    public function eat();
  }

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

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


Exporta una clase

  • « ReflectionClass::__construct
  • ReflectionClass::getConstant »
  • PHP Manual
  • ReflectionClass
  • Exporta una clase

ReflectionClass::export

(PHP 5, PHP 7)

ReflectionClass::export — Exporta una clase

Descripción

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

Exporta una clase reflejada.

Parámetros

argument

La reflexión a exportar.

return

Configurarlo a true devolverá la exportación, a diferencia de emitirla. Configurarlo a false (el valor por defecto) hará lo contrario.

Valores devueltos

Si el parámetro return es seteado a true, la exportación se devolverá como un string, de lo contrario se retornará null.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::export()

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

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

El resultado del ejemplo sería algo similar a:

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

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

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

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

Ver también

  • ReflectionClass::getName() - Obtiene el nombre de la clase

User Contributed Notes

There are no user contributed notes for this page.


Obtener una constante definida

  • « ReflectionClass::export
  • ReflectionClass::getConstants »
  • PHP Manual
  • ReflectionClass
  • Obtener una constante definida

ReflectionClass::getConstant

(PHP 5, PHP 7)

ReflectionClass::getConstant — Obtener una constante definida

Descripción

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

Devuelve la constante definida.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

name

Nombre de la constante.

Valores devueltos

Valor de la constante.

Ver también

  • ReflectionClass::getConstants() - Obtener constantes

User Contributed Notes

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

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

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

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

?>

output:
Number one
Number two


Obtener constantes

  • « ReflectionClass::getConstant
  • ReflectionClass::getConstructor »
  • PHP Manual
  • ReflectionClass
  • Obtener constantes

ReflectionClass::getConstants

(PHP 5, PHP 7)

ReflectionClass::getConstants — Obtener constantes

Descripción

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

Obtiene todas las constantes definidas de una clase, independientemente de su visibilidad.

Parámetros

filter

El filtro opcional, para filtrar las visibilidades constantes deseadas. Se configura utiliando las constantes de ReflectionClassConstant, y por omisión tiene todas las constantes visibles.

Valores devueltos

Un array de constantes. El nombre de la constante en la clave, y en el valor, el valor de la constante.

Historial de cambios

Versión | Descripción
8.0.0 | Se añadió el parámetro filter.

Ver también

  • ReflectionClass::getConstant() - Obtener una constante definida

User Contributed Notes

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

abstract class AbstractEnum
{
    /**
     * ?????????? ??? ????????? ?????? || Return all constants
     *
     * @return array
     */
    static function getConstants()
    {
        $rc = new \ReflectionClass(get_called_class());

        return $rc->getConstants();
    }

    /**
     * ?????????? ?????? ???????? ???????????? ? ?????????? ??????  || Return last constants
     *
     * @return array
     */
    static function lastConstants()
    {
        $parentConstants = static::getParentConstants();

        $allConstants = static::getConstants();

        return array_diff($allConstants, $parentConstants);
    }

    /**
     * ?????????? ??? ????????? ???????????? ??????? || Return parent constants
     *
     * @return array
     */
    static function getParentConstants()
    {
        $rc = new \ReflectionClass(get_parent_class(static::class));
        $consts = $rc->getConstants();

        return $consts;
    }
}

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

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

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

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

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

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

<?php

abstract class AbstractClass
{
    const TEST = "test";

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

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

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

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

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

<?php

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

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

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

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

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

    // others...

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

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

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

1st File:

constants.php

<?php
<?php>

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

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

test.php

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

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

what you would get from the command line:-

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

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

Enjoy!


Obtiene el constructor de una clase

  • « ReflectionClass::getConstants
  • ReflectionClass::getDefaultProperties »
  • PHP Manual
  • ReflectionClass
  • Obtiene el constructor de una clase

ReflectionClass::getConstructor

(PHP 5, PHP 7)

ReflectionClass::getConstructor — Obtiene el constructor de una clase

Descripción

public ReflectionClass::getConstructor ( ) : ReflectionMethod

Obtiene el constructor de la clase reflejada.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un objeto ReflectionMethod que refleja el constructor de la clase, o null si la clase no tiene constructor.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::getConstructor()

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

El resultado del ejemplo sería:

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

Ver también

  • ReflectionClass::getName() - Obtiene el nombre de la clase

User Contributed Notes

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

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

<?php

class SomeClass {

    function SomeClass($some_arg) {
    }

}

$refl = new ReflectionClass('SomeClass');

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

echo $refl->getConstructor();

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

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

?>

Some more behavior:

<?php

class SomeClass {

   function funcA($arg1, $arg2) {

   }

}

$refl = new ReflectionClass('SomeClass');

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

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

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

class AnotherClass {

   private function __construct() {
   }

   function funcB($arg1, $arg2) {

   }

}

$refl = new ReflectionClass('AnotherClass');

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

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

?>

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

<?php

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

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

$class = new ReflectionClass('Say');

$constructor = $class->getConstructor();

echo $constructor;

/*     OUTPUTS:

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

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

*/

$parameters = $constructor->getParameters();

var_export($parameters);

/*    OUTPUT:

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

*/

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

/*    OUTPUT:

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

*/

?>

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

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

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


Obtener propiedades predeterminadas

  • « ReflectionClass::getConstructor
  • ReflectionClass::getDocComment »
  • PHP Manual
  • ReflectionClass
  • Obtener propiedades predeterminadas

ReflectionClass::getDefaultProperties

(PHP 5, PHP 7)

ReflectionClass::getDefaultProperties — Obtener propiedades predeterminadas

Descripción

public ReflectionClass::getDefaultProperties ( ) : array

Devuelve las propiedades predeterminadas de una clase (incluyendo las propiedades heredadas).

Nota:

Este método sólo funciona para las propiedades estáticas cuando se utiliza en las clases internas. El valor por defecto de una propiedad de clase estática no puede ser rastreada utilizando este método sobre las clases definidas por el usuario.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un array de propiedades predeterminadas, donde la clave es el nombre de la propiedad y el valor corresponde con el valor de la propiedad o null si la propiedad no tuviera ningún valor predeterminado. Esta función no hace distinción entre propiedades estáticas y no estáticas, y no tiene en cuenta los modificadores de visibilidad.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::getDefaultProperties()

<?php
class Bar {
    protected $propiedadHeredada = 'predeterminadoHeredada';
}

class Foo extends Bar {
    public $propiedad = 'predeterminadoPropiedad';
    private $propiedadPrivada = 'predeterminadoPropiedadPrivada';
    public static $propiedadEstatica = 'propiedadEstatica';
    public $propiedadSinValor;
}

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

El resultado del ejemplo sería:

array(5) {
   ["propiedadEstatica"]=>
   string(14) "propiedadEstatia"
   ["propiedad"]=>
   string(15) "predeterminadoPropiedad"
   ["propiedadPrivada"]=>
   string(22) "predeterminadoPropiedadPrivada"
   ["propiedadSinValor"]=>
   NULL
   ["propiedadHeredada"]=>
   string(16) "predeterminadoHeredada"
}

Ver también

  • ReflectionClass::getProperties() - Obtiene las propiedades
  • ReflectionClass::getStaticProperties() - Obtiene las propiedades estáticas
  • ReflectionClass::getProperty() - Obtiene un objeto ReflectionProperty para una propiedad de una clase

User Contributed Notes

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

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

Try it:

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

class a {

    use \static_reflector;

    protected $key_a = 'test ok';

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

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

    }
}

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

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

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


Obtener los comentarios de documentación

  • « ReflectionClass::getDefaultProperties
  • ReflectionClass::getEndLine »
  • PHP Manual
  • ReflectionClass
  • Obtener los comentarios de documentación

ReflectionClass::getDocComment

(PHP 5, PHP 7)

ReflectionClass::getDocComment — Obtener los comentarios de documentación

Descripción

public ReflectionClass::getDocComment ( ) : string

Obtiene los comentarios de documentación de una clase.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Los comentarios de documentación, o false si no existiera.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::getDocComment()

<?php
/**
* Clase de prueba
*
* @param  foo bar
* @return baz
*/
class ClaseDePrueba { }

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

El resultado del ejemplo sería:

string(55) "/**
* Clase de prueba
*
* @param  foo bar
* @return baz
*/"

Ver también

  • ReflectionClass::getName() - Obtiene el nombre de la clase

User Contributed Notes

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

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

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

class Home {

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

         #...your code here

      }

}

$object = new Home();

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

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

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

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

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

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

)

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

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

$reflector = new ReflectionClass('Example');

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

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

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

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

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

 /**
 * After namespace.
   */

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

class Foo {
}

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

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

To sum up:

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

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

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

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

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

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

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


Consultar línea final

  • « ReflectionClass::getDocComment
  • ReflectionClass::getExtension »
  • PHP Manual
  • ReflectionClass
  • Consultar línea final

ReflectionClass::getEndLine

(PHP 5, PHP 7)

ReflectionClass::getEndLine — Consultar línea final

Descripción

public ReflectionClass::getEndLine ( ) : int

Devuelve el número de la línea final de una clase definida por el usuario.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Número de la línea final de la clase definida por el usuario, o false si fuera desconocida.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::getEndLine()

<?php
// Clase de prueba
class ClaseDePrueba { }

$rc = new ReflectionClass('ClaseDePrueba');

echo $rc->getEndLine();
?>

El resultado del ejemplo sería:

3

Ver también

  • ReflectionClass::getStartLine() - Obtiene el número de linea de inicio

User Contributed Notes

There are no user contributed notes for this page.


Obtiene un objeto ReflectionExtension para la extensión que definió la clase

  • « ReflectionClass::getEndLine
  • ReflectionClass::getExtensionName »
  • PHP Manual
  • ReflectionClass
  • Obtiene un objeto ReflectionExtension para la extensión que definió la clase

ReflectionClass::getExtension

(PHP 5, PHP 7)

ReflectionClass::getExtension — Obtiene un objeto ReflectionExtension para la extensión que definió la clase

Descripción

public ReflectionClass::getExtension ( ) : ReflectionExtension

Obtiene un objeto ReflectionExtension para la extensión que definió la clase.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un objeto ReflectionExtension que representa la extensión que definió la clase, o null para clases definidas por el usuario.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::getExtension()

<?php
$clase = new ReflectionClass('ReflectionClass');
$extensión = $clase->getExtension();
var_dump($extensión);
?>

El resultado del ejemplo sería:

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

Ver también

  • ReflectionClass::getExtensionName() - Obtiene el nombre de la extensión que definió una clase

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el nombre de la extensión que definió una clase

  • « ReflectionClass::getExtension
  • ReflectionClass::getFileName »
  • PHP Manual
  • ReflectionClass
  • Obtiene el nombre de la extensión que definió una clase

ReflectionClass::getExtensionName

(PHP 5, PHP 7)

ReflectionClass::getExtensionName — Obtiene el nombre de la extensión que definió una clase

Descripción

public ReflectionClass::getExtensionName ( ) : string

Obtiene el nombre de la extensión que definió una clase.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

El nombre de la extensión que definió la clase, o false para clases definidas por el usuario.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::getExtensionName()

<?php
$clase = new ReflectionClass('ReflectionClass');
$extensión = $clase->getExtensionName();
var_dump($extensión);
?>

El resultado del ejemplo sería:

string(10) "Reflection"

Ver también

  • ReflectionClass::getExtension() - Obtiene un objeto ReflectionExtension para la extensión que definió la clase

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el nombre de fichero en el que está definida la clase

  • « ReflectionClass::getExtensionName
  • ReflectionClass::getInterfaceNames »
  • PHP Manual
  • ReflectionClass
  • Obtiene el nombre de fichero en el que está definida la clase

ReflectionClass::getFileName

(PHP 5, PHP 7)

ReflectionClass::getFileName — Obtiene el nombre de fichero en el que está definida la clase

Descripción

public ReflectionClass::getFileName ( ) : string

Devuelve el nombre del fichero en el que está definida la clase.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve el nombre del fichero en el que está definida la clase. Si la clase estuviera definida en el nucleo de PHP o en una extensión de PHP, se devolvería false.

Ver también

  • ReflectionClass::getExtensionName() - Obtiene el nombre de la extensión que definió una clase

User Contributed Notes

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

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

var_dump($a->getFileName());

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


Obtiene nombres de las interfaces

  • « ReflectionClass::getFileName
  • ReflectionClass::getInterfaces »
  • PHP Manual
  • ReflectionClass
  • Obtiene nombres de las interfaces

ReflectionClass::getInterfaceNames

(PHP 5 >= 5.2.0, PHP 7)

ReflectionClass::getInterfaceNames — Obtiene nombres de las interfaces

Descripción

public ReflectionClass::getInterfaceNames ( ) : array

Devuelve los nombres de las interfaces.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Array numérico con el nombre de las interfaces en el valor.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::getInterfaceNames()

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

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

El resultado del ejemplo sería algo similar a:

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

Ver también

  • ReflectionClass::getInterfaces() - Obtiene las interfaces

User Contributed Notes

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

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

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

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

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

class Test5 extends Test1 implements Other {}

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

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

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

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

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

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

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

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


Obtiene las interfaces

  • « ReflectionClass::getInterfaceNames
  • ReflectionClass::getMethod »
  • PHP Manual
  • ReflectionClass
  • Obtiene las interfaces

ReflectionClass::getInterfaces

(PHP 5, PHP 7)

ReflectionClass::getInterfaces — Obtiene las interfaces

Descripción

public ReflectionClass::getInterfaces ( ) : array

Devuelve las interfaces.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

array asociativo de interfaces, donde los nombres se usan como claves, y los objetos ReflectionClass como valor.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::getInterfaces()

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

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

El resultado del ejemplo sería algo similar a:

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

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

)

Ver también

  • ReflectionClass::getInterfaceNames() - Obtiene nombres de las interfaces

User Contributed Notes

There are no user contributed notes for this page.


Obtiene un objeto ReflectionMethod para un método de una clase

  • « ReflectionClass::getInterfaces
  • ReflectionClass::getMethods »
  • PHP Manual
  • ReflectionClass
  • Obtiene un objeto ReflectionMethod para un método de una clase

ReflectionClass::getMethod

(PHP 5, PHP 7)

ReflectionClass::getMethod — Obtiene un objeto ReflectionMethod para un método de una clase

Descripción

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

Obtiene un objeto ReflectionMethod para un método de una clase.

Parámetros

name

El nombre de método a reflejar.

Valores devueltos

Un objeto ReflectionMethod.

Errores/Excepciones

Una excepción ReflectionException si el método no existe.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::getMethod()

<?php
$clase = new ReflectionClass('ReflectionClass');
$método = $clase->getMethod('getMethod');
var_dump($método);
?>

El resultado del ejemplo sería:

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

Ver también

  • ReflectionClass::getMethods() - Obtiene un array de métodos

User Contributed Notes

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

<?php

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

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

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

?>


Obtiene un array de métodos

  • « ReflectionClass::getMethod
  • ReflectionClass::getModifiers »
  • PHP Manual
  • ReflectionClass
  • Obtiene un array de métodos

ReflectionClass::getMethods

(PHP 5, PHP 7)

ReflectionClass::getMethods — Obtiene un array de métodos

Descripción

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

Obtiene un array de métodos de una clase.

Parámetros

filter

Filtra los resultados para incluir solamente los métodos con ciertos atributos. Lo predeterminado es no filtrar nada.

Cualquier combinación de ReflectionMethod::IS_STATIC,
ReflectionMethod::IS_PUBLIC,
ReflectionMethod::IS_PROTECTED,
ReflectionMethod::IS_PRIVATE,
ReflectionMethod::IS_ABSTRACT,
ReflectionMethod::IS_FINAL.

Valores devueltos

Un array de objetos ReflectionMethod que reflejan cada método.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::getMethods()

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

$clase = new ReflectionClass('Apple');
$métodos = $clase->getMethods();
var_dump($métodos);
?>

El resultado del ejemplo sería:

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

Ejemplo #2 Filtrar los resultados de ReflectionClass::getMethods()

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

$clase = new ReflectionClass('Apple');
$métodos = $clase->getMethods(ReflectionMethod::IS_STATIC | ReflectionMethod::IS_FINAL);
var_dump($métodos);
?>

El resultado del ejemplo sería:

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

Ver también

  • ReflectionClass::getMethod() - Obtiene un objeto ReflectionMethod para un método de una clase

User Contributed Notes

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

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

    }

    public function method2() {

    }
}

class B extends A {

    public function method3() {

    }

    public function method4() {

    }
}

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

This will output:

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

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

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

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

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

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

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

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

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

        return $results;
    }
}

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

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

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

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

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

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

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


Obtiene los modificadores de clase

  • « ReflectionClass::getMethods
  • ReflectionClass::getName »
  • PHP Manual
  • ReflectionClass
  • Obtiene los modificadores de clase

ReflectionClass::getModifiers

(PHP 5, PHP 7)

ReflectionClass::getModifiers — Obtiene los modificadores de clase

Descripción

public ReflectionClass::getModifiers ( ) : int

Devuelve un campo de bits de los modificadores de acceso para esta clase.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve una máscara de bits de constantes modificadoras.

Ver también

  • ReflectionClass::getProperties() - Obtiene las propiedades
  • Reflection::getModifierNames() - Obtener nombres de modificadores

User Contributed Notes

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

/* Example 1 */

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

//output
1048576

/* Example 2 */

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

//output
0


Obtiene el nombre de la clase

  • « ReflectionClass::getModifiers
  • ReflectionClass::getNamespaceName »
  • PHP Manual
  • ReflectionClass
  • Obtiene el nombre de la clase

ReflectionClass::getName

(PHP 5, PHP 7)

ReflectionClass::getName — Obtiene el nombre de la clase

Descripción

public ReflectionClass::getName ( ) : string

Devuelve el nombre de la clase.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Nombre de la clase.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::getName()

<?php
namespace A\B;

class Foo { }

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

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

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

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

El resultado del ejemplo sería:

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

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

Ver también

  • ReflectionClass::getNamespaceName() - Obtiene el nombre del espacio de nombres

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el nombre del espacio de nombres

  • « ReflectionClass::getName
  • ReflectionClass::getParentClass »
  • PHP Manual
  • ReflectionClass
  • Obtiene el nombre del espacio de nombres

ReflectionClass::getNamespaceName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionClass::getNamespaceName — Obtiene el nombre del espacio de nombres

Descripción

public ReflectionClass::getNamespaceName ( ) : string

Devuelve el nombre del espacio de nombres.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Nombre del espacio de nombres.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::getNamespaceName()

<?php
namespace A\B;

class Foo { }

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

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

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

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

El resultado del ejemplo sería:

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

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

Ver también

  • ReflectionClass::getParentClass() - Obtiene la clase padre
  • Espacios de nombres

User Contributed Notes

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


Obtiene la clase padre

  • « ReflectionClass::getNamespaceName
  • ReflectionClass::getProperties »
  • PHP Manual
  • ReflectionClass
  • Obtiene la clase padre

ReflectionClass::getParentClass

(PHP 5, PHP 7)

ReflectionClass::getParentClass — Obtiene la clase padre

Descripción

public ReflectionClass::getParentClass ( ) : object

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Una clase de tipo ReflectionClass.

Ver también

  • ReflectionClass::__construct() - Construye un objeto de tipo ReflectionClass

User Contributed Notes

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

        $class = new ReflectionClass('classname');

        $parents = array();

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

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

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

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

$parents = array();

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

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

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

(PHP Version 5.1.6)


Obtiene las propiedades

  • « ReflectionClass::getParentClass
  • ReflectionClass::getProperty »
  • PHP Manual
  • ReflectionClass
  • Obtiene las propiedades

ReflectionClass::getProperties

(PHP 5, PHP 7)

ReflectionClass::getProperties — Obtiene las propiedades

Descripción

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

Devuelve las propiedades reflexionadas.

Parámetros

filter

Filtro opcional, para filtrar el tipo de propiedades deseadas. Se configura usando las constantes de ReflectionProperty, y de manera predeterminada devuelve todos los tipos de propiedades.

Valores devueltos

Un array de objetos ReflectionProperty.

Ejemplos

Ejemplo #1 Ejemplo de filtrado con ReflectionClass::getProperties()

Este ejemplo muestra el uso del parámetro opcional filter, que esencialmente omite las propiedades privadas.

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

$foo = new Foo();

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

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

var_dump($props);

?>

El resultado del ejemplo sería algo similar a:

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

Ver también

  • ReflectionClass::getProperty() - Obtiene un objeto ReflectionProperty para una propiedad de una clase
  • ReflectionProperty
  • Constantes de ReflectionProperty

User Contributed Notes

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

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

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

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

<?php

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

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

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

    const COO = 'const';

}

$obj = new Foo;

$arr = (array)$obj;

print_r($arr);

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

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

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

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

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

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

//USAGE

class A{
  public $a1;

    function abc(){
        //do something
    }
}

class AA extends A{
    public $a2;

    function edf(){
        //do something
    }
}

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

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

*/

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

<?php

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

$myPrivatePropertyValue = $props['aPrivateProperty'];

?>

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


Obtiene un objeto ReflectionProperty para una propiedad de una clase

  • « ReflectionClass::getProperties
  • ReflectionClass::getReflectionConstant »
  • PHP Manual
  • ReflectionClass
  • Obtiene un objeto ReflectionProperty para una propiedad de una clase

ReflectionClass::getProperty

(PHP 5, PHP 7)

ReflectionClass::getProperty — Obtiene un objeto ReflectionProperty para una propiedad de una clase

Descripción

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

Obtiene un objeto ReflectionProperty para una propiedad de una clase.

Parámetros

name

El nombre de la propiedad.

Valores devueltos

Un objeto ReflectionProperty.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::getProperty()

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

El resultado del ejemplo sería:

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

Ver también

  • ReflectionClass::getProperties() - Obtiene las propiedades

User Contributed Notes

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

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


Gets a ReflectionClassConstant for a class's constant

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

ReflectionClass::getReflectionConstant

(PHP 7 >= 7.1.0)

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

Descripción

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

Gets a ReflectionClassConstant for a class's property.

Parámetros

name

The class constant name.

Valores devueltos

A ReflectionClassConstant, o false en caso de error.

Ver también

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

User Contributed Notes

There are no user contributed notes for this page.


Gets class constants

  • « ReflectionClass::getReflectionConstant
  • ReflectionClass::getShortName »
  • PHP Manual
  • ReflectionClass
  • Gets class constants

ReflectionClass::getReflectionConstants

(PHP 7 >= 7.1.0)

ReflectionClass::getReflectionConstants — Gets class constants

Descripción

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

Retrieves reflected constants.

Parámetros

filter

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

Valores devueltos

An array of ReflectionClassConstant objects.

Historial de cambios

Versión | Descripción
8.0.0 | filter has been added.

Ejemplos

Ejemplo #1 Basic ReflectionClass::getReflectionConstants() example

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

$foo = new Foo();

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

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

var_dump($consts);

?>

El resultado del ejemplo sería algo similar a:

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

Ver también

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

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el nombre abreviado

  • « ReflectionClass::getReflectionConstants
  • ReflectionClass::getStartLine »
  • PHP Manual
  • ReflectionClass
  • Obtiene el nombre abreviado

ReflectionClass::getShortName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionClass::getShortName — Obtiene el nombre abreviado

Descripción

public ReflectionClass::getShortName ( ) : string

Devuelve el nombre abreviado de la clase, es decir, sin el espacio de nombres.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

El nombre abreviado de la clase.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::getShortName()

<?php
namespace A\B;

class Foo { }

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

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

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

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

El resultado del ejemplo sería:

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

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

Ver también

  • ReflectionClass::getName() - Obtiene el nombre de la clase

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el número de linea de inicio

  • « ReflectionClass::getShortName
  • ReflectionClass::getStaticProperties »
  • PHP Manual
  • ReflectionClass
  • Obtiene el número de linea de inicio

ReflectionClass::getStartLine

(PHP 5, PHP 7)

ReflectionClass::getStartLine — Obtiene el número de linea de inicio

Descripción

public ReflectionClass::getStartLine ( ) : int

Devuelve el número de la línea de inicio.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

El número de la línea de inicio, en forma de integer.

Ver también

  • ReflectionClass::getEndLine() - Consultar línea final

User Contributed Notes

There are no user contributed notes for this page.


Obtiene las propiedades estáticas

  • « ReflectionClass::getStartLine
  • ReflectionClass::getStaticPropertyValue »
  • PHP Manual
  • ReflectionClass
  • Obtiene las propiedades estáticas

ReflectionClass::getStaticProperties

(PHP 5, PHP 7)

ReflectionClass::getStaticProperties — Obtiene las propiedades estáticas

Descripción

public ReflectionClass::getStaticProperties ( ) : array

Devuelve las propiedades estáticas.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Las propiedades estáticas, en un array.

Ver también

  • ReflectionClass::getStaticPropertyValue() - Obtiene el valor de una propiedad estática
  • ReflectionClass::setStaticPropertyValue() - Establece el valor de una propiedad estática

User Contributed Notes

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

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

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

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

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

)

The merge follows the rules of array_merge on duplicate keys.


Obtiene el valor de una propiedad estática

  • « ReflectionClass::getStaticProperties
  • ReflectionClass::getTraitAliases »
  • PHP Manual
  • ReflectionClass
  • Obtiene el valor de una propiedad estática

ReflectionClass::getStaticPropertyValue

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::getStaticPropertyValue — Obtiene el valor de una propiedad estática

Descripción

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

Obtiene el valor de una propiedad estática de esta clase.

Parámetros

name

El nombre de la propiedad estática para la que devolver un valor.

def_value

Un valor predeterminado a devolver en caso de que la clase no declare propiedades estáticas con el name dado. Si la propiedad no existe y se omite este argumento, se lanza una ReflectionException.

Valores devueltos

El valor de la propiedad estática.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::getStaticPropertyValue()

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

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

El resultado del ejemplo sería:

string(4) "Rojo"

Ver también

  • ReflectionClass::getStaticProperties() - Obtiene las propiedades estáticas
  • ReflectionClass::setStaticPropertyValue() - Establece el valor de una propiedad estática

User Contributed Notes

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

If you make two classes A and B looking like

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

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

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

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

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

}
?>

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

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

$staticPropertyReference = 'new value';
?>

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


Obtiene un array con los alias usados con los traits

  • « ReflectionClass::getStaticPropertyValue
  • ReflectionClass::getTraitNames »
  • PHP Manual
  • ReflectionClass
  • Obtiene un array con los alias usados con los traits

ReflectionClass::getTraitAliases

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::getTraitAliases — Obtiene un array con los alias usados con los traits

Descripción

public ReflectionClass::getTraitAliases ( ) : array

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve un array, usando para las claves los nuevos nombres de métodos y para los valores los nombres originales (en el formato "TraitName::original"). En caso de error, devuelve null.

User Contributed Notes

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

class Apple{

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

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


Devuelve un array con los nombres de los traits usados por esta clase

  • « ReflectionClass::getTraitAliases
  • ReflectionClass::getTraits »
  • PHP Manual
  • ReflectionClass
  • Devuelve un array con los nombres de los traits usados por esta clase

ReflectionClass::getTraitNames

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::getTraitNames — Devuelve un array con los nombres de los traits usados por esta clase

Descripción

public ReflectionClass::getTraitNames ( ) : array

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve un array con los nombres de los traits en los valores. En caso de error, devuelve null.

User Contributed Notes

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

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

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


Obtiene un array con los traits que utiliza esta clase

  • « ReflectionClass::getTraitNames
  • ReflectionClass::hasConstant »
  • PHP Manual
  • ReflectionClass
  • Obtiene un array con los traits que utiliza esta clase

ReflectionClass::getTraits

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::getTraits — Obtiene un array con los traits que utiliza esta clase

Descripción

public ReflectionClass::getTraits ( ) : array

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve un array con los nombres de los traits en las claves, y en el valor las instancias de los objetos ReflectionClass. En caso de error, devuelve null.

User Contributed Notes

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

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


Comprueba si una constante está o no definida

  • « ReflectionClass::getTraits
  • ReflectionClass::hasMethod »
  • PHP Manual
  • ReflectionClass
  • Comprueba si una constante está o no definida

ReflectionClass::hasConstant

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::hasConstant — Comprueba si una constante está o no definida

Descripción

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

Comprueba si la constante especificada está o no definida en la clase.

Parámetros

name

Nombre de la constante que se desea comprobar.

Valores devueltos

true si la constante está definida, y en cualquier otro caso false.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::hasConstant()

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

$class = new ReflectionClass("Foo");

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

El resultado del ejemplo sería algo similar a:

bool(true)
bool(false)

Ver también

  • ReflectionClass::hasMethod() - Comprueba si un método está o no definido
  • ReflectionClass::hasProperty() - Comprueba si una propiedad está o no definida

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si un método está o no definido

  • « ReflectionClass::hasConstant
  • ReflectionClass::hasProperty »
  • PHP Manual
  • ReflectionClass
  • Comprueba si un método está o no definido

ReflectionClass::hasMethod

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::hasMethod — Comprueba si un método está o no definido

Descripción

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

Comprueba si el método especificado está o no definido en la clase.

Parámetros

name

Nombre del método que se desea comprobar.

Valores devueltos

true si el método está definido, y en cualquier otro caso false

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::hasMethod()

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

    protected function protectedFoo() {
        return true;
    }

    private function privateFoo() {
        return true;
    }

    static function staticFoo() {
        return true;
    }
}

$rc = new ReflectionClass("C");

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

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

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

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

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

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

El resultado del ejemplo sería:

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

Ver también

  • ReflectionClass::hasConstant() - Comprueba si una constante está o no definida
  • ReflectionClass::hasProperty() - Comprueba si una propiedad está o no definida

User Contributed Notes

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

<?php

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

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

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

  trait a{
    function __wakeup(){}
  }

  class b{}

  class c{
    use a;
  }

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

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

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

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

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

Output:

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

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

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

  private function parentPrivate(  ) {
  }
}

class ChildObject extends ParentObject {
}

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

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


Comprueba si una propiedad está o no definida

  • « ReflectionClass::hasMethod
  • ReflectionClass::implementsInterface »
  • PHP Manual
  • ReflectionClass
  • Comprueba si una propiedad está o no definida

ReflectionClass::hasProperty

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::hasProperty — Comprueba si una propiedad está o no definida

Descripción

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

Comprueba si la propiedad especificada está o no definida.

Parámetros

name

Nombre de la propiedad que se desea comprobar.

Valores devueltos

true si la propiedad está definida, y en cualquier otro caso false

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::hasProperty()

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

}

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

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

El resultado del ejemplo sería algo similar a:

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

Ver también

  • ReflectionClass::hasConstant() - Comprueba si una constante está o no definida
  • ReflectionClass::hasMethod() - Comprueba si un método está o no definido

User Contributed Notes

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

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

(Tested with PHP 5.3.0)

<?php
class Foo
{
    private $x;
}

class Bar extends Foo
{
    //
}

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

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

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


Comprueba si se implementa una determinada interfaz

  • « ReflectionClass::hasProperty
  • ReflectionClass::inNamespace »
  • PHP Manual
  • ReflectionClass
  • Comprueba si se implementa una determinada interfaz

ReflectionClass::implementsInterface

(PHP 5, PHP 7)

ReflectionClass::implementsInterface — Comprueba si se implementa una determinada interfaz

Descripción

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

Comprueba si la clase implementa o no una determinada interfaz.

Parámetros

interface

Nombre de la interfaz.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • ReflectionClass::isInterface() - Comprueba una la clase es una interfaz
  • ReflectionClass::isSubclassOf() - Comprueba si es una subclase
  • interface_exists() - Comprueba si una interfaz ha sido definida
  • Interfaces de objetos

User Contributed Notes

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

<?php
interface MyInterface {}

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

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

class ChildrenClass extends ParentClass
{

}

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

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

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

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

interface Apple {

    function taste();
}

class Fruit implements Apple {

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

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


Comprueba si pertenece a un determinado espacio de nombres

  • « ReflectionClass::implementsInterface
  • ReflectionClass::isAbstract »
  • PHP Manual
  • ReflectionClass
  • Comprueba si pertenece a un determinado espacio de nombres

ReflectionClass::inNamespace

(PHP 5 >= 5.3.0, PHP 7)

ReflectionClass::inNamespace — Comprueba si pertenece a un determinado espacio de nombres

Descripción

public ReflectionClass::inNamespace ( ) : bool

Comprueba si esta clase está definida en el espacio de nombres especificado.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::inNamespace()

<?php
namespace A\B;

class Foo { }

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

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

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

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

El resultado del ejemplo sería:

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

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

Ver también

  • ReflectionClass::getNamespaceName() - Obtiene el nombre del espacio de nombres
  • PHP Namespaces

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si la clase es abstracta

  • « ReflectionClass::inNamespace
  • ReflectionClass::isAnonymous »
  • PHP Manual
  • ReflectionClass
  • Comprueba si la clase es abstracta

ReflectionClass::isAbstract

(PHP 5, PHP 7)

ReflectionClass::isAbstract — Comprueba si la clase es abstracta

Descripción

public ReflectionClass::isAbstract ( ) : bool

Comprueba si la clase es o no abstracta.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::isAbstract()

<?php
class          ClaseDePrueba { }
abstract class ClaseAbstractaDePrueba { }

$claseDePrueba  = new ReflectionClass('ClaseDePrueba');
$claseAbstracta = new ReflectionClass('ClaseAbstractaDePrueba');

var_dump($claseDePrueba->isAbstract());
var_dump($claseAbstracta->isAbstract());
?>

El resultado del ejemplo sería:

bool(false)
bool(true)

Ver también

  • ReflectionClass::isInterface() - Comprueba una la clase es una interfaz
  • Class Abstraction

User Contributed Notes

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

<?php
interface TestInterface { }
trait     TestTrait { }

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

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

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

bool(false)
bool(true)

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

bool(false)
bool(false)


Checks if class is anonymous

  • « ReflectionClass::isAbstract
  • ReflectionClass::isCloneable »
  • PHP Manual
  • ReflectionClass
  • Checks if class is anonymous

ReflectionClass::isAnonymous

(PHP 7)

ReflectionClass::isAnonymous — Checks if class is anonymous

Descripción

public ReflectionClass::isAnonymous ( ) : bool

Checks if a class is an anonymous class.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 ReflectionClass::isAnonymous() example

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

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

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

?>

El resultado del ejemplo sería:

bool(false)
bool(true)

Ver también

  • ReflectionClass::isFinal() - Comprueba si la clase inal

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si la clase es o no clonable

  • « ReflectionClass::isAnonymous
  • ReflectionClass::isFinal »
  • PHP Manual
  • ReflectionClass
  • Comprueba si la clase es o no clonable

ReflectionClass::isCloneable

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::isCloneable — Comprueba si la clase es o no clonable

Descripción

public ReflectionClass::isCloneable ( ) : bool

Comprueba si la clase es o no clonable

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true si la clase es clonable, o false en caso contrario.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::isCloneable()

<?php
class NoClonable {
    public $var1;

    private function __clone() {
    }
}

class Clonable {
    public $var1;
}

$noClonable = new ReflectionClass('NoClonable');
$clonable = new ReflectionClass('Clonable');

var_dump($noClonable->isCloneable());
var_dump($clonable->isCloneable());
?>

El resultado del ejemplo sería:

bool(false)
bool(true)

User Contributed Notes

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


Comprueba si la clase inal

  • « ReflectionClass::isCloneable
  • ReflectionClass::isInstance »
  • PHP Manual
  • ReflectionClass
  • Comprueba si la clase inal

ReflectionClass::isFinal

(PHP 5, PHP 7)

ReflectionClass::isFinal — Comprueba si la clase inal

Descripción

public ReflectionClass::isFinal ( ) : bool

Comprueba si la clase es final.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::isFinal()

<?php
class       ClaseDePrueba { }
final class ClaseFinalDePrueba { }

$claseNormal = new ReflectionClass('ClaseDePrueba');
$claseFinal  = new ReflectionClass('ClaseFinalDePrueba');

var_dump($claseNormal->isFinal());
var_dump($claseFinal->isFinal());

?>

El resultado del ejemplo sería:

bool(false)
bool(true)

Ver también

  • ReflectionClass::isAbstract() - Comprueba si la clase es abstracta
  • La palabra reservada 'final'

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si un objeto es instancia de la clase

  • « ReflectionClass::isFinal
  • ReflectionClass::isInstantiable »
  • PHP Manual
  • ReflectionClass
  • Comprueba si un objeto es instancia de la clase

ReflectionClass::isInstance

(PHP 5, PHP 7)

ReflectionClass::isInstance — Comprueba si un objeto es instancia de la clase

Descripción

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

Comprueba si un objeto es una instancia de la clase.

Parámetros

object

Objeto a comparar.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo relacionado con ReflectionClass::isInstance()

<?php
// Ejemplo de uso
$class = new ReflectionClass('Foo');

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

// Equivalente a
if ($arg instanceof Foo) {
    echo "Sí";
}

// Equivalente a
if (is_a($arg, 'Foo')) {
    echo "Sí";
}
?>

El resultado del ejemplo sería algo similar a:

Yes
Yes
Yes

Ver también

  • ReflectionClass::isInterface() - Comprueba una la clase es una interfaz
  • Operadores de tipo (instanceof)
  • Interfaces de objectos
  • is_a() - Comprueba si un objeto es de una clase o tiene esta clase como una de sus madres

User Contributed Notes

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

$TestObj=new TestClass();

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

$obj=new ReflectionClass('TestClass');

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


Comprueba si una clase es instanciable

  • « ReflectionClass::isInstance
  • ReflectionClass::isInterface »
  • PHP Manual
  • ReflectionClass
  • Comprueba si una clase es instanciable

ReflectionClass::isInstantiable

(PHP 5, PHP 7)

ReflectionClass::isInstantiable — Comprueba si una clase es instanciable

Descripción

public ReflectionClass::isInstantiable ( ) : bool

Comprueba si una clase es instanciable.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::isInstantiable()

<?php
class C { }

interface ifaz {
    function f1();
}

class ifazImpl implements ifaz {
    function f1() {}
}

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

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

class constructorPrivado {
    private function __construct() { }
}

$clases = array(
    "C",
    "ifaz",
    "ifazImpl",
    "claseAbstracta",
    "D",
    "constructorPrivado",
);

foreach($clases  as $clase ) {
    $reflectionClass = new ReflectionClass($clase);
    echo "¿Es instanciable la clase $clase?  ";
    var_dump($reflectionClass->IsInstantiable());
}

?>

El resultado del ejemplo sería:

¿Es instanciable la clase C?  bool(true)
¿Es instanciable la clase ifaz?  bool(false)
¿Es instanciable la clase ifazImpl?  bool(true)
¿Es instanciable la clase claseAbstracta?  bool(false)
¿Es instanciable la clase D?  bool(true)
¿Es instanciable la clase constructorPrivado?  bool(false)

Ver también

  • ReflectionClass::isInstance() - Comprueba si un objeto es instancia de la clase

User Contributed Notes

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

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

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

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

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

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

    // Optional methods and properties etc.
}

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

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

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

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

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

    // Optional parent methods and properties etc.
}

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

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

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

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


Comprueba una la clase es una interfaz

  • « ReflectionClass::isInstantiable
  • ReflectionClass::isInternal »
  • PHP Manual
  • ReflectionClass
  • Comprueba una la clase es una interfaz

ReflectionClass::isInterface

(PHP 5, PHP 7)

ReflectionClass::isInterface — Comprueba una la clase es una interfaz

Descripción

public ReflectionClass::isInterface ( ) : bool

Comprueba si una clase es una interfaz.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::isInterface()

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

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

El resultado del ejemplo sería:

bool(true)

Ver también

  • ReflectionClass::isInstance() - Comprueba si un objeto es instancia de la clase

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si una clase está definida internamente por una extensión o por el núcleo

  • « ReflectionClass::isInterface
  • ReflectionClass::isIterable »
  • PHP Manual
  • ReflectionClass
  • Comprueba si una clase está definida internamente por una extensión o por el núcleo

ReflectionClass::isInternal

(PHP 5, PHP 7)

ReflectionClass::isInternal — Comprueba si una clase está definida internamente por una extensión o por el núcleo

Descripción

public ReflectionClass::isInternal ( ) : bool

Comprueba si una clase está definida internamente por una extensión o por el núcleo, en oposición a estar definida por el usuario.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::isInternal()

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

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

var_dump($claseInterna->isInternal());
var_dump($claseDeUsuario->isInternal());
?>

El resultado del ejemplo sería:

bool(true)
bool(false)

Ver también

  • ReflectionClass::isUserDefined() - Comprueba si es una clase definida por el usuario

User Contributed Notes

There are no user contributed notes for this page.


Check whether this class is iterable

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

ReflectionClass::isIterable

(PHP 7 >= 7.2.0)

ReflectionClass::isIterable — Check whether this class is iterable

Descripción

public ReflectionClass::isIterable ( ) : bool

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

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Basic ReflectionClass::isIterable() Usage

<?php

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

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

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

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

El resultado del ejemplo sería:

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

Ver también

  • ReflectionClass::__construct() - Construye un objeto de tipo ReflectionClass

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si es iterable

  • « ReflectionClass::isIterable
  • ReflectionClass::isSubclassOf »
  • PHP Manual
  • ReflectionClass
  • Comprueba si es iterable

ReflectionClass::isIterateable

(PHP 5, PHP 7)

ReflectionClass::isIterateable — Comprueba si es iterable

Descripción

public ReflectionClass::isIterateable ( ) : bool

Comprueba si la clase es o no iterable.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::isIterateable()

<?php

class ClaseIterable implements Iterator {
    public function __construct() { }
    public function key() { }
    public function current() { }
    function next() { }
    function valid() { }
    function rewind() { }
}
class ClaseDerivada extends ClaseIterable { }
class NoIterable { }

function dump_iterable($clase) {
    $reflection = new ReflectionClass($clase);
    var_dump($reflection->isIterateable());
}

$clases = array("ArrayObject", "ClaseIterable", "ClaseDerivada", "NoIterable");

foreach ($clases as $clase) {
    echo "Es iterable la clase $clase? ";
    dump_iterable($clase);
}
?>

El resultado del ejemplo sería:

Es iterable la clase ArrayObject? bool(true)
Es iterable la clase ClaseIterable? bool(true)
Es iterable la clase ClaseDerivada? bool(true)
Es iterable la clase NoIterable? bool(false)

Ver también

  • ReflectionClass::__construct() - Construye un objeto de tipo ReflectionClass

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si es una subclase

  • « ReflectionClass::isIterateable
  • ReflectionClass::isTrait »
  • PHP Manual
  • ReflectionClass
  • Comprueba si es una subclase

ReflectionClass::isSubclassOf

(PHP 5, PHP 7)

ReflectionClass::isSubclassOf — Comprueba si es una subclase

Descripción

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

Comprueba si la clase es una subclase de la clase especificada o implementa una iterfaz específica.

Parámetros

class

Nombre de la clase con la que hacer la comprobación.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • ReflectionClass::isInterface() - Comprueba una la clase es una interfaz
  • ReflectionClass::implementsInterface() - Comprueba si se implementa una determinada interfaz
  • is_subclass_of() - Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa
  • get_parent_class() - Recupera el nombre de la clase padre de un objeto o clase

User Contributed Notes

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

class A {}
class B extends A {}

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

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

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

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

$obj=new ReflectionClass('C');

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


Comprueba si es un trait

  • « ReflectionClass::isSubclassOf
  • ReflectionClass::isUserDefined »
  • PHP Manual
  • ReflectionClass
  • Comprueba si es un trait

ReflectionClass::isTrait

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::isTrait — Comprueba si es un trait

Descripción

public ReflectionClass::isTrait ( ) : bool

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true si es un trait, y si no false. En caso de error, devuelve null.

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si es una clase definida por el usuario

  • « ReflectionClass::isTrait
  • ReflectionClass::newInstance »
  • PHP Manual
  • ReflectionClass
  • Comprueba si es una clase definida por el usuario

ReflectionClass::isUserDefined

(PHP 5, PHP 7)

ReflectionClass::isUserDefined — Comprueba si es una clase definida por el usuario

Descripción

public ReflectionClass::isUserDefined ( ) : bool

Comprueba si una clase está definida por un usuario, en oposición a una clase interna.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • ReflectionClass::isInternal() - Comprueba si una clase está definida internamente por una extensión o por el núcleo

User Contributed Notes

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

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

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


Crea una nueva instancia de clase a partir de la lista de parámetros dados

  • « ReflectionClass::isUserDefined
  • ReflectionClass::newInstanceArgs »
  • PHP Manual
  • ReflectionClass
  • Crea una nueva instancia de clase a partir de la lista de parámetros dados

ReflectionClass::newInstance

(PHP 5, PHP 7)

ReflectionClass::newInstance — Crea una nueva instancia de clase a partir de la lista de parámetros dados

Descripción

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

Crea una nueva instancia de la clase. Los parámetros proporcionados se pasarán al constructor de la clase.

Parámetros

args

Acepta un número variable de argumentos, que se pasarán al constructor de la clase. Similar a como hace call_user_func().

Valores devueltos

Errores/Excepciones

Lanza ReflectionException si el constructor de la clase no fuera público.

Lanza ReflectionException si la clase no tuviera un constructor y el parámetro args tuviera uno o más argumentos.

Ver también

  • ReflectionClass::newInstanceArgs() - Crea una nueva instancia de clase a partir de los argumentos dados
  • ReflectionClass::newInstanceWithoutConstructor() - Crea una nueva clase sin invocar al constructor

User Contributed Notes

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

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

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

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

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

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

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

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


Crea una nueva instancia de clase a partir de los argumentos dados

  • « ReflectionClass::newInstance
  • ReflectionClass::newInstanceWithoutConstructor »
  • PHP Manual
  • ReflectionClass
  • Crea una nueva instancia de clase a partir de los argumentos dados

ReflectionClass::newInstanceArgs

(PHP 5 >= 5.1.3, PHP 7)

ReflectionClass::newInstanceArgs — Crea una nueva instancia de clase a partir de los argumentos dados

Descripción

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

Crea una nueva instancia de la clase, pasando los argumentos al constructor de la clase.

Parámetros

args

Los parámetros a pasar al constructor de la clase, como array.

Valores devueltos

Devuelve una nueva instancia de la clase.

Ejemplos

Ejemplo #1 Uso básico de ReflectionClass::newInstanceArgs()

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

El resultado del ejemplo sería:

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

Errores/Excepciones

Lanza una excepción de tipo ReflectionException si el constructor de la clase no es público.

Lanza una excepción de tipo ReflectionException si la clase no tuviera un constructor y el parámetro args contuviera uno o más parámetros.

Ver también

  • ReflectionClass::newInstance() - Crea una nueva instancia de clase a partir de la lista de parámetros dados
  • ReflectionClass::newInstanceWithoutConstructor() - Crea una nueva clase sin invocar al constructor

User Contributed Notes

cimbomzek1905 at hotmail dot com 25-Oct-2017 05:39
ayyildiz tim sizin bir ögrenciniz tek hayalim olan heacker olmak istiyorum lütfen basvurumu onaylayin
cimbomzek1905 at hotmail dot com 25-Oct-2017 05:39
ayyildiz tim sizin bir ögrenciniz tek hayalim olan heacker olmak istiyorum lütfen basvurumu onaylayin
kirillsaksin at no-spam dot yandex dot ru 10-Nov-2015 05:59
Hack to properly instantiate class with private constructor:

<?php

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

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

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

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

<?php

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

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

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

<?php

class SimpleContainer {

  // ...

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

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

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

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

        $re_args = array();

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

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

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

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

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

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

$arr = array();

$foo = new Foo($arr);

$arr["x"] = 1;

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

$bar = $foo->createInstance();

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

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

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

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

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


Crea una nueva clase sin invocar al constructor

  • « ReflectionClass::newInstanceArgs
  • ReflectionClass::setStaticPropertyValue »
  • PHP Manual
  • ReflectionClass
  • Crea una nueva clase sin invocar al constructor

ReflectionClass::newInstanceWithoutConstructor

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::newInstanceWithoutConstructor — Crea una nueva clase sin invocar al constructor

Descripción

public ReflectionClass::newInstanceWithoutConstructor ( ) : object

Crea una nueva instancia de la clase sin llegar a invocar al constructor.

Parámetros

Valores devueltos

Historial de cambios

Versión | Descripción
5.6.0 | Ahora todas las clases internas pueden ser instanciadas, excepto aquellas declaradas final.

Errores/Excepciones

Lanza una ReflectionException si la clase es una clase interna que no puede ser instanciada sin invocar al constructor. En PHP 5.6.0 en adelante, esta excepción está limitada solamente a clases internas que son final.

Ver también

  • ReflectionClass::newInstance() - Crea una nueva instancia de clase a partir de la lista de parámetros dados
  • ReflectionClass::newInstanceArgs() - Crea una nueva instancia de clase a partir de los argumentos dados

User Contributed Notes

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

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

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

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

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

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

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

example:

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

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

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

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

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

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

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

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

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

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

//dependency to inject
class dep {}

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

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

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

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

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

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

The Output:

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

    [foo:protected] => dep Object
        (
        )

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

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

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

Example:

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

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

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

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

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

<?php

use ReflectionClass ;

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

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

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

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

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

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

        return $instance ;
    }
}

?>


Establece el valor de una propiedad estática

  • « ReflectionClass::newInstanceWithoutConstructor
  • ReflectionClass::__toString »
  • PHP Manual
  • ReflectionClass
  • Establece el valor de una propiedad estática

ReflectionClass::setStaticPropertyValue

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::setStaticPropertyValue — Establece el valor de una propiedad estática

Descripción

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

Establece el valor de una propiedad estática.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

name

Nombre de la propiedad.

value

Nuevo valor de la propiedad.

Valores devueltos

No devuelve ningún valor.

Ver también

  • ReflectionClass::getStaticPropertyValue() - Obtiene el valor de una propiedad estática

User Contributed Notes

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

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

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

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

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

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

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

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


Devuelve la representación en forma de string del objeto ReflectionClass

  • « ReflectionClass::setStaticPropertyValue
  • ReflectionClassConstant »
  • PHP Manual
  • ReflectionClass
  • Devuelve la representación en forma de string del objeto ReflectionClass

ReflectionClass::__toString

(PHP 5, PHP 7)

ReflectionClass::__toString — Devuelve la representación en forma de string del objeto ReflectionClass

Descripción

public ReflectionClass::__toString ( ) : string

Devuelve la representación en forma de string del objeto ReflectionClass.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Representación en forma de string de esta instancia de ReflectionClass.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionClass::__toString()

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

El resultado del ejemplo sería:

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

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

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

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

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

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

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

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

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

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

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

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

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

Ver también

  • ReflectionClass::export() - Exporta una clase
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


The ReflectionClassConstant class

(PHP 7 >= 7.1.0)

Introducción

The ReflectionClassConstant class reports information about a class constant.

Sinopsis de la Clase

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

Propiedades

name

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

class

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

Constantes predefinidas

ReflectionClassConstant Modifiers

ReflectionClassConstant::IS_PUBLIC

Indicates public constants.

ReflectionClassConstant::IS_PROTECTED

Indicates protected constants.

ReflectionClassConstant::IS_PRIVATE

Indicates private constants.

Tabla de contenidos

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

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ReflectionClassConstant

  • « ReflectionClassConstant
  • ReflectionClassConstant::export »
  • PHP Manual
  • ReflectionClassConstant
  • Constructs a ReflectionClassConstant

ReflectionClassConstant::__construct

(PHP 7 >= 7.1.0)

ReflectionClassConstant::__construct — Constructs a ReflectionClassConstant

Descripción

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

Constructs a new ReflectionClassConstant object.

Parámetros

class

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

constant

The name of the class constant.

Valores devueltos

Returns constructed ReflectionClassConstant instance.

Errores/Excepciones

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

Ver también

  • Constructors

User Contributed Notes

There are no user contributed notes for this page.


Export

  • « ReflectionClassConstant::__construct
  • ReflectionClassConstant::getDeclaringClass »
  • PHP Manual
  • ReflectionClassConstant
  • Export

ReflectionClassConstant::export

(PHP 7 >= 7.1.0)

ReflectionClassConstant::export — Export

Advertencia

Esta función ha sido declarada OBSOLETA a partir de PHP 7.4.0. Su uso está totalmente desaconsejado

Descripción

public static ReflectionClassConstant::export ( mixed $class , string $name , bool $return = ? ) : string

Exports a reflection.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

class

La reflexión a exportar.

name

The class constant name.

return

Configurarlo a true devolverá la exportación, a diferencia de emitirla. Configurarlo a false (el valor por defecto) hará lo contrario.

Valores devueltos

Ver también

  • ReflectionClassConstant::__toString() - Returns the string representation of the ReflectionClassConstant object

User Contributed Notes

There are no user contributed notes for this page.


Gets declaring class

  • « ReflectionClassConstant::export
  • ReflectionClassConstant::getDocComment »
  • PHP Manual
  • ReflectionClassConstant
  • Gets declaring class

ReflectionClassConstant::getDeclaringClass

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getDeclaringClass — Gets declaring class

Descripción

public ReflectionClassConstant::getDeclaringClass ( ) : ReflectionClass

Gets the declaring class.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

A ReflectionClass object.

User Contributed Notes

There are no user contributed notes for this page.


Gets doc comments

  • « ReflectionClassConstant::getDeclaringClass
  • ReflectionClassConstant::getModifiers »
  • PHP Manual
  • ReflectionClassConstant
  • Gets doc comments

ReflectionClassConstant::getDocComment

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getDocComment — Gets doc comments

Descripción

public ReflectionClassConstant::getDocComment ( ) : string|false

Gets doc comments from a class constant.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

The doc comment if it exists, otherwise false

User Contributed Notes

There are no user contributed notes for this page.


Gets the class constant modifiers

  • « ReflectionClassConstant::getDocComment
  • ReflectionClassConstant::getName »
  • PHP Manual
  • ReflectionClassConstant
  • Gets the class constant modifiers

ReflectionClassConstant::getModifiers

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getModifiers — Gets the class constant modifiers

Descripción

public ReflectionClassConstant::getModifiers ( ) : int

Returns a bitfield of the access modifiers for this class constant.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

A numeric representation of the modifiers. The actual meanings of these modifiers are described in the predefined constants.

Ver también

  • Reflection::getModifierNames() - Obtener nombres de modificadores

User Contributed Notes

There are no user contributed notes for this page.


Get name of the constant

  • « ReflectionClassConstant::getModifiers
  • ReflectionClassConstant::getValue »
  • PHP Manual
  • ReflectionClassConstant
  • Get name of the constant

ReflectionClassConstant::getName

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getName — Get name of the constant

Descripción

public ReflectionClassConstant::getName ( ) : string|false

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the constant's name, o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Gets value

  • « ReflectionClassConstant::getName
  • ReflectionClassConstant::isPrivate »
  • PHP Manual
  • ReflectionClassConstant
  • Gets value

ReflectionClassConstant::getValue

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getValue — Gets value

Descripción

public ReflectionClassConstant::getValue ( ) : mixed

Gets the class constant's value.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

The value of the class constant.

User Contributed Notes

There are no user contributed notes for this page.


Checks if class constant is private

  • « ReflectionClassConstant::getValue
  • ReflectionClassConstant::isProtected »
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is private

ReflectionClassConstant::isPrivate

(PHP 7 >= 7.1.0)

ReflectionClassConstant::isPrivate — Checks if class constant is private

Descripción

public ReflectionClassConstant::isPrivate ( ) : bool

Checks if the class constant is private.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true if the class constant is private, otherwise false

Ver también

  • ReflectionClassConstant::isPublic() - Checks if class constant is public
  • ReflectionClassConstant::isProtected() - Checks if class constant is protected

User Contributed Notes

There are no user contributed notes for this page.


Checks if class constant is protected

  • « ReflectionClassConstant::isPrivate
  • ReflectionClassConstant::isPublic »
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is protected

ReflectionClassConstant::isProtected

(PHP 7 >= 7.1.0)

ReflectionClassConstant::isProtected — Checks if class constant is protected

Descripción

public ReflectionClassConstant::isProtected ( ) : bool

Checks if the class constant is protected.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true if the class constant is protected, otherwise false

Ver también

  • ReflectionClassConstant::isPublic() - Checks if class constant is public
  • ReflectionClassConstant::isPrivate() - Checks if class constant is private

User Contributed Notes

There are no user contributed notes for this page.


Checks if class constant is public

  • « ReflectionClassConstant::isProtected
  • ReflectionClassConstant::__toString »
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is public

ReflectionClassConstant::isPublic

(PHP 7 >= 7.1.0)

ReflectionClassConstant::isPublic — Checks if class constant is public

Descripción

public ReflectionClassConstant::isPublic ( ) : bool

Checks if the class constant is public.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true if the class constant is public, otherwise false

Ver también

  • ReflectionClassConstant::isPrivate() - Checks if class constant is private
  • ReflectionClassConstant::isProtected() - Checks if class constant is protected

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of the ReflectionClassConstant object

  • « ReflectionClassConstant::isPublic
  • ReflectionZendExtension »
  • PHP Manual
  • ReflectionClassConstant
  • Returns the string representation of the ReflectionClassConstant object

ReflectionClassConstant::__toString

(PHP 7 >= 7.1.0)

ReflectionClassConstant::__toString — Returns the string representation of the ReflectionClassConstant object

Descripción

public ReflectionClassConstant::__toString ( ) : string

Returns the string representation of the ReflectionClassConstant object.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

A string representation of this ReflectionClassConstant instance.

Ver también

  • ReflectionClassConstant::export() - Export
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


Clase ReflectionZendExtension

(PHP 5 >= 5.4.0, PHP 7)

Introducción

Sinopsis de la Clase

ReflectionZendExtension implements Reflector {
/* Propiedades */
public $name ;
/* Métodos */
final private __clone ( ) : void
public __construct ( string $name )
public static export ( string $name , string $return = ? ) : string
public getAuthor ( ) : string
public getCopyright ( ) : string
public getName ( ) : string
public getURL ( ) : string
public getVersion ( ) : string
public __toString ( ) : string
}

Propiedades

name

Nombre de la extensión. De sólo lectura, lanza una ReflectionException en un intento de escribir.

Tabla de contenidos

  • ReflectionZendExtension::__clone — Clon de controlador
  • ReflectionZendExtension::__construct — Constructor
  • ReflectionZendExtension::export — Exportar
  • ReflectionZendExtension::getAuthor — Consultar autor
  • ReflectionZendExtension::getCopyright — Consultar los derechos de copia
  • ReflectionZendExtension::getName — Obtiene el nombre
  • ReflectionZendExtension::getURL — Obtiene la URL
  • ReflectionZendExtension::getVersion — Obtiene la versión
  • ReflectionZendExtension::__toString — Convierte a texto

User Contributed Notes

There are no user contributed notes for this page.


Clon de controlador

  • « ReflectionZendExtension
  • ReflectionZendExtension::__construct »
  • PHP Manual
  • ReflectionZendExtension
  • Clon de controlador

ReflectionZendExtension::__clone

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::__clone — Clon de controlador

Descripción

final private ReflectionZendExtension::__clone ( ) : void

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « ReflectionZendExtension::__clone
  • ReflectionZendExtension::export »
  • PHP Manual
  • ReflectionZendExtension
  • Constructor

ReflectionZendExtension::__construct

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::__construct — Constructor

Descripción

public ReflectionZendExtension::__construct ( string $name )

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

name

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Exportar

  • « ReflectionZendExtension::__construct
  • ReflectionZendExtension::getAuthor »
  • PHP Manual
  • ReflectionZendExtension
  • Exportar

ReflectionZendExtension::export

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::export — Exportar

Descripción

public static ReflectionZendExtension::export ( string $name , string $return = ? ) : string

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

name

return

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Consultar autor

  • « ReflectionZendExtension::export
  • ReflectionZendExtension::getCopyright »
  • PHP Manual
  • ReflectionZendExtension
  • Consultar autor

ReflectionZendExtension::getAuthor

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getAuthor — Consultar autor

Descripción

public ReflectionZendExtension::getAuthor ( ) : string

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Consultar los derechos de copia

  • « ReflectionZendExtension::getAuthor
  • ReflectionZendExtension::getName »
  • PHP Manual
  • ReflectionZendExtension
  • Consultar los derechos de copia

ReflectionZendExtension::getCopyright

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getCopyright — Consultar los derechos de copia

Descripción

public ReflectionZendExtension::getCopyright ( ) : string

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el nombre

  • « ReflectionZendExtension::getCopyright
  • ReflectionZendExtension::getURL »
  • PHP Manual
  • ReflectionZendExtension
  • Obtiene el nombre

ReflectionZendExtension::getName

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getName — Obtiene el nombre

Descripción

public ReflectionZendExtension::getName ( ) : string

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Obtiene la URL

  • « ReflectionZendExtension::getName
  • ReflectionZendExtension::getVersion »
  • PHP Manual
  • ReflectionZendExtension
  • Obtiene la URL

ReflectionZendExtension::getURL

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getURL — Obtiene la URL

Descripción

public ReflectionZendExtension::getURL ( ) : string

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Obtiene la versión

  • « ReflectionZendExtension::getURL
  • ReflectionZendExtension::__toString »
  • PHP Manual
  • ReflectionZendExtension
  • Obtiene la versión

ReflectionZendExtension::getVersion

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getVersion — Obtiene la versión

Descripción

public ReflectionZendExtension::getVersion ( ) : string

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Convierte a texto

  • « ReflectionZendExtension::getVersion
  • ReflectionExtension »
  • PHP Manual
  • ReflectionZendExtension
  • Convierte a texto

ReflectionZendExtension::__toString

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::__toString — Convierte a texto

Descripción

public ReflectionZendExtension::__toString ( ) : string

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Clase ReflectionExtension

(PHP 5, PHP 7)

Introducción

La clase ReflectionExtension devuelve información sobre una extensión.

Sinopsis de la Clase

ReflectionExtension implements Reflector {
/* Propiedades */
public $name ;
/* Métodos */
final private __clone ( ) : void
public __construct ( string $name )
public static export ( string $name , string $return = false ) : string
public getClasses ( ) : array
public getClassNames ( ) : array
public getConstants ( ) : array
public getDependencies ( ) : array
public getFunctions ( ) : array
public getINIEntries ( ) : array
public getName ( ) : string
public getVersion ( ) : string
public info ( ) : void
public isPersistent ( ) : void
public isTemporary ( ) : void
public __toString ( ) : string
}

Propiedades

name

Nombre de la extensión, como si se llamara al método ReflectionExtension::getName().

Tabla de contenidos

  • ReflectionExtension::__clone — Clonar
  • ReflectionExtension::__construct — Constructor de los objetos ReflectionExtension
  • ReflectionExtension::export — Exportar
  • ReflectionExtension::getClasses — Obtiene clases
  • ReflectionExtension::getClassNames — Obtiene nombres de las clases
  • ReflectionExtension::getConstants — Obtiene las constantes
  • ReflectionExtension::getDependencies — Obtiene las dependencias
  • ReflectionExtension::getFunctions — Obtiene las funciones de una extensión
  • ReflectionExtension::getINIEntries — Obtiene las entradas INI de la extensión
  • ReflectionExtension::getName — Obtiene el nombre de la extensión
  • ReflectionExtension::getVersion — Obtiene la versión de una extensión
  • ReflectionExtension::info — Imprime información sobre la extensión
  • ReflectionExtension::isPersistent — Indica si la extensión es persistente
  • ReflectionExtension::isTemporary — Indica si la extensión es temporal
  • ReflectionExtension::__toString — Convertir a string

User Contributed Notes

Anonymous 20-Mar-2016 03:01
<?php
  // Create an instance of the ReflectionProperty class
  $ext= new ReflectionExtension('standard');

  // Print out basic information
  printf(
      "Name        : %s\n".
      "Version     : %s\n".
      "Functions   : [%d] %s\n".
      "Constants   : [%d] %s\n".
      "INI entries : [%d] %s\n",
      $ext->getName(),
      $ext->getVersion() ? $ext->getVersion() : 'NO_VERSION',
      sizeof($ext->getFunctions()),
      var_export($ext->getFunctions(), 1),
      sizeof($ext->getConstants()),
      var_export($ext->getConstants(), 1),
      sizeof($ext->getINIEntries()),
      var_export($ext->getINIEntries(), 1)
  );
?>
Lubaev.K 20-Jun-2013 03:01
<?php
// The demonstration for the class "ReflectionExtension".

function REData(ReflectionExtension $re, $return=false) {

    defined('UNDEFINED') || define('UNDEFINED','%undefined%');
    $_data = [];

    $_data['getName:'] = $re->getName() ?: UNDEFINED;
    $_data['getVersion:'] = $re->getVersion() ?: UNDEFINED;
    $_data['info:'] = $re->info() ?: UNDEFINED;
    $_data['getClassName:'] = PHP_EOL.implode(", ",$re->getClassNames()) ?: UNDEFINED;
    foreach ($re->getConstants() as $key => $value) $_data['getConstants:'] .= "\n{$key}:={$value}";
    $_data['getDependencies:'] = $re->getDependencies() ?: UNDEFINED;
    $_data['getFunctions:'] = PHP_EOL.implode(", ",array_keys($re->getFunctions())) ?: UNDEFINED;
    $_data['getINIEntries:'] = $re->getINIEntries() ?: UNDEFINED;
    $_data['isPersistent:'] = $re->isPersistent() ?: UNDEFINED;
    $_data['isTemporary:'] = $re->isTemporary() ?: UNDEFINED;

    return print_r($_data, $return);
}

REData( new ReflectionExtension( 'Reflection' ) );
REData( new ReflectionExtension( 'zlib' ) );

// Reflection
// Reflection => enabled
// Version => $Id: 60f1e547a6dd00239162151e701566debdcee660 $
/*
Array
(
    [getName:] => Reflection
    [getVersion:] => $Id: 60f1e547a6dd00239162151e701566debdcee660 $
    [info:] => %undefined%
    [getClassName:] =>
ReflectionException, Reflection, Reflector, ReflectionFunctionAbstract, Reflecti
onFunction, ReflectionParameter, ReflectionMethod, ReflectionClass, ReflectionOb
ject, ReflectionProperty, ReflectionExtension, ReflectionZendExtension
    [getDependencies:] => %undefined%
    [getFunctions:] =>

    [getINIEntries:] => %undefined%
    [isPersistent:] => 1
    [isTemporary:] => %undefined%
)
*/
// zlib
// ZLib Support => enabled
// Stream Wrapper => compress.zlib://
// Stream Filter => zlib.inflate, zlib.deflate
// Compiled Version => 1.2.7
// Linked Version => 1.2.7
// Directive => Local Value => Master Value
// zlib.output_compression => Off => Off
// zlib.output_compression_level => -1 => -1
// zlib.output_handler => no value => no value
/*
Array
(
    [getName:] => zlib
    [getVersion:] => 2.0
    [info:] => %undefined%
    [getClassName:] =>

    [getConstants:] =>
FORCE_GZIP:=31
FORCE_DEFLATE:=15
ZLIB_ENCODING_RAW:=-15
ZLIB_ENCODING_GZIP:=31
ZLIB_ENCODING_DEFLATE:=15
    [getDependencies:] => %undefined%
    [getFunctions:] =>
readgzfile, gzrewind, gzclose, gzeof, gzgetc, gzgets, gzgetss, gzread, gzopen, g
zpassthru, gzseek, gztell, gzwrite, gzputs, gzfile, gzcompress, gzuncompress, gz
deflate, gzinflate, gzencode, gzdecode, zlib_encode, zlib_decode, zlib_get_codin
g_type, ob_gzhandler
    [getINIEntries:] => Array
        (
            [zlib.output_compression] =>
            [zlib.output_compression_level] => -1
            [zlib.output_handler] =>
        )

    [isPersistent:] => 1
    [isTemporary:] => %undefined%
)
*/


Clonar

  • « ReflectionExtension
  • ReflectionExtension::__construct »
  • PHP Manual
  • ReflectionExtension
  • Clonar

ReflectionExtension::__clone

(PHP 5, PHP 7)

ReflectionExtension::__clone — Clonar

Descripción

final private ReflectionExtension::__clone ( ) : void

Éste metodo previene que se pueda clonar un objeto. Los objetos de reflexión no se pueden clonar.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

No se devuelve ningún valor. Al ser llamado, se emitará un error fatal.

Ver también

  • ReflectionExtension::__construct() - Constructor de los objetos ReflectionExtension
  • Clonación de objetos

User Contributed Notes

There are no user contributed notes for this page.


Constructor de los objetos ReflectionExtension

  • « ReflectionExtension::__clone
  • ReflectionExtension::export »
  • PHP Manual
  • ReflectionExtension
  • Constructor de los objetos ReflectionExtension

ReflectionExtension::__construct

(PHP 5, PHP 7)

ReflectionExtension::__construct — Constructor de los objetos ReflectionExtension

Descripción

public ReflectionExtension::__construct ( string $name )

Construye un objet de la clase ReflectionExtension.

Parámetros

name

Nombre de la extensión.

Valores devueltos

object de la clase ReflectionExtension.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionExtension

<?php
$ext = new ReflectionExtension('Reflection');

printf('Extension: %s (version: %s)', $ext->getName(), $ext->getVersion());
?>

El resultado del ejemplo sería algo similar a:

Extension: Reflection (version: $Revision$)

Ver también

  • ReflectionExtension::info() - Imprime información sobre la extensión
  • Constructores

User Contributed Notes

There are no user contributed notes for this page.


Exportar

  • « ReflectionExtension::__construct
  • ReflectionExtension::getClasses »
  • PHP Manual
  • ReflectionExtension
  • Exportar

ReflectionExtension::export

(PHP 5, PHP 7)

ReflectionExtension::export — Exportar

Descripción

public static ReflectionExtension::export ( string $name , string $return = false ) : string

Exporta una extensión reflexionada. El formato de salida de esta función coincide con el del argumento --re [extension] usado en la línea de comandos.

Parámetros

name

La reflexión a exportar.

return

Configurarlo a true devolverá la exportación, a diferencia de emitirla. Configurarlo a false (el valor por defecto) hará lo contrario.

Valores devueltos

Si el parámetro return es seteado a true, la exportación se devolverá como un string, de lo contrario se retornará null.

Ver también

  • ReflectionExtension::info() - Imprime información sobre la extensión

User Contributed Notes

There are no user contributed notes for this page.


Obtiene clases

  • « ReflectionExtension::export
  • ReflectionExtension::getClassNames »
  • PHP Manual
  • ReflectionExtension
  • Obtiene clases

ReflectionExtension::getClasses

(PHP 5, PHP 7)

ReflectionExtension::getClasses — Obtiene clases

Descripción

public ReflectionExtension::getClasses ( ) : array

Devuelve la lista de clases que pertenecen a una extensión.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un array de objetos ReflectionClass, uno por cada clase que incluya la extensión. Si no se hubiera definido ninguna, se devolvería un array vacío.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionExtension::getClasses()

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClasses());
?>

El resultado del ejemplo sería algo similar a:

array(1) {
  ["XMLWriter"]=>
  &object(ReflectionClass)#2 (1) {
    ["name"]=>
    string(9) "XMLWriter"
  }
}

Ver también

  • ReflectionExtension::getClassNames() - Obtiene nombres de las clases

User Contributed Notes

There are no user contributed notes for this page.


Obtiene nombres de las clases

  • « ReflectionExtension::getClasses
  • ReflectionExtension::getConstants »
  • PHP Manual
  • ReflectionExtension
  • Obtiene nombres de las clases

ReflectionExtension::getClassNames

(PHP 5, PHP 7)

ReflectionExtension::getClassNames — Obtiene nombres de las clases

Descripción

public ReflectionExtension::getClassNames ( ) : array

Devuelve una lsita de los nombres de las clases que pertenecen a esta extensión.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un array con los nombres de las clases, tal como estuvieran definidos en la extensión. Si no hubiera ninguna clase, se devolvería un array vacío.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionExtension::getClassNames()

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClassNames());
?>

El resultado del ejemplo sería algo similar a:

array(1) {
  [0]=>
  string(9) "XMLWriter"
}

Ver también

  • ReflectionExtension::getClasses() - Obtiene clases
  • ReflectionExtension::getName() - Obtiene el nombre de la extensión

User Contributed Notes

There are no user contributed notes for this page.


Obtiene las constantes

  • « ReflectionExtension::getClassNames
  • ReflectionExtension::getDependencies »
  • PHP Manual
  • ReflectionExtension
  • Obtiene las constantes

ReflectionExtension::getConstants

(PHP 5, PHP 7)

ReflectionExtension::getConstants — Obtiene las constantes

Descripción

public ReflectionExtension::getConstants ( ) : array

Devuelve las constantes definidas dentro de una extensión.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Array asociativo utilizando los nombres de constantes en las claves.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionExtension::getConstants()

<?php
$ext = new ReflectionExtension('DOM');

print_r($ext->getConstants());
?>

El resultado del ejemplo sería algo similar a:

Array
(
    [XML_ELEMENT_NODE] => 1
    [XML_ATTRIBUTE_NODE] => 2
    [XML_TEXT_NODE] => 3
    [XML_CDATA_SECTION_NODE] => 4
    [XML_ENTITY_REF_NODE] => 5
    [XML_ENTITY_NODE] => 6
    [XML_PI_NODE] => 7
    [XML_COMMENT_NODE] => 8
    [XML_DOCUMENT_NODE] => 9
    [XML_DOCUMENT_TYPE_NODE] => 10
    [XML_DOCUMENT_FRAG_NODE] => 11
    [XML_NOTATION_NODE] => 12
    [XML_HTML_DOCUMENT_NODE] => 13
    [XML_DTD_NODE] => 14
    [XML_ELEMENT_DECL_NODE] => 15
    [XML_ATTRIBUTE_DECL_NODE] => 16
    [XML_ENTITY_DECL_NODE] => 17
    [XML_NAMESPACE_DECL_NODE] => 18
    [XML_LOCAL_NAMESPACE] => 18
    [XML_ATTRIBUTE_CDATA] => 1
    [XML_ATTRIBUTE_ID] => 2
    [XML_ATTRIBUTE_IDREF] => 3
    [XML_ATTRIBUTE_IDREFS] => 4
    [XML_ATTRIBUTE_ENTITY] => 6
    [XML_ATTRIBUTE_NMTOKEN] => 7
    [XML_ATTRIBUTE_NMTOKENS] => 8
    [XML_ATTRIBUTE_ENUMERATION] => 9
    [XML_ATTRIBUTE_NOTATION] => 10
    [DOM_PHP_ERR] => 0
    [DOM_INDEX_SIZE_ERR] => 1
    [DOMSTRING_SIZE_ERR] => 2
    [DOM_HIERARCHY_REQUEST_ERR] => 3
    [DOM_WRONG_DOCUMENT_ERR] => 4
    [DOM_INVALID_CHARACTER_ERR] => 5
    [DOM_NO_DATA_ALLOWED_ERR] => 6
    [DOM_NO_MODIFICATION_ALLOWED_ERR] => 7
    [DOM_NOT_FOUND_ERR] => 8
    [DOM_NOT_SUPPORTED_ERR] => 9
    [DOM_INUSE_ATTRIBUTE_ERR] => 10
    [DOM_INVALID_STATE_ERR] => 11
    [DOM_SYNTAX_ERR] => 12
    [DOM_INVALID_MODIFICATION_ERR] => 13
    [DOM_NAMESPACE_ERR] => 14
    [DOM_INVALID_ACCESS_ERR] => 15
    [DOM_VALIDATION_ERR] => 16
)

Ver también

  • ReflectionExtension::getINIEntries() - Obtiene las entradas INI de la extensión

User Contributed Notes

There are no user contributed notes for this page.


Obtiene las dependencias

  • « ReflectionExtension::getConstants
  • ReflectionExtension::getFunctions »
  • PHP Manual
  • ReflectionExtension
  • Obtiene las dependencias

ReflectionExtension::getDependencies

(PHP 5 >= 5.1.3, PHP 7)

ReflectionExtension::getDependencies — Obtiene las dependencias

Descripción

public ReflectionExtension::getDependencies ( ) : array

Devuelve las dependencias, listando tanto aquéllas que sean obligatorias, como las conflictivas.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un array asociativo con los nombres de las dependencias como clave, y Required (obligatorio), Optional (opcional) o Conflicts (conflictivo) como valor.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionExtension::getDependencies()

<?php
$dom = new ReflectionExtension('dom');

print_r($dom->getDependencies());
?>

El resultado del ejemplo sería algo similar a:

Array
(
    [libxml] => Required
    [domxml] => Conflicts
)

Ver también

  • ReflectionClass::getVersion()

User Contributed Notes

There are no user contributed notes for this page.


Obtiene las funciones de una extensión

  • « ReflectionExtension::getDependencies
  • ReflectionExtension::getINIEntries »
  • PHP Manual
  • ReflectionExtension
  • Obtiene las funciones de una extensión

ReflectionExtension::getFunctions

(PHP 5, PHP 7)

ReflectionExtension::getFunctions — Obtiene las funciones de una extensión

Descripción

public ReflectionExtension::getFunctions ( ) : array

Devuelve las funciones definidas en una extensión.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Array asociativo de objetos ReflectionFunction. Para cada función que haya definida en la extensión, se usará su nombre como valor de clave del array. Si no hubiera ninguna función definida, se devolvería un array vacío.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionExtension::getFunctions()

<?php
$dom = new ReflectionExtension('SimpleXML');

print_r($dom->getFunctions());
?>

El resultado del ejemplo sería algo similar a:

Array
(
    [simplexml_load_file] => ReflectionFunction Object
        (
            [name] => simplexml_load_file
        )

    [simplexml_load_string] => ReflectionFunction Object
        (
            [name] => simplexml_load_string
        )

    [simplexml_import_dom] => ReflectionFunction Object
        (
            [name] => simplexml_import_dom
        )

)

Ver también

  • ReflectionExtension::getClasses() - Obtiene clases
  • get_extension_funcs() - Devuelve una matriz con los nombres de funciones de un módulo

User Contributed Notes

There are no user contributed notes for this page.


Obtiene las entradas INI de la extensión

  • « ReflectionExtension::getFunctions
  • ReflectionExtension::getName »
  • PHP Manual
  • ReflectionExtension
  • Obtiene las entradas INI de la extensión

ReflectionExtension::getINIEntries

(PHP 5, PHP 7)

ReflectionExtension::getINIEntries — Obtiene las entradas INI de la extensión

Descripción

public ReflectionExtension::getINIEntries ( ) : array

Devuelve las entradas INI de la extensión.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un array asociativo usando la entrada INI en la clave, y su valor como valor del elemento del array.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionExtension::getINIEntries()

<?php
$ext = new ReflectionExtension('mysql');

print_r($ext->getINIEntries());
?>

El resultado del ejemplo sería algo similar a:

Array
(
    [mysql.allow_persistent] => 1
    [mysql.max_persistent] => -1
    [mysql.max_links] => -1
    [mysql.default_host] =>
    [mysql.default_user] =>
    [mysql.default_password] =>
    [mysql.default_port] =>
    [mysql.default_socket] =>
    [mysql.connect_timeout] => 60
    [mysql.trace_mode] =>
    [mysql.allow_local_infile] => 1
    [mysql.cache_size] => 2000
)

Ver también

  • ini_get_all() - Obtiene todas las opciones de configuración
  • ReflectionExtension::getConstants() - Obtiene las constantes

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el nombre de la extensión

  • « ReflectionExtension::getINIEntries
  • ReflectionExtension::getVersion »
  • PHP Manual
  • ReflectionExtension
  • Obtiene el nombre de la extensión

ReflectionExtension::getName

(PHP 5, PHP 7)

ReflectionExtension::getName — Obtiene el nombre de la extensión

Descripción

public ReflectionExtension::getName ( ) : string

Devuelve el nombre de la extensión.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Nombre de la extensión.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionExtension::getName()

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getName());
?>

El resultado del ejemplo sería algo similar a:

string(6) "mysqli"

Ver también

  • ReflectionExtension::getClassNames() - Obtiene nombres de las clases

User Contributed Notes

There are no user contributed notes for this page.


Obtiene la versión de una extensión

  • « ReflectionExtension::getName
  • ReflectionExtension::info »
  • PHP Manual
  • ReflectionExtension
  • Obtiene la versión de una extensión

ReflectionExtension::getVersion

(PHP 5, PHP 7)

ReflectionExtension::getVersion — Obtiene la versión de una extensión

Descripción

public ReflectionExtension::getVersion ( ) : string

Devuelve la versión de la extensión.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Versión de la extensión.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionExtension::getVersion()

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getVersion());
?>

El resultado del ejemplo sería algo similar a:

string(3) "0.1"

Ver también

  • ReflectionExtension::info() - Imprime información sobre la extensión

User Contributed Notes

There are no user contributed notes for this page.


Imprime información sobre la extensión

  • « ReflectionExtension::getVersion
  • ReflectionExtension::isPersistent »
  • PHP Manual
  • ReflectionExtension
  • Imprime información sobre la extensión

ReflectionExtension::info

(PHP 5 >= 5.2.4, PHP 7)

ReflectionExtension::info — Imprime información sobre la extensión

Descripción

public ReflectionExtension::info ( ) : void

Imprime el bloque de "phpinfo()" correspondiente a la extensión dada.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Información sobre la extensión.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionExtension::info()

<?php
$ext = new ReflectionExtension('mysqli');
$ext->info();
?>

El resultado del ejemplo sería algo similar a:

mysqli

MysqlI Support => enabled
Client API library version => mysqlnd 5.0.5-dev - 081106 - $Revision$
Active Persistent Links => 0
Inactive Persistent Links => 0
Active Links => 0
Persistent cache => enabled
put_hits => 0
put_misses => 0
get_hits => 0
get_misses => 0
size => 2000
free_items => 2000
references => 2

Directive => Local Value => Master Value
mysqli.max_links => Unlimited => Unlimited
mysqli.max_persistent => Unlimited => Unlimited
mysqli.allow_persistent => On => On
mysqli.default_host => no value => no value
mysqli.default_user => no value => no value
mysqli.default_pw => no value => no value
mysqli.default_port => 3306 => 3306
mysqli.default_socket => no value => no value
mysqli.reconnect => Off => Off
mysqli.allow_local_infile => On => On
mysqli.cache_size => 2000 => 2000

Ver también

  • ReflectionExtension::getName() - Obtiene el nombre de la extensión
  • phpinfo() - Muestra información sobre la configuración de PHP

User Contributed Notes

There are no user contributed notes for this page.


Indica si la extensión es persistente

  • « ReflectionExtension::info
  • ReflectionExtension::isTemporary »
  • PHP Manual
  • ReflectionExtension
  • Indica si la extensión es persistente

ReflectionExtension::isPersistent

(PHP 5 >= 5.4.0, PHP 7)

ReflectionExtension::isPersistent — Indica si la extensión es persistente

Descripción

public ReflectionExtension::isPersistent ( ) : void

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true si la extensión ha sido cargado por extension, o false en caso contrario.

Ver también

  • ReflectionExtension::isTemporary() - Indica si la extensión es temporal

User Contributed Notes

There are no user contributed notes for this page.


Indica si la extensión es temporal

  • « ReflectionExtension::isPersistent
  • ReflectionExtension::__toString »
  • PHP Manual
  • ReflectionExtension
  • Indica si la extensión es temporal

ReflectionExtension::isTemporary

(PHP 5 >= 5.4.0, PHP 7)

ReflectionExtension::isTemporary — Indica si la extensión es temporal

Descripción

public ReflectionExtension::isTemporary ( ) : void

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true para las extensiones cargadas con dl(), o false en caso contrario.

Ver también

  • ReflectionExtension::isPersistent() - Indica si la extensión es persistente

User Contributed Notes

There are no user contributed notes for this page.


Convertir a string

  • « ReflectionExtension::isTemporary
  • ReflectionFunction »
  • PHP Manual
  • ReflectionExtension
  • Convertir a string

ReflectionExtension::__toString

(PHP 5, PHP 7)

ReflectionExtension::__toString — Convertir a string

Descripción

public ReflectionExtension::__toString ( ) : string

Exporta una extensión reflexionada devolvíendola en forma de string. Es equivalente al método ReflectionExtension::export() estableciendo en el parámetro return el valor true.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve la extensión en forma de string, de la misma forma que haría ReflectionExtension::export().

Ver también

  • ReflectionExtension::__construct() - Constructor de los objetos ReflectionExtension
  • ReflectionExtension::export() - Exportar
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


Clase ReflectionFunction

(PHP 5, PHP 7)

Introducción

La ReflectionFunction muestra información sobre una función.

Sinopsis de la Clase

ReflectionFunction extends ReflectionFunctionAbstract implements Reflector {
/* Constantes */
const integer IS_DEPRECATED = 262144 ;
/* Propiedades */
public $name ;
/* Métodos */
public __construct ( mixed $name )
public static export ( string $name , string $return = ? ) : string
public getClosure ( ) : Closure
public invoke ( mixed $... = ? ) : mixed
public invokeArgs ( array $args ) : mixed
public isDisabled ( ) : bool
public __toString ( ) : string
/* Métodos heredados */
final private ReflectionFunctionAbstract::__clone ( ) : void
public ReflectionFunctionAbstract::getClosureScopeClass ( ) : ReflectionClass
public ReflectionFunctionAbstract::getClosureThis ( ) : object
public ReflectionFunctionAbstract::getDocComment ( ) : string
public ReflectionFunctionAbstract::getEndLine ( ) : int
public ReflectionFunctionAbstract::getExtension ( ) : ReflectionExtension
public ReflectionFunctionAbstract::getExtensionName ( ) : string
public ReflectionFunctionAbstract::getFileName ( ) : string
public ReflectionFunctionAbstract::getName ( ) : string
public ReflectionFunctionAbstract::getNamespaceName ( ) : string
public ReflectionFunctionAbstract::getNumberOfParameters ( ) : int
public ReflectionFunctionAbstract::getNumberOfRequiredParameters ( ) : int
public ReflectionFunctionAbstract::getParameters ( ) : array
public ReflectionFunctionAbstract::getReturnType ( ) : ReflectionType|null
public ReflectionFunctionAbstract::getShortName ( ) : string
public ReflectionFunctionAbstract::getStartLine ( ) : int
public ReflectionFunctionAbstract::getStaticVariables ( ) : array
public ReflectionFunctionAbstract::hasReturnType ( ) : bool
public ReflectionFunctionAbstract::inNamespace ( ) : bool
public ReflectionFunctionAbstract::isClosure ( ) : bool
public ReflectionFunctionAbstract::isDeprecated ( ) : bool
public ReflectionFunctionAbstract::isGenerator ( ) : bool
public ReflectionFunctionAbstract::isInternal ( ) : bool
public ReflectionFunctionAbstract::isUserDefined ( ) : bool
public ReflectionFunctionAbstract::isVariadic ( ) : bool
public ReflectionFunctionAbstract::returnsReference ( ) : bool
abstract public ReflectionFunctionAbstract::__toString ( ) : void
}

Propiedades

name

Nombre de la función. De sólo lectura, lanza una ReflectionException en el intento de escribir.

Constantes predefinidas

Modificadores ReflectionFunction

ReflectionFunction::IS_DEPRECATED

Indica las funciones obsoletas.

Tabla de contenidos

  • ReflectionFunction::__construct — Contruye un objeto de tipo ReflectionFunction
  • ReflectionFunction::export — Exporta una función
  • ReflectionFunction::getClosure — Genera dinámicamente una función anónima de esta función
  • ReflectionFunction::invoke — Invoca una función
  • ReflectionFunction::invokeArgs — Invoca a la función con argumentos
  • ReflectionFunction::isDisabled — Comprueba si una función está desactivada
  • ReflectionFunction::__toString — Convertir a string

User Contributed Notes

a dot lucassilvadeoliveira at gmail dot com 28-Nov-2020 06:15
We can use this functionality to automatically pass arguments to our function based on some data structure.

NOTE: I am using a php 8.0> feature called "Nameds parameter"

<?php

$valuesToProcess = [
  'name' => 'Anderson Lucas Silva de Oliveira',
  'age' => 21,
  'hobbie' => 'Play games'
];

function processUserData($name, $age, $job = "", $hobbie = "")
{
    $msg = "Hello $name. You have $age years old";
    if (!empty($job)) {
    $msg .= ". Your job is $job";
    }

    if (!empty($hobbie)) {
        $msg .= ". Your hobbie is $hobbie";
    }

    echo $msg . ".";
}

$refFunction = new ReflectionFunction('processUserData');
$parameters = $refFunction->getParameters();

$validParameters = [];
foreach ($parameters as $parameter) {
    if (!array_key_exists($parameter->getName(), $valuesToProcess) && !$parameter->isOptional()) {
        throw new DomainException('Cannot resolve the parameter' . $parameter->getName());
    }

    if(!array_key_exists($parameter->getName(), $valuesToProcess)) {
        continue;
    }

    $validParameters[$parameter->getName()] = $valuesToProcess[$parameter->getName()];
}

$refFunction->invoke(...$validParameters);
?>

Results in:

Hello Anderson Lucas Silva de Oliveira. You have 21 years old. Your hobbie is Play games.
Lorenz R.S. 12-Aug-2011 01:24
Here is a concise example of ReflectionFunction usage for Parameter Reflection / introspection (e.g. to automatically generate API descriptions)

<?php
$properties = $reflector->getProperties();
$refFunc = new ReflectionFunction('preg_replace');
foreach( $refFunc->getParameters() as $param ){
    //invokes ¦ReflectionParameter::__toString
    print $param;
}
?>

prints:

Parameter #0 [ <required> $regex ]
Parameter #1 [ <required> $replace ]
Parameter #2 [ <required> $subject ]
Parameter #3 [ <optional> $limit ]
Parameter #4 [ <optional> &$count ]


Contruye un objeto de tipo ReflectionFunction

  • « ReflectionFunction
  • ReflectionFunction::export »
  • PHP Manual
  • ReflectionFunction
  • Contruye un objeto de tipo ReflectionFunction

ReflectionFunction::__construct

(PHP 5, PHP 7)

ReflectionFunction::__construct — Contruye un objeto de tipo ReflectionFunction

Descripción

public ReflectionFunction::__construct ( mixed $name )

Construye un objeto de tipo ReflectionFunction.

Parámetros

name

Nombre de la función que se desea reflexionar, o una función anónima.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

Lanza ReflectionException si el parámetro name no contuviera una función válida.

Historial de cambios

Versión | Descripción
5.3.0 | ahora name puede representar una función anónima.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionFunction::__construct()

<?php
/**
 * Contador sencillo
 *
 * @return    int
 */
function contador1()
{
    static $c = 0;
    return ++$c;
}

/**
 * Otro contador sencillo
 *
 * @return    int
 */
$contador2 = function()
{
    static $d = 0;
    return ++$d;

};

function mostrarFuncionesReflexionadas($func)
{
    // Mostrar información básica
    printf(
        "\n\n===> La función %s '%s'\n".
        "     declarada en %s\n".
        "     líneas %d a %d\n",
        $func->isInternal() ? 'interna' : 'definida por el usuario',
        $func->getName(),
        $func->getFileName(),
        $func->getStartLine(),
        $func->getEndline()
    );

    // Mostrar comentarios de documentación
    printf("---> Documentación:\n %s\n", var_export($func->getDocComment(), 1));

    // Mostrar, si existen, variables estáticas
    if ($statics = $func->getStaticVariables())
    {
        printf("---> Variables estáticas: %s\n", var_export($statics, 1));
    }
}

// Crear una instancia de la clase ReflectionFunction
mostrarFuncionesReflexionadas(new ReflectionFunction('contador1'));
mostrarFuncionesReflexionadas(new ReflectionFunction($contador2));
?>

El resultado del ejemplo sería algo similar a:

===> La función definida por el usuario 'contador1'
     declarada en /Users/chuso/dropme.php
     líneas 7 a 11
---> Documentación:
 '/**
 * Contador sencillo
 *
 * @return    int
 */'
---> Variables estáticas: array (
  'c' => 0,
)

===> La función definida por el usuario '{closure}'
     declarada en /Users/chuso/dropme.php
     líneas 18 a 23
---> Documentación:
 '/**
 * Otro contador sencillo
 *
 * @return    int
 */'
---> Variables estáticas: array (
  'd' => 0,
)

Ver también

  • ReflectionMethod::__construct() - Construye un objeto ReflectionMethod
  • Constructores

User Contributed Notes

There are no user contributed notes for this page.


Exporta una función

  • « ReflectionFunction::__construct
  • ReflectionFunction::getClosure »
  • PHP Manual
  • ReflectionFunction
  • Exporta una función

ReflectionFunction::export

(PHP 5, PHP 7)

ReflectionFunction::export — Exporta una función

Descripción

public static ReflectionFunction::export ( string $name , string $return = ? ) : string

Exporta una función reflexionada.

Parámetros

name

La reflexión a exportar.

return

Configurarlo a true devolverá la exportación, a diferencia de emitirla. Configurarlo a false (el valor por defecto) hará lo contrario.

Valores devueltos

Si el parámetro return es seteado a true, la exportación se devolverá como un string, de lo contrario se retornará null.

Ver también

  • ReflectionFunction::invoke() - Invoca una función

User Contributed Notes

hytest at gmail dot com 22-Nov-2011 08:04
Example:

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

echo ReflectionFunction::export('title',true);

?>

Output:

Function [ <user> function title ] {
  @@ /path/to/file.php 2 - 5

  - Parameters [2] {
    Parameter #0 [ <required> $title ]
    Parameter #1 [ <required> $name ]
  }
}


Genera dinámicamente una función anónima de esta función

  • « ReflectionFunction::export
  • ReflectionFunction::invoke »
  • PHP Manual
  • ReflectionFunction
  • Genera dinámicamente una función anónima de esta función

ReflectionFunction::getClosure

(PHP 5 >= 5.4.0, PHP 7)

ReflectionFunction::getClosure — Genera dinámicamente una función anónima de esta función

Descripción

public ReflectionFunction::getClosure ( ) : Closure

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve un objeto Closure. En caso de error, devuelve null.

User Contributed Notes

php dot net-bug at spamhereplease dot com 23-Nov-2013 05:34
If you have a callback that is going to be invoked often, you can use this method (and the related method for ReflectProperty) to get a closure that will execute at near native speed.

Some benchmark comparisons with php 5.4.22 on ubuntu:

[function call]      [time]     [%slower]
function():          0.09527      0%
Reflection::Closure: 0.09729      2%
$string():           0.102641     8%
Reflection:          0.197122   107%
call_user_func:      0.214045   125%

[method call]        [time]  [% slower] [%vs func]
->method():          0.103611    0%       9%
Reflection::Closure: 0.1043      1%       9%
$string():           0.109885    6%      15%
Reflection:          0.20451    97%     115%
call_user_func:      0.219205  112%     130%


Invoca una función

  • « ReflectionFunction::getClosure
  • ReflectionFunction::invokeArgs »
  • PHP Manual
  • ReflectionFunction
  • Invoca una función

ReflectionFunction::invoke

(PHP 5, PHP 7)

ReflectionFunction::invoke — Invoca una función

Descripción

public ReflectionFunction::invoke ( mixed $... = ? ) : mixed

Invoca una función reflejada.

Parámetros

...

Lista de argumentos que se pasan a la función. Acepta un número variabel de argumentos, que se pasan a la función de manera similar a como lo hace call_user_func().

Valores devueltos

Devuelve el resultado de llamar a la función invocada.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionFunction::invoke() example

<?php
function titule($titule, $nombre)
{
    return sprintf("%s. %s\r\n", $titulo, $nombre);
}

$funcion = new ReflectionFunction('titule');

echo $funcion->invoke('Sr', 'Pedro');
?>

El resultado del ejemplo sería:

Sr. Pedro

Notas

Nota:

Si la función tiene argumentos que necesitan ser referencias, éstos deben ser referencias en la lista de argumentos pasados.

Ver también

  • ReflectionFunction::export() - Exporta una función
  • __invoke()
  • call_user_func() - Llamar a una llamada de retorno dada por el primer parámetro

User Contributed Notes

spark at limao dot com dot br 10-Jun-2011 10:55
I know Reflections classes have a lot of power, but sometimes all we need is to store a annonymus function or even create a simple callback somewhere.

so here it is, the Callback class:
<?php
    class Callback{
        private $name = false;

        public function Callback($obj,$call=false){
            $name = array($obj);
            if($call) $name[] = $call;

            $this->name = $name;
        }
        public function invoke($params=array()){
            return call_user_func_array($this->name,$params);
        }
    }
?>

Usage:
<?php
    function sayName(){
        return "goku";
    }

    $myVar = new Callback("sayName");

    echo "Hi, I am ".$myVar->invoke()."!";

    //also works with methods: new Callback($obj,"method");
?>


Invoca a la función con argumentos

  • « ReflectionFunction::invoke
  • ReflectionFunction::isDisabled »
  • PHP Manual
  • ReflectionFunction
  • Invoca a la función con argumentos

ReflectionFunction::invokeArgs

(PHP 5 >= 5.1.2, PHP 7)

ReflectionFunction::invokeArgs — Invoca a la función con argumentos

Descripción

public ReflectionFunction::invokeArgs ( array $args ) : mixed

Invoca la función y pasa sus argumentos como array.

Parámetros

args

Array con la lista de argumentos que se pasan a la función, similar a cómo funciona call_user_func_array().

Valores devueltos

Devuelve el resultado de la función invocada

Ejemplos

Ejemplo #1 Ejemplo de ReflectionFunction::invokeArgs()

<?php
function titulo($titulo, $nombre)
{
    return sprintf("%s. %s\r\n", $titulo, $nombre);
}

$function = new ReflectionFunction('titulo');

echo $function->invokeArgs(array('Sr', 'Pedro'));
?>

El resultado del ejemplo sería:

Dr. Pedro

Ejemplo #2 Ejemplo de ReflectionFunction::invokeArgs() con argumentos por referencia

<?php
function obtener_condiciones_falsas(array $condiciones, array &$condiciones_falsas)
{
    foreach ($condiciones as $condicion) {
        if (!$condicion) {
            $condiciones_falsas[] = $condicion;
        }
    }
}

$ref_a_funcion     = new ReflectionFunction('obtener_condiciones_falsas');

$condiciones        = array(true, false, -1, 0, 1);
$condiciones_falsas = array();

$ref_a_funcion->invokeArgs(array($condiciones, &$condiciones_falsas));

var_dump($condiciones_falsas);
?>

El resultado del ejemplo sería:

array(2) {
  [0]=>
  bool(false)
  [1]=>
  int(0)
}

Notas

Nota:

Si la función tiene argumentos que necesitan ser referencias, éstos deben ser referencias en la lista de argumentos pasados.

Ver también

  • ReflectionFunction::invoke() - Invoca una función
  • ReflectionFunctionAbstract::getNumberOfParameters() - Obtiene el número total de parámetros
  • __invoke()
  • call_user_func_array() - Llamar a una llamada de retorno con un array de parámetros

User Contributed Notes

theyourcomputer at gmail dot com 05-Dec-2017 01:40
In the case of call_user_func_array(), if you were to pass around an anonymous function and reference $this within the anonymous function, $this will faithfully refer to the class in the context in which the function was defined. Using ReflectionFunction::invokeArgs() does not seem to retain its original context--yeah, even if you bind the anonymous function before invoking. I recommend call_user_func_array() where context is a concern.
Andrea Giammarchi 16-Feb-2008 06:41
I encountered a weird problem with ReflectionFunction, described in ticket 44139 of PHP Bugs.

If for some reason you need to call with invoke, or invokeArgs, a function like array_unshift (that accepts internally the array by reference) you could use this code to avoid the generated warning or fatal error.

<?php
function unshift(){
    $ref        = new ReflectionFunction('array_unshift');
    $arguments    = func_get_args();
    return        $ref->invokeArgs(array_merge(array(&$this->arr), $arguments));
}
?>

I don't know about performances (you can create an array manually too, starting from array(&$this->something) and adding arguments). However, it seems to work correctly without problems, at least until the send by reference will be usable with one single value ...


Comprueba si una función está desactivada

  • « ReflectionFunction::invokeArgs
  • ReflectionFunction::__toString »
  • PHP Manual
  • ReflectionFunction
  • Comprueba si una función está desactivada

ReflectionFunction::isDisabled

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunction::isDisabled — Comprueba si una función está desactivada

Descripción

public ReflectionFunction::isDisabled ( ) : bool

Comprueba si una función está desactivada, mediante la directiva disable_functions.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si está desactivadao, o false en caso contrario.

Ver también

  • ReflectionFunctionAbstract::isUserDefined() - Comprueba si es una función definida por un usuario
  • directiva disable_functions

User Contributed Notes

There are no user contributed notes for this page.


Convertir a string

  • « ReflectionFunction::isDisabled
  • ReflectionFunctionAbstract »
  • PHP Manual
  • ReflectionFunction
  • Convertir a string

ReflectionFunction::__toString

(PHP 5, PHP 7)

ReflectionFunction::__toString — Convertir a string

Descripción

public ReflectionFunction::__toString ( ) : string

Convierte a string.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve una salida similar a la de ReflectionFunction::export().

Ejemplos

Ejemplo #1 Ejemplo de ReflectionFunction::__toString()

<?php
function título($título, $nombre)
{
    return sprintf("%s. %s\r\n", $título, $nombre);
}

echo new ReflectionFunction('título');
?>

El resultado del ejemplo sería algo similar a:

Function [ <user> function title ] {
  @@ Command line code 2 - 5

  - Parameters [2] {
    Parameter #0 [ <required> $título ]
    Parameter #1 [ <required> $nombre ]
  }
}

Ver también

  • ReflectionFunction::export() - Exporta una función
  • ReflectionClass::clone()
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


Clase ReflectionFunctionAbstract

(PHP 5 >= 5.2.0, PHP 7)

Introducción

Clase padre de ReflectionFunction. Lea su descripción para conocer más detalles.

Sinopsis de la Clase

ReflectionFunctionAbstract implements Reflector {
/* Propiedades */
public $name ;
/* Métodos */
final private __clone ( ) : void
public getClosureScopeClass ( ) : ReflectionClass
public getClosureThis ( ) : object
public getDocComment ( ) : string
public getEndLine ( ) : int
public getExtension ( ) : ReflectionExtension
public getExtensionName ( ) : string
public getFileName ( ) : string
public getName ( ) : string
public getNamespaceName ( ) : string
public getNumberOfParameters ( ) : int
public getNumberOfRequiredParameters ( ) : int
public getParameters ( ) : array
public getReturnType ( ) : ReflectionType|null
public getShortName ( ) : string
public getStartLine ( ) : int
public getStaticVariables ( ) : array
public hasReturnType ( ) : bool
public inNamespace ( ) : bool
public isClosure ( ) : bool
public isDeprecated ( ) : bool
public isGenerator ( ) : bool
public isInternal ( ) : bool
public isUserDefined ( ) : bool
public isVariadic ( ) : bool
public returnsReference ( ) : bool
abstract public __toString ( ) : void
}

Propiedades

name

Nombre de la función. De sólo lectura, lanza una ReflectionException en el intento de escribir.

Tabla de contenidos

  • ReflectionFunctionAbstract::__clone — Clona una función
  • ReflectionFunctionAbstract::getClosureScopeClass — Devuelve el ámbito asociado al cierre
  • ReflectionFunctionAbstract::getClosureThis — Devuelve una función anónima que apunta a esta función
  • ReflectionFunctionAbstract::getDocComment — Obtiene comentarios de documentación
  • ReflectionFunctionAbstract::getEndLine — Obtiene número de linea final
  • ReflectionFunctionAbstract::getExtension — Obtiene información sobre la extensión
  • ReflectionFunctionAbstract::getExtensionName — Obtiene el nombre de la extensión
  • ReflectionFunctionAbstract::getFileName — Obtiene el nombre del fichero
  • ReflectionFunctionAbstract::getName — Obtiene el nombre de la función
  • ReflectionFunctionAbstract::getNamespaceName — Obtiene el nombre del espacio de nombres
  • ReflectionFunctionAbstract::getNumberOfParameters — Obtiene el número total de parámetros
  • ReflectionFunctionAbstract::getNumberOfRequiredParameters — Obtiene el número de parámetros obligatorios
  • ReflectionFunctionAbstract::getParameters — Obtiene los parámetros
  • ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function
  • ReflectionFunctionAbstract::getShortName — Obtiene el nombre abreviado de la función
  • ReflectionFunctionAbstract::getStartLine — Obtiene el número de la línea de inicio
  • ReflectionFunctionAbstract::getStaticVariables — Obtiene las variable estáticas
  • ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type
  • ReflectionFunctionAbstract::inNamespace — Comprueba si pertenece a un espacio de nombres
  • ReflectionFunctionAbstract::isClosure — Comprobar si es un cierre
  • ReflectionFunctionAbstract::isDeprecated — Comprueba si está obsoleta
  • ReflectionFunctionAbstract::isGenerator — Devuelve si la función es un generador
  • ReflectionFunctionAbstract::isInternal — Comprueba si la función es interna
  • ReflectionFunctionAbstract::isUserDefined — Comprueba si es una función definida por un usuario
  • ReflectionFunctionAbstract::isVariadic — Comprueba si la función es varíadica
  • ReflectionFunctionAbstract::returnsReference — Comprueba si devuelve una referencia
  • ReflectionFunctionAbstract::__toString — Convertir a texto

User Contributed Notes

There are no user contributed notes for this page.


Clona una función

  • « ReflectionFunctionAbstract
  • ReflectionFunctionAbstract::getClosureScopeClass »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Clona una función

ReflectionFunctionAbstract::__clone

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::__clone — Clona una función

Descripción

final private ReflectionFunctionAbstract::__clone ( ) : void

Clona una función.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Ver también

  • Clonación de objetos

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el ámbito asociado al cierre

  • « ReflectionFunctionAbstract::__clone
  • ReflectionFunctionAbstract::getClosureThis »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Devuelve el ámbito asociado al cierre

ReflectionFunctionAbstract::getClosureScopeClass

(PHP 5 >= 5.4.0, PHP 7)

ReflectionFunctionAbstract::getClosureScopeClass — Devuelve el ámbito asociado al cierre

Descripción

public ReflectionFunctionAbstract::getClosureScopeClass ( ) : ReflectionClass

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve la clase en caso de éxito o null en caso de fallo.

User Contributed Notes

There are no user contributed notes for this page.


Devuelve una función anónima que apunta a esta función

  • « ReflectionFunctionAbstract::getClosureScopeClass
  • ReflectionFunctionAbstract::getDocComment »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Devuelve una función anónima que apunta a esta función

ReflectionFunctionAbstract::getClosureThis

(PHP 5 >= 5.4.0, PHP 7)

ReflectionFunctionAbstract::getClosureThis — Devuelve una función anónima que apunta a esta función

Descripción

public ReflectionFunctionAbstract::getClosureThis ( ) : object

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve un puntero a $this. En caso de error, devuelve null.

User Contributed Notes

There are no user contributed notes for this page.


Obtiene comentarios de documentación

  • « ReflectionFunctionAbstract::getClosureThis
  • ReflectionFunctionAbstract::getEndLine »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene comentarios de documentación

ReflectionFunctionAbstract::getDocComment

(PHP 5 >= 5.1.0, PHP 7)

ReflectionFunctionAbstract::getDocComment — Obtiene comentarios de documentación

Descripción

public ReflectionFunctionAbstract::getDocComment ( ) : string

Devuelve los comentarios de documentación de una función.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Si existieran, comentarios de documentación. En caso contrario, false.

Ver también

  • ReflectionFunctionAbstract::getStartLine() - Obtiene el número de la línea de inicio

User Contributed Notes

jens dot kohl+php at gmail dot com 26-Mar-2012 11:19
Beware when you try to use the getDocComment() methods with eAccelerator turned on. eAccelerator »optimizes« your code in a way that it removes any comments from your source. So at runtime you're not able to get any comments and therefor getDocComments return false.
bruno at vault7 dot com 12-Nov-2009 11:09
In order to retrieve a comment with this method, the comment must be imediately before the class, function or method, start with /** and end with */


Obtiene número de linea final

  • « ReflectionFunctionAbstract::getDocComment
  • ReflectionFunctionAbstract::getExtension »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene número de linea final

ReflectionFunctionAbstract::getEndLine

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getEndLine — Obtiene número de linea final

Descripción

public ReflectionFunctionAbstract::getEndLine ( ) : int

Devuelve el número de linea final.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

El número de la línea final de la función definida por el usuario, o false si fuera desconocido.

Ver también

  • ReflectionFunctionAbstract::getStartLine() - Obtiene el número de la línea de inicio

User Contributed Notes

There are no user contributed notes for this page.


Obtiene información sobre la extensión

  • « ReflectionFunctionAbstract::getEndLine
  • ReflectionFunctionAbstract::getExtensionName »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene información sobre la extensión

ReflectionFunctionAbstract::getExtension

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getExtension — Obtiene información sobre la extensión

Descripción

public ReflectionFunctionAbstract::getExtension ( ) : ReflectionExtension

Devuelve información de la extensión a la que pertenece la función.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Información de la extensión, en forma de objeto ReflectionExtension.

Ver también

  • ReflectionFunctionAbstract::getExtensionName() - Obtiene el nombre de la extensión

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el nombre de la extensión

  • « ReflectionFunctionAbstract::getExtension
  • ReflectionFunctionAbstract::getFileName »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene el nombre de la extensión

ReflectionFunctionAbstract::getExtensionName

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getExtensionName — Obtiene el nombre de la extensión

Descripción

public ReflectionFunctionAbstract::getExtensionName ( ) : string

Devuelve el nombre de la extensión.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Nombre de la extensión.

Ver también

  • ReflectionFunctionAbstract::getExtension() - Obtiene información sobre la extensión

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el nombre del fichero

  • « ReflectionFunctionAbstract::getExtensionName
  • ReflectionFunctionAbstract::getName »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene el nombre del fichero

ReflectionFunctionAbstract::getFileName

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getFileName — Obtiene el nombre del fichero

Descripción

public ReflectionFunctionAbstract::getFileName ( ) : string

Obtiene el nombre de fichero que contiene una función definida por el usuario.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Nombre del fichero.

Ver también

  • ReflectionFunctionAbstract::getNamespaceName() - Obtiene el nombre del espacio de nombres

User Contributed Notes

stein at visibone dot com 04-Jul-2013 10:53
Returns FALSE for an internal function (when isInternal() returns TRUE, e.g. for 'strlen').


Obtiene el nombre de la función

  • « ReflectionFunctionAbstract::getFileName
  • ReflectionFunctionAbstract::getNamespaceName »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene el nombre de la función

ReflectionFunctionAbstract::getName

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getName — Obtiene el nombre de la función

Descripción

public ReflectionFunctionAbstract::getName ( ) : string

Devuelve el nombre de la función.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Nombre de la función.

Ver también

  • ReflectionFunctionAbstract::getExtensionName() - Obtiene el nombre de la extensión
  • ReflectionFunctionAbstract::isUserDefined() - Comprueba si es una función definida por un usuario

User Contributed Notes

PR 14-Feb-2021 01:28
If you call getName() on an anonymous function you'll get "{closure}".


Obtiene el nombre del espacio de nombres

  • « ReflectionFunctionAbstract::getName
  • ReflectionFunctionAbstract::getNumberOfParameters »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene el nombre del espacio de nombres

ReflectionFunctionAbstract::getNamespaceName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getNamespaceName — Obtiene el nombre del espacio de nombres

Descripción

public ReflectionFunctionAbstract::getNamespaceName ( ) : string

Devuelve el nombre del espacio de nombres en el que está definida la clase.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Nombre del espacio de nombres.

Ver también

  • ReflectionFunctionAbstract::getFileName() - Obtiene el nombre del fichero
  • espacios de nombres

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el número total de parámetros

  • « ReflectionFunctionAbstract::getNamespaceName
  • ReflectionFunctionAbstract::getNumberOfRequiredParameters »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene el número total de parámetros

ReflectionFunctionAbstract::getNumberOfParameters

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getNumberOfParameters — Obtiene el número total de parámetros

Descripción

public ReflectionFunctionAbstract::getNumberOfParameters ( ) : int

Devuelve el número total de parámetros definidos en una función, ya sean opcionales u obligatorios.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Número de parámetros.

Ver también

  • ReflectionFunctionAbstract::getNumberOfRequiredParameters() - Obtiene el número de parámetros obligatorios
  • func_num_args() - Devuelve el número de argumentos pasados a la función

User Contributed Notes

8ctopus 23-Nov-2020 08:26
$reflection = new ReflectionFunction('implode');
echo $reflection->getNumberOfParameters();
Robert Pitt ( LitePHP ) 11-Apr-2010 03:42
Working on a new MVC Application Framework i use this method to check how many arguments are required before calling the sub method!

Example

<?php
        $this->method_args_count = $this->CReflection
            ->getMethod($Route->getMethod())
            ->getNumberOfParameters();
        //Maybe be 5 but if uri is /controller/method/single_param/ we only of 1
        $this->params = $Route->getParams(); //0 in some cases

        if($this->method_args_count > count($this->params))
        {
            $this->difference = ($this->method_args_count - count($this->params));
            for($i=0;$i<=$this->difference;$i++)
            {
                $this->params[] = false;
            }
        }

        //Call the method with correct amount of params
        // but as false for params that have not been passed!
        call_user_func_array(array(new $this->obj,$Route->getMethod()),$this->params);
?>


Obtiene el número de parámetros obligatorios

  • « ReflectionFunctionAbstract::getNumberOfParameters
  • ReflectionFunctionAbstract::getParameters »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene el número de parámetros obligatorios

ReflectionFunctionAbstract::getNumberOfRequiredParameters

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getNumberOfRequiredParameters — Obtiene el número de parámetros obligatorios

Descripción

public ReflectionFunctionAbstract::getNumberOfRequiredParameters ( ) : int

Devuelve el número de parámetros obligatorios definidos en una función.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Número de parámetros obligatorios.

Ver también

  • ReflectionFunctionAbstract::getNumberOfParameters() - Obtiene el número total de parámetros

User Contributed Notes

cesar at magic3w dot com 07-Jul-2015 12:45
It's interesting to note that this function will treat optional parameters that come before a required parameter as required too. This is good since it allows you to verify that the function will be receiving enough parameters for the it to work, regardless where they are located.

<?php

class MyTest() {
    public function test($a = null, $b) {}
    public function test2($a = null, $b, $c = null) {}
}

//Create the reflection
$r  = new \ReflectionMethod('MyTest', 'test');
$r2 = new \ReflectionMethod('MyTest', 'test2');

//Verify the numbers
echo 'Test: ' . $r->getNumberOfRequiredParameters()); //Output: 2
echo 'Test2: ' . $r->getNumberOfRequiredParameters()); //Output: 2

?>
sebastian at sebastian-eiweleit dot de 02-Sep-2013 03:03
<?php
namespace ExampleWorld;
// The Class
class helloWorld {
    /* Method with two required arguments */

    public function requiredTwoArguments ( $var1, $var2 ) {
        // Some code ...
    }

    /* Method with two arguments, but just one is required */
    public function requiredOneArgument ( $var1, $var2 = false ) {
        // Some code ...
    }
}

$r = new \ReflectionMethod ( 'ExampleWorld\helloWorld', 'requiredTwoArguments' );
echo $r->getNumberOfRequiredParameters ();

$r = new \ReflectionMethod ( 'ExampleWorld\helloWorld', 'requiredOneArgument' );
echo $r->getNumberOfRequiredParameters ();

// Output: 2 1


Obtiene los parámetros

  • « ReflectionFunctionAbstract::getNumberOfRequiredParameters
  • ReflectionFunctionAbstract::getReturnType »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene los parámetros

ReflectionFunctionAbstract::getParameters

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getParameters — Obtiene los parámetros

Descripción

public ReflectionFunctionAbstract::getParameters ( ) : array

Devuelve los parámetros en forma de array de ReflectionParameter.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Parámetros, en forma de objetos ReflectionParameter.

Ver también

  • ReflectionFunctionAbstract::getNumberOfParameters() - Obtiene el número total de parámetros
  • func_get_args() - Devuelve un array que se compone de una lista de argumentos de función

User Contributed Notes

a dot lucassilvadeoliveira at gmail dot com 28-Nov-2020 06:08
We can use this functionality to automatically pass arguments to our function based on some data structure.

NOTE: I am using a php 8.0> feature called "Nameds parameter".

<?php

$valuesToProcess = [
  'name' => 'Anderson Lucas Silva de Oliveira',
  'age' => 21,
  'hobbie' => 'Play games'
];

function processUserData($name, $age, $job = "", $hobbie = "")
{
    $msg = "Hello $name. You have $age years old";
    if (!empty($job)) {
    $msg .= ". Your job is $job";
    }

    if (!empty($hobbie)) {
        $msg .= ". Your hobbie is $hobbie";
    }

    echo $msg . ".";
}

$refFunction = new ReflectionFunction('processUserData');
$parameters = $refFunction->getParameters();

$validParameters = [];
foreach ($parameters as $parameter) {
    if (!array_key_exists($parameter->getName(), $valuesToProcess) && !$parameter->isOptional()) {
        throw new DomainException('Cannot resolve the parameter' . $parameter->getName());
    }

    if(!array_key_exists($parameter->getName(), $valuesToProcess)) {
        continue;
    }

    $validParameters[$parameter->getName()] = $valuesToProcess[$parameter->getName()];
}

$refFunction->invoke(...$validParameters);
?>

Results in:

Hello Anderson Lucas Silva de Oliveira. You have 21 years old. Your hobbie is Play games.
dabidi at slupca dot pl 27-Oct-2015 01:33
This is part of my private framework that uses reflection.
This function get arguments list from theme method and puts corresponding vars from $_REQUEST ($_GET, $_POST, and $_COOKIE)

<?php
public static function fire_theme_method($class, $method)
{
        $fire_args=array();

        $reflection = new ReflectionMethod($class, $method);

    foreach($reflection->getParameters() AS $arg)
    {
        if($_REQUEST[$arg->name])
        $fire_args[$arg->name]=$_REQUEST[$arg->name];
        else
        $fire_args[$arg->name]=null;
    }

    return call_user_func_array(array($class, $method), $fire_args);
}
?>
For example, if my theme method needs only id, and we get this url:
http://example.com/my_class/my_method/?id=12&some_unwanted_var=123
will be ignored some_unwanted_var

Of course behind this i have .htaccess, autoloader and controller


Gets the specified return type of a function

  • « ReflectionFunctionAbstract::getParameters
  • ReflectionFunctionAbstract::getShortName »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets the specified return type of a function

ReflectionFunctionAbstract::getReturnType

(PHP 7)

ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function

Descripción

public ReflectionFunctionAbstract::getReturnType ( ) : ReflectionType|null

Gets the specified return type of a reflected function.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns a ReflectionType object if a return type is specified, null otherwise.

Ejemplos

Ejemplo #1 ReflectionFunctionAbstract::getReturnType() example

<?php

function to_int($param) : int {
    return (int) $param;
}

$reflection1 = new ReflectionFunction('to_int');
echo $reflection1->getReturnType();

El resultado del ejemplo sería:

int

Ejemplo #2 Usage on built-in functions

<?php

$reflection2 = new ReflectionFunction('array_merge');

var_dump($reflection2->getReturnType());

El resultado del ejemplo sería:

null

This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions.

Ver también

  • ReflectionFunctionAbstract::hasReturnType() - Checks if the function has a specified return type
  • ReflectionType::__toString() - To string

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el nombre abreviado de la función

  • « ReflectionFunctionAbstract::getReturnType
  • ReflectionFunctionAbstract::getStartLine »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene el nombre abreviado de la función

ReflectionFunctionAbstract::getShortName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getShortName — Obtiene el nombre abreviado de la función

Descripción

public ReflectionFunctionAbstract::getShortName ( ) : string

Devuelve el nombre abreviado de la función (sin la parte del espacio de nombres).

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Nombre abreviado de la función.

Ver también

  • ReflectionFunctionAbstract::getNamespaceName() - Obtiene el nombre del espacio de nombres
  • espcios de nombres

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el número de la línea de inicio

  • « ReflectionFunctionAbstract::getShortName
  • ReflectionFunctionAbstract::getStaticVariables »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene el número de la línea de inicio

ReflectionFunctionAbstract::getStartLine

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getStartLine — Obtiene el número de la línea de inicio

Descripción

public ReflectionFunctionAbstract::getStartLine ( ) : int

Devuelve el número de la línea de inicio de esta función.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Número de la línea de inicio.

Ver también

  • ReflectionFunctionAbstract::getEndLine() - Obtiene número de linea final

User Contributed Notes

There are no user contributed notes for this page.


Obtiene las variable estáticas

  • « ReflectionFunctionAbstract::getStartLine
  • ReflectionFunctionAbstract::hasReturnType »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Obtiene las variable estáticas

ReflectionFunctionAbstract::getStaticVariables

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getStaticVariables — Obtiene las variable estáticas

Descripción

public ReflectionFunctionAbstract::getStaticVariables ( ) : array

Devuelve las variables estáticas.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

array de variables estáticas.

Ver también

  • ReflectionFunctionAbstract::getParameters() - Obtiene los parámetros

User Contributed Notes

Martiros Aghajanyan 11-Oct-2014 01:27
<?php

function test()
{
    static $a = 0, $b = 15;
    $a++;
    $b++;
    return $a;
}

$rf = new ReflectionFunction('test');

// result - Array ( [a] => 0 [b] => 15 )
print_r( $rf->getStaticVariables() );

//call test function and print again static variables
test();

// result - Array ( [a] => 1 [b] => 16 )
print_r( $rf->getStaticVariables() );

?>


Checks if the function has a specified return type

  • « ReflectionFunctionAbstract::getStaticVariables
  • ReflectionFunctionAbstract::inNamespace »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if the function has a specified return type

ReflectionFunctionAbstract::hasReturnType

(PHP 7)

ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type

Descripción

public ReflectionFunctionAbstract::hasReturnType ( ) : bool

Checks whether the reflected function has a return type specified.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns true if the function is a specified return type, otherwise false.

Ejemplos

Ejemplo #1 ReflectionFunctionAbstract::hasReturnType() example

<?php

function to_int($param) : int {
    return (int) $param;
}

$reflection1 = new ReflectionFunction('to_int');
var_dump($reflection1->hasReturnType());

El resultado del ejemplo sería:

bool(true)

Ejemplo #2 Usage on built-in functions

<?php

$reflection2 = new ReflectionFunction('array_merge');

var_dump($reflection2->hasReturnType());

El resultado del ejemplo sería:

bool(false)

This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions.

Ver también

  • ReflectionFunctionAbstract::getReturnType() - Gets the specified return type of a function

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si pertenece a un espacio de nombres

  • « ReflectionFunctionAbstract::hasReturnType
  • ReflectionFunctionAbstract::isClosure »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Comprueba si pertenece a un espacio de nombres

ReflectionFunctionAbstract::inNamespace

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::inNamespace — Comprueba si pertenece a un espacio de nombres

Descripción

public ReflectionFunctionAbstract::inNamespace ( ) : bool

Comprueba si la función está definida o no en un espacio de nombres.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si está en un espacio de nombres, o si no false

Ver también

  • ReflectionFunctionAbstract::getNamespaceName() - Obtiene el nombre del espacio de nombres
  • espacios de nombres

User Contributed Notes

There are no user contributed notes for this page.


Comprobar si es un cierre

  • « ReflectionFunctionAbstract::inNamespace
  • ReflectionFunctionAbstract::isDeprecated »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Comprobar si es un cierre

ReflectionFunctionAbstract::isClosure

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::isClosure — Comprobar si es un cierre

Descripción

public ReflectionFunctionAbstract::isClosure ( ) : bool

Comprueba si la función reflejada es un objeto Closure.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true si la función es una Closure, false si no.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionFunctionAbstract::isClosure()

<?php
// No cierre
$función1 = 'str_replace';
$$reflejo1 = new ReflectionFunction($función1);
var_dump($reflejo1->isClosure());

// Cierre
$función2 = function () {};
$reflejo2 = new ReflectionFunction($función2);
var_dump($reflejo2->isClosure());
?>

El resultado del ejemplo sería:

bool(false)
bool(true)

Ver también

  • ReflectionFunctionAbstract::isGenerator() - Devuelve si la función es un generador

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si está obsoleta

  • « ReflectionFunctionAbstract::isClosure
  • ReflectionFunctionAbstract::isGenerator »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Comprueba si está obsoleta

ReflectionFunctionAbstract::isDeprecated

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::isDeprecated — Comprueba si está obsoleta

Descripción

public ReflectionFunctionAbstract::isDeprecated ( ) : bool

Comprueba si la función está o no obsoleta.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si está obsoleta, o si no false

Ejemplos

Ejemplo #1 Ejemplo de ReflectionFunctionAbstract::isDeprecated()

<?php
$rf = new ReflectionFunction('ereg');
var_dump($rf->isDeprecated());
?>

El resultado del ejemplo sería:

bool(true)

Ver también

  • ReflectionFunctionAbstract::getDocComment() - Obtiene comentarios de documentación

User Contributed Notes

There are no user contributed notes for this page.


Devuelve si la función es un generador

  • « ReflectionFunctionAbstract::isDeprecated
  • ReflectionFunctionAbstract::isInternal »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Devuelve si la función es un generador

ReflectionFunctionAbstract::isGenerator

(PHP 5 >= 5.5.0, PHP 7)

ReflectionFunctionAbstract::isGenerator — Devuelve si la función es un generador

Descripción

public ReflectionFunctionAbstract::isGenerator ( ) : bool

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true si la función es un generador, false si no lo es, o null en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si la función es interna

  • « ReflectionFunctionAbstract::isGenerator
  • ReflectionFunctionAbstract::isUserDefined »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Comprueba si la función es interna

ReflectionFunctionAbstract::isInternal

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::isInternal — Comprueba si la función es interna

Descripción

public ReflectionFunctionAbstract::isInternal ( ) : bool

Comprueba si la función es interna, en contraposición a las funciones definidas por el usuario.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si es interna, o si no false

Ver también

  • ReflectionFunctionAbstract::isUserDefined() - Comprueba si es una función definida por un usuario

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si es una función definida por un usuario

  • « ReflectionFunctionAbstract::isInternal
  • ReflectionFunctionAbstract::isVariadic »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Comprueba si es una función definida por un usuario

ReflectionFunctionAbstract::isUserDefined

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::isUserDefined — Comprueba si es una función definida por un usuario

Descripción

public ReflectionFunctionAbstract::isUserDefined ( ) : bool

Comprueba si una función está definida por un usuario, en contraposición a las funciones internas.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si está definida por el usuario, y en cualquier otro caso false.

Ver también

  • ReflectionFunctionAbstract::isInternal() - Comprueba si la función es interna

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si la función es varíadica

  • « ReflectionFunctionAbstract::isUserDefined
  • ReflectionFunctionAbstract::returnsReference »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Comprueba si la función es varíadica

ReflectionFunctionAbstract::isVariadic

(PHP 5 >= 5.6.0, PHP 7)

ReflectionFunctionAbstract::isVariadic — Comprueba si la función es varíadica

Descripción

public ReflectionFunctionAbstract::isVariadic ( ) : bool

Comprueba si la función es varíadica.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true si la función es varíadica, false en caso contrario.

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si devuelve una referencia

  • « ReflectionFunctionAbstract::isVariadic
  • ReflectionFunctionAbstract::__toString »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Comprueba si devuelve una referencia

ReflectionFunctionAbstract::returnsReference

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::returnsReference — Comprueba si devuelve una referencia

Descripción

public ReflectionFunctionAbstract::returnsReference ( ) : bool

Comprueba si la función devuelve o no una referencia.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si la función devuelve una referencia, o si no false

Ver también

  • ReflectionFunctionAbstract::isClosure() - Comprobar si es un cierre

User Contributed Notes

There are no user contributed notes for this page.


Convertir a texto

  • « ReflectionFunctionAbstract::returnsReference
  • ReflectionMethod »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Convertir a texto

ReflectionFunctionAbstract::__toString

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::__toString — Convertir a texto

Descripción

abstract public ReflectionFunctionAbstract::__toString ( ) : void

Convierte a texto.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Texto.

Ver también

  • ReflectionClass::clone()
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


La clase ReflectionMethod

(PHP 5, PHP 7)

Introducción

La clase ReflectionMethod muestra información sobre un método.

Sinopsis de la Clase

ReflectionMethod extends ReflectionFunctionAbstract implements Reflector {
/* Constantes */
const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
const integer IS_ABSTRACT = 2 ;
const integer IS_FINAL = 4 ;
/* Propiedades */
public $name ;
public $class ;
/* Métodos */
public __construct ( mixed $class , string $name )
public static export ( string $class , string $name , bool $return = false ) : string
public getClosure ( object $object ) : Closure
public getDeclaringClass ( ) : ReflectionClass
public getModifiers ( ) : int
public getPrototype ( ) : ReflectionMethod
public invoke ( object $object , mixed $... = ? ) : mixed
public invokeArgs ( object $object , array $args ) : mixed
public isAbstract ( ) : bool
public isConstructor ( ) : bool
public isDestructor ( ) : bool
public isFinal ( ) : bool
public isPrivate ( ) : bool
public isProtected ( ) : bool
public isPublic ( ) : bool
public isStatic ( ) : bool
public setAccessible ( bool $accessible ) : void
public __toString ( ) : string
/* Métodos heredados */
final private ReflectionFunctionAbstract::__clone ( ) : void
public ReflectionFunctionAbstract::getClosureScopeClass ( ) : ReflectionClass
public ReflectionFunctionAbstract::getClosureThis ( ) : object
public ReflectionFunctionAbstract::getDocComment ( ) : string
public ReflectionFunctionAbstract::getEndLine ( ) : int
public ReflectionFunctionAbstract::getExtension ( ) : ReflectionExtension
public ReflectionFunctionAbstract::getExtensionName ( ) : string
public ReflectionFunctionAbstract::getFileName ( ) : string
public ReflectionFunctionAbstract::getName ( ) : string
public ReflectionFunctionAbstract::getNamespaceName ( ) : string
public ReflectionFunctionAbstract::getNumberOfParameters ( ) : int
public ReflectionFunctionAbstract::getNumberOfRequiredParameters ( ) : int
public ReflectionFunctionAbstract::getParameters ( ) : array
public ReflectionFunctionAbstract::getReturnType ( ) : ReflectionType|null
public ReflectionFunctionAbstract::getShortName ( ) : string
public ReflectionFunctionAbstract::getStartLine ( ) : int
public ReflectionFunctionAbstract::getStaticVariables ( ) : array
public ReflectionFunctionAbstract::hasReturnType ( ) : bool
public ReflectionFunctionAbstract::inNamespace ( ) : bool
public ReflectionFunctionAbstract::isClosure ( ) : bool
public ReflectionFunctionAbstract::isDeprecated ( ) : bool
public ReflectionFunctionAbstract::isGenerator ( ) : bool
public ReflectionFunctionAbstract::isInternal ( ) : bool
public ReflectionFunctionAbstract::isUserDefined ( ) : bool
public ReflectionFunctionAbstract::isVariadic ( ) : bool
public ReflectionFunctionAbstract::returnsReference ( ) : bool
abstract public ReflectionFunctionAbstract::__toString ( ) : void
}

Propiedades

name

Nombre del método

class

Nombre de la clase

Constantes predefinidas

Modificadores ReflectionMethod

ReflectionMethod::IS_STATIC

Indica que el método es estático.

ReflectionMethod::IS_PUBLIC

Indica que el método es público.

ReflectionMethod::IS_PROTECTED

Indica que el método está protegido.

ReflectionMethod::IS_PRIVATE

Indica que el método es privado.

ReflectionMethod::IS_ABSTRACT

Indicates that the method is abstract.

ReflectionMethod::IS_FINAL

Indica que este método es final.

Tabla de contenidos

  • ReflectionMethod::__construct — Construye un objeto ReflectionMethod
  • ReflectionMethod::export — Exporta un objeto de tipo ReflectionMethod
  • ReflectionMethod::getClosure — Devuelve un cierre creado dinámicamente para este método
  • ReflectionMethod::getDeclaringClass — Obtiene la clase en la que se ha declarado el método
  • ReflectionMethod::getModifiers — Obtiene los modificadores del método
  • ReflectionMethod::getPrototype — Obtiene el prototipo del método (si lo hubiera)
  • ReflectionMethod::invoke — Invoca un método
  • ReflectionMethod::invokeArgs — Invoca un método con argumentos
  • ReflectionMethod::isAbstract — Comprueba si el método es abstracto
  • ReflectionMethod::isConstructor — Comprueba si el método es un constructor
  • ReflectionMethod::isDestructor — Comprueba si el método es un destructor
  • ReflectionMethod::isFinal — Comprueba si el método es final
  • ReflectionMethod::isPrivate — Comprueba si el método es privado
  • ReflectionMethod::isProtected — Comprueba si el método está protegido
  • ReflectionMethod::isPublic — Comprueba si el método es público
  • ReflectionMethod::isStatic — Comprueba si el método es estático
  • ReflectionMethod::setAccessible — Asigna la accesibilidad del método
  • ReflectionMethod::__toString — Devuelve la representación en forma de texto de este objeto

User Contributed Notes

Anonymous 02-Nov-2020 10:15
We can make a "Automatic dependenci injector" in classes when her constructors depends other classes (with type hint).

<?php

class Dependence1 {
    function foo() {
        echo "foo";
    }
}

class Dependence2 {
    function foo2() {
        echo "foo2";
    }
}

final class myClass
{
    private $dep1;
    private $dep2;

    public function __construct(
        Dependence1 $dependence1,
        Dependence2 $dependence2
    )
    {
        $this->dep1 = $dependence1;
        $this->dep2 = $dependence2;
    }

}

// Automatic dependence injection (CLASSES)

$constructor = new ReflectionMethod(myClass::class, '__construct');
$parameters = $constructor->getParameters();

$dependences = [];
foreach ($parameters as $parameter) {
    $dependenceClass = (string) $parameter->getType();
    $dependences[] = new $dependenceClass();
}

$instance = new myClass(...$dependences);
var_dump($instance);

?>

Results in:

object(myClass)#6 (2) {
  ["dep1":"myClass":private]=>
  object(Dependence1)#4 (0) {
  }
  ["dep2":"myClass":private]=>
  object(Dependence2)#5 (0) {
  }
}
webseiten dot designer at googlemail dot com 02-Apr-2011 11:53
Note that the public member $class contains the name of the class in which the method has been defined:

<?php
class A {public function __construct() {}}
class B extends A {}

$method = new ReflectionMethod('B', '__construct');
echo $method->class; // prints 'A'
?>
no dot prob at gmx dot net 02-Jun-2006 01:09
I have written a function which returns the value of a given DocComment tag.

Full example:

<?php

header('Content-Type: text/plain');

class Example
{
    /**
     * This is my DocComment!
     *
     * @DocTag: prints Hello World!
     */
    public function myMethod()
    {
        echo 'Hello World!';
    }
}

function getDocComment($str, $tag = '')
{
    if (empty($tag))
    {
        return $str;
    }

    $matches = array();
    preg_match("/".$tag.":(.*)(\\r\\n|\\r|\\n)/U", $str, $matches);

    if (isset($matches[1]))
    {
        return trim($matches[1]);
    }

    return '';
}

$method = new ReflectionMethod('Example', 'myMethod');

// will return Hello World!
echo getDocComment($method->getDocComment(), '@DocTag');

?>

Maybe you can add this functionality to the getDocComment methods of the reflection classes.


Construye un objeto ReflectionMethod

  • « ReflectionMethod
  • ReflectionMethod::export »
  • PHP Manual
  • ReflectionMethod
  • Construye un objeto ReflectionMethod

ReflectionMethod::__construct

(PHP 5, PHP 7)

ReflectionMethod::__construct — Construye un objeto ReflectionMethod

Descripción

public ReflectionMethod::__construct ( mixed $class , string $name )
public ReflectionMethod::__construct ( string $class_method )

Construye un nuevo objeto de tipo ReflectionMethod.

Parámetros

class

Nombre de clase u objeto (instancia de la clase) a la que pertenece el método.

name

Nombre del método.

class_method

Nombre de la clase y nombre del método delimitados por ::.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

Lnaza ReflectionException si no existiera el método.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionMethod::__construct()

<?php
class Contador
{
    private static $c = 0;

    /**
     * Incrementar contador
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */
    final public static function incrementar()
    {
        return ++self::$c;
    }
}

// Crea una instancia de la clase ReflectionMethod
$metodo = new ReflectionMethod('Contador', 'incrementar');

// Muestra información básica
printf(
    "===> El método %s%s%s%s%s%s%s '%s' (que es %s)\n" .
    "     declarado en %s\n" .
    "     líneas %d a %d\n" .
    "     con los modificadores %d[%s]\n",
        $metodo->isInternal() ? 'interno' : 'definido por el usuario',
        $metodo->isAbstract() ? ' abstract' : '',
        $metodo->isFinal() ? ' final' : '',
        $metodo->isPublic() ? ' public' : '',
        $metodo->isPrivate() ? ' private' : '',
        $metodo->isProtected() ? ' protected' : '',
        $metodo->isStatic() ? ' static' : '',
        $metodo->getName(),
        $metodo->isConstructor() ? 'un constructor' : 'un método regular',
        $metodo->getFileName(),
        $metodo->getStartLine(),
        $metodo->getEndline(),
        $metodo->getModifiers(),
        implode(' ', Reflection::getModifierNames($metodo->getModifiers()))
);

// Mostrar comentarios de documentación
printf("---> Documentación:\n %s\n", var_export($metodo->getDocComment(), 1));

// Si existieran, mostrar variables estáticas
if ($statics= $metodo->getStaticVariables()) {
    printf("---> Variables estáticas: %s\n", var_export($statics, 1));
}

// Invocación del método
printf("---> Resultado de la invocación: ");
var_dump($metodo->invoke(NULL));
?>

El resultado del ejemplo sería algo similar a:

===> El método definido por el usuario final public static 'incrementar' (que es un método regular)
     declared in /Users/philip/cvs/phpdoc/test.php
     líneas 14 a 17
     con los modificadores 261[final public static]
---> Documentación:
 '/**
     * Incrementar contador
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */'
---> Resultado de la invocación: int(1)

Ver también

  • ReflectionMethod::export() - Exporta un objeto de tipo ReflectionMethod
  • Constructores

User Contributed Notes

There are no user contributed notes for this page.


Exporta un objeto de tipo ReflectionMethod

  • « ReflectionMethod::__construct
  • ReflectionMethod::getClosure »
  • PHP Manual
  • ReflectionMethod
  • Exporta un objeto de tipo ReflectionMethod

ReflectionMethod::export

(PHP 5, PHP 7)

ReflectionMethod::export — Exporta un objeto de tipo ReflectionMethod

Descripción

public static ReflectionMethod::export ( string $class , string $name , bool $return = false ) : string

Exportar un ReflectionMethod.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

class

Nombre de la clase.

name

Nombre del método.

return

Configurarlo a true devolverá la exportación, a diferencia de emitirla. Configurarlo a false (el valor por defecto) hará lo contrario.

Valores devueltos

Si el parámetro return es seteado a true, la exportación se devolverá como un string, de lo contrario se retornará null.

Ver también

  • ReflectionMethod::__construct() - Construye un objeto ReflectionMethod
  • ReflectionMethod::__toString() - Devuelve la representación en forma de texto de este objeto

User Contributed Notes

There are no user contributed notes for this page.


Devuelve un cierre creado dinámicamente para este método

  • « ReflectionMethod::export
  • ReflectionMethod::getDeclaringClass »
  • PHP Manual
  • ReflectionMethod
  • Devuelve un cierre creado dinámicamente para este método

ReflectionMethod::getClosure

(PHP 5 >= 5.4.0, PHP 7)

ReflectionMethod::getClosure — Devuelve un cierre creado dinámicamente para este método

Descripción

public ReflectionMethod::getClosure ( object $object ) : Closure

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

object

No permitido en métodos estáticos. Obligatorio para el resto de métodos.

Valores devueltos

Devuelve un objeto Closure. En caso de error, devuelve null.

User Contributed Notes

okto 14-Aug-2016 10:45
Use method from another class context.

<?php

class A {
    private $var = 'class A';

    public function getVar() {
        return $this->var;
    }

    public function getCl() {
        return function () {
            $this->getVar();
        };
    }
}

class B {
    private $var = 'class B';
}

$a = new A();
$b = new B();

print $a->getVar() . PHP_EOL;

$reflection = new ReflectionClass(get_class($a));
$closure    = $reflection->getMethod('getVar')->getClosure($a);
$get_var_b  = $closure->bindTo($b, $b);

print $get_var_b() . PHP_EOL;

// Output:
// class A
// class B
Denis Doronin 18-Jan-2013 08:05
You can call private methods with getClosure():

<?php

function call_private_method($object, $method, $args = array()) {
    $reflection = new ReflectionClass(get_class($object));
    $closure = $reflection->getMethod($method)->getClosure($object);
    return call_user_func_array($closure, $args);
}

class Example {

    private $x = 1, $y = 10;

    private function sum() {
        print $this->x + $this->y;
    }

}

call_private_method(new Example(), 'sum');

?>

Output is 11.


Obtiene la clase en la que se ha declarado el método

  • « ReflectionMethod::getClosure
  • ReflectionMethod::getModifiers »
  • PHP Manual
  • ReflectionMethod
  • Obtiene la clase en la que se ha declarado el método

ReflectionMethod::getDeclaringClass

(PHP 5, PHP 7)

ReflectionMethod::getDeclaringClass — Obtiene la clase en la que se ha declarado el método

Descripción

public ReflectionMethod::getDeclaringClass ( ) : ReflectionClass

Devuelve la clase en la que se ha declarado el método.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Objeto ReflectionClass de la clase a la que pertenece el método reflexionado.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionMethod::getDeclaringClass()

<?php
class HelloWorld {

    protected function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
var_dump($reflectionMethod->getDeclaringClass());
?>

El resultado del ejemplo sería:

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

Ver también

  • ReflectionMethod::isAbstract() - Comprueba si el método es abstracto

User Contributed Notes

There are no user contributed notes for this page.


Obtiene los modificadores del método

  • « ReflectionMethod::getDeclaringClass
  • ReflectionMethod::getPrototype »
  • PHP Manual
  • ReflectionMethod
  • Obtiene los modificadores del método

ReflectionMethod::getModifiers

(PHP 5, PHP 7)

ReflectionMethod::getModifiers — Obtiene los modificadores del método

Descripción

public ReflectionMethod::getModifiers ( ) : int

Devuelve un campo de bits de los modificadores de acceso para este método.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Representación numérica de los modificadores enumerados a continuación. El significado de estos modificadores se describe en las constantes predefinidas.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionMethod::getModifiers()

<?php
class Prueba
{
    final public static function foo()
    {
        return;
    }
    public function bar()
    {
        return;
    }
}

$foo = new ReflectionMethod('Prueba', 'foo');

echo "Modificadores del método foo():\n";
echo $foo->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($foo->getModifiers())) . "\n";

$bar = new ReflectionMethod('Prueba', 'bar');

echo "Modificadores del método bar():\n";
echo $bar->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($bar->getModifiers()));
?>

El resultado del ejemplo sería algo similar a:

Modificadores del método foo():
261
final public static
Modificadores del método bar():
65792
public

Ver también

  • Reflection::getModifierNames() - Obtener nombres de modificadores

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el prototipo del método (si lo hubiera)

  • « ReflectionMethod::getModifiers
  • ReflectionMethod::invoke »
  • PHP Manual
  • ReflectionMethod
  • Obtiene el prototipo del método (si lo hubiera)

ReflectionMethod::getPrototype

(PHP 5 >= 5.1.2, PHP 7)

ReflectionMethod::getPrototype — Obtiene el prototipo del método (si lo hubiera)

Descripción

public ReflectionMethod::getPrototype ( ) : ReflectionMethod

Devuelve el prototipo del método.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve una instancia de tipo ReflectionMethod del prototipo del método.

Errores/Excepciones

Lanza ReflectionException si el método no tuviera un prototipo.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionMethod::getPrototype()

<?php
class Hola {

    public function saludarA($nombre) {
        return 'Hola ' . $nombre;
    }

}
class HolaMundo extends Hola {

    public function saludarA($nombre) {
        return 'Hola Mundo: ' . $nombre;
    }

}

$metodoReflexionado = new ReflectionMethod('HolaMundo', 'saludarA');
var_dump($metodoReflexionado->getPrototype());
?>

El resultado del ejemplo sería:

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(10) "saludarA"
  ["class"]=>
  string(5) "Hola"
}

Ver también

  • ReflectionMethod::getModifiers() - Obtiene los modificadores del método

User Contributed Notes

There are no user contributed notes for this page.


Invoca un método

  • « ReflectionMethod::getPrototype
  • ReflectionMethod::invokeArgs »
  • PHP Manual
  • ReflectionMethod
  • Invoca un método

ReflectionMethod::invoke

(PHP 5, PHP 7)

ReflectionMethod::invoke — Invoca un método

Descripción

public ReflectionMethod::invoke ( object $object , mixed $... = ? ) : mixed

Invoca al método reflejado.

Parámetros

object

Objeto al que pertenece el método invocado. En métodos estáticos, se podrá introducir null en este parámetro.

...

Cero o más parámetros para pasar a este método. Acepta un número variable de parámetros, que se pasarán al método.

Valores devueltos

Devuelve el resultado del método.

Errores/Excepciones

Lanza ReflectionException si el parámetro object no contiene una instancia de la clase en la que se declaró este método.

Lanza ReflectionException si fallara la invocación al método.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionMethod::invoke()

<?php
class HolaMundo {

    public function saludarA($nombre) {
        return 'Hola ' . $nombre;
    }

}

$metodoReflexionado = new ReflectionMethod('HolaMundo', 'saludarA');
echo $metodoReflexionado->invoke(new HolaMundo(), 'Miguel');
?>

El resultado del ejemplo sería:

Hola Miguel

Notas

Nota:

Si la función tiene argumentos que necesitan ser referencias, éstos deben ser referencias en la lista de argumentos pasados.

Ver también

  • ReflectionMethod::invokeArgs() - Invoca un método con argumentos
  • __invoke()
  • call_user_func() - Llamar a una llamada de retorno dada por el primer parámetro

User Contributed Notes

dimitriy at remerov dot ru 06-Jun-2012 01:19
This method can be used to call a overwritten public method of a parent class on an child instance
The following code will output "A":

<?php

class A
{
    public function foo()
    {
        return __CLASS__;
    }
}

class B extends A
{
    public function foo()
    {
        return __CLASS__;
    }
}

$b = new B();

$reflection = new ReflectionObject($b);

$parentReflection = $reflection->getParentClass();

$parentFooReflection = $parentReflection->getMethod('foo');

$data = $parentFooReflection->invoke($b);

echo $data;

?>
templargrey at wp dot pl 21-Jul-2011 01:12
Seems that Reflection doesn`t resolve late static bindings - var_dump will show "string 'a' (length=1)".

<?php
class ParentClass { protected static $a = 'a'; static public function init() { return static::$a; } }
class ChildClass extends ParentClass { protected static $a = 'b'; }

$r = new ReflectionClass('ChildClass');
var_dump($r->getMethod('init')->invoke(null));
?>
rojaro at gmail dot com 10-Feb-2011 01:56
Note: If you want to invoke protected or private methods, you'll first have to make them accessible using the setAccessible() method (see http://php.net/reflectionmethod.setaccessible ).


Invoca un método con argumentos

  • « ReflectionMethod::invoke
  • ReflectionMethod::isAbstract »
  • PHP Manual
  • ReflectionMethod
  • Invoca un método con argumentos

ReflectionMethod::invokeArgs

(PHP 5 >= 5.1.2, PHP 7)

ReflectionMethod::invokeArgs — Invoca un método con argumentos

Descripción

public ReflectionMethod::invokeArgs ( object $object , array $args ) : mixed

Invoca el método reflejado y pasa sus argumentos como array.

Parámetros

object

Objeto en el que se invoca al método. En caso de métodos estáticos, se podrá introducir null en este parámetro.

args

Argumentos que se pasan a la función, en un array.

Valores devueltos

Devuelve el resultado del método.

Errores/Excepciones

Lanza ReflectionException si el parámetro object no contiene una instancia de la clase en la que está declarado este método.

Lanza ReflectionException si falla la invocación al método.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionMethod::invokeArgs()

<?php
class HolaMundo {

    public function saludarA($nombre) {
        return 'Hola ' . $nombre;
    }

}

$metodoReflexionado = new ReflectionMethod('HolaMundo', 'saludarA');
echo $metodoReflexionado->invokeArgs(new HolaMundo(), array('Miguel'));
?>

El resultado del ejemplo sería:

Hola Miguel

Notas

Nota:

Si la función tiene argumentos que necesitan ser referencias, éstos deben ser referencias en la lista de argumentos pasados.

Ver también

  • ReflectionMethod::invoke() - Invoca un método
  • __invoke()
  • call_user_func_array() - Llamar a una llamada de retorno con un array de parámetros

User Contributed Notes

CodeCoutureXX at gmail dot com 03-Sep-2015 09:12
If you need to call ReflectionMethod::invokeArgs() on a static function you can pass NULL in for the $object parameter.

Example:

<?php
     class myClass {
          public static myStaticFunc($a, $b) {
               return $a + $b;
          }
     }

     $ref = new ReflectionMethod('myClass', 'myStaticFunc');
     echo $ref->invokeArgs(NULL, [12, 7]);
?>

produces the following output:

19
cweiske at cweiske dot de 25-Mar-2011 07:34
Passing arguments by reference works:
<?php $rm->invokeArgs($object, array(&$foo, $bar)); ?>
agent_harris at secure-mail dot biz 13-Feb-2011 07:12
There is a simple workaround for the reference passing problem:
Since the reflection api has to handle all parameters in a generic way it has no chance to guess if you wish to pass data per value or reference.

But it seems that you can also decide to pass a reference from where you call the function or method (not just only by the ampersand prefix in its declaration).

So just do the following; which worked for me:

<?php
//...
$method->invoke($object, $inputValue, &$outputValue);
?>

Since this will only be necessary with arrays and primitive data types it should be acceptable in most cases to know in advance if you need to pass per reference. But it is probably although necessary to keep the ampersand always in the declaration (because of the at least two layers between the actual function and your invoke call).

If this is the expected behavior it will maybe make sense to mention it in the documentation for invoke and invokeArgs.
serg dot smertin at gmail dot com 21-Sep-2010 06:51
We can do black magic, which is useful in templating block calls:

<?php
     $object->__named('methodNameHere', array('arg3' => 'three', 'arg1' => 'one'));

     ...

      /**
       * Pass method arguments by name
       *
       * @param string $method
       * @param array $args
       * @return mixed
       */
      public function __named($method, array $args = array())
      {
        $reflection = new ReflectionMethod($this, $method);

        $pass = array();
        foreach($reflection->getParameters() as $param)
        {
          /* @var $param ReflectionParameter */
          if(isset($args[$param->getName()]))
          {
            $pass[] = $args[$param->getName()];
          }
          else
          {
            $pass[] = $param->getDefaultValue();
          }
        }

        return $reflection->invokeArgs($this, $pass);
      }
?>


Comprueba si el método es abstracto

  • « ReflectionMethod::invokeArgs
  • ReflectionMethod::isConstructor »
  • PHP Manual
  • ReflectionMethod
  • Comprueba si el método es abstracto

ReflectionMethod::isAbstract

(PHP 5, PHP 7)

ReflectionMethod::isAbstract — Comprueba si el método es abstracto

Descripción

public ReflectionMethod::isAbstract ( ) : bool

Comprueba si el método es abstracto.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el método es abstracto, o si no false

Ver también

  • ReflectionMethod::getDeclaringClass() - Obtiene la clase en la que se ha declarado el método

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el método es un constructor

  • « ReflectionMethod::isAbstract
  • ReflectionMethod::isDestructor »
  • PHP Manual
  • ReflectionMethod
  • Comprueba si el método es un constructor

ReflectionMethod::isConstructor

(PHP 5, PHP 7)

ReflectionMethod::isConstructor — Comprueba si el método es un constructor

Descripción

public ReflectionMethod::isConstructor ( ) : bool

Comprueba si el método es un constructor.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el método es un constructor, o si no false

Ver también

  • ReflectionMethod::__construct() - Construye un objeto ReflectionMethod
  • ReflectionMethod::isAbstract() - Comprueba si el método es abstracto
  • ReflectionMethod::isDestructor() - Comprueba si el método es un destructor

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el método es un destructor

  • « ReflectionMethod::isConstructor
  • ReflectionMethod::isFinal »
  • PHP Manual
  • ReflectionMethod
  • Comprueba si el método es un destructor

ReflectionMethod::isDestructor

(PHP 5, PHP 7)

ReflectionMethod::isDestructor — Comprueba si el método es un destructor

Descripción

public ReflectionMethod::isDestructor ( ) : bool

Comprueba si el método es un destructor.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el método es un destructor, o si no false

Ver también

  • ReflectionMethod::isConstructor() - Comprueba si el método es un constructor

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el método es final

  • « ReflectionMethod::isDestructor
  • ReflectionMethod::isPrivate »
  • PHP Manual
  • ReflectionMethod
  • Comprueba si el método es final

ReflectionMethod::isFinal

(PHP 5, PHP 7)

ReflectionMethod::isFinal — Comprueba si el método es final

Descripción

public ReflectionMethod::isFinal ( ) : bool

Comprueba si el método es final.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el método es final, o si no false

Ver también

  • ReflectionMethod::isStatic() - Comprueba si el método es estático

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el método es privado

  • « ReflectionMethod::isFinal
  • ReflectionMethod::isProtected »
  • PHP Manual
  • ReflectionMethod
  • Comprueba si el método es privado

ReflectionMethod::isPrivate

(PHP 5, PHP 7)

ReflectionMethod::isPrivate — Comprueba si el método es privado

Descripción

public ReflectionMethod::isPrivate ( ) : bool

Comprueba si el método es privado.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el método es privado, o si no false

Ver también

  • ReflectionMethod::isPublic() - Comprueba si el método es público

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el método está protegido

  • « ReflectionMethod::isPrivate
  • ReflectionMethod::isPublic »
  • PHP Manual
  • ReflectionMethod
  • Comprueba si el método está protegido

ReflectionMethod::isProtected

(PHP 5, PHP 7)

ReflectionMethod::isProtected — Comprueba si el método está protegido

Descripción

public ReflectionMethod::isProtected ( ) : bool

Comprueba si el método está protegido.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el método está protegido, o si no false

Ver también

  • ReflectionMethod::isPrivate() - Comprueba si el método es privado

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el método es público

  • « ReflectionMethod::isProtected
  • ReflectionMethod::isStatic »
  • PHP Manual
  • ReflectionMethod
  • Comprueba si el método es público

ReflectionMethod::isPublic

(PHP 5, PHP 7)

ReflectionMethod::isPublic — Comprueba si el método es público

Descripción

public ReflectionMethod::isPublic ( ) : bool

Comprueba si el método es público.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el método es público, o si no false

Ver también

  • ReflectionMethod::isPrivate() - Comprueba si el método es privado

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el método es estático

  • « ReflectionMethod::isPublic
  • ReflectionMethod::setAccessible »
  • PHP Manual
  • ReflectionMethod
  • Comprueba si el método es estático

ReflectionMethod::isStatic

(PHP 5, PHP 7)

ReflectionMethod::isStatic — Comprueba si el método es estático

Descripción

public ReflectionMethod::isStatic ( ) : bool

Comprueba si el método es estático.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el método es estático, o si no false

Ver también

  • ReflectionMethod::isFinal() - Comprueba si el método es final

User Contributed Notes

There are no user contributed notes for this page.


Asigna la accesibilidad del método

  • « ReflectionMethod::isStatic
  • ReflectionMethod::__toString »
  • PHP Manual
  • ReflectionMethod
  • Asigna la accesibilidad del método

ReflectionMethod::setAccessible

(PHP 5 >= 5.3.2, PHP 7)

ReflectionMethod::setAccessible — Asigna la accesibilidad del método

Descripción

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

Marca un método como accesible. Por ejemplo, podría hacer que los métodos protegidos o privados fueran invocados.

Parámetros

accessible

true para permitir que sea accesible, o false.

Valores devueltos

No devuelve ningún valor.

Ver también

  • ReflectionMethod::isPrivate() - Comprueba si el método es privado
  • ReflectionMethod::isProtected() - Comprueba si el método está protegido

User Contributed Notes

dave1010 at gmail dot com 11-May-2011 03:21
This is handy for accessing private methods but remember that things are normally private for a reason! Unit Testing is one (debatable) use case for this.

Example:
<?php
class Foo {
  private function myPrivateMethod() {
    return 7;
  }
}

$method = new ReflectionMethod('Foo', 'myPrivateMethod');
$method->setAccessible(true);

echo $method->invoke(new Foo);
// echos "7"
?>

This works nicely with PHPUnit: http://php.net/manual/en/reflectionmethod.setaccessible.php


Devuelve la representación en forma de texto de este objeto

  • « ReflectionMethod::setAccessible
  • ReflectionNamedType »
  • PHP Manual
  • ReflectionMethod
  • Devuelve la representación en forma de texto de este objeto

ReflectionMethod::__toString

(PHP 5, PHP 7)

ReflectionMethod::__toString — Devuelve la representación en forma de texto de este objeto

Descripción

public ReflectionMethod::__toString ( ) : string

Devuelve la representación en forma de texto de este objeto.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Representación en forma de texto de esta instancia de ReflectionMethod.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionMethod::__toString()

<?php
class HolaMundo {

    public function saludarA($nombre) {
        return 'Hola ' . $nombre;
    }

}

$metodoReflexionado = new ReflectionMethod('HolaMundo', 'saludarA');
echo $metodoReflexionado;
?>

El resultado del ejemplo sería:

Method [ <user> public method saludarA ] {
  @@ /Users/chuso/Downloads/dropme.php 4 - 6

  - Parameters [1] {
    Parameter #0 [ <required> $nombre ]
  }
}

Ver también

  • ReflectionMethod::export() - Exporta un objeto de tipo ReflectionMethod
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


The ReflectionNamedType class

(PHP 7 >= 7.1.0)

Introducción

Sinopsis de la Clase

ReflectionNamedType extends ReflectionType {
/* Métodos */
public getName ( ) : string
public isBuiltin ( ) : bool
/* Métodos heredados */
public ReflectionType::allowsNull ( ) : bool
public ReflectionType::__toString ( ) : string
}

Tabla de contenidos

  • ReflectionNamedType::getName — Get the text of the type hint
  • ReflectionNamedType::isBuiltin — Checks if it is a built-in type

User Contributed Notes

There are no user contributed notes for this page.


Get the text of the type hint

  • « ReflectionNamedType
  • ReflectionNamedType::isBuiltin »
  • PHP Manual
  • ReflectionNamedType
  • Get the text of the type hint

ReflectionNamedType::getName

(PHP 7 >= 7.1.0)

ReflectionNamedType::getName — Get the text of the type hint

Descripción

public ReflectionNamedType::getName ( ) : string

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the text of the type hint.

Ver también

  • ReflectionType::__toString() - To string

User Contributed Notes

e3jeremy at gmail dot com 04-Jul-2018 07:28
Method "getName" is available when you access getType from getParameters from class reports information of a method(ReflectionMethod).
No need to instantiate the ReflectionNamedType.

Below is my custom method on resolving method dependencies, getName is a big help.

<?php

class A
{
    public function my()
    {
        return ' My ';
    }
}

class B
{
    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function hello($string)
    {
        return 'Hello' . $this->a->my() . $string . '.';
    }
}

class C
{
    public function print($instance, $method)
    {
        $params = ['World'];

        echo call_user_func_array(array($instance, $method), array_merge($this->resolveMethodDependencies($instance, $method), $params));
    }

    public function instantiate($class)
    {
        if(method_exists($class, '__construct')) $instance = new $class(...$this->resolveMethodDependencies($class, '__construct'));
        else $instance = new $class;

        return $instance;
    }

    protected function resolveMethodDependencies($class, $method)
    {
        $params = [];
        $reflection = new \ReflectionMethod($class, $method);

        foreach ($reflection->getParameters() as $param) {

            if($type = $param->getType()) {

                if(!$type || !$this->instatiatable ($type)) continue;

                // This is the right way to get the class name in string.
                $className = $type->getName();

                // This will throw error.
                // $className = $param->getType();

                // Alos this one will do the trick.
                // $className = (string) $param->getType();

                if(method_exists($className, '__construct')) {
                    $params[] = new $className(...$this->resolveMethodDependencies($className, '__construct'));
                    continue;
                }

                $params[] = new $className;
            }
        }
        return $params;
    }

    protected function instatiatable ($type)
    {
        // Add conditon if something is leftout.
        // This is to ensure that the type is existing class.
        return $type != 'Closure' && !is_callable($type) && class_exists($type);
    }
}

$class = new C;

$class->print(
    $class->instantiate('B'), 'hello'
);

Output:
Hello My World.


Checks if it is a built-in type

  • « ReflectionNamedType::getName
  • ReflectionObject »
  • PHP Manual
  • ReflectionNamedType
  • Checks if it is a built-in type

ReflectionNamedType::isBuiltin

(PHP 7)

ReflectionNamedType::isBuiltin — Checks if it is a built-in type

Descripción

public ReflectionNamedType::isBuiltin ( ) : bool

Checks if the type is a built-in type in PHP.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true if it's a built-in type, otherwise false

Ejemplos

Ejemplo #1 ReflectionNamedType::isBuiltin() example

<?php
class SomeClass {}

function someFunction(string $param, SomeClass $param2, StdClass $param3) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->getType()->isBuiltin());
var_dump($reflectionParams[1]->getType()->isBuiltin());
var_dump($reflectionParams[2]->getType()->isBuiltin());

El resultado del ejemplo sería:

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

Note that the ReflectionNamedType::isBuiltin() method does not distinguish between internal and custom classes. To make this distinction, the ReflectionClass::isInternal() method should be used on the returned class name.

Ver también

  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionType::__toString() - To string
  • ReflectionClass::isInternal() - Comprueba si una clase está definida internamente por una extensión o por el núcleo
  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

mndevel at gmail dot com 13-Mar-2021 10:16
I couldn't find a list of what qualifies as a builtin. Here is what I have so far:
string
float
bool
int
iterable (Iterator reflects as type iterable)
mixed
array

These do not qualify as builtins:
Closure
Stringable
Generator
Traversable
Serializable
Throwable
IteratorAggregate
ArrayAccess
WeakReference
JsonSerializeable


Clase ReflectionObject

(PHP 5, PHP 7)

Introducción

La clase ReflectionObject reporta información sobre un object.

Sinopsis de la Clase

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

Propiedades

name

Nombre de la clase del objeto. De sólo lectura, lanza una ReflectionException en el intento de escribir .

Tabla de contenidos

  • ReflectionObject::__construct — Construye un ReflectionObject
  • ReflectionObject::export — Exportación

User Contributed Notes

ccb_bc at hotmail dot com 21-May-2019 03:39
<?php
    class FullReflectionObject {

        /**
        * @var obj => $ReflectionObject = propriedade que representa o objeto $ReflectionObject
        * @var obj => $ReflectionProperty = propriedade que representa o objeto $ReflectionProperty
        * @var obj => $ReflectionMethod = propriedade que representa o objeto $ReflectionMethod
        * @var obj => $ReflectionParameter = propriedade que representa o objeto $ReflectionParameter
        * @var bol => $reflect_object = true se o método object() for invocado
        * @var bol => $reflect_property = true se o método property() for invocado
        * @var bol => $reflect_method = true se o método method() for invocado
        * @var bol => $reflect_parameter = true se o método parameter() for invocado
        */

        private $ReflectionObject;
        private $ReflectionProperty;
        private $ReflectionMethod;
        private $ReflectionParameter;
        private $reflect_object    = false;
        private $reflect_property  = false;
        private $reflect_method    = false;
        private $reflect_parameter = false;

        /**
        * @param obj => $object = objeto a ser refletido
        */
        public function object(object $object) : object {
            $this->reflect_object = true;
            $this->ReflectionObject = new \ReflectionObject($object);
            return $this;
        }

        /**
        * @param str => $class_name = nome da classe o qual a properiedade ser refletida pertence
        * @param str => $property = nome da properiedade a ser refletida
        */
        public function property(string $class_name, string $property) : object {
            $this->reflect_property = true;
            $this->ReflectionProperty = new \ReflectionProperty($class_name, $property);
            return $this;
        }

        /**
        * @param str => $class_name = nome da classe o qual o método ser refletido pertence
        * @param str => $method = nome do método a ser refletido
        */
        public function method(string $class_name, string $method) : object {
            $this->reflect_method = true;
            $this->ReflectionMethod = new \ReflectionMethod($class_name, $method);
            return $this;
        }

        /**
        * @param str => $class_name = nome da classe o qual o parametro a ser refletido pertence
        * @param str => $method = nome do método o qual o parametro a ser refletido pertence
        * @param str => $parameter = nome do parametro a ser refletido
        */
        public function parameter(string $class_name, string $method, string $parameter) : object {
            $this->reflect_parameter = true;
            $this->ReflectionParameter = new \ReflectionParameter(array($class_name, $method), $parameter);
            return $this;
        }

        public function __call($methodName, $args){
            if($this->reflect_object){
                return call_user_func_array(array($this->ReflectionObject, $methodName), $args);
            }
            if($this->reflect_property){
                return call_user_func_array(array($this->ReflectionProperty, $methodName), $args);
            }
            if($this->reflect_method){
                return call_user_func_array(array($this->ReflectionMethod, $methodName), $args);
            }
            if($this->reflect_parameter){
                return call_user_func_array(array($this->ReflectionParameter, $methodName), $args);
            }
        }
    }

    // Digamos que você tenha no seu projeto a classe Client do pacote Guzzle
    $FullReflectionObject = new FullReflectionObject;
    var_dump($FullReflectionObject->object(new GuzzleHttp\Client)->getMethods());
    var_dump($FullReflectionObject->property('GuzzleHttp\Client', 'config')->isPrivate());
    var_dump($FullReflectionObject->method('GuzzleHttp\Client', 'buildUri')->isPrivate());
    var_dump($FullReflectionObject->parameter('GuzzleHttp\Client', 'send', 'options')->getDefaultValue());
kuldipem at gmail dot com 17-Jun-2015 06:01
class a {
    const abc = 1;
    public function __get($key){
        $r = new ReflectionObject($this);
        if($r->hasConstant($key)){ return $r->getConstant($key); }
    }
}
class b {
    public function getA(){
        return new a();
    }
}
$b = new b();
var_dump($b->getA()::abc);
var_dump($b->getA()::def);
marcel dot nolte at noltecomputer dot de 02-Sep-2009 02:42
To simply enlist all methods and properties of an object simply write:

<?php ReflectionObject::export($yourObject); ?>

,which will cause an var_export-like output.


Construye un ReflectionObject

  • « ReflectionObject
  • ReflectionObject::export »
  • PHP Manual
  • ReflectionObject
  • Construye un ReflectionObject

ReflectionObject::__construct

(PHP 5, PHP 7)

ReflectionObject::__construct — Construye un ReflectionObject

Descripción

public ReflectionObject::__construct ( object $argument )

Construye un ReflectionObject.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

argument

Una instancia del objeto.

Valores devueltos

No devuelve ningún valor.

Ver también

  • ReflectionObject::export() - Exportación
  • Constructores

User Contributed Notes

There are no user contributed notes for this page.


Exportación

  • « ReflectionObject::__construct
  • ReflectionParameter »
  • PHP Manual
  • ReflectionObject
  • Exportación

ReflectionObject::export

(PHP 5, PHP 7)

ReflectionObject::export — Exportación

Descripción

public static ReflectionObject::export ( string $argument , bool $return = ? ) : string

Exportaciones a la reflexión.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

argument

La reflexión a exportar.

return

Configurarlo a true devolverá la exportación, a diferencia de emitirla. Configurarlo a false (el valor por defecto) hará lo contrario.

Valores devueltos

Si el parámetro return es seteado a true, la exportación se devolverá como un string, de lo contrario se retornará null.

Ver también

  • ReflectionObject::__construct() - Construye un ReflectionObject

User Contributed Notes

There are no user contributed notes for this page.


La clase ReflectionParameter

(PHP 5, PHP 7)

Introducción

La clase ReflectionParameter recupera información sobre los parámetros de la función o del método.

Para hacer la introspección a los parámetros de la función, primero se crea una instancia de ReflectionFunction o de ReflectionMethod, y entonces se utiliza su método ReflectionFunctionAbstract::getParameters() para obtener un array de los parámetros.

Sinopsis de la Clase

ReflectionParameter implements Reflector {
/* Propiedades */
public $name ;
/* Métodos */
public allowsNull ( ) : bool
public canBePassedByValue ( ) : bool
final private __clone ( ) : void
public __construct ( callable $function , mixed $parameter )
public static export ( string $function , string $parameter , bool $return = ? ) : string
public getClass ( ) : ReflectionClass
public getDeclaringClass ( ) : ReflectionClass
public getDeclaringFunction ( ) : ReflectionFunctionAbstract
public getDefaultValue ( ) : mixed
public getDefaultValueConstantName ( ) : string
public getName ( ) : string
public getPosition ( ) : int
public getType ( ) : ReflectionType|null
public hasType ( ) : bool
public isArray ( ) : bool
public isCallable ( ) : bool
public isDefaultValueAvailable ( ) : bool
public isDefaultValueConstant ( ) : bool
public isOptional ( ) : bool
public isPassedByReference ( ) : bool
public isVariadic ( ) : bool
public __toString ( ) : string
}

Propiedades

name

Nombre de el parámetro. De sólo lectura, lanza una ReflectionException en el intento de escribir.

Tabla de contenidos

  • ReflectionParameter::allowsNull — Comprueba si null es permitido
  • ReflectionParameter::canBePassedByValue — Devuelve si este parámetro de puede pasar por valor
  • ReflectionParameter::__clone — Clon
  • ReflectionParameter::__construct — Construct
  • ReflectionParameter::export — Exportar
  • ReflectionParameter::getClass — Obtener la clase con declaraciones de tipos
  • ReflectionParameter::getDeclaringClass — Obtiene declaración de la clase
  • ReflectionParameter::getDeclaringFunction — Obtiene declaración de función
  • ReflectionParameter::getDefaultValue — Obtiene el valor del parámetro por defecto
  • ReflectionParameter::getDefaultValueConstantName — Devuelve el nombre de la consntante del valor predeterminado si el valor predeterminado es constante o null
  • ReflectionParameter::getName — Obtener el nombre del parámetro
  • ReflectionParameter::getPosition — Obtiene la posición del parámetro
  • ReflectionParameter::getType — Gets a parameter's type
  • ReflectionParameter::hasType — Checks if parameter has a type
  • ReflectionParameter::isArray — Comprueba si el parámetro espera un array
  • ReflectionParameter::isCallable — Devuelve si el parámetro DEBE ser de tipo callable
  • ReflectionParameter::isDefaultValueAvailable — Comprueba si el valor por defecto está disponible
  • ReflectionParameter::isDefaultValueConstant — Devuelve si el valor predeterminado de este parámetro es constante
  • ReflectionParameter::isOptional — Comprueba si es opcional
  • ReflectionParameter::isPassedByReference — Comprueba si es pasado por referencia
  • ReflectionParameter::isVariadic — Comprueba si el parámetro es varíadico
  • ReflectionParameter::__toString — A string

User Contributed Notes

fgm at riff dot org 11-May-2008 12:44
The note about the signature of the ReflectionParameter constructor is actually incomplete, at least in 5.2.5: it is possible to use an integer for the second parameter, and the constructor will use it to return the n-th parameter.

This allows you to obtain proper ReflectionParameter objects even when documenting code from extensions which (strangely enough) define several parameters with the same name. The string-based constructor always returns the first parameter with the matching name, whereas the integer-based constructor correctly returns the n-th parameter.

So, in short, this works:
<?php
// supposing the extension defined something like:
// Some_Class::someMethod($a, $x, $y, $x, $y)
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 4);
// returns the last parameter, whereas
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 'y');
// always returns the first $y at position 2
?>
killgecNOFSPAM at gmail dot com 25-Jul-2007 05:53
Signature of constructor of ReflectionParameter correctly is:

public function __construct(array/string $function, string $name);

where $function is either a name of a global function, or a class/method name pair.
massimo at mmware dot it 18-Jul-2007 08:58
I found these limitations using class ReflectionParameter from ReflectionFunction with INTERNAL FUNCTIONS (eg print_r, str_replace, ... ) :

1. parameter names don't match with manual: (try example 19.35 with arg "call_user_func" )
2. some functions (eg PCRE function, preg_match etc) have EMPTY parameter names
3. calling getDefaultValue on Parameters will result in Exception "Cannot determine default value for internal functions"


Comprueba si null es permitido

  • « ReflectionParameter
  • ReflectionParameter::canBePassedByValue »
  • PHP Manual
  • ReflectionParameter
  • Comprueba si null es permitido

ReflectionParameter::allowsNull

(PHP 5, PHP 7)

ReflectionParameter::allowsNull — Comprueba si null es permitido

Descripción

public ReflectionParameter::allowsNull ( ) : bool

Comprueba si el parámetro permite null.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si null es permitido, en caso contrario false

Ver también

  • ReflectionParameter::isOptional() - Comprueba si es opcional

User Contributed Notes

Geoffrey LAURENT 05-May-2013 03:53
The allowsNull method look if arguments have a type.
If a type is defined, null is allowed only if default value is null.

 <?php
function myfunction ( $param ) {

}

echo (new ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";

?>

Result : true

<?php
function myfunction ( stdClass $param ) {

}

echo (new ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";

?>

Result : false

<?php
function myfunction ( stdClass $param = null ) {

}

echo (new ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";
?>

Result : true


Devuelve si este parámetro de puede pasar por valor

  • « ReflectionParameter::allowsNull
  • ReflectionParameter::__clone »
  • PHP Manual
  • ReflectionParameter
  • Devuelve si este parámetro de puede pasar por valor

ReflectionParameter::canBePassedByValue

(PHP 5 >= 5.4.0, PHP 7)

ReflectionParameter::canBePassedByValue — Devuelve si este parámetro de puede pasar por valor

Descripción

public ReflectionParameter::canBePassedByValue ( ) : bool

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true si el parámetro se puede pasar por valor, de lo contrario false. Retorna null en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Clon

  • « ReflectionParameter::canBePassedByValue
  • ReflectionParameter::__construct »
  • PHP Manual
  • ReflectionParameter
  • Clon

ReflectionParameter::__clone

(PHP 5, PHP 7)

ReflectionParameter::__clone — Clon

Descripción

final private ReflectionParameter::__clone ( ) : void

Clones.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Ver también

  • ReflectionParameter::toString()
  • Clonación de Objetos

User Contributed Notes

There are no user contributed notes for this page.


Construct

  • « ReflectionParameter::__clone
  • ReflectionParameter::export »
  • PHP Manual
  • ReflectionParameter
  • Construct

ReflectionParameter::__construct

(PHP 5, PHP 7)

ReflectionParameter::__construct — Construct

Descripción

public ReflectionParameter::__construct ( callable $function , mixed $parameter )

Construye una instancia ReflectionParameter.

Parámetros

function

La función a reflejar parámetros.

parameter

O bien un int especificando la posición del parámetro (empezando con cero), o un nombre de parámetro como string.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Usando la clase ReflectionParameter

<?php
function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }

$reflect = new ReflectionFunction('foo');

echo $reflect;

foreach ($reflect->getParameters() as $i => $param) {
    printf(
        "-- Parameter #%d: %s {\n".
        "   Class: %s\n".
        "   Allows NULL: %s\n".
        "   Passed to by reference: %s\n".
        "   Is optional?: %s\n".
        "}\n",
        $i, // $param->getPosition() can be used from PHP 5.2.3
        $param->getName(),
        var_export($param->getClass(), 1),
        var_export($param->allowsNull(), 1),
        var_export($param->isPassedByReference(), 1),
        $param->isOptional() ? 'yes' : 'no'
    );
}
?>

El resultado del ejemplo sería algo similar a:

Function [ <user> function foo ] {
  @@ /Users/philip/cvs/phpdoc/a 2 - 2

  - Parameters [3] {
    Parameter #0 [ <required> $a ]
    Parameter #1 [ <required> $b ]
    Parameter #2 [ <required> $c ]
  }
}
-- Parameter #0: a {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}
-- Parameter #1: b {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}
-- Parameter #2: c {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}

Ver también

  • ReflectionFunctionAbstract::getParameters() - Obtiene los parámetros
  • ReflectionFunction::__construct() - Contruye un objeto de tipo ReflectionFunction
  • ReflectionMethod::__construct() - Construye un objeto ReflectionMethod
  • Constructors

User Contributed Notes

tracid2008 t gmail o com 06-Dec-2011 03:31
You also can use a class instead of a function name. Just use an array like that
<?php
$reflect = new ReflectionParameter(array('className', 'methodName'), 'property');
?>


Exportar

  • « ReflectionParameter::__construct
  • ReflectionParameter::getClass »
  • PHP Manual
  • ReflectionParameter
  • Exportar

ReflectionParameter::export

(PHP 5, PHP 7)

ReflectionParameter::export — Exportar

Descripción

public static ReflectionParameter::export ( string $function , string $parameter , bool $return = ? ) : string

Exportar.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

function

El nombre de la función.

parameter

El nombre del parámetro.

return

Configurarlo a true devolverá la exportación, a diferencia de emitirla. Configurarlo a false (el valor por defecto) hará lo contrario.

Valores devueltos

La reflexión exportada.

Ver también

  • ReflectionParameter::toString()

User Contributed Notes

There are no user contributed notes for this page.


Obtener la clase con declaraciones de tipos

  • « ReflectionParameter::export
  • ReflectionParameter::getDeclaringClass »
  • PHP Manual
  • ReflectionParameter
  • Obtener la clase con declaraciones de tipos

ReflectionParameter::getClass

(PHP 5, PHP 7)

ReflectionParameter::getClass — Obtener la clase con declaraciones de tipos

Descripción

public ReflectionParameter::getClass ( ) : ReflectionClass

Obtiene la clase con declaraciones de tipos para el parámetro como un objeto ReflectionClass.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un objeto ReflectionClass.

Ejemplos

Ejemplo #1 Utilizar la clase ReflectionParameter

<?php
function foo(Exception $a) { }

$functionReflection = new ReflectionFunction('foo');
$parameters = $functionReflection->getParameters();
$aParameter = $parameters[0];

echo $aParameter->getClass()->name;
?>

El resultado del ejemplo sería:

Exception

Ver también

  • ReflectionParameter::getDeclaringClass() - Obtiene declaración de la clase

User Contributed Notes

tarik at bitstore dot ru 22-Feb-2021 07:08
You may use this one function instead depricated

    /**
     * Get parameter class
     * @param \ReflectionParameter $parameter
     * @return \ReflectionClass|null
     */
    private function getClass(\ReflectionParameter $parameter):?\ReflectionClass
    {
        $type = $parameter->getType();
        if (!$type || $type->isBuiltin())
            return NULL;

// This line triggers autoloader!
        if(!class_exists($type->getName()))
            return NULL;

        return  new \ReflectionClass($type->getName());
    }
Dylan 12-Feb-2021 11:47
For php version >=8
ReflectionParamter::getType() is the recommended way to replace the deprecated methods:

- getClass()
e.g: $name = $param->getType() && !$param->getType()->isBuiltin()
       ? new ReflectionClass($param->getType()->getName())
       : null;

- isArray()
e.g: $isArray = $param->getType() && $param->getType()->getName() === 'array';

- isCallable()
e.g: $isCallable = $param->getType() && $param->getType()->getName() === 'callable';

This method is available in PHP 7.0 and later.
richard dot t dot rohrig at gmail dot com 01-Jun-2020 09:33
Example of how to use getClass() in conjunction with getConstructor() to build the dependencies of a class.

private function buildDependencies(ReflectionClass $reflection)
    {
        $constructor = $reflection->getConstructor();

        if (!$constructor) {
            return [];
        }

        $params = $constructor->getParameters();

        return array_map(function ($param) {

            $className = $param->getClass();

            if (!$className) {
                throw new Exception();
            }

            $className = $param->getClass()->getName();

            return $this->make($className);
        }, $params);
    }
tom at r dot je 11-May-2012 09:15
ReflectionParameter::getClass() will cause a fatal error (and trigger __autoload) if the class required by the parameter is not defined.

Sometimes it's useful to only know the class name without needing the class to be loaded.

Here's a simple function that will retrieve only the class name without requiring the class to exist:

<?php
function getClassName(ReflectionParameter $param) {
    preg_match('/\[\s\<\w+?>\s([\w]+)/s', $param->__toString(), $matches);
    return isset($matches[1]) ? $matches[1] : null;
}
?>
infernaz at gmail dot com 31-Jan-2011 12:09
The method returns ReflectionClass object of parameter type class or NULL if none.

<?php

class A {
    function b(B $c, array $d, $e) {
    }
}
class B {
}

$refl = new ReflectionClass('A');
$par = $refl->getMethod('b')->getParameters();

var_dump($par[0]->getClass()->getName());  // outputs B
var_dump($par[1]->getClass());  // note that array type outputs NULL
var_dump($par[2]->getClass());  // outputs NULL

?>


Obtiene declaración de la clase

  • « ReflectionParameter::getClass
  • ReflectionParameter::getDeclaringFunction »
  • PHP Manual
  • ReflectionParameter
  • Obtiene declaración de la clase

ReflectionParameter::getDeclaringClass

(PHP 5 >= 5.1.3, PHP 7)

ReflectionParameter::getDeclaringClass — Obtiene declaración de la clase

Descripción

public ReflectionParameter::getDeclaringClass ( ) : ReflectionClass

Obtiene la declaración de la clase.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un objeto ReflectionClass.

Ejemplos

Ejemplo #1 Obtener la clase que declaró el método

<?php
class Foo
{
    public function bar(\DateTime $datetime)
    {
    }
}

class Baz extends Foo
{
}

$param = new \ReflectionParameter(['Baz', 'bar'], 0);

var_dump($param->getDeclaringClass());

El resultado del ejemplo sería:

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(3) "Foo"
}

Ver también

  • ReflectionParameter::getClass() - Obtener la clase con declaraciones de tipos

User Contributed Notes

There are no user contributed notes for this page.


Obtiene declaración de función

  • « ReflectionParameter::getDeclaringClass
  • ReflectionParameter::getDefaultValue »
  • PHP Manual
  • ReflectionParameter
  • Obtiene declaración de función

ReflectionParameter::getDeclaringFunction

(PHP 5 >= 5.1.3, PHP 7)

ReflectionParameter::getDeclaringFunction — Obtiene declaración de función

Descripción

public ReflectionParameter::getDeclaringFunction ( ) : ReflectionFunctionAbstract

Obtiene declaración de la función.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un objeto ReflectionFunction.

Ver también

  • ReflectionParameter::getDeclaringClass() - Obtiene declaración de la clase

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el valor del parámetro por defecto

  • « ReflectionParameter::getDeclaringFunction
  • ReflectionParameter::getDefaultValueConstantName »
  • PHP Manual
  • ReflectionParameter
  • Obtiene el valor del parámetro por defecto

ReflectionParameter::getDefaultValue

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::getDefaultValue — Obtiene el valor del parámetro por defecto

Descripción

public ReflectionParameter::getDefaultValue ( ) : mixed

Obtiene el valor por defecto del parámetro de una función definida por el usuario o en el método. Si el parámetro no es opcional una ReflectionException será lanzada.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

El valor de los parámetros por defecto.

Ejemplos

Ejemplo #1 Obtención de los valores por defecto de los parámetros de la función

<?php
function foo($test, $bar = 'baz')
{
    echo $test . $bar;
}

$function = new ReflectionFunction('foo');

foreach ($function->getParameters() as $param) {
    echo 'Nombre: ' . $param->getName() . PHP_EOL;
    if ($param->isOptional()) {
        echo 'Valor por defecto: ' . $param->getDefaultValue() . PHP_EOL;
    }
    echo PHP_EOL;
}
?>

El resultado del ejemplo sería:

Nombre: test

Nombre: bar
Valor por defecto: baz

Notas

Nota:

Debido a detalles de implementación, no es posible obtener el valor por omisión de una función o método de clases incorporadas. intentar hacer esto una ReflectionException será lanzada.

Ver también

  • ReflectionParameter::isOptional() - Comprueba si es opcional
  • ReflectionParameter::isDefaultValueAvailable() - Comprueba si el valor por defecto está disponible
  • ReflectionParameter::getDefaultValueConstantName() - Devuelve el nombre de la consntante del valor predeterminado si el valor predeterminado es constante o null
  • ReflectionParameter::isPassedByReference() - Comprueba si es pasado por referencia

User Contributed Notes

gmail@asmqb7 16-May-2016 12:57
[Editor's note: fixed on user's request]

Getting `Uncaught ReflectionException: Internal error: Failed to retrieve the default value`?

You have to wrap this inside ->isDefaultValueAvailable().


Devuelve el nombre de la consntante del valor predeterminado si el valor predeterminado es constante o null

  • « ReflectionParameter::getDefaultValue
  • ReflectionParameter::getName »
  • PHP Manual
  • ReflectionParameter
  • Devuelve el nombre de la consntante del valor predeterminado si el valor predeterminado es constante o null

ReflectionParameter::getDefaultValueConstantName

(PHP 5 >= 5.4.6, PHP 7)

ReflectionParameter::getDefaultValueConstantName — Devuelve el nombre de la consntante del valor predeterminado si el valor predeterminado es constante o null

Descripción

public ReflectionParameter::getDefaultValueConstantName ( ) : string

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve un string en caso de éxito o null en caso de fallo.

User Contributed Notes

There are no user contributed notes for this page.


Obtener el nombre del parámetro

  • « ReflectionParameter::getDefaultValueConstantName
  • ReflectionParameter::getPosition »
  • PHP Manual
  • ReflectionParameter
  • Obtener el nombre del parámetro

ReflectionParameter::getName

(PHP 5, PHP 7)

ReflectionParameter::getName — Obtener el nombre del parámetro

Descripción

public ReflectionParameter::getName ( ) : string

Obtener el nombre de el parámetro.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

El nombre del parámetro reflejado.

Ver también

  • ReflectionParameter::getValue()

User Contributed Notes

mike 25-May-2015 07:26
FYI, it returns the parameter name without the dollars($) sign at the start.


Obtiene la posición del parámetro

  • « ReflectionParameter::getName
  • ReflectionParameter::getType »
  • PHP Manual
  • ReflectionParameter
  • Obtiene la posición del parámetro

ReflectionParameter::getPosition

(PHP 5 >= 5.1.3, PHP 7)

ReflectionParameter::getPosition — Obtiene la posición del parámetro

Descripción

public ReflectionParameter::getPosition ( ) : int

Obtiene la posición de el parámetro.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

La posición de el parámetro, de izquierda a derecha, comenzando en la posición #0.

Ver también

  • ReflectionParameter::getName() - Obtener el nombre del parámetro

User Contributed Notes

micah at raincross-tech dot com 05-Dec-2010 07:26
Note that the ReflectionFunctionAbstract::getParameters() method will return the parameters in the correct order.


Gets a parameter's type

  • « ReflectionParameter::getPosition
  • ReflectionParameter::hasType »
  • PHP Manual
  • ReflectionParameter
  • Gets a parameter's type

ReflectionParameter::getType

(PHP 7)

ReflectionParameter::getType — Gets a parameter's type

Descripción

public ReflectionParameter::getType ( ) : ReflectionType|null

Gets the associated type of a parameter.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns a ReflectionType object if a parameter type is specified, null otherwise.

Ejemplos

Ejemplo #1 ReflectionParameter::getType() Usage as of PHP 7.1.0

As of PHP 7.1.0, ReflectionType::__toString() is deprecated, and ReflectionParameter::getType() may return an instance of ReflectionNamedType. To get the name of the parameter type, ReflectionNamedType() is available in this case.

<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

assert($reflectionType1 instanceof ReflectionNamedType);
echo $reflectionType1->getName(), PHP_EOL;
var_dump($reflectionType2);
?>

El resultado del ejemplo sería:

int
NULL

Ejemplo #2 ReflectionParameter::getType() Usage before PHP 7.1.0

<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

echo $reflectionType1, PHP_EOL;
var_dump($reflectionType2);
?>

Salida del ejemplo anterior en PHP 7.0:

int
NULL

Ver también

  • ReflectionParameter::hasType() - Checks if parameter has a type
  • ReflectionType::__toString() - To string

User Contributed Notes

Will Beaumont 05-Sep-2020 04:26
As of 7.1, if a parameter type is found then this method returns an instance of ReflectionNamedType (https://www.php.net/manual/en/class.reflectionnamedtype.php), a subclass of ReflectionType.


Checks if parameter has a type

  • « ReflectionParameter::getType
  • ReflectionParameter::isArray »
  • PHP Manual
  • ReflectionParameter
  • Checks if parameter has a type

ReflectionParameter::hasType

(PHP 7)

ReflectionParameter::hasType — Checks if parameter has a type

Descripción

public ReflectionParameter::hasType ( ) : bool

Checks if the parameter has a type associated with it.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true if a type is specified, false otherwise.

Ejemplos

Ejemplo #1 ReflectionParameter::hasType() example

<?php
function someFunction(string $param, $param2 = null) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->hasType());
var_dump($reflectionParams[1]->hasType());

El resultado del ejemplo sería algo similar a:

bool(true)
bool(false)

Ver también

  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el parámetro espera un array

  • « ReflectionParameter::hasType
  • ReflectionParameter::isCallable »
  • PHP Manual
  • ReflectionParameter
  • Comprueba si el parámetro espera un array

ReflectionParameter::isArray

(PHP 5 >= 5.1.2, PHP 7)

ReflectionParameter::isArray — Comprueba si el parámetro espera un array

Descripción

public ReflectionParameter::isArray ( ) : bool

Comprueba si el parámetro espera un array.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si un array es esperado, en caso contrario false.

Ver también

  • ReflectionParameter::isOptional() - Comprueba si es opcional

User Contributed Notes

denis at example dot com 19-Feb-2020 08:45
Hi, this is simple example of how to use it.

class Test
{
    public function testArray(array $a)
    {
        // do something...

        return $a;
    }

    public function testString(string $a)
    {
        // do something...

        return $a;
    }
}

$reflection = new ReflectionClass('Test');

foreach($reflection->getMethods() as $methods){
    foreach($methods->getParameters() as $param){
        var_dump($param->isArray());
    }
}

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


Devuelve si el parámetro DEBE ser de tipo callable

  • « ReflectionParameter::isArray
  • ReflectionParameter::isDefaultValueAvailable »
  • PHP Manual
  • ReflectionParameter
  • Devuelve si el parámetro DEBE ser de tipo callable

ReflectionParameter::isCallable

(PHP 5 >= 5.4.0, PHP 7)

ReflectionParameter::isCallable — Devuelve si el parámetro DEBE ser de tipo callable

Descripción

public ReflectionParameter::isCallable ( ) : bool

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true si el parámetro es callable, false si no, o null en caso de error.

User Contributed Notes

me at abiusx dot com 15-Jan-2016 05:18
Apparently this does not return true for callback arguments to many of the internal functions, such as array_map and array_walk.


Comprueba si el valor por defecto está disponible

  • « ReflectionParameter::isCallable
  • ReflectionParameter::isDefaultValueConstant »
  • PHP Manual
  • ReflectionParameter
  • Comprueba si el valor por defecto está disponible

ReflectionParameter::isDefaultValueAvailable

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::isDefaultValueAvailable — Comprueba si el valor por defecto está disponible

Descripción

public ReflectionParameter::isDefaultValueAvailable ( ) : bool

Comprueba si el valor por defecto para el parámetro está disponible.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el valor por defecto está disponible, en caso contrario false

Ver también

  • ReflectionParameter::getDefaultValue() - Obtiene el valor del parámetro por defecto
  • ReflectionParameter::isDefaultValueConstant() - Devuelve si el valor predeterminado de este parámetro es constante
  • ReflectionParameter::getName() - Obtener el nombre del parámetro

User Contributed Notes

There are no user contributed notes for this page.


Devuelve si el valor predeterminado de este parámetro es constante

  • « ReflectionParameter::isDefaultValueAvailable
  • ReflectionParameter::isOptional »
  • PHP Manual
  • ReflectionParameter
  • Devuelve si el valor predeterminado de este parámetro es constante

ReflectionParameter::isDefaultValueConstant

(PHP 5 >= 5.4.6, PHP 7)

ReflectionParameter::isDefaultValueConstant — Devuelve si el valor predeterminado de este parámetro es constante

Descripción

public ReflectionParameter::isDefaultValueConstant ( ) : bool

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true si el valor predeterminado es constante, false si no lo es, o null en caso de error.

User Contributed Notes

kristianoye at gmail dot com 25-May-2015 09:39
This method returns true only if the parameter's default value is set to a named constant.  e.g.

class Foo {
   const OPTION_MULTIGET = 1;

   //Method 1
   public function setGetOptions($opts=0);

   //Method 2
   public function setMultiGetOptions($opts=Foo::OPTION_MULTIGET);
}

Method 1's first ReflectionParameter will return isDefaultValueConstant() = false (0 is a "constant"/static value but not a named constant) and Method 2's will return isDefaultValueConsntant() = true.


Comprueba si es opcional

  • « ReflectionParameter::isDefaultValueConstant
  • ReflectionParameter::isPassedByReference »
  • PHP Manual
  • ReflectionParameter
  • Comprueba si es opcional

ReflectionParameter::isOptional

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::isOptional — Comprueba si es opcional

Descripción

public ReflectionParameter::isOptional ( ) : bool

Comprueba si el parámetro es opcional.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el parámetro es opcional, en caso contrario false

Ver también

  • ReflectionParameter::getName() - Obtener el nombre del parámetro

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si es pasado por referencia

  • « ReflectionParameter::isOptional
  • ReflectionParameter::isVariadic »
  • PHP Manual
  • ReflectionParameter
  • Comprueba si es pasado por referencia

ReflectionParameter::isPassedByReference

(PHP 5, PHP 7)

ReflectionParameter::isPassedByReference — Comprueba si es pasado por referencia

Descripción

public ReflectionParameter::isPassedByReference ( ) : bool

Comprueba si el parámetro es pasado por referencia.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el parámetro es pasado por referencia, en caso contrario false

Ver también

  • ReflectionParameter::getName() - Obtener el nombre del parámetro

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el parámetro es varíadico

  • « ReflectionParameter::isPassedByReference
  • ReflectionParameter::__toString »
  • PHP Manual
  • ReflectionParameter
  • Comprueba si el parámetro es varíadico

ReflectionParameter::isVariadic

(PHP 5 >= 5.6.0, PHP 7)

ReflectionParameter::isVariadic — Comprueba si el parámetro es varíadico

Descripción

public ReflectionParameter::isVariadic ( ) : bool

Comprueba si el parámetro fue declarado como un parámetro variádico.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true si el parámetro es varíadico, o false en caso contrario.

User Contributed Notes

There are no user contributed notes for this page.


A string

  • « ReflectionParameter::isVariadic
  • ReflectionProperty »
  • PHP Manual
  • ReflectionParameter
  • A string

ReflectionParameter::__toString

(PHP 5, PHP 7)

ReflectionParameter::__toString — A string

Descripción

public ReflectionParameter::__toString ( ) : string

A string.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Ver también

  • ReflectionParameter::export() - Exportar
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


Clase ReflectionProperty

(PHP 5, PHP 7)

Introducción

La clase ReflectionProperty muestra información sobre las propiedades de una clase.

Sinopsis de la Clase

ReflectionProperty implements Reflector {
/* Constantes */
const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
/* Propiedades */
public $name ;
public $class ;
/* Métodos */
final private __clone ( ) : void
public __construct ( mixed $class , string $name )
public static export ( mixed $class , string $name , bool $return = ? ) : string
public getDeclaringClass ( ) : ReflectionClass
public getDefaultValue ( ) : mixed
public getDocComment ( ) : string
public getModifiers ( ) : int
public getName ( ) : string
public getType ( ) : ReflectionType|null
public getValue ( object $object = ? ) : mixed
public hasDefaultValue ( ) : bool
public hasType ( ) : bool
public isDefault ( ) : bool
public isInitialized ( object|null $object = null ) : bool
public isPrivate ( ) : bool
public isProtected ( ) : bool
public isPublic ( ) : bool
public isStatic ( ) : bool
public setAccessible ( bool $accessible ) : void
public setValue ( object $object , mixed $value ) : void
public __toString ( ) : string
}

Propiedades

name

Nombre de la propiedad. De sólo lectura, lanza una ReflectionException en un intento de escribir.

class

Nombre de la clase donde se define la propiedad. De sólo lectura, lanza una ReflectionException en un intento de escribir.

Constantes predefinidas

Modificadores ReflectionProperty

ReflectionProperty::IS_STATIC

Indica las propiedades static.

ReflectionProperty::IS_PUBLIC

Indica las propiedades public.

ReflectionProperty::IS_PROTECTED

Indica las propiedades protected.

ReflectionProperty::IS_PRIVATE

Indica las propiedades private.

Tabla de contenidos

  • ReflectionProperty::__clone — Clonar
  • ReflectionProperty::__construct — Construir un objeto ReflectionProperty
  • ReflectionProperty::export — Exportar
  • ReflectionProperty::getDeclaringClass — Obtiene la clase en la que se declaró
  • ReflectionProperty::getDefaultValue — Returns the default value declared for a property
  • ReflectionProperty::getDocComment — Obtiene los comentarios de documentación de una propiedad
  • ReflectionProperty::getModifiers — Obtiene los modificadores
  • ReflectionProperty::getName — Obtiene el nombre de la propiedad
  • ReflectionProperty::getType — Gets a property's type
  • ReflectionProperty::getValue — Obtiene el valor
  • ReflectionProperty::hasDefaultValue — Checks if property has a default value declared
  • ReflectionProperty::hasType — Checks if property has a type
  • ReflectionProperty::isDefault — Comprueba si una propiedad es predeterminada
  • ReflectionProperty::isInitialized — Checks whether a property is initialized
  • ReflectionProperty::isPrivate — Comprueba si una propiedad es privada
  • ReflectionProperty::isProtected — Comprueba si la propiedad es protegida
  • ReflectionProperty::isPublic — Comprueba si la propiedad es pública
  • ReflectionProperty::isStatic — Comprueba si la propiedad es estática
  • ReflectionProperty::setAccessible — Hace accesible una propiedad
  • ReflectionProperty::setValue — Establece el valor de la propiedad
  • ReflectionProperty::__toString — Convertir a texto

User Contributed Notes

Nanhe Kumar 06-Jan-2014 12:36
<?php
//serialize static properties (class variable)

class Student {

    private $members = array();
    protected $name;
    public static $noOfStudent;

    public function __construct($name = 'Nanhe Kumar') {
        $this->name = $name;
        Student::$noOfStudent++;
    }

    public function __sleep() {
        $vars = get_class_vars(get_class($this));
        foreach ($vars as $key => $val) {
            if (!empty($val))
                $this->members[$key] = $val;
        }
        return array_keys(get_object_vars($this));
    }

    public function __wakeup() {
        foreach ($this->members as $key => $val) {
            $prop = new ReflectionProperty(get_class($this), $key);
            $prop->setValue(get_class($this), $val);
        }
        $this->members = array();
    }

    public function getTotalStudent() {
        return self::$noOfStudent;
    }

}

$so1 = new Student();
$so2 = new Student();
$serialized = serialize($so1);
print_r($serialized); //O:7:"Student":2:{s:16:"Studentmembers";a:1:{s:11:"noOfStudent";i:2;}s:7:"*name";s:11:"Nanhe Kumar";}
$unserialized = unserialize($serialized);
print_r($unserialized); //Student Object ( [members:Student:private] => Array ( ) [name:protected] => Nanhe Kumar )
echo Student::$noOfStudent; //2
?>
rasmus at mindplay dot dk 30-Jul-2010 05:06
I think a more accurate explanation is this:

The Reflection classes are designed to reflect upon the source code of an application, not on any runtime information.

I think you misunderstand the ReflectionProperty constructor in your example above. The fact that it accepts an object as argument is just a convenience feature - you are actually inspecting the class of that object, not the object itself, so it's basically equivalent to:

<?php

// works fine
$Reflection = new ReflectionProperty(get_class($a), 'a');

// throws exception
$Reflection = new ReflectionProperty(get_class($a), 'foo');

?>

Getting the class of the object you're passing in is implied, since inspecting a defined property is the purpose of this class.

In your example, $a->foo is a dynamic member - it is not defined as a member of class, so there is no defining class reference, line number, default value, etc. - which means, there is nothing to reflect upon.

Clearly this very useful library could use some real documentation...


Clonar

  • « ReflectionProperty
  • ReflectionProperty::__construct »
  • PHP Manual
  • ReflectionProperty
  • Clonar

ReflectionProperty::__clone

(PHP 5, PHP 7)

ReflectionProperty::__clone — Clonar

Descripción

final private ReflectionProperty::__clone ( ) : void

Clonar.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Ver también

  • ReflectionProperty::export() - Exportar
  • Clonación de objetos

User Contributed Notes

There are no user contributed notes for this page.


Construir un objeto ReflectionProperty

  • « ReflectionProperty::__clone
  • ReflectionProperty::export »
  • PHP Manual
  • ReflectionProperty
  • Construir un objeto ReflectionProperty

ReflectionProperty::__construct

(PHP 5, PHP 7)

ReflectionProperty::__construct — Construir un objeto ReflectionProperty

Descripción

public ReflectionProperty::__construct ( mixed $class , string $name )

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

class

El nombre de la clase que contiene la propiedad.

name

El nombre de la propiedad a reflexionar.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

Si se tratara de consultar o modificar propiedades privadas o protegidas de la clase, se lanzará una excepción.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionProperty::__construct()

<?php
class Str
{
    public $longitud = 5;
}

// Crear una instancia de la clase ReflectionProperty
$prop = new ReflectionProperty('Str', 'longitud');

// Mostrar información básica
printf(
    "===> La propiedad %s%s%s%s '%s' (que está %s)\n" .
    "     con los modificadores %s\n",
        $prop->isPublic() ? ' pública' : '',
        $prop->isPrivate() ? ' privada' : '',
        $prop->isProtected() ? ' protegida' : '',
        $prop->isStatic() ? ' estática' : '',
        $prop->getName(),
        $prop->isDefault() ? 'declarada en tiempo de compilación' : 'creada en tiempo de ejecución',
        var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);

// Crear una instancia de Str
$obj= new Texto();

// Obtener el valor actual
printf("---> Valor: ");
var_dump($prop->getValue($obj));

// Cambiar valor
$prop->setValue($obj, 10);
printf("---> Al establecer como valor 10, su nuevo valor es: ");
var_dump($prop->getValue($obj));

// Volcar objeto
var_dump($obj);
?>

El resultado del ejemplo sería algo similar a:

===> La propiedad  pública 'longitud' (que está declarada en tiempo de compilación)
     con los modificadores array (
  0 => 'public',
)
---> Valor: int(5)
---> Al establecer como valor 10, su nuevo valor es: int(10)
object(Str)#2 (1) {
  ["longitud"]=>
  int(10)
}

Ejemplo #2 Obtener el valor de propiedades privadas y protegidas con ReflectionProperty

<?php

class Foo {
    public $x = 1;
    protected $y = 2;
    private $z = 3;
}

$obj = new Foo;

$prop = new ReflectionProperty('Foo', 'y');
$prop->setAccessible(true); /* Desde PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

$prop = new ReflectionProperty('Foo', 'z');
$prop->setAccessible(true); /* Desde PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

?>

El resultado del ejemplo sería algo similar a:

int(2)
int(3)

Ver también

  • ReflectionProperty::getName() - Obtiene el nombre de la propiedad
  • Constructores

User Contributed Notes

geoffsmiths at hotmail dot com 05-Jul-2017 12:20
At example #2: the comment // int(2) is stated while the value for the private property is actually 3. (private $z = 3;)

var_dump($prop->getValue($obj)); // This should be int(3)


Exportar

  • « ReflectionProperty::__construct
  • ReflectionProperty::getDeclaringClass »
  • PHP Manual
  • ReflectionProperty
  • Exportar

ReflectionProperty::export

(PHP 5, PHP 7)

ReflectionProperty::export — Exportar

Descripción

public static ReflectionProperty::export ( mixed $class , string $name , bool $return = ? ) : string

Exporta una reflexión.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

argument

La reflexión a exportar.

name

Nombre de la propiedad.

return

Configurarlo a true devolverá la exportación, a diferencia de emitirla. Configurarlo a false (el valor por defecto) hará lo contrario.

Valores devueltos

Ver también

  • ReflectionProperty::toString()

User Contributed Notes

antonfedonyuk at gmail dot com 03-Sep-2020 03:16
Note: export() method is deprecated in PHP 7.4, use __toString() instead - this method return same result.


Obtiene la clase en la que se declaró

  • « ReflectionProperty::export
  • ReflectionProperty::getDefaultValue »
  • PHP Manual
  • ReflectionProperty
  • Obtiene la clase en la que se declaró

ReflectionProperty::getDeclaringClass

(PHP 5, PHP 7)

ReflectionProperty::getDeclaringClass — Obtiene la clase en la que se declaró

Descripción

public ReflectionProperty::getDeclaringClass ( ) : ReflectionClass

Devuelve la clase en la que se declaró.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Objeto de tipo ReflectionClass.

Ver también

  • ReflectionProperty::getName() - Obtiene el nombre de la propiedad

User Contributed Notes

metamarkers at gmail dot com 17-May-2013 06:30
If you're reflecting an object and get the declaring class of a property that's set but wasn't declared in any class, it returns the class of the instance.

<?php

class X {

}

$x = new X();
$x->foo = 'bar';
$reflection = new ReflectionObject($x);
echo $reflection->getProperty('foo')->getDeclaringClass()->getName(); // X

?>


Returns the default value declared for a property

  • « ReflectionProperty::getDeclaringClass
  • ReflectionProperty::getDocComment »
  • PHP Manual
  • ReflectionProperty
  • Returns the default value declared for a property

ReflectionProperty::getDefaultValue

(PHP 8)

ReflectionProperty::getDefaultValue — Returns the default value declared for a property

Descripción

public ReflectionProperty::getDefaultValue ( ) : mixed

Gets the implicit or explicitly declared default value for a property.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

The default value if the property has any default value (including null). If there is no default value, then null is returned. It is not possible to differentiate between a null default value and an unitialized typed property. Use ReflectionClass::hasDefaultValue() to detect the difference.

Ejemplos

Ejemplo #1 ReflectionClass::getDefaultValue() example

<?php
class Foo {
    public $bar = 1;
    public ?int $baz;
    public int $boing = 0;
}

$ro = new ReflectionClass(Foo::class);
var_dump($ro->getProperty('bar')->getDefaultValue());
var_dump($ro->getProperty('baz')->getDefaultValue());
var_dump($ro->getProperty('boing')->getDefaultValue());
?>

El resultado del ejemplo sería:

int(1)
NULL
int(0)

Ver también

  • ReflectionProperty::hasDefaultValue() - Checks if property has a default value declared

User Contributed Notes

There are no user contributed notes for this page.


Obtiene los comentarios de documentación de una propiedad

  • « ReflectionProperty::getDefaultValue
  • ReflectionProperty::getModifiers »
  • PHP Manual
  • ReflectionProperty
  • Obtiene los comentarios de documentación de una propiedad

ReflectionProperty::getDocComment

(PHP 5 >= 5.1.0, PHP 7)

ReflectionProperty::getDocComment — Obtiene los comentarios de documentación de una propiedad

Descripción

public ReflectionProperty::getDocComment ( ) : string

Obtiene los comentarios de documentación de una propiedad.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Los comentarios de documentación de una propiedad.

Ejemplos

Ejemplo #1 Ejemplo de ReflectionProperty::getDocComment()

<?php
class Str
{
    /**
     * @var int  La longitud del string
     */
    public $length = 5;
}

$prop = new ReflectionProperty('Str', 'length');

var_dump($prop->getDocComment());

?>

El resultado del ejemplo sería algo similar a:

string(51) "/**
     * @var int  La longitud del string
     */"

Ver también

  • ReflectionProperty::getModifiers() - Obtiene los modificadores
  • ReflectionProperty::getName() - Obtiene el nombre de la propiedad
  • ReflectionProperty::getValue() - Obtiene el valor

User Contributed Notes

There are no user contributed notes for this page.


Obtiene los modificadores

  • « ReflectionProperty::getDocComment
  • ReflectionProperty::getName »
  • PHP Manual
  • ReflectionProperty
  • Obtiene los modificadores

ReflectionProperty::getModifiers

(PHP 5, PHP 7)

ReflectionProperty::getModifiers — Obtiene los modificadores

Descripción

public ReflectionProperty::getModifiers ( ) : int

Devuelve los modificadores de la propiedad.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Representación numérica de los modificadores.

Ver también

  • ReflectionProperty::isPrivate() - Comprueba si una propiedad es privada
  • Reflection::getModifierNames() - Obtener nombres de modificadores

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el nombre de la propiedad

  • « ReflectionProperty::getModifiers
  • ReflectionProperty::getType »
  • PHP Manual
  • ReflectionProperty
  • Obtiene el nombre de la propiedad

ReflectionProperty::getName

(PHP 5, PHP 7)

ReflectionProperty::getName — Obtiene el nombre de la propiedad

Descripción

public ReflectionProperty::getName ( ) : string

Devuelve el nombre de la propiedad.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Nombre de la propiedad.

Ver también

  • ReflectionProperty::getValue() - Obtiene el valor

User Contributed Notes

There are no user contributed notes for this page.


Gets a property's type

  • « ReflectionProperty::getName
  • ReflectionProperty::getValue »
  • PHP Manual
  • ReflectionProperty
  • Gets a property's type

ReflectionProperty::getType

(PHP 7 >= 7.4.0)

ReflectionProperty::getType — Gets a property's type

Descripción

public ReflectionProperty::getType ( ) : ReflectionType|null

Gets the associated type of a property.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns a ReflectionType if the property has a type, and null otherwise.

Ejemplos

Ejemplo #1 ReflectionProperty::getType() example

<?php
class User
{
    public string $name;
}

$rp = new ReflectionProperty('User', 'name');
echo $rp->getType()->getName();
?>

El resultado del ejemplo sería:

string

Ver también

  • ReflectionProperty::hasType() - Checks if property has a type
  • ReflectionProperty::isInitialized() - Checks whether a property is initialized

User Contributed Notes

andr3medeiros at gmail dot com 06-Aug-2020 10:31
<?php

namespace App\Traits;

use ReflectionClass;
use Illuminate\Support\Str;
use InvalidArgumentException;

trait FieldTypeTrait {

  protected function getType(String $field, ReflectionClass $reflectedClass = null)
  {
    if(is_null($reflectedClass)) {
      $reflectedClass = new ReflectionClass($this);
    }

    if ($reflectedClass->hasProperty($field)) {
      return $this->getFieldType($field, $reflectedClass);
    }

    return null;
  }

  protected function enumValue(String $field) {
    if($this->isEnum($field)) {
      throw new InvalidArgumentException("'$field' is not an enum");
    }

    $type = $this->getType($field);
    $enumClass = $type->name;

    return new $enumClass($this->{$field});
  }

  protected function isEnum(String $field)
  {
    $type = $this->getType($field);

    if(!is_object($type)) {
      return false;
    }

    $className = $type->name;

    $reflectedClass = new ReflectionClass($className);
    $reflectedParent = $reflectedClass->getParentClass();

    return $reflectedParent->getName() == 'MyCLabs\Enum\Enum';
  }

  private function getUseStatements(): array
  {
    $reflectedThis = new ReflectionClass($this);
    $contents = file_get_contents($reflectedThis->getFileName());

    $matches = [];

    preg_match_all("/use ([\w\\\\]+)( as \w+)*/", $contents, $matches);

    $results = [];
    foreach ($matches[1] as $index => $value) {
      $results[] = [
        'namespace' => $value,
        'alias' => isset($matches[2][$index]) ? str_replace(' as ', '', $matches[2][$index]) : null
      ];
    }

    return $results;
  }

  private function getFieldType(String $field, ReflectionClass $reflectedClass)
  {
    $docComment = $reflectedClass->getProperty($field)->getDocComment();
    $type = $this->getFieldTypeByFieldDocComment($docComment);

    if (!is_object($type)) {
      $fromClass = $this->getTypeByClassDocComment($field, $reflectedClass->getDocComment());

      if(is_object($fromClass)) {
          return $fromClass;
      }
    }

    return $type;
  }

  private function getFieldTypeByFieldDocComment(String $docComment)
  {
    $matches = [];

    if (preg_match("/\@var (\w+)(\[\])*/", $docComment, $matches) === 1) {

      if (count($matches) > 0) {
        $type = $matches[1];
        $isArray = isset($matches[2]);
        $fullyQualifiedName = $this->getFullyQualifiedName($type);

        if (class_exists($fullyQualifiedName)) {
          return (object) [
            'name' => $fullyQualifiedName,
            'array' => $isArray
          ];
        }
      }

      return $type;
    }
  }

  private function getTypeByClassDocComment(String $field, String $docComment)
  {
    $matches = [];

    if (preg_match_all("/\@property (\w+) (\\$\w+)/", $docComment, $matches) > 0) {
      $type = null;
      $isArray = false;

      foreach ($matches[2] as $index => $value) {
        if($value == $field) {
          $type = $matches[1][$index];
          $isArray = Str::endsWith($type, '[]');
          $type = str_replace('[]', '', $type);
        }
      }

      if ($type) {
        $fullyQualifiedName = $this->getFullyQualifiedName($type);

        if (class_exists($fullyQualifiedName)) {
          return (object) [
            'name' => $fullyQualifiedName,
            'array' => $isArray
          ];
        }
      }

      return $type;
    }
  }

  private function getFullyQualifiedName($className)
  {
    $useStatements = collect($this->getUseStatements());
    $aliasedStatement = $useStatements->where('alias', $className);

    if ($aliasedStatement) {
      return $aliasedStatement['namespace'];
    }

    $statement = $useStatements->first(function ($statement) use ($className) {
      return Str::endsWith($statement['namespace'], $className);
    });

    if ($statement) {
      return $statement['namespace'];
    }

    return null;
  }
}
email at dronov dot vg 03-Jun-2020 02:46
class User
{
    /**
     * @var string
     */
    public $name;
}

function getTypeNameFromAnnotation(string $className, string $propertyName): ?string
{
    $rp = new \ReflectionProperty($className, $propertyName);
    if (preg_match('/@var\s+([^\s]+)/', $rp->getDocComment(), $matches)) {
        return $matches[1];
    }

    return null;
}

echo getTypeNameFromAnnotation('User', 'name');

// string


Obtiene el valor

  • « ReflectionProperty::getType
  • ReflectionProperty::hasDefaultValue »
  • PHP Manual
  • ReflectionProperty
  • Obtiene el valor

ReflectionProperty::getValue

(PHP 5, PHP 7)

ReflectionProperty::getValue — Obtiene el valor

Descripción

public ReflectionProperty::getValue ( object $object = ? ) : mixed

Obtiene el valor de la propiedad.

Parámetros

object

Si la propiedad no fuera estática, se deberá adjuntar un objeto del que obtener la propiedad. Si se deseara obtener las propiedades predeterminadas sin proporcionar ningún objeto, utilice en su lugar ReflectionClass::getDefaultProperties().

Valores devueltos

Valor que contiene la propiedad.

Errores/Excepciones

Lanza ReflectionException si la propiedad no fuera accesible. Una propiedad protegida o privada puede hacerse accesible mediante ReflectionProperty::setAccessible().

Ejemplos

Ejemplo #1 Ejemplo de ReflectionProperty::getValue()

<?php
class Foo {
    public static $staticProperty = 'foobar';

    public $property = 'barfoo';
    protected $privateProperty = 'foofoo';
}

$reflectionClass = new ReflectionClass('Foo');

var_dump($reflectionClass->getProperty('staticProperty')->getValue());
var_dump($reflectionClass->getProperty('property')->getValue(new Foo));

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true);
var_dump($reflectionProperty->getValue(new Foo));
?>

El resultado del ejemplo sería:

string(6) "foobar"
string(6) "barfoo"
string(6) "foofoo"

Ver también

  • ReflectionProperty::setValue() - Establece el valor de la propiedad
  • ReflectionProperty::setAccessible() - Hace accesible una propiedad
  • ReflectionClass::getDefaultProperties() - Obtener propiedades predeterminadas
  • ReflectionClass::getStaticPropertyValue() - Obtiene el valor de una propiedad estática

User Contributed Notes

sergiy dot sokolenko at gmail dot com 28-Jun-2010 03:48
To allow protected and private properties to be accessed, you should use
ReflectionProperty::setAccessible(bool $accessible):

<?php
/** Class Foo with protected and private members */
class Foo {
    protected $bar = 'barrr!';
    private $baz = 'bazzz!';
}

$reflFoo = new ReflectionClass('Foo');
$reflBar = $reflFoo->getProperty('bar');
$reflBaz = $reflFoo->getProperty('baz');

// Set private and protected members accessible for getValue/setValue
$reflBar->setAccessible(true);
$reflBaz->setAccessible(true);

$foo = new Foo();
echo $reflBar->getValue($foo); // will output "barrr!"
echo $reflBaz->getValue($foo); // will output "bazzz!"

// You can also setValue
$reflBar->setValue($foo, "new value");
echo $reflBar->getValue($foo); // will output "new value"
?>


Checks if property has a default value declared

  • « ReflectionProperty::getValue
  • ReflectionProperty::hasType »
  • PHP Manual
  • ReflectionProperty
  • Checks if property has a default value declared

ReflectionProperty::hasDefaultValue

(PHP 8)

ReflectionProperty::hasDefaultValue — Checks if property has a default value declared

Descripción

public ReflectionProperty::hasDefaultValue ( ) : bool

Checks whether the property was declared with a default value, including an implicit null default value. Only returns false for typed properties without default value (or dynamic properties).

Parámetros

Esta función no tiene parámetros.

Valores devueltos

If the property has any default value (including null) true is returned; if the property is typed without a default value declared or is a dynamic property, false is returned.

Ejemplos

Ejemplo #1 ReflectionClass::hasDefaultValue() example

<?php
class Foo {
    public $bar;
    public ?int $baz;
    public ?int $foo = null;
    public int $boing;

    public function __construct()
    {
        $this->ping = '';
    }
}

$ro = new ReflectionObject(new Foo());
var_dump($ro->getProperty('bar')->hasDefaultValue());
var_dump($ro->getProperty('baz')->hasDefaultValue());
var_dump($ro->getProperty('foo')->hasDefaultValue());
var_dump($ro->getProperty('boing')->hasDefaultValue());
var_dump($ro->getProperty('ping')->hasDefaultValue()); // Dynamic property
var_dump($ro->getProperty('pong')->hasDefaultValue()); // Not defined property
?>

El resultado del ejemplo sería:

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

Fatal error: Uncaught ReflectionException: Property Foo::$pong does not exist in example.php

Ver también

  • ReflectionProperty::getDefaultValue() - Returns the default value declared for a property

User Contributed Notes

There are no user contributed notes for this page.


Checks if property has a type

  • « ReflectionProperty::hasDefaultValue
  • ReflectionProperty::isDefault »
  • PHP Manual
  • ReflectionProperty
  • Checks if property has a type

ReflectionProperty::hasType

(PHP 7 >= 7.4.0)

ReflectionProperty::hasType — Checks if property has a type

Descripción

public ReflectionProperty::hasType ( ) : bool

Checks if the property has a type associated with it.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true if a type is specified, false otherwise.

Ejemplos

Ejemplo #1 ReflectionProperty::hasType() example

<?php
class User
{
    public string $name;
}

$rp = new ReflectionProperty('User', 'name');
var_dump($rp->hasType());
?>

El resultado del ejemplo sería:

bool(true)

Ver también

  • ReflectionProperty::getType() - Gets a property's type
  • ReflectionProperty::isInitialized() - Checks whether a property is initialized

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si una propiedad es predeterminada

  • « ReflectionProperty::hasType
  • ReflectionProperty::isInitialized »
  • PHP Manual
  • ReflectionProperty
  • Comprueba si una propiedad es predeterminada

ReflectionProperty::isDefault

(PHP 5, PHP 7)

ReflectionProperty::isDefault — Comprueba si una propiedad es predeterminada

Descripción

public ReflectionProperty::isDefault ( ) : bool

Comprueba si la propiedad se declaró durante la compilación o si se declaró dinámicamente durante la ejecución.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si la propiedad se declaró en tiempo de compilación, o false si se creó en tiempo de ejecución.

Ejemplos

Ejemplo #1 Ejemplo de 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());
?>

El resultado del ejemplo sería:

bool(true)
bool(false)

Ver también

  • ReflectionProperty::getValue() - Obtiene el valor

User Contributed Notes

There are no user contributed notes for this page.


Checks whether a property is initialized

  • « ReflectionProperty::isDefault
  • ReflectionProperty::isPrivate »
  • PHP Manual
  • ReflectionProperty
  • Checks whether a property is initialized

ReflectionProperty::isInitialized

(PHP 7 >= 7.4.0)

ReflectionProperty::isInitialized — Checks whether a property is initialized

Descripción

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

Checks whether a property is initialized.

Parámetros

object

If the property is non-static an object must be provided to fetch the property from.

Valores devueltos

Returns false for typed properties prior to initialization, and for properties that have been explicitly unset(). For all other properties true will be returned.

Errores/Excepciones

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

Historial de cambios

Versión | Descripción
8.0.0 | object is nullable now.

Ejemplos

Ejemplo #1 ReflectionProperty::isInitialized() example

<?php
class User
{
    public string $name;
}

$rp = new ReflectionProperty('User', 'name');
$user = new User;
var_dump($rp->isInitialized($user));
$user->name = 'Nikita';
var_dump($rp->isInitialized($user));
?>

El resultado del ejemplo sería:

bool(false)
bool(true)

Ver también

  • ReflectionProperty::hasType() - Checks if property has a type

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si una propiedad es privada

  • « ReflectionProperty::isInitialized
  • ReflectionProperty::isProtected »
  • PHP Manual
  • ReflectionProperty
  • Comprueba si una propiedad es privada

ReflectionProperty::isPrivate

(PHP 5, PHP 7)

ReflectionProperty::isPrivate — Comprueba si una propiedad es privada

Descripción

public ReflectionProperty::isPrivate ( ) : bool

Comprueba si una propiedad es privada.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si la propiedad es privada, o false en caso contrario.

Ver también

  • ReflectionProperty::isPublic() - Comprueba si la propiedad es pública
  • ReflectionProperty::isProtected() - Comprueba si la propiedad es protegida
  • ReflectionProperty::isStatic() - Comprueba si la propiedad es estática

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si la propiedad es protegida

  • « ReflectionProperty::isPrivate
  • ReflectionProperty::isPublic »
  • PHP Manual
  • ReflectionProperty
  • Comprueba si la propiedad es protegida

ReflectionProperty::isProtected

(PHP 5, PHP 7)

ReflectionProperty::isProtected — Comprueba si la propiedad es protegida

Descripción

public ReflectionProperty::isProtected ( ) : bool

Comprueba si la propiedad es protegida.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si la propiedad está protegida, o false en caso contrario.

Ver también

  • ReflectionProperty::isPublic() - Comprueba si la propiedad es pública
  • ReflectionProperty::isPrivate() - Comprueba si una propiedad es privada
  • ReflectionProperty::isStatic() - Comprueba si la propiedad es estática

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


Comprueba si la propiedad es pública

  • « ReflectionProperty::isProtected
  • ReflectionProperty::isStatic »
  • PHP Manual
  • ReflectionProperty
  • Comprueba si la propiedad es pública

ReflectionProperty::isPublic

(PHP 5, PHP 7)

ReflectionProperty::isPublic — Comprueba si la propiedad es pública

Descripción

public ReflectionProperty::isPublic ( ) : bool

Comprueba si la propiedad es pública.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si la propiedad es pública, o false en caso contrario.

Ver también

  • ReflectionProperty::isProtected() - Comprueba si la propiedad es protegida
  • ReflectionProperty::isPrivate() - Comprueba si una propiedad es privada
  • ReflectionProperty::isStatic() - Comprueba si la propiedad es estática

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si la propiedad es estática

  • « ReflectionProperty::isPublic
  • ReflectionProperty::setAccessible »
  • PHP Manual
  • ReflectionProperty
  • Comprueba si la propiedad es estática

ReflectionProperty::isStatic

(PHP 5, PHP 7)

ReflectionProperty::isStatic — Comprueba si la propiedad es estática

Descripción

public ReflectionProperty::isStatic ( ) : bool

Comprueba si la propiedad es estática.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si la propiedad es estática, o false en caso contrario.

Ver también

  • ReflectionProperty::isPublic() - Comprueba si la propiedad es pública
  • ReflectionProperty::isProtected() - Comprueba si la propiedad es protegida
  • ReflectionProperty::isPrivate() - Comprueba si una propiedad es privada

User Contributed Notes

There are no user contributed notes for this page.


Hace accesible una propiedad

  • « ReflectionProperty::isStatic
  • ReflectionProperty::setValue »
  • PHP Manual
  • ReflectionProperty
  • Hace accesible una propiedad

ReflectionProperty::setAccessible

(PHP 5 >= 5.3.0, PHP 7)

ReflectionProperty::setAccessible — Hace accesible una propiedad

Descripción

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

Hace accesible una propiedad. Por ejemplo, podrá hacer que las propiedades protegidas o privadas sean accesibles.

Parámetros

accessible

true para permitir su acceso, o false.

Valores devueltos

No devuelve ningún valor.

Ver también

  • ReflectionProperty::isPrivate() - Comprueba si una propiedad es privada
  • ReflectionProperty::isProtected() - Comprueba si la propiedad es protegida

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


Establece el valor de la propiedad

  • « ReflectionProperty::setAccessible
  • ReflectionProperty::__toString »
  • PHP Manual
  • ReflectionProperty
  • Establece el valor de la propiedad

ReflectionProperty::setValue

(PHP 5, PHP 7)

ReflectionProperty::setValue — Establece el valor de la propiedad

Descripción

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

Establece (cambia) el valor de la propiedad.

Parámetros

object

Si la propiedad no fuera estática, se deberá proporcionar un objeto sobre el que se cambiará la propiedad. Si la propiedad fuera estática, se omite este parámetro y sólo será necesario completar el value.

value

El nuevo valor.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

Lanza ReflectionException si la propiedad no fuera accesible. Si la propiedad fuera de tipo protegido o privado, podrá hacerse accesible mediante ReflectionProperty::setAccessible().

Ejemplos

Ejemplo #1 Ejemplo de ReflectionProperty::setValue()

<?php
class Foo {
    public static $staticProperty;

    public $property;
    protected $privateProperty;
}

$reflectionClass = new ReflectionClass('Foo');

$reflectionClass->getProperty('staticProperty')->setValue('foo');
var_dump(Foo::$staticProperty);

$foo = new Foo;

$reflectionClass->getProperty('property')->setValue($foo, 'bar');
var_dump($foo->property);

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($foo, 'foobar');
var_dump($reflectionProperty->getValue($foo));
?>

El resultado del ejemplo sería:

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

Ver también

  • ReflectionProperty::getValue() - Obtiene el valor
  • ReflectionProperty::setAccessible() - Hace accesible una propiedad
  • ReflectionClass::setStaticPropertyValue() - Establece el valor de una propiedad estática

User Contributed Notes

me at ircmaxell dot om 22-Jun-2011 09:27
You can use ReflectionProperty::setValue to set the value on static properties as well as regular instance properties.  Simply pass null in place of the instance:

<?php
class Foo {
    protected static $bar = null;
    public static function sayBar() {
        echo self::$bar;
    }
}

$r = new ReflectionProperty('Foo', 'bar');
$r->setAccessible(true);
$r->setValue(null, 'foo');

Foo::sayBar(); // "foo"
?>


Convertir a texto

  • « ReflectionProperty::setValue
  • ReflectionType »
  • PHP Manual
  • ReflectionProperty
  • Convertir a texto

ReflectionProperty::__toString

(PHP 5, PHP 7)

ReflectionProperty::__toString — Convertir a texto

Descripción

public ReflectionProperty::__toString ( ) : string

Convierte a texto.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Ver también

  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


The ReflectionType class

(PHP 7)

Introducción

The ReflectionType class reports information about a function's return type.

Sinopsis de la Clase

abstract ReflectionType {
/* Métodos */
public allowsNull ( ) : bool
public __toString ( ) : string
}

Historial de cambios

Versión | Descripción
8.0.0 | ReflectionType has become abstract and ReflectionType::isBuiltin() has been moved to ReflectionNamedType::isBuiltin().

Tabla de contenidos

  • ReflectionType::allowsNull — Checks if null is allowed
  • ReflectionType::__toString — To string

User Contributed Notes

Ondej Mirtes 27-Sep-2020 06:53
Method ReflectionType::getName() does not exist. This may have been virtually true in the past but not anymore. It exists on ReflectionNamedType which used to be the only child class of ReflectionType. So you could have kind of relied on that.

But in PHP 8 there's also ReflectionUnionType which doesn't have the getName() method. So in order to support PHP 8, you need to support both ReflectionNamedType and ReflectionUnionType.
benjamin dot morel at gmail dot com 18-Sep-2020 09:03
Known subclasses:

- ReflectionNamedType
- ReflectionUnionType
roland at mxchange dot org 11-Mar-2020 09:13
I guess it is <?php ReflectionNamedType::getName(); ?> ?
1franck 28-Jan-2020 08:59
For those who stumble on notice about ReflectionType::__toString() beeing deprecated, use method ReflectionType::getName() instead which is not yet documented.


Checks if null is allowed

  • « ReflectionType
  • ReflectionType::__toString »
  • PHP Manual
  • ReflectionType
  • Checks if null is allowed

ReflectionType::allowsNull

(PHP 7)

ReflectionType::allowsNull — Checks if null is allowed

Descripción

public ReflectionType::allowsNull ( ) : bool

Checks whether the parameter allows null.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true if null is allowed, otherwise false

Ejemplos

Ejemplo #1 ReflectionType::allowsNull() example

<?php
function someFunction(string $param, StdClass $param2 = null) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->getType()->allowsNull());
var_dump($reflectionParams[1]->getType()->allowsNull());

El resultado del ejemplo sería:

bool(false)
bool(true)

Ver también

  • ReflectionNamedType::isBuiltin() - Checks if it is a built-in type
  • ReflectionType::__toString() - To string
  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

There are no user contributed notes for this page.


To string

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

ReflectionType::__toString

(PHP 7)

ReflectionType::__toString — To string

Advertencia

Esta función ha sido declarada OBSOLETA a partir de PHP 7.1.0. Su uso está totalmente desaconsejado.

Descripción

public ReflectionType::__toString ( ) : string

Gets the parameter type name.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the type of the parameter.

Ejemplos

Ejemplo #1 ReflectionType::__toString() example

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

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

echo $reflectionParam->getType();

El resultado del ejemplo sería algo similar a:

string

Historial de cambios

Versión | Descripción
7.1.0 | ReflectionType::__toString() has been deprecated.

Ver también

  • ReflectionNamedType::getName() - Get the text of the type hint
  • ReflectionNamedType::isBuiltin() - Checks if it is a built-in type
  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionUnionType::getTypes() - Returns the types included in the union type
  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

Anonymous 26-Jul-2020 04:32
Regarding this method's deprecation:

ReflectionType::__toString() was first deprecated in PHP 7.1.0 alpha1.
The deprecation notice was removed in PHP 7.1.0 RC3, before being reinstated in PHP 7.4.0 alpha1.

Starting with PHP 7.1.0 beta 3, ReflectionParameter::getType() & ReflectionFunctionAbstract::getReturnType() return instances of ReflectionNamedType instead of ReflectionType.
The ReflectionNamedType class inherits from ReflectionType but provides an additional getName() method which can be used to retrieve the type hint.

Lastly, PHP 8.0.0 alpha1 introduced the concept of union types (see https://wiki.php.net/rfc/union_types_v2). As a result, ReflectionParameter::getType() & ReflectionFunctionAbstract::getReturnType() will now return either instances of ReflectionNamedType or ReflectionUnionType depending on the type hint, both of which are descendants of ReflectionType.


The ReflectionUnionType class

(PHP 8)

Introducción

Sinopsis de la Clase

ReflectionUnionType extends ReflectionType {
/* Métodos */
public getTypes ( ) : array
/* Métodos heredados */
public ReflectionType::allowsNull ( ) : bool
public ReflectionType::__toString ( ) : string
}

Tabla de contenidos

  • 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

Descripción

public ReflectionUnionType::getTypes ( ) : array

Returns the reflections of types included in the union type.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

An array of ReflectionType objects.

Ejemplos

Ejemplo #1 ReflectionUnionType::getTypes() example

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

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

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

El resultado del ejemplo sería algo similar a:

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

Ver también

  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

There are no user contributed notes for this page.


The ReflectionGenerator class

(PHP 7)

Introducción

The ReflectionGenerator class reports information about a generator.

Sinopsis de la Clase

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

Tabla de contenidos

  • ReflectionGenerator::__construct — Constructs a ReflectionGenerator object
  • ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator
  • ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object
  • ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator
  • ReflectionGenerator::getFunction — Gets the function name of the generator
  • ReflectionGenerator::getThis — Gets the $this value of the generator
  • ReflectionGenerator::getTrace — Gets the trace of the executing generator

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ReflectionGenerator object

  • « ReflectionGenerator
  • ReflectionGenerator::getExecutingFile »
  • PHP Manual
  • ReflectionGenerator
  • Constructs a ReflectionGenerator object

ReflectionGenerator::__construct

(PHP 7)

ReflectionGenerator::__construct — Constructs a ReflectionGenerator object

Descripción

public ReflectionGenerator::__construct ( Generator $generator )

Constructs a ReflectionGenerator object.

Parámetros

generator

A generator object.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 ReflectionGenerator::__construct() example

<?php

function gen()
{
    yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

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

El resultado del ejemplo sería algo similar a:

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

Ver también

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the file name of the currently executing generator

  • « ReflectionGenerator::__construct
  • ReflectionGenerator::getExecutingGenerator »
  • PHP Manual
  • ReflectionGenerator
  • Gets the file name of the currently executing generator

ReflectionGenerator::getExecutingFile

(PHP 7)

ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator

Descripción

public ReflectionGenerator::getExecutingFile ( ) : string

Get the full path and file name of the currently executing generator.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the full path and file name of the currently executing generator.

Ejemplos

Ejemplo #1 ReflectionGenerator::getExecutingFile() example

<?php

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

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

$reflectionGen = new ReflectionGenerator($gen);

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

El resultado del ejemplo sería algo similar a:

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

Ver también

  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingGenerator() - Gets the executing Generator object

User Contributed Notes

There are no user contributed notes for this page.


Gets the executing Generator object

  • « ReflectionGenerator::getExecutingFile
  • ReflectionGenerator::getExecutingLine »
  • PHP Manual
  • ReflectionGenerator
  • Gets the executing Generator object

ReflectionGenerator::getExecutingGenerator

(PHP 7)

ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object

Descripción

public ReflectionGenerator::getExecutingGenerator ( ) : Generator

Get the executing Generator object

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the currently executing Generator object.

Ejemplos

Ejemplo #1 ReflectionGenerator::getExecutingGenerator() example

<?php

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

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

$reflectionGen = new ReflectionGenerator($gen);

$gen2 = $reflectionGen->getExecutingGenerator();

var_dump($gen2 === $gen);
var_dump($gen2->current());

El resultado del ejemplo sería algo similar a:

bool(true)
int(1);

Ver también

  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the currently executing line of the generator

  • « ReflectionGenerator::getExecutingGenerator
  • ReflectionGenerator::getFunction »
  • PHP Manual
  • ReflectionGenerator
  • Gets the currently executing line of the generator

ReflectionGenerator::getExecutingLine

(PHP 7)

ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator

Descripción

public ReflectionGenerator::getExecutingLine ( ) : int

Get the currently executing line number of the generator.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the line number of the currently executing statement in the generator.

Ejemplos

Ejemplo #1 ReflectionGenerator::getExecutingLine() example

<?php

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

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

$reflectionGen = new ReflectionGenerator($gen);

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

El resultado del ejemplo sería algo similar a:

Line: 7

Ver también

  • ReflectionGenerator::getExecutingGenerator() - Gets the executing Generator object
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the function name of the generator

  • « ReflectionGenerator::getExecutingLine
  • ReflectionGenerator::getThis »
  • PHP Manual
  • ReflectionGenerator
  • Gets the function name of the generator

ReflectionGenerator::getFunction

(PHP 7)

ReflectionGenerator::getFunction — Gets the function name of the generator

Descripción

public ReflectionGenerator::getFunction ( ) : ReflectionFunctionAbstract

Enables the function name of the generator to be obtained by returning a class derived from ReflectionFunctionAbstract.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns a ReflectionFunctionAbstract class. This will be ReflectionFunction for functions, or ReflectionMethod for methods.

Ejemplos

Ejemplo #1 ReflectionGenerator::getFunction() example

<?php

function gen()
{
    yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getFunction());

El resultado del ejemplo sería algo similar a:

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

Ver también

  • ReflectionGenerator::getThis() - Gets the $this value of the generator
  • ReflectionGenerator::getTrace() - Gets the trace of the executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the $this value of the generator

  • « ReflectionGenerator::getFunction
  • ReflectionGenerator::getTrace »
  • PHP Manual
  • ReflectionGenerator
  • Gets the $this value of the generator

ReflectionGenerator::getThis

(PHP 7)

ReflectionGenerator::getThis — Gets the $this value of the generator

Descripción

public ReflectionGenerator::getThis ( ) : object|null

Get the $this value that the generator has access to.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the $this value, or null if the generator was not created in a class context.

Ejemplos

Ejemplo #1 ReflectionGenerator::getThis() example

<?php

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

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

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getThis());

El resultado del ejemplo sería algo similar a:

object(GenExample)#3 (0) {
}

Ver también

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getTrace() - Gets the trace of the executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the trace of the executing generator

  • « ReflectionGenerator::getThis
  • ReflectionReference »
  • PHP Manual
  • ReflectionGenerator
  • Gets the trace of the executing generator

ReflectionGenerator::getTrace

(PHP 7)

ReflectionGenerator::getTrace — Gets the trace of the executing generator

Descripción

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

Get the trace of the currently executing generator.

Parámetros

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.

Valores devueltos

Returns the trace of the currently executing generator.

Ejemplos

Ejemplo #1 ReflectionGenerator::getTrace() example

<?php
function foo() {
    yield 1;
}

function bar()
{
    yield from foo();
}

function baz()
{
    yield from bar();
}

$gen = baz();
$gen->valid(); // start the generator

var_dump((new ReflectionGenerator($gen))->getTrace());

El resultado del ejemplo sería algo similar a:

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

Ver también

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getThis() - Gets the $this value of the generator

User Contributed Notes

There are no user contributed notes for this page.


The ReflectionReference class

(PHP 7 >= 7.4.0)

Introducción

The ReflectionReference class provides information about a reference.

Sinopsis de la Clase

final ReflectionReference {
/* Métodos */
public static fromArrayElement ( array $array , int|string $key ) : ReflectionReference|null
public getId ( ) : string
}

Tabla de contenidos

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


Create a ReflectionReference from an array element

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

ReflectionReference::fromArrayElement

(PHP 7 >= 7.4.0)

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

Descripción

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

Creates a ReflectionReference from an array element.

Parámetros

array

The array which contains the potential reference.

key

The key; either an int or a string.

Valores devueltos

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

Errores/Excepciones

If array is not an array, or key is not an int or string, 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
  • Reflector »
  • PHP Manual
  • ReflectionReference
  • Get unique ID of a reference

ReflectionReference::getId

(PHP 7 >= 7.4.0)

ReflectionReference::getId — Get unique ID of a reference

Descripción

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.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns a string of unspecified format.

Ejemplos

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

El resultado del ejemplo sería:

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


La interfaz Reflector

(PHP 5, PHP 7)

Introducción

Reflector es una interfaz que implementan todas las clases exportables de Reflection.

Sinopsis de la Clase

Reflector {
/* Métodos */
public static export ( ) : string
public __toString ( ) : string
}

Tabla de contenidos

  • Reflector::export — Exportar
  • Reflector::__toString — Convertir a String

User Contributed Notes

There are no user contributed notes for this page.


Exportar

  • « Reflector
  • Reflector::__toString »
  • PHP Manual
  • Reflector
  • Exportar

Reflector::export

(PHP 5, PHP 7)

Reflector::export — Exportar

Descripción

public static Reflector::export ( ) : string

Exporta.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Ver también

  • Reflection::__toString()

User Contributed Notes

There are no user contributed notes for this page.


Convertir a String

  • « Reflector::export
  • ReflectionException »
  • PHP Manual
  • Reflector
  • Convertir a String

Reflector::__toString

(PHP 5, PHP 7)

Reflector::__toString — Convertir a String

Descripción

public Reflector::__toString ( ) : string

Convierte a String.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Ver también

  • ReflectionProperty::export() - Exportar
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


La clase ReflectionException

(PHP 5, PHP 7)

Introducción

La clase ReflectionException.

Sinopsis de la Clase

ReflectionException extends Exception {
/* Propiedades */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Métodos heredados */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

User Contributed Notes

temirkhan.nasukhov 18-Apr-2019 11:50
Note that this exception is unchecked even if it is not based on RuntimeException.  Such error must lead to direct fixes in code and not in catch-handle of situation.

Also keep in mind that IDE (mine is Phpstorm 2018.3.4) inspections will highlight it for that reason so do not create phpdoc with throws for any Runtime exceptions.

<?php

/**
 * This way is wrong
 *
 * @throws \ReflectionException
 */
function createReflection()
{
    return new \ReflectionClass('invalid argument');
}

/**
 * This way is fine(I don't mean the code of course)
 */
function createReflection()
{
    return new \ReflectionClass('invalid argument');
}


Manejo de variables

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Funciones de manejo de variables
    • boolval — Obtener el valor booleano de una variable
    • debug_zval_dump — Vuelca a la salida una cadena con la representación de un valor interno de zend
    • doubleval — Alias de floatval
    • empty — Determina si una variable está vacía
    • floatval — Obtener el valor flotante de una variable
    • get_defined_vars — Devuelve una matriz con todas las variables definidas
    • get_resource_id — Returns an integer identifier for the given resource
    • get_resource_type — Devuelve el tipo de recurso
    • gettype — Obtener el tipo de una variable
    • intval — Obtiene el valor entero de una variable
    • is_array — Comprueba si una variable es un array
    • is_bool — Comprueba si una variable es de tipo booleano
    • is_callable — Verificar que los contenidos de una variable puedan ser llamados como una función
    • is_countable — Verifica que el contenido de una variable es un valor contable
    • is_double — Alias de is_float
    • is_float — Comprueba si el tipo de una variable es float
    • is_int — Comprueba si el tipo de una variable es integer
    • is_integer — Alias de is_int
    • is_iterable — Verifica que el contenido de una variable es un valor iterable
    • is_long — Alias de is_int
    • is_null — Comprueba si una variable es null
    • is_numeric — Comprueba si una variable es un número o un string numérico
    • is_object — Comprueba si una variable es un objeto
    • is_real — Alias de is_float
    • is_resource — Comprueba si una variable es un recurso
    • is_scalar — Comprueba si una variable es escalar
    • is_string — Comprueba si una variable es de tipo string
    • isset — Determina si una variable está definida y no es null
    • print_r — Imprime información legible para humanos sobre una variable
    • serialize — Genera una representación apta para el almacenamiento de un valor
    • settype — Establece el tipo de una variable
    • strval — Obtiene el valor de cadena de una variable
    • unserialize — Crea un valor PHP a partir de una representación almacenada
    • unset — Destruye una variable especificada
    • var_dump — Muestra información sobre una variable
    • var_export — Imprime o devuelve una representación string de una variable analizable

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Para obtener información sobre cómo funcionan las variables, vea la entrada Variables dentro de la sección Referencia del lenguaje del manual.

User Contributed Notes

There are no user contributed notes for this page.


Configuración en tiempo de ejecución

El comportamiento de estas funciones se ve afectado por la configuración de php.ini.

Opciones de configuración de variables
Nombre | Por defecto | Cambiable | Historial de cambios
unserialize_callback_func | null | PHP_INI_ALL |
Para más detalles y definiciones de los modos de PHP_INI_*, vea Dónde se puede realizar un ajuste de configuración.

He aquí una breve explicación de las directivas de configuración.

unserialize_callback_func string

La función de llamada de retorno especificada será llamada cuando unserialize() intente usar una clase no definida. Una advertencia aparecerá si la llamada de retorno especificada no está definida o si la función de llamada de retorno falla al intentar definir la clase faltante.

Vea también unserialize() y Autoloading Objects.

User Contributed Notes

There are no user contributed notes for this page.


Funciones de manejo de variables

Tabla de contenidos

  • boolval — Obtener el valor booleano de una variable
  • debug_zval_dump — Vuelca a la salida una cadena con la representación de un valor interno de zend
  • doubleval — Alias de floatval
  • empty — Determina si una variable está vacía
  • floatval — Obtener el valor flotante de una variable
  • get_defined_vars — Devuelve una matriz con todas las variables definidas
  • get_resource_id — Returns an integer identifier for the given resource
  • get_resource_type — Devuelve el tipo de recurso
  • gettype — Obtener el tipo de una variable
  • intval — Obtiene el valor entero de una variable
  • is_array — Comprueba si una variable es un array
  • is_bool — Comprueba si una variable es de tipo booleano
  • is_callable — Verificar que los contenidos de una variable puedan ser llamados como una función
  • is_countable — Verifica que el contenido de una variable es un valor contable
  • is_double — Alias de is_float
  • is_float — Comprueba si el tipo de una variable es float
  • is_int — Comprueba si el tipo de una variable es integer
  • is_integer — Alias de is_int
  • is_iterable — Verifica que el contenido de una variable es un valor iterable
  • is_long — Alias de is_int
  • is_null — Comprueba si una variable es null
  • is_numeric — Comprueba si una variable es un número o un string numérico
  • is_object — Comprueba si una variable es un objeto
  • is_real — Alias de is_float
  • is_resource — Comprueba si una variable es un recurso
  • is_scalar — Comprueba si una variable es escalar
  • is_string — Comprueba si una variable es de tipo string
  • isset — Determina si una variable está definida y no es null
  • print_r — Imprime información legible para humanos sobre una variable
  • serialize — Genera una representación apta para el almacenamiento de un valor
  • settype — Establece el tipo de una variable
  • strval — Obtiene el valor de cadena de una variable
  • unserialize — Crea un valor PHP a partir de una representación almacenada
  • unset — Destruye una variable especificada
  • var_dump — Muestra información sobre una variable
  • var_export — Imprime o devuelve una representación string de una variable analizable

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.


Obtener el valor booleano de una variable

  • « Funciones de manejo de variables
  • debug_zval_dump »
  • PHP Manual
  • Funciones de manejo de variables
  • Obtener el valor booleano de una variable

boolval

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

boolval — Obtener el valor booleano de una variable

Descripción

boolval ( mixed $var ) : bool

Devuelve el valor boolean de var.

Parámetros

var

El valor escalar a convertir a un boolean.

Valores devueltos

El valor boolean de var.

Ejemplos

Ejemplo #1 Ejemplos de 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";
?>

El resultado del ejemplo sería:

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

Ver también

  • floatval() - Obtener el valor flotante de una variable
  • intval() - Obtiene el valor entero de una variable
  • strval() - Obtiene el valor de cadena de una variable
  • settype() - Establece el tipo de una variable
  • is_bool() - Comprueba si una variable es de tipo booleano
  • Manipulación de tipos

User Contributed Notes

uasenior at gmail dot com 28-Jan-2020 08:02
<?

// Some way to print boolean value as string

$b = true;

echo ['false', 'true'][$b];

?>
raphael.satyago 20-Jan-2015 09:20
function is_true($val, $return_null=false){
    $boolval = ( is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : (bool) $val );
    return ( $boolval===null && !$return_null ? false : $boolval );
}

// Return Values:

is_true(new stdClass);      // true
is_true([1,2]);             // true
is_true([1]);               // true
is_true([0]);               // true
is_true(42);                // true
is_true(-42);               // true
is_true('true');            // true
is_true('on')               // true
is_true('off')              // false
is_true('yes')              // true
is_true('no')               // false
is_true('ja')               // false
is_true('nein')             // false
is_true('1');               // true
is_true(NULL);              // false
is_true(0);                 // false
is_true('false');           // false
is_true('string');          // false
is_true('0.0');             // false
is_true('4.2');             // false
is_true('0');               // false
is_true('');                // false
is_true([]);                // false
Matt M 09-Jan-2015 05:27
To anyone like me who came here looking for a way to turn any value into a 0/1 that will fit into a MySQL boolean (tinyint) field:

<?php
$tinyint = (int) filter_var($valToCheck, FILTER_VALIDATE_BOOLEAN);
?>

tinyint will be 0 (zero) for values like string "false", boolean false, int 0

tinyint will be 1 for values like string "true", boolean true, int 1

Useful if you are accepting data that might be from a language like Javascript that sends string "false" for a boolean false.
Babak Bandpey 13-May-2014 09:14
I believe that the double negation !! can perform the same task with the same result if your PHP is not up2date

var_dump(!!1, !!0, !!"test", !!"");

outputs:
boolean true

boolean false

boolean true

boolean false

May the life be good to you.
Anonymous 30-Dec-2013 05:12
A misspell in v2.0.
:-)

Hack v2.1

<?php

if( ! function_exists('boolval'))
{
    /**
     * Get the boolean value of a variable
     *
     * @param mixed The scalar value being converted to a boolean.
     * @return boolean The boolean value of var.
     */
    function boolval($var)
    {
        return !! $var;
    }
}

?>
info at lomalkin dot ru 15-Mar-2013 11:08
<?

// Hack for old php versions to use boolval()

if (!function_exists('boolval')) {
        function boolval($val) {
                return (bool) $val;
        }
}
?>


Vuelca a la salida una cadena con la representación de un valor interno de zend

  • « boolval
  • doubleval »
  • PHP Manual
  • Funciones de manejo de variables
  • Vuelca a la salida una cadena con la representación de un valor interno de zend

debug_zval_dump

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

debug_zval_dump — Vuelca a la salida una cadena con la representación de un valor interno de zend

Descripción

debug_zval_dump ( mixed $variable , mixed $... = ? ) : void

Volcar a la salida una cadena con la representación de un valor interno de zend.

Parámetros

variable

La variable a ser evaluada

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo debug_zval_dump()

<?php
$var1 = 'Hola Mundo';
$var2 = '';

$var2 =& $var1;

debug_zval_dump(&$var1);
?>

El resultado del ejemplo sería:

&string(11) "Hola Mundo" refcount(3)

Nota: Cuidado con refcount

El valor refcount devuelto por esta función no es evidente en determinadas circunstancias. Por ejemplo, un desarrollador puede esperar que el ejemplo anterior indique un refcount de 2. La tercera referencia se crea cuando se realiza la llamada a debug_zval_dump().

Este comportamiento se agrava aún más cuando una variable no se pasa a debug_zval_dump() por referencia. Para ilustrar esto, considere una versión ligeramente modificada del ejemplo anterior:

<?php
$var1 = 'Hola Mundo';
$var2 = '';

$var2 =& $var1;

debug_zval_dump($var1); // esta vez, no pasada por referencia
?>

El resultado del ejemplo sería:

string(11) "Hola Mundo" refcount(1)

Por qué refcount(1)? Porque una copia de $var1 es realizada, cuando se llama a la función.

Esta función se hace aún más confusa cuando una variable con un refcount de 1 es pasada (por copia/valor):

<?php
$var1 = 'Hola Mundo';

debug_zval_dump($var1);
?>

El resultado del ejemplo sería:

string(11) "Hola Mundo" refcount(2)

Un refcount de 2, aquí, no es extremedamente evidente. Especialmente teniendo en cuenta los ejemplos anteriores. ¿Qué ha ocurrido?

Cuando una variable tiene una sola referencia (como ocurría con $var1 antes de que fuera utilizada como un argumento para debug_zval_dump()), el motor de PHP optimiza la manera en que se pasa a una función. Internamente, PHP trata $var1 como una referencia (en esa refcount se incrementa para el ámbito de esa función), con la salvedad de que si la referencia pasa a ser aprobada por escrito y, una copia es realizada, pero sólo en el momento de la escritura. Esto se conoce como "copiar al escribir."

Así que, si debug_zval_dump() pasa a escribir en su único parámetro (y no lo hace), es entonces cuando se haría una copia. Hasta entonces, el parámetro sigue siendo una referencia, haciendo que refcount sea incrementado a 2 en el ámbito de la función llamada.

Ver también

  • var_dump() - Muestra información sobre una variable
  • debug_backtrace() - Genera un rastreo
  • Explicación de las Referencias
  • » Explicación de las Referencias (por 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
  • Funciones de manejo de variables
  • Alias de floatval

doubleval

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

doubleval — Alias de floatval()

Descripción

Esta función es un alias de: floatval().

User Contributed Notes

There are no user contributed notes for this page.


Determina si una variable está vacía

  • « doubleval
  • floatval »
  • PHP Manual
  • Funciones de manejo de variables
  • Determina si una variable está vacía

empty

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

empty — Determina si una variable está vacía

Descripción

empty ( mixed $var ) : bool

Determina si una variable es considerada vacía. Una variable se considera vacía si no existe o si su valor es igual a false. empty() no genera una advertencia si la variable no existe.

Parámetros

var

La variable que se comprueba

Nota:

Antes de PHP 5.5, empty() sólo soportaba variables; cualquier otra cosa provocaría un error del intérprete. En otras palabras, lo siguiente no funcionaría: empty(trim($nombre)). En su lugar, utilice trim($nombre) == false.

No se genera una advertencia si la variable no existe. Esto significa que empty() es esencialmente el equivalente conciso de !isset($var) || $var == false.

Valores devueltos

Devuelve false si var existe y tiene un valor no vacío, distinto de cero. De otro modo devuelve true.

Los siguientes valores son considerados como vacíos:

  • "" (una cadena vacía)
  • 0 (0 como un integer)
  • 0.0 (0 como un float)
  • "0" (0 como un string)
  • null
  • false
  • array() (un array vacío)

Historial de cambios

Versión | Descripción
5.5.0 | empty() ahora soporta expresiones, en vez de únicamente variables.
5.4.0 | Verificación de índices no numéricos de strings devuelve true.

Ejemplos

Ejemplo #1 Una simple comparación empty() / isset()

<?php
$var = 0;

// Se evalúa a true ya que $var está vacia
if (empty($var)) {
    echo '$var es o bien 0, vacía, o no se encuentra definida en absoluto';
}

// Se evalúa como true ya que $var está definida
if (isset($var)) {
    echo '$var está definida a pesar que está vacía';
}
?>

Ejemplo #2 empty() en índices de string

PHP 5.4 cambia como empty() se comporta cuando se pasan índices de string.

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

Salida del ejemplo anterior en PHP 5.3:

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

Salida del ejemplo anterior en PHP 5.4:

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

Notas

Nota: Puesto que esto es una construcción del lenguaje y no una función, no puede ser llamada usando funciones variables.

Nota:

Cuando se utiliza empty() sobre las propiedades de objetos inaccesibles, el método sobrecargado __isset() será llamado, si se declara.

Ver también

  • isset() - Determina si una variable está definida y no es null
  • __isset()
  • unset() - Destruye una variable especificada
  • array_key_exists() - Verifica si el índice o clave dada existe en el array
  • count() - Cuenta todos los elementos de un array o algo de un objeto
  • strlen() - Obtiene la longitud de un string
  • Las tablas de comparación de tipos

User Contributed Notes

pm1625637 at gmail dot com 05-Dec-2019 02:11
Be careful about this  :

<?php
$del = '';
echo empty($del);
?>

Output : 1
markmanning at gmail dot com 23-Mar-2019 09:15
I normally count() an array, so I wanted to see how empty() would stack up.

<?php
    $test = array();
    $test2 = array();
    for ($x = 0; $x < 1000; $x++)  $test[] = $x;

    $ts = microtime(true);
    for ($x = 0; $x < 100000000; $x++)
    {
        if (count($test))
        {
        }
    }

    echo "Time taken:  " . (microtime(true) - $ts) . " sec\n";
?>

For 100,000,000 comparisons, here are the results against PHP 7.2.16 on my hardware:

count($test):  2.697 sec
count($test2):  2.596 sec
$test === array():  2.579 sec
$test2 === array():  2.552 sec
empty($test):  3.085 sec
empty($test2):  3.113 sec

In short, it doesn't matter what method is used although empty() is actually just ever so slightly slower despite it being a language construct.  YMMV.
fahimcseiiuc at gmail dot com 25-Feb-2019 10:02
<?php

    /*"" (an empty string)
      0 (0 as an integer)
      0.0 (0 as a float)
      "0" (0 as a string)
      NULL
      FALSE
      array() (an empty array)*/

$anEmptyString = "";
empty($anEmptyString);
if(empty($anEmptyString) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";         //line break

$anIntegerNumber = 0;
empty($anIntegerNumber);
if(empty($anIntegerNumber) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";         //line break

$aFloatNumber = 0.0;
empty($aFloatNumber);
if(empty($aFloatNumber) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";       //line break

$aZeroValuedString = "0";
empty($aZeroValuedString);
if(empty($aZeroValuedString) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";        //line break

$aNULL = NULL;
empty($aNULL);
if(empty($aNULL) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";        //line break

$aBooleanFALSE = FALSE;
empty($aBooleanFALSE);
if(empty($aBooleanFALSE) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";        //line break

$anEmptyArray = array();
empty($anEmptyArray);
if(empty($anEmptyArray) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";       //line break

?>
GazetteSDF 21-Sep-2018 09:02
For the verification of a form, to "block" entries such as a simple space or other, I thought of this combination:

function isEmpty($string){
    $val = preg_replace('#[^A-Za-z0-9]+#', '', $string) ;
    $val = trim($string, '');
    return ($string=='') ;
}

This protects entries like: ' ' ,'  -  ', '. - +', ... On entries like name, profession, ... it's helpful
aditycse at gmail dot com 10-Nov-2017 03:58
<?php

/**
 * Used for checking empty objects/array
 * @uses How to check empty objects and array in php code
 * @author Aditya Mehrotra<aditycse@gmail.com>
 */

/**
 * Empty class
 */
class EmptyClass {

}

$obj = new stdClass();
//or any other class empty object
$emptyClassObj = new EmptyClass();
$array = array();

if (empty($array)) {
    echo 'array is empty'; //expected result
} else {
    echo 'array is not empty'; //unexpected result
}
echo "<br>";

if (empty($obj)) {
    echo 'object is empty'; //expected result
} else {
    echo 'object is not empty'; //unexpected result
}
echo "<br>";

if (empty($emptyClassObj)) {
    echo 'EmptyClass is empty'; //expected result
} else {
    echo 'EmptyClass is not empty'; //unexpected result
}
echo "<br>";

//Result SET 1
//array is empty      => expected result
//object is not empty => ouch what happened
//EmptyClass is not empty => ouch what happened

/**
 * So what we do for checking empty object
 * @solution use any known property or check property count
 * Or you can use below method
 * Count function will not return 0 in empty object
 */

//Below line print "Object count:1"
echo 'Object count:' . count($obj);

echo "<br>";

/**
 * This function is used to get object item counts
 * @function getCount
 * @access public
 * @param object|array $var
 * @return integer
 */
function getCount($var) {
    $count = 0;
    if (is_array($var) || is_object($var)) {
        foreach ($var as $value) {
            $count++;
        }
    }
    unset($value);
    return $count;
}

//Running code again with new logic
if (getCount($array) === 0) {
    echo 'array is empty'; //expected result
} else {
    echo 'array is not empty'; //unexpected result
}
echo "<br>";

if (getCount($obj) === 0) {
    echo 'object is empty'; //expected result
} else {
    echo 'object is not empty'; //unexpected result
}

echo "<br>";

if (getCount($emptyClassObj) === 0) {
    echo 'EmptyClass is empty'; //expected result
} else {
    echo 'EmptyClass is not empty'; //unexpected result
}

//Result SET 2
//array is empty    => expected result  ##everything is all right
//object is empty   => expected result  ##everything is all right
//EmptyClass is empty   => expected result  ##everything is all right
xzero at elite7hackers dot net 13-Jul-2017 11:36
Note that empty() will return false on null byte. Eg.

<?php
// Save to variable, so it works on older PHP versions
$null_byte = chr(0); // === \0

var_dump(
    empty(null),
    empty($null_byte)
);
/**
 * Results:
 *
 * bool(true)
 * bool(false)
 */
wranvaud at gmail dot com 02-Jul-2017 06:22
Note that if your variable only has an "end of line" (aka carriage return), PHP_EOL it is not considered as empty. Since end of lines are not always easy to spot this can be confusing.
Claudio Galdiolo 25-Mar-2017 12:20
Warning: an "empty" object is NOT considered to be empty
<?php
$var = new stdClass(); // "empty" object
var_dump(empty($var)); // bool(false)
?>

I don't know if there is a standard way to test for "empty" objects, I personally use array casting:
<?php
$var = new stdClass(); // "empty" object
$var = (array) $var; // cast to empty array
var_dump(empty($var)); // bool(true)
?>
mcfogw at gmail dot com 08-May-2016 02:40
I'm comparing behavior of `!` and `empty()`, find an undocumented behavior here.

just like cast-to-boolean, `empty()` cares about if SimpleXML object is made from emty tags.

`empty(simplexml_load_string('<root />'))` is TRUE

this behavior begins from php 5.1.0~7, in 5.0.x that's FALSE

proof here => https://3v4l.org/74Tc4
Javier Alfonso 11-Mar-2016 01:05
If you test an element of an array (like $_POST['key]), it test if the key doesn't exist or if it exist if its value is empty and never emit a warning.

For who don't want to test what happen if passed an array element here is my test and result.

<?php
$a = array();
$b = array('key');
$c = array('key' => false);
$d = array('key' => 'La verdad nos hace libres');

echo (empty($a['key'])?'A empty':'A not empty'), ' - ', (empty($b['key'])?'B empty':'B not empty'), ' - ', (empty($c['key'])?'C empty':'C not empty'), ' - ', (empty($d['key'])?'D empty':'D not empty');
?>

And the result is:

    A empty - B empty - C empty - D not empty
your dot brother dot t at hotmail dot com 25-Dec-2014 09:38
(experienced in PHP 5.6.3) The `empty()` can't evaluate `__get()` results explicitly, so the `empty()` statement bellow always renders true
<?php
class Juice extends Liquid{
   protected $apple;
   protected $orange;
   public function __get($name) {
      return $this->$name;
   }
   public function __construct($apple, $orange) {
      $this->apple = $apple;
      $this->orange = $orange;
   }
}

class Glass {
   protected $liquid;
   public function __get($name) {
      return $name == "liquid" ? $this->liquid : false;
   }
   public function __construct() {
      $this->juice = new Juice(3, 5);
   }
}

$glass = new Glass();
var_dump(empty($this->liquid->apple));

/**
 * The output is:
 * bool(true)
 */
?>

The correct way is to force the evaluation of `__get()` first, by using extra braces around implicit statements like this:
<?php
var_dump(empty(($this->liquid->apple)));

/**
 * The output is:
 * bool(false)
 */
?>

So if you are using packages that utilize object oriented designs and magic methods like `__get()`, it's a good practice to always use double braces for `empty()` calls.
chrisdmiddleton at gmail dot com 09-Sep-2014 08:37
If you want to use empty() to evaluate an expression (not a variable), and you don't have PHP 5.5+, you can do it by wrapping the call to empty in a function, like so:
<?php
function is_empty($var) {

    return empty($var);

}
?>
Then you can do something like
<?php
if(is_empty(NULL)) {
 /* ... */
}
?>
without issue, since the local variable $var is being tested rather than the expression in the function call itself.
Nanhe Kumar 31-Jan-2014 10:17
<?php
/**
* @author :  Nanhe Kumar <nanhe.kumar@gmail.com>
* List of all empty values
**/

$testCase = array(
    1 => '',
    2 => "",
    3 => null,
    4 => array(),
    5 => FALSE,
    6 => NULL,
    7=>'0',
    8=>0,

);

foreach ($testCase as $k => $v) {
    if (empty($v)) {
        echo "<br> $k=>$v is empty";
    }
}
/**
Output
1=> is empty
2=> is empty
3=> is empty
4=>Array is empty
5=> is empty
6=> is empty
7=>0 is empty
8=>0 is empty
**/
?>
martin dot aarhof at gmail dot com 15-Mar-2012 08:38
<?php
$str = '            ';
var_dump(empty($str)); // boolean false
?>

So remember to trim your strings first!

<?php
$str = '        ';
$str = trim($str);
var_dump(empty($str)); // boolean true
?>
qeremy 07-Mar-2012 03:33
Simple solution for: "Fatal error: Can't use function return value in write context in ..."

<?php
function _empty($val) { return empty($val); }
?>
chris dot wisefool at gmail dot com 09-Sep-2011 12:44
Note that checking the existence of a subkey of an array when that subkey does not exist but the parent does and is a string will return false for empty.

i.e.

<?php
$params = array('search'=>'1');
empty($params['search']['filter']); # returns false
?>

This is correct, per the documentation (http://php.net/manual/en/language.types.string.php); quite a bit down the page is the Warning: "Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer." ) I didn't receive a warning but perhaps that's correct too...depends on whether the string -> integer conversion is considered "illegal": "Illegal offset type emits E_NOTICE."

(i.e. since $params['search'] is a string, the 'filter' subscript is converted to 0, so the test becomes empty($params['search'][0]), which is obviously false), but it tripped me up enough to mistakenly file a bug report (which I've since closed).
steven at nevvix dot com 02-May-2011 09:16
When you need to accept these as valid, non-empty values:
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)

<?php
function is_blank($value) {
    return empty($value) && !is_numeric($value);
}
?>

This is similar to Rails' blank? method.
phpsort 21-Jan-2011 11:13
I'm summarising a few points on empty() with inaccessible properties, in the hope of saving others a bit of time. Using PHP 5.3.2.
<?php
class MyClass {
    private $foo = 'foo';
}
$myClass = new MyClass;
echo $myClass->foo;
?>
As expected, this gives "Fatal error: Cannot access private property MyClass::$foo".
But substitute the line
if (empty($myClass->foo)) echo 'foo is empty'; else echo 'foo is not empty';
and we get the misleading result "foo is empty".
There is NO ERROR OR WARNING, so this is a real gotcha. Your code will just go wrong silently, and I would say it amounts to a bug.
If you add two magic functions to the class:
public function __get($var) { return $this->$var; }
public function __isset($var) { return isset($this->$var); }
then we get the expected result. You need both functions.
For empty($myClass->foo), I believe PHP calls __isset, and if that is true returns the result of empty on the result of __get. (Some earlier posts wrongly suggest PHP just returns the negation of __isset).
BUT …
See the earlier post by php at lanar dot com. I confirm those results, and if you extend the test with isset($x->a->b->c) it appears that __isset is only called for the last property in the chain. Arguably another bug. empty() behaves in the same way. So things are not as clear as we might hope.
See also the note on empty() at
http://uk3.php.net/manual/en/language.oop5.overloading.php
Clear as mud!
e dot klerks at i-bytes dot nl 08-Nov-2010 06:16
To make an empty function, which only accepts arrays, one can use type-hinting:

<?php
// emptyArray :: [a] -> Bool

function emptyArray(array $xs){
 return empty($xs);
}
?>

Type hinting is a good thing to use in your code, because it makes it more easy to reason about your code. Besides that, it automatically documents the code.
rodolphe dot bodeau at free dot fr 25-Oct-2010 06:37
Be careful, if "0" (zero as a string), 0 (zero as an integer) and -0 (minus zero as an integer) return true, "-0" (minus zero as a string (yes, I already had some customers that wrote -0 into a form field)) returns false. You need to cast your variable before testing it with the empty() function :

<?php
$var = "-0";
echo empty($var);  // returns false
$var = (int) $var; // casts $var as an integer
echo empty($vat);  // returns true
?>
ehsmeng 21-Sep-2010 05:25
I can't use empty() in all situations because '0' is usually not considered empty to me. I did a quick benchmark over the most common ways of testing it. '' == var suffers from '' == 0 is true so that's just there for curiosity.

<?php
    $microtimeref = microtime(true);
    $a = 0;
    $b = 'asd';
    for ($i = 0; $i < 5000000; $i++)
    {
        if (0 == mb_strlen ($b))
        {
            $a++;
        }
    }
    echo "Total time 0 == mb_strlen(var): <b>" . round(microtime(true) - $microtimeref,3) . 's</b><br />';
?>

The results:

Total time 0 == mb_strlen(var): 3.141s
Total time 0 === strlen(var): 2.904s
Total time 0 == strlen(var): 2.878s
Total time '' == var: 1.774s
Total time '' === var: 1.706s
Total time empty(var): 1.496s

Thus '' === var will be my zero length string test.
marko dot crni at gmail dot com 16-Sep-2010 11:06
Calling non existing object property, empty($object->prop), will trigger __isset(), the same way as isset($object->prop) does, but there is one difference. If __isset() returns TRUE, another call to __get() will be made and actual return value will be result of empty() and result of __get().
aidan1103 at yahoo dot com 26-Mar-2010 10:11
empty() should not necessarily return the negation of the __isset() magic function result, if you set a data member to 0, isset() should return true and empty should also return true.  A simpler implementation of the __isset magic function would be:

public function __isset($key) {
  return isset($this->{$key});
}

I don't understand why this isn't included in stdClass and inherited by default.
Janci 24-Aug-2009 08:57
Please note that results of empty() when called on non-existing / non-public variables of a class are a bit confusing if using magic method __get (as previously mentioned by nahpeps at gmx dot de). Consider this example:

<?php
class Registry
{
    protected $_items = array();
    public function __set($key, $value)
    {
        $this->_items[$key] = $value;
    }
    public function __get($key)
    {
        if (isset($this->_items[$key])) {
            return $this->_items[$key];
        } else {
            return null;
        }
    }
}

$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';

var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // true, .. say what?
$tmp = $registry->notEmpty;
var_dump(empty($tmp)); // false as expected
?>

The result for empty($registry->notEmpty) is a bit unexpeced as the value is obviously set and non-empty. This is due to the fact that the empty() function uses __isset() magic functin in these cases. Although it's noted in the documentation above, I think it's worth mentioning in more detail as the behaviour is not straightforward. In order to achieve desired (expexted?) results, you need to add  __isset() magic function to your class:

<?php
class Registry
{
    protected $_items = array();
    public function __set($key, $value)
    {
        $this->_items[$key] = $value;
    }
    public function __get($key)
    {
        if (isset($this->_items[$key])) {
            return $this->_items[$key];
        } else {
            return null;
        }
    }
    public function __isset($key)
    {
        if (isset($this->_items[$key])) {
            return (false === empty($this->_items[$key]));
        } else {
            return null;
        }
    }
}

$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';

var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // false, finally!
?>

It actually seems that empty() is returning negation of the __isset() magic function result, hence the negation of the empty() result in the __isset() function above.
denobasis-bozic et yahoo.com 18-Jul-2009 04:54
test if all multiarray's are empty

<?php
function is_multiArrayEmpty($multiarray) {
    if(is_array($multiarray) and !empty($multiarray)){
        $tmp = array_shift($multiarray);
            if(!is_multiArrayEmpty($multiarray) or !is_multiArrayEmpty($tmp)){
                return false;
            }
            return true;
    }
    if(empty($multiarray)){
        return true;
    }
    return false;
}

$testCase = array (
0 => '',
1 => "",
2 => null,
3 => array(),
4 => array(array()),
5 => array(array(array(array(array())))),
6 => array(array(), array(), array(), array(), array()),
7 => array(array(array(), array()), array(array(array(array(array(array(), array())))))),
8 => array(null),
9 => 'not empty',
10 => "not empty",
11 => array(array("not empty")),
12 => array(array(),array("not empty"),array(array()))
);

foreach ($testCase as $key => $case ) {
    echo "$key is_multiArrayEmpty= ".is_multiArrayEmpty($case)."<br>";
}
?>

OUTPUT:
========

0 is_multiArrayEmpty= 1
1 is_multiArrayEmpty= 1
2 is_multiArrayEmpty= 1
3 is_multiArrayEmpty= 1
4 is_multiArrayEmpty= 1
5 is_multiArrayEmpty= 1
6 is_multiArrayEmpty= 1
7 is_multiArrayEmpty= 1
8 is_multiArrayEmpty= 1
9 is_multiArrayEmpty=
10 is_multiArrayEmpty=
11 is_multiArrayEmpty=
12 is_multiArrayEmpty=
mlibazisi mabandla 28-May-2009 02:47
in cases when "0" is not intended to be empty, here is a simple function to safely test for an empty string (or mixed variable):

<?php
function _empty($string){
     $string = trim($string);
     if(!is_numeric($string)) return empty($string);
     return FALSE;
}
?>
thomas at thomasnoest dot nl 28-Nov-2008 01:54
Note on the selfmade empty function below:

function_exists() returns false on language constructs and empty is a language construct.
Anonymous 20-Aug-2008 02:41
To add on to what anon said, what's happening in john_jian's example seems unusual because we don't see the implicit typecasting going on behind the scenes.  What's really happening is:

$a = '';
$b = 0;
$c = '0';

(int)$a == $b -> true, because any string that's not a number gets converted to 0
$b==(int)$c -> true, because the int in the string gets converted
and
$a==$c -> false, because they're being compared as strings, rather than integers.  (int)$a==(int)$c should return true, however.

Note: I don't remember if PHP even *has* typecasting, much less if this is the correct syntax.  I'm just using something for the sake of examples.
tom at tomwardrop dot com 22-May-2008 05:01
In reply to "admin at ninthcircuit dot info",

Using str_replace is unnecessary. I would encourage the use of trim which would most likely be faster (haven't tested) and easier. Trim also takes care of other white space like line breaks and tabs. Actually, in most of the applications I code, I use a multi-dimensional array map function with trim on the Super Globals such as $_POST, $_GET and $_COOKIE as so far, there hasn't been an instance where I would want any user input to begin or end with whitespace. The good thing about doing this is that you never have to worry about 'trimming' your input which makes your code easier and more reliable (incase you forget to trim some input).
Greg Hartwig 02-May-2008 02:55
David from CodeXplorer:
>> The ONLY reason to use empty() is for code readability. It is the same as an IF/ELSE check.
>> So, don't bother using EMPTY in the real world.

This is NOT true.  empty() will not generate warnings if you're testing against an undefined variable as a simple boolean check will.  On production systems, warnings are usually shut off, but they are often active on development systems.

You could test a flag with
   <?php if ($flagvar)  ... ?>
but this can generate a warning if $flagvar is not set.

Instead of
   <?php if (isset($flagvar) && $flagvar)  ... ?>
you can simply use
   <?php if (!empty($flagvar))  ... ?>

for easy readability without warnings.
EllisGL 04-Oct-2007 02:48
Here's what I do for the zero issue issue:
if($val == '' && $val !== 0 && $val !== '0')
rkulla2 at gmail dot com 05-Sep-2007 03:57
Since I didn't like how empty() considers 0 and "0" to be empty (which can easily lead to bugs in your code), and since it doesn't deal with whitespace, i created the following function:

<?php
function check_not_empty($s, $include_whitespace = false)
{
    if ($include_whitespace) {
        // make it so strings containing white space are treated as empty too
        $s = trim($s);
    }
    return (isset($s) && strlen($s)); // var is set and not an empty string ''
}
?>

Instead of saying if (!empty($var)) { // it's not empty } you can just say if (check_not_empty($var)) { // it's not empty }.

If you want strings that only contain whitespace (such as tabs or spaces) to be treated as empty then do: check_not_empty($var, 1)

If you want to check if a string IS empty then do: !check_not_empty($var).

So, whenever you want to check if a form field both exists and contains a value just do: if (check_not_empty($_POST['foo'], 1))

no need to do if (isset() && !empty()) anymore =]
jmarbas at hotmail dot com 01-Jul-2005 09:10
empty($var) will return TRUE if $var is empty (according to the definition of 'empty' above) AND if $var is not set.

I know that the statement in the "Return Values" section of the manual already says this in reverse:

"Returns FALSE if var has a non-empty and non-zero value."

but I was like "Why is this thing returning TRUE for unset variables???"... oh i see now... Its supposed to return TRUE for unset variables!!!

<?php
  ini_set('error_reporting',E_ALL);
  ini_set('display_errors','1');
  empty($var);
?>
paul at worldwithoutwalls dot co dot uk 22-May-2004 10:09
Note the exceptions when it comes to decimal numbers:

<?php
$a = 0.00;
$b = '0.00';
echo (empty($a)? "empty": "not empty"); //result empty
echo (empty($b)? "empty": "not empty"); //result not empty
//BUT...
$c = intval($b);
echo (empty($c)? "empty": "not empty"); //result empty
?>

For those of you using MySQL, if you have a table with a column of decimal type, when you do a SELECT, your data will be returned as a string, so you'll need to do apply intval() before testing for empty.

e.g.
TABLE t has columns id MEDIUMINT and d DECIMAL(4,2)
and contains 1 row where id=1, d=0.00
<?php
$q = "SELECT * FROM t";
$res = mysql_query($q);
$row = mysql_fetch_assoc($res);
echo (empty($row['d'])? "empty": "not empty"); //result not empty
?>


Obtener el valor flotante de una variable

  • « empty
  • get_defined_vars »
  • PHP Manual
  • Funciones de manejo de variables
  • Obtener el valor flotante de una variable

floatval

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

floatval — Obtener el valor flotante de una variable

Descripción

floatval ( mixed $var ) : float

Obtiene el valor valor float de var.

Parámetros

var

Puede ser cualquier tipo escalar. No se puede utilizar floatval() en objetos, si es usado emitirá un error de nivel E_NOTICE y devolverá 1.

Valores devueltos

El valor flotante de la variable dada. Arrays vacios devolverán 0, arrays no vacios devolverán 1.

Las cadenas generalmente devolverán 0, aunque esto depende de los primeros caracteres de la cadena. Las reglas comunes de conversión a flotante se aplican en cualquier caso.

Ejemplos

Ejemplo #1 Ejemplo de floatval()

<?php
 $var = '122.34343El';
 $valor_float_de_var = floatval($var);
 echo $valor_float_de_var; // 122.34343
 ?>

Ejemplo #2 Ejemplo de floatval() con caracteres a la izquierda no numéricos

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

Ver también

  • boolval() - Obtener el valor booleano de una variable
  • intval() - Obtiene el valor entero de una variable
  • strval() - Obtiene el valor de cadena de una variable
  • settype() - Establece el tipo de una variable
  • Conversión de Tipos

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.


Devuelve una matriz con todas las variables definidas

  • « floatval
  • get_resource_id »
  • PHP Manual
  • Funciones de manejo de variables
  • Devuelve una matriz con todas las variables definidas

get_defined_vars

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

get_defined_vars — Devuelve una matriz con todas las variables definidas

Descripción

get_defined_vars ( ) : array

Esta función devuelve una matriz multidimensional que contiene una lista de todas las variables definidas, ya sean variables de entorno, de servidor o definidas por el usuario, en el ámbito que get_defined_vars() es llamado.

Valores devueltos

Una matriz multidimensional con todas las variables.

Ejemplos

Ejemplo #1 Ejemplo de get_defined_vars()

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

$arr = get_defined_vars();

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

/* imprime ruta de acceso al intérprete de PHP (si es usado como CGI)
 * e.g. /usr/local/bin/php */
echo $arr["_"];

// imprime los parámetros de la linea de comandos, si existen
print_r($arr["argv"]);

// imprime todas las variables del servidor
print_r($arr["_SERVER"]);

// imprime todas las claves disponibles para las matrices de variables
print_r(array_keys(get_defined_vars()));
?>

Ver también

  • isset() - Determina si una variable está definida y no es null
  • get_defined_functions() - Devuelve un array de todas las funciones definidas
  • get_defined_constants() - Devuelve un array asociativo con los nombres de todas las constantes y sus valores

User Contributed Notes

antonfedonyuk at gmail dot com 05-Feb-2021 09:29
NOTE: when you call code by eval() PHP append self vars to result, they have "__" prefix ("__source_code" and "__bootstrap_file" in PHP 7.3).

Fix:
<?php
function filter_eval_vars(array $vars): array
{
    foreach ($vars as $key => $value) {
         if ($key[0] === '_' && $key[1] === '_') {
              unset($vars[$key]);
         }
    }
    return $vars;
}

?>
npelov at croler dot net 02-Feb-2021 12:35
get_defined_vars() returns all variables - locally defined vars and global vars (well actually only super globals). If you need local vars only  - for example you need to get variables from a file - let's say config.php and you don't want a missing value to be replaced with a global defined somewhere else.

<?php

  /**
   * Filters out global vars from get_defined_vars() in order to get local vars only
   * @param array $localVars pass get_defined_vars() here
   *
   * @return array local vars only
   */
  function removeGlobals(array $localVars) {
    return array_diff_key($localVars, $GLOBALS);
  }

  define('CONFIG_FILE_PATH', '/path/to/config.php');
  function readConfig() {
    require CONFIG_FILE_PATH;
    $config = removeGlobals(get_defined_vars());
    return $config;
  }

?>
Joey 11-Jun-2018 07:22
I posted here before about "this" being in get_defined_vars.

It turns out it's not always there but in certain cases it will inexplicably appear.

    php -r '
    class Test {
        public function a() {var_dump(array_keys(get_defined_vars()));$a = 123;}
        public function b() {var_dump(array_keys(get_defined_vars()));$this;}
    }
    $t = new Test();
    $t->a();
    $t->b();
    '

    array()
    array('this')

This does not happen in PHP 7.2 but will happen in PHP 5.6.
Joey 24-Apr-2018 08:30
Some comments here point out that this function wont return references. It does however return names and names are "references".

I would not recommend the suggestions here that convert it to references.

Instead...

    public function x($a, $b, $c) {
        foreach(array_keys(get_defined_vars()) as $key)
            if($key !== 'this')
                $this->y(${$key});
    }

    public function y(&$input) {
        $input++;
    }

Instead of ${} you can also use $$.

I have done some whacky things in my time to make extremely generic code but I've never had to do anything like the above. It might not even work (but should since it's no different to $a[$key]).

You could also do $$key++ but I've never seen code like that which wasn't horrifically bad (using dynamic where dynamic isn't beneficial).

If you're doing something like that then give it additional scrutiny.
Joey 24-Apr-2018 08:20
I occasionally use this as a hack to convert arguments to an array where terseness is needed (dealing with legacy code, etc).

However in an object context it'll also pull in $this.

Make sure to unset it. If you map it to properties or an array then setting the key this wont be an error.

I recommend using a wrapper function that strips this from the result.
istiaquealamjoy at gmail dot com 23-May-2017 05:37
for all those who don't know how to us this function. copy and run this code in your computer  .

note: you need to know what superglobals are.....

<?php

$A = 5  ;
$B = 10 ;
$C = 15 ;
$D = 20 ;

$F = get_defined_vars($A);

var_dump($F);  //don't use echo. it will show error

?>

Result : will show all superglobals status along with your defined
variables along with its values
sergeyzuzic at mail dot ru 14-Nov-2015 10:35
dirty code sample:

print_r(compact(array_keys(get_defined_vars())));
mail at mkharitonov dot net 01-Jun-2014 07:14
Reference variables are returned by reference (tested on PHP 5.5.11):
<?php
$a = null;
$b = &$a;
get_defined_vars()['b'] = 4;
var_dump($b); // int(4)
?>
ryanlwh at yahoo dot com 02-Apr-2013 05:28
Since get_defined_vars() only gets the variables at the point you call the function, there is a simple way to get the variables defined within the current scope.

<?php
// The very top of your php script
$vars = get_defined_vars();

// Now do your stuff
$foo = 'foo';
$bar = 'bar';

// Get all the variables defined in current scope
$vars = array_diff(get_defined_vars(),$vars);

echo '<pre>';
print_r($vars);
echo '</pre>';
?>
Anonymous 18-Apr-2011 05:32
get_defined_vars() returns ALL the vars (in the current scope), what if you just want all YOUR vars, not PHP's super-globals?

<?php
    var_export(array_diff(get_defined_vars(), array(array())));
?>

Example...

<?php
    $TOP_LEVEL_VAR=1;
    var_export(array_diff(get_defined_vars(), array(array())));
?>

The output (with register_globals off) should be...

array (
  'TOP_LEVEL_VAR' => 1,
)

...it perfectly eliminated all the super-globals, without me having to specify them! (note with register_globals on, the output includes those globals, then TOP_LEVEL_VAR).

Here it is, as a function...(it's the best I could do {I can't call get_defined_vars() inside get_user_defined_vars() cuz of the scope issue}).

<?php
    header('Content-type: text/plain');

    $TOP_LEVEL_VAR=1;

    echo 'register_globals(';
    echo ini_get('register_globals');
    echo ') '.phpversion()."\n";

    var_export(get_user_defined_vars(get_defined_vars()));

    function get_user_defined_vars($vars) {
        return array_diff($vars, array(array()));
    }
?>

Note that originally I had an array of the super-globals I wanted removed from get_defined_vars()'s array, then I noticed even an empty double-array, array(array()), made it give me the correct result. Weird.

This was tested on PHP 5.2.9.
meint at meint dot net 11-Jan-2011 12:46
Please be aware that function_get_vars only returns the variables defined at the point before you call the function_get_vars function, it does not scan the entire function for you, only the lines before you call it.
Johan de Vries 17-Jun-2010 08:09
Note that this only returns things you've used. See http://bugs.php.net/bug.php?id=52110 . So don't expect this to have the $this entry, unless you assign $this to return $this.
donovan at example dot com 21-Oct-2008 09:15
As a note, get_defined_vars() does not return a set of variable references (as I hoped). For example:

<?php

// define a variable
$my_var = "foo";

// get our list of defined variables
$defined_vars = get_defined_vars();

// now try to change the value through the returned array
$defined_vars["my_var"] = "bar";

echo $my_var, "\n";

?>

will output "foo" (the original value). It'd be nice if get_defined_vars() had an optional argument to make them references, but I imagine its a rather specialized request. You can do it yourself (less conveniently) with something like:

<?php

$defined_vars = array();
$var_names = array_keys(get_defined_vars());

foreach ($var_names as $var_name)
{
    $defined_vars[$var_name] =& $$var_name;
}

?>
SyCo 21-Aug-2008 03:52
Here's a very simple function for debugging. It's far from perfect but I find it very handy. It outputs the var value and the var name on a new line. The problem is it'll echo any vars and their name if they share the same value. No big deal when debugging and saves the hassle of writing the HTML and var name when echoing a variable. (ev=echo variable). Using get_defined_vars() inside a function renames the var name to the functions variable so isn't as useful for debugging. Of course, you'll need access to the $GLOBALS array
<?
function ev($variable){
    foreach($GLOBALS as $key => $value){
        if($variable===$value){
            echo '<p>'.$key.' - '.$value.'</p>';
        }
    }
}

$a=0;
ev($a);
$b=0;
ev($b);
$c=0;
ev($c);
?>
Will output
a - 0

a - 0
b - 0

a - 0
b - 0
c - 0
zabmilenko at hotmail dot com 31-Aug-2006 07:32
A little gotcha to watch out for:

If you turn off RegisterGlobals and related, then use get_defined_vars(), you may see something like the following:

<?php
Array
(
    [GLOBALS] => Array
        (
            [GLOBALS] => Array
 *RECURSION*
            [_POST] => Array()
            [_GET] => Array()
            [_COOKIE] => Array()
            [_FILES] => Array()
        )

    [_POST] => Array()
    [_GET] => Array()
    [_COOKIE] => Array()
    [_FILES] => Array()

)
?>

Notice that $_SERVER isn't there.  It seems that php only loads the superglobal $_SERVER if it is used somewhere.  You could do this:

<?php
print '<pre>' . htmlspecialchars(print_r(get_defined_vars(), true)) . '</pre>';
print '<pre>' . htmlspecialchars(print_r($_SERVER, true)) . '</pre>';
?>

And then $_SERVER will appear in both lists.  I guess it's not really a gotcha, because nothing bad will happen either way, but it's an interesting curiosity nonetheless.
lbowerh at adelphia dot net 04-Jun-2004 08:19
Here is a function which generates a debug report for display or email
using get_defined_vars. Great for getting a detailed snapshot without
relying on user input.

<?php
function generateDebugReport($method,$defined_vars,$email="undefined"){
    // Function to create a debug report to display or email.
    // Usage: generateDebugReport(method,get_defined_vars(),email[optional]);
    // Where method is "browser" or "email".

    // Create an ignore list for keys returned by 'get_defined_vars'.
    // For example, HTTP_POST_VARS, HTTP_GET_VARS and others are
    // redundant (same as _POST, _GET)
    // Also include vars you want ignored for security reasons - i.e. PHPSESSID.
    $ignorelist=array("HTTP_POST_VARS","HTTP_GET_VARS",
    "HTTP_COOKIE_VARS","HTTP_SERVER_VARS",
    "HTTP_ENV_VARS","HTTP_SESSION_VARS",
    "_ENV","PHPSESSID","SESS_DBUSER",
    "SESS_DBPASS","HTTP_COOKIE");

    $timestamp=date("m/d/y h:m:s");
    $message="Debug report created $timestamp\n";

    // Get the last SQL error for good measure, where $link is the resource identifier
    // for mysql_connect. Comment out or modify for your database or abstraction setup.
    global $link;
    $sql_error=mysql_error($link);
    if($sql_error){
      $message.="\nMysql Messages:\n".mysql_error($link);
    }
    // End MySQL

    // Could use a recursive function here. You get the idea ;-)
    foreach($defined_vars as $key=>$val){
      if(is_array($val) && !in_array($key,$ignorelist) && count($val) > 0){
        $message.="\n$key array (key=value):\n";
        foreach($val as $subkey=>$subval){
          if(!in_array($subkey,$ignorelist) && !is_array($subval)){
            $message.=$subkey." = ".$subval."\n";
          }
          elseif(!in_array($subkey,$ignorelist) && is_array($subval)){
            foreach($subval as $subsubkey=>$subsubval){
              if(!in_array($subsubkey,$ignorelist)){
                $message.=$subsubkey." = ".$subsubval."\n";
              }
            }
          }
        }
      }
      elseif(!is_array($val) && !in_array($key,$ignorelist) && $val){
        $message.="\nVariable ".$key." = ".$val."\n";
      }
    }

    if($method=="browser"){
      echo nl2br($message);
    }
    elseif($method=="email"){
      if($email=="undefined"){
        $email=$_SERVER["SERVER_ADMIN"];
      }

      $mresult=mail($email,"Debug Report for ".$_ENV["HOSTNAME"]."",$message);
      if($mresult==1){
        echo "Debug Report sent successfully.\n";
      }
      else{
        echo "Failed to send Debug Report.\n";
      }
    }
}
?>
jgettys at gnuvox dot com 22-Feb-2002 07:09
Simple routine to convert a get_defined_vars object to XML.

<?php
function obj2xml($v, $indent='') {
  while (list($key, $val) = each($v)) {
    if ($key == '__attr') continue;
    // Check for __attr
    if (is_object($val->__attr)) {
      while (list($key2, $val2) = each($val->__attr)) {
        $attr .= " $key2=\"$val2\"";
      }
    }
    else $attr = '';
    if (is_array($val) || is_object($val)) {
      print("$indent<$key$attr>\n");
      obj2xml($val, $indent.'  ');
      print("$indent</$key>\n");
    }
    else print("$indent<$key$attr>$val</$key>\n");
  }
}

//Example object
$x->name->first = "John";
$x->name->last = "Smith";
$x->arr['Fruit'] = 'Bannana';
$x->arr['Veg'] = 'Carrot';
$y->customer = $x;
$y->customer->__attr->id='176C4';

$z = get_defined_vars();
obj2xml($z['y']);
?>

will output:
<customer id="176C4">
  <name>
    <first>John</first>
    <last>Smith</last>
  </name>
  <arr>
    <Fruit>Bannana</Fruit>
    <Veg>Carrot</Veg>
  </arr>
</customer>


Returns an integer identifier for the given resource

  • « get_defined_vars
  • get_resource_type »
  • PHP Manual
  • Funciones de manejo de variables
  • Returns an integer identifier for the given resource

get_resource_id

(PHP 8)

get_resource_id — Returns an integer identifier for the given resource

Descripción

get_resource_id ( resource $res ) : int

This function provides a type-safe way for generating the integer identifier for a resource.

Parámetros

res

The evaluated resource handle.

Valores devueltos

The int identifier for the given res.

This function is essentially an int cast of res to make it easier to retrieve the resource ID.

Ejemplos

Ejemplo #1 get_resource_id() example

<?php
$handle = fopen('./storage/logs/lumen.log', 'rt');

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

echo get_resource_id($handle);

?>

El resultado del ejemplo sería:

698

698

Ver también

  • get_resource_type() - Devuelve el tipo de recurso

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el tipo de recurso

  • « get_resource_id
  • gettype »
  • PHP Manual
  • Funciones de manejo de variables
  • Devuelve el tipo de recurso

get_resource_type

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

get_resource_type — Devuelve el tipo de recurso

Descripción

get_resource_type ( resource $handle ) : string

Esta función obtiene el tipo del recurso dado.

Parámetros

handle

El gestor de recurso evaluado.

Valores devueltos

Si el dado handle es un recurso esta función devolverá una cadena que representa su tipo. Si el tipo no es identificado por esta función, el valor de retorno será la cadena Unknown.

Está función devolverá false y generará un error si handle no es un resource.

Ejemplos

Ejemplo #1 Ejemplo deget_resource_type()

<?php
// imprime: mysql link
$c = mysql_connect();
echo get_resource_type($c) . "\n";

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

// imprime: domxml document
$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc) . "\n";
?>

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


Obtener el tipo de una variable

  • « get_resource_type
  • intval »
  • PHP Manual
  • Funciones de manejo de variables
  • Obtener el tipo de una variable

gettype

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

gettype — Obtener el tipo de una variable

Descripción

gettype ( mixed $var ) : string

Devuelve el tipo de la variable PHP var. Para la comprobación de tipos, utilice las funciones is_*.

Parámetros

var

La variable de la cual queremos comprobar su tipo.

Valores devueltos

Los valores posibles para la cadena devuelta son:

  • "boolean"
  • "integer"
  • "double" (por razones históricas "double" es devuelto en caso de que un valor sea de tipo float, y no simplemente "float")
  • "string"
  • "array"
  • "object"
  • "resource"
  • "NULL"
  • "unknown type"

Ejemplos

Ejemplo #1 Ejemplo de gettype()

<?php

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

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

?>

El resultado del ejemplo sería algo similar a:

integer
double
NULL
object
string

Ver también

  • settype() - Establece el tipo de una variable
  • get_class() - Devuelve el nombre de la clase de un objeto
  • is_array() - Comprueba si una variable es un array
  • is_bool() - Comprueba si una variable es de tipo booleano
  • is_callable() - Verificar que los contenidos de una variable puedan ser llamados como una función
  • is_float() - Comprueba si el tipo de una variable es float
  • is_int() - Comprueba si el tipo de una variable es integer
  • is_null() - Comprueba si una variable es null
  • is_numeric() - Comprueba si una variable es un número o un string numérico
  • is_object() - Comprueba si una variable es un objeto
  • is_resource() - Comprueba si una variable es un recurso
  • is_scalar() - Comprueba si una variable es escalar
  • is_string() - Comprueba si una variable es de tipo string
  • function_exists() - Devuelve true si la función dada ha sido definida
  • method_exists() - Comprueba si existe un método de una clase

User Contributed Notes

matt at appstate 16-Dec-2004 11:10
Here is something that had me stumped with regards to gettype and is_object.
Gettype will report an incomplete object as such, whereas is_object will return FALSE.

<?php
if (!is_object($incomplete_obj)) {
   echo 'This variable is not an object, it is a/an ' . gettype($incomplete_obj);
}
?>

Will print:
This variable is not an object, it is a/an object


Obtiene el valor entero de una variable

  • « gettype
  • is_array »
  • PHP Manual
  • Funciones de manejo de variables
  • Obtiene el valor entero de una variable

intval

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

intval — Obtiene el valor entero de una variable

Descripción

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

Devuelve el valor integer de una var, con la especificada base para la conversión (por defecto es base 10). No debería ser usado en objetos, si es usado emitirá un error de nivel E_NOTICE y devolverá 1.

Parámetros

var

El valor escalar a convertir a un entero

base

La base para la conversión

Nota:

Si base es 0, la base usada estará determinada por el formato de var:

  • si el string incuye el prefijo "0x" (o "0X"), la base se tomará como 16 (hex); si no,
  • si el string comienza con "0", la base se tomará como 8 (octal); si no,
  • la base se toma como 10 (decimal).

Valores devueltos

El valor entero de var en caso de éxito, o 0 en caso de error. Arrays vacíos devuelven 0, arrays no vacíos devuelven 1.

El valor máximo depende del sistema. Los sistemas de 32 bits tienen un rango máximo para un entero con signo que va desde -2147483648 a 2147483647. Así, por ejemplo, en tal sistema, intval('1000000000000') devolverá 2147483647. El valor máximo para un entero con signo en sistemas de 64 bits es 9223372036854775807.

Las cadenas muy probablemente devolverán 0, aunque esto depende de los carácteres del extremo izquierdo de la cadena. Aplican las reglas comunes para moldeado de enteros.

Ejemplos

Ejemplo #1 Ejemplos de intval()

Los siguientes ejemplos se basan en un sistema de 32 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);                    // 1410065408
echo intval('1e10');                  // 1
echo intval(0x1A);                    // 26
echo intval(42000000);                // 42000000
echo intval(420000000000000000000);   // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8);                   // 42
echo intval('42', 8);                 // 34
echo intval(array());                 // 0
echo intval(array('foo', 'bar'));     // 1
?>

Notas

Nota:

El parámetro base no tiene ningún efecto a menos que el parámetro var sea una cadena.

Historial de cambios

Versión | Descripción
5.1.0 | Lanza E_NOTICE y devuelve 1, cuando se pasa un objecto a var.

Ver también

  • boolval() - Obtener el valor booleano de una variable
  • floatval() - Obtener el valor flotante de una variable
  • strval() - Obtiene el valor de cadena de una variable
  • settype() - Establece el tipo de una variable
  • is_numeric() - Comprueba si una variable es un número o un string numérico
  • Manipulación de tipos
  • Funciones matemáticas de precisión arbitraria de 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


Comprueba si una variable es un array

  • « intval
  • is_bool »
  • PHP Manual
  • Funciones de manejo de variables
  • Comprueba si una variable es un array

is_array

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

is_array — Comprueba si una variable es un array

Descripción

is_array ( mixed $var ) : bool

Comprueba si la variable es un array.

Parámetros

var

La variable a ser evaluada.

Valores devueltos

Devuelve true si var es un array, o de lo contrario false.

Ejemplos

Ejemplo #1 Comprobar que la variable es un array

<?php
$si = array('esto', 'es', 'un array');

echo is_array($si) ? 'Array' : 'No es un array';
echo "\n";

$no = 'esto es un string';

echo is_array($no) ? 'Array' : 'No es un array';
?>

El resultado del ejemplo sería:

Array
No es un array

Ver también

  • is_float() - Comprueba si el tipo de una variable es float
  • is_int() - Comprueba si el tipo de una variable es integer
  • is_string() - Comprueba si una variable es de tipo string
  • is_object() - Comprueba si una variable es un objeto

User Contributed Notes

Daniel 14-Jul-2019 06:54
The next post is not correct because has problems with blank array index:
https://www.php.net/manual/es/function.is-array.php#89332

The next code use the above link php code

<?php
function is_assoc($var)
{
        return is_array($var) && array_diff_key($var,array_keys(array_keys($var)));
}

function test($var)
{
        echo is_assoc($var) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n";
}

// an assoc array
$a = array("a"=>"aaa","b"=>1,"c"=>true);
test($a);

// maybe assoc array?
$b = array(0 => "aaa", 1 => 1, 3 => true); // Index 2 not exist
test($b);
?>

# Output
I'm an assoc array.
I'm an assoc array.

"Associative arrays are arrays that use named keys that you assign to them."
https://www.w3schools.com/php/php_arrays.asp

Solution:

<?php
function is_assoc(array $array)
{
    return count(array_filter(array_keys($array), 'is_string')) > 0;
}
function test(array $array)
{
    echo is_assoc($array) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n";
}
// an assoc array
$a = array("a"=>"aaa","b"=>1,"c"=>true);
test($a);
// an array
$b = array(0=>"aaa",1=>1,3=>true);
test($b);
?>

# Output
I'm an assoc array.
I'm not an assoc array.

If you want check pure assoc. array replace > 0 by === count($array)
lrgbx0 at gmail dot com 10-May-2018 08:48
is_assoc() Benchmark:

<?php

function is_assoc1($array) {
    if (!is_array($array)) return false;
    $i = count($array);
    while ($i > 0) unset($array[--$i]);
    return (bool)$array;
}

function is_assoc2(&$array) {
    if (!is_array($array)) return false;
    $i = count($array);
    while ($i > 0) {
        if (!isset($array[--$i])) return true;
    }
    return false;
}

function is_assoc3(&$array) {
    if (!is_array($array)) return false;
    $i = count($array);
    while ($i > 0) {
        if (!array_key_exists(--$i, $array)) return true;
    }
    return false;
}

function is_assoc4($array) {
    if (!is_array($array)) return false;
    ksort($array);
    foreach (array_keys($array) as $k => $v) {
        if ($k !== $v) return true;
    }
    return false;
}

function is_assoc5(&$array) {
    return is_array($array) && array_diff_key($array, array_keys($array));
}

$arr1 = array(); // not associative
$arr2 = $arr3 = array('foo', 'bar', 'baz', 'foo', 'bar', 'baz', 'foo', 'bar', 'baz', 'foo'); // not associative
asort($arr3); // not associative, shuffled keys
$arr4 = array('foo', 'bar', 'baz', 'foo', 'bar', null, 'foo', 'bar', 'baz', 'foo'); // not associative but is_assoc2() thinks it is
$arr5 = array(0 => 'foo', 1 => 'bar', 2 => 'baz', 3 => 'foo', 4 => 'bar', 5 => 'baz', 'foo3' => 'foo', 'bar3' => 'bar', 'baz3' => 'baz', 'foo4' => 'foo'); // associative

$i = $j = 0;
$time = array(0.0, 0.0, 0.0, 0.0, 0.0);

for ($j = 0; $j < 2000; $j++) {
    $time[0] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc1($arr1) || is_assoc1($arr2) || is_assoc1($arr3) || is_assoc1($arr4) || !is_assoc1($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[0] += microtime(true);
    $time[1] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc2($arr1) || is_assoc2($arr2) || is_assoc2($arr3) || !is_assoc2($arr4) || !is_assoc2($arr5)) { // $arr4 tweaked
            echo 'error';
            break;
        }
    }
    $time[1] += microtime(true);
    $time[2] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc3($arr1) || is_assoc3($arr2) || is_assoc3($arr3) || is_assoc3($arr4) || !is_assoc3($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[2] += microtime(true);
    $time[3] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc4($arr1) || is_assoc4($arr2) || is_assoc4($arr3) || is_assoc4($arr4) || !is_assoc4($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[3] += microtime(true);
    $time[4] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc5($arr1) || is_assoc5($arr2) || is_assoc5($arr3) || is_assoc5($arr4) || !is_assoc5($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[4] += microtime(true);
}

echo 'is_assoc1(): ' . $time[0] . "\n";
echo 'is_assoc2(): ' . $time[1] . "\n";
echo 'is_assoc3(): ' . $time[2] . "\n";
echo 'is_assoc4(): ' . $time[3] . "\n";
echo 'is_assoc5(): ' . $time[4] . "\n";

?>

is_assoc1() - uses unset(), a bit slow, but mem friendly and no function calls
is_assoc2() - uses isset(), fastest one, but returns TRUE whenever array contains NULL
is_assoc3() - fixed is_assoc2(), uses array_key_exists(), fast and memory friendly, and much smarter than the following (no need to check all those keys)
is_assoc4() - alex' version with proper check and key sorting
is_assoc5() - fixed a bit JTS' version, really nice one, but uses too many functions and checks all keys

Results:

is_assoc1(): 2.1628699302673
is_assoc2(): 1.1079933643341
is_assoc3(): 1.7120850086212
is_assoc4(): 3.9194552898407
is_assoc5(): 1.9509885311127
rik at mmod dot co 12-Apr-2018 05:39
Using is_array prior to an in_array within an if clause will safely escape a check against a variable that could potentially be a non-array when using in_array.  For instance:

NOTE: A real use case might be that we have a list of possible flags which  in a database we have stored whether each of the flags are 0 or 1.  We want a list of the flags which have the value of 1 to be returned.

Our example here will not use so many technical artifacts, but will be based on similar logic just to get the point across.

<?php

// We have a list of known values
$knownVars = ['apple', 'orange'];

// A list of values to check
$listToCheck = ['pear', 'banana'];

// And a method that takes a list of values to check and returns a new list
// of the items from said list that are found to be valid...
public function getValidItemsList( $listToCheck /*['pear', 'banana']*/)
{
    $returnList = [];
    foreach($listToCheck as $key => $val)
    {
        if(in_array($val, $knownVars))
        {
            array_push($returnList, $val);
        }
    }

    if(empty($returnList))
    {
        // We have a special case if there were no valid items found, which is the case we are going over
        return  -1;
    }

    // Otherwise, normally returns a list of the items that were found to be valid
    return $returnList;
}

// Call the method and check for any valid items that can be used for some purpose
$validItemsList =  getValidItemsList($listToCheck);

// In this usage we could potentially get an exception because
// in_array() expects an array for argument #2, checking that the value != -1 does not escape the if statement:
if(isset($validItemsList) && $validItemsList != -1 && in_array('apple', $validItemsList))
{
    //...
}

// In this usage, we break free from the if statement safely:
if(isset($validItemsList) && $validItemsList != -1 && is_array($validItemsList) && in_array('apple', $validItemsList))
{
    //...
}

?>

Hope that can help someone, I know it helped me.
gwschnell at ewe dot net 22-Mar-2018 04:58
An error will be thrown If is_array() is applied to a nonexisting varble.
carren at AngieBecker dot ch 26-Sep-2017 08:48
This is probably the best way to test for associative arrays:

<?php
function is_assoc($test) {
        if (empty($test)) { return(false); }
        if (!is_array($test)) { return(false); }
        return ($test !== array_values($test));
}
?>

This version is based on the one from dmitry dot sushilov, which is unfortunately exactly opposite and misses the is_array and empty test.
http://php.net/manual/en/function.is-array.php#115901
marko at newvibrations dot net 20-Oct-2016 12:08
hperrin at gmail dot com
i tested modified version of your code:

<?php
$test = array_fill(0, $size, rand());
$test3 = (object) $test;
?>

Results are quite different!

PHP 5.5:
is_array - execution time is constant over different $size
cast, === - execution time is proportional with $size, for small arrays, it's faster than is_array, but for bigger arrays, it's way slower. Also, bigger memory allocation because casting actually allocates memory

PHP 7.0:
is_array and cast, === have constant execution time over different $size:
is_array  :  0.12564396858215
cast, === :  0.24629783630371

Looks like casting is optimised, but still slower.

Bottom line is: optimisation is not done for special scenario, but for average use and scalability. Don't reinvent wheel.
Rob Thomas 05-Oct-2016 10:40
Please note that the 'cast to array' check is horrendously out of date.

Running that code against PHP 5.6 results in this:

is_array  :  0.93975400924683
cast, === :  1.2425191402435

So, please use 'is_array', not the horrible casting hack.
mt at banita dot de 08-Sep-2016 09:30
I'm using PHP 5.3.10 and the remark from hperrin is not (no longer?) valid

is_array is (now?) faster than if ( (array) $unknown !== $unknown )

my result of hperrins test script

is_array  :  0.61710119247437
cast, === :  1.1551909446716
ari at umbrella dot bz 05-Sep-2016 08:34
hperrin's results have indeed changed in PHP 7. The opposite is now true, is_array is faster than comparison:

is_array  :  0.52148389816284
cast, === :  0.84179711341858

Tested 1000000 iterations.
mbrodala at pagemachine dot de 24-Aug-2016 01:22
Notice that the benchmark results from hperrin at gmail dot com have changed in the meantime:

is_array  :  0.31888604164124
cast, === :  0.58448791503906

(Using PHP 5.6.24, I expect other results with PHP 7)
dmitry dot sushilov at gmail dot com 12-Oct-2014 12:49
function is_associate_array($array)
{
    return $array === array_values($array);
}

or you can add check is_array in functions
joksnet at gmail dot com 08-Oct-2013 10:17
Here is something for compare `is_assoc` functions.

<?php
function is_assoc1($var)
{
    return is_array($var) && array_diff_key($var, array_keys(array_keys($var)));
}

function is_assoc2($var)
{
    return is_array($var) && array_diff_key($var, array_fill(0, count($var), null));
}

$count = 1000000;

$a = array('a' => 'foo', 'b' => 1, 'c' => true);
$b = array('a', 'b', 'c');

$i = $start_time = $end_time = 0;

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    assert(is_assoc1($a) === true);
    assert(is_assoc1($b) === false);
}
$end_time = microtime(true);
echo 'is_assoc1  :  ' . ($end_time - $start_time) . "\n";

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    assert(is_assoc2($a) === true);
    assert(is_assoc2($b) === false);
}
$end_time = microtime(true);
echo 'is_assoc2  :  ' . ($end_time - $start_time) . "\n";
?>

It prints something like this:

```
% php is_assoc.php
is_assoc1  :  19.36315202713
is_assoc2  :  18.954080104828
```

The first one is from
skaimauve (http://www.php.net/manual/en/function.is-array.php#89332). The second one is mine.
magentix at gmail dot com 26-Feb-2011 09:12
If you wanted to have 'pure' associative arrays,
you could filter out non-string keys and then compare the count of the original array with the count of the filtered array.

<?php
    // Only validates empty or completely associative arrays
    function is_assoc ($arr) {
        return (is_array($arr) && count(array_filter(array_keys($arr),'is_string')) == count($arr));
    }

    $a = '';
    $b = 'z';
    $c = array();
    $d = array('x','y','z');
    $e = array('x','y','zed'=>'z');
    $f = array('ex'=>'x','why'=>'y','zed'=>'z');

    echo '$a: ' . ( (is_assoc($a)) ? 'true' : 'false' ) ."\n"; // False
    echo '$b: ' . ( (is_assoc($b)) ? 'true' : 'false' ) ."\n"; // False
    echo '$c: ' . ( (is_assoc($c)) ? 'true' : 'false' ) ."\n"; // True
    echo '$d: ' . ( (is_assoc($d)) ? 'true' : 'false' ) ."\n"; // False
    echo '$e: ' . ( (is_assoc($e)) ? 'true' : 'false' ) ."\n"; // False
    echo '$f: ' . ( (is_assoc($f)) ? 'true' : 'false' ) ."\n"; // True
?>

I've tested the point of checking whether the array is empty first.
The overall result was a 200% speed increase when the array was indeed empty,
but an average 10% slow when it had elements inside.

<?php
    /***********************************************************
     *    Benchmarks: checking for empty array vs. not checking  *
     ***********************************************************/

    // With empty check
    function is_assoc ($arr) {
        return (is_array($arr) && (!count($arr) || count(array_filter(array_keys($arr),'is_string')) == count($arr)));
    }

    function test_speed($arr) {
        $t = microtime(true);
        for($i = 0; $i < 100000; ++$i) is_assoc($arr);
        return (microtime(true) - $t);
    }

    echo '$a: ' . test_speed($a) ."\n"; // 0.20597505569458
    echo '$b: ' . test_speed($b) ."\n"; // 0.19199514389038
    echo '$c: ' . test_speed($c) ."\n"; // 0.28803396224976
    echo '$d: ' . test_speed($d) ."\n"; // 0.94685983657837
    echo '$e: ' . test_speed($e) ."\n"; // 0.96698403358459
    echo '$f: ' . test_speed($f) ."\n"; // 0.98052096366882

    // Without empty check
    function is_assoc_2 ($arr) {
        return (is_array($arr) && count(array_filter(array_keys($arr),'is_string')) == count($arr));
    }

    function test_speed_2($arr) {
        $t = microtime(true);
        for($i = 0; $i < 100000; ++$i) is_assoc_2($arr);
        return (microtime(true) - $t);
    }

    echo '$a: ' . test_speed_2($a) ."\n"; // 0.18811202049255 = FASTER:  91.3% of is_assoc
    echo '$b: ' . test_speed_2($b) ."\n"; // 0.18782901763916 = FASTER:  97.8% of is_assoc
    echo '$c: ' . test_speed_2($c) ."\n"; // 0.64437484741211 = SLOWER: 223.7% of is_assoc
    echo '$d: ' . test_speed_2($d) ."\n"; // 0.84632205963135 = FASTER:  89.4% of is_assoc
    echo '$e: ' . test_speed_2($e) ."\n"; // 0.86739897727966 = FASTER:  89.7% of is_assoc
    echo '$f: ' . test_speed_2($f) ."\n"; // 0.87963700294495 = FASTER:  89.7% of is_assoc
?>
JTS 08-Jun-2010 04:22
I would change the order of the comparison, because if it is really an empty array, it is better to stop at that point before doing several 'cpu & memory intensive' function calls.

In the end on a ratio of 3 not empty arrays to 1 empty array computed for 1000000 iterations it needed 10% less time.
Or the other way round:
It needed approx 3% to 4% more time if the array is not empty, but was at least 4 times faster on empty arrays.

Additionally the memory consumption veritably lesser.

<?php
function is_assoc($array) {
    return (is_array($array) && (count($array)==0 || 0 !== count(array_diff_key($array, array_keys(array_keys($array))) )));
}
?>
hperrin at gmail dot com 28-May-2010 10:02
I've found a faster way of determining an array. If you use is_array() millions of times, you will notice a *huge* difference. On my machine, this method takes about 1/4 the time of using is_array().

Cast the value to an array, then check (using ===) if it is identical to the original.

<?php
if ( (array) $unknown !== $unknown ) {
    echo '$unknown is not an array';
} else {
    echo '$unknown is an array';
}
?>

You can use this script to test the speed of both methods.

<pre>
What's faster for determining arrays?

<?php

$count = 1000000;

$test = array('im', 'an', 'array');
$test2 = 'im not an array';
$test3 = (object) array('im' => 'not', 'going' => 'to be', 'an' => 'array');
$test4 = 42;
// Set this now so the first for loop doesn't do the extra work.
$i = $start_time = $end_time = 0;

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!is_array($test) || is_array($test2) || is_array($test3) || is_array($test4)) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'is_array  :  '.($end_time - $start_time)."\n";

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!(array) $test === $test || (array) $test2 === $test2 || (array) $test3 === $test3 || (array) $test4 === $test4) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'cast, === :  '.($end_time - $start_time)."\n";

echo "\nTested $count iterations."

?>
</pre>

Prints something like:

What's faster for determining arrays?

is_array  :  7.9920151233673
cast, === :  1.8978719711304

Tested 1000000 iterations.
Anonymous 16-May-2009 02:18
Using empty() in the previous example posted by Anonymous will result in a "Fatal error: Can't use function return value in write context".  I suggest using count() instead:

<?php
function is_assoc($array) {
    return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
}
?>
skaimauve at yahoo dot ca 03-Mar-2009 12:12
Or you could make use of the array_diff_key and array_key function:

<?php

function is_assoc($var)
{
        return is_array($var) && array_diff_key($var,array_keys(array_keys($var)));
}

function test($var)
{
        echo is_assoc($var) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n";
}

// an assoc array
$a = array("a"=>"aaa","b"=>1,"c"=>true);
test($a);

// an array
$b = array_values($a);
test($b);

// an object
$c = (object)$a;
test($c);

// other types
test($a->a);
test($a->b);
test($a->c);

?>

The above code outputs:
I'm an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
Matthias Loitsch 03-Dec-2008 11:36
Or you could make use of the array_diff_key and range functions:

<?php

function isVector($var) { return count(array_diff_key($var, range(0, count($var) - 1))) == 0; }

function isAssociative($var) { return !isVector($var); }

?>
jim at akubo dot net 28-Oct-2008 11:02
yousef's example was wrong because is_vector returned true instead of false if the key was found
here is the fixed version (only 2 lines differ)
<?php
function is_vector( &$array ) {
   if ( !is_array($array) || empty($array) ) {
      return -1;
   }
   $next = 0;
   foreach ( $array as $k => $v ) {
      if ( $k !== $next ) return false;
      $next++;
   }
   return true;
}
?>
yousuf at philipz dot com 16-Oct-2008 03:41
alex frase's example is fast but elanthis at awesomeplay dot com's example is faster and Ilgar's modification of alex's code is faulty (the part " || $_array[$k] !== $v"). Also, Ilgar's suggestion of giving a false return value when the variable isnt an array is not suitable in my opinion and i think checking if the array is empty would also be a suitable check before the rest of the code runs.

So here's the modified (is_vector) version

<?php
function is_vector( &$array ) {
   if ( !is_array($array) || empty($array) ) {
      return -1;
   }
   $next = 0;
   foreach ( $array as $k => $v ) {
      if ( $k !== $next ) return true;
      $next++;
   }
   return false;
}
?>

and the modified (alex's is_assoc) version

<?php
function is_assoc($_array) {
    if ( !is_array($_array) || empty($array) ) {
        return -1;
    }
    foreach (array_keys($_array) as $k => $v) {
        if ($k !== $v) {
            return true;
        }
    }
    return false;
}
?>
alex frase 16-Jul-2008 08:05
Yet another simpler, faster is_assoc():

<?php
function is_assoc($array) {
  foreach (array_keys($array) as $k => $v) {
    if ($k !== $v)
      return true;
  }
  return false;
}
?>

In my tests it runs about twice as fast as Michael/Gabriel's array_reduce() method.

(Speaking of which: Gabriel's version doesn't work as written; it reports associative arrays as numeric if only the first key is non-numeric, or if the keys are numeric but ordered backwards.  Michael solves this problem by comparing array_reduce() to count(), but that costs another function call; it also works to just compare to -1 instead of 0, and therefore return -1 as the ternary else from the callback).
Michael 11-Sep-2007 12:37
A slight modification of what's below:

<?php

function is_assoc($array)
{
    return is_array($array) && count($array) !== array_reduce(array_keys($array), 'is_assoc_callback', 0);
}

function is_assoc_callback($a, $b)
{
    return $a === $b ? $a + 1 : 0;
}

?>
gabriel at bumpt dot nothing-here dot net 29-Aug-2007 08:34
Yet another safer, faster way of detecting whether an array is associative.

The principle is: using array reduction on the keys, we verify that each key is numeric and is equal to its rank.

Beware: integer keys that are not in sequence, or are negative, or with "holes", still make an associative array.

<?php
/**
  * @param array $arr
  * @returns boolean
  */
function isNotAssocArray($arr)
{
    return (0 !== array_reduce(
        array_keys($arr),
        create_function('$a, $b', 'return ($b === $a ? $a + 1 : 0);'),
        0
        )
    );
}
?>

Of course, it is still faster if the callback for array_reduce is not an anonymous function:

<?php
function callbackReduceNotArray($a, $b)
{
    return ($b === $a ? $a + 1 : 0);
}
function isVector($arr)
{
    return (0 !== array_reduce(
        array_keys($arr),
        'callbackReduceNotArray',
        0
        )
    );
}
?>
Alfred J Fazio <alfred dot fazio at gmail dot com> 04-Apr-2007 04:32
Yet another associative array test:

<?php
function binary_nand ($a, $b) { return !$a && !$b; }
function binary_nor ($a, $b)  { return !$a || !$b; }

// Returns true if array has elements with non-numeric keys
function is_associative_array ($arr) {
  return is_array($arr) && !empty($arr) && array_reduce(array_map("is_numeric", array_keys($arr)), "binary_nor", true);
}

// Returns true if all elements of array have a non-numeric key
function is_strict_associative_array ($arr) {
  return is_array($arr) && !empty($arr) && array_reduce(array_map("is_numeric", array_keys($arr)), "binary_nand", false);
}
?>
angelo [at] mandato <dot> com 26-Feb-2007 01:32
The is_associative_array() and is_sequential_array() functions posted by 'rjg4013 at rit dot edu' are not accurate.

The functions fail to recognize indexes that are not in sequence or in order.  For example, array(0=>'a', 2=>'b', 1=>'c') and array(0=>'a', 3=>'b', 5=>'c') would be considered as sequential arrays. A true sequential array would be in consecutive order with no gaps in the indices.

The following solution utilizes the array_merge properties. If only one array is given and the array is numerically indexed, the keys get re-indexed in a continuous way.  The result must match the array passed to it in order to truly be a numerically indexed (sequential) array.  Otherwise it can be assumed to be an associative array (something unobtainable in languages such as C).

The following functions will work for PHP >= 4.

<?php
    function is_sequential_array($var)
    {
        return (array_merge($var) === $var && is_numeric( implode( array_keys( $var ) ) ) );
    }

    function is_assoc_array($var)
    {
        return (array_merge($var) !== $var || !is_numeric( implode( array_keys( $var ) ) ) );
    }
?>

If you are not concerned about the actual order of the indices, you can change the comparison to == and != respectively.
jupiter at nospam dot com 29-May-2006 11:42
Will check a Multi-Dimentional Array to any specified level.  This is a fix to 11/16/05 submission, which would break since you must supply a foreach with an array. Beware recursive functions shouldn't go over 100 deep or could break the memory stack on server.

<?php
// checks for multiarray to defined depth level recursively
// original $level must be 2 or more, else will instantly return true
function isDeepMultiArray($multiarray, $level = 2) {  // default is simple multiarray
    if (is_array($multiarray)) {  // confirms array
        if ($level == 1) {  // $level reaches 1 after specified # of recursions
            return true;  // returns true to recursive function conditional
        }  // end conditional
        foreach ($multiarray as $array) {  // goes one level deeper into array
            if (isDeepMultiArray($array, $level - 1)) {  // check subarray
                $message = "I'm a multiarray";  // optional message
                return $message;  // best if $message = true so function returns boolean
            }  // end recursive function
        }  // end loop
    } else {  // not an array at specified level
    return false;  // is also used recursively so can't change to message
    }
}

if (isDeepMultiArray(array(array()), 2)); // beware this returns true eventhough arrays are empty

?>
BTW my notation is consistent with the PEAR manual on coding standards, which is what php.net says to follow. I hope a function like this gets included in PHP6.
jupiter at nospam dot com 29-May-2006 09:15
Simple check for a Multi-Dimentional Array of any depth
<?php
// checks for multiarray (2 or more levels deep)
function isMultiArray($multiarray) {
  if (is_array($multiarray)) {  // confirms array
    foreach ($multiarray as $array) {  // goes one level deeper
      if (is_array($array)) {  // is subarray an array
        return true;  // return will stop function
      }  // end 2nd check
    }  // end loop
  }  // end 1st check
  return false;  // not a multiarray if this far
}
?>
March 30-Mar-2006 06:28
And here is another variation for a function to test if an array is associative. Based on the idea by mot4h.

<?php
function is_associative($array)
{
  if (!is_array($array) || empty($array))
    return false;

  $keys = array_keys($array);
  return array_keys($keys) !== $keys;
}
?>
dan at cain dot sh 10-Dec-2004 05:05
is_array() under PHP 5.0.2 will return FALSE when passed an object descended from the internal class interface ArrayAccess(http://www.php.net/spl) even though said object behaves as an array would in most instances.

I've found the following user function helpful with my own classes and functions that expect array(s) as arguments, but work fine with objects that behave as an array would.

<?php
function is_array_abled(&$x)
{
    return (bool)($x instanceof ArrayAccess or is_array($x));
}
?>
vhermecz at ixpert dot hu 01-Apr-2004 04:58
Mike's function is quite cool, it is just the one, I was searching for. Using range is a great idea! But it's a bit long for me. Here is a shorter version:

<?php
function is_assoc_array($var) {
    if (!is_array($var)) {
        return false;
    }
    return array_keys($var)!==range(0,sizeof($var)-1);
}
?>

Or, if you don't want to type that much:

<?php
function is_assoc($var) {
    return is_array($var) && array_keys($var)!==range(0,sizeof($var)-1);
}
?>


Comprueba si una variable es de tipo booleano

  • « is_array
  • is_callable »
  • PHP Manual
  • Funciones de manejo de variables
  • Comprueba si una variable es de tipo booleano

is_bool

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

is_bool — Comprueba si una variable es de tipo booleano

Descripción

is_bool ( mixed $var ) : bool

Obtiene si la variable dada es un booleano.

Parámetros

var

La variable a ser evaluada.

Valores devueltos

Devuelve true si var es un boolean, false de lo contrario.

Ejemplos

Ejemplo #1 Ejemplos de is_bool()

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

// Ya que $a es un booleano, devolverá true
if (is_bool($a) === true) {
    echo "Sí, este es un booleano";
}

// Ya que $b no es un booleano, devolverá false
if (is_bool($b) === false) {
    echo "No, este no es un booleano";
}
?>

Ver también

  • is_float() - Comprueba si el tipo de una variable es float
  • is_int() - Comprueba si el tipo de una variable es integer
  • is_string() - Comprueba si una variable es de tipo string
  • is_object() - Comprueba si una variable es un objeto
  • is_array() - Comprueba si una variable es un array

User Contributed Notes

Julio Marchi 08-Sep-2019 12:32
The function Michael Smith published doesn't do the work as it should.

To check if a variable is boolean is one thing, to evaluate if the value of a variable represents a boolean condition (true or false) is another.

Here a simple function that checks the status of the received variable in regards to boolean equivalencies (case insensitive).

<?php
/**
 * Check "Booleanic" Conditions :)
 *
 * @param  [mixed]  $variable  Can be anything (string, bol, integer, etc.)
 * @return [boolean]           Returns TRUE  for "1", "true", "on" and "yes"
 *                             Returns FALSE for "0", "false", "off" and "no"
 *                             Returns NULL otherwise.
 */
function is_enabled($variable)
{
    if (!isset($variable)) return null;
    return filter_var($variable, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
}
?>

Of course, it is a simplistic approach, but for the majority of cases it will do the job right.

And, just to put thing in the right perspective, here's a real function that does what Phill disclosed:

<?php
/**
 * Convert $variable to boolean (adapted from Phill answer)
 *
 * @param  [mixed]  $variable  Can be anything
 * @return [boolean]           Returns the booelan equivalent to $variable based on Zend Enegine interpretation
 */
function to_bool($variable)
{
    return (bool)$variable;
}
?>

I hope it helps someone. Happy coding.
phil 10-Jan-2019 06:21
It should be stated that this function returns true if the _type_ of it's argument is boolean. It does not convert or coerce the value to a boolean type, not sure why so many comments focus on how to do this.
However, if you arrived here looking for a solution to convert a value to a boolean type, use this:

to_bool($x) { return (bool)$x; }
Michael Smith 17-Nov-2013 01:17
The function in the last comment also converts the string 'false' to a true boolean. Here's a function that does what I think was intended:

<?php
function toBool($var) {
  if (!is_string($var)) return (bool) $var;
  switch (strtolower($var)) {
    case '1':
    case 'true':
    case 'on':
    case 'yes':
    case 'y':
      return true;
    default:
      return false;
  }
}


Verificar que los contenidos de una variable puedan ser llamados como una función

  • « is_bool
  • is_countable »
  • PHP Manual
  • Funciones de manejo de variables
  • Verificar que los contenidos de una variable puedan ser llamados como una función

is_callable

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

is_callable — Verificar que los contenidos de una variable puedan ser llamados como una función

Descripción

is_callable ( mixed $var , bool $syntax_only = false , string &$callable_name = ? ) : bool

Verifica que los contenidos de una variable puedan ser llamados como una función. Esto permite revisar que los contenidos de una variable contengan el nombre de una función válida, o que un array contenga un objeto adecuadamente codificado y un nombre de función.

Parámetros

var

El valor a revisar

solo_sintaxis

Si es true la función solo verifica que nombre pueda ser una función o un método. Solo rechazará variables simples que no sean cadenas, o un array que no tenga una estructura válida para ser usado como llamada de retorno. Se espera que las matrices válidas tengan solo 2 entradas, la primera de las cuales es un objeto o una cadena, y la segunda una cadena.

callable_name

Recibe el "nombre que puede ser llamado". En el ejemplo siguiente aquél es "algunaClase:algunMetodo". Tenga en cuenta, sin embargo, que a pesar de la implicación de que algunaClase::algunMetodo() es un método estático que puede ser llamado, este no es el caso.

Valores devueltos

Devuelve true si var puede ser llamado, false de lo contrario.

Ejemplos

Ejemplo #1 Ejemplo de is_callable()

<?php
//  Cómo chequear una variable para ver si puede ser llamada
//  como una función.

//
//  Variable simple que contiene una función
//

function algunaFuncion()
{
}

$variableFuncion = 'algunaFuncion';

var_dump(is_callable($variableFuncion, false, $nombre_a_llamar));  // bool(true)

echo $nombre_a_llamar, "\n";  // algunaFuncion

//
//  Array que contiene un método
//

class algunaClase {

  function algunMetodo()
  {
  }

}

$unObjeto = new algunaClase();

$variableMetodo = array($unObjeto, 'algunMetodo');

var_dump(is_callable($variableMetodo, true, $nombre_a_llamar));  //  bool(true)

echo $nombre_a_llamar, "\n";  //  algunaClase::algunMetodo

?>

Ejemplo #2 Función is_callable() y constructores

A partir de PHP 5.3.0 la función is_callable() reporta constructores como que no se pueden llamar. Esto afecta el estilo de los constructores de PHP 5 (__construct) así también el estilo de los constructors de PHP 4 (por ejemplo metodos con el mismo nombre de la clase). Anteriormente, ambos casos han sido considerados como llamables.

<?php

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

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

El resultado del ejemplo sería:

bool(false)
bool(false)

Ver también

  • function_exists() - Devuelve true si la función dada ha sido definida
  • method_exists() - Comprueba si existe un método de una clase

User Contributed Notes

jlh 22-Mar-2019 09:28
The story about __call() is a bit more complicated unfortunately. It will always return true ONLY if you pass an instance of a class, not if you pass the class name itself:

<?php
class MyClass {
    public function method() { }
    public function __call($name, $arguments) { }
}

is_callable([MyClass::class, 'method']); // true
is_callable([new MyClass(), 'method']); // true
is_callable([MyClass::class, 'other']); // false!!!
is_callable([new MyClass(), 'other'])); // true
bienvenunet at yaho dot com 06-Mar-2018 10:29
It's not immediately evident from the content of the article, but implementing __invoke() makes an object callable.

<?php
class ObjectWithInvoke {
  public function __invoke() {}
}

$o = new ObjectWithInvoke();
if (is_callable($o)) echo "true"; else echo "false";
// echoes "true"
?>
roland at mxchange dot org 27-Feb-2017 10:17
Please note that the example at comment #104633 is no longer valid with PHP 7 as it seems to be fixed:

PHP 7.0.16-1~dotdeb+8.1

correctly outputs:
bool(true)
mikko dot rantalainen at peda dot net 03-Feb-2017 08:29
Some additional notes about the implementation (PHP 5.6):

- <?php is_callable(array("myclass", "f1")) ?> will return true even if myclass::f1() is not a static method. As such, even if is_callable() will return true, the method cannot be called.

- <?php is_callable(array($object, "f2")) ?> will return true even if $object->f2() cannot be called because of method visibility (e.g. f2() is private or protected).
heah at heahprod dot com 20-Apr-2016 11:48
I don't know if it is a bug but when you test an array with a class and method, is_callable returns true for non static method.

Consider the following code:
<?php

class A
{
    public static function test()
    {
        echo 'test', '<br>';
    }

    public function hello()
    {
        echo 'hello', '<br>';
    }
}

echo "Static #1: call_user_func(array('A', 'test')) => ", call_user_func(array('A', 'test')), '<br>';
echo 'expect is_callable TRUE => ',
    is_callable(array('A', 'test'))
        ? 'TRUE, A::test() is callable statically'
        : 'FALSE, A::test() is not callable statically',
    '<br><br>'
;

echo "Static #2: call_user_func(array('A', 'hello')) => ", call_user_func(array('A', 'hello')), '<br>';
echo 'expect is_callable FALSE => ',
    is_callable(array('A', 'hello'))
        ? 'TRUE, A::hello() is callable statically'
        : 'FALSE, A::hello() is not callable statically',
    '<br><br>'
;

$a = new A();

echo "Instance #1: call_user_func(array(\$a, 'test')) => ", call_user_func(array($a, 'test')), '<br>';
echo 'expect is_callable TRUE => ',
    is_callable(array($a, 'test'))
        ? 'TRUE, $a::test() is callable'
        : 'FALSE, $a::test() is not callable',
    '<br><br>'
;

echo "Instance #2: call_user_func(array(\$a, 'hello')) => ", call_user_func(array($a, 'hello')), '<br>';
echo 'expect is_callable FALSE => ',
    is_callable(array($a, 'hello'))
        ? 'TRUE, $a::hello() is callable'
        : 'FALSE, $a::hello() is not callable',
    '<br><br>'
;

?>

Will output:
Static #1: call_user_func(array('A', 'test')) => test

expect is_callable TRUE => TRUE, A::test() is callable statically

Static #2: call_user_func(array('A', 'hello')) =>
Strict Standards: call_user_func() expects parameter 1 to be a valid callback, non-static method A::hello() should not be called statically in test.php on line 24
hello

expect is_callable FALSE => TRUE, A::hello() is callable statically

Instance #1: call_user_func(array($a, 'test')) => test

expect is_callable TRUE => TRUE, $a::test() is callable

Instance #2: call_user_func(array($a, 'hello')) => hello

expect is_callable TRUE => TRUE, $a::hello() is callable

------------------------------------------------------------

Also note that this works the same for inherited methods (I read other posts suggesting otherwise), and that private methods (static, inherited or both) always return false in any case as expected.

Tested with php 5.6.20.
izharaazmi at gmail dot com 11-Jan-2016 06:50
If the target class has __call() magic function implemented, then is_callable will ALWAYS return TRUE for whatever method you call it.
is_callable does not evaluate your internal logic inside __call() implementation (and this is for good).
Therefore every method name is callable for such classes.

Hence it is WRONG to say (as someone said):
...is_callable will correctly determine the existence of methods made with __call...

Example:
<?php
class TestCallable
{
    public function testing()
    {
          return "I am called.";
    }

    public function __call($name, $args)
    {
        if($name == 'testingOther')
        {
                return call_user_func_array(array($this, 'testing'), $args);
        }
    }
}

$t = new TestCallable();
echo $t->testing();      // Output: I am called.
echo $t->testingOther(); // Output: I am called.
echo $t->working();      // Output: (null)

echo is_callable(array($t, 'testing'));       // Output: TRUE
echo is_callable(array($t, 'testingOther'));  // Output: TRUE
echo is_callable(array($t, 'working'));       // Output: TRUE, expected: FALSE
?>
ffalek at banfi dot pl 13-Mar-2015 05:42
Example how is_callable works:

<?php
$counter = 0;

class TestClassOne {
    function testMethod(){
        global $counter;
        return ++$counter;
    }
    static function testMethodStatic(){
        global $counter;
        return ++$counter;
    }
}

class TestClassTwo {
    function __invoke() {
        global $counter;
        return ++$counter;
    }
}

function test_function() {
    global $counter;
    return ++$counter;
}

$p1 = 'test_function';
$p2 = new TestClassOne();
$p3 = ['TestClassOne', 'testMethodStatic'];
$p4 = [new TestClassOne(), 'testMethod'];
$p5 = new TestClassTwo();
$p6 = function() {
    global $counter;
    return ++$counter;
};

foreach ([$p1, $p2, $p3, $p4, $p5, $p6] as $p) {
    if(is_callable($p)){
        echo 'is invokable: yes '.$p().PHP_EOL;
    } else {
        echo 'is invokable: no'.PHP_EOL;
    }
}
?>

And output is:

is invokable: yes 1
is invokable: no
is invokable: yes 2
is invokable: yes 3
is invokable: yes 4
is invokable: yes 5
wowkise at gmail dot com 07-Mar-2013 10:10
beware calling is_callable on class that has the same method name will return false, i filed a bug report to be included in function description as example

<?php
class test {
 function test() {
 }
}
$class = new test();
var_dump(is_callable([$class, 'test']));
?>

will return false
np dot liamg at gmail dot com 08-Dec-2012 01:52
is_callable() will try __autoload(), if have one.
Athari 13-May-2012 03:58
For closures, the function will return true and $callable_name will be set to "Closure::__invoke".
passivesmoking AT yahoo DOT com 07-Jan-2012 06:06
is_callable doesn't seem able to resolve namespaces.  If you're passing a string, then the string has to include the function's full namespace.

<?php
namespace foo\bar\baz;

function something ()
{
    return (42);
}

var_dump (is_callable ('something')); // false
var_dump (is_callable ('foo\bar\baz\something')); // true
?>

It's easy to forget, but if you just prepend __NAMESPACE__ to your function name strings you should be fine in most cases.
fgm at osinet dot fr 27-Jun-2011 05:03
Note that, for the purpose of this function, an abstract method, although necessarily non-callable since it does not have a body, is still considered to be callable:

<?php
abstract class Foo {
  abstract function bar();
}

echo is_callable(array('Foo', 'bar'));
// display: 1
?>
Andy at txtNation dot com 27-Jun-2011 03:50
Note that is_callable is aware of context, and you can ask it things like parent::__construct from within a child constructor

<?php

    class TestClass extends TestClassParent {

        /** @brief Object initialisation callback
            @returns void */
        public function __construct() {

            # do initialisation

            # ...

            # if we have a parent

            if(is_callable('parent::__construct')) {

                # then bubble up

                parent::__construct();
            }
        }
    }
?>
colin 03-Oct-2010 11:30
I haven't seen anyone note this before, but is_callable will correctly determine the existence of methods made with __call. The method_exists function will not.

Example:
<?php

class Test {

    public function testing($not = false) {
        $not = $not ? 'true' : 'false';
        echo "testing - not: $not<br/>";
    }

    public function __call($name, $args) {
        if(preg_match('/^not([A-Z]\w+)$/', $name, $matches)) {
            $fn_name = strtolower($matches[1]);
            if(method_exists($this, $fn_name)) {
                $args[] = true; // add NOT boolean to args
                return call_user_func_array(array($this, $matches[1]), $args);
            }
        }
        die("No method with name: $name<br/>");
    }

}

$t = new Test();
$t->testing();
$t->notTesting();

echo "exists: ".method_exists($t, 'notTesting').'<br/>';
echo "callable: ".is_callable(array($t, 'notTesting'));

?>

Output:

testing - not: false
testing - not: true
exists:
callable: 1
Constantin Kpplinger 10-Jun-2010 12:16
It seems the only issue left with is_callable() is the disable_functions ini-setting. Apart from that, is_callable() will reliably evaluate whether the passed function or method can be called from within the same context is_callable() was called from, taking visibility and inheritance into account. This includes functions, regular and static methods, magic functions and methods and implemented interfaces (which are regular methods within the implementing class anyway).

<?php
function regular_function() {}

abstract class ParentTest
{
    public function public_parent_method() {}
    protected function protected_parent_method() {}
    public static function static_method() {}
    protected static function protected_static_method() {}
}

class CallableTest extends ParentTest implements Countable
{
    public function __invoke() { } // Introduced in 5.3, see http://php.net/manual/language.oop5.magic.php
    protected function protected_method() { }
    public function is_callable($args)
    {
        return is_callable($args);
    }
    // Countable
    public function count()
    {
        return 1;
    }
}

$o = new CallableTest();

// Regular function:
var_dump(is_callable('regular_function')); // true

// Magic __invoke method:
var_dump(is_callable($o)); // true if PHP >= 5.3, false otherwise

// Countable implementation (regular method really):
var_dump(is_callable(array($o, 'count'))); // true

// Protected method from outside the object's scope:
var_dump(is_callable(array($o, 'protected_method'))); // false

// Protected method from inside the object's scope via public proxy method:
var_dump($o->is_callable(array($o, 'protected_method'))); // true

// Parent's public method
var_dump(is_callable(array($o, 'public_parent_method'))); // true

// Parent's protected method
var_dump(is_callable(array($o, 'protected_parent_method'))); // false

// Parent's protected method via proxy
var_dump($o->is_callable(array($o, 'protected_parent_method'))); // true

// Parent's static public method
var_dump(is_callable('CallableTest::static_method')); // true

// Parent's static protected method
var_dump(is_callable('CallableTest::protected_static_method')); // false

// Parent's static protected method via proxy
var_dump($o->is_callable('CallableTest::protected_static_method')); // true
?>

Tested PHP versions were 5.2.9 on openSUSE 10.3 (x64) and 5.3.1 on Windows Server 2003 (x86).
juand at softwarecubes dot com 21-Feb-2009 11:39
Revised function with static support:

<?php
    /**
    * The is_callable php function only considers methods declared in the class itself, and ignores the parent's.
    * This version considers all of the hierarchy.
    *
    * @param (string|Object) $class_name
    * @param string $method_name
    * @param bool $static the method being tested is static.
    */
    public static function isCallable( $class_name, $method_name, $static = false ){

        if( !is_string( $class_name ) ){
            $class_name = get_class( $class_name );
        }

        // Define Callable
        if( $static ){
            $callable = "{$class_name}::{$method_name}";
        }else{
            $callable = array( $class_name, $method_name );
        }

        // Check class itself
            if( @is_callable( $callable ) === true ){
                if( $method_name == 'setEmailAddressTypeHash' ) {
                    ErrorHandler::preDump($callable);
                }
                return true;
            }

        // Check all parents
            while( $parent_class = get_parent_class( $class_name ) ){
                if( @is_callable( $callable ) === true ){
                    return true;
                }
                $class_name = $parent_class;
            }

        return false;
    }
?>
Rafael M. Salvioni 20-May-2008 09:10
The PHP's function is_callable not verify the visibility of the tested method.

The following function uses the Reflection classes of the PHP5 to check it.

<?php

/**
 * Function is_callback().
 *
 * @param mixed $var Var
 * @return bool
 */
function is_callback($var)
{
    if (is_array($var) && count($var) == 2) {
        $var = array_values($var);
        if ((!is_string($var[0]) && !is_object($var[0])) || (is_string($var[0]) && !class_exists($var[0]))) {
            return false;
        }
        $isObj = is_object($var[0]);
        $class = new ReflectionClass($isObj ? get_class($var[0]) : $var[0]);
        if ($class->isAbstract()) {
            return false;
        }
        try {
            $method = $class->getMethod($var[1]);
            if (!$method->isPublic() || $method->isAbstract()) {
                return false;
            }
            if (!$isObj && !$method->isStatic()) {
                return false;
            }
        } catch (ReflectionException $e) {
            return false;
        }
        return true;
    } elseif (is_string($var) && function_exists($var)) {
        return true;
    }
    return false;
}

?>
rahadotaboulfethatgmail.com 01-Mar-2008 04:44
is_callable generates an [E_STRICT] error if the  tested method cannot be called staticly. (and returns the good value)

I used @is_called
i'm using php 5.2.1
Quis strrev TA omicidio strrev TOD com 13-Nov-2007 03:50
is_callable() does _not_ check wheter this function is disabled by php.ini's disable_functions

use:

<?PHP
function is_disabled($function) {
  $disabled_functions=explode(',',ini_get('disable_functions'));
  return in_array($function, $disabled_functions);
}
?>

I`m running PHP 5.2.4
mw at NO-SPAM hire mason wolf dot com 19-Oct-2007 07:35
As empyone noted, early versions of php 5 incorrectly returned true if is_callable checked on a protected or private method. Later versions of php 5 will now only return true if the method is public and can be called externally. I do not know precisely when this behavior was changed, so you may have to test on your own. But sometime between 5.0.4, which empyone said he was using, and 5.2.4 where I tested it myself, the behavior was modified.
hcblue 24-Aug-2006 01:51
True that method_exists() is faster than is_callable(). However, is_callable() will be able to correctly recognize method calls handled by __call() in PHP 5, while method_exists() will not.
jphp at dsf dot org dot uk 12-Feb-2006 03:38
bob at theshirdshift:

"function_exists" doesn't do this, no, but "method_exists" works fine, and is still faster than is_callable:

<?php
function doTimes($start, $end)
  {
   $start_time = explode (" ", $start);
   $start_time = $start_time[1] + $start_time[0];
   $end_time = explode (" ", $end);
   $end_time = $end_time[1] + $end_time[0];
   $time = $end_time - $start_time;
   return $time;
  }

class test
  {
     function test()
     {
         return true;
     }
  }

$test = new test;

$callableIsTrue = false;
$startIsCallable = microtime();
for($i = 0; $i < 10000; $i++)
  {
     if(is_callable(array('test', 'test'))) { $callableIsTrue = true; }
  }
$endIsCallable = microtime();

$existsIsTrue = false;
$startExists = microtime();
for($i = 0; $i < 10000; $i++)
  {
     if(method_exists('test', 'test')) { $existsIsTrue = true; }
  }
$endExists = microtime();

$timeIsCallable = doTimes($startIsCallable, $endIsCallable);
$timeExists    = doTimes($startExists, $endExists);

echo "<b>is_callable = ".($callableIsTrue ? "TRUE" : "FALSE")."</b>, \n";
echo "<b>method_exists = ".($existsIsTrue ? "TRUE" : "FALSE")."</b><br>\n";

echo "<br>Did 10000 is_callables in ".$timeIsCallable." seconds";
echo "<br>Did 10000 method_exists in ".$timeExists." seconds";
?>

is_callable = TRUE, method_exists = TRUE

Did 10000 is_callables in 0.410346984863 seconds
Did 10000 method_exists in 0.175447940826 seconds
yetanotheruser at hotmail etc 15-Dec-2005 06:47
I have come across a strange oddity in versions around the 4.3.11 mark - I may have missunderstood the purpose of this function but hope this'll be helpful for some.

The point the code below is supposed to illustrate is that in some cases with

    <? $myFunc = Array( $myObj, 'myMethod' ); ?>

    <? is_callable( $myFunc, true, $callMe ); ?>

will return true, and give you $callMe set to myObj::myMethod but calling

    <? $callMe(); ?>

doesn't work... however calling

    <? $myFunc[0]->$myFunc[1](); ?>

seems to work fine..

... the reason all the code is down there is I think this oddity is due to how/the order in which I've instantiated my classes or something...

anyhow... HTH someone! :-)

Code follows:

FILE 1 :
<?
    include('myTools');

    $foo = new myClass();

    print $foo->getMySource();

    class myClass{

        var $flibble = 'wibble';

        function myClass(
            // Initialise loads of stuff.. including..
            $this->tools = new myTools();
        )

        function getMySource(){
            // This just returns the source.. ok, like some HTML to go into an email for example.
            // Some arguments;
            $args   = $this->flibble;
            // Call our Tool that returns the source..
            $source = $this->tools->returnSource( Array ( $this, 'someHTML' ), $args );
            // and return it..
            return ( $source );
        }

        function someHTML($args){
            // Leave PHP
            ?>
            Here is some HTML.. that we want to build outside a PHP block,
            possibly just cos it's tidier in <B>your favourite text editor</B>..
            .. or you want this function to be elsewhere.. for your designers
            to play with etc.. ... incidentally I'd like to say "<?=$args?>" etc.
            <?
            // .. and we're back.
        }
    }

?>

FILE 2:

<?
    /* OK - this is some other big library and a whole load more
       faff but this is the particular function in question... it
       just calls the function it's been asked to and uses an output
       buffer to grab the output and return it as a string rather than
       letting it go to terminal/browser.... useful for grabbing PHP pages
       for spidering, emailing etc. etc. etc..
    */

    class myTools(){

        function returnSource($func, $args){

            if ( is_callable ( $func, true, $callMe ){
                // Start a buffer
                ob_start();
                // Calling the function like this DOESN'T seem to work:
                // ~~~~~~~~
                // "Command not found : myClass::someHTML"
                // $callMe($args);
                // ~~~~~~~~
                // But - what I've discovered is that this behaves fine..
                if ( is_array($func) ){
                    $func[0]->$func[1]($args);
                } else {
                    $func($args);
                }
                // Then we just carry on with our code..
                $rtn =     ob_get_contents();
                ob_clean();
                return ( $rtn );
            } else {
                error_log("Doh!");
            }
        }
    }

?>
empyone at tiscalinet dot it 08-Nov-2005 12:41
To corey at eyewantmedia dot com:

your misunderstanding lies in passing in the naked $object parameter. It is correct for is_callable to return FALSE since you cannot 'call an object', you can only call one of its methods, but you don't specify which one. Hence:

is_callable(array($object, 'some_function'), [true or false], $callable_name)

will yield the correct result.

Notice, though, that a quick test I made (PHP 5.0.4) showed that is_callable incorrectly returns TRUE also if you specify the name of a protected/private method from outside of the context of the defining class, so, as wasti dot redl at gmx dot net pointed out, reflection is the way to go if you want to take visibility into account (which you should for true OOP, IMHO).
wasti dot redl at gmx dot net 09-Oct-2005 04:14
The way to discover whether a method exists in face of a __call is reflection.

It should be mentioned that although array('Test', 'func') is callable according to this function (where func is a public static method of Test), actually calling this construct as $fn() fails.
corey at eyewantmedia dot com 18-Mar-2005 03:39
I've been spending a month on and off trying to figure out why

is_callable($object, [true or false], $varContainingFunctionName)

returned false when it should not have (ie: $object->FunctionName() was callable), I realized I must have misunderstood its purpose. If you find yourself in the same situation, try

function_exists(string functionname)

or

method_exists ( object object, string method_name )

before you rip your hair out :)
mcroghan at digitalkeg dot com 10-Feb-2005 07:36
Be careful when using this function and __call (PHP5).  This function will always report true when using __call.

Need a specific function for the purpose of checking if a class method exists explicitly even when using __call.

Haven't ruled out the possibility of the existence of such a function yet.  So if someone knows of one, please point it out.
bob at thethirdshift dot net 23-Jun-2004 09:54
I, too, was wondering whether is_callable or function exists is faster when checking class methods.  So, I setup the following test:

<?php
function doTimes($start, $end)
  {
    $start_time = explode (" ", $start);
    $start_time = $start_time[1] + $start_time[0];
    $end_time = explode (" ", $end);
    $end_time = $end_time[1] + $end_time[0];
    $time = $end_time - $start_time;
    return $time;
  }

class test
  {
      function test()
      {
          return true;
      }
  }

$callableIsTrue = false;
$startIsCallable = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(is_callable(array('test', 'test'))) { $callableIsTrue = true; }
  }
$endIsCallable = microtime();

$existsIsTrue = false;
$startExists = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(function_exists('test::test')) { $existsIsTrue = true; }
  }
$endExists = microtime();

$timeIsCallable = doTimes($startIsCallable, $endIsCallable);
$timeExists     = doTimes($startExists, $endExists);

echo "<b>is_callable = ".($callableIsTrue ? "TRUE" : "FALSE")."</b>, \n";
echo "<b>function_exists = ".($existsIsTrue ? "TRUE" : "FALSE")."</b><br>\n";

echo "<br>Did 10000 is_callables in ".$timeIsCallable." seconds";
echo "<br>Did 10000 function_exists in ".$timeExists." seconds";
?>

This gives the output :

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0640790462494 seconds
Did 10000 function_exists in 0.0304429531097 seconds

So the fact that function_exists is twice as fast is slightly over shadowed by the fact that it doesn't work on class methods, at least not as far as I can tell.


Verifica que el contenido de una variable es un valor contable

  • « is_callable
  • is_double »
  • PHP Manual
  • Funciones de manejo de variables
  • Verifica que el contenido de una variable es un valor contable

is_countable

(PHP 7 >= 7.3.0, PHP 8)

is_countable — Verifica que el contenido de una variable es un valor contable

Descripción

is_countable ( mixed $var ) : bool

Verifica que el contenido de una variable es un array o un objeto implementando Countable

Parámetros

var

El valor a comprobar

Valores devueltos

Devuelve true si var es contable, false en caso contrario.

Historial de cambios

Versión | Descripción
7.3.0 | is_countable() ha sido añadido.

Ejemplos

Ejemplo #1 ejemplos de 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)

Ver también

  • is_array() - Comprueba si una variable es un array
  • is_object() - Comprueba si una variable es un objeto
  • is_iterable() - Verifica que el contenido de una variable es un valor iterable
  • is_bool() - Comprueba si una variable es de tipo booleano

User Contributed Notes

info at ensostudio dot ru 25-Oct-2020 06:29
Note: if is_countable() return true is does not guarantee that the it can be calculated recursively and correctly:
<?php
$iterator = new ArrayIterator(['one', 'two', new ArrayIterator(['three', 'four'])]);
var_dump(is_countable($iterator), count($iterator, COUNT_RECURSIVE));
// return TRUE and 3!
?>
Anonymous 25-Oct-2020 04:58
Fixed polyfill:
<?php
if (! function_exists('is_countable')) {
    /**
      * @param mixed $value The value to check
      * @return bool
      */
    function is_countable($value): bool
    {
        return is_array($value) || (is_object($value) && $value instanceof Countable);
    }
}
?>
renic 12-Jun-2019 08:33
be wary of using is_object($var) and assuming that the object has implemented Countable.  Not all objects are countable directly with count().
danmichaelo at gmail dot com 08-Apr-2019 08:33
Note that a polyfill for this method is also provided by the symfony/polyfill project.
deoomen 01-Apr-2019 11:58
Polyfill written by arisendrake is not quite good. It return FALSE when checking an Simple XML Node but count() works properly on PHP 7.1 and 7.3.
Better is this one:

<?php
if (version_compare(PHP_VERSION, "7.3") < 0 && !function_exists("is_countable")) {
    function is_countable($var): bool
    {
        return (is_array($var) || is_object($var) || is_iterable($var) || $var instanceof Countable);
    }
}
?>
info at arisendrake dot de 30-Aug-2018 11:10
If you are unable to upgrade to PHP 7.3 (not released at the time of writing), you can use this simple polyfill:

<?php
if (!function_exists('is_countable')) {
    function is_countable($var) {
        return (is_array($var) || $var instanceof Countable);
    }
}
?>


Alias de is_float

  • « is_countable
  • is_float »
  • PHP Manual
  • Funciones de manejo de variables
  • Alias de is_float

is_double

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

is_double — Alias de is_float()

Descripción

Esta función es un alias de: is_float().

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el tipo de una variable es float

  • « is_double
  • is_int »
  • PHP Manual
  • Funciones de manejo de variables
  • Comprueba si el tipo de una variable es float

is_float

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

is_float — Comprueba si el tipo de una variable es float

Descripción

is_float ( mixed $var ) : bool

Comprueba si el tipo de variable dado es float.

Nota:

Para comprobar si una variable es un número o un string numérico (por ejemplo, un formulario de entrada, que es siempre un string), debe utilizar is_numeric().

Parámetros

var

La variable a ser evaluada.

Valores devueltos

Devuelve true si var es de tipo float, o false de lo contrario.

Ejemplos

Ejemplo #1 Ejemplo de is_float()

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));  //Notación Científica
var_dump(is_float(true));
?>

El resultado del ejemplo sería:

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

Ver también

  • is_bool() - Comprueba si una variable es de tipo booleano
  • is_int() - Comprueba si el tipo de una variable es integer
  • is_numeric() - Comprueba si una variable es un número o un string numérico
  • is_string() - Comprueba si una variable es de tipo string
  • is_array() - Comprueba si una variable es un array
  • is_object() - Comprueba si una variable es un objeto

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


Comprueba si el tipo de una variable es integer

  • « is_float
  • is_integer »
  • PHP Manual
  • Funciones de manejo de variables
  • Comprueba si el tipo de una variable es integer

is_int

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

is_int — Comprueba si el tipo de una variable es integer

Descripción

is_int ( mixed $var ) : bool

Comprueba si el tipo de variable dado es integer.

Nota:

Para comprobar si una variable es un número o un string numérico (por ejemplo, un formulario de entrada, que es siempre un string), debe utilizar is_numeric().

Parámetros

var

La variable a ser evaluada.

Valores devueltos

Devuelve true si var es de tipo integer, o false de lo contrario.

Ejemplos

Ejemplo #1 Ejemplo de 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));
}
?>

El resultado del ejemplo sería:

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)

Ver también

  • is_bool() - Comprueba si una variable es de tipo booleano
  • is_float() - Comprueba si el tipo de una variable es float
  • is_numeric() - Comprueba si una variable es un número o un string numérico
  • is_string() - Comprueba si una variable es de tipo string
  • is_array() - Comprueba si una variable es un array
  • is_object() - Comprueba si una variable es un objeto

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
  • Funciones de manejo de variables
  • Alias de is_int

is_integer

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

is_integer — Alias de is_int()

Descripción

Esta función es un alias de: is_int().

User Contributed Notes

ru dot mahmoud at mail dot ru 17-Jan-2019 08:05
using function :

if(is_integer($_POST[mobile_number])){
 return true; //// 0-9
}else{
 echo "Wrong number";
return false;
}
gldbrzent at gmail dot com 24-Sep-2017 07:37
There are two different functions.  But, the reason why is beyond the scope of this article!
being dot juan at icloud dot com 26-Jul-2017 05:07
There is no difference, per se. is_integer() is an alias of is_int().


Verifica que el contenido de una variable es un valor iterable

  • « is_integer
  • is_long »
  • PHP Manual
  • Funciones de manejo de variables
  • Verifica que el contenido de una variable es un valor iterable

is_iterable

(PHP 7 >= 7.1.0, PHP 8)

is_iterable — Verifica que el contenido de una variable es un valor iterable

Descripción

is_iterable ( mixed $var ) : bool

Verifica que el contenido de una variable es aceptado por el pseudo-tipo iterable, p.e. que es o bien un array o un objeto implementando Traversable

Parámetros

var

El valor a comprobar

Valores devueltos

Devuelve true si var es iterable, false en caso contrario.

Ejemplos

Ejemplo #1 ejemplos de 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)

?>

Ver también

  • is_array() - Comprueba si una variable es un array

User Contributed Notes

mopsyd at me dot com 01-Apr-2018 04:24
A slight correction to brcontainer's polyfill, which prevents errors on a non-object in a non-blocking way, and also corrects the issue of  the conditional checking "file_exists" instead of the correct "function_exists":

if ( !function_exists(  'is_iterable' ) )
{

    function is_iterable( $obj )
    {
        return is_array( $obj ) || ( is_object( $obj ) && ( $obj instanceof \Traversable ) );
    }

}

The original answer would not have resolved correctly, because it was looking for a file instead of a function, and the provided method would error if given a non-iterable non-object value such as false.
brcontainer at yahoo dot com dot br 09-Mar-2018 08:35
Polyfill for PHP5.6 and PHP7.0

    if (!file_exists('is_iterable')) {
        function is_iterable($obj)
        {
            return is_array($obj) || $obj instanceof \Traversable;
        }
    }
anatoly dot pashin at gmail dot com 01-Feb-2018 07:02
Here is more details on iterable type: http://php.net/manual/en/language.types.iterable.php


Alias de is_int

  • « is_iterable
  • is_null »
  • PHP Manual
  • Funciones de manejo de variables
  • Alias de is_int

is_long

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

is_long — Alias de is_int()

Descripción

Esta función es un alias de: is_int().

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si una variable es null

  • « is_long
  • is_numeric »
  • PHP Manual
  • Funciones de manejo de variables
  • Comprueba si una variable es null

is_null

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

is_null — Comprueba si una variable es null

Descripción

is_null ( mixed $var ) : bool

Comprueba si la variable dada es null.

Parámetros

var

La variable a ser evaluada

Valores devueltos

Devuelve true si var es null, false de lo contrario.

Ejemplos

Ejemplo #1 Ejemplo is_null()

<?php

error_reporting(E_ALL);

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

?>
Aviso: Variable indefinida: inexistente en ...
bool(true)
bool(true)

Ver también

  • El tipo null
  • isset() - Determina si una variable está definida y no es null
  • is_bool() - Comprueba si una variable es de tipo booleano
  • is_numeric() - Comprueba si una variable es un número o un string numérico
  • is_float() - Comprueba si el tipo de una variable es float
  • is_int() - Comprueba si el tipo de una variable es integer
  • is_string() - Comprueba si una variable es de tipo string
  • is_object() - Comprueba si una variable es un objeto
  • is_array() - Comprueba si una variable es un array

User Contributed Notes

etimjoshua4 at gmail dot com 20-Jan-2021 05:09
I've found that for HTTP requests such as POST, is_null isn't the most reliable choice for checking if empty.

Try using

if(trim($var) == ""){
    // do something
}

instead.

I think the request does something to the input that makes it definitely not NULL.
contact dot 01834e2c at renegade334 dot me dot uk 25-May-2015 06:57
In PHP 7 (phpng), is_null is actually marginally faster than ===, although the performance difference between the two is far smaller.

PHP 5.5.9
is_null - float(2.2381200790405)
===     - float(1.0024659633636)
=== faster by ~100ns per call

PHP 7.0.0-dev (built: May 19 2015 10:16:06)
is_null - float(1.4121870994568)
===     - float(1.4577329158783)
is_null faster by ~5ns per call
normadize (a) gmail (d) com 07-Jul-2012 10:08
Using === NULL instead of is_null(), is actually useful in loaded server scenarios where you have hundreds or thousands of requests per second. Saving microseconds on a lot of "simple" operations in the entire PHP execution chain usually results in being able to serve more pages per second at the same speed, or lowering your cpu usage. People usually write very bad and slow code.
george at fauxpanels dot com 01-Dec-2008 01:58
See how php parses different values. $var is the variable.

$var        =    NULL    ""    0    "0"    1

strlen($var)    =    0    0    1    1    1
is_null($var)    =    TRUE    FALSE    FALSE    FALSE    FALSE
$var == ""    =    TRUE    TRUE    TRUE    FALSE    FALSE
!$var        =    TRUE    TRUE    TRUE    TRUE    FALSE
!is_null($var)    =    FALSE    TRUE    TRUE    TRUE    TRUE
$var != ""    =    FALSE    FALSE    FALSE    TRUE    TRUE
$var        =    FALSE    FALSE    FALSE    FALSE    TRUE

Peace!
Malfist 01-Jul-2008 07:54
Micro optimization isn't worth it.

You had to do it ten million times to notice a difference, a little more than 2 seconds

$a===NULL; Took: 1.2424390316s
 is_null($a); Took: 3.70693397522s

difference = 2.46449494362
difference/10,000,000 = 0.000000246449494362

The execution time difference between ===NULL and is_null is less than 250 nanoseconds. Go optimize something that matters.
strrev xc.noxeh@ellij 03-Jun-2008 05:42
$var===NULL is much faster than is_null($var) (with the same result)

I did some benchmarking with 10 million iterations:

$a=null;
 isset($a); Took: 1.71841216087s
 $a==NULL; Took: 1.27205181122s
 $a===NULL; Took: 1.2424390316s
 is_null($a); Took: 3.70693397522s
$a=5;
 isset($a); Took: 1.15165400505s
 $a==NULL; Took: 1.41901302338s
 $a===NULL; Took: 1.21655392647s
 is_null($a); Took: 3.78501200676s
error_reporting(E_ALL&~E_NOTICE);
unset($a);
 isset($a); Took: 1.51441502571s
 $a==NULL; Took: 16.5414860249s
 $a===NULL; Took: 16.1273870468s
 is_null($a); Took: 23.1918480396s

Please note, that isset is only included because it gives a good performance in any case; HOWEVER isset is NOT the same, or the opposite.
But you might be able to use isset() instead of null-checking.

You should not use is_null, except when you need a callback-function, or for conformity with is_int, is_float, etc.
ai dot unstmann at combase dot de 14-Jan-2008 12:17
For what I realized is that  is_null($var)  returns exactly the opposite of  isset($var) , except that is_null($var) throws a notice if $var hasn't been set yet.

the following will prove that:

<?php

$quirks = array(null, true, false, 0, 1, '', "\0", "unset");

foreach($quirks as $var) {
    if ($var === "unset") unset($var);

    echo is_null($var) ? 1 : 0;
    echo isset($var) ? 1 : 0;
    echo "\n";
}

?>

this will print out something like:

10    // null
01    // true
01    // false
01    // 0
01    // 1
01    // ''
01    // "\0"
Notice:  Undefined variable: var in /srv/www/htdocs/sandbox/null/nulltest.php on line 8
10    // (unset)

For the major quirky types/values is_null($var) obviously always returns the opposite of isset($var), and the notice clearly points out the faulty line with the is_null() statement. You might want to examine the return value of those functions in detail, but since both are specified to return boolean types there should be no doubt.

A second look into the PHP specs tells that is_null() checks whether a value is null or not. So, you may pass any VALUE to it, eg. the result of a function.
isset() on the other hand is supposed to check for a VARIABLE's existence, which makes it a language construct rather than a function. Its sole porpuse lies in that checking. Passing anything else will result in an error.

Knowing that, allows us to draw the following unlikely conclusion:

isset() as a language construct is way faster, more reliable and powerful than is_null() and should be prefered over is_null(), except for when you're directly passing a function's result, which is considered bad programming practice anyways.
michael at cannonbose dot com 30-Dec-2003 09:42
Regarding avoidance of NULLs in your MySQL queries, why not use  IS NULL and IS NOT NULL in your WHERE clauses.

SELECT *
FROM someDatabase
WHERE someAttribute IS NOT NULL

Cheers,

Michael
uioreanu at hotmail dot com 23-Mar-2001 06:36
Don't try to test
if ($intSomething==NULL) {
 ...
}
use is_null() instead.
The first statement misses 0 values.

Regards,
Calin

[Ed. note: this is because == tests for equivalence of value, but not type. NULL evaluates to
false, as does 0, so NULL == 0 is true--even though 0 is type int and NULL is type null.
You should use either is_null() as noted or ===, which returns true only if its operands are
equal and of the same type.]


Comprueba si una variable es un número o un string numérico

  • « is_null
  • is_object »
  • PHP Manual
  • Funciones de manejo de variables
  • Comprueba si una variable es un número o un string numérico

is_numeric

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

is_numeric — Comprueba si una variable es un número o un string numérico

Descripción

is_numeric ( mixed $value ) : bool

Comprueba si la variable dada es numérica o string numérico.

Parámetros

value

La variable a evaluar.

Valores devueltos

Devuelve true si var es un número o una cadena numérica, false de lo contrario.

Ejemplos

Ejemplo #1 Ejemplos de 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) . " es numérico", PHP_EOL;
    } else {
        echo var_export($element, true) . " NO es numérico", PHP_EOL;
    }
}
?>

El resultado del ejemplo sería:

'42' is numérico
1337 is numérico
1337 is numérico
1337 is numérico
1337 is numérico
1337.0 is numérico
'0x539' NO es numérico
'02471' is numérico
'0b10100111001' NO es numérico
'1337e0' is numérico
'not numeric' NO es numérico
array (
) NO es numérico
9.1 is numérico
NULL NO es numérico

Ver también

  • String numérico
  • ctype_digit() - Chequear posibles caracteres numéricos
  • is_bool() - Comprueba si una variable es de tipo booleano
  • is_null() - Comprueba si una variable es null
  • is_float() - Comprueba si el tipo de una variable es float
  • is_int() - Comprueba si el tipo de una variable es integer
  • is_string() - Comprueba si una variable es de tipo string
  • is_object() - Comprueba si una variable es un objeto
  • is_array() - Comprueba si una variable es un array

User Contributed Notes

rds88 10-Mar-2021 01:46
Notice that not only are leading spaces valid, but pretty much all whitespace characters and any combination thereof seems to be valid.

Examples (999 is the actual number), verified in PHP 7.3.x:

%09999 - a leading horizontal tabulator followed by the number
%20999 - a leading space followed by the number
%09%20999 - a leading tab, followed by a space, followed by the number
orcinus 22-Aug-2019 09:37
This page is a hot mess.

The changes note states:

“7.0.0    Strings in hexadecimal (e.g. 0xf4c3b00c) notation are no longer regarded as numeric strings, i.e. is_numeric() returns FALSE now.”

Meanwhile, the description says:

“Hexadecimal (e.g. 0xf4c3b00c) *and binary* (e.g. 0b10100111001) notation is not allowed.”

And finally, the examples section claims both are TRUE for is_binary.
What the hell?
sandreas 21-Feb-2019 10:48
Note that strings with leading zeros containing only digits also return true on check with is_numeric, although they might be not a valid number. Example:

<?php
$x = 009; // this is invalid php code, 009 is not octal
$y = 007; // this is valid php code, 007 is octal
$z = 01.12; // this also is valid php code

var_dump(is_numeric("009")); // outputs true
var_dump(is_numeric("007")); // outputs true
var_dump(is_numeric("00.12")); // outputs true
?>
Ray.Paseur sometimes uses Gmail 19-Dec-2018 08:50
intval() appears to be helpful with hex strings:

<?php // is_hex_numeric.php
/**
 * PHP 7.0.0+ Strings in hexadecimal (e.g. 0xf4c3b00c) notation
 * are no longer regarded as numeric strings, i.e. is_numeric() returns FALSE now.
 * See: http://php.net/manual/en/function.intval.php
 */
error_reporting(E_ALL);

var_dump( PHP_VERSION );              // string(6) "7.1.25"
var_dump( PHP_INT_SIZE );             // int(8)

$x = 0xf4c3b00c;                      // --> Assignment of hex value
var_dump($x);                         // int(4106465292)
var_dump( is_numeric($x) );           // bool(true)

$y = '0x' . dechex($x);               // --> Convert hex value to a string
var_dump($y);                         // string(10) "0xf4c3b00c"
var_dump( is_numeric($y) );           // bool(false)

$z = intval($y, 0);                   // --> intval() with base zero recognizes hex notation
var_dump($z);                         // int(4106465292)
var_dump( is_numeric($z) );           // bool(true)
var_dump($x == $z);                   // bool(true)
phil at kiwilimon dot com 07-May-2018 04:43
There is another not documented big difference between PHP 5 and PHP 7:
is_numeric("45 "); // with a space at the end
will return true on PHP 5 and false on PHP 7
za at byza dot it 26-Sep-2017 02:21
To check if a numeric string is a valid integer or float number:

function is_valid_number($a) {
   return $a==(float)$a && strlen($a)==strlen((float)$a);
}

This returns false for "0012345" and true for "0.12345"
cottton 05-Feb-2017 02:20
As of http://php.net/manual/de/function.is-numeric.php#111709
' 12345' is considered numeric.

BUT '12345 ' NOT.

Test:
<?php
foreach (
    [
        ' 12345',
        '12345 ',
        ' 12345 ',
    ] as $value

) {
    echo "'{$value}'\t" . var_export(is_numeric($value), true) . PHP_EOL;
}
/**
 * Output:
 *
 *  ' 12345'        true
 *  '12345 '        false
 *  ' 12345 '       false
 */
?>
tanguy_barsik at hotmail dot com 03-Feb-2017 03:22
for strings, it return true only if float number has a dot

is_numeric( '42.1' )//true
is_numeric( '42,1' )//false
Vasiliy Makogon 08-Apr-2016 08:22
If you want detect integer of float values, which presents as pure int or float, and presents as string values, use this functions:

<?php
function isInteger($val)
{
    if (!is_scalar($val) || is_bool($val)) {
        return false;
    }
    if (is_float($val + 0) && ($val + 0) > PHP_INT_MAX) {
        return false;
    }
    return is_float($val) ? false : preg_match('~^((?:\+|-)?[0-9]+)$~', $val);
}

function isFloat($val)
{
    if (!is_scalar($val)) {
        return false;
    }
    return is_float($val + 0);
}

foreach ([
    '11111111111111111', 11111111111111111, // > PHP_INT_MAX - presents in PHP as float
    1, '10', '+1', '1.1', 1.1, .2, 2., '.2', '2.',
    '-2.', '-.2', null, [], true, false, 'string'
] as $value) {
    echo $value . ':' . gettype($value) . ' is Integer? - '  . (isInteger($value) ? 'yes' : 'no') . PHP_EOL;
    echo $value . ':' . gettype($value) . ' is Float? - '  . (isFloat($value) ? 'yes' : 'no') . PHP_EOL;
}
?>

Output:

11111111111111111:string is Integer? - no
11111111111111111:string is Float? - yes
1,1111111111111E+16:double is Integer? - no
1,1111111111111E+16:double is Float? - yes
1:integer is Integer? - yes
1:integer is Float? - no
10:string is Integer? - yes
10:string is Float? - no
+1:string is Integer? - yes
+1:string is Float? - no
1.1:string is Integer? - no
1.1:string is Float? - yes
1,1:double is Integer? - no
1,1:double is Float? - yes
0,2:double is Integer? - no
0,2:double is Float? - yes
2:double is Integer? - no
2:double is Float? - yes
.2:string is Integer? - no
.2:string is Float? - yes
2.:string is Integer? - no
2.:string is Float? - yes
-2.:string is Integer? - no
-2.:string is Float? - yes
-.2:string is Integer? - no
-.2:string is Float? - yes
:NULL is Integer? - no
:NULL is Float? - no
Array:array is Integer? - no
Array:array is Float? - no
1:boolean is Integer? - no
1:boolean is Float? - no
:boolean is Integer? - no
:boolean is Float? - no
string:string is Integer? - no
string:string is Float? - no
vikramverma214 at gmail dot com 26-Dec-2015 06:24
check if given string is mobile number

function filterNumber($str)
        {
            //remove non number
            $count = strlen($str);
            $newNumber = "";
            for($i = 0; $i<$count; $i++)
            {
                if(is_numeric($str[$i]))
                    $newNumber .= $str[$i];
            }

            //removes leading 0s
            $newNumber = ltrim($newNumber, '0');

            //remove 91 in starting, 91 is specific to Indian Numbers
            if(strlen($newNumber) == 12)
            {
                if(substr($newNumber, 0, 2) == '91')
                    $newNumber = substr($newNumber, 2);
            }

            //final check for length 10
            if(strlen($newNumber) != 10 )
                return null;
            else
                return $newNumber;
        }
lihatskiym at gmail dot com 30-Sep-2015 11:26
Check that value is whole numeric or is whole integer.
<?php
function whole_numeric($val)
{
    if (is_numeric($val)
        && floor($val) == $val)
    {
        if ((string)$val === (string)0)
            return true;
        elseif(ltrim((string)$val, '0') === (string)$val)
            return true;
    }

    return false;
}

function whole_int($val)
{
    $val = strval($val);
    $val = str_replace('-', '', $val);

    if (ctype_digit($val))
    {
        if ($val === (string)0)
            return true;
        elseif(ltrim($val, '0') === $val)
            return true;
    }

    return false;
}
?>

Result will be like this:

<?php
whole_numeric('-1.0');  // true
whole_numeric(0);        // true
whole_numeric('0');      // true
whole_numeric('00');     // false
whole_numeric(1);        // true
whole_numeric('1');      // true
whole_numeric('1.0');    // true
whole_numeric('1,0');    // false
whole_numeric('1.2');    // false
whole_numeric('001');    // false
whole_numeric(array()); // false

whole_int('-1.0');    // false
whole_int('-1');       // true
whole_int(0);          // true
whole_int('0');        // true
whole_int('00');      // false
whole_int(1);          // true
whole_int('1');         // true
whole_int('1.0');      // false
whole_int('1.2');      // false
whole_int('001');     // false
whole_int(array()); // false
?>
Tim Robert-Fitzgerald 26-Jun-2015 11:17
Be careful when using `is_numeric()` to validate user input and protect against SQL injection. According to wiki.hashphp.org,

"Many people reach for is_numeric() thinking this is a good approach, and it will seem to work just fine. However the problem with is_numeric() isn't that it can't detect an integer, it is that it detects a lot more than just integers. All of the following are valid numbers to is_numeric():

- 1
- 1.123
- 0xFF
- +0123.45e6

See the problem? If we really want just an integer, this function is too broad."

Source: http://wiki.hashphp.org/Validation#Why_is_numeric.28.29_is_bad
charlike dot mike at mail dot bg 03-Feb-2014 04:24
I think that is best check solution if u want to create real calculator for example :)

<?php
function is_number($var)
{
    if ($var == (string) (float) $var) {
        return (bool) is_numeric($var);
    }
    if ($var >= 0 && is_string($var) && !is_float($var)) {
        return (bool) ctype_digit($var);
    }
    return (bool) is_numeric($var);
}

is_number(12); // true
is_number(-12); // true
is_number(-12.2); // true
is_number("12"); // true
is_number("-124.3"); // true
is_number(0.8); // true
is_number("0.8"); // true
is_number(0); // true
is_number("0"); // true
is_number(NULL); // false
is_number(true); // false
is_number(false); // false
is_number("324jdas32"); // false
is_number("123-"); // false
is_number(1e7); // true
is_number("1e7"); // true
is_number(0x155); // true
is_number("0x155"); // false
?>
ben at chico dot com 07-Jan-2014 11:20
Apparently NAN (Not A Number) is a number for the sake of is_numeric().

<?php
echo "is ";
if (!is_numeric(NAN))
 echo "not ";
 echo "a number";
?>

Outputs "is a number". So something that is NOT a number (by defintion) is a number...
jsnell at e-normous dot com 19-Mar-2013 09:38
Note that this function handles leading spaces differently than is_int(), is_float(), is_real(), is_long(), and is_double().

is_numeric(" 12345") = true
is_int(" 12345") = false
is_float(" 12345") = false
is_real(" 12345") = false
is_long(" 12345") = false
is_double(" 12345") = false
jeffvanhees at gmail dot com 19-Jun-2012 05:20
Function for checking all the values in an array for being numeric:

<?php
function is_numeric_array($array) {
    foreach ($array as $key => $value) {
        if (!is_numeric($value)) return false;
    }
    return true;
}

$array_not_numeric = array('1', '2', 3, 'a'); // returns false
$array_numeric = array('1', '2', 3, 4); // returns true
?>
dave dot marr at gmail dot com 31-Jan-2012 04:30
If you want the numerical value of a string, this will return a float or int value:

<?php
function get_numeric($val) {
  if (is_numeric($val)) {
    return $val + 0;
  }
  return 0;
}
?>

Example:
<?php
get_numeric('3'); // int(3)
get_numeric('1.2'); // float(1.2)
get_numeric('3.0'); // float(3)
?>
akam at akameng dor com 22-Jan-2012 09:22
<?php
$d = @$_GET['d'];

/*
assuming that passing value of d in the mysql
$sql = "select * from books where bookid = '$d' "
*/

/*
now check if $d is numeric?
*/

if(!is_numeric($d)){
 $d = preg_replace("/[^0-9]+/", "", $d);
}
echo "Cleared value: $d \n<br />Original Vlaue:".@$_GET['d'];
//then using clear value of $d in the mysql query
$sql = "select * from books where bookid = '$d' ";
?>
Example:
?d=52;d;s;s'2233l'[[22

Outpt:

Cleared value: 52223322
Original Vlaue:52;d;s;s'2233l'[[22
sobolanx at gmail dot com 22-Jan-2011 03:55
Note that the function accepts extremely big numbers and correctly evaluates them.

For example:

<?php
    $v = is_numeric ('58635272821786587286382824657568871098287278276543219876543') ? true : false;

    var_dump ($v);
?>

The above script will output:

bool(true)

So this function is not intimidated by super-big numbers. I hope this helps someone.

PS: Also note that if you write is_numeric (45thg), this will generate a parse error (since the parameter is not enclosed between apostrophes or double quotes). Keep this in mind when you use this function.
Martyn Ranyard 10-Jan-2011 04:14
The documentation does not clarify what happens if you the input is an empty string - it correctly returns false in my experience.  Useful to state these odd cases, for when you see code that checks for an empty string and is_numeric, you can tell it's a waste of a comparison.
Nitrogen 11-Sep-2010 10:40
I find it a little weird that people are having issues with ordinal numbers, it's pretty easy..
Notes are in the commenting, check out the example outputs.

<?php

function ordinal($i='') {
  // a temporary value we can change, and keep the original value.
  $o=$i;

  // suffixes = 0th, 1st, 2nd, third == zeroth, first, second, third
  $s=array('th','st','nd','rd');

  // if input just so happens to be a string, we check to make sure it
  // still holds a numeric value and only acquire the last 2 numbers.
  // if it's not a string, nor an integer, we freak out and say no.
  if(!is_int($o))
    if(ctype_digit($o))
      $o=(int)substr($o,-2,2);
    else
      return(false);

  // basically, if $o is between 11 and 19, we use 'th'
  // otherwise we use the last digit and if it's over
  // 4 then we use 0 (for the $s array index).
  return($i.$s[($o%100>10&&$o%100<20)?0:($o%10<4?$o%10:0)]);
}

var_dump(ordinal(5));

/* Example Outputs of ordinal():
  0th, 1st, 2nd, 3rd, 4th, ..., 9th,
  10th, 11th, 12th, 13th, 14th, ..., 19th,
  110th, 111th, ..., 199th, 200th, 201st.

  ordinal('-1'); returns false because ctype_digit hates anything that
  isn't strictly 0 through 9 and '-' trips it to false.

  ordinal('asdf'); returns false for the exact same reason.

  ordinal(); returns false because it's blank.

  signed integers on a 32-bit system (and the same issue on a 64-bit
  system using 0x7FFFFFFFFFFFFFFF because of two's compliment,
  anything higher will become a negative number):
  ordinal(0x7FFFFFFF  ); returns 2147483647th (which is correct)
  ordinal(0x7FFFFFFF+1); returns false.
*/

?>
Kiam 23-Jul-2009 11:02
empty(trim($test, '+-.,0123456789')) doesn't assure you $test contains a number. It returns TRUE also for a string containing ".+1234.56", which is not a valid number.
codeslinger at compsalot dot com 15-Jul-2009 01:34
if speed is important, the liberal use of regex should be avoided, especially complex ones like those here.

For most purposes, this will be sufficient and has the advantages of both speed and clarity.

$BoolResult = empty(trim($Test, '+-.,0123456789'));

If the $Test contains any character that is not a valid part of a number the remaining string will not be empty.

if you want to be more restrictive of the '+-'  then you can use a separate trim for that and nest it.  Keep in mind that some notations pt the sign to the right of the number instead of to the left.  Depending upon your specific application you can also choose to ignore spaces and allow for 'e' notation.

I also use this approach when testing for other character sets such as Hex.
Magnus Deininger, dma05 at web dot de 07-Jan-2009 06:01
regarding the global vs. american numeral notations, it should be noted that at least in japanese, numbers aren't grouped with an extra symbol every three digits, but rather every four digits (for example 1,0000 instead of 10.000). also nadim's regexen are slightly suboptimal at one point having an unescaped '.' operator, and the whole thing could easily be combined into a single regex (speed and all).

adjustments:

<?php
$eng_or_world = preg_match
  ('/^[+-]?'. // start marker and sign prefix
  '(((([0-9]+)|([0-9]{1,4}(,[0-9]{3,4})+)))?(\\.[0-9])?([0-9]*)|'. // american
  '((([0-9]+)|([0-9]{1,4}(\\.[0-9]{3,4})+)))?(,[0-9])?([0-9]*))'. // world
  '(e[0-9]+)?'. // exponent
  '$/', // end marker
  $str) == 1;
?>

i'm sure this still isn't optimal, but it should also cover japanese-style numerals and it fixed a couple of other issues with the other regexen. it also allows for an exponent suffix, the pre-decimal digits are optional and it enforces using either grouped or ungrouped integer parts. should be easier to trim to your liking too.
Elwin van Huissteden 27-Mar-2007 04:05
To James holwell:

Maybe your function was more strickt, but profides FALSE to any numeric string that wasnt written in the English/American notition. To enable a person to use the both the English/American and the rest of the world's way:

<?php
  function my_is_numeric($value)
  {
   return (preg_match ("/\A(-){0, 1}([0-9]+)((,|.)[0-9]{3, 3})*((,|.)[0-9]){0, 1}([0-9]*)\z/" ,$value) == 1);
  }
?>

Other than that, i'd recommend using yours, if it works (i havent tested either yours or mine)
By using mine, there might be a slight chance to not being able to do calculations with the numeric string if it's not the English/American way.

(*Note:
-the E/A way of writing 1 million (with decimal for 1/50): 1,000,000.02
-the global way of writing 1 million (with decimal for 1/50): 1.000.000,02
james.holwell( at )exeter.ox.ac.uk 20-Mar-2007 02:07
In reply to www.kigoobe.com, a more strict expression is

<?php
  function my_is_numeric($value)
  {
    return (preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/", $value) == 1);
  }
?>

This will not match strings like -6,77.8,8 which are matched by the below expression, and instead requires a single decimal point, with at least one character following, and only permits comma-separation when the right hand side is a triplet.
Stephen 25-Jan-2007 09:31
The documentation is not completely precise here. is_numeric will also return true if the number begins with a decimal point  and/or a space, provided a number follows (rather than a letter or punctuation). So, it doesn't necessarily have to start with a digit.
moskalyuk at gmail dot com 21-Aug-2006 10:18
is_numeric fails on the hex values greater than LONG_MAX, so having a large hex value parsed through is_numeric would result in FALSE being returned even though the value is a valid hex number
rontarrant at NO_SPAMsympatico dot ca 23-Jul-2006 07:15
Here's an even simpler pair of functions for finding out if a number is odd or even:

function IS_ODD($number) { return($number & 1); }

function IS_EVEN($number) { return(!($number & 1)); }

Test:
$myNumber = 151;

if(IS_ODD($myNumber))
    echo("number is odd\n");
else
    echo("number is NOT odd\n");

if(IS_even($myNumber))
    echo("number is even\n");
else
    echo("number is NOT even\n");

Results:
number is odd
number is NOT even
andrea dot vacondio at gmail dot com 13-Dec-2005 07:52
Two simple functions using is_numeric:

<?php

 function is_odd($num){
     return (is_numeric($num)&($num&1));
 }

 function is_even($num){
     return (is_numeric($num)&(!($num&1)));
 }

 //examples
echo "1: odd? ".(is_odd(1)? "TRUE": "FALSE")."<br />";
//is_numeric(0) returns true
echo "0: odd? ".(is_odd(0)? "TRUE": "FALSE")."<br />";
echo "6: odd? ".(is_odd(6)? "TRUE": "FALSE")."<br />";
echo "\"italy\": odd? ".(is_odd("italy")? "TRUE": "FALSE")."<br />";
echo "null: odd? ".(is_odd(null)? "TRUE": "FALSE")."<br /><br />";
echo "1: even? ".(is_even(1)? "TRUE": "FALSE")."<br />";
echo "0: even? ".(is_even(0)? "TRUE": "FALSE")."<br />";
echo "6: even? ".(is_even(6)? "TRUE": "FALSE")."<br />";
echo "\"italy\": even? ".(is_even("italy")? "TRUE": "FALSE")."<br />";
echo "null: even? ".(is_even(null)? "TRUE": "FALSE")."<br />";

?>
And here is the result:
1: odd? TRUE
0: odd? FALSE
6: odd? FALSE
"italy": odd? FALSE
null: odd? FALSE

1: even? FALSE
0: even? TRUE
6: even? TRUE
"italy": even? FALSE
null: even? FALSE
jamespam at hotmail dot com 08-Aug-2005 02:31
Here's a function to determine if a variable represents a whole number:

function is_whole_number($var){
  return (is_numeric($var)&&(intval($var)==floatval($var)));
}

just simple stuff...
is_whole_number(2.00000000001); will return false
is_whole_number(2.00000000000); will return true
namik at hub-cafe dot net 29-Jul-2005 06:11
I needed a number_suffix function that takes numbers with thousand seperators (using number_format() function).  Note that this doesn't properly handle decimals.

Example:
<?= number_suffix('1,021') ?> returns: 1,021st

Also, increasing the range above the condition statements increases efficiency.  That's almost 20% of the numbers between 0 and 100 that get to end early.

<?
  function number_suffix($number)
  {
    // Validate and translate our input
    if ( is_numeric($number) )
    {
      // Get the last two digits (only once)
      $n = $number % 100;
    } else {
     // If the last two characters are numbers
     if ( preg_match( '/[0-9]?[0-9]$/', $number, $matches ) )
     {
       // Return the last one or two digits
       $n = array_pop($matches);
     } else {
       // Return the string, we can add a suffix to it
       return $number;
     }
    }
    // Skip the switch for as many numbers as possible.
    if ( $n > 3 && $n < 21 )
      return $number . 'th';

    // Determine the suffix for numbers ending in 1, 2 or 3, otherwise add a 'th'
    switch ( $n % 10 )
    {
      case '1': return $number . 'st';
      case '2': return $number . 'nd';
      case '3': return $number . 'rd';
      default:  return $number . 'th';
    }
  }
?>
sebu 28-Jul-2005 04:37
Referring to previous post "Be aware if you use is_numeric() or is_float() after using set_locale(LC_ALL,'lang') or set_locale(LC_NUMERIC,'lang')":

This is totally wrong!

This was the example code:

-----
  set_locale(LC_NUMERIC,'fr');
  is_numeric(12.25); // Return False
  is_numeric(12,25); // Return True
  is_float(12.25); //Return False
  is_float(12,25); //Return True
-----

This is nonsense!

- set_locale() does not exist, you must use setlocale() instead
- you have to enclose 12,25 with quotes; otherwise PHP will think that
the function gets _two_ arguments: 12 and 25 (depending on PHP version and setup you may additionally get a PHP warning)
- if you don't enclose 12,25 with quotes the first argument will be the inspected value (12), the second value (25) is discarded. And is_numeric(12) and is_float(12) is always TRUE

Corrected Example:

----
  setlocale(LC_NUMERIC,'fr');
  is_numeric(12.25); // Return True
  is_numeric("12,25"); // Return False
  is_float(12.25); //Return True
  is_float("12,25"); //Return False
----

Remarks:
- is_float(12.25) is _always_ TRUE, 12.25 is a PHP language construct (a "value") and the way PHP interpretes files is definitely _not_ affected by the locale
- is_float("12,25") is _always_ FALSE, since is_float (other than is_numeric): if the argument is a string then is_float() always returns FALSE since it does a strict check for floats

And the corrected example shows: you get the _same_ results for every possible locale, is_numeric() does not depend on the locale.
mdallaire at virtuelcom dot com 17-Nov-2004 04:23
Sometimes, we need to have no letters in the number and is_numeric does not quit the job.
You can try it this ways to make sure of the number format:

    function new_is_unsigned_float($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^([0-9])+([\.|,]([0-9])*)?$",$val);
    }

    function new_is_unsigned_integer($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^([0-9])+$",$val);
    }

    function new_is_signed_float($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^-?([0-9])+([\.|,]([0-9])*)?$",$val);
    }

    function new_is_signed_integer($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^-?([0-9])+$",$val);
    }

It returns 1 if okay and returns nothing "" if it's bad number formating.
renimar no spam at nospam yahoo dot com 03-May-2004 12:54
A little function to ordinalize numbers using is_numeric() and accounting for the numbers in the teens.

<?php
function ordinalize($num) {

        if (!is_numeric($num))
                return $num;

        if ($num >= 11 and $num <= 19)
                return $num."th";
        elseif ( $num % 10 == 1 )
                return $num."st";
        elseif ( $num % 10 == 2 )
                return $num."nd";
        elseif ( $num % 10 == 3 )
                return $num."rd";
        else
                return $num."th";

}

// Demo
for ($i=1; $i<=25; $i++) {
        print ordinalize($i) . " ";
}

// The loop returns:
// 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th
// 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd
// 23rd 24th 25th

?>
joe at kewlmail dot net 16-Jan-2004 03:12
Here is a simple function that I found usefull for filtering user input into numbers. Basically, it attempts to fix fat fingering. For example:

$userString = "$654.4r5";

function numpass_filter($userString){
    $money = explode(".", $userString);
    //now $money[0] = "$645" and $money[1] = "4r5"

    //next remove all characters save 0 though 9
    //in both elements of the array
    $dollars = eregi_replace("[^0-9]", null, $money[0]);
    $cents = eregi_replace("[^0-9]", null, $money[1]);

    //if there was a decimal in the original string, put it back
    if((string)$cents!=null){
        $cents = "." . $cents;
    }

   $result = $dollars . $cents;

    return($result);
}

The output in this case would be '654.45'.
Please note that this function will work properly unless the user fat fingers an extra decimal in the wrong place.
kouber at saparev dot com 24-Nov-2003 03:05
Note that this function is not appropriate to check if "is_numeric" for very long strings. In fact, everything passed to this function is converted to long and then to a double. Anything greater than approximately 1.8e308 is too large for a double, so it becomes infinity, i.e. FALSE. What that means is that, for each string with more than 308 characters, is_numeric() will return FALSE, even if all chars are digits.

However, this behaviour is platform-specific.

http://www.php.net/manual/en/language.types.float.php

In such a case, it is suitable to use regular expressions:

function is_numeric_big($s=0) {
  return preg_match('/^-?\d+$/', $s);
}
stew_wilde at hotmail dot com 07-Aug-2003 01:25
When using the exec() function in php to execute anther php script, any command line arguments passed the script will lose their type association, regardless of whether they are numeric or not, the same seems to hold true for strings as well.

ie : two scripts test.php:

<?php
$val = trim($argv[1]);
echo is_string($val);
?>

and testwrapper.php:

<?php
$tmp = 5;
exec("php ./test.php ".$tmp);
?>

Executing testwrapper.php on the command line will echo nothing (ie false), and false will be returned regardless of any escaping of parameters or other such attempts to overcome this.  The solution then is to explicitly cast $val in test.php to be an int and then is_numeric will work.  But as stated the same test was performed using a string for $val and the is_string() function and the same thing occurs.  Not the end of the world, but something to be aware of :)
andi_nrw at hotmail dot com 12-Feb-2003 08:25
<?php
/* This function is not useful if you want
to check that someone has filled in only
numbers into a form because for example
4e4 and 444 are both "numeric".

I used a regular expression for this problem
and it works pretty good. Maybe it is a good
idea to write a function and then to use it.

$input_number = "444"; // Answer 1
$input_number = "44 "; // Answer 2
$input_number = "4 4"; // Answer 2
$input_number = "4e4"; // Answer 2
$input_number = "e44"; // Answer 2
$input_number = "e4e"; // Answer 2
$input_number = "abc"; // Answer 2
*/
$input_number = "444";

if (preg_match ("/^([0-9]+)$/", $input_number)) {
     print "Answer 1";
} else {
     print "Answer 2";
}
?>
eagleflyer2 at lycos dot com 06-Sep-2002 01:02
Hi !
Many of you may have experienced that the 'is_numeric' function seems to fail always when form entries are checked against their variable type. So the function seems to return  'false' even if the form entry was aparently a number or numeric string.

The solution is pretty simple and no subroutines or fancy operations are necessary to make the 'is_numeric' function usable for form entry checks:

Simply strip off all (invisible) characters that may be sent along with the value when submitting a form entry.

Just use the 'trim' function before 'is_numeric'.

Example:

$variable = trim($variable);
if (is_numeric($variable)
{...#do something#...}
else
{...#do something else#...}


Comprueba si una variable es un objeto

  • « is_numeric
  • is_real »
  • PHP Manual
  • Funciones de manejo de variables
  • Comprueba si una variable es un objeto

is_object

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

is_object — Comprueba si una variable es un objeto

Descripción

is_object ( mixed $var ) : bool

Comprueba si la variable dada es un objeto.

Parámetros

var

La variable a ser evaluada.

Valores devueltos

Devuelve true si var es un object, o false de lo contrario.

Ejemplos

Ejemplo #1 Ejemplo is_object()

<?php
// Declarar una simple función para devolver un
// array de nuestro objeto
function get_students($obj)
{
    if(!is_object($obj)) {
        return false;
    }

    return $obj->students;
}

// Declara una nueva instancia de clase y rellena
// algunos valores
$obj = new stdClass();
$obj->students = array('Kalle', 'Ross', 'Felipe');

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

Historial de cambios

Versión | Descripción
7.2.0 | is_object() ahora devuelve true para objetos no seriados sin una definición de clase (clase de __PHP_Incomplete_Class). Anteriormente false era devuelto.

Ver también

  • is_bool() - Comprueba si una variable es de tipo booleano
  • is_int() - Comprueba si el tipo de una variable es integer
  • is_float() - Comprueba si el tipo de una variable es float
  • is_string() - Comprueba si una variable es de tipo string
  • is_array() - Comprueba si una variable es un array

User Contributed Notes

wadih at creationmw dot com 29-Jul-2017 06:47
Note that closures return true when passed to is_object():

<?php

echo
    is_object(
        function(){return "hello";}
    );

?>

Returns true (1)
shadow_games at abv dot bg 11-Jun-2014 03:42
here i created one function that i wanted to find but i had never found :X

    function compare_two_object_recursive($object_1, $object_2, $object_1_Identifier = false, $object_2_Identifier = false){
        $object1 = (array)$object_1;
        $object2 = (array)$object_2;
        $object3 = array();

        $o1i = $object_1_Identifier ? $object_1_Identifier : 1;
        $o2i = $object_2_Identifier ? $object_2_Identifier : 2;

        foreach($object1 as $key => $value){
            if(is_object($object1[$key])){
                $object1[$key] = (array)$object1[$key];
                $object2[$key] = (array)$object2[$key];
                $object3[$key] = (object)compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }elseif(is_array($object1[$key])){
                $object3[$key] = compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }else{
                if($object1[$key] == $object2[$key]){
                    $object3[$key]['comparison_status'] = "SAME";
                }else{
                    $object3[$key]['comparison_status'] = "NOT THE SAME";
                    $object3[$key][$o1i] = $object1[$key];
                    $object3[$key][$o2i] = $object2[$key];
                }
            }
        }
        return $object3;
    }
mark at not4you dot com 21-Sep-2011 12:23
Unserializes data as returned by the standard PHP serialize() function. If the unserialized object is not an array, it will be converted to one, particularily useful if it returns a __PHP_Incomplete_Class.

<?php
/**
 *
 * @param string $data Serialized data
 *
 * @return array    Unserialized array
 */
function unserialize2array($data) {
    $obj = unserialize($data);
    if(is_array($obj)) return $obj;
    $arr = array();
    foreach($obj as $k=>$v) {
        $arr[$k] = $v;
    }
    unset($arr['__PHP_Incomplete_Class_Name']);
    return $arr;
}
?>
peter dot nagel at portavita dot nl 22-Mar-2011 01:46
Note: is_object(null) returns false

This should actually be part of the input/output specification at the top of this page.
will 20-Mar-2010 02:36
Just discovered:
is_a  (  object $object  ,  string $class_name  )
Which checks if the object is of this class or has this class as one of its parents

Which seems to do what a lot here are trying to replicate
ldean at saleamp dot com 01-Sep-2009 07:16
Use instanceof() to check for a specific type.
Senthryl 17-Mar-2009 06:03
Cleaning it up even more:

<?php
function is_obj(&$object, $className = null, $caseSensitive = true) {
    return is_object($object) && (!is_string($className) || preg_match('/^'.$className.'$/D'.($caseSensitive ? '' : 'i'), get_class($object)));
}
?>
gregdangelo at gmail dot com 14-Apr-2008 12:03
cleaned up peter's code... use only one return statement

function is_obj( &$object, $check=null, $strict=true )
{
$result = false;
  if (is_object($object)) {
      if ($check == null) {
          $result =  true;
      } else {
           $object_name = get_class($object);
           $result =  ($strict === true)?
               ( $object_name == $check ):
               ( strtolower($object_name) == strtolower($check) );
      }
  }
return $result;
}
corychristison[aT-]lavacube(.dot)com 02-Feb-2005 05:06
Thank you victor AT fourstones DOT net.

I have written a function to do what victor has suggested, with the ease of use of is_object. It can be used to replace is_object(), but has an extra field [$check], to compare to a certain name. If $check is left empty, it will just check if &$object is an object.

<?php

function is_obj( &$object, $check=null, $strict=true )
{
    if( $check == null && is_object($object) )
    {
        return true;
    }
    if( is_object($object) )
    {
        $object_name = get_class($object);
        if( $strict === true )
        {
            if( $object_name == $check )
            {
                return true;
            }
        }
        else
        {
            if( strtolower($object_name) == strtolower($check) )
            {
                return true;
            }
        }
    }
}

?>

This could probably be cleaned up, but it's spaced out to be easy to read.
victor AT fourstones DOT net 01-Jan-2005 03:49
er, I don't think that's right, especially if calling from another object instance:

<?

function test_this()
{
    $c2 = new C2();
    $c2->func();
    $c1 = new C1();
    $c1->func();
    C1::func();
}

class C2
{
    function func()
    {
        C1::func();
    }
}

class C1
{
    function func()
    {
        if( isset($this) )
        {
            if( strtolower(get_class($this)) != 'c1' )
                print("oops\n");
            else
                print("this is ok\n" );
        }
        else
        {
            print("static call\n");
        }
    }
}

test_this();
?>

yields:
---------- run-php ----------

oops
this is ok
static call
corychristison[aT-]lavacube(.dot)com 01-Jan-2005 07:47
You can use is_object($this) to detect if the function is being called via instance or procedure.

Example:

<?php

class mrClass {

    function test( )
    {
        if( is_object($this) )
        {
         // do something for instance method
            echo 'this is an instance call <br />' . "\n";
        }
        else
        {
         // do something different for procedural method
            echo 'this is a procedure call <br />' . "\n";
        }
    }

}

$inst = new mrClass();
$inst->test();

mrClass::test();

?>

This would output:
this is an instance call <br />
this is a procedure call <br />

:-) Happy coding!
lbjay can be emailed at reallywow dot com 02-May-2003 12:18
I'm not even sure how to articulate this, so I'm going to just include test code. Maybe someone else will someday wonder the same thing.

<?
    error_reporting(E_ALL);
    class testParent
    {
        var $child;

        function testParent()
        {
            $this->child = new testChild();
        }
    }

    class testChild
    {
        function testChild()
        {
        }
    }

    $parent = new testParent();
    $parent2 = 'foobar';

    print join(',', Array(
        is_object($parent) ? 'yes' : 'no',
        is_object($parent->child) ? 'yes' : 'no',
        is_object($parent2) ? 'yes' : 'no',
        is_object($parent2->child) ? 'yes' : 'no'
    ));

?>

This prints "yes,yes,no,no". Basically this shows that you can use is_object to test if the child object is an object without worrying about an error if the parent object isn't an object either.


Alias de is_float

  • « is_object
  • is_resource »
  • PHP Manual
  • Funciones de manejo de variables
  • Alias de is_float

is_real

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

is_real — Alias de is_float()

Descripción

Esta función es un alias de: is_float().

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si una variable es un recurso

  • « is_real
  • is_scalar »
  • PHP Manual
  • Funciones de manejo de variables
  • Comprueba si una variable es un recurso

is_resource

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

is_resource — Comprueba si una variable es un recurso

Descripción

is_resource ( mixed $var ) : bool

Comprueba si la variable es un recurso.

Parámetros

var

La variable que se evalúa.

Valores devueltos

Devuelve true si var es un resource, false de lo contrario.

Ejemplos

Ejemplo #1 Ejemplo de is_resource()

<?php

$db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_pass');
if (!is_resource($db_link)) {
    die('No pudo realizarse la conexión : ' . mysql_error());
}

?>

Ver también

  • La documentación del tipo recurso
  • get_resource_type() - Devuelve el tipo de recurso

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.


Comprueba si una variable es escalar

  • « is_resource
  • is_string »
  • PHP Manual
  • Funciones de manejo de variables
  • Comprueba si una variable es escalar

is_scalar

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

is_scalar — Comprueba si una variable es escalar

Descripción

is_scalar ( mixed $var ) : bool

Obtiene si la variable dada es escalar.

Las variables escalares son aquellas que contienen un integer, float, string o boolean. Tipos array, object y resource no son escalares.

Nota:

is_scalar() no tiene en cuenta resource como escalares ya que los recursos son tipos de datos abstractos que actualmente se basan en enteros. No debe confiar en este detalle de implementación, ya que puede cambiar.

Nota:

is_scalar() no considera que NULL sea escalar.

Parámetros

var

La variable a ser evaluada.

Valores devueltos

Devuelve true si var es escalar, false de lo contrario.

Ejemplos

Ejemplo #1 Ejemplo is_scalar()

<?php
function show_var($var)
{
    if (is_scalar($var)) {
        echo $var;
    } else {
        var_dump($var);
    }
}
$pi = 3.1416;
$proteinas = array("hemoglobina", "citocromo c oxidasa", "ferredoxin");

show_var($pi);
show_var($proteinas)

?>

El resultado del ejemplo sería:

3.1416
array(3) {
  [0]=>
  string(10) "hemoglobina"
  [1]=>
  string(20) "citocromo c oxidasa"
  [2]=>
  string(10) "ferredoxin"
}

Ver también

  • is_float() - Comprueba si el tipo de una variable es float
  • is_int() - Comprueba si el tipo de una variable es integer
  • is_numeric() - Comprueba si una variable es un número o un string numérico
  • is_real() - Alias de is_float
  • is_string() - Comprueba si una variable es de tipo string
  • is_bool() - Comprueba si una variable es de tipo booleano
  • is_object() - Comprueba si una variable es un objeto
  • is_array() - Comprueba si una variable es un array

User Contributed Notes

31-Jul-2006 08:59
Another warning in response to the previous note:
> just a warning as it appears that an empty value is not a scalar.

That statement is wrong--or, at least, has been fixed with a later revision than the one tested.  The following code generated the following output on PHP 4.3.9.

CODE:
<?php
    echo('is_scalar() test:'.EOL);
    echo("NULL: "      . print_R(is_scalar(NULL),     true) . EOL);
    echo("false: "    . print_R(is_scalar(false),   true) . EOL);
    echo("(empty): "  . print_R(is_scalar(''),      true) . EOL);
    echo("0: "         . print_R(is_scalar(0),       true) . EOL);
    echo("'0': "      . print_R(is_scalar('0'),     true) . EOL);
?>

OUTPUT:
is_scalar() test:
NULL:
false: 1
(empty): 1
0: 1
'0': 1

THUS:
   * NULL is NOT a scalar
   * false, (empty string), 0, and "0" ARE scalars
efelch at gmail dot com 17-Aug-2005 02:31
A scalar is a single item or value, compared to things like arrays and objects which have multiple values. This tends to be the standard definition of the word in terms of programming. An integer, character, etc are scalars. Strings are probably considered scalars since they only hold "one" value (the value represented by the characters represented) and nothing else.
Dr K 14-Aug-2005 03:48
Having hunted around the manual, I've not found a clear statement of what makes a type "scalar" (e.g. if some future version of the language introduces a new kind of type, what criterion will decide if it's "scalar"? - that goes beyond just listing what's scalar in the current version.)

In other lanuages, it means "has ordering operators" - i.e. "less than" and friends.

It (-:currently:-) appears to have the same meaning in PHP.
popanowel HAT hotmailZ DOT cum 14-May-2004 12:31
Hi ... for newbees here, I just want to mention that reference and scalar variable aren't the same. A reference is a pointer to a scalar, just like in C or C++.

<? php  // simple reference to scalar

  $a = 2;
  $ref = & $a;

  echo "$a <br> $ref";

?>
this should print out: "2 <br> 2".

Scalar class also exists. Look below:
<? php

  class Object_t {

     var $a;

     function Object_t ()  // constructor
     {
        $this->a = 1;
     }

  }

  $a = new Object_t; // we define a scalar object

  $ref_a = &a;

  echo "$a->a <br> $ref->a";

?>
again, this should echo: "1 <br> 1";

Here is another method isued in OOP to acheive on working only over reference to scalar object. Using this, you won't ever have to  ask yourself if you work on a copy of the scalar or its reference. You will only possess reference to the scalar object. If you want to duplicate the scalar object, you will have to create a function for that purpose that would read by the reference the values and assign them to another scalar of the same type... or an other type, it is as you wish at that moment.
<?php

  class objet_t {
     var $a;

     function object_t
     {
        $this->a = "patate_poil";
     }
  }

   function &get_ref($object_type)
   {
      // here we create a scalar object in memory
      // and we return it by reference to the calling
      // control scope.
      return &new $object_type;
   }

   $ref_object_t = get_ref(object_t);

   echo "$ref_object_t->a <br>";

?>
this should echo: "patate_poit <br>".

The only thing that I try to demonstrate is that scalar variable ARE object in memory while a reference is usualy a variable (scalar object) that contain the address of another scalar object, which contain the informations you want by using the reference.

Good Luck!

otek is popanowel HAT hotmailZ DOT cum


Comprueba si una variable es de tipo string

  • « is_scalar
  • isset »
  • PHP Manual
  • Funciones de manejo de variables
  • Comprueba si una variable es de tipo string

is_string

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

is_string — Comprueba si una variable es de tipo string

Descripción

is_string ( mixed $var ) : bool

Obtiene si la variable dada es de tipo string.

Parámetros

var

La variable a ser evaluada.

Valores devueltos

Devuelve true si var es de tipo string, false de lo contrario.

Ejemplos

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

El resultado del ejemplo sería:

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)

Ver también

  • is_float() - Comprueba si el tipo de una variable es float
  • is_int() - Comprueba si el tipo de una variable es integer
  • is_bool() - Comprueba si una variable es de tipo booleano
  • is_object() - Comprueba si una variable es un objeto
  • is_array() - Comprueba si una variable es un array

User Contributed Notes

jcours at numifinancial dot com 15-Jul-2020 07:59
is_string() of an integer or float returns false, so it might be useful to include an is_numeric() when checking if a value is stringy:

<?php
function is_stringy($val) {
  return (is_string($val) || is_numeric($val)
    || (is_object($val) && method_exists($val, '__toString')));
}
?>

Test code (which should print "vector N OK" for each test vector):
<?php
foreach ([[NULL, false], [false, false], [true, false],
  [0, true], [[], false], [0.1, true], ["x", true],
  ["", true], [new Exception("x"), true]] as $idx => $vector) {
  list ($val, $expected) = $vector;
  if (is_stringy($val) != $expected) {
    print ("mismatch at $idx\n");
    var_dump($val);
  } else {
    print ("vector $idx OK\n");
  }
}
?>
Peter Barney 13-Sep-2017 10:47
As noted earlier, is_string() returns false on an object that has a __toString() method. Here is a simple way to do a check that will work:

<?php
// determine if the passed argument can be treated like a string.
function is_stringy($text) {
    return (is_string($text) || (is_object($text) && method_exists($text, '__toString' ));
}
laszlo dot heredy shift-two gmail etc 27-Feb-2014 09:22
Using is_string() on an object will always return false (even with __toString()).

<?php
class B {
  public function __toString() {
    return "Instances of B() can be treated as a strings!\n";
  }
}

$b = new B();
print($b); //Instances of B() can be treated as a strings!
print(is_string($b) ? 'true' : 'false'); //false
?>


Determina si una variable está definida y no es null

  • « is_string
  • print_r »
  • PHP Manual
  • Funciones de manejo de variables
  • Determina si una variable está definida y no es null

isset

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

isset — Determina si una variable está definida y no es null

Descripción

isset ( mixed $var , mixed $... = ? ) : bool

Determina si una variable está definida y no es null.

Si una variable ha sido removida con unset(), esta ya no estará definida. isset() devolverá false si prueba una variable que ha sido definida como null. También tenga en cuenta que un byte null ("\0") no es equivalente a la constante null de PHP.

Si son pasados varios parámetros, entonces isset() devolverá true únicamente si todos los parámetros están definidos. La evaluación se realiza de izquierda a derecha y se detiene tan pronto como se encuentre una variable no definida.

Parámetros

var

La variable a ser evaluada.

...

Otra variable...

Valores devueltos

Devuelve true si var existe y tiene un valor distinto de null, false de lo contrario.

Historial de cambios

Versión | Descripción
5.4.0 | Comprobación de indices no numéricos de strings ahora retorna false.

Ejemplos

Ejemplo #1 Ejemplos isset()

<?php

$var = '';

// Esto evaluará a TRUE así que el texto se imprimirá.
if (isset($var)) {
    echo "Esta variable está definida, así que se imprimirá";
}

// En los siguientes ejemplo usaremos var_dump para imprimir
// el valor devuelto por isset().

$a = "prueba";
$b = "otraprueba";

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

?>

También trabaja con elementos en matrices:

<?php

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

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

// La clave 'helo' es igual a NULL así que no se considera definida
// Si desea comprobar los valores NULL clave, intente:
var_dump(array_key_exists('hello', $a)); // TRUE

// Comprobando valores de arrays con más profunidad
var_dump(isset($a['pie']['a']));        // TRUE
var_dump(isset($a['pie']['b']));        // FALSE
var_dump(isset($a['cake']['a']['b']));  // FALSE

?>

Notas

Advertencia

isset() sólo trabaja con variables, ya que pasar cualquier otra cosa dará como resultado un error de intérprete. Para comprobar si se han definidoconstantes use la función defined().

Nota: Puesto que esto es una construcción del lenguaje y no una función, no puede ser llamada usando funciones variables.

Nota:

Cuando se utiliza isset() sobre las propiedades de objetos inaccesibles, el método sobrecargado __isset() será llamado, si se declara.

Ejemplo #2 isset() en indices de String

PHP 5.4 cambia ahora el comportamiendo de isset() cuando son pasados indices de string.

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

Salida del ejemplo anterior en PHP 5.3:

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

Salida del ejemplo anterior en PHP 5.4:

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

Ver también

  • empty() - Determina si una variable está vacía
  • __isset()
  • unset() - Destruye una variable especificada
  • defined() - Comprueba si existe una constante con nombre dada
  • las tablas de comparación de tipos
  • array_key_exists() - Verifica si el índice o clave dada existe en el array
  • is_null() - Comprueba si una variable es null
  • el operador @ de control de errores

User Contributed Notes

razvan_bc at yahoo dot com 13-Feb-2019 07:25
In these days you can use ISSET to compare a sting length
COOOL! I love php !!!!

<?php
//FIRST:try to run the script like this,
//THEN: try to uncomment the seccond $str=

$yes="SURE!!!";
$no="NOPE !";

$str="12345";//the string is long 5 bytes ?
//$str="123456";

echo !isset($str{5}) ? $yes : $no;

?>
borshak at gmail dot com 24-Jun-2018 03:13
Would be nice to have is_set() alias for more language consistency (alike of is_int, is_bull so on).
venimus at gmail dot com 27-Apr-2018 11:46
Be warned that before checking an array key existence with isset() the key will be typecasted to integer if it is not a string or integer!

See Example #2 in http://php.net/manual/en/language.types.array.php

I.e.

$a = ['test']; // 'test' will have key 0
$key = false;

var_dump(isset($a[$key]) ); // true, because false will be typecasted to 0

It is not a problem with isset but rather the lose typing when you access keys in arrays
Hayley Watson 30-Jul-2017 01:12
If you regard isset() as indicating whether the given variable has a value or not, and recall that NULL is intended to indicate that a value is _absent_ (as said, somewhat awkwardly, on its manual page), then its behaviour is not at all inconsistent or confusing.

It's not just to check for uninitialised variables - a lot of the time those are just due to sloppy coding. There are other ways a variable could fail to have a value (e.g., it's meant to hold the value returned from a function call but the function didn't have a value to return) where uninitialising the variable would not be an option nor even make sense (e.g., depending on what was to be done with the returned value).
kurdtpage at gmail dot com 21-Dec-2016 01:03
The new (as of PHP7) 'null coalesce operator' allows shorthand isset. You can use it like so:

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Quoted from http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
p_ignorethis_lbowers at gmail dot com 06-Oct-2016 07:26
I, too, was dismayed to find that isset($foo) returns false if ($foo == null). Here's an (awkward) way around it.

unset($foo);
if (compact('foo') != array()) {
  do_your_thing();
}

Of course, that is very non-intuitive, long, hard-to-understand, and kludgy. Better to design your code so you don't depend on the difference between an unset variable and a variable with the value null. But "better" only because PHP has made this weird development choice.

In my thinking this was a mistake in the development of PHP. The name ("isset") should describe the function and not have the desciption be "is set AND is not null". If it was done properly a programmer could very easily do (isset($var) || is_null($var)) if they wanted to check for this!

A variable set to null is a different state than a variable not set - there should be some easy way to differentiate. Just my (pointless) $0.02.
ayyappan dot ashok at gmail dot com 24-Mar-2016 07:23
Return Values :
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

<?php
$a=NULL;
$b=FALSE; //The out put was TRUE.
$c=TRUE;
$d='';
$e="";
if(isset($b)):
echo "TRUE";
else:
echo "FALSE";
endif;
?>
Could any one explain me in clarity.
andreasonny83 at gmail dot com 12-May-2015 11:26
Here is an example with multiple parameters supplied

<?php
$var = array();
$var['val1'] = 'test';
$var['val2'] = 'on';

if ( isset( $var['val1'], $var['val2'] ) && $var['val2'] === 'on' ) {
    unset( $var['val1'] );
}
print_r( $var );
?>

This will output:
Array
(
    [val2] => on
)

The following code does the same calling "isset" 2 times:

<?php
$var = array();
$var['val1'] = 'test';
$var['val2'] = 'on';

if ( isset( $var['val1'] ) && isset( $var['val2'] ) && $var['val2'] === 'on' ) {
    unset( $var['val1'] );
}
print_r( $var );
?>
uramihsayibok, gmail, com 25-Apr-2013 11:32
Note that isset() is not recursive as of the 5.4.8 I have available here to test with: if you use it on a multidimensional array or an object it will not check isset() on each dimension as it goes.

Imagine you have a class with a normal __isset and a __get that fatals for non-existant properties. isset($object->nosuch) will behave normally but isset($object->nosuch->foo) will crash. Rather harsh IMO but still possible.

<?php

class FatalOnGet {

    // pretend that the methods have implementations that actually try to do work
    // in this example I only care about the worst case conditions

    public function __get($name) {
        echo "(getting {$name}) ";

        // if property does not exist {
            echo "Property does not exist!";
            exit;
        // }
    }

    public function __isset($name) {
        echo "(isset {$name}?) ";
        // return whether the property exists
        return false;
    }

}

$obj = new FatalOnGet();

// works
echo "Testing if ->nosuch exists: ";
if (isset($obj->nosuch)) echo "Yes"; else echo "No";

// fatals
echo "\nTesting if ->nosuch->foo exists: ";
if (isset($obj->nosuch->foo)) echo "Yes"; else echo "No";

// not executed
echo "\nTesting if ->irrelevant exists: ";
if (isset($obj->irrelevant)) echo "Yes"; else echo "No";

?>

    Testing if ->nosuch exists: No
    Testing if ->nosuch->foo exists: Property does not exist!

Uncomment the echos in the methods and you'll see exactly what happened:

    Testing if ->nosuch exists: (isset nosuch?) No
    Testing if ->nosuch->foo exists: (getting nosuch) Property does not exist!

On a similar note, if __get always returns but instead issues warnings or notices then those will surface.
Daniel Klein 29-May-2012 03:49
How to test for a variable actually existing, including being set to null. This will prevent errors when passing to functions.

<?php
// false
var_export(
  array_key_exists('myvar', get_defined_vars())
);

$myvar;
// false
var_export(
  array_key_exists('myvar', get_defined_vars())
);

$myvar = null;
// true
var_export(
  array_key_exists('myvar', get_defined_vars())
);

unset($myvar);
// false
var_export(
  array_key_exists('myvar', get_defined_vars())
);

if (array_key_exists('myvar', get_defined_vars())) {
  myfunction($myvar);
}
?>

Note: you can't turn this into a function (e.g. is_defined($myvar)) because get_defined_vars() only gets the variables in the current scope and entering a function changes the scope.
Cuong Huy To 23-Mar-2011 05:08
1) Note that isset($var) doesn't distinguish the two cases when $var is undefined, or is null. Evidence is in the following code.

<?php
unset($undefined);
$null = null;
if (true === isset($undefined)){echo 'isset($undefined) === true'} else {echo 'isset($undefined) === false'); // 'isset($undefined) === false'
if (true === isset($null)){echo 'isset($null) === true'} else {echo 'isset($null) === false');              // 'isset($null)      === false'
?>

2) If you want to distinguish undefined variable with a defined variable with a null value, then use array_key_exist

<?php
unset($undefined);
$null = null;

if (true !== array_key_exists('undefined', get_defined_vars())) {echo '$undefined does not exist';} else {echo '$undefined exists';} // '$undefined does not exist'
if (true === array_key_exists('null', get_defined_vars())) {echo '$null exists';} else {echo '$null does not exist';}                // '$null exists'
?>
francois vespa 22-Dec-2010 07:21
Now this is how to achieve the same effect (ie, having isset() returning true even if variable has been set to null) for objects and arrays

<?php

// array

$array=array('foo'=>null);

return isset($array['foo']) || array_key_exists('foo',$array)
  ? true : false ; // return true

return isset($array['inexistent']) || array_key_exists('inexistent',$array)
  ? true : false ; // return false

// static class

class bar

{
  static $foo=null;
}

return isset(bar::$foo) || array_key_exists('foo',get_class_vars('bar'))
  ? true : false ; // return true

return isset(bar::$inexistent) || array_key_exists('inexistent',get_class_vars('bar'))
  ? true : false ; // return false

// object

class bar
{
    public $foo=null;
}

$bar=new bar();

return isset($bar->foo) || array_key_exists('foo',get_object_vars($bar))
  ? true : false ; // return true

return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
  ? true : false ; // return true

// stdClass

$bar=new stdClass;
$bar->foo=null;

return isset($bar->foo) || array_key_exists('foo',get_object_vars($bar))
  ? true : false ; // return true

return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
  ? true : false ; // return true

?>
Anl zselgin 14-Aug-2009 03:30
Note: Because this is a language construct and not a function, it cannot be called using variable functions.

So why it is under "Variable handling Functions". Maybe there should be some good documentation field for language constructs.
Ashus 08-Dec-2008 01:05
Note that array keys are case sensitive.

<?php
$ar['w'] = true;

var_dump(isset($ar['w']),
      isset($ar['W']));
?>

will report:
bool(true) bool(false)
a dot schaffhirt at sedna-soft dot de 12-Oct-2008 08:01
You can safely use isset to check properties and subproperties of objects directly. So instead of writing

    isset($abc) && isset($abc->def) && isset($abc->def->ghi)

or in a shorter form

    isset($abc, $abc->def, $abc->def->ghi)

you can just write

    isset ($abc->def->ghi)

without raising any errors, warnings or notices.

Examples
<?php
    $abc = (object) array("def" => 123);
    var_dump(isset($abc));                // bool(true)
    var_dump(isset($abc->def));           // bool(true)
    var_dump(isset($abc->def->ghi));      // bool(false)
    var_dump(isset($abc->def->ghi->jkl)); // bool(false)
    var_dump(isset($def));                // bool(false)
    var_dump(isset($def->ghi));           // bool(false)
    var_dump(isset($def->ghi->jkl));      // bool(false)

    var_dump($abc);                       // object(stdClass)#1 (1) { ["def"] => int(123) }
    var_dump($abc->def);                  // int(123)
    var_dump($abc->def->ghi);             // null / E_NOTICE: Trying to get property of non-object
    var_dump($abc->def->ghi->jkl);        // null / E_NOTICE: Trying to get property of non-object
    var_dump($def);                       // null / E_NOTICE: Trying to get property of non-object
    var_dump($def->ghi);                  // null / E_NOTICE: Trying to get property of non-object
    var_dump($def->ghi->jkl);             // null / E_NOTICE: Trying to get property of non-object
?>
mark dot fabrizio at gmail dot com 15-Sep-2008 07:01
I know this is probably not the recommended way to do this, but it seems to work fine for me. Instead of the normal isset check to extract variables from arrays (like $_REQUEST), you can use the @ prefix to squelch any errors.

For example, instead of:
<?php
$test = isset($_REQUEST['test']) ? $_REQUEST['test'] : null;
?>
you can use:
<?php
$test = @$_REQUEST['test'];
?>

It saves some typing, but doesn't give the opportunity to provide a default value. If 'test' is not an assigned key for $_REQUEST, the assigned value will be null.
mandos78 AT mail from google 29-Jul-2008 02:40
Careful with this function "ifsetfor" by soapergem, passing by reference means that if, like the example $_GET['id'], the argument is an array index, it will be created in the original array (with a null value), thus causing posible trouble with the following code. At least in PHP 5.

For example:

<?php
$a = array();
print_r($a);
ifsetor($a["unsetindex"], 'default');
print_r($a);
?>

will print

Array
(
)
Array
(
    [unsetindex] =>
)

Any foreach or similar will be different before and after the call.
anonymousleaf at gmail dot com 25-Feb-2008 10:16
isset expects the variable sign first, so you can't add parentheses or anything.

<?php
    $foo = 1;
    if(isset(($foo))) { // Syntax error at isset((
        $foo = 2;
    }
?>
muratyaman at gmail dot com 07-Feb-2008 04:40
To organize some of the frequently used functions..

<?php

/**
 * Returns field of variable (arr[key] or obj->prop), otherwise the third parameter
 * @param array/object $arr_or_obj
 * @param string $key_or_prop
 * @param mixed $else
 */
function nz($arr_or_obj, $key_or_prop, $else){
  $result = $else;
  if(isset($arr_or_obj)){
    if(is_array($arr_or_obj){
      if(isset($arr_or_obj[$key_or_prop]))
        $result = $arr_or_obj[$key_or_prop];
    }elseif(is_object($arr_or_object))
      if(isset($arr_or_obj->$key_or_prop))
        $result = $arr_or_obj->$key_or_prop;
    }
  }
  return $result;
}

/**
 * Returns integer value using nz()
 */
function nz_int($arr_or_obj, $key_or_prop, $else){
  return intval(nz($arr_or_obj, $key_or_prop, $else));
}

$my_id = nz_int($_REQUEST, 'id', 0);
if($my_id > 0){
  //why?
}
?>
packard_bell_nec at hotmail dot com 25-Dec-2007 11:18
Note: isset() only checks variables as anything else will result in a parse error. In other words, the following will not work: isset(trim($name)).

isset() is the opposite of is_null($var) , except that no warning is generated when the variable is not set.
talbutt(at)mail(dot)med(dot)upenn(edu) 13-Aug-2007 08:30
In PHP 5.2.3, really returns true if the variable is set to null.
beuc at beuc dot net 16-Dec-2006 12:35
"empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set."

So essentially
<?php
if (isset($var) && $var)
?>
is the same as
<?php
if (!empty($var))
?>
doesn't it? :)

!empty() mimics the chk() function posted before.
randallgirard at hotmail dot com 27-Sep-2006 11:51
The unexpected results of isset has been really frustrating to me. Hence, it doesn't work how you'd think it would, (as documented) a var currently in the scope with a null value will return false.

Heres a quick solution, perhaps there are better ways of going about this, but heres my solution...

<?php
function is_set( $varname, $parent=null ) {
  if ( !is_array( $parent ) && !is_object($parent) ) {
    $parent = $GLOBALS;
  }
  return array_key_exists( $varname, $parent );
}
?>

Hence, $varname should be a mixed value of var's to check for, and $parent can be an array or object, which will default to the GLOBAL scope. See the documentation of array_key_exists for further information.

This will allow to check if a var is in the current scope, object, or array... Whether it's a null, false, true, or any value. It depends on ARRAY_KEY_EXISTS for it's functionality which also works with Objects. Feel free to improve on this anyone ;D
Tee Cee 20-Aug-2006 05:20
In response to 10-Feb-2006 06:02, isset($v) is in all (except possibly buggy) cases equivalent to !is_null($v). And no, it doesn't actually test if a variable is set or not by my definition "$v is set if unset($v) has no effect".

<?php
unset($c); //force $c to be unset
var_dump($a=&$c); // NULL, but this actually sets $a and $c to the 'same' NULL.
var_dump(isset($c)); // bool(false)
var_dump($a = 5); // int(5)
var_dump($c); // int(5)

unset($c);
var_dump($a=&$c); // NULL
var_dump(isset($c)); // bool(false)
unset($c);
var_dump($a = 5); // int(5)
var_dump($c); // NULL
?>

In the following example, we see an alternate method of testing if a variable is actually set or not:
<?php
var_dump(array_key_exists('c',get_defined_vars())); // false
var_dump(isset($c));                                // also false
var_dump($c);                                       // manipulate $c a bit...
var_dump((string)$c);
var_dump(print_r($c,true));
var_dump($a=$c);
var_dump(array_key_exists('c',get_defined_vars())); // ... still false
var_dump($c = NULL);                                // this sets $c
var_dump(array_key_exists('c',get_defined_vars())); // true!
var_dump(isset($c));                                // false; isset() still says it's unset
unset($c);                                          // actually unset it
var_dump(array_key_exists('c',get_defined_vars())); // false
var_dump($a=&$c);
var_dump(array_key_exists('c',get_defined_vars())); // true!
unset($c);                                          // unset it again
var_dump(&$c);                                      // &NULL
var_dump(array_key_exists('c',get_defined_vars())); // true!
?>

Obviously, null values take up space (or they wouldn't show up in get_defined_vars). Also, note that &$v sets $v to NULL if it is unset.
21-Jul-2006 07:08
I tried the example posted previously by Slawek:

$foo = 'a little string';
echo isset($foo)?'yes ':'no ', isset($foo['aaaa'])?'yes ':'no ';

He got yes yes, but he didn't say what version of PHP he was using.

I tried this on PHP 5.0.5 and got:  yes no

But on PHP 4.3.5 I got:  yes yes

Apparently, PHP4 converts the the string 'aaaa' to zero and then returns the string character at that position within the string $foo, when $foo is not an array. That means you can't assume you are dealing with an array, even if you used an expression such as isset($foo['aaaa']['bbb']['cc']['d']), because it will return true also if any part is a string.

PHP5 does not do this. If $foo is a string, the index must actually be numeric (e.g. $foo[0]) for it to return the indexed character.
soywiz at php dot net 14-Apr-2006 06:12
Sometimes you have to check if an array has some keys. To achieve it you can use "isset" like this: isset($array['key1'], $array['key2'], $array['key3'], $array['key4'])
You have to write $array all times and it is reiterative if you use same array each time.

With this simple function you can check if an array has some keys:

<?php
function isset_array() {
    if (func_num_args() < 2) return true;
    $args = func_get_args();
    $array = array_shift($args);
    if (!is_array($array)) return false;
    foreach ($args as $n) if (!isset($array[$n])) return false;
    return true;
}
?>

Use: isset_array($array, 'key1', 'key2', 'key3', 'key4')
First parameter has the array; following parameters has the keys you want to check.
Slawek Petrykowski 29-Nov-2005 03:06
<?php
$foo = 'a little string';
echo isset($foo)?'yes ':'no ', isset($foo['aaaa'])?'yes ':'no ';
>

results with unexpected values:
yes yes

Well, it is necessary to check type of $foo first !
Andrew Penry 11-May-2005 08:17
The following is an example of how to test if a variable is set, whether or not it is NULL. It makes use of the fact that an unset variable will throw an E_NOTICE error, but one initialized as NULL will not.

<?php

function var_exists($var){
    if (empty($GLOBALS['var_exists_err'])) {
        return true;
    } else {
        unset($GLOBALS['var_exists_err']);
        return false;
    }
}

function var_existsHandler($errno, $errstr, $errfile, $errline) {
   $GLOBALS['var_exists_err'] = true;
}

$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (var_exists($l)) ? "True " : "False ";
echo (var_exists($k)) ? "True " : "False ";
restore_error_handler();

?>

Outputs:
True False

The problem is, the set_error_handler and restore_error_handler calls can not be inside the function, which means you need 2 extra lines of code every time you are testing. And if you have any E_NOTICE errors caused by other code between the set_error_handler and restore_error_handler they will not be dealt with properly. One solution:

<?php

function var_exists($var){
   if (empty($GLOBALS['var_exists_err'])) {
       return true;
   } else {
       unset($GLOBALS['var_exists_err']);
       return false;
   }
}

function var_existsHandler($errno, $errstr, $errfile, $errline) {
    $filearr = file($errfile);
    if (strpos($filearr[$errline-1], 'var_exists') !== false) {
        $GLOBALS['var_exists_err'] = true;
        return true;
    } else {
        return false;
    }
}

$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (var_exists($l)) ? "True " : "False ";
echo (var_exists($k)) ? "True " : "False ";
is_null($j);
restore_error_handler();

?>

Outputs:
True False
Notice: Undefined variable: j in filename.php on line 26

This will make the handler only handle var_exists, but it adds a lot of overhead. Everytime an E_NOTICE error happens, the file it originated from will be loaded into an array.
yaogzhan at gmail dot com 20-Mar-2005 04:52
in PHP5, if you have

<?PHP
class Foo
{
    protected $data = array('bar' => null);

    function __get($p)
    {
        if( isset($this->data[$p]) ) return $this->data[$p];
    }
}
?>

and
<?PHP
$foo = new Foo;
echo isset($foo->bar);
?>
will always echo 'false'. because the isset() accepts VARIABLES as it parameters, but in this case, $foo->bar is NOT a VARIABLE. it is a VALUE returned from the __get() method of the class Foo. thus the isset($foo->bar) expreesion will always equal 'false'.
pianistsk8er at gmail dot com 09-Dec-2004 06:23
This function is very useful while calling to the URL to specify which template to be used on certain parts of your application.

Here is an example...

<?php

    $cat = $_GET['c'];
    $id = $_GET['id'];
    $error = 'templates/error.tpl';

    if( isset($cat))
    {
        if( isset($id))
        {
            $var = 'templates/pics/' . $cat . '-' . $id . '.tpl';
            if (is_file($var))
            {
                include($var);
            }
            else
            {
                include($error);
            }
        }
        else
        {
            $var = 'templates/pics/' . $cat . '.tpl';
            if (is_file($var))
            {
                include($var);
            }
            else
            {
                include($error);
            }
        }
    }
    else
    {
        include('templates/alternative.'.tpl);
    }

?>

You can see several uses of the isset function being used to specify wheter a template is to be called upon or not.  This can easily prevent other generic PHP errors.


Imprime información legible para humanos sobre una variable

  • « isset
  • serialize »
  • PHP Manual
  • Funciones de manejo de variables
  • Imprime información legible para humanos sobre una variable

print_r

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

print_r — Imprime información legible para humanos sobre una variable

Descripción

print_r ( mixed $expression , bool $return = false ) : mixed

print_r() muestra información sobre una variable en una forma que es legible por humanos.

print_r(), var_dump() y var_export() mostrarán también propiedades protegidas y privadas de objetos. Miembros de la clase estática no se mostrarán.

Parámetros

expresión

La expresión a ser impresa.

return

Si desea capturar la salida de print_r(), use el parámetro return. Cuando el parámetro es establecido a true, print_r() devolverá la información en lugar de imprimirla.

Valores devueltos

Si se le da string, integer o float, el valor en sí mismo será impreso. Si le dan un array, los valores serán presentados en un formato que muestra las claves y los elementos. Una notación similar se utiliza para objects.

Cuando el parámetro return es true, esta función devolverá un string. De lo contrario, devolverá true.

Notas

Nota:

Cuando el parámetro return se usa, esta función utiliza el almacenamiento en búfer de salida interno, por lo que no puede usarse dentro de una función de llamada de retorno ob_start().

Ejemplos

Ejemplo #1 Ejemplo print_r()

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

El resultado del ejemplo sería:

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

Ejemplo #2 Ejemplo del parámetro devolver

<?php
$b = array ('m' => 'mono', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$resultados = print_r($b, true); // $resultados contiene ahora la salida de print_r
?>

Ver también

  • ob_start() - Activa el almacenamiento en búfer de la salida
  • var_dump() - Muestra información sobre una variable
  • var_export() - Imprime o devuelve una representación string de una variable analizable

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


Genera una representación apta para el almacenamiento de un valor

  • « print_r
  • settype »
  • PHP Manual
  • Funciones de manejo de variables
  • Genera una representación apta para el almacenamiento de un valor

serialize

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

serialize — Genera una representación apta para el almacenamiento de un valor

Descripción

serialize ( mixed $value ) : string

Genera una representación almacenable de un valor.

Esto es útil para el almacenamiento de valores en PHP sin perder su tipo y estructura.

Para recuperar el valor PHP a partir de la cadena seriada, utilice unserialize().

Parámetros

value

El valor a ser serializado. serialize() maneja todos los tipos, excepto el tipo resource. Puede incluso usar serialize() sobre arrays que contienen referencias a ellos mismos. Las referencias circulares encontradas en el array/objeto que procede a serializar también serán almacenadas. Cualquier otra referencia se perderá.

Cuando se trata de objetos, PHP intentará llamar a la función miembro __sleep() antes de la serialización. Esto permite que el objeto efectúe limpiezas de último minuto, etc. antes de ser serializado. Del mismo modo, cuando el objeto es recuperado usando unserialize(), la función miembro __wakeup() es llamada.

Nota:

Los miembros privados del objeto tienen el nombre de la clase al comienzo de su nombre; los miembros protegidos tienen un '*' al comienzo de su nombre. estos valores antepuestos tienen bytes nulos a ambos lados.

Valores devueltos

Devuelve una cadena que contiene una representación de flujo de bytes del value que puede ser almacenada en cualquier parte.

Observe que esto es una cadena binaria que puede incluir bytes nulos, y necesita ser almacenada y manipulada como tal. Por ejemplo, la salida de serialize() debe ser generalmente almacenada en un campo de tipo BLOB en la base de datos, en vez de en campos de tipo CHAR o TEXT.

Ejemplos

Ejemplo #1 Ejemplo serialize()

<?php
// $datos_sesion contiene un array multi-dimensional con
// información del usuario actual. Usamos serialize() para
// almacenarla en una base de datos al final de la petición.

$con  = odbc_connect("bd_web", "php", "gallina");
$sent = odbc_prepare($con,
      "UPDATE sesiones SET datos = ? WHERE id = ?");
$datos_sql = array (serialize($datos_sesion), $_SERVER['PHP_AUTH_USER']);

if (!odbc_execute($sent, &$datos_sql)) {
    $sent = odbc_prepare($con,
     "INSERT INTO sesiones (id, datos) VALUES(?, ?)");
    if (!odbc_execute($sent, &$datos_sql)) {
        /* Algo ha fallado.. */
    }
}
?>

Notas

Nota:

Tenga en cuenta que muchos objetos integrados de PHP no se pueden serializar. Sin embargo, aquellos con esta habilidad o implementan la interfaz Serializable o los métodos mágicos __sleep() y __wakeup(). Si una clase interna no cumple cualquiera de esos requisitos, estas seguramente no puedan ser serializadas.

Hay algunas excepciones históricas a la regla anterior, donde algunos objetos internos podrían ser serializados sin implementar la interfaz o la exposición de los métodos. En particular, la clase ArrayObject anterior a PHP 5.2.0.

Advertencia

Cuando serialize() serializa los objetos, la barra inicial no está incluido en el nombre de clase de las clases de espacios de nombres para una máxima compatibilidad.

Ver también

  • unserialize() - Crea un valor PHP a partir de una representación almacenada
  • var_export() - Imprime o devuelve una representación string de una variable analizable
  • json_encode() - Retorna la representación JSON del valor dado
  • Serialización de Objetos
  • __sleep()
  • __wakeup()

User Contributed Notes

Kantin Charignon 15-Jun-2018 02:50
I did the same test as MiChAeLoKGB but in another version of PHP.
I don't post his code because I executed exactly the same script (after correcting a small variable naming error and add a line to display the PHP version).

PHP version: 7.1.9
PHP serialized in 0.0032186679840088 seconds average
JSON encoded in 0.0035939190387726 seconds average
serialize() was roughly 11.66% faster than json_encode()
Test took 6.8132710456848 seconds with 1000 iterations.

It would seem that in the current version of PHP the serialize function is faster.
lincoln dot du dot j at gmail dot com 11-Jul-2017 05:48
class A{
    public $tumi='Ami';
    public $ami='Tumi';

    public function ami(){
        $this->ami='You love me.';
    }
    public function tumi(){
        $this->tumi="I love you.";
    }
}
$obj=new A;
$serial=serialize($obj);

echo $serial;

echo PHP_EOL;

$uns=unserialize($serial);

print_r($uns);
sinus-php at sinpi dot net 03-Jul-2017 01:49
Here's a serialization function that doesn't serialize objects (it could, I just didn't care for that) but writes straight to a file. Very useful if you run out of memory when trying to serialize that 5-level nested 100000-entry array of strings.

Call it with the subject variable and a file name, it'll do the rest.

<?php
function serialize_to_file($subject,$file,$level=0) {
    if ($level==0) {
        $file=fopen($file,"w");
        if (!$file) return FALSE;
    }
    if (is_numeric($subject))
        fputs($file,"i:".$subject);
    elseif (is_string($subject))
        fputs($file,"s:".strlen($subject).":\"".addslashes($subject)."\"");
    elseif (is_bool($subject))
        fputs($file,"b:".($subject?1:0));
    elseif (is_array($subject)) {
        $keys = array_keys($subject);
        fputs($file,"a:".count($keys).":{");
        foreach ($keys as $key) {
            flat_serialize_to_file($key,$file,$level+1);
            fputs($file,";");
            flat_serialize_to_file($subject[$key],$file,$level+1);
            if (!is_array($subject[$key])) fputs($file,";");
        }
        fputs($file,"}");
    }
    if ($level==0)
        fclose($file);
}
?>
Anonymous 28-Dec-2016 05:10
If you want write something strange, like string array to binary string, and you are afraid 0-days of php's serialize function, you can use this.

Out:

string(88) "031a000a0001004c6f72..."
array(3) {
  [0]=>
  string(26) "Lorem ipsum dolor sit amet"
  [1]=>
  string(10) "8726348723"
  [2]=>
  string(1) "1"
}
string(152) "1c5e108afdec7c27a..."
array(3) {
  [0]=>
  string(26) "Lorem ipsum dolor sit amet"
  [1]=>
  string(10) "8726348723"
  [2]=>
  string(1) "1"
}

<?php

$arrToPack = array('Lorem ipsum dolor sit amet', 8726348723, true);

$packer = new ArraysPack();
$packer->privateKey = hash('sha256', 'k6LYiB8cnr5ESBMpVUBdC3c73Mt52p8w' ,true);

$dataPacked = $packer->pack($arrToPack);
$dataUnpacked = $packer->unPack($dataPacked);

$dataHMACPacked = $packer->hmacPack($arrToPack);
$dataHMACUnpacked = $packer->hmacUnPack($dataHMACPacked);

var_dump(bin2hex($dataPacked));
var_dump($dataUnpacked);

var_dump(bin2hex($dataHMACPacked));
var_dump($dataHMACUnpacked);

class ArraysPack
{
    public $hmacAlgo = 'sha256';
    public $hmacLen = 32;
    public $privateKey = '';

    public function hmacPack($array)
    {
        if(($ret = $this->pack($array)) === false)
            return false;

        $hmacHash = hash_hmac($this->hmacAlgo, $ret, $this->privateKey, true);
        return $hmacHash.$ret;
    }

    public function hmacUnPack($binaryString)
    {
        if(strlen($binaryString) < $this->hmacLen)
            return false;

        $hmacHash = substr($binaryString, 0, $this->hmacLen);
        $binaryString = substr($binaryString, $this->hmacLen);
        $binaryStringHash = hash_hmac($this->hmacAlgo, $binaryString, $this->privateKey, true);

        // Timing attack safe string comparison
        if(hash_equals($hmacHash, $binaryStringHash) === false)
            return false;

        return $this->unPack($binaryString);
    }

    public function pack($array)
    {
        if(!is_array($array))
            return false;

        $cnt = count($array);
        $header = pack('C', $cnt);
        $bin = '';

        for($i=0;$i<$cnt;$i++) {
            if(($strLen = strlen($array[$i])) > 65535 || $strLen === 0)
                return false;

            $header .= pack('S', $strLen);
            $bin .= $array[$i];
        }

        return $header.$bin;
    }

    public function unPack($bin)
    {
        if(empty($bin))
            return false;

        $arr = array();
        $cnt = unpack('C', $bin);
        $cnt = $cnt[1];

        if(!isset($bin[$cnt * 4]))
            return false;

        $header = substr($bin, 1, $cnt * 4);
        $bin = substr($bin, ($cnt * 2)+1);
        $int = unpack('S'.$cnt, $header);

        for($i=1;$i<=$cnt;$i++) {
            $val = substr($bin, 0, $int[$i]);

            if($val === false)
                return false;

            $arr[] = $val;
            $bin = substr($bin, $int[$i]);
        }

        if($bin !== false)
            return false;

        return $arr;
    }
}
?>
MiChAeLoKGB 23-May-2015 05:28
I did some testing to see the speed differences between serialize and json_encode, and my results with 250 iterations are:

PHP serialized in 0.0651714730263 seconds average
JSON encoded in 0.0254955434799 seconds average
json_encode() was roughly 155.62% faster than serialize()
Test took 27.2039430141 seconds with 300 iretations.

PHP serialized in 0.0564563179016 seconds average
JSON encoded in 0.0249140485128 seconds average
json_encode() was roughly 126.60% faster than serialize()
Test took 24.4148340225 seconds with 300 iretations.

From all my tests it looks like json_encode is on average about 120% faster (sometimes it gets to about 85% and sometimes to 150%).

Here is the PHP code you can run on your server to try it out:

<?php

// fillArray function myde by Peter Bailey
function fillArray($depth, $max){
    static $seed;
    if (is_null($seed)){
        $seed = array('a', 2, 'c', 4, 'e', 6, 'g', 8, 'i', 10);
    }
    if ($depth < $max){
        $node = array();
        foreach ($seed as $key){
            $node[$key] = fillArray( $depth + 1, $max );
        }
        return $node;
    }
    return 'empty';
}

function testSpeed($testArray, $iterations = 100){

    $json_time = array();
    $serialize_time = array();
    $test_start = microtime(true);

    for ($x = 1; $x <= $iterations; $x++){
        $start = microtime(true);
        json_encode($testArray);
        $json_time[] = microtime(true) - $start;

        $start = microtime(true);
        serialize($testArray);
        $serialize_time[] = microtime(true) - $start;
    }

    $test_lenght = microtime(true) - $test_start;
    $json_average = array_sum($json_time) / count($json_time);
    $serialize_average = array_sum($serialize_time) / count($serialize_time);

    $result = "PHP serialized in ".$serialize_average." seconds average<br>";
    $result .= "JSON encoded in ".$json_average." seconds average<br>";

    if ($json_average < $serialize_average){
        $result .= "json_encode() was roughly ".number_format( ($serialize_average / $json_average - 1 ) * 100, 2 )."% faster than serialize()<br>";
    } else if ( $serializeTime < $jsonTime ){
        $result .= "serialize() was roughly ".number_format( ($json_average / $serialize_average - 1 ) * 100, 2 )."% faster than json_encode()<br>";
    } else {
        $result .= "No way!<br>";
    }

    $result .= "Test took ".$test_lenght." seconds with ".$iterations." iterations.";

    return $result;

}

// Change the number of iterations (250) to lower if you exceed your maximum execution time
echo testSpeed(fillArray(0, 5), 250);

?>
Anonymous 14-Apr-2015 01:57
For everyone facing the conversion nightmare another Anonymous described here in an older comment (and he took the words out of my mouth), this T-SQL script might be of great help: https://github.com/mjohnsonperl/tsqlphpunserialize/tree/master.

Please do not follow the path of evil by dumping serialized data into relational databases.
tuxedobob 04-Jun-2014 04:36
When using serialize() to convert, say, an array to a string to pass via HTML forms, you will likely run into issues with quoting. This is because serialize() puts values in double quotes. The simplest solution is to quote your HTML form value with single quotes rather than double quotes. (This *is* allowed, according to W3C specs.)

So, instead of:

<?php
$arr = serialize($some_array);
?>
<input type="hidden" name="array" value="$arr" />

you would want to use:

<?php
$arr = serialize($some_array);
?>
<input type="hidden" name="array" value='$arr' />
Nanhe Kumar 27-Dec-2013 05:57
Note : You cannot save the state of a static variable by serializing.
<?php
/*
 * student.class.php
 */
class Student {

    public $name;
    private $roll;
    protected $age;
    static $class;

    public function __construct() {
        $this->name = "Nanhe Kumar";
        $this->roll = 1;
        $this->age = 16;
        Student::$class = "10+2";
    }

}
?>
<?php
/**
 * serialize.php
 */
include_once("student.class.php");

//Serialize
$so = new Student();
$serialized = serialize($so);
file_put_contents("test.txt", $serialized);
echo $serialized; //O:7:"Student":3:{s:4:"name";s:11:"Nanhe Kumar";s:13:"Studentroll";i:1;s:6:"*age";i:16;}
?>
<?php
/**
 * unserialize.php
 */
include_once("student.class.php");
$content = file_get_contents("test.txt");
$unserialized = unserialize($content);
print_r($unserialized);//Student Object ( [name] => Nanhe Kumar [roll:Student:private] => 1 [age:protected] => 16 )
?>
frost at easycast dot ru 23-Sep-2013 10:56
Closures cannot be serialized:
<?php
$func = function () {echo 'hello!';};
$func(); // prints "hello!"

$result = serialize($func);  // Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'Closure' is not allowed'
?>
allan666 at gmail.com 07-Mar-2013 01:28
Oddly, if you serialize a class that was previously unserialized, the class of the variable changes to string... Example:

$R = unserialize($serialized_object);
$R->method(); // this is ok
$str = serialize($R);
echo(get_class($R));

this will output "string"!!!!! whereas if the first line was

$R = new my_class();

it would output "my_class"!

I don't know if that is a bug, but the manual is not clear about that! (somehow $R in serialize($R) is being passed by reference, since it changes class).
nh at ngin dot de 21-Jan-2013 09:59
Serializing floating point numbers leads to weird precision offset errors:

<?php

echo round(96.670000000000002, 2);
// 96.67

echo serialize(round(96.670000000000002, 2));
// d:96.670000000000002;

echo serialize(96.67);
// d:96.670000000000002;

?>

Not only is this wrong, but it adds a lot of unnecessary bulk to serialized data. Probably better to use json_encode() instead (which apparently is faster than serialize(), anyway).
Andrew B 05-Sep-2012 09:42
When you serialize an array the internal pointer will not be preserved. Apparently this is the expected behavior but was a bit of a gotcha moment for me. Copy and paste example below.

<?php
//Internal Pointer will be 2 once variables have been assigned.
$array = array();
$array[] = 1;
$array[] = 2;
$array[] = 3;

//Unset variables. Internal pointer will still be at 2.
unset($array[0]);
unset($array[1]);
unset($array[2]);

//Serialize
$serializeArray = serialize($array);

//Unserialize
$array = unserialize($serializeArray);

//Add a new element to the array
//If the internal pointer was preserved, the new array key should be 3.
//Instead the internal pointer has been reset, and the new array key is 0.
$array[] = 4;

//Expected Key - 3
//Actual Key - 0
echo "<pre>" , print_r($array, 1) , "</pre>";
?>
Anonymous 28-Feb-2012 07:44
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.

I've encountered this too many times in my career, it makes for difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.

That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
pgl at yoyo dot org 03-Feb-2011 09:13
Another suggestion for coping with binary data in serialize()d variables is just to base64_encode() those fields before serializing. It will increase the size of the variable, but not by too much.
travis at travishegner dot com 02-Mar-2010 12:37
If serializing objects to be stored into a postgresql database, the 'null byte' injected for private and protected members throws a wrench into the system. Even pg_escape_bytea() on the value, and storing the value as a binary type fails under certain circumstances.

For a dirty work around:
<?php

$serialized_object = serialize($my_object);
$safe_object = str_replace("\0", "~~NULL_BYTE~~", $serialized_object);

?>

this allows you to store the object in a readable text format as well. When reading the data back:

<?php

$serialized_object = str_replace("~~NULL_BYTE~~", "\0", $safe_object);
$my_object = unserialize($serialized_object);

?>

The only gotcha's with this method is if your object member names or values may somehow contain the odd "~~NULL_BYTE~~" string. If that is the case, then str_replace() to a string that you are guaranteed not to have any where else in the string that serialize() returns.
Also remember to define the class before calling unserialize().

If you are storing session data into a postgresql database, then this workaround is an absolute must, because the $data passed to the session's write function is already serialized.

Thanks,
Travis Hegner
Anonymous 21-Jan-2010 09:23
you should really use mysql_real_escape_string() for escaping (serialized) strings that got thrown into a query (visit php.net/mysql_real_escape_string for further information)
donotmail at me dot com 02-Sep-2009 11:16
NOTE: php's serialize does not properly serialize arrays with which a slice of the array is a reference to the array itself, observe:

<?php
$a = array();
$a[0] = "blah";
$a[1] =& $a;

$a[1][0] = "pleh"; // $a[0] === "pleh"

$b = unserialize(serialize($a));

// $b[0] == "pleh", $b[1][0] == "pleh"

$b[1][0] = "blah";
?>

now $b[1][0] == "blah", but $b[0] == "pleh"
after serializing and unserializing, slice 1 is no longer a reference to the array itself... I have found no way around this problem... even manually modifying the serialized string from
'a:2:{i:0;s:4:"pleh";i:1;a:2:{i:0;s:4:"pleh";i:1;R:3;}}'
to
'a:2:{i:0;s:4:"pleh";i:1;R:1;}'

to force the second slice to be a reference to the first element of the serialization (the array itself), it seemed to work at first glance, but then unreferences it when you alter it again, observe:

<?php
    $testser = 'a:2:{i:0;s:4:"pleh";i:1;R:1;}';

    $tmp = unserialize($testser);

    print_r($tmp);

    print "\n-----------------------\n";

    $tmp[1][0] = "blah";

    print_r($tmp);

?>

outputs:
Array
(
    [0] => pleh
    [1] => Array
 *RECURSION*
)

-----------------------
Array
(
    [0] => pleh
    [1] => Array
        (
            [0] => blah
            [1] => Array
                (
                    [0] => pleh
                    [1] => Array
 *RECURSION*
                )

        )

)
Alessandro Segala 17-Jul-2009 08:18
I needed to serialize an array to store it inside a database.
I was looking for a fast, simple way to do serialization, and I came out with 2 options: serialize() or json_encode().

I ran some benchmarks to see which is the faster, and, surprisingly, I found that serialize() is always between 46% and 96% SLOWER than json_encode().
So, if you don't need to serialize objects and have the json extension available, consider using it instead of serialize().
barbuj at NOSPAM dot yahoo dot com 14-Nov-2007 02:19
In my specific situation, I wanted to be able to pass some data from page to page, but without relying on a session variable. The answer I came up with was to serialize() the object in question, pass it on to the next page as a hidden form field, then unserialize() it. When ALL class variables are public, this worked fine. However, if there was at least one private/protected variable, the code no longer worked as expected ("Fatal error: Call to a member function display() on a non-object in page2.php on line 4")

As others have already mentioned, private/protected class variables will not behave nicely (private variables are prefixed by class_name + &#65533;, while protected variables are only prefixed by &#65533; - when looking at the page source using Firefox). Internet Explorer does NOT display the extra character between the class name and variable name, but the code still doesn't work as one would expect.

Suppose you have a simple class:

testclass.php
=============
<?php
class TestClass {
  var $i = 1;

  function display() {
    echo "i=" . $this->i;
  }
?>

page1.php
=========
<?php
  require_once 'testclass.php';
  $tc = new TestClass;
  $tc->display();
?>
<form method = "post" action = "page2.php">
<input type = "hidden" name = "str" value = "<?php echo htmlspecialchars( serialize( $tc ) ); ?>">
<input type = "submit">
</form>

page2.php
=========
<?php
  require_once 'testclass.php';
  $tc = unserialize( stripslashes( htmlspecialchars_decode( $_POST["str"] ) ) );
  $tc->display();
?>

The fix, suggested by evulish on #php/irc.dal.net, is to replace htmlspecialchars()/htmlspecialchars_decode() by base64_encode()/base64_decode. The code becomes:

page1.php
=========
<input type = "hidden" name = "str" value = "<?php echo base64_encode( serialize( $tc ) ); ?>">

page2.php
=========
<?php
  $tc = unserialize( base64_decode( $_POST["str"] ) );
?>

Hope this will help someone...
Jeex 06-Nov-2007 02:59
It may be worth noting that, depending on the size of the object you are serializing, the serialize function can take up a lot of memory.

If your script isn't working as expected, your serialize call may have pushed the memory usage over the limit set by memory_limit in php.ini.

More info on memory limits here: http://www.php.net/manual/en/ini.core.php
friday13 at ig dot com dot br 19-Jun-2007 07:15
I have problem to use serialize function with hidden form field and the resolution was use htmlentities.

Ex.:

<?

$lista = array( 'pera', 'maça', 'laranja' );

print "< input type='hidden' name='teste' value='htmlentities( serialize( $lista ) )'" >";

?>
Ates Goral 18-Jul-2006 11:59
Corrections/clarifications to  "Anatomy of a serialize()'ed value":

All strings appear inside quotes. This applies to string values, object class names and array key names. For example:

s:3:"foo"
O:7:"MyClass":1:{...
a:2:{s:3:"bar";i:42;...

Object property names and values are delimited by semi-colons, not colons. For example:

O:7:"MyClass":2:{s:3:"foo";i:10;s:3:"bar";i:20}

Double/float values are represented as:

d:0.23241446
egingell at sisna dot com 15-May-2006 05:12
<?
/*
Anatomy of a serialize()'ed value:

 String
 s:size:value;

 Integer
 i:value;

 Boolean
 b:value; (does not store "true" or "false", does store '1' or '0')

 Null
 N;

 Array
 a:size:{key definition;value definition;(repeated per element)}

 Object
 O:strlen(object name):object name:object size:{s:strlen(property name):property name:property definition;(repeated per property)}

 String values are always in double quotes
 Array keys are always integers or strings
    "null => 'value'" equates to 's:0:"";s:5:"value";',
    "true => 'value'" equates to 'i:1;s:5:"value";',
    "false => 'value'" equates to 'i:0;s:5:"value";',
    "array(whatever the contents) => 'value'" equates to an "illegal offset type" warning because you can't use an
    array as a key; however, if you use a variable containing an array as a key, it will equate to 's:5:"Array";s:5:"value";',
     and
    attempting to use an object as a key will result in the same behavior as using an array will.
*/
?>
MC_Gurk at gmx dot net 03-Jan-2006 07:44
If you are going to serialie an object which contains references to other objects you want to serialize some time later, these references will be lost when the object is unserialized.
The references can only be kept if all of your objects are serialized at once.
That means:

$a = new ClassA();
$b = new ClassB($a); //$b containes a reference to $a;

$s1=serialize($a);
$s2=serialize($b);

$a=unserialize($s1);
$b=unserialize($s2);

now b references to an object of ClassA which is not $a. $a is another object of Class A.

use this:
$buf[0]=$a;
$buf[1]=$b;
$s=serialize($buf);
$buf=unserialize($s);
$a=$buf[0];
$b=$buf[1];

all references are intact.
Alexander Podgorny 02-Dec-2005 11:47
Here is an example of a base class to implement object persistence using serialize and unserialize:

<?php
class Persistent
{
    var $filename;

    /**********************/
    function Persistent($filename)
    {
        $this->filename = $filename;
        if(!file_exists($this->filename)) $this->save();
    }
    /**********************/
    function save()
    {
        if($f = @fopen($this->filename,"w"))
        {
            if(@fwrite($f,serialize(get_object_vars($this))))
            {
                @fclose($f);
            }
            else die("Could not write to file ".$this->filename." at Persistant::save");
        }
        else die("Could not open file ".$this->filename." for writing, at Persistant::save");

    }
    /**********************/
    function open()
    {
        $vars = unserialize(file_get_contents($this->filename));
        foreach($vars as $key=>$val)
        {
            eval("$"."this->$key = $"."vars['"."$key'];");
        }
    }
    /**********************/
}

?>

When an object is extended from this one it can be easily saved and re-opened using it's own methods as follows:

<?

class foo extends Persistent
{
   var $counter;
   function inc()
   {
       $this->counter++;
   }
}

$fooObj = new $foo;
$foo->open();
print $foo->counter; // displays incrementing integer as page reloads
$foo->inc();
$foo->save();

?>
stephen dot adamson at smius dot com 01-Nov-2005 09:40
If you are serializing an object to store it in the database, using __sleep() can save you some space. The following code will not store empty (null) variables in the serialized string. For my purposes this saved a lot of space, since some of the member variables would not be given values.

function __sleep()
{
    $allVars = get_object_vars($this);
    $toReturn = array();
    foreach(array_keys($allVars) as $name)
    {
        if (isset($this->$name))
        {
            $toReturn[] = $name;
        }
    }
    return $toReturn;
}
wiart at yahoo dot com 16-Dec-2004 03:40
Warning: on 64 bits machines,  if you use a long string only composed of numbers as a key in an array and serialize/unserialize it, you can run into problems:

an example code:
$arr["20041001103319"] = 'test';
var_dump( $arr);
$arr_in_str = serialize($arr);
print "Now result is: $arr_in_str<BR />";
$final_arr = unserialize($arr_in_str);
print "The final unserialized array:<BR />";
var_dump($final_arr);

The result:
array(1) { [20041001103319]=>  string(4) "test" }
Now result is: a:1:{i:20041001103319;s:4:"test";}
The final unserialized array:
array(1) { [683700183]=> string(4) "test" }

As you can see, the original array :
$arr["20041001103319"] = "test"

after serialize/unserialize is:
$arr[683700183] = "test"

As you can see,  the key has changed ...

Apparently a problem of implicit casting + integer overflow (I posted a PHP bug report: http://bugs.php.net/bug.php?id=31117)

I tested with the latest 4.3.10 compiled on my laptop (32 bits, Mandrake 9.1) --> no such problem. But compiled on AMD 64 bits (Red Hat Taroon), the problem is present.

Hope this will help some of you to not loose almost a whole day of debugging ;-)
paul at moveNOtoSPAMiceland DOT com 18-Nov-2004 08:29
I was trying to submit a serialized array through a hidden form field using POST and was having a lot of trouble with the quotes. I couldn't figure out a way to escape the quotes in the string so that they'd show up right inside the form, so only the characters up to the first set of quotes were being sent.

My solution was to base64_encode() the string, put that in the hidden form field, and send that through the POST method. Then I decoded it (using base64_decode()) on the other end. This seemed to solve the problem.
hfuecks at phppatterns dot com 21-Apr-2004 08:20
Regarding serializing PHP data types to Javascript, following Ivans note below, theres an example at http://www.tekool.net/php/js_serializer/.

The basic serialization looks good although, in its current form, it works on the basis of generating Javascript source which a browser executes as a page loads. Using Javascripts eval() the same can be done with strings containing Javascript if youre working with something like XMLHTTPRequest
pli9 at itsa dot ucsf dot edu 31-Jan-2003 11:05
I have also written some code for importing serialized PHP data into PERL and then writing it back into PHP.  I think the similar library posted above is actually more robust for a few select cases, but mine is more compact and a little easier to follow.  I'd really like comments if anyone finds this useful or has improvements.  Please credit me if you use my code.

http://www.hcs.harvard.edu/~pli/code/serialPHP.pm
MarkRoedel at letu dot edu 21-Feb-2000 10:58
A call to serialize() appears to mess with the array's internal pointer.  If you're going to be walking through your array after serializing it, you'll want to make a call to reset() first.


Establece el tipo de una variable

  • « serialize
  • strval »
  • PHP Manual
  • Funciones de manejo de variables
  • Establece el tipo de una variable

settype

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

settype — Establece el tipo de una variable

Descripción

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

Establece el tipo de la variable var a tipo.

Parámetros

var

La variable a ser convertida.

tipo

Los posibles valores de tipo son:

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

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo settype()

<?php
$foo = "5bar"; // cadena
$bar = true;   // booleano

settype($foo, "integer"); // $foo es ahora 5   (entero)
settype($bar, "string");  // $bar es ahora "1" (cadena)
?>

Notas

Nota:

El máximo valor para "int" es PHP_INT_MAX.

Ver también

  • gettype() - Obtener el tipo de una variable
  • type-casting
  • type-juggling

User Contributed Notes

geoffsmiths at hotmail dot com 24-Dec-2019 10:23
Please note:

When using settype to convert indexed arrays to objects, the properties of the typed object will be integers:

A brief example:

$a = ['1', '2'];

settype($a, 'object');

var_dump($a);

// output
object(stdClass)#1 (2) {
  ["0"]=>
  string(1) "1"
  ["1"]=>
  string(1) "2"
}
Anonymous 04-Jan-2019 01:41
If you attempt to convert the special $this variable from an instance method (only in classes) :
* PHP will silently return TRUE and leave $this unchanged if the type was 'bool', 'array', 'object' or 'NULL'
* PHP will generate an E_NOTICE if the type was 'int', 'float' or 'double', and $this will not be casted
* PHP will throw a catchable fatal error when the type is 'string' and the class does not define the __toString() method
Unless the new variable type passed as the second argument is invalid, settype() will return TRUE. In all cases the object will remain unchanged.
<?php
    // This was tested with PHP 7.2
    class Foo {
        function test() {
            printf("%-20s %-20s %s\n", 'Type', 'Succeed?', 'Converted');

            // settype() should throw a fatal error, as $this cannot be re-assigned
            printf("%-20s %-20s %s\n", 'bool', settype($this, 'bool'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'int', settype($this, 'int'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'float', settype($this, 'float'), print_r($this));
            printf("%-20s %-20s %s\n", 'array', settype($this, 'array'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'object', settype($this, 'object'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'unknowntype', settype($this, 'unknowntype'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'NULL', settype($this, 'NULL'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'string', settype($this, 'string'), print_r($this, TRUE));
        }
    }
    $a = new Foo();
    $a->test();
?>
Here is the result :
Type                 Succeed?             Converted
bool                 1                    Foo Object
(
)

Notice: Object of class Foo could not be converted to int in C:\php\examples\oop-settype-this.php on line 9

int                  1                    Foo Object
(
)

Notice: Object of class Foo could not be converted to float in C:\php\examples\oop-settype-this.php on line 10

float                1                    Foo Object
(
)

array                1                    Foo Object
(
)

object               1                    Foo Object
(
)

Warning: settype(): Invalid type in C:\php\examples\oop-settype-this.php on line 14

unknowntype                               Foo Object
(
)

NULL                 1                    Foo Object
(
)

Catchable fatal error: Object of class Foo could not be converted to string in C:\php\examples\oop-settype-this.php on line 15

If the class Foo implements __toString() :
<?php
    class Foo {
        // ...
        function __toString() {
            return 'Foo object is awesome!';
        }
        // ...
    }
?>
So the first code snippet will not generate an E_RECOVERABLE_ERROR, but instead print the same string as for the other types, and not look at the one returned by the __toString() method.

Hope this helps !  :)
Skayo 26-Jul-2017 08:59
$foo = "1";
settype($foo, "bool");
var_dump($foo); // Outputs: bool(true)

$bar = "0";
settype($bar, "bool");
var_dump($bar); // Outputs: bool(false)
marjune 10-Nov-2016 05:31
any digit except 0 or -0 are considered true in boolean, and any string except '0' or '' are also considered true.

<?php

$foo = '0';
settype($foo, 'boolean');
var_dump($foo); // false

$foo = 0;
settype($foo, 'boolean');
var_dump($foo); // false
Special Notes 26-Feb-2012 12:00
Note that you can't use this to convert a string 'true' or 'false' to a boolean variable true or false as a string 'false' is a boolean true. The empty string would be false instead...

<?php
$var = "true";
settype($var, 'bool');
var_dump($var); // true

$var = "false";
settype($var, 'bool');
var_dump($var); // true as well!

$var = "";
settype($var, 'bool');
var_dump($var); // false
?>
Chris Sullins 18-Apr-2010 11:59
settype() has some really strange, potentially buggy behavior.

As noted by Michael Benedict, using settype() on a variable will initialize that variable.  What is stranger is that using settype() on an uninitialized variable that you are treating as an array or object will also initialize the variable.  So:

<?php
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

This works for a chain of any length: $foo->bar['baz']->etc

Next we look at what happens if $foo is already set.

<?php
$foo = false;
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

In and of itself, this wouldn't be problematic.  It might even make sense.  But in all other cases where $foo is defined, even if (boolean) $foo === false, it will throw an error unless $foo->bar is valid (i.e. $foo is an object already).

<?php
$foo = true;
settype($foo->bar,"integer"); // Notice: Trying to get property of non-object
?>
NWdev 17-Nov-2008 09:38
In trying to convert an array of strings to an array of ints,
I attempted to use settype with array_walk.

<?php
//$numArray is generated by another process
$numArray = array('13','14','33');

var_dump($numArray);

//my conversion function
function str_to_int($val){
  //remember: settype($x, 'int') returns boolean (1=success, 0=failure)
  //--> so return $x to return new value
    settype($val,'int');
    echo "<br />gettype = ".gettype($val)."<br />";
    return $val;
}

array_walk($numArray,'str_to_int');

var_dump($numArray);
?>

The var_dumps both return the following:
<?php
array(3) { [0]=> string(2) "13" [1]=> string(2) "14" [2]=> string(2) "33" }
?>

The gettype echo will show the value as an integer.

So it seems that settype($val,'int') makes the conversion,
but the function return value remains a string.
Since settype returns a boolean, using
<?php $val = settype($val, 'int'); ?>
is not a option.

I resolved my array value conversion using this instead:
<?php
$numArray =
      array_map(create_function('$value', 'return (int)$value;'),$numArray);
?>
Thanks to the posting here:
http://usrportage.de/archives/
808-Convert-an-array-of-strings-into-an-array-of-integers.html

Perhaps this will save someone else spinning wheels a bit.

Also thanks to robin at barafranca dot com for
pointing out the boolean return value of settype.
robin at barafranca dot com 05-Mar-2008 04:20
Just a quick note, as this caught me out very briefly:

settype() returns bool, not the typecasted variable - so:

$blah = settype($blah, "int"); // is wrong, changes $blah to 0 or 1
settype($blah, "int"); // is correct

Hope this helps someone else who makes a mistake.. ;)
ludvig dot ericson gmail.dot com 09-Apr-2006 08:36
To matt:
This function accepts a paremeter, which does not imply you using hardcoded stuff, instead you can let the user choose! \o/

As a part of a framework or something.

Plus, you can probably call this with call_user_func
matt at mattsoft dot net 06-Dec-2005 09:49
using (int) insted of the settype function works out much better for me. I have always used it. I personally don't see where settype would ever come in handy.
Michael Benedict 29-Oct-2005 10:55
note that settype() will initialize an undefined variable.  Therefore, if you want to preserve type and value, you should wrap the settype() call in a call to isset().

<?php
settype($foo, "integer");
echo("|$foo|");
?>

prints "|0|", NOT "||".

To get the latter, use:
<?php
if(isset($foo)) settype($foo, "integer");
echo("|$foo|");
?>
nospamplease at veganismus dot ch 22-Jul-2005 07:38
you must note that this function will not set the type permanently! the next time you set the value of that variable php will change its type as well.
reinier_deblois at hotmail dot com 13-Mar-2005 09:18
Instead of settype you could use:
<?php

$int=593;  // $int is a integer

$int.="";   // $int is now a string
memandeemail at gmail dot com 09-Dec-2004 05:17
/**
    * @return bool
    * @param array[byreference] $values
    * @desc Convert an array or any value to Escalar Object [not tested in large scale]
    */
    function setobject(&$values) {
        $values = (object) $values;
        foreach ($values as $tkey => $val) {
            if (is_array($val)) {
                setobject($val);
                $values->$tkey = $val;
            }
        }
        return (bool) $values;
    }
sdibb at myway dot com 06-Sep-2003 10:03
Using settype is not the best way to convert a string into an integer, since it will strip the string wherever the first non-numeric character begins.  The function intval($string) does the same thing.

If you're looking for a security check, or to strip non-numeric characters (such as cleaning up phone numbers or ZIP codes),  try this instead:

<?
     $number=ereg_replace("[^0-9]","",$number);
?>
ns at canada dot com 05-May-2000 04:38
This settype() behaviour seems consistent to me. Quoting two sections from the manual:

"When casting from a scalar or a string variable to an array, the variable will become the first element of the array: "
<pre>
2 $var = 'ciao';
3 $arr = (array) $var;
4 echo $arr[0];  // outputs 'ciao'
</pre>

And if (like your code above) you do a settype on an empty variable, you'll end up with a one element array with an empty (not unset!) first element. So appeanding to it will start appending at index 1. As for why reset() doesn't do anything:

"When you assign a value to an array variable using empty brackets, the value will be added onto the end of the array."

It doesn't matter where the array counter is; values are added at the end, not at the counter.


Obtiene el valor de cadena de una variable

  • « settype
  • unserialize »
  • PHP Manual
  • Funciones de manejo de variables
  • Obtiene el valor de cadena de una variable

strval

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

strval — Obtiene el valor de cadena de una variable

Descripción

strval ( mixed $var ) : string

Obtener el valor de la cadena de una variable. Vea la documentación sobre el tipo de dato string para obtener más información sobre la conversión a cadena.

Esta función no realiza ninguna de formato en el valor devuelto. Si está buscando una manera de dar formato a un valor numérico como una cadena, por favor consulte las funciones sprintf() o number_format().

Parámetros

var

La variable que se está convirtiendo en un string.

var puede ser cualquier tipo escalar o un objeto que implemente el método __toString(). No puede usar strval() en arrays u objetos que no implementen el método __toString().

Valores devueltos

El valor string de var.

Ejemplos

Ejemplo #1 strval() usando el método mágico __toString() de PHP 5

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

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

Ver también

  • boolval() - Obtener el valor booleano de una variable
  • floatval() - Obtener el valor flotante de una variable
  • intval() - Obtiene el valor entero de una variable
  • settype() - Establece el tipo de una variable
  • sprintf() - Devuelve un string formateado
  • number_format() - Formatear un número con los millares agrupados
  • Manipulación de Tipos
  • __toString()

User Contributed Notes

Mark Clements 02-Jun-2016 01:17
Some notes about how this function has changed over time, with regards the following statement:

> You cannot use strval() on arrays or on objects that
> do not implement the __toString() method.

== Arrays ==

In PHP 5.3 and below, strval(array(1, 2, 3)) would return the string "Array" without any sort of error occurring.

From 5.4 and above, the return value is unchanged but you will now get a notice-level error: "Array to string conversion".

== Objects ==

For objects that do not implement __toString(), the behaviour has varied:

PHP 4: "Object"
PHP 5 < 5.2: "Object id #1" (number obviously varies)
PHP >= 5.2: Catchable fatal error:  Object of class X could not be converted to string
Hayley Watson 21-Aug-2007 08:53
As of PHP 5.2, strval() will return the string value of an object, calling its __toString() method to determine what that value is.
NyctoFixer at gmail dot com 11-Jun-2007 12:19
As of PHP 5.1.4 (I have not tested it in later versions), the strval function does not attempt to invoke the __toString method when it encounters an object. This simple wrapper function will handle this circumstance for you:

<?

/**
 * Returns the string value of a variable
 *
 * This differs from strval in that it invokes __toString if an object is given
 * and the object has that method
 */
function stringVal ($value)
{
    // We use get_class_methods instead of method_exists to ensure that __toString is a public method
    if (is_object($value) && in_array("__toString", get_class_methods($value)))
        return strval($value->__toString());
    else
        return strval($value);
}

?>
kendsnyder+phpnet at gmail dot com 01-Jun-2007 10:08
The only way to convert a large float to a string is to use printf('%0.0f',$float); instead of strval($float); (php 5.1.4).

// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015

// full conversion
printf('%0.0f',pow(2,50)); // 112589906846624
echo sprintf('%0.0f',pow(2,50)); // 112589906846624
portos_ze_retour at hotmail dot fr 10-Mar-2006 08:15
In complement to Tom Nicholson's contribution, here is the french version (actually it's possible to change the language, but you should check the syntax ;) )

function int_to_words($x) {
   global $nwords;

   if(!is_numeric($x))
     $w = '#';
   else if(fmod($x, 1) != 0)
     $w = '#';
   else {
     if($x < 0) {
         $w = $nwords['minus'].' ';
         $x = -$x;
     } else
         $w = '';
     // ... now $x is a non-negative integer.

     if($x < 21)  // 0 to 20
         $w .= $nwords[$x];
     else if($x < 100) {  // 21 to 99
         $w .= $nwords[10 * floor($x/10)];
         $r = fmod($x, 10);
         if($r > 0)
           $w .= '-'. $nwords[$r];
     } else if($x < 1000) {  // 100 to 999
         $w .= $nwords[floor($x/100)] .' '.$nwords['hundred'];
         $r = fmod($x, 100);
         if($r > 0)
           $w .= ' '.$nwords['separator'].' '. int_to_words($r);
     } else if($x < 1000000) {  // 1000 to 999999
         $w .= int_to_words(floor($x/1000)) .' '.$nwords['thousand'];
         $r = fmod($x, 1000);
         if($r > 0) {
           $w .= ' ';
           if($r < 100)
               $w .= $nwords['separator'].' ';
           $w .= int_to_words($r);

         }
     } else {    //  millions
         $w .= int_to_words(floor($x/1000000)) .' '.$nwords['million'];
         $r = fmod($x, 1000000);
         if($r > 0) {
           $w .= ' ';
           if($r < 100)
               $word .= $nwords['separator'].' ';
           $w .= int_to_words($r);
         }
     }
   }
   return $w;
}

 // Usage in English
$nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven",
                   "eight", "nine", "ten", "eleven", "twelve", "thirteen",
                   "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
                   "nineteen", "twenty", 30 => "thirty", 40 => "forty",
                   50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty",
                   90 => "ninety" , "hundred" => "hundred", "thousand"=> "thousand", "million"=>"million",
                   "separator"=>"and", "minus"=>"minus");

echo 'There are currently '. int_to_words(-120223456) . ' members logged on.<br>';

 //Utilisation en Francais
$nwords = array( "zéro", "un", "deux", "trois", "quatre", "cinq", "six", "sept",
                   "huit", "neuf", "dix", "onze", "douze", "treize",
                   "quatorze", "quinze", "seize", "dix-sept", "dix-huit",
                   "dix-neuf", "vingt", 30 => "trente", 40 => "quarante",
                   50 => "cinquante", 60 => "soixante", 70 => "soixante-dix", 80 => "quatre-vingt",
                   90 => "quatre-vingt-dix" , "hundred" => "cent", "thousand"=> "mille", "million"=>"million",
                   "separator"=>"", "minus"=>"moins");

echo 'Il y a actuellement '. int_to_words(-120223456) . ' membres connectés.<br>';
php at ianco dot co dot uk 07-Oct-2005 04:36
I can't help being surprised that

(string)"0" == (string)"0.00"

evaluates to true. It's the same with strval and single quotes.
=== avoids it.

Why does it matter? One of my suppliers, unbelievably, uses 0 to mean standard discount and 0.00 to mean no discount in their stock files.
Steve Ball 08-Sep-2005 07:18
It seems that one is being treated as an unsigned large int (32 bit), and the other as a signed large int (which has rolled over/under).

2326201276 - (-1968766020) =  4294967296.
Tom Nicholson 28-Apr-2004 09:13
If you want to convert an integer into an English word string, eg. 29 -> twenty-nine, then here's a function to do it.

Note on use of fmod()
  I used the floating point fmod() in preference to the % operator, because % converts the operands to int, corrupting values outside of the range [-2147483648, 2147483647]

I haven't bothered with "billion" because the word means 10e9 or 10e12 depending who you ask.

The function returns '#' if the argument does not represent a whole number.

<?php
$nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven",
                   "eight", "nine", "ten", "eleven", "twelve", "thirteen",
                   "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
                   "nineteen", "twenty", 30 => "thirty", 40 => "forty",
                   50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty",
                   90 => "ninety" );

function int_to_words($x) {
   global $nwords;

   if(!is_numeric($x))
      $w = '#';
   else if(fmod($x, 1) != 0)
      $w = '#';
   else {
      if($x < 0) {
         $w = 'minus ';
         $x = -$x;
      } else
         $w = '';
      // ... now $x is a non-negative integer.

      if($x < 21)   // 0 to 20
         $w .= $nwords[$x];
      else if($x < 100) {   // 21 to 99
         $w .= $nwords[10 * floor($x/10)];
         $r = fmod($x, 10);
         if($r > 0)
            $w .= '-'. $nwords[$r];
      } else if($x < 1000) {   // 100 to 999
         $w .= $nwords[floor($x/100)] .' hundred';
         $r = fmod($x, 100);
         if($r > 0)
            $w .= ' and '. int_to_words($r);
      } else if($x < 1000000) {   // 1000 to 999999
         $w .= int_to_words(floor($x/1000)) .' thousand';
         $r = fmod($x, 1000);
         if($r > 0) {
            $w .= ' ';
            if($r < 100)
               $w .= 'and ';
            $w .= int_to_words($r);
         }
      } else {    //  millions
         $w .= int_to_words(floor($x/1000000)) .' million';
         $r = fmod($x, 1000000);
         if($r > 0) {
            $w .= ' ';
            if($r < 100)
               $word .= 'and ';
            $w .= int_to_words($r);
         }
      }
   }
   return $w;
}

?>

Usage:
<?php
echo 'There are currently '. int_to_words($count) . ' members logged on.';
?>


Crea un valor PHP a partir de una representación almacenada

  • « strval
  • unset »
  • PHP Manual
  • Funciones de manejo de variables
  • Crea un valor PHP a partir de una representación almacenada

unserialize

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

unserialize — Crea un valor PHP a partir de una representación almacenada

Descripción

unserialize ( string $str , array $options = ? ) : mixed

unserialize() toma una única variable serializada y la vuelve a convertir a un valor de PHP.

Advertencia

No pases valores no confiables proporcionados por el usuario a unserialize() con independencia del valor dado en options a allowed_classes. La deserialización puede resultar en que el código sea cargado y ejecutado debido a la instanciación y autocarga de objetos, y un usuario malicioso podría ser capaz de explotar este comportamiento. Utiliza un formato de intercambio de datos estándar y seguro como JSON (mediante json_decode() y json_encode()) si necesitas pasar datos serializados al usuario.

Si necesitas deserializar datos almacenados externamente, considera utilizar hash_hmac() para verificarlos. Asegúrate de que los datos no son modificados por nadie excepto por ti.

Parámetros

str

El string serializado.

Si la variable que está siendo convertida de vuelta es un objeto, PHP intentará llamar la función miembro __wakeup() si existe) automáticamente luego de haber recontruido satisfactoriamente el objeto.

Nota: Directiva unserialize_callback_func

Es posible establecer una función-llamada de retorno la cual será llamada si una clase no definida debería ser instanciada durante el proceso de revertir la seriación(para prevenir que se reciba un object incompleto "__PHP_Incomplete_Class".) Use su php.ini, ini_set() o .htaccess para definir unserialize_callback_func. Cada vez que una clase no definida deba ser instanciada, esta función será llamada. Para deshabilitar esta característica simplemente asigne un valor vacío a este parámetro.

options

Cualquier opción para unserialize(), dada como un array asociativo.

Opciones válidas
Nombre | Tipo | Descripción
allowed_classes | mixed | Puede ser un array de nombres de clases que deben ser aceptadas, false para no aceptar clases, o true para aceptar todas las clases. Si esta opción se define y unserialize() encuentra un objeto de una clase que no se acepta, el objeto será instanciado como __PHP_Incomplete_Class en su lugar. La omisión de esta opción es lo mismo que definirla como true: PHP intentará instanciar objetos de cualquier clase.

Valores devueltos

El valor convertido es retornado, y puede ser un boolean, integer, float, string, array u object.

En caso de que el string pasado no pueda ser procesado para revertir la serialización, se devuelve false y un error de tipo E_NOTICE es generado.

Historial de cambios

Versión | Descripción
7.1.0 | El elemento allowed_classes de options) es ahora estrictamente tipado, es decir: si cualquier cosa distinta de un array o un boolean es proporcionada, unserialize() retornará false y lanzará un E_WARNING.
7.0.0 | Se añadió el parámetro options.
5.6.0 | Manipular los datos serializados reemplazando C: con O: para forzar la instanciación de objetos sin llamar al constructor ahora fallará.

Ejemplos

Ejemplo #1 Ejemplo de unserialize()

<?php
// Aquí usamos unserialize() para cargar los datos de sesión
// provenientes del string seleccionado desde la base de datos en el
// array $datos_sesion. Este ejemplo complementa aquel descrito con serialize().

$con  = odbc_connect("bd_web", "php", "gallina");
$sent = odbc_prepare($con, "SELECT datos FROM sesiones WHERE id = ?");
$datos_sql = array($_SERVER['PHP_AUTH_USER']);

if (!odbc_execute($sent, &$datos_sql) || !odbc_fetch_into($sent, &$tmp)) {
    // si la ejecución del comando o la recuperación de datos falla,
    // inicializar una matriz vacía
    $datos_sesion = array();
} else {
    // ahora deberíamos tener los datos serializados en $tmp[0].
    $datos_sesion = unserialize($tmp[0]);
    if (!is_array($datos_sesion)) {
        // algo ha fallado, inicializar un array vacío
        $datos_sesion = array();
    }
}
?>

Ejemplo #2 Ejemplo de unserialize_callback_func

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

ini_set('unserialize_callback_func', 'mi_llamada_de_retorno'); // defina su callback_function

function mi_llamada_de_retorno($nombre_clase)
{
    // tan solo incluya un fichero que contenga su definición de clase
    // recibe $nombre_clase para determinar qué definición de clase requiere
}
?>

Notas

Advertencia

false es devuelto tanto en el caso de un error como cuando se convierte el valor seriado false. Es posible atrapar este caso especial comparando str con serialize(false) o atrapando el error E_NOTICE generado.

Ver también

  • json_encode() - Retorna la representación JSON del valor dado
  • json_decode() - Decodifica un string de JSON
  • hash_hmac() - Genera un valor cifrado mediante una clave especificada usando el método HMAC
  • serialize() - Genera una representación apta para el almacenamiento de un valor
  • Autocarga de clases
  • unserialize_callback_func
  • __wakeup()

User Contributed Notes

karsten at dambekalns dot de 27-Nov-2020 07:53
Keep in mind that the allowed_classes does not use inheritance, i.e. allowing an interface is not possible and sub-classes won't pass the check. See https://3v4l.org/tdHfl
hadley8899 at gmail dot com 13-Jan-2020 01:58
For the people who are getting the error

PHP Notice:  unserialize(): Error at offset 191 of 285 bytes in ...

and are getting the data from a database, Make sure that you have the database set the the correct encoding, I had the database set as latin1_swedish_ci and all of the data looked perfect, Infact when i copied it into a online unserialize it worked fine. I changed the collation to utf8mb4_unicode_ci and all worked fine.
Anonymous 11-Mar-2019 06:36
If serialize() is the answer, you're almost certainly asking the wrong question.

JSON is widely available. The only thing it does not do, is the very thing that makes serialization immensely dangerous. All it takes is a crafty hacker to pass a crafted payload to a supposedly 'secured' serialize call, for a database driver to be overwritten with malicious code, for example.

Recreate the object. Normally. With actual data, and a source file, not with serialize. To do otherwise is laziness bordering on malice.
me+phpnet at unreal4u dot com 30-Oct-2017 03:30
Just some reminder which may save somebody some time regarding the `$options` array:

Say you want to be on the safe side and not allow any objects to be unserialized... My first thought was doing the following:

<?php
$lol = unserialize($string, false);
// This will generate:
// Warning: unserialize() expects parameter 2 to be array, boolean given
?>

The correct way of doing this is the following:
<?php
$lol = unserialize($string, ['allowed_classes' => false]);
?>

Hope it helps somebody!
bjd 02-Jan-2017 12:49
Talk on Exploiting PHP7 Unserialize here: https://media.ccc.de/v/33c3-7858-exploiting_php7_unserialize
m.m.j.kronenburg 06-Sep-2016 09:52
You can use the following code to use the php 7 unserialize function in php 5.3 and upwards. This adds the $option argument.

<?php

namespace
{

/**
 * PHP 7 unserialize function for PHP 5.3 upwards.
 * Added the $option argument (allowed_classes).
 * See php unserialize manual for more detail.
 **/
function php7_unserialize($str, $options = array())
{
  if(version_compare(PHP_VERSION, '7.0.0', '>='))
  { return unserialize($str, $options); }

  $allowed_classes = isset($options['allowed_classes']) ?
    $options['allowed_classes'] : true;
  if(is_array($allowed_classes) || !$allowed_classes)
  {
    $str = preg_replace_callback(
      '/(?=^|:)(O|C):\d+:"([^"]*)":(\d+):{/',
      function($matches) use ($allowed_classes)
      {
        if(is_array($allowed_classes) &&
          in_array($matches[2], $allowed_classes))
        { return $matches[0]; }
        else
        {
          return $matches[1].':22:"__PHP_Incomplete_Class":'.
            ($matches[3] + 1).
            ':{s:27:"__PHP_Incomplete_Class_Name";'.
            serialize($matches[2]);
        }
      },
      $str
    );
  }
  unset($allowed_classes);
  return unserialize($str);
}

} // namespace

namespace my_name_space
{
  /**
   * Use the new php7 unserialize in your namespace without
   * renaming all unserialize(...) function calls to
   * php7_unserialize(...).
   **/
  function unserialize($str, $options = array())
  { return php7_unserialize($str, $options); }
}

?>
chris at pollett dot org 02-Jul-2015 03:28
When you serialize an object of a class from a particular namespace, the namespace is recorded as part of the serialization. If you decide to change this namespace's name, it can be hard to read in old serialized objects. I.e., suppose you had serialized an object of type foo\A, you change the namespace of your project to goo but otherwise leave the class definition of A unchanged. You would like to be able to unserialize the object as goo\A, instead unserialization will only create a partial object. To fix this in the case where you don't have nested objects in your class definition, you can use the following simple rename function:
/**
 * Used to change the namespace of a serialized php object (assumes doesn't
 * have nested subobjects)
 *
 * @param string $class_name new fully qualified name with namespace
 * @param string $object_string serialized object
 *
 * @return string serialized object with new name
 */
function renameSerializedObject($class_name, $object_string)
{
    /*  number of digits in the length of name of the object needs to be
        less than 12 digits (probably more like 4) for this to work.
    */
    $name_length = intval(substr($object_string, 2, 14));
    $name_space_info_length = strlen("O:".$name_length.":") +
        $name_length + 2; // 2 for quotes;
    $object_string = 'O:' .
        strlen($class_name) . ':"'. $class_name.'"' .
        substr($object_string, $name_space_info_length);
    return $object_string;
}
ErnestV 03-Aug-2013 01:05
Just a note - if the serialized string contains a reference to a class that cannot be instantiated (e.g. being abstract) PHP will immediately die with a fatal error. If the unserialize() statement is preceded with a '@' to avoid cluttering the logs with warns or notices there will be absolutely no clue as to why the script stopped working. Cost me a couple of hours...
Ray.Paseur often uses Gmail 26-Jul-2013 01:41
In the Classes and Objects docs, there is this: In order to be able to unserialize() an object, the class of that object needs to be defined.

Prior to PHP 5.3, this was not an issue.  But after PHP 5.3 an object made by SimpleXML_Load_String() cannot be serialized.  An attempt to do so will result in a run-time failure, throwing an exception.  If you store such an object in $_SESSION, you will get a post-execution error that says this:

Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed' in [no active file]:0 Stack trace: #0 {main} thrown in [no active file] on line 0

The entire contents of the session will be lost.  Hope this saves someone some time!

<?php // RAY_temp_ser.php
error_reporting(E_ALL);
session_start();
var_dump($_SESSION);
$_SESSION['hello'] = 'World';
var_dump($_SESSION);

// AN XML STRING FOR TEST DATA
$xml = '<?xml version="1.0"?>
<families>
  <parent>
    <child index="1" value="Category 1">Child One</child>
  </parent>
</families>';

// MAKE AN OBJECT (GIVES SimpleXMLElement)
$obj = SimpleXML_Load_String($xml);

// STORE THE OBJECT IN THE SESSION
$_SESSION['obj'] = $obj;
suman dot jis at gmail dot com 13-Mar-2012 09:12
I was getting unserialize()  Error at offset error.

If you face similar problem  then use the following procedure

$auctionDetails = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $dataArr[$i]['auction_details'] );
$auctionDetails = unserialize($auctionDetails);
walf 22-Aug-2011 08:22
a replacement for unserialize that returns whether it worked and populates the unserialized variable by reference:
<?php
function funserialize($serialized, &$into) {
    static $sfalse;
    if ($sfalse === null)
        $sfalse = serialize(false);
    $into = @unserialize($serialized);
    return $into !== false || rtrim($serialized) === $sfalse;//whitespace at end of serialized var is ignored by PHP
}

$s_foo = 'b:0;';
var_dump(funserialize($s_foo, $foo), $foo);

$s_bar = 'bar';
var_dump(funserialize($s_bar, $bar), $bar);

$s_foo = 'a:0:{};';
var_dump(funserialize($s_foo, $foo), $foo);

?>
gives:

bool(true)
bool(false)

bool(false)
bool(false)

bool(true)
array(0) {
}
MBa 02-Aug-2011 03:49
To check if a string is serialized:

$blSerialized=(@unserialize($sText)||$sText=='b:0;');
chris at colourlovers dot com 16-Jun-2011 05:31
Anyone having trouble serializing data with SimpleXMLElement objects stored within it, check this out:

This will traverse $data looking for any children which are instances of SimpleXMLElement, and will run ->asXML() on them, turning them into a string and making them serializable. Other data will be left alone.

<?php
function exportNestedSimpleXML($data) {
    if (is_scalar($data) === false) {
        foreach ($data as $k => $v) {
            if ($v instanceof SimpleXMLElement) {
                $v = str_replace("&#13;","\r",$v->asXML());
            } else {
                $v = exportNestedSimpleXML($v);
            }

            if (is_array($data)) {
                $data[$k] = $v;
            } else if (is_object($data)) {
                $data->$k = $v;
            }
        }
    }

    return $data;
}

$data = array (
    "baz" => array (
        "foo" => new stdClass(),
        "int" => 123,
        "str" => "asdf",
        "bar" => new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><foo>bar</foo>'),
    )
);

var_dump($data);
/*array(1) {
  ["baz"]=>
  array(4) {
    ["foo"]=>
    object(stdClass)#3 (0) {
    }
    ["int"]=>
    int(123)
    ["str"]=>
    string(4) "asdf"
    ["bar"]=>
    object(SimpleXMLElement)#4 (1) {
      [0]=>
      string(3) "bar"
    }
  }
}*/

var_dump(exportNestedSimpleXML($data));
/*array(1) {
  ["baz"]=>
  array(4) {
    ["foo"]=>
    object(stdClass)#3 (0) {
    }
    ["int"]=>
    int(123)
    ["str"]=>
    string(4) "asdf"
    ["bar"]=>
    string(54) "<?xml version="1.0" encoding="UTF-8"?>
<foo>bar</foo>
"
  }
}
*/
?>
daniel at fourstaples dot com 23-Mar-2010 08:46
Here's a simple function to get the class of a serialized string (that is, the type of object that will be returned if it's unserialized):

<?php
function get_serial_class($serial) {
    $types = array('s' => 'string', 'a' => 'array', 'b' => 'bool', 'i' => 'int', 'd' => 'float', 'N;' => 'NULL');

    $parts = explode(':', $serial, 4);
    return isset($types[$parts[0]]) ? $types[$parts[0]] : trim($parts[2], '"');
}
?>

I use this when saving a serialized object to a cookie, to make sure it is the right type when I go to unserialize it.

The type names are the same format/case as you would see if you did a var_dump().
Fagzal 09-Mar-2010 10:10
To all who have problem with quoting and slashes when storing serialized data in MySQL: you are probably doing it wrong.

Use e.g. PDO with placeholders and the blob column type, and it will Just Work.
arbie samong 10-Sep-2009 07:42
__PHP_Incomplete_Class Object Demystified

1. First take note of the output. A simple example:

__PHP_Incomplete_Class Object (
[__PHP_Incomplete_Class_Name] => SomeObject1
[obj1property1] => somevalue1 [obj1property2] => __PHP_Incomplete_Class Object ( [__PHP_Incomplete_Class_Name] => SomeObject2 [obj2property1] => somevalue1 [obj2property2] => Array (
['key1'] => somevalue3, ['key2'] => somevalue4 ) ) )

2. We analyze this and break it down.
__PHP_Incomplete_Class Object tells you there is an object that needs to be declared somehow.
__PHP_Incomplete_Class_Name simply tells you the expected class name. It is just one of the properties for now.

So we have:
a) an unknown object that has a class name SomeObject1 (first class)
b) it has 2 properties, namely obj1property1 and obj2property2
c) obj2property2 is itself an object whose class name is SomeObject2 (the second class)
d) SomeObject2 has two properties, obj2property1 and obj2property2
e) obj2property2 is an array that contains two elements

3. Now that we have an idea of the structure, we shall create class definitions based from it. We will just create properties for now, methods are not required as a minimum.

<?php
class SomeObject1 {
        public $obj1property1;
        public $obj1property2;
}
class SomeObject2 {
        public $obj2property1;
        public $obj2property2;
}
?>

4. Have that accessible to your script and it will solve the __PHP_Incomplete_Class Object problem as far as the output is concerned. Now you will have:

SomeObject1 ( [obj1property1] => somevalue1 [obj1property2] => SomeObject2 ( [obj2property1] => somevalue1 [obj2property2] => Array ( ['key1'] => somevalue3, ['key2'] => somevalue4 ) ) )

As you will notice, __PHP_Incomplete_Class Object is gone and replaced by the class name. The property __PHP_Incomplete_Class_Name is also removed.

5. As for the array property obj2property2, we can directly access that and just assume that it is an array and loop through it:

<?php

// this will be SomeObject1
$data = unserialize($serialized_data);

// this will be SomeObject2
$data2 = $data->obj1property2();

foreach($data2->obj2property2 as $key => $value):
         print $key.' : '. $value .'<br>';
endforeach;

?>

Outputs:
key1 : somevalue3
key2 : somevalue4

That's it. You can add more methods on the class declarations for the given properties, provided you keep your original output as basis for the data types.
w dot laurencine at teknoa dot net 07-Apr-2009 05:54
When dealing with a string which contain "\r", it seems that the length is not evaluated correctly. The following solves the problem for me :

<?php
// remove the \r caracters from the $unserialized string
$unserialized = str_replace("\r","",$unserialized);

// and then unserialize()
unserialize($unserialized);
?>
chris AT cmbuckley DOT co DOT uk 14-Aug-2008 06:47
As mentioned in the notes, unserialize returns false in the event of an error and for boolean false. Here is the first solution mentioned, without using error handling:

<?php
function isSerialized($str) {
    return ($str == serialize(false) || @unserialize($str) !== false);
}

var_dump(isSerialized('s:6:"foobar";')); // bool(true)
var_dump(isSerialized('foobar'));        // bool(false)
var_dump(isSerialized('b:0;'));          // bool(true)
?>
BenBE at omorphia dot de 02-Mar-2007 06:20
When trying to serialize or unserialize recursive arrays or otherwise linked data you might find the undocumented R data type quite useful.

If you want a array like the one produced with
<?
$a = array();
$a[0] =& $a;
?>
serialized you can store it using a string simular to this one:
<?
$a = unserialize("a:1:{i:0;R:1;}");
?>

Both sources will make $a hold an array that self-references itself in index 0.

The argument for R is the index of the created sub-variable of the serialize-string beginning with 1.
double at dumpit dot com 19-Dec-2006 05:09
This little function will check whether the serialized string is well formed.

PHP < 6 because i'd heard changes will be made in this php-intern function,
maybe it could be edited easy for it.

<?php

function wd_check_serialization( $string, &$errmsg )
{

    $str = 's';
    $array = 'a';
    $integer = 'i';
    $any = '[^}]*?';
    $count = '\d+';
    $content = '"(?:\\\";|.)*?";';
    $open_tag = '\{';
    $close_tag = '\}';
    $parameter = "($str|$array|$integer|$any):($count)" . "(?:[:]($open_tag|$content)|[;])";
    $preg = "/$parameter|($close_tag)/";
    if( !preg_match_all( $preg, $string, $matches ) )
    {
        $errmsg = 'not a serialized string';
        return false;
    }
    $open_arrays = 0;
    foreach( $matches[1] AS $key => $value )
    {
        if( !empty( $value ) && ( $value != $array xor $value != $str xor $value != $integer ) )
        {
            $errmsg = 'undefined datatype';
            return false;
        }
        if( $value == $array )
        {
            $open_arrays++;
            if( $matches[3][$key] != '{' )
            {
                $errmsg = 'open tag expected';
                return false;
            }
        }
        if( $value == '' )
        {
            if( $matches[4][$key] != '}' )
            {
                $errmsg = 'close tag expected';
                return false;
            }
            $open_arrays--;
        }
        if( $value == $str )
        {
            $aVar = ltrim( $matches[3][$key], '"' );
            $aVar = rtrim( $aVar, '";' );
            if( strlen( $aVar ) != $matches[2][$key] )
            {
                $errmsg = 'stringlen for string not match';
                return false;
            }
        }
        if( $value == $integer )
        {
            if( !empty( $matches[3][$key] ) )
            {
                $errmsg = 'unexpected data';
                return false;
            }
            if( !is_integer( (int)$matches[2][$key] ) )
            {
                $errmsg = 'integer expected';
                return false;
            }
        }
    }
    if( $open_arrays != 0 )
    {
        $errmsg = 'wrong setted arrays';
        return false;
    }
    return true;
}

?>
Are Pedersen 09-Aug-2006 01:46
Be aware that if useing serialize/unserialize in a serverfarm with both 32bit and 64bit servers you can get unexpected results.

Ex: if you serialize an integer with value of 2147483648 on a 64bit system and then unserialize it on a 32bit system you will get the value -2147483648 instead. This is because an integer on 32bit cannot be above 2147483647 so it wraps.
Chris Hayes (chris at hypersites dot com) 23-Oct-2004 09:27
In reply to the earlier post about having to include object definitions *before* using unserialize.  There is a workaround for this.

When an object is serialized, the first bit of the string is actually the name of the class.  When an unknown object is unserialized, this is maintained as a property.  So if you serialize it again, you get back the exact same string as if you'd serialized the original object.  Basically, to cut to the point...

If you use

$_SESSION['my_object'] = unserialize(serialize($_SESSION['my_object']))

then you get back an object of the correct type, even if the session had originally loaded it as an object of type stdClass.
aderyn at nowhere dot tld 30-Oct-2003 10:02
A quick note:
If you store a serialized object in a session, you have to include the class _before_ you initialize (session_start()) the session.


Destruye una variable especificada

  • « unserialize
  • var_dump »
  • PHP Manual
  • Funciones de manejo de variables
  • Destruye una variable especificada

unset

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

unset — Destruye una variable especificada

Descripción

unset ( mixed $var , mixed $... = ? ) : void

unset() destruye las variables especificadas.

El comportamiento de unset() dentro de una función puede variar dependiendo de qué tipo de variable que se está tratando de destruir.

Si una variable global es unset() dentro de una función, solo la variable local es destruida. La variable en el entorno de la llamada mantendrá el mismo valor anterior a la llamada a unset().

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

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

El resultado del ejemplo sería:

bar

Si desea aplicar unset() a una variable global dentro de una función, puede usar la matriz $GLOBALS para hacerlo:

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

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

Si una variable que se pasa POR REFERENCIA es unset() dentro de una función, sólo la variable local es destruida. La variable en el entorno de la llamada mantendrá el mismo valor anterior a la llamada a unset()

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

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

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

El resultado del ejemplo sería:

algo
algo

Si una variable estática es unset() dentro de una función, unset() destruye la variable únicamente en el contexto del resto de una función. Las llamadas siguientes recuperarán el valor previo de una variable.

<?php
function foo()
{
    static $bar;
    $bar++;
    echo "Antes de unset: $bar, ";
    unset($bar);
    $bar = 23;
    echo "Después de unset: $bar\n";
}

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

El resultado del ejemplo sería:

Antes de unset: 1, después de unset: 23
Antes de unset: 2, después de unset: 23
Antes de unset: 3, después de unset: 23

Parámetros

var

La variable a ser destruida.

...

Otra variable...

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo de unset()

<?php
// destruir una sola variable
unset($foo);

// destruir un solo elemento de una matriz
unset($bar['quux']);

// destruir más de una variable
unset($foo1, $foo2, $foo3);
?>

Ejemplo #2 Usando el forzado a (unset)

El forzado a (unset) a menudo se confunde con la función unset(). El forzado (unset) sólo sirve como una conversión de tipo NULL. Esto no altera la variable que se está forzando.

<?php
$name = 'Felipe';

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

El resultado del ejemplo sería:

NULL
string(6) "Felipe"

Notas

Nota: Puesto que esto es una construcción del lenguaje y no una función, no puede ser llamada usando funciones variables.

Nota:

Es posible remover incluso propiedades de objetos visibles en el contexto actual.

Nota:

No es posible remover $this dentro de un método de objeto a partir de PHP 5.

Nota:

Cuando se utiliza unset() sobre las propiedades de objetos inaccesibles, el método de sobrecarga __unset() será llamado, si se declara.

Ver también

  • isset() - Determina si una variable está definida y no es null
  • empty() - Determina si una variable está vacía
  • __unset()
  • array_splice() - Elimina una porción del array y la reemplaza con otra cosa

User Contributed Notes

ronan at shopping-feed dot com 04-Feb-2020 08:19
<?php

$list = ['a', 'b', 'c'];
next($list);
unset($list[1]);

echo current($list); // result : "c"
Phantasma_9 at yahoo dot com 08-Aug-2016 06:17
This is probably trivial but there is no error for unsetting a non-existing variable.
magnesium dot oxide dot play+php at gmail dot com 20-Mar-2014 08:10
You can unset superglobals like $GLOBALS, $_GET etc., but causing an unususal behavior (as of PHP 5.3.3).

1) unsetting of superglobals is done globally, i.e. unsetting inside the function affects GLOBALLY.

2) Recreation of unset'ed superglobals can be done (recreated valiables are superglobals), but original functionality (in $GLOBALS, $_SESSION ...) has lost.

<?php

function foo(){
  unset($GLOBALS);
}

function bar(){
  var_dump($GLOBALS);
}

foo();
bar(); //issues E_NOTICE ($GLOBALS not defined)
$GLOBALS=3;
bar(); //displays int(3)

?>
Hayley Watson 05-Mar-2013 09:41
You don't need to check that a variable is set before you unset it.
<?php
unset($a);
?>
is harmless.
<?php
if(isset($a)) {
    unset($a);
}
?>
is pointless complication.

This doesn't apply to properties of objects that have __isset() methods that visibly change object state or __unset() methods that don't properly check their arguments or have extra side effects.

The latter case means that __unset shouldn't do more than what it says on the tin, and also has the responsibility for checking (possibly using __isset()) that what it's being asked to do makes sense.

The former case is just plain bad design.
tigercat at aol dot com 10-Oct-2012 07:55
The combination of "global" and "unset" in functions can lead to some unexpected results.  This is because the "global" function creates a reference to a variable at the time it's executed, so a variable can be deleted out from under a "global $my_variable" declaration in a function.  Accessing data that's been deleted with an obsolete reference is usually a bad thing; in some languages it can generate a machine address fault.

<?php
$my_global_var = "old data";
f1();

function f1() // example of invalid variable reference use
{
  global $my_global_var;   // creates reference to global variable
  f2(); // recreates global variable, so reference is now invalid

// bad...
  echo $my_global_var;     // outputs "old data" (from invalid memory???)

// good...
  global $my_global_var;  // reestablish reference to new global variable
  echo $my_global_var;     // outputs "new data" as expected
}

function f2() // recreate global variable
{
  unset($GLOBALS['my_global_var']); // this syntax works with all variable types including arrays
  global $my_global_var; // must do this after unset to access new global variable
  $my_global_var = "new data";
}
?>
pfreilly at umd dot umich dot edu 29-Sep-2011 04:56
Despite much searching, I have not yet found an explanation as to how one can manually free resources from variables, not so much objects, in PHP.  I have also seen many comments regarding the merits and demerits of unset() versus setting a variable to null.  Thus, here are the results of some benchmarks performed comparing unset() of numerous variables to setting them to null (with regards to memory usage and processing time):

10 variables:
Unset:
Memory Usage: 296
Time Elapsed: 1.0013580322266E-5

Null set:
Memory Usage: 1736
Time Elapsed: 5.9604644775391E-6

50 variables:
Unset:
Memory Usage: 296
Time Elapsed: 3.6001205444336E-5

Null set:
Memory Usage: 8328
Time Elapsed: 3.2901763916016E-5

100 variables:
Unset:
Memory Usage: 296
Time Elapsed: 5.6982040405273E-5

Null set:
Memory Usage: 15928
Time Elapsed: 5.8174133300781E-5

1000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.00041294097900391

Null set:
Memory Usage: 168096
Time Elapsed: 0.00067591667175293

10000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.0042569637298584

Null set:
Memory Usage: 1650848
Time Elapsed: 0.0076930522918701

100000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.042603969573975

Null set:
Memory Usage: 16249080
Time Elapsed: 0.087724924087524

300000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.13177299499512

Null set:
Memory Usage: 49796320
Time Elapsed: 0.28617882728577

Perhaps my test code for the null set was flawed, but despite that possibility it is simple to see that unset() has minimal processing time impact, and no apparent memory usage impact (unless the values returned by memory_get_usage() are flawed).  If you truly care about the ~4 microseconds saved over <50 variables, more power to you.  Otherwise, use unset() to minimize script impact on your system.
Note: Tested on PHP 5.3.8 installed via RPM on Fedora 14
edouard dot berge at gmail dot com 24-Sep-2010 09:09
Warning!

When unset from an array, if you unset all elements, the array is always set

$tab=array('A'=>1,'B'=>2);
unset($tab['A']);
unset($tab['B']);
echo isset($tab)." ".count($tab);

output: 1 0
Andreas 24-Sep-2010 05:51
You can not unset a numeric key of an array, if key is a string. See this example:

// Create a simple array with 3 different key types
$test[1] = array(
    10 => array('apples'),
    "20" => array('bananas'),
    '30' => array('peaches')
);
$test[2] = (array) json_decode(json_encode($test[1]));
$test[3] = (array) (object) $test[1];
// array form a stdClass object
$testClass = new stdClass();
$testClass->{10} =  array('apples');
$testClass->{"20"} =  array('bananas');
$test[4] = (array) $testClass[6];

echo "<pre>";
foreach($test as $testNum => $arr) {

    echo "\nTest: " . $testNum  . " \n";
    var_dump($arr);

    foreach($arr as $key => $fruit) {
        echo "key: " . $key . "\n";
        echo "key exists: ";
        var_dump(array_key_exists(strval($key), $arr));
        echo "typeof key is: " . gettype($key) . "\n";

        unset($arr[$key]);
    }
    var_dump($arr);
    echo "\n" . str_repeat("-", 80);
}
echo "</pre>";

And here is the output:

Test: 1
array(3) {
  [10]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  [20]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  [30]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}

--------------------------------------------------------------
Test: 2
array(3) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  ["30"]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
key: 30
key exists: bool(false)
typeof key is: string
array(3) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  ["30"]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}

--------------------------------------------------------------
Test: 3
array(3) {
  [10]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  [20]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  [30]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}

--------------------------------------------------------------
Test: 4
array(2) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
array(2) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
}

--------------------------------------------------------------

Fix the problem with a rebuild of the array:
$oldArray = $array();
$array = array();
foreach($oldArray as $key => $item) {
    $array[intval($key)] = $item;
}
j dot vd dot merwe at enovision dot net 26-Aug-2010 05:08
A sample how to unset array elements from an array result coming from a mysql request. In this sample it is checking if a file exists and removes the row from the array if it not exists.

<?php
$db->set_query("select * from documents where document_in_user = 0"); //1
$documents = $db->result_to_array($db->get_result()); //1

foreach ($documents as $key => $row) { //2

    $file     = "uploads/".rawurldecode($row['document_name']);

    if ( file_exists ( $file ) == FALSE ) {
         unset($documents[$key]);  //3
    }
}

$documents = array_values($documents); // reindex the array (4)
?>

variables:
mysql table = documents,
array = $documents
array key (index) = $key
array row (record sort of speak) = $row

explanation:

1.
it gets the array from the table (mysql)

2.
foreach goes through the array $documents

3.
unset if record does not exist

4.
the array_values($documents) reindexes the $documents array, for otherwise you might end up in trouble when your  process will start expecting an array starting with key ($key) 0 (zero).
Anonymous 02-Jul-2010 07:20
further I realized that an object, when getting detroyed, does care about destroying variable in object space visibility but not those in local visibility, be aware of the found pattern:

<?php
class release_test{
  private $buffer;
  private $other_object;
  public function __construct(){
    $this->other_object=new other_object_class();
  }
  public function __destruct(){
    //note that you always have to unset class objects, in order to get the resources released
    unset($this->other_object);
  }
  public allocate_mem_A(){
    $this->buffer=file("/tmp/bigfile");
  }
  public allocate_mem_B(){
    $buffer=file("/tmp/bigfile");
  }
  public allocate_mem_C(){
    $buffer=file("/tmp/bigfile");
    unset($buffer);
  }
  public allocate_mem_D(){
    $this->other_buffer=file("/tmp/bigfile");
  }
}

//this does not lead to a resource problem
$A=new release_test();
$A->allocate_mem_A();
$A->__destruct();
unset($A);

//this DOES lead to a resource problem
$B=new release_test();
$B->allocate_mem_B();
$B->__destruct();
unset($B);

//this does not lead to a resource problem
$C=new release_test();
$C->allocate_mem_C();
$C->__destruct();
unset($C);

//this does not lead to a resource problem
$D=new release_test();
$D->allocate_mem_D();
$D->__destruct();
unset($D);
?>
phpmanual at kennel17 dot co dot uk 26-Feb-2010 08:55
Note that PHP 4 will generate a warning if you try to unset an array index that doesn't exist and whose parent doesn't exist.

Example:

<?php

  $foo = array();

  unset($foo['Bar']['Baz']);

?>

RESULT: "Notice:  Undefined index:  Bar"

On PHP5 no error is raised, which seems to me like the correct behaviour.

Note that using unset($foo['Bar']) in the above example does not generate a warning in either version.

(Tested on 4.4.9 and 5.2.4)
macnimble at gmail dot com 26-Mar-2009 02:39
Two ways of unsetting values within an array:

<?php
# remove by key:
function array_remove_key ()
{
  $args  = func_get_args();
  return array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
  $args = func_get_args();
  return array_diff($args[0],array_slice($args,1));
}

$fruit_inventory = array(
  'apples' => 52,
  'bananas' => 78,
  'peaches' => 'out of season',
  'pears' => 'out of season',
  'oranges' => 'no longer sold',
  'carrots' => 15,
  'beets' => 15,
);

echo "<pre>Original Array:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
                                    "beets",
                                    "carrots");
echo "<pre>Array after key removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
                                      "out of season",
                                      "no longer sold");
echo "<pre>Array after value removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';
?>
lion_cat at mail ru 12-Nov-2008 02:22
about unset for arrays

if you unset the last array member
$ar[0]==2
$ar[1]==7
$ar[2]==9

unset ($ar[2])

after addition a new member by $ar[]=7,

you will get
$ar[0]==2
$ar[1]==7
$ar[3]==7,

So, unset has no effect to internal array counter!!!
nox at oreigon dot de 05-Aug-2008 12:24
if you try to unset an object, please be careful about references.

Objects will only free their resources and trigger their __destruct method when *all* references are unsetted.
Even when they are *in* the object... sigh!

<?php

class A {
  function __destruct() {
    echo "cYa later!!\n";
  }
}

$a = new A();
$a -> a = $a;
#unset($a); # Just uncomment, and you'll see

echo "No Message ... hm, what now?\n";
unset($a -> a);
unset($a);

echo "Finally that thing is gone\n";

?>

Of course the object completely dies at the end of the script.
stacionari at gmail dot com 17-Mar-2008 01:41
Sometimes you need to assigne values to an array index in some loop (if, while, foreach etc.) but you wish to set starting index key to some number greater then zero (lets say 5). One idea how to do this is:

<?php
    $values = array(5, 10, 15, 100);  //array of values that we wish to add to our new array

    $myArray = array(4=>0);   //sets starting key to be 4 and assigns some value (lets say 0)
    unset($myArray[4]);   //delete this index key, but preserves further enumeration

    foreach($values as $value){
        $myArray[] = $value;   //asign values to our array
    }

    print_r($myArray);

/* Output:

Array ( [5] => 5 [6] => 10 [7] => 15 [8] => 100 )

*/

?>
pauljamescampbell at gmail dot com 15-Mar-2008 05:22
Here's my variation on the slightly dull unset method. It throws in a bit of 80's Stallone action spice into the mix. Enjoy!

<?php
/**
 * function rambo (first blood)
 *
 * Completely and utterly destroys everything, returning the kill count of victims
 *
 * @param    It don't matter, it’s Rambo baby
 * @return    Integer    Body count (but any less than 500 and it's not really worth mentioning)
 */
function rambo() {

    // Get the victims and initiate that body count status
    $victims = func_get_args();
    $body_count = 0;

    // Kill those damn punks
    foreach($victims as $victim) {
        if($death_and_suffering = @unset($victim)) {
            $body_count++;
        }
    }

    // How many kills did Rambo tally up on this mission?
    return($body_count);
}
?>
Kai Kunstmann 10-Mar-2008 05:09
Since unset() is a language construct, it cannot be passed anything other than a variable. It's sole purpose is to "unset" this variable, ie. to remove it from the current scope and destroy it's associated data. This is true especially for reference variables, where not the actual value is destroyed but the reference to that value. This is why you can't wrap 'unset()' in a user defined function: You would either unset a copy of the data if the parameter is passed by value, or you would just unset the reference variable within the functions scope if the parameter is passed by reference. There is no workaround for that, as you cannot pass 'scope' to a function in PHP. Such a function can only work for variables that exist in a common or global scope (compare 'unset($_GLOBALS[variable])').

I don't know how PHP handles garbage collection internally, but I guess this behavior can result in a huge memory leak: if a value variable goes out of scope with a second variable still holding a reference to the in-memory value, then unsetting that reference would still hold the value in memory but potentially unset the last reference to that in-memory data, hence: occupied memory that is rendered useless as you cannot reference it anymore.
Hayley Watson 23-Aug-2007 09:02
In regard to some confusion earlier in these notes about what causes unset() to trigger notices when unsetting variables that don't exist....

Unsetting variables that don't exist, as in
<?php
unset($undefinedVariable);
?>
does not trigger an "Undefined variable" notice. But
<?php
unset($undefinedArray[$undefinedKey]);
?>
triggers two notices, because this code is for unsetting an element of an array; neither $undefinedArray nor $undefinedKey are themselves being unset, they're merely being used to locate what should be unset. After all, if they did exist, you'd still expect them to both be around afterwards. You would NOT want your entire array to disappear just because you unset() one of its elements!
chad 0x40 herballure 0x2e com 31-May-2007 07:11
It is observed on PHP 5.1.6 that <?php unset($this); ?> inside of a method will remove the reference to $this in that method. $this isn't considered "special" as far as unset() is concerned.
09-Feb-2007 08:10
Just to confirm, USING UNSET CAN DESTROY AN ENTIRE ARRAY. I couldn't find reference to this anywhere so I decided to write this.

The difference between using unset and using $myarray=array(); to unset is that obviously the array will just be overwritten and will still exist.

<?php

$myarray=array("Hello","World");

echo $myarray[0].$myarray[1];

unset($myarray);
//$myarray=array();

echo $myarray[0].$myarray[1];

echo $myarray;
?>

Output with unset is:
<?
HelloWorld

Notice: Undefined offset: 0 in C:\webpages\dainsider\myarray.php on line 10

Notice: Undefined offset: 1 in C:\webpages\dainsider\myarray.php on line 10

Output with $myarray=array(); is:
?>

<?
HelloWorld

Notice: Undefined offset: 0 in C:\webpages\dainsider\myarray.php on line 10

Notice: Undefined offset: 1 in C:\webpages\dainsider\myarray.php on line 10

Array
?>
hessodreamy at gmail dot com 17-Jan-2007 03:51
To clarify what hugo dot dworak at gmail dot com said about unsetting things that aren't already set:

unsetting a non-existent key within an array does NOT throw an error.
<?
$array = array();

unset($array[2]);
//this does not throw an error

unset($array[$undefinedVar]);
//Throws an error because of the undefined variable, not because of a non-existent key.
?>
dibakar dot datta at gmail dot com 31-Mar-2006 11:31
Instead of using the unset function  for unregistering your session or other array values you can also do this samll feature and get this task done with just 1 line code.

Suppose, if you like to unregister your session store values.
You can use:

      $_SESSION = array();

Well this syntax saves lot's of time instead of unsetting each values.
clark at everettsconsulting dot com 11-Sep-2005 12:50
In PHP 5.0.4, at least, one CAN unset array elements inside functions from arrays passed by reference to the function.
As implied by the manual, however, one can't unset the entire array by passing it by reference.

<?php
function remove_variable (&$variable)  // pass variable by reference
{
    unset($variable);
}

function remove_element (&$array, $key) // pass array by reference
{
    unset($array[$key]);
}

$scalar = 'Hello, there';
echo 'Value of $scalar is: ';
print_r ($scalar); echo '<br />';
// Value of $scalar is: Hello, there

remove_variable($scalar); // try to unset the variable
echo 'Value of $scalar is: ';
print_r ($scalar); echo '<br />';
// Value of $scalar is: Hello, there

$array = array('one' => 1, 'two' => 2, 'three' => 3);
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [two] => 2 [three] => 3 )

remove_variable($array); // try to unset the array
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [two] => 2 [three] => 3 )

remove_element($array, 'two'); // successfully remove an element from the array
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [three] => 3 )

?>
no at spam dot com 30-Aug-2005 03:22
In addition to what timo dot hummel at 4fb dot de said;

>For the curious: unset also frees memory of the variable used.
>
>It might be possible that the in-memory size of the PHP Interpreter isn't reduced, but your scripts won't touch the memory_limit boundary. Memory is reused if you declare new variables.

It might be worth adding that functions apparently don't free up memory on exit the same way unset does..
Maybe this is common knowledge, but although functions destroys variables on exit, it (apparently) doesn't help the memory.

So if you use huge variables inside functions, be sure to unset them if you can before returning from the function.

In my case, if I did not unset before return, then the script would use 20 MB more of memory than if I did unset.
This was tested with php 5.0.4 on apache 2 on windows xp, with no memory limit.

Before I did the test, I was under the impression that when you exit from functions, the memory used inside it would be cleared and reused. Maybe this should be made clear in the manual, for either unset() or in the chapter for functions.
muhamad_zakaria at yahoo dot com 04-Jul-2005 07:08
We have experienced when we applied 'unset' to the overloaded properties (PHP5), consider the code below:
<?php
    class TheObj {
        public $RealVar1, $RealVar2, $RealVar3, $RealVar4;
        public $Var = array();

        function __set($var, $val) {
            $this->Var[$var] = $val;
        }
        function __get($var) {
            if(isset($this->Var[$var])) return $this->Var[$var];
            else return -1;
        }
    }

    $SomeObj = new TheObj;

    // here we set for real variables
    $SomeObj->RealVar1 = 'somevalue';
    $SomeObj->{'RealVar2'} = 'othervalue';
    $SomeObj->{'RealVar'.(3)} = 'othervaluetoo';
    $SomeObj->{'RealVar'.'4'} = 'anothervalue';

    // and here we set for virtual variables
    $SomeObj->Virtual1 = 'somevalue';
    $SomeObj->{'Virtual2'} = 'othervalue';
    $SomeObj->{'Virtual'.(3)} = 'othervaluetoo';
    $SomeObj->{'Virtual'.'4'} = 'anothervalue';

    // now we will try to unset these variables
    unset($SomeObj->RealVar1);
    unset($SomeObj->{'RealVar'.(3)});

    //the lines below will catch by '__get' magic method since these variables are unavailable anymore
    print $SomeObj->RealVar1."\n";
    print $SomeObj->{'RealVar'.(3)}."\n";

    // now we will try to unset these variables
    unset($SomeObj->Virtual1);
    unset($SomeObj->{'Virtual'.(3)});

    //but, these variables are still available??? eventhough they're "unset"-ed
    print $SomeObj->Virtual1."\n";
    print $SomeObj->{'Virtual'.(3)}."\n";
?>

Please note that PHP doesn't have magic callback to unset overloaded properties. This is the reason why unset($SomeObj->Virtual1) doesn't work.

But it does work when we set 'null' value such as the following code:
<?php
    // now we will set 'null' value instead of using unset statement
    $SomeObj->Virtual1 = null;
    $SomeObj->{'Virtual'.(3)} = null;

    // and now these variables are no longer available
    print $SomeObj->Virtual1."\n";
    print $SomeObj->{'Virtual'.(3)}."\n";
?>
Sound ugly, yeah?

This applied to the "virtual" array variable too, see more at http://bugs.php.net/bug.php?id=33513 (at feedback) about it.
PS: we used PHP version 5.1.0-dev from the CVS snapshot when we wrote the above codes.
franckraynal at free dot fr 26-Feb-2005 05:02
Here is another way to make 'unset' work with session variables from within a function :

<?php
function unsetSessionVariable ($sessionVariableName) {
   unset($GLOBALS[_SESSION][$sessionVariableName]);
}
?>

May it work with others than me...
F.
dan AT --nospam-- cubeland DOT co DOT uk 04-Nov-2004 11:38
dh at argosign dot de -
it is possible to unset globals from within functions thanks to the $GLOBALS array:

<?php
$x = 10;

function test() {
    // don't need to do ' global $x; '
    unset ($GLOBALS['x']);
    echo 'x: ' . $GLOBALS['x'] . '<br />';
}

test();
echo "x: $x<br />";

// will result in
/*
x:
x:
*/
?>
thorry at thorry dot net 05-Aug-2004 02:15
The documentation is not entirely clear when it comes to static variables. It says:

If a static variable is unset() inside of a function, unset() destroys the variable and all its references.

<?php
function foo()
{
   static $a;
   $a++;
   echo "$a\n";
   unset($a);
}

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

The above example would output:

1
2
3

And it does! But the variable is NOT deleted, that's why the value keeps on increasing, otherwise the output would be:

1
1
1

The references are destroyed within the function, this handeling is the same as with global variables, the difference is a static variable is a local variable.

Be carefull using unset and static values as the output may not be what you expect it to be. It appears to be impossible to destroy a static variable. You can only destroy the references within the current executing function, a successive static statement will restore the references.

The documentation would be better if it would say:
"If a static variable is unset() inside of a function, unset() destroys all references to the variable. "

Example: (tested PHP 4.3.7)
<?php
function foo()
{
   static $a;
   $a++;
   echo "$a\n";
   unset($a);
   echo "$a\n";
   static $a;
   echo "$a\n";
}

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

Would output:

1

1
2

2
3

3
anon at no spam dot no address dot com 16-Jul-2004 09:19
Adding on to what bond at noellebond dot com said, if you want to remove an index from the end of the array, if you use unset, the next index value will still be what it would have been.

Eg you have
<?php
 $x = array(1, 2);

 for ($i = 0; $i < 5; $i++)
 {
    unset($x[(count($x)-1)]); //remove last set key in the array

    $x[] = $i;
 }
?>

You would expect:
Array([0] => 1, [1] => 4)
as you want it to remove the last set key....

but you actually get
Array ( [0] => 1 [4] => 2 [5] => 3 [6] => 4 )

This is since even though the last key is removed, the auto indexing still keeps its previous value.

The only time where this would not seem right is when you remove a value off the end. I guess different people would want it different ways.

The way around this is to use array_pop() instead of unset() as array_pop() refreshes the autoindexing thing for the array.
<?php
 $x = array(1, 2);

 for ($i = 0; $i < 5; $i++)
 {
    array_pop($x); // removes the last item in the array

    $x[] = $i;
 }
?>

 This returns the expected value of x = Array([0] => 1, [1] => 4);

Hope this helps someone who may need this for some odd reason, I did.
andre at twg dot com dot au 06-Mar-2004 09:16
Only This works with register_globals being 'ON'.

unset( $_SESSION['variable'] );

The above will not work with register_globals turned on (will only work outside of a function).

$variable = $_SESSION['variable'];
unset( $_SESSION['variable'], $variable );

The above will work with register_globals on & inside a function
warhog at warhog dot net 27-Jan-2004 08:52
you may wan't to unset all variables which are defined, here's one way:

<?php

function unset_all_vars($a)
{ foreach($a as $key => $val)
  { unset($GLOBALS[$key]); }
  return serialize($a); }

unset_all_vars(get_defined_vars());

?>

you can also save than a serialized var of the "memory" and perhaps store this in a temporary file.. very usefull if you work with text files and/or file uploads when you've got very large variables.

greetz


Muestra información sobre una variable

  • « unset
  • var_export »
  • PHP Manual
  • Funciones de manejo de variables
  • Muestra información sobre una variable

var_dump

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

var_dump — Muestra información sobre una variable

Descripción

var_dump ( mixed $expression , mixed $... = ? ) : void

Esta función muestra información estructurada sobre una o más expresiones incluyendo su tipo y valor. Las matrices y los objetos son explorados recursivamente con valores sangrados para mostrar su estructura.

En PHP 5 todas las propiedades públicas, privadas y protegidas de los objetos serán devueltas en la salida.

Sugerencia

Como con todo lo que genera un resultado directamente en el navegador, se pueden utilizar las funciones de control de salida para capturar el resultado de esta función y guardarlo, por ejemplo, en un string.

Parámetros

expresion

La variable que desea vacíar la información.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo var_dump()

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

El resultado del ejemplo sería:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}
<?php

$b = 3.1;
$c = true;
var_dump($b, $c);

?>

El resultado del ejemplo sería:

float(3.1)
bool(true)

Ver también

  • print_r() - Imprime información legible para humanos sobre una variable
  • debug_zval_dump() - Vuelca a la salida una cadena con la representación de un valor interno de zend
  • var_export() - Imprime o devuelve una representación string de una variable analizable

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.


Imprime o devuelve una representación string de una variable analizable

  • « var_dump
  • Servicios web »
  • PHP Manual
  • Funciones de manejo de variables
  • Imprime o devuelve una representación string de una variable analizable

var_export

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

var_export — Imprime o devuelve una representación string de una variable analizable

Descripción

var_export ( mixed $expression , bool $return = false ) : mixed

var_export() obtiene información estructurada sobre la variable dada. Es similar a la función var_dump() con una excepción: la representación devuelta es código PHP válido.

Parámetros

expression

La variable que desea exportar.

return

Si es usada y se define como true, var_export() devolverá la representación de la variable en lugar de imprimirla.

Valores devueltos

Devuelve la representación de la variable cuando el parámetro return es utilizado y evaluado como true. En caso contrario, esta función devolverá null.

Notas

Nota:

Cuando el parámetro return se usa, esta función utiliza el almacenamiento en búfer de salida interno, por lo que no puede usarse dentro de una función de llamada de retorno ob_start().

Historial de cambios

Versión | Descripción
5.1.0 | Posibilidad de exportar las clases y los arrays que contienen las clases utilizando el método mágico __set_state.

Ejemplos

Ejemplo #1 Ejemplos de var_export()

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

El resultado del ejemplo sería:

array (
  0 => 1,
  1 => 2,
  2 =>
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
<?php

$b = 3.1;
$v = var_export($b, true);
echo $v;

?>

El resultado del ejemplo sería:

3.1

Ejemplo #2 Exportación de clases a partir de PHP 5.1.0

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

El resultado del ejemplo sería:

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

Ejemplo #3 Uso de __set_state (a partir de PHP 5.1.0)

<?php
class A
{
    public $var1;
    public $var2;

    public static function __set_state($una_matriz)
    {
        $obj = new A;
        $obj->var1 = $una_matriz['var1'];
        $obj->var2 = $una_matriz['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);
?>

El resultado del ejemplo sería:

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

Notas

Nota:

Las variables de tipo resource no pueden ser exportadas por esta función.

Nota:

var_export() no maneja referencias circulares ya que sería prácticamente imposible generar código PHP interpretable en tal caso. Si desea trabajar con la representación completa de una matriz u objeto, use serialize().

Advertencia

Cuando var_export() exporta objectos, la barra diagonal no se incluye en el nombre de clases que pertencen a un namespace para mantener compatibilidad.

Ver también

  • print_r() - Imprime información legible para humanos sobre una variable
  • serialize() - Genera una representación apta para el almacenamiento de un valor
  • var_dump() - Muestra información sobre una variable

User Contributed Notes

steven at nevvix dot com 13-Sep-2019 03:52
I improved my previous varexport().

<?php
/**
 * PHP var_export() with short array syntax (square brackets) indented 2 spaces.
 *
 * NOTE: The only issue is when a string value has `=>\n[`, it will get converted to `=> [`
 * @link https://www.php.net/manual/en/function.var-export.php
 */
function varexport($expression, $return=FALSE) {
    $export = var_export($expression, TRUE);
    $patterns = [
        "/array \(/" => '[',
        "/^([ ]*)\)(,?)$/m" => '$1]$2',
        "/=>[ ]?\n[ ]+\[/" => '=> [',
        "/([ ]*)(\'[^\']+\') => ([\[\'])/" => '$1$2 => $3',
    ];
    $export = preg_replace(array_keys($patterns), array_values($patterns), $export);
    if ((bool)$return) return $export; else echo $export;
}

$array = [
    'str' => 'Test
       spaces',
       0 => 33,
       1 => TRUE,
       [3,4,'d',[]],
    'arr' => [
        'text with spaces' => '[Tes\'t"s":
 => [
 =>
  [
   {
      spaces',
    ],
    "str2" => "Test's'
 } spaces",
    'arr2' => [
        'text with spaces' => [
            'arr3' => [
                'text with spaces' => 'Te": "st \' => [
      spaces',
            ],
        ],
    ],
];
varexport($array);
// Result:
```
[
  'str' => 'Test
       spaces',
  0 => 33,
  1 => true,
  2 => [
    0 => 3,
    1 => 4,
    2 => 'd',
    3 => [
    ],
  ],
  'arr' => [
    'text with spaces' => '[Tes\'t"s":
 => [
 => [
   {
      spaces',
  ],
  'str2' => 'Test\'s\'
 } spaces',
  'arr2' => [
    'text with spaces' => [
      'arr3' => [
        'text with spaces' => 'Te": "st \' => [
      spaces',
      ],
    ],
  ],
]
```
NOTE: The only issue is when a string value has `=>\n[`, it will get converted to `=> [`
beverasrilakshmi at gmail dot com 01-May-2019 08:24
Just for fun, trying to understand the definition of "returns parsable string"....any type of variable passed to var_export, the return value will be a typecasted as string...

<?php

$var = 1;
var_dump($var); //type is int as expected
echo "<br>";
$var_after_export = var_export($var,true); //returning $var will now makes it a string
var_dump($var_after_export);

?>
steven at nevvix dot com 18-Jun-2018 06:24
/**
 * var_export() with square brackets and indented 4 spaces.
 */
<?php
function varexport($expression, $return=FALSE) {
    $export = var_export($expression, TRUE);
    $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
    $array = preg_split("/\r\n|\n|\r/", $export);
    $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => ['], $array);
    $export = join(PHP_EOL, array_filter(["["] + $array));
    if ((bool)$return) return $export; else echo $export;
}
Mark P 29-Jan-2016 09:09
It doesn't appear to be documented, but the behaviour of `var_export()` changed in PHP 7.

Previously, `var_export(3.)` returned "3", now it returns "3.0".
cpmcgrat()uci ! edu 27-Jul-2015 10:45
When trying to use __set_state() to rebuild a huge, tricky class use the following:

class Foo
{
    public $a;
    public $b;
    public $c;
    public $d;
    public $e;
    public $f;
    public $g;
    public $h;
    public $i;

    public function __set_state($array)
    {
        $obj = new ArrayConfig;
        foreach($array as $k => $v) {
            eval('$obj->'.$k.' = '.$v.';');
        }
        return $obj;
    }
}

This will return a reconstructed version of the class without having to manually type each individual object in the class manually (as shown in the __set_state() example)
dan at coders dot co dot nz 10-Jan-2014 02:11
I found that my complex type was exporting with
  stdClass::__set_state()
in places. Not only was that strange and messy, it cannot be eval()-ed back in at all. Fatal error. Doh!

However a quick string-replace tidy-up of the result rendered it valid again.

    $macro = var_export($data, TRUE);
    $macro = str_replace("stdClass::__set_state", "(object)", $macro);
    $macro = '$data = ' . $macro . ';';

And now the string I output *can* be evaluated back in again.
wyattstorch42 at outlook dot com 22-Dec-2013 10:11
If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.

However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I'd advise you to implement ::__set_state().

<?php
/**
 * An implementation of var_export() that is compatible with instances
 * of stdClass.
 * @param mixed $variable The variable you want to export
 * @param bool $return If used and set to true, improved_var_export()
 *     will return the variable representation instead of outputting it.
 * @return mixed|null Returns the variable representation when the
 *     return parameter is used and evaluates to TRUE. Otherwise, this
 *     function will return NULL.
 */
function improved_var_export ($variable, $return = false) {
    if ($variable instanceof stdClass) {
        $result = '(object) '.improved_var_export(get_object_vars($variable), true);
    } else if (is_array($variable)) {
        $array = array ();
        foreach ($variable as $key => $value) {
            $array[] = var_export($key, true).' => '.improved_var_export($value, true);
        }
        $result = 'array ('.implode(', ', $array).')';
    } else {
        $result = var_export($variable, true);
    }

    if (!$return) {
        print $result;
        return null;
    } else {
        return $result;
    }
}

// Example usage:
$obj = new stdClass;
$obj->test = 'abc';
$obj->other = 6.2;
$obj->arr = array (1, 2, 3);

improved_var_export((object) array (
    'prop1' => true,
    'prop2' => $obj,
    'assocArray' => array (
        'apple' => 'good',
        'orange' => 'great'
    )
));

/* Output:
(object) array ('prop1' => true, 'prop2' => (object) array ('test' => 'abc', 'other' => 6.2, 'arr' => array (0 => 1, 1 => 2, 2 => 3)), 'assocArray' => array ('apple' => 'good', 'orange' => 'great'))
*/
?>

Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn't formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().
chudinov at yahoo dot com 29-Nov-2013 09:55
Looks like since version 5.4.22 var_export uses the serialize_precision ini setting, rather than the precision one used for normal output of floating-point numbers.
As a consequence since version 5.4.22 for example var_export(1.1) will output 1.1000000000000001 (17 is default precision value) and not 1.1 as before.

<?php
//ouput 1.1000000000000001
var_export(1.1)
 ?>
NitPicker 10-Jul-2013 04:33
When it comes to HTML output (as discussed below), it's all fun and games until someone pokes their eye out with a "<".

Surround it with "<pre>", but do remember to wrap it in htmlspecialchars() as well.
sergei dot solomonov at gmail dot com 04-Oct-2012 04:00
<?php
$closure = function(){};

var_export($closure);

// output: Closure::__set_state(array())
?>
kexianbin at diyism dot com 16-Sep-2012 02:33
to use my_var_export(), it is as beautiful as var_export() and as could deal with recursive reference as print_r():

<?php
function my_var_export($var, $is_str=false)
         {$rtn=preg_replace(array('/Array\s+\(/', '/\[(\d+)\] => (.*)\n/', '/\[([^\d].*)\] => (.*)\n/'), array('array (', '\1 => \'\2\''."\n", '\'\1\' => \'\2\''."\n"), substr(print_r($var, true), 0, -1));
          $rtn=strtr($rtn, array("=> 'array ('"=>'=> array ('));
          $rtn=strtr($rtn, array(")\n\n"=>")\n"));
          $rtn=strtr($rtn, array("'\n"=>"',\n", ")\n"=>"),\n"));
          $rtn=preg_replace(array('/\n +/e'), array('strtr(\'\0\', array(\'    \'=>\'  \'))'), $rtn);
          $rtn=strtr($rtn, array(" Object',"=>" Object'<-"));
          if ($is_str)
             {return $rtn;
             }
          else
              {echo $rtn;
              }
         }

?>
jodybrabec at gmail dot com 28-Mar-2012 05:52
WORKAROUND for error "Nesting level too deep - recursive dependency":
ob_start();
var_dump($GLOBALS);
$dataDump = ob_get_clean();
echo $dataDump;
Anonymous 11-Nov-2011 09:13
There is an even simpler way to have clean output from var_export and print_r in html pages:

<?php
function pretty_var($myArray)
{
    echo "<pre>";
    var_export($myArray);
    echo "</pre>";
}
?>
laszlo dot heredy at gmail dot com 06-Oct-2010 01:57
Try this function instead of var_export($GLOBALS) or var_dump($GLOBALS) when all you want to know is the values of the variables you set on the current page.

<?php
function globalvars(){
    $result=array();
    $skip=array('GLOBALS','_ENV','HTTP_ENV_VARS',
                        '_POST','HTTP_POST_VARS','_GET',
                        'HTTP_GET_VARS',
                        '_COOKIE',
                        'HTTP_COOKIE_VARS','_SERVER',
                        'HTTP_SERVER_VARS',
                        '_FILES','HTTP_POST_FILES',
                        '_REQUEST','HTTP_SESSION_VARS',
                        '_SESSION');
    foreach($GLOBALS as $k=>$v)
        if(!in_array($k,$skip))
            $result[$k]=$v;
    return $result;
}//functionglobalvars

var_export(globalvars());
?>
4n4jmza02 at sneakemail dot com 17-Jun-2010 04:50
I learned the hard way that if var_export encounters a resource handle it exports it as "NULL", even if it is a valid handle. The documentation states that a handle cannot be exported, but it does not describe what happens if you try to do so anyway.

I had been using var_export in some debugging code while tracing a problem with a resource handle not being generated and ended up thinking that null handles were still being generated long after the problem had been fixed.
john dot risken at gmail dot com 16-Jan-2010 03:53
I didn't see this simple little item anywhere in the user notes. Maybe I'm blind!

Anyway, var_export and print_r both use spaces and carriage returns for formatting.  Sent to an html page, most of the formatting is lost. This simple function prints a nicely formatted array to an html screen:

<?php
function pretty_var($myArray){
    print str_replace(array("\n"," "),array("<br>","&nbsp;"), var_export($myArray,true))."<br>";
}
?>
rarioj at gmail dot com 28-Oct-2009 10:43
NOTE: If an object Foo has __set_state() method, but if that object contains another object Bar with no __set_state() method implemented, the resulting PHP expression will not be eval()-able.

This is an example (object Test that contains an instance of Exception).

<?php

class Test
{
  public $one;
  public $two;
  public function __construct($one, $two)
  {
    $this->one = $one;
    $this->two = $two;
  }
  public static function __set_state(array $array)
  {
    return new self($array['one'], $array['two']);
  }
}

$test = new Test('one', new Exception('test'));

$string = var_export($test, true);

/* $string =
Test::__set_state(array(
   'one' => 'one',
   'two' =>
  Exception::__set_state(array(
     'message' => 'test',
     'string' => '',
     'code' => 0,
     'file' => 'E:\\xampp\\htdocs\\test.Q.php',
     'line' => 35,
     'trace' =>
    array (
    ),
     'previous' => NULL,
  )),
))
*/

eval('$test2 = '.$string.';'); // Fatal error: Call to undefined method Exception::__set_state

?>

So avoid using var_export() on a complex array/object that contains other objects. Instead, use serialize() and unserialize() functions.

<?php

$string = 'unserialize('.var_export(serialize($test), true).')';

eval('$test2 = '.$string.';');

var_dump($test == $test2); // bool(true)

?>
ravenswd at gmail dot com 07-Jul-2009 10:32
(This replaces my note of 3-July-2009. The original version produced no output if a variable contained an empty array, or an array consisting only of empty arrays. For example, $bigarray['x'] = array(); Also, I have added a second version of the function.)

The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print ('$bigarray', $bigarray);
?>

and it will return:

$bigarray = array()
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . $varval . "<br>\n";
  else:
    print $varname . " = array()<br>\n";
    foreach ($varval as $key => $val):
      recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}
?>

For those who want a version that produces valid PHP code, use this version:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . var_export($varval, true) . ";<br>\n";
  else:
    print $varname . " = array();<br>\n";
    foreach ($varval as $key => $val):
      recursive_print ($varname . "[" . var_export($key, true) . "]", $val);
    endforeach;
  endif;
}
?>

If your output is to a text file and not an HTML page, remove the <br>s.
ravenswd at gmail dot com 03-Jul-2009 05:21
The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print ('$bigarray', $bigarray);
?>

and it will return:

$bigarray['firstelement'] = 'something'
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . $varval . "<br>\n";
  else:
    foreach ($varval as $key => $val):
      recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}
?>
cmusicfan (at) gmail (daught) com 11-Jun-2009 09:19
Caution! var_export will add a backslash to single quotes (').

You may want to use stripslashes() to remove the mysteriously added backslashes.
stangelanda at arrowquick dot com 29-Jun-2007 04:20
I have been looking for the best method to store data in cache files.

First, I've identified two limitations of var_export verus serialize.  It can't store internal references inside of an array and it can't store a nested object or an array containing objects before PHP 5.1.0.

However, I could deal with both of those so I created a benchmark.  I used a single array containing from 10 to 150 indexes.  I've generate the elements' values randomly using booleans, nulls, integers, floats, and some nested arrays (the nested arrays are smaller averaging 5 elements but created similarly).  The largest percentage of elements are short strings around 10-15 characters.  While there is a small number of long strings (around 500 characters).

Benchmarking returned these results for 1000 * [total time] / [iterations (4000 in this case)]

serialize 3.656, 3.575, 3.68, 3.933, mean of 3.71
include 7.099, 5.42, 5.185, 6.076, mean of 5.95
eval 5.514, 5.204, 5.011, 5.788, mean of 5.38

Meaning serialize is around 1 and a half times faster than var_export for a single large array.  include and eval were consistently very close but eval was usually a few tenths faster (eval did better this particular set of trials than usual). An opcode cache like APC might make include faster, but otherwise serialize is the best choice.
Glen 23-May-2007 05:47
Like previously reported, i find var_export() frustrating when dealing with recursive structures.  Doing a :

<?php
var_export($GLOBALS);
?>

fails.  Interestingly, var_dump() has some logic to avoid recursive references.  So :

<?php
var_dump($GLOBALS);
?>

works (while being more ugly).  Unlike var_export(), var_dump() has no option to return the string, so output buffering logic is required if you want to direct the output.
Zorro 04-Sep-2005 11:24
This function can't export EVERYTHING. Moreover, you can have an error on an simple recursive array:

$test = array();
$test["oops"] = & $test;

echo var_export($test);

=>

Fatal error:  Nesting level too deep - recursive dependency? in ??.php on line 59
linus at flowingcreativity dot net 04-Jul-2005 09:50
<roman at DIESPAM dot feather dot org dot ru>, your function has inefficiencies and problems. I probably speak for everyone when I ask you to test code before you add to the manual.

Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().

<?php

function var_export_min($var, $return = false) {
    if (is_array($var)) {
        $toImplode = array();
        foreach ($var as $key => $value) {
            $toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
        }
        $code = 'array('.implode(',', $toImplode).')';
        if ($return) return $code;
        else echo $code;
    } else {
        return var_export($var, $return);
    }
}

?>
paul at worldwithoutwalls dot co dot uk 24-Nov-2004 11:22
var_export() differs from print_r() for variables that are resources, with print_r() being more useful if you are using the function for debugging purposes.
e.g.
<?php
$res = mysql_connect($dbhost, $dbuser, $dbpass);
print_r($res); //output: Resource id #14
var_export($res); //output: NULL
?>
php_manual_note at bigredspark dot com 16-Oct-2003 12:43
[john holmes]
True, but that method would require you to open and read the file into a variable and then unserialize it into another variable.

Using a file created with var_export() could simply be include()'d, which will be less code and faster.

[kaja]
If you are trying to find a way to temporarily save variables into some other file, check out serialize() and unserialize() instead - this one is more useful for its readable property, very handy while debugging.

[original post]
If you're like me, you're wondering why a function that outputs "correct PHP syntax" is useful. This function can be useful in implementing a cache system. You can var_export() the array into a variable and write it into a file. Writing a string such as

<?php
$string = '<?php $array = ' . $data . '; ?>';
?>

where $data is the output of var_export() can create a file that can be easily include()d back into the script to recreate $array.

The raw output of var_export() could also be eval()d to recreate the array.

---John Holmes...


Servicios web

  • OAuth
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Ejemplos
    • Funciones de OAuth
    • OAuth — La clase OAuth
    • OAuthProvider — Clase OAuthProvider
    • OAuthException — Clase OAuthException
  • SOAP
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Funciones de SOAP
    • SoapClient — La clase SoapClient
    • SoapServer — La clase SoapServer
    • SoapFault — La clase SoapFault
    • SoapHeader — La clase SoapHeader
    • SoapParam — La clase SoapParam
    • SoapVar — La clase SoapVar
  • Yar — Yet Another RPC Framework
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Ejemplos
    • Yar_Server — La clase Yar_Server
    • Yar_Client — La clase Yar_Client
    • Yar_Concurrent_Client — La clase Yar_Concurrent_Client
    • Yar_Server_Exception — La clase Yar_Server_Exception
    • Yar_Client_Exception — La clase Yar_Client_Exception
  • XML-RPC
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Funciones de XML-RPC

User Contributed Notes

There are no user contributed notes for this page.


OAuth

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Ejemplos
    • FireEagle
  • Funciones de OAuth
    • oauth_get_sbs — Genera una cadena de firma base
    • oauth_urlencode — Códifica una URI a RFC 3986
  • OAuth — La clase OAuth
    • OAuth::__construct — Crea un nuevo objeto OAuth
    • OAuth::__destruct — El destructor
    • OAuth::disableDebug — Desactiva la depuración detallada
    • OAuth::disableRedirects — Desactiva las redirecciones
    • OAuth::disableSSLChecks — Desactiva la verificación SSL
    • OAuth::enableDebug — Activa la depuración detallada
    • OAuth::enableRedirects — Activa las re-direcciones
    • OAuth::enableSSLChecks — Activa la verificación SSL
    • OAuth::fetch — Obtiene un recurso protegido por OAuth
    • OAuth::generateSignature — Generar una firma
    • OAuth::getAccessToken — Obtiene el token de acceso
    • OAuth::getCAPath — Obtiene la información CA
    • OAuth::getLastResponse — Obtiene la última respuesta
    • OAuth::getLastResponseHeaders — Obtener encabezados de la última respuesta
    • OAuth::getLastResponseInfo — Obtiene la información HTTP sobre la última respuesta
    • OAuth::getRequestHeader — Generar un string de firma de cabecera OAuth
    • OAuth::getRequestToken — Obtiene un token de petición
    • OAuth::setAuthType — Establece el tipo de autorización
    • OAuth::setCAPath — Establece la ruta a CA y su información
    • OAuth::setNonce — Configura el nonce para las solicitudes posteriores
    • OAuth::setRequestEngine — El propósito de setRequestEngine
    • OAuth::setRSACertificate — establece el certificado RSA
    • OAuth::setSSLChecks — Ajustar controles específicos de SSL para las solicitudes
    • OAuth::setTimestamp — Establece el timestamp
    • OAuth::setToken — Establece el token y el secreto
    • OAuth::setVersion — Configura la versión OAuth
  • OAuthProvider — Clase OAuthProvider
    • OAuthProvider::addRequiredParameter — Agregar parámetros necesarios
    • OAuthProvider::callconsumerHandler — Llama al callback consumerNonceHandler
    • OAuthProvider::callTimestampNonceHandler — Llama al callback timestampNonceHandler
    • OAuthProvider::calltokenHandler — Llama al callback tokenNonceHandler
    • OAuthProvider::checkOAuthRequest — Revisa una petición OAuth
    • OAuthProvider::__construct — Construye un nuevo objeto OAuthProvider
    • OAuthProvider::consumerHandler — Establece el manejador callback consumerHandler
    • OAuthProvider::generateToken — Genera un token aleatorio
    • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint — Establece isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter — Remueve un parámetro requerido
    • OAuthProvider::reportProblem — Reportar un problema
    • OAuthProvider::setParam — Establece un parámetro
    • OAuthProvider::setRequestTokenPath — Establece la ruta de petición del token
    • OAuthProvider::timestampNonceHandler — Establece el callback timestampNonceHandler
    • OAuthProvider::tokenHandler — Establece el manejador callback de tokenHandler
  • OAuthException — Clase OAuthException

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Esta extensión provee un cliente y un servicio OAuth. OAuth es un protocolo de autorización basado en HTTP el cual permite a las aplicaciones garantizar el acceso a datos sin tener alojado un nombre de usuario y contraseña.

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.


Requerimientos

PECL/oauth requiere PHP 5.1 o superior, ext/hash y ext/pcre.

PECL/oauth puede requerir opcionalmente libcurl si se selecciona en el momento de compilación. Si se configura con libcurl, debe ser compilado con soporte HTTPS.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

Se puede encontrar información para la instalación de esta extensión PECL en el capítulo del manual titulado Instalación de extensiones PECL. Se puede encontrar información adicional, tal como nuevos lanzamientos, descargas, ficheros fuente, información de mantenimiento, y un CHANGELOG, aquí: » https://pear.php.net/package/oauth

User Contributed Notes

There are no user contributed notes for this page.


Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles sólo cuando la extensión haya sido compilada con PHP, o bien sea cargada dinámicamente en ejecución.

La mayoría de estas constantes involucran problemas, los cuales son descritos en la documentación oficial de OAuth » Problem Reporting. Note sin embargo, que estos nombres de constantes son específicos para PHP, aunque el nombre sea similar.

OAUTH_SIG_METHOD_RSASHA1 (string)
Método de firma OAuth RSA-SHA1.
OAUTH_SIG_METHOD_HMACSHA1 (string)

Método de firma OAuth HMAC-SHA1.

OAUTH_SIG_METHOD_HMACSHA256 (string)
Método de firma OAuth HMAC-SHA256 signature method.
OAUTH_AUTH_TYPE_AUTHORIZATION (string)

Esta constante representa los parámetros OAuth en la cabecera de Authorization.

OAUTH_AUTH_TYPE_NONE (string)

Esta constante indica una petición NoAuth OAuth.

OAUTH_AUTH_TYPE_URI (string)

Esta constante representa los parámetros OAuth en la URI de petición.

OAUTH_AUTH_TYPE_FORM (string)

Esta constante representa los parámetros OAuth como una parte del cuerpo HTTP POST.

OAUTH_HTTP_METHOD_GET (string)

Usa el método GET para la petición OAuth.

OAUTH_HTTP_METHOD_POST (string)

Usa el método POST para la petición OAuth.

OAUTH_HTTP_METHOD_PUT (string)

Usa el método PUT para la petición OAuth.

OAUTH_HTTP_METHOD_HEAD (string)

Usa el método HEAD para la petición OAuth.

OAUTH_HTTP_METHOD_DELETE (string)
Usa el método DELETE para la petición OAuth.
OAUTH_REQENGINE_STREAMS (integer)
Utiliza el método OAuth::setRequestEngine() para definir el motor de PHP streams, en lugar de OAUTH_REQENGINE_CURL para Curl.
OAUTH_REQENGINE_CURL (integer)
Utiliza el método OAuth::setRequestEngine() para definir el motor de Curl, en lugar de OAUTH_REQENGINE_STREAMS para PHP streams.
OAUTH_OK (integer)
La vida es bella.
OAUTH_BAD_NONCE (integer)
El valor oauth_nonce que fue usado en una anterior petición, y no se puede utilizar ahora.
OAUTH_BAD_TIMESTAMP (integer)
El valor oauth_timestamp que no fue aceptado por el proveedor de servicio. En este caso, la respuesta deberá estar también contenida en el parámetro oauth_acceptable_timestamps.
OAUTH_CONSUMER_KEY_UNKNOWN (integer)
oauth_consumer_key es temporalmehte inaceptable para el proveedor de servicio. Por ejemplo, el proveedor de servicio se ha sobrecargado.
OAUTH_CONSUMER_KEY_REFUSED (integer)
La clave de cliente ha sido rechazada.
OAUTH_INVALID_SIGNATURE (integer)
La firma oauth_signature es inválida, no coincide la firma del cliente con la del proveedor.
OAUTH_TOKEN_USED (integer)
El oauth_token ha sido consumido. No se puede utilizar más debido a que ya había sido usada en la/s petición/peticiones anterior/es.
OAUTH_TOKEN_EXPIRED (integer)
El oauth_token ha expirado.
OAUTH_TOKEN_REVOKED (integer)
El oauth_token ha sido revocado, y no será aceptado nunca más.
OAUTH_TOKEN_REJECTED (integer)
El oauth_token no fue aceptado por el proveedor de servicio. La razón es desconocida, pero puede deberse a que el token nunca fue usado, ya había sido consumido, ya había expirado, y/o olvidado por el proveedor de servicio.
OAUTH_VERIFIER_INVALID (integer)
El oauth_verifier es incorrecto.
OAUTH_PARAMETER_ABSENT (integer)
Un parámetro no fue recibido. En ese caso, la respuesta debe también contener el parámetro oauth_parameters_absent.
OAUTH_SIGNATURE_METHOD_REJECTED (integer)
El método oauth_signature_method no fue aceptado por el proveedor de servicio.

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

Tabla de contenidos

  • 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 state=1 la siguiente solicitud debe incluir un oauth_token.
// Si no vuelve a 0 (cero)
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");


Funciones de OAuth

Tabla de contenidos

  • oauth_get_sbs — Genera una cadena de firma base
  • oauth_urlencode — Códifica una URI a RFC 3986

User Contributed Notes

There are no user contributed notes for this page.


Genera una cadena de firma base

  • « Funciones de OAuth
  • oauth_urlencode »
  • PHP Manual
  • Funciones de OAuth
  • Genera una cadena de firma base

oauth_get_sbs

(PECL OAuth >=0.99.7)

oauth_get_sbs — Genera una cadena de firma base

Descripción

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

Genera un string de firma base con PECL/OAuth.

Parámetros

http_method

El método HTTP.

uri

La URI a códificar.

request_parameters

Array de parámetros de petición.

Valores devueltos

Devuelve el string de firma base.

User Contributed Notes

There are no user contributed notes for this page.


Códifica una URI a RFC 3986

  • « oauth_get_sbs
  • OAuth »
  • PHP Manual
  • Funciones de OAuth
  • Códifica una URI a RFC 3986

oauth_urlencode

(PECL OAuth >=0.99.2)

oauth_urlencode — Códifica una URI a RFC 3986

Descripción

oauth_urlencode ( string $uri ) : string

Códifica una URI a » RFC 3986.

Parámetros

uri

URI a codificar.

Valores devueltos

Returns an » RFC 3986 encoded string.

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 clase OAuth

(PECL OAuth >= 0.99.1)

Introducción

La extensión OAuth provee una interfaz simple para interactuar con proveedores de datos usando la especificación HTTP OAuth para proteger los recursos privados.

Sinopsis de la Clase

OAuth {
/* Propiedades */
public $debug ;
public $sslChecks ;
public $debugInfo ;
/* Métodos */
public __construct ( string $consumer_key , string $consumer_secret , string $signature_method = OAUTH_SIG_METHOD_HMACSHA1 , int $auth_type = 0 )
public __destruct ( ) : void
public disableDebug ( ) : bool
public disableRedirects ( ) : bool
public disableSSLChecks ( ) : bool
public enableDebug ( ) : bool
public enableRedirects ( ) : bool
public enableSSLChecks ( ) : bool
public fetch ( string $protected_resource_url , array $extra_parameters = ? , string $http_method = ? , array $http_headers = ? ) : mixed
public generateSignature ( string $http_method , string $url , mixed $extra_parameters = ? ) : string
public getAccessToken ( string $access_token_url , string $auth_session_handle = ? , string $verifier_token = ? , string $http_method = ? ) : array
public getCAPath ( ) : array
public getLastResponse ( ) : string
public getLastResponseHeaders ( ) : string
public getLastResponseInfo ( ) : array
public getRequestHeader ( string $http_method , string $url , mixed $extra_parameters = ? ) : string
public getRequestToken ( string $request_token_url , string $callback_url = ? , 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
}

Propiedades

debug

sslChecks

debugInfo

Tabla de contenidos

  • OAuth::__construct — Crea un nuevo objeto OAuth
  • OAuth::__destruct — El destructor
  • OAuth::disableDebug — Desactiva la depuración detallada
  • OAuth::disableRedirects — Desactiva las redirecciones
  • OAuth::disableSSLChecks — Desactiva la verificación SSL
  • OAuth::enableDebug — Activa la depuración detallada
  • OAuth::enableRedirects — Activa las re-direcciones
  • OAuth::enableSSLChecks — Activa la verificación SSL
  • OAuth::fetch — Obtiene un recurso protegido por OAuth
  • OAuth::generateSignature — Generar una firma
  • OAuth::getAccessToken — Obtiene el token de acceso
  • OAuth::getCAPath — Obtiene la información CA
  • OAuth::getLastResponse — Obtiene la última respuesta
  • OAuth::getLastResponseHeaders — Obtener encabezados de la última respuesta
  • OAuth::getLastResponseInfo — Obtiene la información HTTP sobre la última respuesta
  • OAuth::getRequestHeader — Generar un string de firma de cabecera OAuth
  • OAuth::getRequestToken — Obtiene un token de petición
  • OAuth::setAuthType — Establece el tipo de autorización
  • OAuth::setCAPath — Establece la ruta a CA y su información
  • OAuth::setNonce — Configura el nonce para las solicitudes posteriores
  • OAuth::setRequestEngine — El propósito de setRequestEngine
  • OAuth::setRSACertificate — establece el certificado RSA
  • OAuth::setSSLChecks — Ajustar controles específicos de SSL para las solicitudes
  • OAuth::setTimestamp — Establece el timestamp
  • OAuth::setToken — Establece el token y el secreto
  • OAuth::setVersion — Configura la versión OAuth

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo objeto OAuth

  • « OAuth
  • OAuth::__destruct »
  • PHP Manual
  • OAuth
  • Crea un nuevo objeto OAuth

OAuth::__construct

(PECL OAuth >= 0.99.1)

OAuth::__construct — Crea un nuevo objeto OAuth

Descripción

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

Crea un nuevo objeto OAuth

Parámetros

consumer_key

La clave de lectura proporcionada por el proveedor de servicios.

consumer_secret

El secreto de lectura proporcionada por el proveedor de servicios.

signature_method

Este parámetro es opcional define cual método usar, por omisión es OAUTH_SIG_METHOD_HMACSHA1 (HMAC-SHA1).

auth_type

Este parámetro es opcional define como pasar los parámetros OAuth al lector, por omisión es OAUTH_AUTH_TYPE_AUTHORIZATION (en la cabecerá 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


El destructor

  • « OAuth::__construct
  • OAuth::disableDebug »
  • PHP Manual
  • OAuth
  • El destructor

OAuth::__destruct

(PECL OAuth >= 0.99.9)

OAuth::__destruct — El destructor

Descripción

public OAuth::__destruct ( ) : void

El destructor.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

No devuelve ningún valor.

Ver también

  • OAuth::__construct() - Crea un nuevo objeto OAuth

User Contributed Notes

There are no user contributed notes for this page.


Desactiva la depuración detallada

  • « OAuth::__destruct
  • OAuth::disableRedirects »
  • PHP Manual
  • OAuth
  • Desactiva la depuración detallada

OAuth::disableDebug

(PECL OAuth >= 0.99.3)

OAuth::disableDebug — Desactiva la depuración detallada

Descripción

public OAuth::disableDebug ( ) : bool

Desactiva la solicitud de información detallada (desactivado por omisión). Alternativamente, la propiedad debug puede ser establecida al valor false para desactivar el depurador.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true

Historial de cambios

Versión | Descripción
0.99.8 | La propiedad debug fue agregada.

Ver también

  • OAuth::enableDebug() - Activa la depuración detallada

User Contributed Notes

There are no user contributed notes for this page.


Desactiva las redirecciones

  • « OAuth::disableDebug
  • OAuth::disableSSLChecks »
  • PHP Manual
  • OAuth
  • Desactiva las redirecciones

OAuth::disableRedirects

(PECL OAuth >= 0.99.9)

OAuth::disableRedirects — Desactiva las redirecciones

Descripción

public OAuth::disableRedirects ( ) : bool

Desactiva las redirecciones automáticas, permitiendo que la petición sea manualmente redirigida.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true

Ver también

  • OAuth::enableRedirects() - Activa las re-direcciones

User Contributed Notes

There are no user contributed notes for this page.


Desactiva la verificación SSL

  • « OAuth::disableRedirects
  • OAuth::enableDebug »
  • PHP Manual
  • OAuth
  • Desactiva la verificación SSL

OAuth::disableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::disableSSLChecks — Desactiva la verificación SSL

Descripción

public OAuth::disableSSLChecks ( ) : bool

Desactiva la verificación del certificado y servidor SSL, esto no se recomiendo para entornos en producción. Alternativamente, el miembro sslChecks puede ser puesto false para desactivar la revisión.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true

Historial de cambios

Versión | Descripción
0.99.8 | El miembro sslChecks fue agregado

Ver también

  • OAuth::enableSSLChecks() - Activa la verificación SSL

User Contributed Notes

There are no user contributed notes for this page.


Activa la depuración detallada

  • « OAuth::disableSSLChecks
  • OAuth::enableRedirects »
  • PHP Manual
  • OAuth
  • Activa la depuración detallada

OAuth::enableDebug

(PECL OAuth >= 0.99.3)

OAuth::enableDebug — Activa la depuración detallada

Descripción

public OAuth::enableDebug ( ) : bool

Activa la solititud de información detallada útil para depurar, la información de depuración es almacenada en el miembro debugInfo. Alternativamente, el miembro debug puede ser establecido a un valor no-false para activar el depurador.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true

Historial de cambios

Versión | Descripción
0.99.8 | Los miembros debug y debugInfo fueron agregados.

Ver también

  • OAuth::disableDebug() - Desactiva la depuración detallada

User Contributed Notes

There are no user contributed notes for this page.


Activa las re-direcciones

  • « OAuth::enableDebug
  • OAuth::enableSSLChecks »
  • PHP Manual
  • OAuth
  • Activa las re-direcciones

OAuth::enableRedirects

(PECL OAuth >= 0.99.9)

OAuth::enableRedirects — Activa las re-direcciones

Descripción

public OAuth::enableRedirects ( ) : bool

Sigue y firma las re-direcciones automáticamente, el cual está en activado por omisión.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true

Ver también

  • OAuth::disableRedirects() - Desactiva las redirecciones

User Contributed Notes

There are no user contributed notes for this page.


Activa la verificación SSL

  • « OAuth::enableRedirects
  • OAuth::fetch »
  • PHP Manual
  • OAuth
  • Activa la verificación SSL

OAuth::enableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::enableSSLChecks — Activa la verificación SSL

Descripción

public OAuth::enableSSLChecks ( ) : bool

Activa la verificación del certificado y servidor SSL (activado por omisión). Alternativamente, el miembro sslChecks puede ser puesto a un valor distinto a false para desactivar la revisión.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true

Historial de cambios

Versión | Descripción
0.99.8 | El miembro sslChecks fue agregado

Ver también

  • OAuth::disableSSLChecks() - Desactiva la verificación SSL

User Contributed Notes

There are no user contributed notes for this page.


Obtiene un recurso protegido por OAuth

  • « OAuth::enableSSLChecks
  • OAuth::generateSignature »
  • PHP Manual
  • OAuth
  • Obtiene un recurso protegido por OAuth

OAuth::fetch

(PECL OAuth >= 0.99.1)

OAuth::fetch — Obtiene un recurso protegido por OAuth

Descripción

public OAuth::fetch ( string $protected_resource_url , array $extra_parameters = ? , string $http_method = ? , array $http_headers = ? ) : mixed

Obtiene un recurso.

Parámetros

protected_resource_url

URL del recurso OAuth protegio.

extra_parameters

Parámetros adicionales para enviar con la petición del recurso.

http_method

Una de las OAUTH_HTTP_METHOD_* constantes OAUTH, which includes GET, POST, PUT, HEAD, or DELETE.

HEAD (OAUTH_HTTP_METHOD_HEAD) can be useful for discovering information prior to the request (if OAuth credentials are in the Authorization header).

http_headers

Encabezados cliente HTTP (como por ejemplo User-Agent, Accept, etc.)

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
1.0.0 | Antes devolvía null en caso de falla, en lugar de false.
0.99.5 | El parámetro http_method fue agregado
0.99.8 | El parámetro http_headers fue agregado

Ejemplos

Ejemplo #1 Ejemplo de 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 "Excepción atrapada!\n";
    echo "Respuesta: ". $E->lastResponse . "\n";
}
?>

Ver también

  • OAuth::getLastResponse() - Obtiene la última respuesta
  • OAuth::getLastResponseInfo() - Obtiene la información HTTP sobre la última respuesta
  • OAuth::setToken() - Establece el token y el secreto

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.


Generar una firma

  • « OAuth::fetch
  • OAuth::getAccessToken »
  • PHP Manual
  • OAuth
  • Generar una firma

OAuth::generateSignature

(No hay información de versión disponible, podría estar únicamente en Git)

OAuth::generateSignature — Generar una firma

Descripción

public OAuth::generateSignature ( string $http_method , string $url , mixed $extra_parameters = ? ) : string

Generar una firma basada en el método HTTP final, URL y un string/array de parámetros.

Parámetros

http_method

Método HTTP para la solicitud

url

URL de solicitud

extra_parameters

String o array de parámetros adicionales.

Valores devueltos

Un string que contiene la firma generada o false en caso de error

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el token de acceso

  • « OAuth::generateSignature
  • OAuth::getCAPath »
  • PHP Manual
  • OAuth
  • Obtiene el token de acceso

OAuth::getAccessToken

(PECL OAuth >= 0.99.1)

OAuth::getAccessToken — Obtiene el token de acceso

Descripción

public OAuth::getAccessToken ( string $access_token_url , string $auth_session_handle = ? , string $verifier_token = ? , string $http_method = ? ) : array

Obtiene un token de acceso, secreto y cualquier parámetro de respuesta adicional del proveedor de servicio.

Parámetros

access_token_url

URL al token de acceso de la API.

auth_session_handle

El manejador de autorización de sesión, este parámetro no existe en la especificación OAuth 1.0 pero puede ser implementada por muchos proveedores. » Visite ScalableOAuth para más información.

verifier_token

Para los proveedores de servicio que soportan 1.0a, Un parámetro verifier_token debe ser pasado mientras se solicita el token de acceso. Si el parámetro verifier_token está presente en $_GET o $_POST es pasado automáticamente y el solicitante ya no necesita especificar el verifier_token (usualmente el token de acceso es intercambiado en la URL del oauth_callback). » Visite ScalableOAuth para más información.

http_method

Método HTTP a usar, por ejemplo GET o POST.

Valores devueltos

Devuelve un array que contiene las respuestas OAuth analizadas al tener éxito o false al fallar.

Historial de cambios

Versión | Descripción
1.0.0 | Antes devolvía null en caso de falla, en lugar de false.
0.99.9 | El parámetro verifier_token fue agregado

Ejemplos

Ejemplo #1 Ejemplo de 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 "Falló obteniendo el token de acceso, la respuesta fue: " . $oauth->getLastResponse();
    }
} catch(OAuthException $E) {
    echo "Respuesta: ". $E->lastResponse . "\n";
}
?>

El resultado del ejemplo sería algo similar a:

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

Ver también

  • OAuth::getLastResponse() - Obtiene la última respuesta
  • OAuth::getLastResponseInfo() - Obtiene la información HTTP sobre la última respuesta
  • OAuth::setToken() - Establece el token y el secreto

User Contributed Notes

There are no user contributed notes for this page.


Obtiene la información CA

  • « OAuth::getAccessToken
  • OAuth::getLastResponse »
  • PHP Manual
  • OAuth
  • Obtiene la información CA

OAuth::getCAPath

(PECL OAuth >= 0.99.8)

OAuth::getCAPath — Obtiene la información CA

Descripción

public OAuth::getCAPath ( ) : array

Obtiene la información del certificado de Autoridad, el cual incluye los ca_path y ca_info establecidos por OAuth::setCaPath().

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un array con información del Certificado de Autoridad, específicamente como claves ca_path y ca_info dentro del array asociativo devuelto.

Ver también

  • OAuth::setCAPath() - Establece la ruta a CA y su información
  • OAuth::getLastResponseInfo() - Obtiene la información HTTP sobre la última respuesta

User Contributed Notes

There are no user contributed notes for this page.


Obtiene la última respuesta

  • « OAuth::getCAPath
  • OAuth::getLastResponseHeaders »
  • PHP Manual
  • OAuth
  • Obtiene la última respuesta

OAuth::getLastResponse

(PECL OAuth >= 0.99.1)

OAuth::getLastResponse — Obtiene la última respuesta

Descripción

public OAuth::getLastResponse ( ) : string

Obtiene la respuesta original de la más reciente petición.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve la cadena conteniendo la última respuesta.

Ver también

  • OAuth::getLastResponseInfo() - Obtiene la información HTTP sobre la última respuesta
  • OAuth::fetch() - Obtiene un recurso protegido por OAuth

User Contributed Notes

There are no user contributed notes for this page.


Obtener encabezados de la última respuesta

  • « OAuth::getLastResponse
  • OAuth::getLastResponseInfo »
  • PHP Manual
  • OAuth
  • Obtener encabezados de la última respuesta

OAuth::getLastResponseHeaders

(No hay información de versión disponible, podría estar únicamente en Git)

OAuth::getLastResponseHeaders — Obtener encabezados de la última respuesta

Descripción

public OAuth::getLastResponseHeaders ( ) : string

Obtiene los encabezados de la última respuesta.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un string que contiene los encabezados de la última respuesta o false en caso de error

User Contributed Notes

There are no user contributed notes for this page.


Obtiene la información HTTP sobre la última respuesta

  • « OAuth::getLastResponseHeaders
  • OAuth::getRequestHeader »
  • PHP Manual
  • OAuth
  • Obtiene la información HTTP sobre la última respuesta

OAuth::getLastResponseInfo

(PECL OAuth >= 0.99.1)

OAuth::getLastResponseInfo — Obtiene la información HTTP sobre la última respuesta

Descripción

public OAuth::getLastResponseInfo ( ) : array

Obtiene la información HTTP sobre la última respuesta.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve un array conteniendo la información de respuesta de la última petición. Constantes de curl_getinfo() pueden ser usadas.

Ver también

  • OAuth::fetch() - Obtiene un recurso protegido por OAuth
  • OAuth::getLastResponse() - Obtiene la última respuesta

User Contributed Notes

There are no user contributed notes for this page.


Generar un string de firma de cabecera OAuth

  • « OAuth::getLastResponseInfo
  • OAuth::getRequestToken »
  • PHP Manual
  • OAuth
  • Generar un string de firma de cabecera OAuth

OAuth::getRequestHeader

(No hay información de versión disponible, podría estar únicamente en Git)

OAuth::getRequestHeader — Generar un string de firma de cabecera OAuth

Descripción

public OAuth::getRequestHeader ( string $http_method , string $url , mixed $extra_parameters = ? ) : string

Generar un string de firma de cabecera OAuth basada en el método HTTP final, el URL y los parámetros de string/array

Parámetros

http_method

Método HTTP para la petición.

url

URL para la petición.

extra_parameters

String o array de parámetros adicionales.

Valores devueltos

Un string que contiene la cabecera solicitada generada o false en caso de error

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.


Obtiene un token de petición

  • « OAuth::getRequestHeader
  • OAuth::setAuthType »
  • PHP Manual
  • OAuth
  • Obtiene un token de petición

OAuth::getRequestToken

(PECL OAuth >= 0.99.1)

OAuth::getRequestToken — Obtiene un token de petición

Descripción

public OAuth::getRequestToken ( string $request_token_url , string $callback_url = ? , string $http_method = ? ) : array

Obtiene un token de petición, secreto y cualquier parámetro adicional de respuesta del proveedor de servicio.

Parámetros

request_token_url

URL al token de solicitud de la API.

callback_url

URL del callback OAuth. Si callback_url es pasado y es un valor vacío, este es puesto a "oob" para satisfacer las exigencias de OAuth 2009.1 advisory.

http_method

Método HTTP a usar, por ejemplo GET o POST.

Valores devueltos

Devuelve un array conteniendo las respuestas OAuth analizadas al tener éxitoo false al fallar.

Historial de cambios

Versión | Descripción
1.0.0 | Antes devolvía null en caso de falla, en lugar de false.
0.99.9 | El parámetro callback_url fue agregado

Ejemplos

Ejemplo #1 Ejemplo de 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 "Falló obteniendo el token de petición, la respuesta fue: " . $oauth->getLastResponse();
    }
} catch(OAuthException $E) {
    echo "Respuesta: ". $E->lastResponse . "\n";
}
?>

El resultado del ejemplo sería algo similar a:

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

Ver también

  • OAuth::getLastResponse() - Obtiene la última respuesta
  • OAuth::getLastResponseInfo() - Obtiene la información HTTP sobre la última respuesta

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.


Establece el tipo de autorización

  • « OAuth::getRequestToken
  • OAuth::setCAPath »
  • PHP Manual
  • OAuth
  • Establece el tipo de autorización

OAuth::setAuthType

(PECL OAuth >= 0.99.1)

OAuth::setAuthType — Establece el tipo de autorización

Descripción

public OAuth::setAuthType ( int $auth_type ) : bool

Establece donde un parámetro OAuthdebería ser pasado.

Parámetros

auth_type

auth_type puede ser una de las siguientes banderas (in orden descendente de preferencia según OAuth 1.0 sección 5.2):

OAUTH_AUTH_TYPE_AUTHORIZATION
Pasa los parámetros OAuth en la cabecera de Authorization HTTP.
OAUTH_AUTH_TYPE_FORM
Anexa los parámetros OAuth al cuerpo de petición HTTP POST.
OAUTH_AUTH_TYPE_URI
Anexa los parámetros OAuth a la URI de petición.
OAUTH_AUTH_TYPE_NONE
Ninguno.

Valores devueltos

Devuelve true si el parámetro es correctamente establecido, de otra manera false (Ejemplo, si un inválido parámetro auth_type es pasado.)

Historial de cambios

Versión | Descripción
1.0.0 | Antes devolvía null en caso de falla, en lugar de false.

User Contributed Notes

There are no user contributed notes for this page.


Establece la ruta a CA y su información

  • « OAuth::setAuthType
  • OAuth::setNonce »
  • PHP Manual
  • OAuth
  • Establece la ruta a CA y su información

OAuth::setCAPath

(PECL OAuth >= 0.99.8)

OAuth::setCAPath — Establece la ruta a CA y su información

Descripción

public OAuth::setCAPath ( string $ca_path = ? , string $ca_info = ? ) : mixed

Establece el Certificado de Autoridad (CA), tanto la ruta como la información.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

ca_path

La ruta CA a ser establecida.

ca_info

La ruta de información CA a ser establecido.

Valores devueltos

Devuelve true al tener éxitos, o false si tanto ca_path o ca_info son considerados como inválidos.

Historial de cambios

Versión | Descripción
1.0.0 | Antes devolvía null en caso de falla, en lugar de false.

Ver también

  • OAuth::getCaPath() - Obtiene la información CA

User Contributed Notes

There are no user contributed notes for this page.


Configura el nonce para las solicitudes posteriores

  • « OAuth::setCAPath
  • OAuth::setRequestEngine »
  • PHP Manual
  • OAuth
  • Configura el nonce para las solicitudes posteriores

OAuth::setNonce

(PECL OAuth >= 0.99.1)

OAuth::setNonce — Configura el nonce para las solicitudes posteriores

Descripción

public OAuth::setNonce ( string $nonce ) : mixed

Establece el nonce para todas las solicitudes posteriores.

Parámetros

nonce

El valor para oauth_nonce.

Valores devueltos

Devuelve true si tiene éxito, o false si nonce es considerado como inválido.

Historial de cambios

Versión | Descripción
1.0.0 | Antes devolvía null en caso de falla, en lugar de false.

Ver también

  • OAuth::setToken() - Establece el token y el secreto
  • OAuth::setAuthType() - Establece el tipo de autorización
  • OAuth::setVersion() - Configura la versión OAuth

User Contributed Notes

There are no user contributed notes for this page.


El propósito de setRequestEngine

  • « OAuth::setNonce
  • OAuth::setRSACertificate »
  • PHP Manual
  • OAuth
  • El propósito de setRequestEngine

OAuth::setRequestEngine

(PECL OAuth >= 1.0.0)

OAuth::setRequestEngine — El propósito de setRequestEngine

Descripción

public OAuth::setRequestEngine ( int $reqengine ) : void

Establece el motor de peticiones, que estará enviando las peticiones HTTP.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

reqengine

El motor de peticiones deseado. Poner a OAUTH_REQENGINE_STREAMS para usar el Stream PHP, o OAUTH_REQENGINE_CURL para usar Curl.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

Emite una excepción OAuthException si un motor de peticiones inválido es escogido.

Ejemplos

Ejemplo #1 Ejemplo de OAuth::setRequestEngine()

<?php
$consumer = new OAuth();

$consumer->setRequestEngine(OAUTH_REQENGINE_STREAMS);
?>

Ver también

  • Curl
  • PHP streams
  • OAuthException

User Contributed Notes

There are no user contributed notes for this page.


establece el certificado RSA

  • « OAuth::setRequestEngine
  • OAuth::setSSLChecks »
  • PHP Manual
  • OAuth
  • establece el certificado RSA

OAuth::setRSACertificate

(PECL OAuth >= 1.0.0)

OAuth::setRSACertificate — establece el certificado RSA

Descripción

public OAuth::setRSACertificate ( string $cert ) : mixed

Establece el certificado RSA.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

cert

El certificado RSA.

Valores devueltos

Devuelve true si tiene éxito, o false al fallar (Ejemplo, el certificado RSA no se pudo procesar.)

Historial de cambios

Versión | Descripción
1.0.0 | Antes devolvía null en caso de falla, en lugar de false.

Ejemplos

Ejemplo #1 Ejemplo de OAuth::setRsaCertificate()

<?php
$consume = new OAuth('1234', '', OAUTH_SIG_METHOD_RSASHA1);

$consume->setRSACertificate(file_get_contents('test.pem'));
?>

Ver también

  • OAuth::setCaPath() - Establece la ruta a CA y su información

User Contributed Notes

There are no user contributed notes for this page.


Ajustar controles específicos de SSL para las solicitudes

  • « OAuth::setRSACertificate
  • OAuth::setTimestamp »
  • PHP Manual
  • OAuth
  • Ajustar controles específicos de SSL para las solicitudes

OAuth::setSSLChecks

(No hay información de versión disponible, podría estar únicamente en Git)

OAuth::setSSLChecks — Ajustar controles específicos de SSL para las solicitudes

Descripción

public OAuth::setSSLChecks ( int $sslcheck ) : bool

Ajusta controles específicos de SSL para las solicitudes.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

sslcheck

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Establece el timestamp

  • « OAuth::setSSLChecks
  • OAuth::setToken »
  • PHP Manual
  • OAuth
  • Establece el timestamp

OAuth::setTimestamp

(PECL OAuth >= 1.0.0)

OAuth::setTimestamp — Establece el timestamp

Descripción

public OAuth::setTimestamp ( string $timestamp ) : mixed

Establece el timestamp de OAuth para las subsecuentes peticiones.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

timestamp

El timestamp.

Valores devueltos

Devuelve true, a menos que timestamp sea inválido, en cuyo caso false será devuelto.

Historial de cambios

Versión | Descripción
1.0.0 | Antes devolvía null en caso de falla, en lugar de false.

Ver también

  • OAuth::setNonce() - Configura el nonce para las solicitudes posteriores

User Contributed Notes

There are no user contributed notes for this page.


Establece el token y el secreto

  • « OAuth::setTimestamp
  • OAuth::setVersion »
  • PHP Manual
  • OAuth
  • Establece el token y el secreto

OAuth::setToken

(PECL OAuth >= 0.99.1)

OAuth::setToken — Establece el token y el secreto

Descripción

public OAuth::setToken ( string $token , string $token_secret ) : bool

Establece el token y el secreto para las subsecuentes peticiones.

Parámetros

token

El token OAuth.

token_secret

El secreto OAuth.

Valores devueltos

true

Ejemplos

Ejemplo #1 Ejemplo 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.


Configura la versión OAuth

  • « OAuth::setToken
  • OAuthProvider »
  • PHP Manual
  • OAuth
  • Configura la versión OAuth

OAuth::setVersion

(PECL OAuth >= 0.99.1)

OAuth::setVersion — Configura la versión OAuth

Descripción

public OAuth::setVersion ( string $version ) : bool

Establece la versión OAuth para las subsecuentes peticiones

Parámetros

version

Versión OAuth, el valor por omisión es siempre "1.0"

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Clase OAuthProvider

(PECL OAuth >= 1.0.0)

Introducción

Administra una clase OAuthProvider.

Vea también el tutorial externo llamado » Escribiendo un proveedor de servicios OAuth, Que tiene un enfoque práctico a la prestación de este servicio. También hay » Ejemplos de proveedor OAuth en la fuente de la extensión Oauth.

Sinopsis de la Clase

OAuthProvider {
/* Methods */
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
}

Tabla de contenidos

  • OAuthProvider::addRequiredParameter — Agregar parámetros necesarios
  • OAuthProvider::callconsumerHandler — Llama al callback consumerNonceHandler
  • OAuthProvider::callTimestampNonceHandler — Llama al callback timestampNonceHandler
  • OAuthProvider::calltokenHandler — Llama al callback tokenNonceHandler
  • OAuthProvider::checkOAuthRequest — Revisa una petición OAuth
  • OAuthProvider::__construct — Construye un nuevo objeto OAuthProvider
  • OAuthProvider::consumerHandler — Establece el manejador callback consumerHandler
  • OAuthProvider::generateToken — Genera un token aleatorio
  • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
  • OAuthProvider::isRequestTokenEndpoint — Establece isRequestTokenEndpoint
  • OAuthProvider::removeRequiredParameter — Remueve un parámetro requerido
  • OAuthProvider::reportProblem — Reportar un problema
  • OAuthProvider::setParam — Establece un parámetro
  • OAuthProvider::setRequestTokenPath — Establece la ruta de petición del token
  • OAuthProvider::timestampNonceHandler — Establece el callback timestampNonceHandler
  • OAuthProvider::tokenHandler — Establece el manejador callback de tokenHandler

User Contributed Notes

There are no user contributed notes for this page.


Agregar parámetros necesarios

  • « OAuthProvider
  • OAuthProvider::callconsumerHandler »
  • PHP Manual
  • OAuthProvider
  • Agregar parámetros necesarios

OAuthProvider::addRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::addRequiredParameter — Agregar parámetros necesarios

Descripción

final public OAuthProvider::addRequiredParameter ( string $req_params ) : bool

Agregar parámetros requeridos por el proveedor OAuth.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

req_params

Los parámetros requeridos.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • OAuthProvider::removeRequiredParameter() - Remueve un parámetro requerido

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


Llama al callback consumerNonceHandler

  • « OAuthProvider::addRequiredParameter
  • OAuthProvider::callTimestampNonceHandler »
  • PHP Manual
  • OAuthProvider
  • Llama al callback consumerNonceHandler

OAuthProvider::callconsumerHandler

(No hay información de versión disponible, podría estar únicamente en Git)

OAuthProvider::callconsumerHandler — Llama al callback consumerNonceHandler

Descripción

public OAuthProvider::callconsumerHandler ( ) : void

Llama al callback del manejador del consumidor registrado, la cual es establecida con OAuthProvider::consumerHandler().

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

Muestra un error E_ERROR level si la llamada de retorno no puede ser llamada, o no se especificó.

Ver también

  • OAuthProvider::consumerHandler() - Establece el manejador callback consumerHandler

User Contributed Notes

There are no user contributed notes for this page.


Llama al callback timestampNonceHandler

  • « OAuthProvider::callconsumerHandler
  • OAuthProvider::calltokenHandler »
  • PHP Manual
  • OAuthProvider
  • Llama al callback timestampNonceHandler

OAuthProvider::callTimestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::callTimestampNonceHandler — Llama al callback timestampNonceHandler

Descripción

public OAuthProvider::callTimestampNonceHandler ( ) : void

Llama a la función callback del timestamp registrado, que fue establecido con OAuthProvider::timestampNonceHandler().

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

Muestra un error E_ERROR level si la llamada de retorno no puede ser llamada, o no se especificó.

Ver también

  • OAuthProvider::timestampNonceHandler() - Establece el callback timestampNonceHandler

User Contributed Notes

There are no user contributed notes for this page.


Llama al callback tokenNonceHandler

  • « OAuthProvider::callTimestampNonceHandler
  • OAuthProvider::checkOAuthRequest »
  • PHP Manual
  • OAuthProvider
  • Llama al callback tokenNonceHandler

OAuthProvider::calltokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::calltokenHandler — Llama al callback tokenNonceHandler

Descripción

public OAuthProvider::calltokenHandler ( ) : void

Llama a la función callback del token registrado, que fue establecido con OAuthProvider::tokenHandler().

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

Muestra un error E_ERROR level si la llamada de retorno no puede ser llamada, o no se especificó.

Ver también

  • OAuthProvider::tokenHandler() - Establece el manejador callback de tokenHandler

User Contributed Notes

There are no user contributed notes for this page.


Revisa una petición OAuth

  • « OAuthProvider::calltokenHandler
  • OAuthProvider::__construct »
  • PHP Manual
  • OAuthProvider
  • Revisa una petición OAuth

OAuthProvider::checkOAuthRequest

(PECL OAuth >= 1.0.0)

OAuthProvider::checkOAuthRequest — Revisa una petición OAuth

Descripción

public OAuthProvider::checkOAuthRequest ( string $uri = ? , string $method = ? ) : void

Revisa una petición OAuth.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

uri

La URI opcional, o punto final.

method

El métodoHTTP. opcionalmente pasar una de las OAUTH_HTTP_METHOD_* Constantes OAuth.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

Emite un error E_ERROR si el método HTTP no puede ser detectado.

Ver también

  • OAuthProvider::reportProblem() - Reportar un problema

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

?>


Construye un nuevo objeto OAuthProvider

  • « OAuthProvider::checkOAuthRequest
  • OAuthProvider::consumerHandler »
  • PHP Manual
  • OAuthProvider
  • Construye un nuevo objeto OAuthProvider

OAuthProvider::__construct

(PECL OAuth >= 1.0.0)

OAuthProvider::__construct — Construye un nuevo objeto OAuthProvider

Descripción

public OAuthProvider::__construct ( array $params_array = ? )

Inicia un nuevo object OAuthProvider .

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

params_array

La configuración de estos parámetros opcionales se limita al CLI SAPI.

Valores devueltos

Un object OAuthProvider .

Ejemplos

Ejemplo #1 Ejemplo de OAuthProvider::__construct()

<?php
try {

    $op = new OAuthProvider();

    // Usa funciones callback definidas por el usuario
    $op->consumerHandler(array($this, 'lookupConsumer'));
    $op->timestampNonceHandler(array($this, 'timestampNonceChecker'));
    $op->tokenHandler(array($this, 'myTokenHandler'));

    // Ignora el parámetro foo_uri
    $op->setParam('foo_uri', NULL);

    // No es necesario el token para este punto final
    $op->setRequestTokenPath('/v1/oauth/request_token');

    $op->checkOAuthRequest();

} catch (OAuthException $e) {

    echo OAuthProvider::reportProblem($e);
}
?>

Ver también

  • OAuthProvider::setParam() - Establece un parámetro

User Contributed Notes

There are no user contributed notes for this page.


Establece el manejador callback consumerHandler

  • « OAuthProvider::__construct
  • OAuthProvider::generateToken »
  • PHP Manual
  • OAuthProvider
  • Establece el manejador callback consumerHandler

OAuthProvider::consumerHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::consumerHandler — Establece el manejador callback consumerHandler

Descripción

public OAuthProvider::consumerHandler ( callable $callback_function ) : void

Establece el manejador callback, que más tarde será llamado con OAuthProvider::callConsumerHandler().

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

callback_function

El nombre de la función callable.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo del callback 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;
}
?>

Ver también

  • OAuthProvider::callConsumerHandler() - Llama al callback consumerNonceHandler

User Contributed Notes

There are no user contributed notes for this page.


Genera un token aleatorio

  • « OAuthProvider::consumerHandler
  • OAuthProvider::is2LeggedEndpoint »
  • PHP Manual
  • OAuthProvider
  • Genera un token aleatorio

OAuthProvider::generateToken

(PECL OAuth >= 1.0.0)

OAuthProvider::generateToken — Genera un token aleatorio

Descripción

final public static OAuthProvider::generateToken ( int $size , bool $strong = false ) : string

Genera una string de bytes pseudo-aleatorios.

Parámetros

size

La longitud The desired token length, in terms of bytes.

strong

Establecer a true significa que /dev/random será usada para la entropía, de lo contrario /dev/urandom será usado. Este parámetro es ignorado en Windows.

Valores devueltos

El token generado, como un string de bytes.

Errores/Excepciones

Si el parámetro strong es true, entonces un error E_WARNING será emitido cuando la implementación rand() sea usada para rellenar los restantes bytes aleatorios (Ejemplo, cuando no suficientes datos aleatorios fueron encontrados, inicialmente).

Ejemplos

Ejemplo #1 Ejemplo de OAuthProvider::generateToken()

<?php
$p = new OAuthProvider();

$t = $p->generateToken(4);

echo strlen($t),  PHP_EOL;
echo bin2hex($t), PHP_EOL;

?>

El resultado del ejemplo sería algo similar a:

4
b6a82c27

Notas

Nota:

Cuando no suficientes datos aleatorios están disponibles para el sistema, esta función llenará los restantes bytes aleatorios usando la implementación interna de PHP rand().

Ver también

  • openssl_random_pseudo_bytes() - Genera una cadena de bytes pseudo-aleatoria
  • mcrypt_create_iv() - Crea un vector de inicialización (IV) desde una fuente aleatoria

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

Descripción

public OAuthProvider::is2LeggedEndpoint ( mixed $params_array ) : void

El flujo de 2-piernas, o la suscripción de petición. No requiere token.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

params_array

Valores devueltos

An OAuthProvider object.

Ejemplos

Ejemplo #1 Ejemplo de OAuthProvider::is2LeggedEndpoint()

<?php

$provider = new OAuthProvider();

$provider->is2LeggedEndpoint(true);

?>

Ver también

  • OAuthProvider::__construct() - Construye un nuevo objeto OAuthProvider

User Contributed Notes

There are no user contributed notes for this page.


Establece isRequestTokenEndpoint

  • « OAuthProvider::is2LeggedEndpoint
  • OAuthProvider::removeRequiredParameter »
  • PHP Manual
  • OAuthProvider
  • Establece isRequestTokenEndpoint

OAuthProvider::isRequestTokenEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::isRequestTokenEndpoint — Establece isRequestTokenEndpoint

Descripción

public OAuthProvider::isRequestTokenEndpoint ( bool $will_issue_request_token ) : void

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

will_issue_request_token

Establece si emitirá o no una emisión de petición de token, determinando si OAuthProvider::tokenHandler() necesita ser llamado.

Valores devueltos

No devuelve ningún valor.

Ver también

  • OAuthProvider::setRequestTokenPath() - Establece la ruta de petición del token
  • OAuthProvider::reportProblem() - Reportar un problema

User Contributed Notes

There are no user contributed notes for this page.


Remueve un parámetro requerido

  • « OAuthProvider::isRequestTokenEndpoint
  • OAuthProvider::reportProblem »
  • PHP Manual
  • OAuthProvider
  • Remueve un parámetro requerido

OAuthProvider::removeRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::removeRequiredParameter — Remueve un parámetro requerido

Descripción

final public OAuthProvider::removeRequiredParameter ( string $req_params ) : bool

Remueve un parámetro requerido.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

req_params

El parámetro requerido a ser removido.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • OAuthProvider::setParam() - Establece un parámetro
  • OAuthProvider::addRequiredParameter() - Agregar parámetros necesarios

User Contributed Notes

There are no user contributed notes for this page.


Reportar un problema

  • « OAuthProvider::removeRequiredParameter
  • OAuthProvider::setParam »
  • PHP Manual
  • OAuthProvider
  • Reportar un problema

OAuthProvider::reportProblem

(PECL OAuth >= 1.0.0)

OAuthProvider::reportProblem — Reportar un problema

Descripción

final public static OAuthProvider::reportProblem ( string $oauthexception , bool $send_headers = true ) : string

Sucede en un problema como OAuthException, con posibles problemas listados en la sección OAuth constants.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

oauthexception

La OAuthException.

Valores devueltos

No devuelve ningún valor.

Ver también

  • OAuthProvider::checkOAuthRequest() - Revisa una petición OAuth
  • OAuthProvider::isRequestTokenEndpoint() - Establece isRequestTokenEndpoint

User Contributed Notes

There are no user contributed notes for this page.


Establece un parámetro

  • « OAuthProvider::reportProblem
  • OAuthProvider::setRequestTokenPath »
  • PHP Manual
  • OAuthProvider
  • Establece un parámetro

OAuthProvider::setParam

(PECL OAuth >= 1.0.0)

OAuthProvider::setParam — Establece un parámetro

Descripción

final public OAuthProvider::setParam ( string $param_key , mixed $param_val = ? ) : bool

Establece un parámetro.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

param_key

La clave del parámetro.

param_val

El valor opcional del parámetro.

Para excluir un parámetro de la verificación de firmas, colocar este valor a null.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • OAuthProvider::addRequiredParameter() - Agregar parámetros necesarios

User Contributed Notes

There are no user contributed notes for this page.


Establece la ruta de petición del token

  • « OAuthProvider::setParam
  • OAuthProvider::timestampNonceHandler »
  • PHP Manual
  • OAuthProvider
  • Establece la ruta de petición del token

OAuthProvider::setRequestTokenPath

(PECL OAuth >= 1.0.0)

OAuthProvider::setRequestTokenPath — Establece la ruta de petición del token

Descripción

final public OAuthProvider::setRequestTokenPath ( string $path ) : bool

Establece la ruta de petición del token.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

path

La ruta.

Valores devueltos

true

Ver también

  • OAuthProvider::tokenHandler() - Establece el manejador callback de tokenHandler

User Contributed Notes

There are no user contributed notes for this page.


Establece el callback timestampNonceHandler

  • « OAuthProvider::setRequestTokenPath
  • OAuthProvider::tokenHandler »
  • PHP Manual
  • OAuthProvider
  • Establece el callback timestampNonceHandler

OAuthProvider::timestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::timestampNonceHandler — Establece el callback timestampNonceHandler

Descripción

public OAuthProvider::timestampNonceHandler ( callable $callback_function ) : void

Establece el manejador callback timestamp nonce, el cual será llamado luego con OAuthProvider::callTimestampNonceHandler(). Errores relacionados con timestamp/nonce son lanzados a este callback.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

callback_function

El nombre de la función callable.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo de 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;
}
?>

Ver también

  • OAuthProvider::callTimestampNonceHandler() - Llama al callback timestampNonceHandler

User Contributed Notes

There are no user contributed notes for this page.


Establece el manejador callback de tokenHandler

  • « OAuthProvider::timestampNonceHandler
  • OAuthException »
  • PHP Manual
  • OAuthProvider
  • Establece el manejador callback de tokenHandler

OAuthProvider::tokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::tokenHandler — Establece el manejador callback de tokenHandler

Descripción

public OAuthProvider::tokenHandler ( callable $callback_function ) : void

Establece el token del callback, que será llamado después con OAuthProvider::callTokenHandler().

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

callback_function

El nombre de la función callable.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo del callback 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;
}
?>

Ver también

  • OAuthProvider::callTokenHandler() - Llama al callback tokenNonceHandler

User Contributed Notes

There are no user contributed notes for this page.


Clase OAuthException

(PECL OAuth >= 0.99.1)

Introducción

Esta excepción es lanzada cuando un error excepcional durante el uso de la extensión OAuth y contiene información útil de depuración.

Sinopsis de la Clase

OAuthException extends Exception {
/* Propiedades */
public $lastResponse ;
public $debugInfo ;
/* Propiedades heredadas */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Métodos heredados */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

Propiedades

lastResponse

La respuesta de la excepción ocurrida, si la hubiera

debugInfo

User Contributed Notes

There are no user contributed notes for this page.


SOAP

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Funciones de SOAP
    • is_soap_fault — Comprueba si una llamada SOAP ha fallado
    • use_soap_error_handler — Establecer si se desea utilizar el manejador de errores de SOAP
  • SoapClient — La clase SoapClient
    • SoapClient::__call — Llama a una función de SOAP (obsoleto)
    • SoapClient::__construct — Constructor de SoapClient
    • SoapClient::__doRequest — Realiza una petición SOAP
    • SoapClient::__getCookies — Get list of cookies
    • SoapClient::__getFunctions — Devuelve una lista de todas las funciones SOAP disponibles
    • SoapClient::__getLastRequest — Devuelve la última petición SOAP
    • SoapClient::__getLastRequestHeaders — Devuelve los encabezados SOAP de la última petición
    • SoapClient::__getLastResponse — Devuelve la última respuesta SOAP
    • SoapClient::__getLastResponseHeaders — Devuelve los encabezados SOAP de la última respuesta
    • SoapClient::__getTypes — Devuelve una lista de los tipos SOAP
    • SoapClient::__setCookie — El propósito de __setCookie
    • SoapClient::__setLocation — Define la localización del servicio Web a utilizar
    • SoapClient::__setSoapHeaders — Define los encabezados SOAP para las subsiguentes llamadas
    • SoapClient::__soapCall — Llama a una función SOAP
  • SoapServer — La clase SoapServer
    • SoapServer::addFunction — Añade una o más funciones al controlador de peticiones SOAP
    • SoapServer::addSoapHeader — Añade un encabezado SOAP a la respuesta
    • SoapServer::__construct — Constructor de SoapServer
    • SoapServer::fault — SoapServer indica que ocurrió un fallo
    • SoapServer::getFunctions — Devuelve una lista de las funciones definidas
    • SoapServer::handle — Controla la petición SOAP
    • SoapServer::setClass — Define la clase que controla las peticiones SOAP
    • SoapServer::setObject — Define el objecto que será usado para controlar las peticiones SOAP
    • SoapServer::setPersistence — Establece el modo de persistencia de SoapServer
  • SoapFault — La clase SoapFault
    • SoapFault::__construct — Constructor de SoapFault
    • SoapFault::__toString — Obtiene una representación en formato cadena de SoapFault
  • SoapHeader — La clase SoapHeader
    • SoapHeader::__construct — Constructor de SoapHeader
  • SoapParam — La clase SoapParam
    • SoapParam::__construct — Constructor de SoapParam
  • SoapVar — La clase SoapVar
    • SoapVar::__construct — Constructor de 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()


Introducción

La extensión SOAP se puede utilizar para escribir servidores y clientes SOAP. Admite los subconjuntos de especificaciones » SOAP 1.1, » SOAP 1.2 y » WSDL 1.1.

User Contributed Notes

There are no user contributed notes for this page.


Requerimientos

Esta extensión requiere la extensión libxml de PHP. Esto significa que también es necesario pasar la opción --enable-libxml, aunque esto se realiza implícitamente debido a que libxml está habilitada de forma predeterminada.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

Para habilitar el soporte de SOAP, se ha de configurar PHP con --enable-soap.

User Contributed Notes

slawkens 04-Jun-2018 08:01
for latest MacOS with brew, where Homebrew/PHP is deprecated:

brew install php@7.2-soap

(change 7.2 to your version)
cdvillagra 09-May-2017 05:39
If you have not yet updated the OS and also the PHP version

for Ubuntu 14.04 LTS
sudo apt-get install php5.6-soap
sudo service apache2 restart
c at cinqs dot net 16-Feb-2017 07:55
If you received a

    E: Couldn't find any package by regex 'php7.1-soap'

when using docker php:apache image

try

    apt-get install php-soap

instead
digimix.co 24-Jan-2017 01:31
On PHP7.1 Ubuntu 16.04 LTS:
$ sudo apt-get install php7.1-soap
$ sudo service php7.1-fpm reload
wally at soggysoftware dot co dot uk 22-Dec-2016 09:40
If you're using official PHP packages shipped with CentOS or RedHat version 6 or 7:

# yum install php-soap

(Restart Apache/nginx too if appropriate.)
dbagnara 20-Aug-2016 10:02
for Ubuntu 16.04 LTS
sudo apt-get install php7.0-soap
sudo systemctl restart apache2.service


Configuración en tiempo de ejecución

El comportamiento de estas funciones se ve afectado por la configuración de php.ini.

Opciones de configuración de SOAP
Nombre | Por defecto | Cambiable | Historial de cambios
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 |

He aquí una breve explicación de las directivas de configuración.

soap.wsdl_cache_enabled integer

Activa o desactiva la función de almacenamiento en caché de WSDL.

soap.wsdl_cache_dir string

Define el nombre del directorio donde la extensión SOAP guardará los ficheros en caché.

soap.wsdl_cache_ttl integer

Define el número de segundos (tiempo de vida) por los que los ficheros en caché serán usados en lugar de los originales.

soap.wsdl_cache integer

Si la opción soap.wsdl_cache_enabled está activada, este ajuste determina el tipo de almacenamiento en caché. Puede ser cualquiera de estos tipos: WSDL_CACHE_NONE (0), WSDL_CACHE_DISK (1), WSDL_CACHE_MEMORY (2) o WSDL_CACHE_BOTH (3). También puede definirse usando el array options del constructor de SoapClient o de SoapServer.

soap.wsdl_cache_limit integer

Número máximo de ficheros WSDL almacenados en caché de memoria. Si se añaden más ficheros a una caché de memoria llena, se eliminarán los ficheros más antiguos de la misma.

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 predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles sólo cuando la extensión haya sido compilada con PHP, o bien sea cargada dinámicamente en ejecución.

SOAP constants
Constant | Value | Description
SOAP_1_1 (integer) | 1 |
SOAP_1_2 (integer) | 2 |
SOAP_PERSISTENCE_SESSION (integer) | 1 |
SOAP_PERSISTENCE_REQUEST (integer) | 2 |
SOAP_FUNCTIONS_ALL (integer) | 999 |
SOAP_ENCODED (integer) | 1 |
SOAP_LITERAL (integer) | 2 |
SOAP_RPC (integer) | 1 |
SOAP_DOCUMENT (integer) | 2 |
SOAP_ACTOR_NEXT (integer) | 1 |
SOAP_ACTOR_NONE (integer) | 2 |
SOAP_ACTOR_UNLIMATERECEIVER (integer) | 3 |
SOAP_COMPRESSION_ACCEPT (integer) | 32 |
SOAP_COMPRESSION_GZIP (integer) | 0 |
SOAP_COMPRESSION_DEFLATE (integer) | 16 |
SOAP_AUTHENTICATION_BASIC (integer) | 0 |
SOAP_AUTHENTICATION_DIGEST (integer) | 1 |
SOAP_SSL_METHOD_TLS (integer) | 0 | Desde PHP 5.5.0.
SOAP_SSL_METHOD_SSLv2 (integer) | 1 | Desde PHP 5.5.0.
SOAP_SSL_METHOD_SSLv3 (integer) | 2 | Desde PHP 5.5.0.
SOAP_SSL_METHOD_SSLv23 (integer) | 3 | Desde PHP 5.5.0.
UNKNOWN_TYPE (integer) | 999998 |
XSD_STRING (integer) | 101 |
XSD_BOOLEAN (integer) | 102 |
XSD_DECIMAL (integer) | 103 |
XSD_FLOAT (integer) | 104 |
XSD_DOUBLE (integer) | 105 |
XSD_DURATION (integer) | 106 |
XSD_DATETIME (integer) | 107 |
XSD_TIME (integer) | 108 |
XSD_DATE (integer) | 109 |
XSD_GYEARMONTH (integer) | 110 |
XSD_GYEAR (integer) | 111 |
XSD_GMONTHDAY (integer) | 112 |
XSD_GDAY (integer) | 113 |
XSD_GMONTH (integer) | 114 |
XSD_HEXBINARY (integer) | 115 |
XSD_BASE64BINARY (integer) | 116 |
XSD_ANYURI (integer) | 117 |
XSD_QNAME (integer) | 118 |
XSD_NOTATION (integer) | 119 |
XSD_NORMALIZEDSTRING (integer) | 120 |
XSD_TOKEN (integer) | 121 |
XSD_LANGUAGE (integer) | 122 |
XSD_NMTOKEN (integer) | 123 |
XSD_NAME (integer) | 124 |
XSD_NCNAME (integer) | 125 |
XSD_ID (integer) | 126 |
XSD_IDREF (integer) | 127 |
XSD_IDREFS (integer) | 128 |
XSD_ENTITY (integer) | 129 |
XSD_ENTITIES (integer) | 130 |
XSD_INTEGER (integer) | 131 |
XSD_NONPOSITIVEINTEGER (integer) | 132 |
XSD_NEGATIVEINTEGER (integer) | 133 |
XSD_LONG (integer) | 134 |
XSD_INT (integer) | 135 |
XSD_SHORT (integer) | 136 |
XSD_BYTE (integer) | 137 |
XSD_NONNEGATIVEINTEGER (integer) | 138 |
XSD_UNSIGNEDLONG (integer) | 139 |
XSD_UNSIGNEDINT (integer) | 140 |
XSD_UNSIGNEDSHORT (integer) | 141 |
XSD_UNSIGNEDBYTE (integer) | 142 |
XSD_POSITIVEINTEGER (integer) | 143 |
XSD_NMTOKENS (integer) | 144 |
XSD_ANYTYPE (integer) | 145 |
XSD_ANYXML (integer) | 147 |
APACHE_MAP (integer) | 200 |
SOAP_ENC_OBJECT (integer) | 301 |
SOAP_ENC_ARRAY (integer) | 300 |
XSD_1999_TIMEINSTANT (integer) | 401 |
XSD_NAMESPACE (integer) | http://www.w3.org/2001/XMLSchema |
XSD_1999_NAMESPACE (integer) | http://www.w3.org/1999/XMLSchema |
SOAP_SINGLE_ELEMENT_ARRAYS (integer) | 1 |
SOAP_WAIT_ONE_WAY_CALLS (integer) | 2 |
SOAP_USE_XSI_ARRAY_TYPE (integer) | 4 |
WSDL_CACHE_NONE (integer) | 0 |
WSDL_CACHE_DISK (integer) | 1 |
WSDL_CACHE_MEMORY (integer) | 2 |
WSDL_CACHE_BOTH (integer) | 3 |

User Contributed Notes

User 01-Oct-2010 08:56
We are casting the values (float) to simulate the 64-bits long. seem to work fine, of course, the values we are using have no decimal point.


Funciones de SOAP

Tabla de contenidos

  • is_soap_fault — Comprueba si una llamada SOAP ha fallado
  • use_soap_error_handler — Establecer si se desea utilizar el manejador de errores de SOAP

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.


Comprueba si una llamada SOAP ha fallado

  • « Funciones de SOAP
  • use_soap_error_handler »
  • PHP Manual
  • Funciones de SOAP
  • Comprueba si una llamada SOAP ha fallado

is_soap_fault

(PHP 5, PHP 7, PHP 8)

is_soap_fault — Comprueba si una llamada SOAP ha fallado

Descripción

is_soap_fault ( mixed $object ) : bool

Esta función es útil para comprobar si la llamada SOAP ha fallado, pero sin usar excepciones. Para usarse, cree el objecto SoapClient con la opción exceptions definida a cero o false. En este caso, el método SOAP devolverá un objecto especial SoapFault el qual encapsula los datos del fallo (faultcode, faultstring, faultactor and faultdetails).

Si exceptions no está definido la llamada SOAP lanzará una excepción al producirse un error. is_soap_fault() comprueba si un parametro dado es un objecto SoapFault.

Parámetros

object

El objecto a comprobar.

Valores devueltos

Devolverá true si se produce un error y false en caso contrario.

Ejemplos

Ejemplo #1 Ejemplo de 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);
}
?>

Ejemplo #2 El método estándar de SOAP para el informe de errores con las excepciones

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

Ver también

  • SoapClient::SoapClient()
  • SoapFault::SoapFault()

User Contributed Notes

There are no user contributed notes for this page.


Establecer si se desea utilizar el manejador de errores de SOAP

  • « is_soap_fault
  • SoapClient »
  • PHP Manual
  • Funciones de SOAP
  • Establecer si se desea utilizar el manejador de errores de SOAP

use_soap_error_handler

(PHP 5, PHP 7, PHP 8)

use_soap_error_handler — Establecer si se desea utilizar el manejador de errores de SOAP

Descripción

use_soap_error_handler ( bool $handler = true ) : bool

Esta función establece si utilizar o no el manejador de errores de SOAP en el servidor de SOAP. Devolverá el valor anterior. Si está definido a true, los datos de los errores en una aplicación SoapServer serán enviados a los clientes como un mensaje de fallo SOAP. Si es false, el manejador de errores PHP será usado. Lo predeterminado es enviar el error al cliente como un mensaje de fallo de SOAP.

Parámetros

handler

Establecerlo a true para enviar información de los errores al cliente.

Valores devueltos

Devuelve el valor original

Ver también

  • set_error_handler() - Establecer una función de gestión de errores definida por el usuario
  • set_exception_handler() - Establece una función de gestión de excepciones definida por el usuario

User Contributed Notes

There are no user contributed notes for this page.


La clase SoapClient

(PHP 5, PHP 7, PHP 8)

Introducción

La clase SoapClient proporciona un cliente para servidores » SOAP 1.1, » SOAP 1.2. Puede ser usada en modo WSDL o modo no-WSDL.

Sinopsis de la Clase

SoapClient {
/* Métodos */
public __call ( string $function_name , array $arguments ) : mixed
public __construct ( mixed $wsdl , array $options = ? )
public __doRequest ( string $request , string $location , string $action , int $version , int $one_way = 0 ) : 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 = ? ) : void
public __setLocation ( string $new_location = ? ) : string
public __setSoapHeaders ( mixed $soapheaders = ? ) : bool
public __soapCall ( string $function_name , array $arguments , array $options = ? , mixed $input_headers = ? , array &$output_headers = ? ) : mixed
}

Tabla de contenidos

  • SoapClient::__call — Llama a una función de SOAP (obsoleto)
  • SoapClient::__construct — Constructor de SoapClient
  • SoapClient::__doRequest — Realiza una petición SOAP
  • SoapClient::__getCookies — Get list of cookies
  • SoapClient::__getFunctions — Devuelve una lista de todas las funciones SOAP disponibles
  • SoapClient::__getLastRequest — Devuelve la última petición SOAP
  • SoapClient::__getLastRequestHeaders — Devuelve los encabezados SOAP de la última petición
  • SoapClient::__getLastResponse — Devuelve la última respuesta SOAP
  • SoapClient::__getLastResponseHeaders — Devuelve los encabezados SOAP de la última respuesta
  • SoapClient::__getTypes — Devuelve una lista de los tipos SOAP
  • SoapClient::__setCookie — El propósito de __setCookie
  • SoapClient::__setLocation — Define la localización del servicio Web a utilizar
  • SoapClient::__setSoapHeaders — Define los encabezados SOAP para las subsiguentes llamadas
  • SoapClient::__soapCall — Llama a una función SOAP

User Contributed Notes

David 15-Feb-2017 12:57
Under IIS and PHP 7, when creating an new SoapClient, it will through an internal 500 error.

This could be caused by invalid permissions to the wsdl cache directory when using 'cache_wsdl'=>WSDL_CACHE_DISK or WSDL_CACHE_BOTH.

This worked for me:
    try {
        $arrContextOptions=array("ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false,'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT));

        $options = array(
                'soap_version'=>SOAP_1_2,
                'exceptions'=>true,
                'trace'=>1,
                'cache_wsdl'=>WSDL_CACHE_NONE,
                'stream_context' => stream_context_create($arrContextOptions)
        );
        $client = new SoapClient('https://url/dir/file.wsdl', $options);

    } catch (Exception $e) {
        echo "<h2>Exception Error!</h2>";
        echo $e->getMessage();
    }
sheikh303 at gmail dot com 13-Jan-2017 07:51
What is the core method to call remote WSDL file while creating SoapClient object?
is it CURL, wget or anyother?
Ricardo Pedrassani 03-Jun-2016 01:53
If the XML have identities with same name in different levels there is a solution. You don´t have to ever submit a raw XML (this PHP SOAP object don´t allows send a RAW XML), so you have to always translate your XML to a array, like the example below:

$originalXML = "
<xml>
  <firstClient>
      <name>someone</name>
      <adress>R. 1001</adress>
  </firstClient>
  <secondClient>
      <name>another one</name>
      <adress></adress>
  </secondClient>
</xml>"

//Translate the XML above in a array, like PHP SOAP function requires
$myParams = array('firstClient' => array('name' => 'someone',
                                  'adress' => 'R. 1001'),
            'secondClient' => array('name' => 'another one',
                                  'adress' => ''));

$webService = new SoapClient($someURL);
$result = $webService->someWebServiceFunction($myParams);
mcinantyspam at fejm dot pl 13-May-2016 11:32
Please note, that if you provide values that contain illegal xml characters (ASCII codes 0-8,  11-12, 14-15 - or x0-x8, xB-xC, xE-xF in hex), php's SoapClient will do send them in request, although such request is improper because it does not meet XML 1.0 requirements.
You always have to replace or remove these characters in your data before supplying them to SoapClient
info at nospam x valiton x com 13-Apr-2015 08:06
CAUTION:
I had quite a bit of trouble trying to make a request with fopen through a proxy to a secure url.  I kept getting a 400 Bad Request back from the remote host.  It was receiving the proxy url as the SNI host.  In order to get around this I had to explicity set the SNI host to the domain I was trying to reach.  It's apparently the issue outlined in this bug:

https://bugs.php.net/bug.php?id=63519

<?php
$domain = parse_url($file, PHP_URL_HOST);
$proxy_string = "tcp://" . WP_PROXY_HOST  . ":" . WP_PROXY_PORT;
$opts = array(
    'http' => array( 'proxy' => $proxy_string ),
    'ssl' => array( 'SNI_enabled' => true, 'SNI_server_name' => $domain));
$context = stream_context_create($opts);
$handle = fopen( $file, 'r', false, $context );
?>

src:
http://php.net/manual/en/context.http.php#114314
acopantepuy at gmail dot com 11-Apr-2015 02:45
when they want to pass variables into the http header that is how it is done:

<?php

$aHTTP['http']['header'] =  "User-Agent: PHP-SOAP/5.5.11\r\n";

$aHTTP['http']['header'].= "username: XXXXXXXXXXX\r\n"."password: XXXXX\r\n";

$context = stream_context_create($aHTTP);

$client=new SoapClient("https://ocppws-cert.extra.bcv.org.ve:443/AltoValor/BancoUniversal?WSDL",array('trace' => 1,"stream_context" => $context));

$result = $client->jornadaActiva();
var_dump($result);
?>
acopantepuy at gmail dot com 11-Apr-2015 02:42
when they want to pass variables into the http header that is how it is done:

<?php

$aHTTP['http']['header'] =  "User-Agent: PHP-SOAP/5.5.11\r\n";

$aHTTP['http']['header'].= "username: C1040001760102\r\n"."password: bcv2020\r\n";

$context = stream_context_create($aHTTP);

$client=new SoapClient("https://ocppws-cert.extra.bcv.org.ve:443/AltoValor/BancoUniversal?WSDL",array('trace' => 1,"stream_context" => $context));

$result = $client->jornadaActiva();
var_dump($result);
?>
romuloum at hotmail dot com 19-Feb-2015 04:22
After migrating to PHP 5.6.5, the soap 1.2 did not work anymore. So I solved the problem by adding optional parameters SSL.
My error: failed to load external entity
How to solve:
        // options for ssl in php 5.6.5
        $opts = array(
            'ssl' => array('ciphers'=>'RC4-SHA', 'verify_peer'=>false, 'verify_peer_name'=>false)
        );
        // SOAP 1.2 client
        $params = array ('encoding' => 'UTF-8', 'verifypeer' => false, 'verifyhost' => false, 'soap_version' => SOAP_1_2, 'trace' => 1, 'exceptions' => 1, "connection_timeout" => 180, 'stream_context' => stream_context_create($opts) );
        $oSoapClient = new SoapClient ( $url . "?WSDL", $params );
softontherocks at gmail dot com 22-Nov-2014 08:32
I posted in this URL http://softontherocks.blogspot.com/2014/02/web-service-soap-con-php.html a full example of a nusoap web service.

There is defined the server and the cliente who calls the web service.

I hope it would be useful for you.
martin dot schenck at plugsurfing dot com 15-Sep-2014 03:34
If you want to connect to a server that only supports SSLv2/3 and/or TLS 1.0 (no TLS 2 or 3), tell the SOAP client if you get a connection error by setting the appropriate stream context:
<?php
  $opts = array(
    'ssl' => array('ciphers'=>'RC4-SHA')
  );

  $objSoapClient = new SoapClient(
    'https://example.com/?wsdl',
    array ( "encoding"=>"ISO-8859-1",
    'stream_context' => stream_context_create($opts)
    // your options
    );
?>

You might need to disable the SOAP caching of WSDLs in order for the SOAP client to use the new context.
Stefan 03-Jun-2014 11:04
There is a known bug with some versions of Xdebug which can cause SoapClient to not throw an exception but instead cause a fatal error.

Surround the SoapClient call with xdebug_disable(); and xdebug_enable();  to work around this problem.

For reference:

http://bugs.xdebug.org/view.php?id=249
https://bugs.php.net/bug.php?id=47584
Anonymous 12-Sep-2013 09:25
I got the following error when trying to load the WSDL file:

Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: <message> 'MessageName' already defined

In my case there was no double definitions but it was including other files - I think one of them contained a duplicate message with a different namespace (which SoapClient doesn't like).

I resolved it by loading the WSDL in SoapUI, right-clicking and selecting "Export definition". The WSDL that then got created worked fine. Hope this helps somebody.
Guillermo Prandi 20-Feb-2012 02:10
To make an HTTPS call with a client certificate, you can do it this way:

1) Create a file containing both the key and the signed certificate. I did this by concatenating my (.pem) key and the certificate I've got signed from my CA (also .pem format). The file looked like this:

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKagQC1N27Ilb9pWil2NaX2qM8FquXBXK5T1AydOv7sCotsc8MAwbi7
......(snip)......
wAiOCD4K9TyMS76pIS8UyfJl/oIrn7EF24BUpaUfsh8=
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIC/zCCAmigAwIBAgIEAIl1JzANBgkqhkiG9w0BAQQuADBQMQswCQYxVQQGEaJV
......(snip)......
eSPds1hLKYSg0bd3uI7LhaDLOC1PPgb77sYe/uYkUWuHBzllts5x/pfue0zaIBKG
Omjy
-----END CERTIFICATE-----

2) Reference your certificate in the creation of the SOAP client, like this:

$protected_url = "https://my-server/?wsdl";
$my_cert_file = "/my/path/to/mycert.pem";

$client = new SoapClient($protected_url, array('local_cert', $my_cert_file) );
egiardina at badatmath dot com 03-Aug-2011 06:05
This one drove me nuts... if you are connecting to a web service run on Cassini, (Visual Studio's web server) from php, you may not be able to call web service functions or load a WSDL out-of-the-box.

My set up is that I am using xampp on my windows development machine, and also using Visual Studio's built in web-server. I built a web service in visual studio. I wrote a simple PHP script, running under xampp, to access this service, so the two projects can 'talk' to each other. What I found was the WSDL was never loaded.

So I moved the WSDL local to the PHP file and accessed it directly. Still no calls. Turns out, PHP's SoapClient seems to have a problem with 'localhost' as a web service endpoint. So I hand-edited the web service endpoint URL to read 127.0.0.1 instead of localhost, and Voila! Web Service calls work:

Here is my PHP, now working:
<?php
$client = new SoapClient("http://localhost/code/soap.wsdl");
$something =  $client->HelloWorld(array());
echo $something->HelloWorldResult;
die();

?>

Here is my modified WSDL:
  <wsdl:service name="MyService">
    <wsdl:port name="MyServiceSoap" binding="tns:MyServiceSoap">
      <soap:address location="http://127.0.0.1:55274/MyService/MyService.asmx" />
....

    </wsdl:port>
stepan dot zarubin at gmail dot com 30-Jun-2011 11:51
Well, this example works fine:

<?php
try {
    $x = @new SoapClient("non-existent.wsdl");
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Just make sure use NEW with @.
jjlopez 09-Mar-2011 11:36
If you are making soap calls in WSDL mode , and the address of your web service includes a port different from 80 (like http://my_ip_address:8080//service.asmx?wsdl), the WSDL file is fetched correctly, but all subsequent requests are made without any port in the host field. This causes a SoapFault exception when trying to call any of the service’s methods.

You need to redefine the soapClient class and force the port in each call.

See this example:

http://www.victorstanciu.ro/php-soapclient-port-bug-workaround/
hugues at zonereseau dot com 17-Feb-2011 09:17
When you need to connect to services requiring to send extra header use this method.

Here how we can to it with PHP and SoapClient

<?php
class exampleChannelAdvisorAuth
{
    public $DeveloperKey;
    public $Password;

    public function __construct($key, $pass)
    {
        $this->DeveloperKey = $key;
        $this->Password = $pass;
    }
}

$devKey        = "";
$password    = "";
$accountId    = "";

// Create the SoapClient instance
$url         = "";
$client     = new SoapClient($url, array("trace" => 1, "exception" => 0));

// Create the header
$auth         = new ChannelAdvisorAuth($devKey, $password);
$header     = new SoapHeader("http://www.example.com/webservices/", "APICredentials", $auth, false);

// Call wsdl function
$result = $client->__soapCall("DeleteMarketplaceAd", array(
    "DeleteMarketplaceAd" => array(
        "accountID"        => $accountId,
        "marketplaceAdID"    => "9938745"        // The ads ID
    )
), NULL, $header);

// Echo the result
echo "<pre>".print_r($result, true)."</pre>";
if($result->DeleteMarketplaceAdResult->Status == "Success")
{
    echo "Item deleted!";
}
?>
fourat dot zouari at tritux dot com 20-Jun-2009 08:08
In addition to the KeepAlive trick which is a "server-side" modification, on the "client side" default_socket_timeout should be increased from its default value (60) when you deal with ~slow SOAP servers.
As for the KeepAlive, if creating a new separate vhost for the soap api is not possible, you can add this to your existing vhost: BrowserMatch "^PHP-SOAP" nokeepalive
where PHP-SOAP is the agent name of your soap client, if you dont know what agent name your client use, just checkout the access.log of your apache.
peter dot hansen at fastit dot net 01-May-2009 06:57
When you get errors like:
"Fatal error: Uncaught SoapFault exception: [HTTP] Error Fetching http headers in"
after a few (time intensive) SOAP-Calls, check your webserver-config.

Sometimes the webservers "KeepAlive"-Setting tends to result in this error. For SOAP-Environments I recommend you to disable KeepAlive.

Hint: It might be tricky to create a dedicated vhost for your SOAP-Gateways and disable keepalive just for this vhost because for normal webpages Keepalive is a nice speed-boost.


Llama a una función de SOAP (obsoleto)

  • « SoapClient
  • SoapClient::__construct »
  • PHP Manual
  • SoapClient
  • Llama a una función de SOAP (obsoleto)

SoapClient::__call

(PHP 5, PHP 7, PHP 8)

SoapClient::__call — Llama a una función de SOAP (obsoleto)

Descripción

public SoapClient::__call ( string $function_name , array $arguments ) : mixed

Llamar a este método directamente está obsoleto. Normalmente, las funciones de SOAP pueden ser invocadas como métodos del objeto SoapClient; en situaciones donde esto no es posible o son necesarias opciones adicionales, use SoapClient::__soapCall().

User Contributed Notes

philipp dot gruber at catchoftheday dot com dot au 07-Apr-2014 12:27
If you are using a WSDL, the library will strip out anything from your parameters that is not defined in WSDL, without giving you any notice about this.

So if your parameters are not fully matching the WSDL, it will simply send no parameters at all.
This can be a bit hard to debug if you don't have access to the target server.

__soapCall() expects parameters in an array called 'parameters' as opposed to calling the function via it's WSDL name, where it accepts the parameters as a plain array.

I.e. if a function called sendOrder expects a parameter (array) called orderDetails, you can call it like this:

$orderDetails = array(/* your data */);
$soap->sendOrder(array('orderDetails' => $orderDetails));

Which is equivalent to:

$client->__soapCall('sendOrder', array('parameters' => array('orderDetails' => $orderDetails)));

Note the additional 'parameters' key used in __soapCall().
KRavEN 17-Jun-2009 06:56
extend of __call thats adds a retry to handle the occasional 'Could not connect to host' exceptions

<?php
class LocalSoapClient extends SoapClient
{

  public function __call($function_name, $arguments)
  {
    $result = false;
    $max_retries = 5;
    $retry_count = 0;

    while(! $result && $retry_count < $max_retries)
    {
      try
      {
        $result = parent::__call($function_name, $arguments);
      }
      catch(SoapFault $fault)
      {
        if($fault->faultstring != 'Could not connect to host')
        {
          throw $fault;
        }
      }
      sleep(1);
      $retry_count ++;
    }
    if($retry_count == $max_retries)
    {
      throw new SoapFault('Could not connect to host after 5 attempts');
    }
    return $result;
  }
}
?>
bananos at dev dot co dot ua 11-Apr-2008 05:13
I'm writing PHP SOAP client (based on php_soap extension) which uses Google AdService,
today, I tried to create sample Ad using   AdService::addAds()  and discovered that my SOAP library does not pass
"headline", "description1", "description2"  parameters in SOAP request.

First, I thought that this was something wrong with my data, coz I was getting validation errors like
"One or more input elements failed validation."   Then I decided to take a look at WSDL description
https://adwords.google.com/api/adwords/v11/AdService?wsdl

And voilà !  I've found this:

<complexType name="Ad" abstract="true">
<sequence>
  <element name="adGroupId" type="xsd:int"/>
  <element name="adType" nillable="true" minOccurs="0" type="impl:AdType"/>
  <element name="destinationUrl" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="disapproved" type="xsd:boolean"/>
  <element name="displayUrl" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="exemptionRequest" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="id" type="xsd:long"/>
  <element name="status" nillable="true" minOccurs="0" type="impl:AdStatus"/>
</sequence>

</complexType>

There is no any ''description", "headline1", "headline2", however there is another complexType

<complexType name="TextAd">
    <complexContent>
    <extension base="impl:Ad">
    <sequence>

<element name="description1" nillable="true" type="xsd:string"/>
<element name="description2" nillable="true" type="xsd:string"/>
<element name="headline" nillable="true" type="xsd:string"/>
</sequence>

</extension>
</complexContent>
</complexType>

So, the thing is when you are working with php_soap be aware of complexType extensions which does not work in php_soap when you try to do things like:

<?php

$client = new
    SoapClient(
       "https://adwords.google.com/api/adwords/v11/AdService?wsdl",
        array(  'trace'      => true,
                'exceptions' => true,
             )

    );

$entropy     = substr(md5(rand(0, time())), 0, 10);
//create Ad test structure
$sample_ad =  array(
               "id" => 0,
               "adGroupId" => 0,
               "adType" => 'TextAd',
               "disapproved" => false,
               "destinationUrl" => 'http://test.com',
               "displayUrl" => 'www.Test.com',
               "status" => "Paused", //  Enabled / Disabled
               "descr_iption1" => 'D1_'.$entropy,
               "des_cription2" => 'D2_'.$entropy,
               "head_line" => 'H_'.$entropy
        );

$client->addAds(array('ads' => array($sample_ad) );
?>
Samil Abud 19-Dec-2007 12:00
Hi,
This is a good example, for the SOAP function "__call".
However it is deprecated.

<?php
$wsdl = "http://webservices.tekever.eu/ctt/?wsdl";
$int_zona = 5;
$int_peso = 1001;
$cliente = new SoapClient($wsdl);
print "<p>Envio Internacional: ";
$vem = $cliente->__call('CustoEMSInternacional',array($int_zona, $int_peso));
print $vem;
print "</p>";
?>


Constructor de SoapClient

  • « SoapClient::__call
  • SoapClient::__doRequest »
  • PHP Manual
  • SoapClient
  • Constructor de SoapClient

SoapClient::__construct

(PHP 5, PHP 7, PHP 8)

SoapClient::__construct — Constructor de SoapClient

Descripción

public SoapClient::__construct ( mixed $wsdl , array $options = ? )

Esta función es un alias de: SoapClient::SoapClient()

User Contributed Notes

There are no user contributed notes for this page.


Realiza una petición SOAP

  • « SoapClient::__construct
  • SoapClient::__getCookies »
  • PHP Manual
  • SoapClient
  • Realiza una petición SOAP

SoapClient::__doRequest

(PHP 5, PHP 7, PHP 8)

SoapClient::__doRequest — Realiza una petición SOAP

Descripción

public SoapClient::__doRequest ( string $request , string $location , string $action , int $version , int $one_way = 0 ) : string

Realiza una petición SOAP vía HTTP.

Este método puede ser sobreescrito en subclases para implementar diferentes capas de transporte, realizar procesos XML adiciones u otros propósitos.

Parámetros

request

La petición XML SOAP.

location

La URL donde realizar la petición.

action

La acción SOAP.

version

La versión de SOAP.

one_way

Si one_way está defindo a 1, este método no devolverá nada. Use esta opción cuando no se espera una respuesta.

Valores devueltos

La respuesta XML SOAP response.

Historial de cambios

Versión | Descripción
5.1.3 | Se añadió el parámetro one_way.

Ejemplos

Ejemplo #1 Ejemplo de 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, $version, $one_way = 0) {
    ob_start();
    $this->server->handle($request);
    $response = ob_get_contents();
    ob_end_clean();
    return $response;
  }

}

$x = new LocalSoapClient(NULL,array('location'=>'test://',
                                   'uri'=>'http://testuri.org'));
var_dump($x->Add(3,4));
?>

User Contributed Notes

tschallacka 22-Mar-2016 02:01
I just wanted to note in plain english how to build up this request, because I made some assumptions by just misterpreting the parameters.

This is for future reference(for myself) and others that might end up a bit mistified by just not understanding the finesses of soap and are trying to learn.

    $this->__doRequest(string $request , string $location , string $action , int $version [, int $one_way = 0 ] );

$request = The XML Soap enveloppe
$location = The url to the WSDL file. No matter that you defined this before when setting up the object, you need to reuse it here.
$action = the soap action to be performed. This is defined in the wsdl file and can be in the form of a single form or an url. it's just a parameter and might not be an actual valid url
$version = SOAP_1_1 =  content headers (Content-Type: text/xml; CHARSET=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

Descripción

public SoapClient::__getCookies ( ) : array

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Devuelve una lista de todas las funciones SOAP disponibles

  • « SoapClient::__getCookies
  • SoapClient::__getLastRequest »
  • PHP Manual
  • SoapClient
  • Devuelve una lista de todas las funciones SOAP disponibles

SoapClient::__getFunctions

(PHP 5, PHP 7, PHP 8)

SoapClient::__getFunctions — Devuelve una lista de todas las funciones SOAP disponibles

Descripción

public SoapClient::__getFunctions ( ) : array

Devuelve un array de las funciones descritas en el WSDL del servicio web.

Nota:

Esta función funciona sólo en modo WSDL.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

El array de las funciones prototipo de SOAP, que detallan el tipo retornado, el nombre de la función y los parámetros y sus tipos.

Ejemplos

Ejemplo #1 Ejemplo de SoapClient::__getFunctions()

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getFunctions());
?>

El resultado del ejemplo sería:

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

Ver también

  • SoapClient::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.


Devuelve la última petición SOAP

  • « SoapClient::__getFunctions
  • SoapClient::__getLastRequestHeaders »
  • PHP Manual
  • SoapClient
  • Devuelve la última petición SOAP

SoapClient::__getLastRequest

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastRequest — Devuelve la última petición SOAP

Descripción

public SoapClient::__getLastRequest ( ) : string

Devuelve el XML enviado en la última petición SOAP.

Nota:

Este método solo funciona si el objecto SoapClient fue creado con la opción trace establecida a true.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

La última petición SOAP, como cadena XML.

Ejemplos

Ejemplo #1 Ejemplo de SoapClient::__getLastRequest()

<?php
$client = new SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>

Ver también

  • SoapClient::__getLastRequestHeaders() - Devuelve los encabezados SOAP de la última petición
  • SoapClient::__getLastResponse() - Devuelve la última respuesta SOAP
  • SoapClient::__getLastResponseHeaders() - Devuelve los encabezados SOAP de la última respuesta

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


Devuelve los encabezados SOAP de la última petición

  • « SoapClient::__getLastRequest
  • SoapClient::__getLastResponse »
  • PHP Manual
  • SoapClient
  • Devuelve los encabezados SOAP de la última petición

SoapClient::__getLastRequestHeaders

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastRequestHeaders — Devuelve los encabezados SOAP de la última petición

Descripción

public SoapClient::__getLastRequestHeaders ( ) : string

Devuelve los encabezados SOAP de la última petición.

Nota:

Esta función solo funciona si el objecto SoapClient fue creado con la opción trace establecida como true.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

La última petición de los encabezados SOAP.

Ejemplos

Ejemplo #1 Ejemplo de SoapClient::__getLastRequestHeaders()

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST HEADERS:\n" . $client->__getLastRequestHeaders() . "\n";
?>

Ver también

  • SoapClient::__getLastResponseHeaders() - Devuelve los encabezados SOAP de la última respuesta
  • SoapClient::__getLastRequest() - Devuelve la última petición SOAP
  • SoapClient::__getLastResponse() - Devuelve la última respuesta 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....


Devuelve la última respuesta SOAP

  • « SoapClient::__getLastRequestHeaders
  • SoapClient::__getLastResponseHeaders »
  • PHP Manual
  • SoapClient
  • Devuelve la última respuesta SOAP

SoapClient::__getLastResponse

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastResponse — Devuelve la última respuesta SOAP

Descripción

public SoapClient::__getLastResponse ( ) : string

Devuelve el XML recibido en la última respuesta SOAP.

Nota:

Esta función solo funciona si el objecto SoapClient fue creado con la opción trace establecida como true.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

La última respuesta SOAP, como cadena XML.

Ejemplos

Ejemplo #1 Ejemplo de SoapClient::__getLastResponse()

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "Response:\n" . $client->__getLastResponse() . "\n";
?>

Ver también

  • SoapClient::__getLastResponseHeaders() - Devuelve los encabezados SOAP de la última respuesta
  • SoapClient::__getLastRequest() - Devuelve la última petición SOAP
  • SoapClient::__getLastRequestHeaders() - Devuelve los encabezados SOAP de la última petición

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


Devuelve los encabezados SOAP de la última respuesta

  • « SoapClient::__getLastResponse
  • SoapClient::__getTypes »
  • PHP Manual
  • SoapClient
  • Devuelve los encabezados SOAP de la última respuesta

SoapClient::__getLastResponseHeaders

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastResponseHeaders — Devuelve los encabezados SOAP de la última respuesta

Descripción

public SoapClient::__getLastResponseHeaders ( ) : string

Devuelve los encabezados SOAP de la última respuesta

Nota:

Esta función solo funciona si el objecto SoapClient fue creado con la opción trace establecida como true.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

La última respuesta de los encabezados SOAP.

Ejemplos

Ejemplo #1 Ejemplo de SoapClient::__getLastResponse()

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "RESPONSE HEADERS:\n" . $client->__getLastResponseHeaders() . "\n";
?>

Ver también

  • SoapClient::__getLastRequestHeaders() - Devuelve los encabezados SOAP de la última petición
  • SoapClient::__getLastRequest() - Devuelve la última petición SOAP
  • SoapClient::__getLastResponse() - Devuelve la última respuesta 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


Devuelve una lista de los tipos SOAP

  • « SoapClient::__getLastResponseHeaders
  • SoapClient::__setCookie »
  • PHP Manual
  • SoapClient
  • Devuelve una lista de los tipos SOAP

SoapClient::__getTypes

(PHP 5, PHP 7, PHP 8)

SoapClient::__getTypes — Devuelve una lista de los tipos SOAP

Descripción

public SoapClient::__getTypes ( ) : array

Devuelve un array de los tipos descritos en el WSDL para el servicio web.

Nota:

Esta función funciona sólo en modo WSDL.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un array de los tipos SOAP, detallando todas las estructuras y los tipos.

Ejemplos

Ejemplo #1 Ejemplo de SoapClient::__getTypes()

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getTypes());
?>

El resultado del ejemplo sería:

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

Ver también

  • SoapClient::SoapClient()

User Contributed Notes

felipe dot cwb at hotmail dot com 21-Jul-2014 06:50
<?php
// to see formated types

$soap = new SoapClient('http://domain.com/ws.php?WSDL');

echo '<pre>';
echo '<h2>Types:</h2>';
$types = $soap->__getTypes();
foreach ($types as $type) {
    $type = preg_replace(
        array('/(\w+) ([a-zA-Z0-9]+)/', '/\n /'),
        array('<font color="green">${1}</font> <font color="blue">${2}</font>', "\n\t"),
        $type
    );
    echo $type;
    echo "\n\n";
}
echo '</pre>';


El propósito de __setCookie

  • « SoapClient::__getTypes
  • SoapClient::__setLocation »
  • PHP Manual
  • SoapClient
  • El propósito de __setCookie

SoapClient::__setCookie

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

SoapClient::__setCookie — El propósito de __setCookie

Descripción

public SoapClient::__setCookie ( string $name , string $value = ? ) : void

Define una cookie a ser enviada conjunto con la peticiones SOAP.

Nota:

Al llamar este método afectará a todas las siguentes llamadas a los métodos SoapClient.

Parámetros

name

El nombre de la cookie.

value

El valor de la cookie. Si no se especifica, la cookie será eliminada.

Valores devueltos

No devuelve ningún valor.

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.


Define la localización del servicio Web a utilizar

  • « SoapClient::__setCookie
  • SoapClient::__setSoapHeaders »
  • PHP Manual
  • SoapClient
  • Define la localización del servicio Web a utilizar

SoapClient::__setLocation

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

SoapClient::__setLocation — Define la localización del servicio Web a utilizar

Descripción

public SoapClient::__setLocation ( string $new_location = ? ) : string

Define la URL de conexión que será usada por las siguientes peticiones SOAP. Esto es equivalente a especificar la opción location cuando se construye el SoapClient.

Nota:

Llamar este método es opcional. El SoapClient utiliza la URL de conexión desde el fichero WSDL por defecto.

Parámetros

new_location

La nueva URL de conexión.

Valores devueltos

La anterior URL de conexión.

Ejemplos

Ejemplo #1 Ejemplo de SoapClient::__setLocation()

<?php
$client = new SoapClient('http://example.com/webservice.php?wsdl');

$client->__setLocation('http://www.somethirdparty.com');

$old_location = $client->__setLocation(); // Desactiva la opción location

echo $old_location;

?>

El resultado del ejemplo sería algo similar a:

http://www.somethirdparty.com

Ver también

  • SoapClient::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.


Define los encabezados SOAP para las subsiguentes llamadas

  • « SoapClient::__setLocation
  • SoapClient::__soapCall »
  • PHP Manual
  • SoapClient
  • Define los encabezados SOAP para las subsiguentes llamadas

SoapClient::__setSoapHeaders

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

SoapClient::__setSoapHeaders — Define los encabezados SOAP para las subsiguentes llamadas

Descripción

public SoapClient::__setSoapHeaders ( mixed $soapheaders = ? ) : bool

Define los encabezados a enviar en las peticiones SOAP.

Nota:

Llamar este método reemplazará cualquier valor previo.

Parámetros

soapheaders

Encabezados a definir. Puede ser un objecto SoapHeader o un array de objectos SoapHeader. Si no se especifica o se define a null, los encabezados serán eliminados.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de 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',
                            'hola mundo');

$client->__setSoapHeaders($header);

$client->__soapCall("echoVoid", null);
?>

Ejemplo #2 Definir múltiples encabezados

<?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',
                            'hola mundo');

$headers[] = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hola mundo otra vez');

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


Llama a una función SOAP

  • « SoapClient::__setSoapHeaders
  • SoapServer »
  • PHP Manual
  • SoapClient
  • Llama a una función SOAP

SoapClient::__soapCall

(PHP 5, PHP 7, PHP 8)

SoapClient::__soapCall — Llama a una función SOAP

Descripción

public SoapClient::__soapCall ( string $function_name , array $arguments , array $options = ? , mixed $input_headers = ? , array &$output_headers = ? ) : mixed

Esta es una función de bajo nivel del API que se utiliza para hacer llamadas SOAP. Usualmente, en modo WSDL, las funciones soap pueden llamarse como métodos del objecto SoapClient. Este método es útil en módo no-WSDL cuando no se conoce la soapaction, la uri es diferente de la por defecto o cuando se envian y/o reciben encabezados SOAP.

Cuando se produce un error, llamar a una función SOAP puede causar a PHP lanzar una excepción o revolver el objecto SoapFault si las excepciones están desactivadas. Para comprobar si la llamada a la función falló capturar las excepciones SoapFault, comprobar el resultado con is_soap_fault().

Parámetros

function_name

Nombre de la función SOAP a llamar.

arguments

Un array de argumentos a pasar a la función. Puede ser bien un array ordenado o asociativo. Tenga en cuenta que la mayoría de los servidores SOAP requieren que los nombres de parámetros sean proveídos, en cuyo caso ha de ser un array asociativo.

options

Un array asociativo de opciones a pasar al cliente.

La opción location es la URL del servicio Web remoto.

La opción uri es el destino del espacio de nombres del servicio SOAP.

La opción soapaction es la acción a llamar.

input_headers

Un array de encabezados a ser enviados con la petición SOAP.

output_headers

Si se proporciona, este array se llenará con los encabezados de la respuesta SOAP.

Valores devueltos

Las funciones SOAP quizá devuelven uno, o múltiples valores. Si solo un valor es devuelto por la función SOAP, el valor retornado de __soapCall será un valor siemple (p.e.j. un integer, un string, etc). Si múltiples valores son retornados, __soapCall devolverá un array asociativo de los nombrados parámetros de salida.

En caso de error, si el objecto SoapClient fue construido con la opción exceptions establecida a false, devolverá un objeto SoapFault.

Ejemplos

Ejemplo #1 Ejemplo de 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'));
?>

Ver también

  • SoapClient::SoapClient()
  • SoapParam::SoapParam()
  • SoapVar::SoapVar()
  • SoapHeader::SoapHeader()
  • SoapFault::SoapFault()
  • is_soap_fault() - Comprueba si una llamada SOAP ha fallado

User Contributed Notes

arturklesun at gmail dot com 10-Aug-2016 06:16
Sharing my experience cuz i believe it is most important for you if you decide to use this Soap Client implementation.

At php 7.0.8 the stdClass generated by SoapClient from the response does not use "minOccurs" and "maxOccurs" WSDL modifiers to distinct properties in stdClass-es (aka keys in "associative arrays") and elements in arrays ("aka indexed arrays").

Instead, the implementation decides whether tag is _a key in associative array_ or _one of elements with same tag in indexed array_ by simply the fact whether there is just one element with such tag in the sequence or many.

Consider alive example from my case:
<?php
response xml:
...
<ValidatingCarrier>
    <Alternate>AA</Alternate>
</ValidatingCarrier>
...
<ValidatingCarrier>
    <Alternate>AA</Alternate>
    <Alternate>AY</Alternate>
</ValidatingCarrier>
...

response structure generated by SoapClient:
...
[ValidatingCarrier] => stdClass Object(
    [Alternate] => AA // here it is a string
)
...
[ValidatingCarrier] => stdClass Object (
    [Alternate] => Array ( // and here this is an array
        [0] => AA
        [1] => AY
    )
)
...

field XSD definition:
<xs:element name="Alternate" type="CarrierCode" minOccurs="0" maxOccurs="24">
?>

You see, the definition in XSD tells us this tag can be repeated up to 24 times, what means it would be an indexed array, but SoapClient does not take that into account and treats the first <Alternate> in example as a value instead of array containing this value.

Undoubtedly, a value should be a property in the stdClass (a key in associative array) _only_ when maxOccurs is 1 or less or not specified (default is 1, see https://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints). Hope this info will be useful for you when you will be implementing your own, correctly working, SoapClient.
ub at sturmundbraem dot ch 11-Jun-2016 12:51
To avoid the SOAP client returning sometimes objects and sometimes arrays of objects, there's a setting:

   $this->soapClient = new \SoapClient($wsdlUrl, array(
    'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
    'trace' => DEBUG_SOAP
   ));
pmeth at softersoftware dot com 12-May-2014 04:44
Note, when trying to overload the __soapCall function, you should not use type hints or STRICT_STANDARDS will complain.
The correct signature is as follows:

<?php
class MySoapClient extends \SoapClient
{
    ...
    public function __soapCall($function_name, $arguments, $options = null, $input_headers = null, &$output_headers = null)
     {
        ...
    }
    ....
}
?>
vb 17-Oct-2012 04:23
Note that calling __soapCall and calling the generated method from WSDL requires specifying parameters in two different ways.

For example, if you have a web service with method login that takes username and password, you can call it the following way:
<?php
$params = array('username'=>'name', 'password'=>'secret');
$client->login($params);
?>

If you want to call __soapCall, you must wrap the arguments in another array as follows:
<?php
$client->__soapCall('login', array($params));
?>
snuufix+nospam at gmail dot com 11-Feb-2011 03:23
I am using SOAP call response headers to sign request results.

After alot of hours, I finally got the best way to get SOAP response headers (other than parsing __getLastResponse() witch requires trace option enabled) is using __soapCall() wrapper.

You can extend SoapClient class and wrap some functions to make sure you get the headers.

<?php

class API extends SoapClient
{

    // ... Constructor, etc.

    // Get SOAP Server response headers
    public function __soapCall($function, $arguments, $options = array(), $input_headers = null, &$output_headers = null)
    {
        parent::__soapCall($function, $arguments, $options, $input_headers, $output_headers);

        print_r($output_headers); // Array of response headers
    }

    // If you are using WSDL you need this, so you still can call functions directly without calling __soapCall manualy
    public function __call($func, $args)
    {
        return $this->__soapCall($func, $args);
    }

?>
niko dot hujanen at gmail dot com 09-Nov-2010 11:06
I was integrating a local warehouse system with a SOAP to our system and noticed some things.

1) Service uses "dot-namespacing" (fe. Item.Price) I classmapped this to Item_Price and used magical __get() and __set() to strip off 'Item.' from variable names. Works like a charm.

Example:
<Item.Price>1.52</Item.Price>

<?php
class Item_Price {
    public $price;
    public function __get($field) { $field = str_replace('Item.', '', $field); return $this->$field; }
    public function __set($field, $value) { $field = str_replace('Item.', '', $field); $this->$field = $value; }
?>

2) I noticed that classmapping a segment with attributes and value is possible. Class uses variables as attributes and $_ is the value.

Example:
<?php
class Foo {
    public $item = 'Bar';
    public $_ = 'Value here';
}
?>
Turns to <Foo item="Bar">Value here</Foo>

Example of using classes with soapcalls:
<?php
    $client = ExtendSoapClient::getInstance();
    $foo = new Foo();
    $response = $client->sendFoo($foo);
?>

Posted these since I think the documentation is lacking and very obsolete. Hopefully someone's burden eases.
james dot ellis at gmail dot com 09-Jun-2010 07:12
If you are using this method, remember that the array of arguments need to be passed in with the ordering being the same order that the SOAP endpoint expects.

e.g
<?php
//server expects: Foo(string name, int age)

//won't work
$args = array(32, 'john');
$out = $client->__soapCall('Foo', $args);

//will work
$args = array('john', 32);
$out = $client->__soapCall('Foo', $args);
?>
lesley at casbah dot com dot au 21-Apr-2009 06:55
If you are calling a weblogic service with a certificate and you are getting this error on the soap method call statement:

[EJB:010160]Security Violation: User: '<anonymous>' has insufficient permission to access EJB: type=<ejb>, application=app2_0_52_3, module=appsejb.jar, ejb=AppMethod, method=AppMethod, methodInterface=Remote, signature={java.lang.String}.

then check the wsdl in the soap open call - it must be https.  Supplied with an http wsdl this took some time to figure out.

<?php
    $client = new SoapClient("https://example.com/AppWs/Service?WSDL",
                array('trace'=>true,
                      'exceptions'=>true,
                      'local_cert' => "/var/www/html/app/newcert.pem",
                      'passphrase' => "thepassphrase"));
    $response = $client->__soapCall("MyMethod", array("param1" => $value1));
?>

Thanks to the authors for their comments on enabling openssl and curl by uncommenting extension=php_opensll.dll and extension=php_curl.dll in php.ini.  Also for Olaf's instructions "append the content of the private key file and the certificate file to a single file". I did this using copy command on the DOS prompt:

copy mycert.pem+mykey.pem newcert.pem
Tim Williams 08-Apr-2009 06:55
One little gotcha when passing the parameters where you need to have attributes and a simpletype value:

To get the xml

<foo bar="moo">cheese</foo>

You'd pass in:

<?php
array("foo" => array("_" => "cheese", "bar"=>"moo"));
?>

See that "_" bit? It really wasn't obvious from the documentation.
deWarlock 02-Apr-2009 04:10
The most annoying thing is that you'll get no warning trying to pass object not matching wsdl e.g. if server expects smth like $Object->expName->... and you would pass $Object->otherName the client will send empty request without notifying you.
Also pay attention that names are key sensitive.

In my case I spent hours trying to pass $Post->Lead->... object instead of $Post->lead-> ...
Shto 03-Mar-2009 03:17
One thing to note.

This happened to me and it took a while until I discovered what the problem was.

I was trying to get .NET objects from a provided web service, however it always seemed to return empty objects. It did return the backbone, but nothing within the objects that made up the structure.

Anyhow, it seems that you have to be very precise with the arrays when calling these functions. Par example, do this:

<?php
$obj = $client->__soapCall($SOAPCall, array('parameters'=>$SoapCallParameters));
?>

meaning that you must put an array as the second argument with 'parameters' as the key and the soap call parameters as the value.

Also make sure that the parameter variable, in my case $SoapCallParameters is in the form of what is requested by the webservice.

So, don't just make an array of the form:
<?php

(
   [0] => 'Mary',
   [1] => 1983
)

?>

but if the webservice requests a 'muid' variable as 'Mary' and a 'birthyear' as 1983, then make your array like this:

<?php

(
   [muid] => 'Mary',
   [birthyear] => 1983
)

?>

The above arrays refer to the $SoapCallParameters variable.

Hope this helps somebody, not having to spend too much time figuring out the problems.
Alejandro Cavallo 19-Mar-2008 07:38
I get the same problem reported above by ryan:
"ryan at grunt dot tv
22-Sep-2005 01:38
If you want to pass an xml document node as a function parameter, your need to create a SoapVar object with a text represention of the xml node and the XSD_ANYXML encoding constant. However, this constant is not exported by the extension and is not documented for some unknown reason."

When defined variable soapVar I assigned the type XSD_STRING rather than as XSD_ANYXML.
And when calls to the function you must pass the soapVar in an associative array.

For example if the function (called myFunc) expect a parameter called xmlInput you should do something like this:
$soapvar = new SoapVar($query, XSD_STRING);
$result = $client->myFunc(array('xmlInput'=>$soapvar));

This XML fragment are wrapped around xmlImput tags.-
stefan at datax dot biz 24-Oct-2007 07:28
The call to __soapCall returned an object to me either. This is the function which makes my life easier:

function obj2array($obj) {
  $out = array();
  foreach ($obj as $key => $val) {
    switch(true) {
        case is_object($val):
         $out[$key] = obj2array($val);
         break;
      case is_array($val):
         $out[$key] = obj2array($val);
         break;
      default:
        $out[$key] = $val;
    }
  }
  return $out;
}

Usage:
...
$response = $client ->__soapCall("track", array('parameters' => $request));
$response = obj2array($response);

Hope it helps.
temp at mailinator dot com 30-Jan-2007 04:43
The options in the third argument is documented in http://php.net/manual/en/function.soap-soapclient-construct.php
paulsjv at gmail dot com 11-Jan-2006 07:44
I was working with SOAP for the first time and I had to create a client that sent a date range to a WSDL (Web Services Description Language) to return some information I needed.  I didn't know how to pass the params and there really was no documentation about it.  The main thing you have to make sure to do is when you pass params to a method that is definied by the WSDL that you are calling is that you use the same param name for the key of the array or the object variable as shown below.  Also, if you don't know what the methods/functions that a WSDL has or the params that you need to pass it you can use the __getFunctions() and __getTypes() methods after you declare your new SoapClient.

<?php
// From and to are the two params that the execute function needs
// when called from the WSDL so make you to have them as the
// key to an array like below
$params["From"] = "06/01/2005"; // also can use $params->From = "date";
$params["to"] = "12/31/2005"; // also can use $params->to = "date";

$client = new SoapClient("some.wsdl");

try {
        print($client->execute($params));
} catch (SoapFault $exception) {
        echo $exception;
}
?>
ryan at grunt dot tv 21-Sep-2005 09:38
If you want to pass an xml document node as a function parameter, your need to create a SoapVar object with a text represention of the xml node and the XSD_ANYXML encoding constant. However, this constant is not exported by the extension and is not documented for some unknown reason.

Therefore, to get this to work you must either register the XSD_ANYXML #define as a PHP constant, or use the integer value of the constant when creating the SoapVar, which is 147.

$soapvar = new SoapVar($xml_text, 147);

$params = array("ItemXml" => $soapvar, "PropertyView" => "blah");
$result = $this->soapclient->__soapCall("SaveItem", array("parameters"=>$params), null, $this->soapheaders);

However, this still doesnt give the correct result. For some reason, the ItemXml parameter node is not wrapped around the associated xml parameter in the soap request, and the following soap is produced (assumming '<item>blah</item>' is used as the $xml_text):

<SOAP-ENV:Envelope xmlns:SOAP-ENV="..." xmlns:ns1="...">
<SOAP-ENV:Header>...</SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns1:SaveItem>
<item>blah</item>
<ns1:PropertyView>blah</ns1:PropertyView>
</ns1:SaveItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
DesmondJ 04-May-2005 03:36
Following OrionI's example:

<?php
 $client = new SoapClient("http://server/sumservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Sum($params);
 $simpleresult = $objectresult->SumResult;
 print($simpleresult); //produces "-1"
?>

Please note that the lines:

"$client->Sum($params);"

and

"$simpleresult = $objectresult->SumResult;"

are based off of each other. If your web service function is called "Sum", then add "Result" to the end of it to get the results of the call.

EG:

<?php
 $client = new SoapClient("http://server/mathservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Minus($params); // note the name of the function is "Minus"
 $simpleresult = $objectresult->MinusResult; // note the name of the result is referenced as "MinusResult"
 print($simpleresult); //produces "5"
?>
OrionI 18-Apr-2005 07:27
Correction on the previously submitted code snippet...the incoming parameter for .NET also has to be in object or array form for it to be correctly converted to the XML form that .NET expects (as already mentioned by Llu?s P?mies). The full example (when using WSDL) should be like this:
<?php
 $client = new SoapClient("http://server/myservice.asmx?WSDL");
 $params->param1 = $value1;
 $params->param2 = $value2;
 $objectresult = $client->MyMethod($params);
 $simpleresult = $objectresult->MyMethodResult;
?>
So if you have a C# function like this:
//sumservice.asmx
...
[WebMethod]
public int Sum(int a, int b)
{
  return a + b;
}
...
The PHP client would be this:
<?php
 $client = new SoapClient("http://server/sumservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Sum($params);
 $simpleresult = $objectresult->SumResult;
 print($simpleresult); //produces "5"
?>
OrionI 15-Apr-2005 11:46
When calling over SOAP to a .NET application, you may end up with an object as a result instead of a simple type, even if you're just grabbing a simple type (like a boolean result). Use a property accessor to get the actual result, like this:
<?php
 $client = new SoapClient("http://server/myservice.asmx?WSDL");
 $objectresult = $client->MyMethod($param1, $param2);
 $simpleresult = $objectresult->MyMethodResult;
?>
Note that .NET seems to name the result MethodNameResult for method MethodName.
17-Feb-2005 03:19
If your service is a .NET doc/lit, which means the input message has a single part named 'parameters' that is a structure that wraps the parameters.  Your call should look like this:

<?php

$params = array('param_name_1'=>$val_1,'param_name_2'=>$val_2);
$client->call('MethodName', array('parameters' => $params));

?>


La clase SoapServer

(PHP 5, PHP 7, PHP 8)

Introducción

La clase SoapServer proporciona un servidor para los protocolos » SOAP 1.1 y » SOAP 1.2. Se puede usar con o sin servicio de descripción WSDL.

Sinopsis de la Clase

SoapServer {
/* Métodos */
public addFunction ( mixed $functions ) : void
public addSoapHeader ( SoapHeader $object ) : void
public __construct ( mixed $wsdl , array $options = ? )
public fault ( string $code , string $string , string $actor = ? , string $details = ? , string $name = ? ) : void
public getFunctions ( ) : array
public handle ( string $soap_request = ? ) : void
public setClass ( string $class_name , mixed $... = ? ) : void
public setObject ( object $object ) : void
public setPersistence ( int $mode ) : void
}

Tabla de contenidos

  • SoapServer::addFunction — Añade una o más funciones al controlador de peticiones SOAP
  • SoapServer::addSoapHeader — Añade un encabezado SOAP a la respuesta
  • SoapServer::__construct — Constructor de SoapServer
  • SoapServer::fault — SoapServer indica que ocurrió un fallo
  • SoapServer::getFunctions — Devuelve una lista de las funciones definidas
  • SoapServer::handle — Controla la petición SOAP
  • SoapServer::setClass — Define la clase que controla las peticiones SOAP
  • SoapServer::setObject — Define el objecto que será usado para controlar las peticiones SOAP
  • SoapServer::setPersistence — Establece el modo de persistencia 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.


Añade una o más funciones al controlador de peticiones SOAP

  • « SoapServer
  • SoapServer::addSoapHeader »
  • PHP Manual
  • SoapServer
  • Añade una o más funciones al controlador de peticiones SOAP

SoapServer::addFunction

(PHP 5, PHP 7, PHP 8)

SoapServer::addFunction — Añade una o más funciones al controlador de peticiones SOAP

Descripción

public SoapServer::addFunction ( mixed $functions ) : void

Exporta una o más funciones para clientes remotos

Parámetros

functions

Para exportar una función, pasa el nombre de la función en su parámetro como cadena.

Para exportar varias funciones, pasa un array con el nombre de las funciones.

Para exportar todas las funciones, pasa la constante especial SOAP_FUNCTIONS_ALL.

Nota:

Las functions deben recibir todos los argumentos de entrada en el mismo orden que fueron definidos en el fichero WSDL (no deberían recibir ningún parámetro de salida como argumento) y devolver uno o más valores. Para devolver varios valores deben devolver un array con los nombrados parámetros de salida.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplos de 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);

?>

Ver también

  • SoapServer::SoapServer()
  • SoapServer::setClass() - Define la clase que controla las peticiones 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.


Añade un encabezado SOAP a la respuesta

  • « SoapServer::addFunction
  • SoapServer::__construct »
  • PHP Manual
  • SoapServer
  • Añade un encabezado SOAP a la respuesta

SoapServer::addSoapHeader

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

SoapServer::addSoapHeader — Añade un encabezado SOAP a la respuesta

Descripción

public SoapServer::addSoapHeader ( SoapHeader $object ) : void

Añade un encabezado SOAP a ser devuelto en la respuesta de la petición actual.

Parámetros

object

El encabezado a ser devuelto.

Valores devueltos

No devuelve ningún valor.

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.


Constructor de SoapServer

  • « SoapServer::addSoapHeader
  • SoapServer::fault »
  • PHP Manual
  • SoapServer
  • Constructor de SoapServer

SoapServer::__construct

(PHP 5, PHP 7, PHP 8)

SoapServer::__construct — Constructor de SoapServer

Descripción

public SoapServer::__construct ( mixed $wsdl , array $options = ? )

Esta función es un alias de: SoapServer::SoapServer()

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


SoapServer indica que ocurrió un fallo

  • « SoapServer::__construct
  • SoapServer::getFunctions »
  • PHP Manual
  • SoapServer
  • SoapServer indica que ocurrió un fallo

SoapServer::fault

(PHP 5, PHP 7, PHP 8)

SoapServer::fault — SoapServer indica que ocurrió un fallo

Descripción

public SoapServer::fault ( string $code , string $string , string $actor = ? , string $details = ? , string $name = ? ) : void

Envía una respuesta al cliente de la petición actual indicando que ocurrió un error.

Nota:

Solo puede ser llamado cuando se está procesando la petición.

Parámetros

code

El código de error a devolver

string

Una breve descripción del fallo

actor

Una cadena identificando el actor qeu causó el fallo.

details

Más información acerca del fallo

name

Nombre del fallo. Puede ser usado para selecionar un nombre desde el fichero WSDL.

Valores devueltos

No devuelve ningún valor.

Ver también

  • SoapFault::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


Devuelve una lista de las funciones definidas

  • « SoapServer::fault
  • SoapServer::handle »
  • PHP Manual
  • SoapServer
  • Devuelve una lista de las funciones definidas

SoapServer::getFunctions

(PHP 5, PHP 7, PHP 8)

SoapServer::getFunctions — Devuelve una lista de las funciones definidas

Descripción

public SoapServer::getFunctions ( ) : array

Devuelve una lista de las funciones definidas en el objecto SoapServer. Este método devuelve la lista de todas las funciones añadidas por SoapServer::addFunction() o SoapServer::setClass().

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Un array de las funciones definidas.

Ejemplos

Ejemplo #1 Ejemplo de 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 "Este servidor SOAP puede manejar las siguientes funciones: ";
  $functions = $server->getFunctions();
  foreach($functions as $func) {
    echo $func . "\n";
  }
}
?>

Ver también

  • SoapServer::SoapServer()
  • SoapServer::addFunction() - Añade una o más funciones al controlador de peticiones SOAP
  • SoapServer::setClass() - Define la clase que controla las peticiones SOAP

User Contributed Notes

There are no user contributed notes for this page.


Controla la petición SOAP

  • « SoapServer::getFunctions
  • SoapServer::setClass »
  • PHP Manual
  • SoapServer
  • Controla la petición SOAP

SoapServer::handle

(PHP 5, PHP 7, PHP 8)

SoapServer::handle — Controla la petición SOAP

Descripción

public SoapServer::handle ( string $soap_request = ? ) : void

Procesa una petición SOAP, llama a las funciones necesarias y envía una respuesta.

Parámetros

soap_request

La petición SOAP. Si se omite este argumento, se asume que la petición está en los datos POST de la petición HTTP.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo de SoapServer::handle()

<?php
function test($x)
{
    return $x;
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

Ver también

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


Define la clase que controla las peticiones SOAP

  • « SoapServer::handle
  • SoapServer::setObject »
  • PHP Manual
  • SoapServer
  • Define la clase que controla las peticiones SOAP

SoapServer::setClass

(PHP 5, PHP 7, PHP 8)

SoapServer::setClass — Define la clase que controla las peticiones SOAP

Descripción

public SoapServer::setClass ( string $class_name , mixed $... = ? ) : void

Exporta todos los métodos de una clase específica.

El objecto puede ser persistente durante un determinado período de sesiones PHP con el método SoapServer::setPersistence().

Parámetros

class_name

Nombre de la clase exportada.

...

Estos parámetros opcionales serán pasados al constructor de la clase por defecto durante la creación del objeto.

Valores devueltos

No devuelve ningún valor.

Ver también

  • SoapServer::SoapServer()
  • SoapServer::addFunction() - Añade una o más funciones al controlador de peticiones SOAP
  • SoapServer::setPersistence() - Establece el modo de persistencia 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();
?>


Define el objecto que será usado para controlar las peticiones SOAP

  • « SoapServer::setClass
  • SoapServer::setPersistence »
  • PHP Manual
  • SoapServer
  • Define el objecto que será usado para controlar las peticiones SOAP

SoapServer::setObject

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

SoapServer::setObject — Define el objecto que será usado para controlar las peticiones SOAP

Descripción

public SoapServer::setObject ( object $object ) : void

Define un objecto específico como controlador para las peticiones SOAP, en lugar de solo una clase como en SoapServer::setClass().

Parámetros

object

El objecto a controlar las peticiones.

Valores devueltos

No devuelve ningún valor.

Ver también

  • SoapServer::setClass() - Define la clase que controla las peticiones SOAP

User Contributed Notes

There are no user contributed notes for this page.


Establece el modo de persistencia de SoapServer

  • « SoapServer::setObject
  • SoapFault »
  • PHP Manual
  • SoapServer
  • Establece el modo de persistencia de SoapServer

SoapServer::setPersistence

(PHP 5, PHP 7, PHP 8)

SoapServer::setPersistence — Establece el modo de persistencia de SoapServer

Descripción

public SoapServer::setPersistence ( int $mode ) : void

Esta función permite cambiar el estado de persistencia de un objeto SoapServer entre peticiones. Esta función permite guardar datos entre peticiones usando sesiones de PHP. Este método solamente tiene efecto en un SoapServer después de exportar funciones utilizando SoapServer::setClass().

Nota:

La persistencia de SOAP_PERSISTENCE_SESSION solamente hace persistentes a los objetos de la clase dad, no los datos estáticos de la clase. En este caso, use $this->bar en lugar de self::$bar.

Nota:

SOAP_PERSISTENCE_SESSION serializa datos en el objeto de clase entre peticiones. Para poder adecuadamente utilizar recursos (p.ej. PDO), deberían usarse los métodos mágicos __wakeup() y __sleep().

Parámetros

mode

Una de las constantes SOAP_PERSISTENCE_XXX.

SOAP_PERSISTENCE_REQUEST - Los datos de SoapServer no persisten entre peticiones. Este es el comportamiento predeterminado de cualquier objeto SoapServer después de llamar a setClass.

SOAP_PERSISTENCE_SESSION - Los datos de SoapServer persisten entre peticiones. Esto se lleva a cabo serializando los datos de la clase SoapServer en $_SESSION['_nombre_sesión_falso'], ya que session_start() debe invocarse antes de establecer este modo de persistencia.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo de SoapServer::setPersistence()

<?php
 class MyFirstPersistentSoapServer {
     private $resource; // (Tal como PDO, mysqli, etc..)
     public $mivar1;
     public $mivar2;

     public function __construct() {
         $this->__wakeup(); // Estamos llamando nuestro wakeup para manejar nuestro recurso
     }

     public function __wakeup() {
         $this->resource = CodeToStartOurResourceUp();
     }

     public function __sleep() {
         // Nos aseguramos de omitir $resource aquí, por lo que nuestro datos de sesión persisten
         // Un fallo resultará en el fallo durante la deserialilzación de datos
         // en la próxima petición; por lo tanto, nuestro SoapObject no sería persistente entre peticiones.
         return array('mivar1','mivar2');
     }
 }

 try {
     session_start();
     $server = new SoapServer(null, array('uri' => $_SERVER['REQUEST_URI']));
     $server->setClass('MyFirstPersistentSoapServer');
     // setPersistence DEBE invocarse después de setClass, debido a que el comportamiento
     // de setClass establece SESSION_PERSISTENCE_REQUEST tras promulgar el método.
     $server->setPersistence(SOAP_PERSISTENCE_SESSION);
     $server->handle();
 } catch(SoapFault $e) {
     error_log("SOAP ERROR: ". $e->getMessage());
 }
?>

Ver también

  • SoapServer::setClass() - Define la clase que controla las peticiones 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 clase SoapFault

(PHP 5, PHP 7, PHP 8)

Introducción

Representa SOAP fault.

Sinopsis de la Clase

SoapFault extends Exception {
/* Propiedades heredadas */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Métodos */
__construct ( string $faultcode , string $faultstring , string $faultactor = ? , string $detail = ? , string $faultname = ? , string $headerfault = ? )
public __toString ( ) : string
/* Métodos heredados */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

Tabla de contenidos

  • SoapFault::__construct — Constructor de SoapFault
  • SoapFault::__toString — Obtiene una representación en formato cadena de 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


Constructor de SoapFault

  • « SoapFault
  • SoapFault::__toString »
  • PHP Manual
  • SoapFault
  • Constructor de SoapFault

SoapFault::__construct

(PHP 5, PHP 7, PHP 8)

SoapFault::__construct — Constructor de SoapFault

Descripción

SoapFault::__construct ( string $faultcode , string $faultstring , string $faultactor = ? , string $detail = ? , string $faultname = ? , string $headerfault = ? )

Esta función es un alias de: SoapFault::SoapFault()

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


Obtiene una representación en formato cadena de SoapFault

  • « SoapFault::__construct
  • SoapHeader »
  • PHP Manual
  • SoapFault
  • Obtiene una representación en formato cadena de SoapFault

SoapFault::__toString

(PHP 5, PHP 7, PHP 8)

SoapFault::__toString — Obtiene una representación en formato cadena de SoapFault

Descripción

public SoapFault::__toString ( ) : string

Devuelve una representación en formato cadena de SoapFault.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Una cadena describiendo el SoapFault.

User Contributed Notes

There are no user contributed notes for this page.


La clase SoapHeader

(PHP 5, PHP 7, PHP 8)

Introducción

Representa un SOAP header.

Sinopsis de la Clase

SoapHeader {
/* Métodos */
__construct ( string $namespace , string $name , mixed $data = ? , bool $mustunderstand = ? , string $actor = ? )
}

Tabla de contenidos

  • SoapHeader::__construct — Constructor de SoapHeader

User Contributed Notes

ericvaneldik at gmail dot com 08-Apr-2019 07:16
If you want to create an soap header wihtout namespace and without an item key value setup, you can use SoapVar

To get this:
<SOAP-ENV:Header>
    <IdentityHeader>
      <SessionID>123456789</SessionID>
    </IdentityHeader>
  </SOAP-ENV:Header>

you can use this php code:
<?php
$headerVar = new SoapVar('<IdentityHeader><SessionID>123456789</SessionID></IdentityHeader>',
      XSD_ANYXML);
$header = new SoapHeader('http://tempuri.org/','RequestParams',
      $headerVar);
?>
abdul dot rashid at paytabs dot co 13-Mar-2016 10:06
Just to add some note regarding his john at jtresponse dot co dot uk

In PHP you can try following code to avoid the <item><key/>

$Auth = new stdClass();
$Auth->SystemId = "DATA";
$Auth->UserName = "USERNAME";
$Auth->Password = "PASSWORD";

$header = new SoapHeader('NAMESPACE','Auth',$Auth,false);
$soapClient->__setSoapHeaders($header);

  <SOAP-ENV:Header>
    <ns1:Auth>
      <ns1:SystemId>DATA</ns1:SystemId>
      <ns1:UserName>USERNAME</ns1:UserName>
      <ns1:Password>PASSWORD</ns1:Password>
    </ns1:Auth>
  </SOAP-ENV:Header>
voroks at logics dot net dot au 03-Jul-2015 12:43
Example by john at jtresponse dot co dot uk does miss one important point: to be able to add attributes they must be mentioned in WSDL. If they not exist in WSDL they WILL NOT appear as attributes but rather <item><key/><value/></item> elements.
john at jtresponse dot co dot uk 13-Mar-2012 01:30
None of the examples really do it for me.
Note: you should NOT need to hard-code any XML.

Here is an example of creating a nested header and including a parameter.

$client = new SoapClient(WSDL,array());

$auth = array(
        'UserName'=>'USERNAME',
        'Password'=>'PASSWORD',
        'SystemId'=> array('_'=>'DATA','Param'=>'PARAM'),
        );
  $header = new SoapHeader('NAMESPACE','Auth',$auth,false);
  $client->__setSoapHeaders($header);

Gives the following header XML:

  <SOAP-ENV:Header>
    <ns1:Auth>
      <ns1:SystemId Param="PARAM">DATA</ns1:SystemId>
      <ns1:UserName>USERNAME</ns1:UserName>
      <ns1:Password>PASSWORD</ns1:Password>
    </ns1:Auth>
  </SOAP-ENV:Header>


Constructor de SoapHeader

  • « SoapHeader
  • SoapParam »
  • PHP Manual
  • SoapHeader
  • Constructor de SoapHeader

SoapHeader::__construct

(PHP 5, PHP 7, PHP 8)

SoapHeader::__construct — Constructor de SoapHeader

Descripción

SoapHeader::__construct ( string $namespace , string $name , mixed $data = ? , bool $mustunderstand = ? , string $actor = ? )

Esta función es un alias de: SoapHeader::SoapHeader()

User Contributed Notes

There are no user contributed notes for this page.


La clase SoapParam

(PHP 5, PHP 7, PHP 8)

Introducción

Representa el parametro para una llamada a SOAP.

Sinopsis de la Clase

SoapParam {
/* Métodos */
__construct ( mixed $data , string $name )
}

Tabla de contenidos

  • SoapParam::__construct — Constructor de SoapParam

User Contributed Notes

There are no user contributed notes for this page.


Constructor de SoapParam

  • « SoapParam
  • SoapVar »
  • PHP Manual
  • SoapParam
  • Constructor de SoapParam

SoapParam::__construct

(PHP 5, PHP 7, PHP 8)

SoapParam::__construct — Constructor de SoapParam

Descripción

SoapParam::__construct ( mixed $data , string $name )

Esta función es un alias de: SoapParam::SoapParam()

User Contributed Notes

There are no user contributed notes for this page.


La clase SoapVar

(PHP 5, PHP 7, PHP 8)

Introducción

Una clase representando una variable u objecto para usar con los servicios SOAP.

Sinopsis de la Clase

SoapVar {
/* Métodos */
__construct ( mixed $data , string $encoding , string $type_name = ? , string $type_namespace = ? , string $node_name = ? , string $node_namespace = ? )
}

Tabla de contenidos

  • SoapVar::__construct — Constructor de 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


Constructor de SoapVar

  • « SoapVar
  • Yar »
  • PHP Manual
  • SoapVar
  • Constructor de SoapVar

SoapVar::__construct

(PHP 5, PHP 7, PHP 8)

SoapVar::__construct — Constructor de SoapVar

Descripción

SoapVar::__construct ( mixed $data , string $encoding , string $type_name = ? , string $type_namespace = ? , string $node_name = ? , string $node_namespace = ? )

Esta función es un alias de: SoapVar::SoapVar()

User Contributed Notes

There are no user contributed notes for this page.


Yet Another RPC Framework

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Ejemplos
  • Yar_Server — La clase Yar_Server
    • Yar_Server::__construct — Registrar un servidor
    • Yar_Server::handle — Iniciar un servidor RPC
  • Yar_Client — La clase Yar_Client
    • Yar_Client::__call — Llamar a un servicio
    • Yar_Client::__construct — Crear un cliente
    • Yar_Client::setOpt — Establecer los contextos de una llamada
  • Yar_Concurrent_Client — La clase Yar_Concurrent_Client
    • Yar_Concurrent_Client::call — Registrar una llamada concurrente
    • Yar_Concurrent_Client::loop — Enviar todas las llamadas
    • Yar_Concurrent_Client::reset — Limpiar todas las llamadas registradas
  • Yar_Server_Exception — La clase Yar_Server_Exception
    • Yar_Server_Exception::getType — Recuperar el tipo de excepción
  • Yar_Client_Exception — La clase Yar_Client_Exception
    • Yar_Client_Exception::getType — El propósito de getType

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Yar es un «framework» de RPC que pretende simplificar y facilitar la manera en que se comunican las aplicaciones de PHP entre ellas. Tiene la capacidad de llamar concurrentemente a varios servicios remotos.

User Contributed Notes

There are no user contributed notes for this page.


Requerimientos

Para emplear msgpack como empaquetador, es necesario compilar Yar con ./configure --enable-msgpack

User Contributed Notes

There are no user contributed notes for this page.


Instalación

Esta extensión » PECL no se distribuye con PHP.

Se puede encontrar información para la instalación de esta extensión PECL en el capítulo del manual titulado Instalación de extensiones PECL. Se puede encontrar información adicional, tal como nuevos lanzamientos, descargas, ficheros fuente, información de mantenimiento, y un CHANGELOG, aquí: » https://pecl.php.net/package/yar.

Actualmente, no hay ninguna DLL disponible para esta extensión PECL. Véase también la sección Compilación en 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/


Configuración en tiempo de ejecución

El comportamiento de estas funciones se ve afectado por la configuración de php.ini.

Yar Opciones de configuración
Nombre | Por defecto | Cambiable | Historial de cambios
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 |

He aquí una breve explicación de las directivas de configuración.

yar.packager string

Podría ser php, json, y msgpack (requiere construcción con soporte para msgpack)

yar.debug string

yar.connect_timeout integer

Tiempo de espera en ms

yar.timeout integer

Tiempo de espera en ms

yar.expose_info bool

Si exponer la información del servicio (al acceder al servidor mediante GET)

User Contributed Notes

There are no user contributed notes for this page.


Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles sólo cuando la extensión haya sido compilada con PHP, o bien sea cargada dinámicamente en ejecución.

YAR_VERSION (string)
YAR_CLIENT_PROTOCOL_HTTP (integer)
YAR_OPT_PACKAGER (integer)
YAR_OPT_TIMEOUT (integer)
YAR_OPT_CONNECT_TIMEOUT (integer)
YAR_OPT_HEADER (array)
Desde 2.0.4
YAR_PACKAGER_PHP (string)
YAR_PACKAGER_JSON (string)
YAR_ERR_OKEY (integer)
YAR_ERR_OUTPUT (integer)
YAR_ERR_TRANSPORT (integer)
YAR_ERR_REQUEST (integer)
YAR_ERR_PROTOCOL (integer)
YAR_ERR_PACKAGER (integer)
YAR_ERR_EXCEPTION (integer)

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

Ejemplo #1 Ejemplo de servidor de Yar

<?php

/* Se asume que a esta página se puede acceder mediante http://example.com/operator.php */

class Operator {

    /**
     * Add two operands
     * @param interge
     * @return interge
     */
    public function add($a, $b) {
        return $this->_add($a, $b);
    }

    /**
     * Sub
     */
    public function sub($a, $b) {
        return $a - $b;
    }

    /**
     * Mul
     */
    public function mul($a, $b) {
        return $a * $b;
    }

    /**
     * Protected methods will not be exposed
     * @param interge
     * @return interge
     */
    protected function _add($a, $b) {
        return $a + $b;
    }
}

$servidor = new Yar_Server(new Operator());
$servidor->handle();
?>

Ejemplo #2 Acceder al servidor desde el navegador (petición GET)

El resultado del ejemplo sería algo similar a:

Información del servidor de Yar

Ejemplo #3 Ejemplo de cliente de Yar

<?php
$cliente = new yar_client("http://example.com/operator.php");

/* llamar directamente */
var_dump($cliente->add(1, 2));

/* llamar mediante el método 'call' */
var_dump($cliente->call("add", array(3, 2)));

/* __add no puede ser llamado */
var_dump($cliente->_add(1, 2));
?>

El resultado del ejemplo sería algo similar a:

int(3)
int(5)
PHP Fatal error:  Uncaught exception 'Yar_Server_Exception' with message 'call to api Operator::_add() failed' in *

Ejemplo #4 Ejemplo de cliente concurrente de Yar

<?php
function callback($ret, $callinfo) {
    echo $callinfo['method'] , " result: ", $ret , "\n";
}

/* registrar las llamadas asíncronas a servicios remotos */
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");

/* enviar todas las peticiones y esperar una respuesta */
Yar_Concurrent_Client::loop();
?>

El resultado del ejemplo sería algo similar a:

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 clase Yar_Server

(No hay información de versión disponible, podría estar únicamente en Git)

Introducción

Sinopsis de la Clase

Yar_Server {
/* Propiedades */
protected $_executor ;
/* Métodos */
final public __construct ( Object $obj )
public handle ( ) : bool
}

Propiedades

_executor

Tabla de contenidos

  • Yar_Server::__construct — Registrar un servidor
  • Yar_Server::handle — Iniciar un servidor RPC

User Contributed Notes

There are no user contributed notes for this page.


Registrar un servidor

  • « Yar_Server
  • Yar_Server::handle »
  • PHP Manual
  • Yar_Server
  • Registrar un servidor

Yar_Server::__construct

(PECL yar >= 1.0.0)

Yar_Server::__construct — Registrar un servidor

Descripción

final public Yar_Server::__construct ( Object $obj )

Configurar un Servidor Yar HTTP RPC. Todos los métodos públicos de $obj serán registrados como un servicio RPC.

Parámetros

obj

Un objeto, todos sus métodos publicos serán registrados como servicioes RPC.

Valores devueltos

Una instancia de Yar_Server.

Ejemplos

Ejemplo #1 Ejemplo de Yar_Server::__construct()

<?php
class API {
    /**
     * the doc info will be generated automatically into service info page.
     * @params
     * @return
     */
    public function some_method($parameter, $option = "foo") {
         return "some_method";
    }

    protected function client_can_not_see() {
    }
}

$service = new Yar_Server(new API());
$service->handle();
?>

El resultado del ejemplo sería algo similar a:

Ver también

  • Yar_Server::handle() - Iniciar un servidor RPC
    •

User Contributed Notes

There are no user contributed notes for this page.


Iniciar un servidor RPC

  • « Yar_Server::__construct
  • Yar_Client »
  • PHP Manual
  • Yar_Server
  • Iniciar un servidor RPC

Yar_Server::handle

(PECL yar >= 1.0.0)

Yar_Server::handle — Iniciar un servidor RPC

Descripción

public Yar_Server::handle ( ) : bool

Inicia un servidor de HTTP de RPC listo para aceptar peticiones RPC.

Nota:

Las llamadas RPC usuales serán emitidas como peticiones POST de HTTP. Si se emite una petición GET de HTTP al URI, se imprimierá en la página la información del servicio (la sección comentada anteriormente).

Parámetros

Esta función no tiene parámetros.

Valores devueltos

boolean

Ejemplos

Ejemplo #1 Ejemplo de Yar_Server::handle()

<?php
class API {
    /**
     * the doc info will be generated automatically into service info page.
     * @params
     * @return
     */
    public function some_method($parameter, $option = "foo") {
    }

    protected function client_can_not_see() {
    }
}

$service = new Yar_Server(new API());
$service->handle();
?>

El resultado del ejemplo sería algo similar a:

Ver también

  • Yar_Server::__construct() - Registrar un servidor
    •

User Contributed Notes

There are no user contributed notes for this page.


La clase Yar_Client

(No hay información de versión disponible, podría estar únicamente en Git)

Introducción

Sinopsis de la Clase

Yar_Client {
/* Propiedades */
protected $_protocol ;
protected $_uri ;
protected $_options ;
protected $_running ;
/* Métodos */
public __call ( string $method , array $parameters ) : void
final public __construct ( string $url , array $options = ? )
public setOpt ( int $name , mixed $value ) : Yar_Client
}

Propiedades

_protocol

_uri

_options

_running

Tabla de contenidos

  • Yar_Client::__call — Llamar a un servicio
  • Yar_Client::__construct — Crear un cliente
  • Yar_Client::setOpt — Establecer los contextos de una llamada

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


Llamar a un servicio

  • « Yar_Client
  • Yar_Client::__construct »
  • PHP Manual
  • Yar_Client
  • Llamar a un servicio

Yar_Client::__call

(PECL yar >= 1.0.0)

Yar_Client::__call — Llamar a un servicio

Descripción

public Yar_Client::__call ( string $method , array $parameters ) : void

Emite una llamada a un método RPC remoto.

Parámetros

method

Nombre del método RPC remono.

parameters

Parámetros.

Valores devueltos

Ejemplos

Ejemplo #1 Ejemplo de Yar_Client::__call()

<?php

$cliente = new Yar_Client("http://host/api/");

/* llamar al servicio remoto */
$resultado = $cliente->some_method("parameter");
?>

El resultado del ejemplo sería algo similar a:

Ver también

  • Yar_Client::setOpt() - Establecer los contextos de una llamada
    •

User Contributed Notes

There are no user contributed notes for this page.


Crear un cliente

  • « Yar_Client::__call
  • Yar_Client::setOpt »
  • PHP Manual
  • Yar_Client
  • Crear un cliente

Yar_Client::__construct

(PECL yar >= 1.0.0)

Yar_Client::__construct — Crear un cliente

Descripción

final public Yar_Client::__construct ( string $url , array $options = ? )

Crea un Yar_Client hacia un Yar_Server.

Parámetros

url

El URL del servidor de Yar.

Valores devueltos

Una instancia de Yar_Client.

Ejemplos

Ejemplo #1 Ejemplo de Yar_Client::__construct()

<?php
$cliente = new Yar_Client("http://host/api/");
?>

El resultado del ejemplo sería algo similar a:

Ver también

  • Yar_Client::__call() - Llamar a un servicio
    •

  • Yar_Client::setOpt() - Establecer los contextos de una llamada
    •

User Contributed Notes

There are no user contributed notes for this page.


Establecer los contextos de una llamada

  • « Yar_Client::__construct
  • Yar_Concurrent_Client »
  • PHP Manual
  • Yar_Client
  • Establecer los contextos de una llamada

Yar_Client::setOpt

(PECL yar >= 1.0.0)

Yar_Client::setOpt — Establecer los contextos de una llamada

Descripción

public Yar_Client::setOpt ( int $name , mixed $value ) : Yar_Client

Parámetros

name

El nombre puede ser: YAR_OPT_PACKAGER, YAR_OPT_PERSISTENT (Necesita soporte en el servidor), YAR_OPT_TIMEOUT, YAR_OPT_CONNECT_TIMEOUT YAR_OPT_HEADER (Desde 2.0.4)

value

Valores devueltos

Devuelve $this en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de Yar_Client::setOpt()

<?php

$cliente = new Yar_Client("http://host/api/");

//Establecer el tiempo de espera a 1s
$cliente->SetOpt(YAR_OPT_CONNECT_TIMEOUT, 1000);

//Establecer el empaquetador a JSON
$cliente->SetOpt(YAR_OPT_PACKAGER, "json");

//Establecer cabeceras personalizadas
$client->SetOpt(YAR_OPT_HEADER, array("hr1: val1", "hd2: val2"));

/* llamar al servicio remoto */
$result = $cliente->some_method("parameter");
?>

El resultado del ejemplo sería algo similar a:

Ver también

  • Yar_Client::__call() - Llamar a un servicio
    •

User Contributed Notes

There are no user contributed notes for this page.


La clase Yar_Concurrent_Client

(No hay información de versión disponible, podría estar únicamente en Git)

Introducción

Sinopsis de la Clase

Yar_Concurrent_Client {
/* Propiedades */
static $_callstack ;
static $_callback ;
static $_error_callback ;
/* Métodos */
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 ( ) : boolean
}

Propiedades

_callstack

_callback

_error_callback

Tabla de contenidos

  • Yar_Concurrent_Client::call — Registrar una llamada concurrente
  • Yar_Concurrent_Client::loop — Enviar todas las llamadas
  • Yar_Concurrent_Client::reset — Limpiar todas las llamadas registradas

User Contributed Notes

There are no user contributed notes for this page.


Registrar una llamada concurrente

  • « Yar_Concurrent_Client
  • Yar_Concurrent_Client::loop »
  • PHP Manual
  • Yar_Concurrent_Client
  • Registrar una llamada concurrente

Yar_Concurrent_Client::call

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::call — Registrar una llamada concurrente

Descripción

public static Yar_Concurrent_Client::call ( string $uri , string $method , array $parameters = ? , callable $callback = ? , callable $error_callback = ? , array $options = ? ) : int

Registra una llamada RPC, aunque no la envía inmediatamente. Se enviará al llamar a Yar_Concurrent_Client::loop()

Parámetros

uri

El URI del servidor de RPC (http, tcp)

method

El nombre del servicio (es decir, el nombre del método)

parameters

Parámetros

callback

Una retrollamada a una función, la cual será invocada mientras se devuelve la respuesta.

Valores devueltos

Un ID único que se puede utilizar para identificar la llamada que es.

Ejemplos

Ejemplo #1 Ejemplo de 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 no se especifica la retrollamada,
                                                                               // se usará la retrollamada en bucle
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
                                                                               //este servidor acepta empaquetadores json
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
                                                                               //tiempo de espera personalizado

//Las peticiones aún no se han enviado
?>

El resultado del ejemplo sería algo similar a:

Ver también

  • Yar_Concurrent_Client::loop() - Enviar todas las llamadas
    •

  • Yar_Concurrent_Client::reset() - Limpiar todas las llamadas registradas
    •

  • Yar_Server::__construct() - Registrar un servidor
    •

  • Yar_Server::handle() - Iniciar un servidor RPC
    •

User Contributed Notes

There are no user contributed notes for this page.


Enviar todas las llamadas

  • « Yar_Concurrent_Client::call
  • Yar_Concurrent_Client::reset »
  • PHP Manual
  • Yar_Concurrent_Client
  • Enviar todas las llamadas

Yar_Concurrent_Client::loop

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::loop — Enviar todas las llamadas

Descripción

public static Yar_Concurrent_Client::loop ( callable $callback = ? , callable $error_callback = ? ) : bool

Envía todas las llamadas RPC remotas registradas.

Parámetros

callback

Si se establece esta retrollamada, Yar la invocará después de haber enviado todas las llamadas y antes de cualquier respuesta, con un $callinfo NULL.

Entonces, si un usuario no especifica la retrollamada al registrar una llamada concurretne, esta retrollamada se utilizará para manejar la resupesta, o si no, se utilizará la retrollamada especificada durante el registro.

error_callback

Si se establece esta retrollamada, Yar la invocará cuando suceda un error.

Valores devueltos

Ejemplos

Ejemplo #1 Ejemplo de Yar_Concurrent_Client::loop()

<?php
function callback($retval, $callinfo) {
     if ($callinfo == NULL) {
        echo "Now, all requests are sent, and no any response available\n";
     } else {
        echo "This is a remote call response, the method name is", $callinfo["method"],
             ". calling sequence is " , $callinfo["sequence"] , "\n";
        var_dump($retval);
     }
}

function error_callback($type, $error, $callinfo) {
    error_log($error);
}

Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"));   // if the callback is not specificed,
                                                                               // callback in loop will be used
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
                                                                               //this server accept json packager
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
                                                                               //custom timeout

Yar_Concurrent_Client::loop("callback", "error_callback"); //send the requests,
                                                           //the error_callback is optional
?>

El resultado del ejemplo sería algo similar a:

Now, all requests are sent, and no any response available
This is a remote call response, the method name issome_method. calling sequence is 4
string(11) "some_method"
This is a remote call response, the method name issome_method. calling sequence is 1
string(11) "some_method"
This is a remote call response, the method name issome_method. calling sequence is 2
string(11) "some_method"
This is a remote call response, the method name issome_method. calling sequence is 3
string(11) "some_method"

Ver también

  • Yar_Concurrent_Client::call() - Registrar una llamada concurrente
  • Yar_Concurrent_Client::reset() - Limpiar todas las llamadas registradas
  • Yar_Server::__construct() - Registrar un servidor
  • Yar_Server::handle() - Iniciar un servidor RPC

User Contributed Notes

There are no user contributed notes for this page.


Limpiar todas las llamadas registradas

  • « Yar_Concurrent_Client::loop
  • Yar_Server_Exception »
  • PHP Manual
  • Yar_Concurrent_Client
  • Limpiar todas las llamadas registradas

Yar_Concurrent_Client::reset

(PECL yar >= 1.2.4)

Yar_Concurrent_Client::reset — Limpiar todas las llamadas registradas

Descripción

public static Yar_Concurrent_Client::reset ( ) : boolean

Limpia todas las llamadas registradas

Parámetros

Valores devueltos

Ejemplos

Ejemplo #1 Ejemplo de Yar_Concurrent_Client::reset()

El resultado del ejemplo sería algo similar a:

Ver también

  • Yar_Concurrent_Client::call() - Registrar una llamada concurrente
    •

  • Yar_Concurrent_Client::loop() - Enviar todas las llamadas
    •

  • Yar_Server::__construct() - Registrar un servidor
    •

  • Yar_Server::handle() - Iniciar un servidor RPC
    •

User Contributed Notes

There are no user contributed notes for this page.


La clase Yar_Server_Exception

(No hay información de versión disponible, podría estar únicamente en Git)

Introducción

Si un servicio lanza excepciones, se lanzará una Yar_Server_Exception en el lado del cliente.

Sinopsis de la Clase

Yar_Server_Exception extends Exception {
/* Propiedades */
protected $_type ;
/* Métodos */
public getType ( ) : string
/* Métodos heredados */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

Propiedades

message

code

file

line

_type

Tabla de contenidos

  • Yar_Server_Exception::getType — Recuperar el tipo de excepción

User Contributed Notes

There are no user contributed notes for this page.


Recuperar el tipo de excepción

  • « Yar_Server_Exception
  • Yar_Client_Exception »
  • PHP Manual
  • Yar_Server_Exception
  • Recuperar el tipo de excepción

Yar_Server_Exception::getType

(PECL yar >= 1.0.0)

Yar_Server_Exception::getType — Recuperar el tipo de excepción

Descripción

public Yar_Server_Exception::getType ( ) : string

Obtener el tipo original de la excepción lanzada por el servidor

Parámetros

Esta función no tiene parámetros.

Valores devueltos

string

Ejemplos

Ejemplo #1 Ejemplo de 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());
}

El resultado del ejemplo sería algo similar a:

string(16) "Custom_Exception"
string(6) "client"

Ver también

User Contributed Notes

There are no user contributed notes for this page.


La clase Yar_Client_Exception

(No hay información de versión disponible, podría estar únicamente en Git)

Introducción

Sinopsis de la Clase

Yar_Client_Exception extends Exception {
/* Propiedades */
/* Métodos */
public getType ( ) : void
/* Métodos heredados */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

Propiedades

message

code

file

line

Tabla de contenidos

  • Yar_Client_Exception::getType — El propósito de getType

User Contributed Notes

There are no user contributed notes for this page.


El propósito de getType

  • « Yar_Client_Exception
  • XML-RPC »
  • PHP Manual
  • Yar_Client_Exception
  • El propósito de getType

Yar_Client_Exception::getType

(PECL yar >= 1.0.0)

Yar_Client_Exception::getType — El propósito de getType

Descripción

public Yar_Client_Exception::getType ( ) : void

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Ejemplos

Ejemplo #1 Ejemplo de Yar_Client_Exception::getType()

<?php

/* ... */

?>

El resultado del ejemplo sería algo similar a:

...

Ver también

User Contributed Notes

There are no user contributed notes for this page.


XML-RPC

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Funciones de XML-RPC
    • xmlrpc_decode_request — Decodifica el XML en los tipos de PHP nativos
    • xmlrpc_decode — Decodifica el XML en los tipos de PHP nativos
    • xmlrpc_encode_request — Genera XML para el requerimiento de un método
    • xmlrpc_encode — Genera XML para un valor PHP
    • xmlrpc_get_type — Obtiene el tipo del xmlrpc para un valor PHP
    • xmlrpc_is_fault — Determina si el valor de un arreglo representa una falla del XMLRPC
    • xmlrpc_parse_method_descriptions — Decodifica el XML en una lista de las descripciones del método
    • xmlrpc_server_add_introspection_data — Agrega una documentación introspectiva
    • xmlrpc_server_call_method — Analiza los requerimientos del XML y las llamadas de los métodos
    • xmlrpc_server_create — Crea un servidor xmlrpc
    • xmlrpc_server_destroy — Destruye los recursos del servidor
    • xmlrpc_server_register_introspection_callback — Registra una función PHP para generar la documentación
    • xmlrpc_server_register_method — Registra una función PHP para que el recurso del método coincida con method_name
    • xmlrpc_set_type — Establece el tipo del xmlrpc, base64 o fecha-hora, para un valor de cadena PHP

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Estas funciones se pueden usar para escribir servidores y clientes XML-RPC. Se puede encontrar más información acerca de XML-RPC en » http://www.xmlrpc.com/, y más documentación sobre esta extensión y sus funciones en » http://xmlrpc-epi.sourceforge.net/.

Advertencia

Esta extensión es EXPERIMENTAL. Esto significa que el comportamiento de esta extensión, los nombres de sus funciones y todo lo documentado sobre esta extensión, puede cambiar en una futura edición de PHP sin previo aviso. El uso de esta extensión queda bajo su propia responsabilidad.

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


Instalación

El XML-RPC soportado en PHP no está activado por defecto. Se necesita usar la opción configuración de --with-xmlrpc[=DIR] cuando es compilado el PHP para activar el soporte a XML-RPC support.

User Contributed Notes

pitje 31-Jan-2021 07:40
according to php(dot)watch/versions/8.0/xmlrpc ,
PHP 8.0: XMLRPC extension is moved to PECL

checked, xmlrpc-1.0.0RC2 works for me
giunta dot gaetano at gmail dot com 29-Dec-2020 01:18
Here's what I had to do in order to install the xmlrpc extension on php 8 (from sury repos) on Ubuntu 16, as there is no package available via pecl or apt:

# build
git clone https://git.php.net/repository/pecl/networking/xmlrpc.git
export CPPFLAGS=-I/usr/include/libxml2/
cd xmlrpc && phpize && ./configure --with-expat && make && make install

# enable - this varies depending on your configuration; apache/nginx/fpm will also need to be restarted
echo "extension=xmlrpc.so" > /etc/php/8.0/mods-available/xmlrpc.ini
ln -s /etc/php/8.0/mods-available/xmlrpc.ini /etc/php/8.0/cli/conf.d/20-xmlrpc.ini
ln -s /etc/php/8.0/mods-available/xmlrpc.ini /etc/php/8.0/fpm/conf.d/20-xmlrpc.ini
Anonymous 15-Dec-2020 02:11
for centos try:
yum install php-xmlrpc
cnunez at cyberargsistemas dot com dot ar 17-Oct-2019 08:07
sudo apt-get install php7.2-xmlrpc


Tipos de recursos

Ésta extensión define un recurso de servicio de XML-RPC devuelto por xmlrpc_server_create().

User Contributed Notes

There are no user contributed notes for this page.


Funciones de XML-RPC

Tabla de contenidos

  • xmlrpc_decode_request — Decodifica el XML en los tipos de PHP nativos
  • xmlrpc_decode — Decodifica el XML en los tipos de PHP nativos
  • xmlrpc_encode_request — Genera XML para el requerimiento de un método
  • xmlrpc_encode — Genera XML para un valor PHP
  • xmlrpc_get_type — Obtiene el tipo del xmlrpc para un valor PHP
  • xmlrpc_is_fault — Determina si el valor de un arreglo representa una falla del XMLRPC
  • xmlrpc_parse_method_descriptions — Decodifica el XML en una lista de las descripciones del método
  • xmlrpc_server_add_introspection_data — Agrega una documentación introspectiva
  • xmlrpc_server_call_method — Analiza los requerimientos del XML y las llamadas de los métodos
  • xmlrpc_server_create — Crea un servidor xmlrpc
  • xmlrpc_server_destroy — Destruye los recursos del servidor
  • xmlrpc_server_register_introspection_callback — Registra una función PHP para generar la documentación
  • xmlrpc_server_register_method — Registra una función PHP para que el recurso del método coincida con method_name
  • xmlrpc_set_type — Establece el tipo del xmlrpc, base64 o fecha-hora, para un valor de cadena 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


Decodifica el XML en los tipos de PHP nativos

  • « Funciones de XML-RPC
  • xmlrpc_decode »
  • PHP Manual
  • Funciones de XML-RPC
  • Decodifica el XML en los tipos de PHP nativos

xmlrpc_decode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode_request — Decodifica el XML en los tipos de PHP nativos

Descripción

xmlrpc_decode_request ( string $xml , string &$method , string $encoding = ? ) : mixed
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

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.


Decodifica el XML en los tipos de PHP nativos

  • « xmlrpc_decode_request
  • xmlrpc_encode_request »
  • PHP Manual
  • Funciones de XML-RPC
  • Decodifica el XML en los tipos de PHP nativos

xmlrpc_decode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode — Decodifica el XML en los tipos de PHP nativos

Descripción

xmlrpc_decode ( string $xml , string $encoding = "iso-8859-1" ) : mixed
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Parámetros

xml

La respuesta XML devuelta por el método XMLRPC.

encoding

Entrada de codificación que admite iconv.

Valores devueltos

Devuelve o un arreglo, o un entero, o una cadena, o un booleano conforme a la respuesta devuelta por el método XMLRPC.

Ejemplos

Ver el ejemplo de xmlrpc_encode_request().

Ver también

  • xmlrpc_encode_request() - Genera XML para el requerimiento de un método
  • xmlrpc_is_fault() - Determina si el valor de un arreglo representa una falla del 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);
?>


Genera XML para el requerimiento de un método

  • « xmlrpc_decode
  • xmlrpc_encode »
  • PHP Manual
  • Funciones de XML-RPC
  • Genera XML para el requerimiento de un método

xmlrpc_encode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode_request — Genera XML para el requerimiento de un método

Descripción

xmlrpc_encode_request ( string $method , mixed $params , array $output_options = ? ) : string
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Parámetros

method

El nombre del método a llamar.

params

Los parámetros de los métodos compatibles con la firma del método.

output_options

Las opciones de salida de un arreglo especifico pueden contener (por defecto valores que son enfatizados):

  • output_type: php, xml

  • verbosity: no_white_space, newlines_only, pretty

  • escaping: cdata, non-ascii, non-print, markup (may be a string with one value or an array with multiple values)

  • version: simple, xmlrpc, soap 1.1, auto

  • encoding: iso-8859-1, other character set supported by iconv

Valores devueltos

Devuelve una cadena conteniendo la representación del XML del requerimiento.

Ejemplos

Ejemplo #1 Ejmeplo de las funciones de clietes de 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);
}
?>

Ver también

  • stream_context_create() - Crear un contexto de flujo
  • file_get_contents() - Transmite un fichero completo a una cadena
  • xmlrpc_decode() - Decodifica el XML en los tipos de PHP nativos

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.


Genera XML para un valor PHP

  • « xmlrpc_encode_request
  • xmlrpc_get_type »
  • PHP Manual
  • Funciones de XML-RPC
  • Genera XML para un valor PHP

xmlrpc_encode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode — Genera XML para un valor PHP

Descripción

xmlrpc_encode ( mixed $value ) : string
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

User Contributed Notes

remi 13-May-2009 01:56
This xmlrpc_encode function doesn't generate the "methodResponse" tag required by some clients.

Using xmlrpc_encode_request seems better:

<?php
$xmlresponse = xmlrpc_encode_request(NULL, $phpresponse);

xmlrpc_encode(1) generate
<?xml version="1.0" encoding="utf-8"?>
<params>
<param>
 <value>
  <int>1</int>
 </value>
</param>
</params>

xmlrpc_encode_request(NULL,1) generate
<?xml version="1.0" encoding="iso-8859-1"?>
<methodResponse>
<params>
 <param>
  <value>
   <int>1</int>
  </value>
 </param>
</params>
</methodResponse>
?>
dave dot wilcock at gmail dot com 21-Sep-2007 07:05
Worth noting, you can use this function to generate fault response xml.

If you pass a pre-determined array into this function, as follows

<?
$myArray = array ("faultCode"=>1,"faultString"=>"Too many params");
$xml = xmlrpc_encode($myArray);
?>

... you will get output much like the following:

<?xml version="1.0" encoding="utf-8"?>
<fault>
<value>
 <struct>
  <member>
   <name>faultCode</name>
   <value>
    <int>4</int>
   </value>
  </member>
  <member>
   <name>faultString</name>
   <value>
    <string>Too many params</string>
   </value>
  </member>
 </struct>
</value>
</fault>

All that is needed to do here to make it valid XML-RPC is inject some of your own methodResponse tags.

Check the XML-RPC specification at http://www.xmlrpc.com/spec
08-Jun-2006 07:32
Another quirk (more of a bug i think) is the automatic encoding of hashes where all keys that begin with a digit between 1 and 9 are lost:
http://bugs.php.net/bug.php?id=37746

Luckily I found a quick workaround. Just append chr(0x00) to your keys and the xmlrpc response will be correct. Maybe this will apply to encoding of hashes for requests too.
Amir.LaherATcomplinetDOTcom 26-Aug-2005 01:54
Beware this quirk: when you xmlrpc_encode a hash into xmlrpc, numeric keys will not be kept. Even strings containing numbers-only will be lost.

i.e.: xmlrpc_decode(xmlrpc_encode(array('123'=>456)));
returns: array(0=>456);

Apparently this is intentional functionality (see http://bugs.php.net/bug.php?id=21949)

2 workarounds:
1. prepend/append a string (even whitespace) to all keys, and strip them out at the other end. eg array('key_123'=>456);
2. create an array of hashes. array(array('key'=>123,'value'=>456));

I favour the second option because it's more deliberate.

... this also applies to xmlrpc_encode_request()
hfuecks at pinkgoblin dot com 15-Aug-2002 08:16
This function would be used by an XML-RPC server to convert PHP variables into an XML-RPC response.

It would be used within the PHP functions defined using xmlrpc_server_register_method()

Uses PHP variable reflection to assign the correct data types for the XML-RPC response. For example;

<?php
$params = array ( "one"=>"red","two"=>"blue","three"=>"green" );

$response = xmlrpc_encode ( $params );

echo ( $response );
?>

Produces;

<?xml version='1.0' encoding="utf-8" ?>
<params>
<param>
 <value>
  <struct>
   <member>
    <name>one</name>
    <value>
     <string>red</string>
    </value>
   </member>
   <member>
    <name>two</name>
    <value>
     <string>blue</string>
    </value>
   </member>
   <member>
    <name>three</name>
    <value>
     <string>green</string>
    </value>
   </member>
  </struct>
 </value>
</param>
</params>

While
<?php
$params = array ( "red", "blue", "green" );

$response = xmlrpc_encode ( $params );

echo ( $response );
?>

produces;

<?xml version='1.0' encoding="utf-8" ?>
<params>
<param>
 <value>
  <array>
   <data>
    <value>
     <string>red</string>
    </value>
    <value>
     <string>blue</string>
    </value>
    <value>
     <string>green</string>
    </value>
   </data>
  </array>
 </value>
</param>
</params>

And

<?php
$params = 1;

$response = xmlrpc_encode ( $params );

echo ( $response );
?>

produces

<?xml version='1.0' encoding="utf-8" ?>
<params>
<param>
 <value>
  <int>1</int>
 </value>
</param>
</params>

It's useful to be aware of the settype() function (http://www.php.net/settype).

For binary base64 data and XML-RPC iso8601 date times the xmlrpc_set_type() function should be used on a PHP variable before using xmlrpc_encode()


Obtiene el tipo del xmlrpc para un valor PHP

  • « xmlrpc_encode
  • xmlrpc_is_fault »
  • PHP Manual
  • Funciones de XML-RPC
  • Obtiene el tipo del xmlrpc para un valor PHP

xmlrpc_get_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_get_type — Obtiene el tipo del xmlrpc para un valor PHP

Descripción

xmlrpc_get_type ( mixed $value ) : string
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Ésta función es específicamente útil para la base64 y las cadenas fecha-hora.

Parámetros

value

valor de PHP

Valores devueltos

Devuelve el tipo de XML-RPC.

Ejemplos

Ejemplo #1 Ejemplo de tipo de 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
?>

Ver también

  • xmlrpc_set_type() - Establece el tipo del xmlrpc, base64 o fecha-hora, para un valor de cadena 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.


Determina si el valor de un arreglo representa una falla del XMLRPC

  • « xmlrpc_get_type
  • xmlrpc_parse_method_descriptions »
  • PHP Manual
  • Funciones de XML-RPC
  • Determina si el valor de un arreglo representa una falla del XMLRPC

xmlrpc_is_fault

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

xmlrpc_is_fault — Determina si el valor de un arreglo representa una falla del XMLRPC

Descripción

xmlrpc_is_fault ( array $arg ) : bool
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Parámetros

arg

El arreglo devuelto por xmlrpc_decode().

Valores devueltos

Devuelve true si emabargo si el argumento significa fallo retorna, false. La descripción de la falla o falta está disponible en $arg["faultString"], fault el código está en $arg["faultCode"].

Ejemplos

Ver ejemplo dexmlrpc_encode_request().

Ver también

  • xmlrpc_decode() - Decodifica el XML en los tipos de PHP nativos

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

?>


Decodifica el XML en una lista de las descripciones del método

  • « xmlrpc_is_fault
  • xmlrpc_server_add_introspection_data »
  • PHP Manual
  • Funciones de XML-RPC
  • Decodifica el XML en una lista de las descripciones del método

xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_parse_method_descriptions — Decodifica el XML en una lista de las descripciones del método

Descripción

xmlrpc_parse_method_descriptions ( string $xml ) : array
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

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


Agrega una documentación introspectiva

  • « xmlrpc_parse_method_descriptions
  • xmlrpc_server_call_method »
  • PHP Manual
  • Funciones de XML-RPC
  • Agrega una documentación introspectiva

xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_add_introspection_data — Agrega una documentación introspectiva

Descripción

xmlrpc_server_add_introspection_data ( resource $server , array $desc ) : int
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

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`


Analiza los requerimientos del XML y las llamadas de los métodos

  • « xmlrpc_server_add_introspection_data
  • xmlrpc_server_create »
  • PHP Manual
  • Funciones de XML-RPC
  • Analiza los requerimientos del XML y las llamadas de los métodos

xmlrpc_server_call_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_call_method — Analiza los requerimientos del XML y las llamadas de los métodos

Descripción

xmlrpc_server_call_method ( resource $server , string $xml , mixed $user_data , array $output_options = ? ) : string
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

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


Crea un servidor xmlrpc

  • « xmlrpc_server_call_method
  • xmlrpc_server_destroy »
  • PHP Manual
  • Funciones de XML-RPC
  • Crea un servidor xmlrpc

xmlrpc_server_create

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_create — Crea un servidor xmlrpc

Descripción

xmlrpc_server_create ( ) : resource
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Destruye los recursos del servidor

  • « xmlrpc_server_create
  • xmlrpc_server_register_introspection_callback »
  • PHP Manual
  • Funciones de XML-RPC
  • Destruye los recursos del servidor

xmlrpc_server_destroy

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_destroy — Destruye los recursos del servidor

Descripción

xmlrpc_server_destroy ( resource $server ) : bool
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

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.


Registra una función PHP para generar la documentación

  • « xmlrpc_server_destroy
  • xmlrpc_server_register_method »
  • PHP Manual
  • Funciones de XML-RPC
  • Registra una función PHP para generar la documentación

xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_introspection_callback — Registra una función PHP para generar la documentación

Descripción

xmlrpc_server_register_introspection_callback ( resource $server , string $function ) : bool
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

User Contributed Notes

giunta dot gaetano at gmail dot com 29-Dec-2020 01:58
The introspection callback function should return an XML string with the following format:

<?xml version='1.0'?>
<introspection version='1.0'>
 <methodList>
  <methodDescription name='introspection.hello'>
   <author>Dan Libby</author>
   <purpose>greets the caller and demonstrates use of introspection mechanism</purpose>
   <signatures>
    <signature>
     <params>
      <value type='string' name='name'>name of the caller</value>
     </params>
     <returns>
      <value type='string'>a greeting to the caller</value>
     </returns>
    </signature>
   </signatures>
   <see><item>system.listMethods</item></see>
   <examples/>
   <errors>
      <item>returns fault code 1 if the caller's name is not specified</item>
   </errors>
   <notes>
    <item>this is a lame example</item>
    <item>example of multiple notes</item>
   </notes>
   <bugs/>
   <todo/>
  </methodDescription>
 </methodList>
</introspection>


Registra una función PHP para que el recurso del método coincida con method_name

  • « xmlrpc_server_register_introspection_callback
  • xmlrpc_set_type »
  • PHP Manual
  • Funciones de XML-RPC
  • Registra una función PHP para que el recurso del método coincida con method_name

xmlrpc_server_register_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_method — Registra una función PHP para que el recurso del método coincida con method_name

Descripción

xmlrpc_server_register_method ( resource $server , string $method_name , string $function ) : bool
Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

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


Establece el tipo del xmlrpc, base64 o fecha-hora, para un valor de cadena PHP

  • « xmlrpc_server_register_method
  • Extensiones específicas de Windows »
  • PHP Manual
  • Funciones de XML-RPC
  • Establece el tipo del xmlrpc, base64 o fecha-hora, para un valor de cadena PHP

xmlrpc_set_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_set_type — Establece el tipo del xmlrpc, base64 o fecha-hora, para un valor de cadena PHP

Descripción

xmlrpc_set_type ( string &$value , string $type ) : bool

Establece el tipo del xmlrpc, base64 o fecha-hora, para un valor de cadena PHP.

Advertencia

Esta función ha sido declarada EXPERIMENTAL. Su funcionamiento, nombre y la documentación que le acompaña puede cambiar sin previo aviso en futuras versiones de PHP. Utilícela bajo su propia responsabilidad.

Parámetros

value

Value to set the type

type

'base64' or 'datetime'

Valores devueltos

Devuelve true en caso de éxito o false en caso de error. If successful, value is converted to an object.

Ejemplos

Ejemplo #1 A xmlrpc_set_type() example

<?php

$params = date("Ymd\TH:i:s", time());
xmlrpc_set_type($params, 'datetime');
echo xmlrpc_encode($params);

?>

El resultado del ejemplo sería algo similar a:

<?xml version="1.0" encoding="utf-8"?>
<params>
<param>
 <value>
  <dateTime.iso8601>20090322T23:43:03</dateTime.iso8601>
 </value>
</param>
</params>

Errores/Excepciones

Issues E_WARNING with type unsupported by XMLRPC.

User Contributed Notes

bmatheny at mobocracy dot net 24-Mar-2006 03:08
The following code segfaults some older (pre 5.1.2) versions of PHP:

$foo = date('c', time());
xmlrpc_set_type($foo, 'datetime');

Please upgrade before reporting as a bug.
shem((at))etkDOTca [aka.Przemyslaw Szot] 30-Oct-2004 02:23
Once you use the xmlrpc_set_type function, the data is encoded into a PHP object.  In your XMLRPC server, in order to access the data you must be able to access the necessary part of the object.

So.. to expend on the example above:

<---------- CLIENT ---------->
$string = "My logging event.";
$date = "20030115T12:22:37"; // Must be this format
$binary = fread($fp, 128);
xmlrpc_set_type(&$date, "datetime");
xmlrpc_set_type(&$binary, "base64");
$xmlrpcReq = xmlrpc_encode_request("log.data", array($string, $date, $binary));

In order to retrieve the binary file data you would need to get the scalar portion of the object:

<---------- SERVER ------------>
$string=$params[0];
$date_obj=$params[1];
$binary_obj=$params[2];

$date=$date_obj->scalar;
$binary_data=$binary_obj->scalar;

// Then you can proceed to write the binary
fwrite($handle,$binary_data);
kelly at seankelly dot biz 28-Dec-2002 07:53
The problem is that PHP has a string type which is also used to hold binary data and dates.  But XML-RPC defines three separate types for strings, binary data, and dates.  How do you tell how you want strings encoded?  That's where this function comes in.

Suppose the XML-RPC method "log.data" took a string, a date, and a binary object.  To tell XML-RPC that the date (which is a PHP string) is a really a date and that the binary data (which is also a PHP string) is really binary data, try:

$string = "My logging event.";
$date = "20030115T12:22:37"; // Must be this format
$binary = fread($fp, 128);
xmlrpc_set_type(&$date, "datetime");
xmlrpc_set_type(&$binary, "base64");
$xmlrpcReq = xmlrpc_encode_request("log.data", array($string, $date, $binary));

Note the reference passing in the calls to xmlrpc_set_type; that enables the function to change the values from strings into what xmlrpc_encode/_request expects (which are objects that include a bonus field that tells the desired XML-RPC type).


Extensiones específicas de Windows

  • COM — COM y .Net (Windows)
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Errores y manejo de errores
    • Ejemplos
    • COM — La clase COM
    • DOTNET — La clase DOTNET
    • VARIANT — La clase VARIANT
    • COMPersistHelper — La clase COMPersistHelper
    • com_exception — La clase com_exception
    • Funciones de COM
  • win32service
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Ejemplos
    • Funciones win32service

User Contributed Notes

There are no user contributed notes for this page.


COM y .Net (Windows)

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Errores y manejo de errores
  • Ejemplos
    • For Each
    • Arrays y propiedades estilo array de COM
  • COM — La clase COM
  • DOTNET — La clase DOTNET
  • VARIANT — La clase VARIANT
  • COMPersistHelper — La clase COMPersistHelper
    • 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 clase com_exception
  • Funciones de COM
    • com_create_guid — Generar un identificador único globalmente (GUID)
    • com_event_sink — Conectar eventos de un objeto COM a un objeto PHP
    • com_get_active_object — Devuelve un gestor a una instancia de un objeto COM ya en ejecución
    • com_load_typelib — Carga una biblioteca de tipos
    • com_message_pump — Procesar mensajes COM, durmiendo hata timeoutms milisegundos
    • com_print_typeinfo — Imprime una definición de clase de PHP para una interfaz despachable
    • variant_abs — Devuelve el valor absoluto de una variante
    • variant_add — "Suma" dos variantes y devuelve el resultado
    • variant_and — Realiza una operación AND a nivel de bits entre dos variantes
    • variant_cast — Convertir una variante en un nuevo objeto variante de otro tipo
    • variant_cat — Concatena dos valores de variantes y devuelve el resultado
    • variant_cmp — Compara dos variantes
    • variant_date_from_timestamp — Devuelve una representación de variante de fecha de una fecha Unix
    • variant_date_to_timestamp — Convierte un valor de una variante de fecha/hora en una fecha Unix
    • variant_div — Devuelve el resultado de dividir dos variantes
    • variant_eqv — Realiza una equivalencia a nivel de bits en dos variantes
    • variant_fix — Devuelve la parte entera de una variante
    • variant_get_type — Devuelve el tipo de un objeto variante
    • variant_idiv — Convierte variantes a enteros y después devuelve el resultado dividiéndolos
    • variant_imp — Realiza una implicación a nivel de bits de dos variantes
    • variant_int — Devuelve la parte entera de una variante
    • variant_mod — Divide dos variantes y devuelve sólo el resto
    • variant_mul — Multiplica los valores de dos variantes
    • variant_neg — Realiza una negación lógica de una variante
    • variant_not — Realiza una negación NOT a nivel de bits en una variante
    • variant_or — Realiza una disyunción lógica de dos variantes
    • variant_pow — Devuelve el resultado de realizar la exponenciación con dos variantes
    • variant_round — Redondea una variante al número de lugares decimales especificado
    • variant_set_type — Convierte una variante en otro tipo "in situ"
    • variant_set — Asigna un nuevo valor para un objeto variante
    • variant_sub — Resta el valor de la variante derecha del valor de la varienta izquierda
    • variant_xor — Realiza una exclución lógica de dos variantes

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


Introducción

COM es un acrónimo de Component Object Model (Modelo de Objetos de Componentes); es una capa orientada a objetos (y servicios asociados) sobre DCE RPC (un estándar abierto) y define una convención de llamada común que habilita al código escrito en cualquier lenguaje para llamar e interoperar con código escrito en cualquier otro lenguaje (siempre que esos lenguajes sean concernientes a COM). El código no sólo puede ser escrito en cualquier lenguaje, sino que incluso no necesita ser parte del mismo ejecutable; el código se puede cargar desde una DLL, encontrarse en otro proceso en ejecución en la misma máquina, o, con DCOM (COM Distribuido), encontrarse en otro proceso en ejecución en una máquina remota, todo sin que el código necesite conocer dónde reside un componente.

Existe un subconjunto de COM, conocido como OLE Automation, que comprende un conjunto de interfaces COM que permiten la vinculación flexible de objetos COM, por lo que pueden ser examinados internamente y llamados en tiempo de ejecución sin tener conocimiento de cómo funcionan los objetos en tiempo de compilación. La extensión COM de PHP utiliza las interfaces de OLE Automation para permitir crear y llamar objetos compatibles desde los scripts. Técnicamente hablando, esta extensión debería llamarse la "Extensión de OLE Automation para PHP", ya que no todos los objetos COM son compatibles con OLE.

Ahora, ¿por qué usar COM? COM es una de las principales formas de casar aplicaciones y componentes en la plataforma Windows; al usar COM, se puede lanzar Microsoft Word, rellenar una plantilla de documento y guardar el resultado como un documento de Word y enviarlo a un visitante de su página web. También se puede usar COM para realizar tareas administrativas en su red y configurar IIS; estos son lo usos más comunes; se puede hacer mucho más con COM.

Además, se admite la instanciación y creación de ensamblados .Net usando la capa de interoperabilidad de COM proporcionada por Microsoft.

User Contributed Notes

There are no user contributed notes for this page.


Requerimientos

Las funciones de COM únicamente están disponibles para la versión de Windows de PHP.

El soporte para .Net support requiere PHP 5 y .Net runtime.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

A partir de PHP 5.3.15 / 5.4.5, esta extensión requiere php_com_dotnet.dll para habilitarla dentro de php.ini para poder usar estas funciones. Las versiones anteriores de PHP habilitaban estas extensiones de manera predeterminada.

Usted tienen la responsabilidada de instalar el soporte para los diversos objetos COM que tenga intención de usar (como MS Word); no incluimos ni podemos incluir todos estos con PHP.

User Contributed Notes

There are no user contributed notes for this page.


Configuración en tiempo de ejecución

El comportamiento de estas funciones se ve afectado por la configuración de php.ini.

Opciones de configuración de COM
Nombre | Por defecto | Cambiable | Historial de cambios
com.allow_dcom | "0" | PHP_INI_SYSTEM | Disponible desde PHP 4.0.5.
com.autoregister_typelib | "0" | PHP_INI_ALL | PHP_INI_SYSTEM en PHP 4. Disponible desde PHP 4.1.0.
com.autoregister_verbose | "0" | PHP_INI_ALL | PHP_INI_SYSTEM en PHP 4. Disponible desde PHP 4.1.0.
com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP_INI_SYSTEM en PHP 4. Disponible desde PHP 4.1.0.
com.code_page | "" | PHP_INI_ALL | Disponible desde PHP 5.0.0.
com.typelib_file | "" | PHP_INI_SYSTEM | Disponible desde PHP 4.0.5.
Para más detalles y definiciones de los modos de PHP_INI_*, vea Dónde se puede realizar un ajuste de configuración.

He aquí una breve explicación de las directivas de configuración.

com.allow_dcom

Cuando está activada, PHP será capaz de operar como un cliente D-COM (COM Distribuido) y permitirá al script de PHP instanciar objetos COM en un servidor remoto.

com.autoregister_typelib

Cuando está activada, PHP intentará registrar constantes desde la biblioteca de tipos de objetos que instancia, si esos objetos implementan las interfaces requeridas para obtener esa información. La sensibilidad a mayúsculas-minúsculas de las constantes que registra está controlada por la directiva de configuración .

com.autoregister_verbose

Cuando está activada, cualquier problema al cargar una biblioteca de tipos durante la instanciación de un objeto será notificada usando el mecanismo de errores de PHP. Por defecto está desactivada, no emitiendo así ninguna indicación de si hubo un error buscando o cargando una biblioteca de tipos.

com.autoregister_casesensitive

Cuando está activada (predeterminado), las constantes encontradas en las bibliotecas de tipos autocargadas serán registradas con sensibilidad a mayúsculas-minúsculas. Véase com_load_typelib() para más detalles.

com.code_page

Controla la página de código predeterminada del conjunto de caracters a usar cuando se pasan cadenas hacia y desde objetos COM. Si está establecid a una cadena vacía, PHP asumirá CP_ACP, que es la página de código ANSI predeterminada del sistema.

Si el texto de sus scripts está codificado usando un conjunto de caracteres/codificación diferente por omision, establecer esta directiva le ahorrará de tener que pasar la página de código como parámetro al constructor de la clase COM. Por favor, observe que al usar esta directiva (como cualquier otra directiva de configuración de PHP), su script de PHP se convierte en menos portable; debería usar el parámetro del constructor de COM siempre que sea posible.

Nota: Esta directiva de configuración se introdujo con PHP 5.

com.typelib_file

Cuando está establecida debería contener la ruta al fichero que contiene una lista de bibliotecas de tipos que deberían ser cargadas al inicio. Cada línea del fichero será tratada como el nombre de una biblioteca de tipos y será cargada como si se llamara a com_load_typelib(). Las constantes serán registradas de forma persistente, por lo que la biblioteca únicamente necesita ser cargada una vez. Si un nombre de una biblioteca de tipos termina con la cadena #cis o #case_insensitive, las constantes de esa biblioteca serán registradas de manera insensible a mayúsculas-minúsculas.

User Contributed Notes

There are no user contributed notes for this page.


Tipos de recursos

Esta extension define una referencia a un componente COM devuelto por la obsoleta com_load() (esta función no existe en PHP 5; en su lugar use la clase COM).

User Contributed Notes

There are no user contributed notes for this page.


Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles sólo cuando la extensión haya sido compilada con PHP, o bien sea cargada dinámicamente en ejecución.

Constantes COM
Constante | Valor | Descripción | Observaciones
CLSCTX_INPROC_SERVER (integer) | 1 | El código que crea y administra objetos de esta clase es una DLL que se ejecuta en el mismo proceso que el llamador a la función especificando el contexto de la clase. |
CLSCTX_INPROC_HANDLER (integer) | 2 | El código que administra objetos de esta clase es un gestor "en-proceso". Es una DLL que se ejecuta en el proceso cliente e implementa estructuras del lado del cliente de esta clase cuando a las instancias de la clase se acceden de forma remota. |
CLSCTX_LOCAL_SERVER (integer) | 4 | El código EXE que crea y administra objetos de esta clase se ejecuta en la misma máquina, pero se carga en un espacio de proceso distinto. |
CLSCTX_REMOTE_SERVER (integer) | 16 | Un contexto remoto. El código que crea y administra objetos de esta clase se ejecuta en un ordenador diferente. |
CLSCTX_SERVER (integer) | 21 | Indica código de servidor, si es "en-proceso", local, o remoto. Esta definición usa el operador OR con CLSCTX_INPROC_SERVER, CLSCTX_LOCAL_SERVER, y CLSCTX_REMOTE_SERVER. |
CLSCTX_ALL (integer) | 23 | Indica todos los contextos de clase. Esta definición usa el operador OR con CLSCTX_INPROC_HANDLER y CLSCTX_SERVER. |
VT_NULL (integer) | 1 | Referencia a un puntero NULL. |
VT_EMPTY (integer) | 0 | Una propiedad con un indicador de tipo VT_EMPTY no tiene información asociada a ella; es decir, el tamaño del valor es cero. |
VT_UI1 (integer) | 17 | Integer sin signo de 1 byte. |
VT_I2 (integer) | 2 | Dos bytes que representan un integer con signo de 2 bytes. |
VT_I4 (integer) | 3 | Valor de tipo integer con signo de 4 bytes. |
VT_R4 (integer) | 4 | Valor de coma flotante IEEE de 32 bits. |
VT_R8 (integer) | 5 | Valor de coma flotante IEEE de 64 bits. |
VT_BOOL (integer) | 11 | Valor boolean. |
VT_ERROR (integer) | 10 | Código de error; contienen el código de estado asociado con el error. |
VT_CY (integer) | 6 | Integer de complemento a dos de 8 bytes (escalado por 10,000). |
VT_DATE (integer) | 7 | Un número de coma flotante de 64 bits que representa el número de días (no segundos) desde el 31 de diciembre de 1899. Por ejemplo, January 1, 1900, es 2.0, January 2, 1900, es 3.0, y así sucesivamente). Se almacena con la misma representación que VT_R8. |
VT_BSTR (integer) | 8 | Puntero a una cadena Unicode finalizada en null. |
VT_DECIMAL (integer) | 14 | Una estructura decimal. |
VT_UNKNOWN (integer) | 13 | Un puntero a un objeto que implementa al interfaz IUnknown. |
VT_DISPATCH (integer) | 9 | Se especificó un puntero a un puntero a un objeto. |
VT_VARIANT (integer) | 12 | Un indicador de tipo seguido del valor correspondiente. VT_VARIANT sólo se puede usar con VT_BYREF. |
VT_I1 (integer) | 16 | Integer con signo de 1 byte. |
VT_UI2 (integer) | 18 | Integer sin signo de 2 bytes. |
VT_UI4 (integer) | 19 | Integer sin signo de 4 bytes. |
VT_INT (integer) | 22 | Valor integer con signo de 4 bytes (equivalente a VT_I4). |
VT_UINT (integer) | 23 | Valor integer sin signo de 4 bytes (equivalente a VT_UI4). |
VT_ARRAY (integer) | 8192 | Si el indicador de tipo se combina con VT_ARRAY mediante un operador OR, el valor es un puntero a un SAFEARRAY. VT_ARRAY puede usar OR con los siguientes tipos de datos: 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 y VT_VARIANT. |
VT_BYREF (integer) | 16384 | Si el indicador de tipo se combina con VT_BYREF mediante un operador OR, el valor es una referencia. Los tipos de referencias son interpretados como una referencia a datos, similar al tipo de referencia en C++. |
CP_ACP (integer) | 0 | Por defecto la página de código de ANSI. |
CP_MACCP (integer) | 2 | Página de código de Macintosh. |
CP_OEMCP (integer) | 1 | Por defecto la página de código de OEM. |
CP_UTF7 (integer) | 65000 | Unicode (UTF-7). |
CP_UTF8 (integer) | 65001 | Unicode (UTF-8). |
CP_SYMBOL (integer) | 42 | Traducciones de SYMBOL. |
CP_THREAD_ACP (integer) | 3 | Página de código de ANSI del hilo actual |
VARCMP_LT (integer) | 0 | El bstr izquierdo es menor que el bstr derecho. |
VARCMP_EQ (integer) | 1 | Los dos parámetros son iguales. |
VARCMP_GT (integer) | 2 | El bstr izquierdo es mayor que el bstr derecho. |
VARCMP_NULL (integer) | 3 | Ambas expresiones son NULL. |
NORM_IGNORECASE (integer) | 1 | Ignorar la sensibilidad a mayúsculas-minúsculas. |
NORM_IGNORENONSPACE (integer) | 2 | Ignorar los caracters que no son espacios. |
NORM_IGNORESYMBOLS (integer) | 4 | Ignorar los símbolos. |
NORM_IGNOREWIDTH (integer) | 131072 | Ignorar el ancho de cadena. |
NORM_IGNOREKANATYPE (integer) | 65536 | Ignorar el tipo Kana. |
NORM_IGNOREKASHIDA (integer) | 262144 | Ignorar caractares kashida árabes. | La disponibilidad depende de la biblioteca subyacente.
DISP_E_DIVBYZERO (integer) | -2147352558 | Un error devuelto que indica un error de división por cero. |
DISP_E_OVERFLOW (integer) | -2147352566 | Un error que indica que un valor no puede ser coaccionado a su representación esperada. |
MK_E_UNAVAILABLE (integer) | -2147221021 | Código de estado COM de iMoniker, devuelto en errores donde la llamada a la función falló a causa de no estar disponible. |

User Contributed Notes

There are no user contributed notes for this page.


Errores y manejo de errores

Excepciones (PHP 5)

Esta extensión lanzará instancias de la clase com_exception siempre que haya un error potencialmente fatal notificado por COM. Todas las excepciones de COM tienen una propiedad code bien definida que se corresponde con el valor devuelto HRESULT de diferentes operaciones COM. Puede usar este código para tomar decisiones programáticas de cómo manejar la excepción.

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

Tabla de contenidos

  • For Each
  • Arrays y propiedades estilo array de COM

User Contributed Notes

There are no user contributed notes for this page.


For Each

Desde PHP 5 se puede usar la sentencia foreach propia de PHP para iterar sobre el contenido de un COM/OLE IEnumVariant estándar. En términos entendibles, esto significa que se puede usar foreach en lugares donde se podría usar For Each en código VB/ASP.

Ejemplo #1 For Each en ASP

<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
  Response.Write obj.Name & "<br />"
Next
%>

Ejemplo #2 while() ... Next() en PHP 4

<?php
$domainObject = new COM("WinNT://Domain");
while ($obj = $domainObject->Next()) {
   echo $obj->Name . "<br />";
}
?>

Ejemplo #3 foreach en PHP 5

<?php
$domainObject = new COM("WinNT://Domain");
foreach ($domainObject as $obj) {
   echo $obj->Name . "<br />";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Arrays y propiedades estilo array de COM

Muchos objetos COM exponen sus propiedades como arrays, o usan el acceso estilo array. En PHP 4 se puede usar la sintaxis de array de PHP para leer/escribir tales propiedades, pero únicamente se permite una sola dimensión. Si se quiere leer una propiedad multidimensional, en su lugar se podría hacer el acceso a la propiedad dentro de una llamada a una función, cada parámetro representando cada dimensión del acceso al array, pero no hay forma de escribir tal propiedad.

PHP 5 introduce la siguiente característica nueva para hacerle la vida más fácil:

  • Acceder a arrays multidimensionales, o propiedades COM que requieren múltiples parámetros usando la sintaxis de array de PHP. También se puede escribir o establecer propiedades usando esta técnica.

  • Iterar SafeArrays (arrays "verdaderos") usando la estructura de control foreach. Esto funciona ya que SafeArrays incluye información sobre su tamaño. Si una propiedad estilo array implementa IEnumVariant, también se puede usar foreach para esa property; eche un vistazo a For Each para más información sobre este tema.

User Contributed Notes

There are no user contributed notes for this page.


La clase COM

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

Descripción

La clase COM permite crear una instancia de un objeto COM compatible con OLE y llamar sus métodos y aceder sus propiedades.

$obj = new COM("Application.ID")

Métodos

COM::__construct ( string $module_name , mixed $server_name = ? , int $codepage = ? , string $typelib = ? )

Constructor de la clase COM. Los parámetros tienen los siguientes significados:

module_name
Puede ser un ProgID, Class ID o Moniker que tenga el nombre del componente a cargar. Un ProgID tipicamente es el nombre de la aplicación o DLL seguido por un punto, seguido del nombre del objeto, ej.: Word.Application. Un Class ID es el UUID que identifica unívocamente una clase dada. Un Moniker es una forma especial de denominación, similar en concepto a un esquema URL, que identifica un recurso y especifica como debería ser cargado. Como ejemplo, se puede cargar Word y obtener un objeto representando un documento de word especificando el camino completo al documento de word como el nombre del módulo, o puede usar LDAP: como un moniker para usar la interfaz ADSI a LDAP.
server_name
El nombre de un servidor DCOM en donde el componente debería ser cargado y ejecutado. Si es null el objeto es ejecutado usando el predeterminado para la aplicación. Lo predeterminado típicamente es ejecutarlo sobre la máquina local, aunque el administrador puede configurar la aplicación para ejecutarlo en una máquina diferente. Si se especifica un valor distinto de null para el servidor, PHP se reusará a cargar el objeto a no ser que la opción de configuración sea true.

Si server_name es un array, este debería contener los siguientes elementos (distinguiendo mayúsculas de minúsculas!). Note que son todos opcionales (aunque se necesita especificar Username y Password juntos); si se omite el elemento Server, será usado el servidor predeterminado (como se menciona más arriba), y la creación de la instancia del objeto no será afectada por la directiva .

Nombre de servidor DCOM
server_name clave | Tipo | Descripción
Server | string | Nombre del servidor.
Username | string | El nombre de usuario para conectarse.
Password | string | La clave para Username.
Flags | integer | Una o más de las siguientes constantes, unidas por un OR lógico: CLSCTX_INPROC_SERVER, CLSCTX_INPROC_HANDLER, CLSCTX_LOCAL_SERVER, CLSCTX_REMOTE_SERVER, CLSCTX_SERVER y CLSCTX_ALL. El valor predeterminado si no se especifica aquí es CLSCTX_SERVER si tambien se omitió Server, o CLSCTX_REMOTE_SERVER si se especificó un servidor. Se debe consultar la documentación de Microsoft para CoCreateInstance para más información sobre el significado de estas constantes; típicamente nunca suelen usarse.

codepage
Especifica la página de código que es usada para convertir las cadenas a cadenas unicode y viceversa. La conversión es aplicada cuando una cadena PHP es pasada como parámetro o devuelta desde un método de este objeto COM. La página de código es pegajosa en PHP 5, lo que significa que se propaga a objetos y variantes devueltos por el objeto. Los posibles valores son CP_ACP (Usando la página de código ANSI predeterminada - si este parámetro se omite es lo predeterminado), CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP (usando la página de código/localización establecida para el hilo de ejecución actual), CP_UTF7 y CP_UTF8. Tambien puede usar el número de una página de código; consulte la documentación de Microsoft para más detalles sobre los códigos de páginas y sus valores numéricos.

Métodos sobrecargados

El objeto devuelto es un objeto sobrecargado, lo que significa que PHP no ve ningún método fijo como lo hace con las clases regulares; en su lugar, cualquier acceso de propiedad o método son pasados a través de COM.

Comenzando con PHP 5, PHP automáticamente detectará métodos que acepten parámetros por referencia, y automáticamente convertirá las variables regulares de PHP a una forma que pueden ser pasadas por referencia. Esto significa que puede llamar los métodos muy naturalmente; no hay necesidad de ningún esfuerzo extra en su código.

En PHP 4, para pasar parámetros por referencia necesita crear una instancia de la clase VARIANT para envolver los parámetros byref.

Pseudo Métodos

En versiones de PHP anteriores a 5, un número no muy agradables de trucos significaba que los siguientes nombres de métodos no sean pasados a través de COM y fueran directamente controlados por PHP. PHP 5 elimina todo esto; lea los detalles a continuación para determinar como corregir su código. Estos nombres de métodos mágicos son insensible a las mayusculas.

COM::AddRef ( ) : void

Agrega artificialmente una referencia de contador al objeto COM.

Advertencia

No debería tener necesidad de usar este método. Existe como un complemento lógico al método Release() a continuación.

COM::Release ( ) : void

Remueve artificialmente una referencia de contador al objeto COM.

Advertencia

No debería tener necesidad de usar este método. Su existencia en PHP es un error diseñado para evitar un error que mantiene objetos COM ejecutandose por más tiempo que el debido.

Pseudo Métodos para iterar

Estos pseudo métodos solo estan disponibles si com_isenum() devuelve true, en cuyo caso, esconden cualquier método con los mismos nombres que podrían ser proporcionados por el objeto COM. Estos métodos han sido eliminados en PHP 5, y debería usar For Each en su lugar.

COM::All ( ) : variant

Devuelve un variant que representa un SafeArray con 10 elementos; cada elementos será un variant vacío o null. Esta función Returns a variant representing a SafeArray that has 10 elements; each element will be an empty/null variant. This function was supposed to return an array containing all the elements from the iterator, but was never completed. Do not use.

COM::Next ( ) : variant

Devuelve un variant representando el siguiente elemento disponible en el iterador, o false cuando no hay más elementos.

COM::Prev ( ) : variant

Devuelve un variant representando el elemento anterior disponible en el iterador, o false cuando no hay más elementos.

COM::Reset ( ) : void

Retrocede el iterador hasta el principio.

Ejemplos COM

Ejemplo #1 Ejemplo COM (1)

<?php
// Iniciando word
$word = new COM("word.application") or die("No se puede crear la instancia de Word");
echo "Word cargado, versión {$word->Version}\n";

//traerlo al frente
$word->Visible = 1;

//abrir un documento vacío
$word->Documents->Add();

//hacer algunas cosas raras
$word->Selection->TypeText("Esto es una prueba...");
$word->Documents[1]->SaveAs("Prueba inutil.doc");

//cerrando word
$word->Quit();

//liberando el objeto
$word = null;
?>

Ejemplo #2 Ejemplo COM (2)

<?php

$conn = new COM("ADODB.Connection") or die("No se puede iniciar ADO");
$conn->Open("Provider=SQLOLEDB; Data Source=localhost;
Initial Catalog=database; User ID=user; Password=password");

$rs = $conn->Execute("SELECT * FROM sometable");    // Registros

$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++;            // incrementa rowcount
    $rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs = null;
$conn = null;

?>

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


La clase DOTNET

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

Descripción

La clase DOTNET le permite instanciar una clase desde un ensamble .Net y poder llamar sus métodos y acceder a sus propiedades.

$obj = new DOTNET("assembly", "classname")

Métodos

DOTNET::__construct ( string $assembly_name , string $class_name , int $codepage = ? )

Constructor de la clase DOTNET. El parámetro assembly_name especifica cual ensamble debería ser cargado, y class_name especifica cual clase instanciar en ese ensamble. Opcionalmente puede especificar un parámetro codepage para usar transformaciones de cadena unicode; vea la clase COM para más detalles en las páginas de código.

El objeto devuelto es un objeto sobrecargado, lo que significa que PHP no ve ningún método fijo como lo hace con las clases regulares; en su lugar, cualquier método o propiedad que accede se pasa por medio del COM y de allí a DOTNET. En otras palabras, el objeto .Net es mapeado a través de la capa de interoperabilidad COM provista por el runtime de .Net.

Una vez se ha creado un objeto DOTNET, PHP lo trata idénticamente como cualquier otro objeto COM; se aplican todas las mismas reglas.

Ejemplo #1 Ejemplo DOTNET

<?php
 $stack = new DOTNET("mscorlib", "System.Collections.Stack");
 $stack->Push(".Net");
 $stack->Push("Hello ");
 echo $stack->Pop() . $stack->Pop();
?>

Nota:

Necesita instalar el runtime de .Net en su servidor web para tomar las ventajas de esta característica.

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.


La clase VARIANT

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

Descripción

La clase VARIANT es un equivalente de COM para el PHP zval; es una estructura que puede contener un valor con un rango de diferentes tipos posibles. La clase VARIANT suministrada por la extensión COM, permite tener un mayor control sobre el modo en que PHP pasa los valores hacia y desde COM.

$vVar = new VARIANT($var)

Métodos

VARIANT::VARIANT ( mixed $value = ? , int $type = ? , int $codepage = ? )

constructor de clase VARIANT. Parámetros:

value
valor inicial. si se omite, o se le da valor null se creará un objeto vacío VT_EMPTY.
type
especifica el tipo de objeto VARIANT contenido. Los valores posibles son una de las constantes VT_XXX Constantes predefinidas. En versiones PHP anteriores a PHP 5, se puede forzar a PHP para que pase un objeto VARIANT por referencia, combinando VT_BYREF con el operador OR y el parámetro type. En PHP 5, este hack no está soportado; en lugar de eso, PHP 5 puede detectar los parámetros pasados por referencia automáticamente; ni siquiera es necesario pasarlos como objetos VARIANT. Consultar la biblioteca MSDN para información adicional sobre el tipo VARIANT.
codepage
especifica la página de códigos que se utilizará para convertir los strings a unicode. Ver el parámetro del mismo nombre en la clase COM para más información.

Las versiones PHP anteriores a PHP 5 definen un número de propiedades virtuales (no documentadas) para las instancias de la clase VARIANT; estas propiedades han sido eliminadas en PHP 5 en favor de una sintaxis más natural; estas diferencias se ilustran mejor con el siguiente ejemplo:

Ejemplo #1 Ejemplo de una clase VARIANT, utilizada en PHP 4.x

<?php
$v = new VARIANT(42);
print "El tipo es " . $v->type . "<br/>";
print "El valor es " . $v->value . "<br/>";
?>

Ejemplo #2 Ejemplo de una clase VARIANT, utilizada en PHP 5

<?php
$v = new VARIANT(42);
print "El tipo es " . variant_get_type($v) . "<br/>";
print "El valor es " . $v . "<br/>";
?>

La razón para este cambio es que, internamente, la extensión COM ve a las clases VARIANT, COM y DOTNET como la misma cosa, y la filosofía de diseño para estas clases es que todos los accesos a las propiedades y los miembros se transmiten a través de COM sin ninguna interferencia. La nueva sintaxis es más natural y requiere menos esfuerzo, y muchas de las propiedades virtuales eliminadas ya no tienen sentido en un contexto PHP.

Nota:

PHP 5 toma una aproximación mucho más simple en la gestión de VARIANTs; cuando se devuelve un valor o se carga una propiedad VARIANT, ésta se convierte en un valor PHP únicamente cuando hay un mapeo directo entre los tipos de tal forma que no se pierda información. En todos los otros casos, el resultado es devuelto como una instancia de la clase VARIANT. Se puede forzar a PHP para convertir o evaluar la clase VARIANT como un tipo nativo PHP utilizando un operador para clasificarla explícitamente, o implícitamente como un string con la función print. Es posible utilizar el amplio rango de funciones VARIANT para realizar operaciones aritméticas en VARIANTS sin forzar una conversión o arriesgarse a una pérdida de información.

Ver también la función variant_get_type().

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.


La clase COMPersistHelper

(PHP 5, PHP 7, PHP 8)

Introducción

COMPersistHelper mejora la interoperabilidad de COM y PHP con respecto a la directiva php.ini open_basedir, y stream recursos.

Sinopsis de la Clase

final COMPersistHelper {
/* Métodos */
public __construct ( variant|null $variant = null )
public GetCurFileName ( ) : string|false
public GetMaxStreamSize ( ) : int
public InitNew ( ) : bool
public LoadFromFile ( string $filename , int $flags = 0 ) : bool
public LoadFromStream ( resource $stream ) : bool
public SaveToFile ( string|null $filename , bool $remember = true ) : bool
public SaveToStream ( resource $stream ) : bool
}

Tabla de contenidos

  • 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

Descripción

public COMPersistHelper::__construct ( variant|null $variant = null )

Constructs a persistence helper object, usually associated with a variant.

Parámetros

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

Descripción

public COMPersistHelper::GetCurFileName ( ) : string|false

Retrieves the current name of the file associated with the object.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the current name of the file associated with the object.

Errores/Excepciones

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

Descripción

public COMPersistHelper::GetMaxStreamSize ( ) : int

Retrieves the size of the stream (in bytes) needed to save the object.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the size of the stream (in bytes) needed to save the object.

Errores/Excepciones

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

Descripción

public COMPersistHelper::InitNew ( ) : bool

Initializes an object to a default state.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

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

Descripción

public COMPersistHelper::LoadFromFile ( string $filename , int $flags = 0 ) : bool

Opens the specified file and initializes an object from the file contents.

Parámetros

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.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

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

Descripción

public COMPersistHelper::LoadFromStream ( resource $stream ) : bool

Initializes an object from the stream where it was saved previously.

Parámetros

stream
The stream recurso from which to load the object.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

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

Descripción

public COMPersistHelper::SaveToFile ( string|null $filename , bool $remember = true ) : bool

Saves a copy of the object to the specified file.

Parámetros

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.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

A com_exception is thrown if the associated object does not implement the COM interface IPersistFile, or when calling the IPersistFile::Save() method failed.

Ejemplos

Ejemplo #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

Descripción

public COMPersistHelper::SaveToStream ( resource $stream ) : bool

Saves an object to the specified stream.

Parámetros

stream
The stream recurso to which to save the object.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

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 clase com_exception

(PHP 5, PHP 7, PHP 8)

Introducción

Sinopsis de la Clase

com_exception extends Exception implements Throwable {
/* Propiedades heredadas */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Métodos heredados */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

User Contributed Notes

There are no user contributed notes for this page.


Funciones de COM

Ver también

Para más información sobre COM lea la » Especificación COM. Puede encontrar alguna información adicional útil en nuestra FAQ de PHP y COM. Si está pensando usar aplicaciones de MS Office en el lado del servidor, debería leer la información aquí: » Considerations for Server-Side Automation of Office.

Tabla de contenidos

  • com_create_guid — Generar un identificador único globalmente (GUID)
  • com_event_sink — Conectar eventos de un objeto COM a un objeto PHP
  • com_get_active_object — Devuelve un gestor a una instancia de un objeto COM ya en ejecución
  • com_load_typelib — Carga una biblioteca de tipos
  • com_message_pump — Procesar mensajes COM, durmiendo hata timeoutms milisegundos
  • com_print_typeinfo — Imprime una definición de clase de PHP para una interfaz despachable
  • variant_abs — Devuelve el valor absoluto de una variante
  • variant_add — "Suma" dos variantes y devuelve el resultado
  • variant_and — Realiza una operación AND a nivel de bits entre dos variantes
  • variant_cast — Convertir una variante en un nuevo objeto variante de otro tipo
  • variant_cat — Concatena dos valores de variantes y devuelve el resultado
  • variant_cmp — Compara dos variantes
  • variant_date_from_timestamp — Devuelve una representación de variante de fecha de una fecha Unix
  • variant_date_to_timestamp — Convierte un valor de una variante de fecha/hora en una fecha Unix
  • variant_div — Devuelve el resultado de dividir dos variantes
  • variant_eqv — Realiza una equivalencia a nivel de bits en dos variantes
  • variant_fix — Devuelve la parte entera de una variante
  • variant_get_type — Devuelve el tipo de un objeto variante
  • variant_idiv — Convierte variantes a enteros y después devuelve el resultado dividiéndolos
  • variant_imp — Realiza una implicación a nivel de bits de dos variantes
  • variant_int — Devuelve la parte entera de una variante
  • variant_mod — Divide dos variantes y devuelve sólo el resto
  • variant_mul — Multiplica los valores de dos variantes
  • variant_neg — Realiza una negación lógica de una variante
  • variant_not — Realiza una negación NOT a nivel de bits en una variante
  • variant_or — Realiza una disyunción lógica de dos variantes
  • variant_pow — Devuelve el resultado de realizar la exponenciación con dos variantes
  • variant_round — Redondea una variante al número de lugares decimales especificado
  • variant_set_type — Convierte una variante en otro tipo "in situ"
  • variant_set — Asigna un nuevo valor para un objeto variante
  • variant_sub — Resta el valor de la variante derecha del valor de la varienta izquierda
  • variant_xor — Realiza una exclución lógica de dos variantes

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


Generar un identificador único globalmente (GUID)

  • « Funciones de COM
  • com_event_sink »
  • PHP Manual
  • Funciones de COM
  • Generar un identificador único globalmente (GUID)

com_create_guid

(PHP 5, PHP 7, PHP 8)

com_create_guid — Generar un identificador único globalmente (GUID)

Descripción

com_create_guid ( ) : string

Genera un identificador único globalmente (GUID: Globally Unique Identifier).

Un GUID es generado de la misma manera que el DCE UUID, excepto que la convención de Microsoft encierra un GUID entre llaves.

Valores devueltos

Devuelve el GUID como cadena.

Ver también

  • uuid_create() en la extensión uuid de PECL

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.


Conectar eventos de un objeto COM a un objeto PHP

  • « com_create_guid
  • com_get_active_object »
  • PHP Manual
  • Funciones de COM
  • Conectar eventos de un objeto COM a un objeto PHP

com_event_sink

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

com_event_sink — Conectar eventos de un objeto COM a un objeto PHP

Descripción

com_event_sink ( variant $comobject , object $sinkobject , mixed $sinkinterface = ? ) : bool

Ordena a COM que eventos generados por comobject sean absorbidos por el objeto PHP sinkobject.

Tenga cuidado en cómo use esta característica; si está haciendo algo similar al ejemplo de abajo, no tiene sentido ejecutarla en un contexto de servidor web.

Parámetros

comobject

sinkobject

sinkobject debería ser una instancia de una clase con métodos nombrados después de aquellos de la dispinterfaz deseada; se puede usar com_print_typeinfo() para ayudar a generar una clase plantilla para este propósito.

sinkinterface

PHP intentará usar el tipo de dispinterfaz predeterminado especificado por la biblioteca de tipos asociada con comobject, pero se puede sobrescribir esta opción estableciendo sinkinterface al nombre de la dispinterfaz que se desea usar.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de absorción de un evento COM

<?php
class IEEventSinker {
    var $terminated = false;

   function ProgressChange($progress, $progressmax) {
      echo "Download progress: $progress / $progressmax\n";
    }

    function DocumentComplete(&$dom, $url) {
      echo "Document $url complete\n";
    }

    function OnQuit() {
      echo "Quit!\n";
      $this->terminated = true;
    }
}
$ie = new COM("InternetExplorer.Application");
// note that you don't need the & for PHP 5!
$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;
?>

Ver también

  • com_print_typeinfo() - Imprime una definición de clase de PHP para una interfaz despachable
  • com_message_pump() - Procesar mensajes COM, durmiendo hata timeoutms milisegundos

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");
//...


Devuelve un gestor a una instancia de un objeto COM ya en ejecución

  • « com_event_sink
  • com_load_typelib »
  • PHP Manual
  • Funciones de COM
  • Devuelve un gestor a una instancia de un objeto COM ya en ejecución

com_get_active_object

(PHP 5, PHP 7, PHP 8)

com_get_active_object — Devuelve un gestor a una instancia de un objeto COM ya en ejecución

Descripción

com_get_active_object ( string $progid , int $code_page = ? ) : variant

com_get_active_object() es similar a crear una nueva instancia de un objeto COM, excepto que sólo devolverá un objeto a su script si el objeto ya está en ejecución. Las aplicaciones OLE usan algo conocido como la "Tabla de Objetos en Ejecución" para permitir a las famosas aplicaciones que se lancen solo una vez; esta función expone la función de la biblioteca COM, GetActiveObject(), para obtener un gestor sobre una instancia en ejecución.

Parámetros

progid

progid puede ser el ProgID o el CLSID del objeto al que se quiere acceder (por ejemplo Word.Application).

code_page

Actúa exactamente de la misma forma que lo hace la clase COM.

Valores devueltos

Si el objeto solicitado está ejecutándose será devuelto a su script al igual que otro objeto COM.

Errores/Excepciones

Existen diversas razones para que esta función pueda fallar, la más común siendo que el objeto no está ejecutándose aún. En esta situación, el código de error de excepción será MK_E_UNAVAILABLE; se puede usar el método getCode del objeto excepción para comprobar el código de excepción.

Notas

Advertencia

Usar com_get_active_object() en un contexto de servidor web no es siempre una idea inteligente. La mayoría de las aplicaciones COM/OLE no están diseñadas para tratar más de un cliente al mismo tiempo, incluso (¡o especialmente!) Microsoft Office. Debería leer » Consideraciones para la Automatización del Lado del Servidor de Office para más información sobre los temas generales involucrados.

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.


Carga una biblioteca de tipos

  • « com_get_active_object
  • com_message_pump »
  • PHP Manual
  • Funciones de COM
  • Carga una biblioteca de tipos

com_load_typelib

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

com_load_typelib — Carga una biblioteca de tipos

Descripción

com_load_typelib ( string $typelib_name , bool $case_insensitive = true ) : bool

Carga una biblioteca de tipos y registra sus constantes en la máquina, como si fueran definidas usando define().

Observe que es más efectivo usar el ajuste de configuración para pre-cargar y registrar las constantes, aunque no es tan flexible.

Si se ha activado , PHP intenrá registrar automáticamente las constantes asociadas con un objeto COM cuando se instancie. Esto depende de las interfaces proporcionadas por el propio objeto COM, y no siempre puede ser posible.

Parámetros

typelib_name

typelib_name puede ser uno de los siguientes:

  • El nombre de fichero de un fichero .tlb o el módulo ejecutable que contiente la biblioteca de tipos.

  • El GUID de la biblioteca de tipos, seguido de su número de versión, por ejemplo {00000200-0000-0010-8000-00AA006D2EA4},2,0.

  • El nombre de la biblioteca de tipos, p.ej. Microsoft OLE DB ActiveX Data Objects 1.0 Library.

PHP intentará resolver la biblioteca de tipos en este orden, mientras que el proceso se hace más costoso a medida que se baja por la lista; buscar la biblioteca de tipos por nombre se trata físicamente enumerando el registro hasta que se encuentre una coincidencia.

case_insensitive

case_insensitive se comporta de la misma manera que el parámetro con el mismo nombre de la función define().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

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.


Procesar mensajes COM, durmiendo hata timeoutms milisegundos

  • « com_load_typelib
  • com_print_typeinfo »
  • PHP Manual
  • Funciones de COM
  • Procesar mensajes COM, durmiendo hata timeoutms milisegundos

com_message_pump

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

com_message_pump — Procesar mensajes COM, durmiendo hata timeoutms milisegundos

Descripción

com_message_pump ( int $timeoutms = 0 ) : bool

Esta función duerme hasta timeoutms milisegundos, o hasta que llegue un mensaje a la cola.

El propósito de esta función es guiar las llamadas COM entre departamentos y tratar varios temas de sincronización. Permite a su script esperar de manera eficiente a eventos que van a ser desencadenados, mientras que todavía trata otros evetntos o ejecuta otro código en segundo plano. Debería usarla en un bucle, como se demostró en el ejemplo de la función com_event_sink(), hasta que finalice usando objetos COM de límite de eventos.

Parámetros

timeoutms

El tiempo límite, en milisegundos.

Si no se especifica un valor para timeoutms, se asumirá 0. Un valor de 0 significa que no se realizará ninguna espera; si hay mensajes pendientes serán despachados cuanto antes; si no hay mensajes pendientes, la función devolverá false immediatamente sin dormir.

Valores devueltos

Si un mensaje o mensajes llegan antes del tiempo límite, serán despachados y la función devolverá true. Si se agota el tiempo límite y no se procesaron mensajes, el valor devuelto será false.

User Contributed Notes

There are no user contributed notes for this page.


Imprime una definición de clase de PHP para una interfaz despachable

  • « com_message_pump
  • variant_abs »
  • PHP Manual
  • Funciones de COM
  • Imprime una definición de clase de PHP para una interfaz despachable

com_print_typeinfo

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

com_print_typeinfo — Imprime una definición de clase de PHP para una interfaz despachable

Descripción

com_print_typeinfo ( object $comobject , string $dispinterface = ? , bool $wantsink = false ) : bool

El propósito de esta función es ayudar a generar una clase esqueleto para usarla como absorción de eventos. También se puede usar para generar una copia de cualquier objeto COM, siempre que soporte lo suficiente las interfaces de introspección, y que usted sepa el nombre de la interfaz que quiere mostrar.

Parámetros

comobject

comobject debería ser una instancia de un objeto COM, o el nombre de una biblioteca de tipos (que será resuelta según el conjunto de reglas de com_load_typelib()).

dispinterface

El nombre de una interfaz descendiente de IDispatch que se quiere mostrar.

wantsink

Si se establece a true, en su lugar se mostrará la interfaz de absorción.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • com_event_sink() - Conectar eventos de un objeto COM a un objeto PHP
  • com_load_typelib() - Carga una biblioteca de tipos

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


Devuelve el valor absoluto de una variante

  • « com_print_typeinfo
  • variant_add »
  • PHP Manual
  • Funciones de COM
  • Devuelve el valor absoluto de una variante

variant_abs

(PHP 5, PHP 7, PHP 8)

variant_abs — Devuelve el valor absoluto de una variante

Descripción

variant_abs ( mixed $val ) : mixed

Devuelve el valor absoluto de una variante.

Parámetros

val

La variante.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Devuelve el valor absoluto de val.

Ver también

  • abs() - Valor absoluto

User Contributed Notes

There are no user contributed notes for this page.


"Suma" dos variantes y devuelve el resultado

  • « variant_abs
  • variant_and »
  • PHP Manual
  • Funciones de COM
  • "Suma" dos variantes y devuelve el resultado

variant_add

(PHP 5, PHP 7, PHP 8)

variant_add — "Suma" dos variantes y devuelve el resultado

Descripción

variant_add ( mixed $left , mixed $right ) : mixed

Suma left a right usando las siguientes reglas (tomadas de la biblioteca MSDN), que se corresponden a aquellas de Visual Basic:

Reglas de Adición de Variantes
Si | Entonces
Ambas expresiones son de tipo cadena | Concatenación
Una expresión es de tipo cadena y la otra un carácter | Adición
Una expresión es numérica y la otra es una cadena | Adición
Ambas expresiones son numéricas | Adición
Alguna expresión es NULL | Se devuelve NULL
Ambas expresiones están vacías | Se devuelve un subtipo integer

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Devuelve el resultado.

Ver también

  • variant_sub() - Resta el valor de la variante derecha del valor de la varienta izquierda

User Contributed Notes

There are no user contributed notes for this page.


Realiza una operación AND a nivel de bits entre dos variantes

  • « variant_add
  • variant_cast »
  • PHP Manual
  • Funciones de COM
  • Realiza una operación AND a nivel de bits entre dos variantes

variant_and

(PHP 5, PHP 7, PHP 8)

variant_and — Realiza una operación AND a nivel de bits entre dos variantes

Descripción

variant_and ( mixed $left , mixed $right ) : mixed

Realiza una operación AND a nivel de bits. Observer que esto difiere ligeramente de una operación AND normal.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Reglas de Aplicar AND a Variantes
Si left es | Si right es | entonces el resultado es
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

Ver también

  • variant_or() - Realiza una disyunción lógica de dos variantes

User Contributed Notes

There are no user contributed notes for this page.


Convertir una variante en un nuevo objeto variante de otro tipo

  • « variant_and
  • variant_cat »
  • PHP Manual
  • Funciones de COM
  • Convertir una variante en un nuevo objeto variante de otro tipo

variant_cast

(PHP 5, PHP 7, PHP 8)

variant_cast — Convertir una variante en un nuevo objeto variante de otro tipo

Descripción

variant_cast ( variant $variant , int $type ) : variant

Esta función hace una copia de variant y realiza una operación de conversión de variante para forzar a la copia a tener el tipo dado por type.

Esta función envuelve VariantChangeType() de la biblioteca COM; consulte MSDN para más información.

Parámetros

variant

La variante.

type

type debería ser una de las constantes VT_XXX.

Valores devueltos

Devuelve una variante VT_DATE.

Ver también

  • variant_set_type() - Convierte una variante en otro tipo "in situ"

User Contributed Notes

There are no user contributed notes for this page.


Concatena dos valores de variantes y devuelve el resultado

  • « variant_cast
  • variant_cmp »
  • PHP Manual
  • Funciones de COM
  • Concatena dos valores de variantes y devuelve el resultado

variant_cat

(PHP 5, PHP 7, PHP 8)

variant_cat — Concatena dos valores de variantes y devuelve el resultado

Descripción

variant_cat ( mixed $left , mixed $right ) : mixed

Concatena left con right y devuelve el resultado.

Esta función es en teoría equivalente a $left . $right.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Devuelve el resultado de la concatenación.

Ver también

  • Operadores para strings para el operador de concatenación de cadenas

User Contributed Notes

There are no user contributed notes for this page.


Compara dos variantes

  • « variant_cat
  • variant_date_from_timestamp »
  • PHP Manual
  • Funciones de COM
  • Compara dos variantes

variant_cmp

(PHP 5, PHP 7, PHP 8)

variant_cmp — Compara dos variantes

Descripción

variant_cmp ( mixed $left , mixed $right , int $lcid = ? , int $flags = ? ) : int

Compara left con right.

Esta fucnión sólo comparará valores escalares, no arrays o registros de variantes.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

lcid

Un Identificador Regional válido a usar cuando se comparan cadenas (esto afecta a la compaginación de cadenas).

flags

flags puede ser uno o más de los siguientes valores usando OR entre ellos, y afecta a la comparación de cadenas:

Banderas de Comparación de Variantes
valor | significado
NORM_IGNORECASE | Comparara de forma insensible a mayúsculas-minúsculas
NORM_IGNORENONSPACE | Ignorar caracteres que no son de espacio
NORM_IGNORESYMBOLS | Ignorar símbolos
NORM_IGNOREWIDTH | Ignorar el ancho de cadena
NORM_IGNOREKANATYPE | Ignorar el tipo Kana
NORM_IGNOREKASHIDA | Ignorar caracteras kashida arábigos

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Devuelve un valor de los siguientes:

Resultados de la Comparación de Variantes
valor | significado
VARCMP_LT | left es menor que right
VARCMP_EQ | left es igual que right
VARCMP_GT | left es mayor que right
VARCMP_NULL | left o, right o ambos son null

User Contributed Notes

There are no user contributed notes for this page.


Devuelve una representación de variante de fecha de una fecha Unix

  • « variant_cmp
  • variant_date_to_timestamp »
  • PHP Manual
  • Funciones de COM
  • Devuelve una representación de variante de fecha de una fecha Unix

variant_date_from_timestamp

(PHP 5, PHP 7, PHP 8)

variant_date_from_timestamp — Devuelve una representación de variante de fecha de una fecha Unix

Descripción

variant_date_from_timestamp ( int $timestamp ) : variant

Convierte timestamp desde un valor de fecha unix a una variante de tipo VT_DATE. Permite la interpolación más sencilla entre las partes unix de PHP y COM.

Parámetros

timestamp

Una fecha unix.

Valores devueltos

Devuelve una variante VT_DATE.

Ver también

  • variant_date_to_timestamp() - Convierte un valor de una variante de fecha/hora en una fecha Unix
  • mktime() - Obtener la marca de tiempo Unix de una fecha
  • time() - Devuelve la fecha Unix actual

User Contributed Notes

There are no user contributed notes for this page.


Convierte un valor de una variante de fecha/hora en una fecha Unix

  • « variant_date_from_timestamp
  • variant_div »
  • PHP Manual
  • Funciones de COM
  • Convierte un valor de una variante de fecha/hora en una fecha Unix

variant_date_to_timestamp

(PHP 5, PHP 7, PHP 8)

variant_date_to_timestamp — Convierte un valor de una variante de fecha/hora en una fecha Unix

Descripción

variant_date_to_timestamp ( variant $variant ) : int

Convierte variant desde un valor VT_DATE (o similar) a una fecha Unix. Permite la interoperabilidad más sencilla entre las partes Unix de PHP y COM.

Parámetros

variant

La variante.

Valores devueltos

Devuelve una fecha unix.

Ver también

  • variant_date_from_timestamp() - Devuelve una representación de variante de fecha de una fecha Unix
  • date() - Dar formato a la fecha/hora local
  • strftime() - Formatea una fecha/hora local según una configuración local

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


Devuelve el resultado de dividir dos variantes

  • « variant_date_to_timestamp
  • variant_eqv »
  • PHP Manual
  • Funciones de COM
  • Devuelve el resultado de dividir dos variantes

variant_div

(PHP 5, PHP 7, PHP 8)

variant_div — Devuelve el resultado de dividir dos variantes

Descripción

variant_div ( mixed $left , mixed $right ) : mixed

Divide left entre right y devuelve el resultado.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Reglas de División de Variantes
Si | Entonces
Ambas expresiones son de tipo cadena, fecha, carácter, booleano | Se devuelve un valor de tipo double
Una expresión es una cadena y la otra un carácter | División y se devuelve un valor de tipo double
Una expresión es numérica y la otra es una cadena | División y se devuelve un valor de tipo double
Ambas expresiones son numéricas | División y se devuelve un valor de tipo double
Alguna de las expresiones es NULL | Se devuelve NULL
right está vacía y left es cualquier otra cosa menos vacía | Se lanza una com_exception con código DISP_E_DIVBYZERO
left está vacía y right es cualquier otra cosa menos vacía | Se devuelve 0 de tipo double
Ambas expresiones están vacías | Se lanza una com_exception con código DISP_E_OVERFLOW

Ver también

  • variant_idiv() - Convierte variantes a enteros y después devuelve el resultado dividiéndolos

User Contributed Notes

There are no user contributed notes for this page.


Realiza una equivalencia a nivel de bits en dos variantes

  • « variant_div
  • variant_fix »
  • PHP Manual
  • Funciones de COM
  • Realiza una equivalencia a nivel de bits en dos variantes

variant_eqv

(PHP 5, PHP 7, PHP 8)

variant_eqv — Realiza una equivalencia a nivel de bits en dos variantes

Descripción

variant_eqv ( mixed $left , mixed $right ) : mixed

Realiza una equivalencia a nivel de bits en dos variantes.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Si cada bit de left es igual al bit correspondiente de right se devuelve true, si no se devuelve false.

User Contributed Notes

There are no user contributed notes for this page.


Devuelve la parte entera de una variante

  • « variant_eqv
  • variant_get_type »
  • PHP Manual
  • Funciones de COM
  • Devuelve la parte entera de una variante

variant_fix

(PHP 5, PHP 7, PHP 8)

variant_fix — Devuelve la parte entera de una variante

Descripción

variant_fix ( mixed $variant ) : mixed

Obtiene la parte entera de una variante.

Parámetros

variant

La variante.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Si variant es negativo, se devuelve el primer entero negativo mayor o igual que la variante, de otro modo se devuelve la parte entera del valor de variant.

Notas

Advertencia

Esta documentación está basada en la documentación de MSDN; parece que esta función o es la misma que variant_int(), o existe un error en la documentación de MSDN.

Ver también

  • variant_int() - Devuelve la parte entera de una variante
  • variant_round() - Redondea una variante al número de lugares decimales especificado
  • floor() - Redondear fracciones hacia abajo
  • ceil() - Redondear fracciones hacia arriba
  • round() - Redondea un float

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el tipo de un objeto variante

  • « variant_fix
  • variant_idiv »
  • PHP Manual
  • Funciones de COM
  • Devuelve el tipo de un objeto variante

variant_get_type

(PHP 5, PHP 7, PHP 8)

variant_get_type — Devuelve el tipo de un objeto variante

Descripción

variant_get_type ( variant $variant ) : int

Devuelve el tipo de un objeto variante.

Parámetros

variant

El objeto variante.

Valores devueltos

Esta función devuelve un valor de tipo integer que indica el tipo de variant, que puede ser una instancia de las clases COM, DOTNET o VARIANT. El valor devuelto puede ser comparado con una de las constantes VT_XXX.

El valor devuelto para objetos COM y DOTNET será normalmente VT_DISPATCH; la única razón de que esta función funcione con estas clases es que COM y DOTNET son descendientes de VARIANT.

En versiones de PHP anteriores a 5 se podría obtener esta información ÚNICAMENTE desde instancias de la clase VARIANT, leyendo una propiedad type falsa. Véase la clase VARIANT para más información sobre esto.

User Contributed Notes

There are no user contributed notes for this page.


Convierte variantes a enteros y después devuelve el resultado dividiéndolos

  • « variant_get_type
  • variant_imp »
  • PHP Manual
  • Funciones de COM
  • Convierte variantes a enteros y después devuelve el resultado dividiéndolos

variant_idiv

(PHP 5, PHP 7, PHP 8)

variant_idiv — Convierte variantes a enteros y después devuelve el resultado dividiéndolos

Descripción

variant_idiv ( mixed $left , mixed $right ) : mixed

Convierte left y right a valores de tipo integer, y después realiza la división entera.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Reglas de División Entera de Variantes
Si | Entonces
Ambas expresiones son de tipo cadena, fecha, carácter, booleano | División y se devuelve un entero
Una expresión es de tipo cadena y la otra un carácter | División
Una expresión es numérica y la otra es una cadena | División
Ambas expresiones son numéricas | División
Alguna de las expresiones es NULL | Se devuelve NULL
Ambas expresiones están vacías | Se lanza una com_exception con código DISP_E_DIVBYZERO

Ver también

  • variant_div() - Devuelve el resultado de dividir dos variantes

User Contributed Notes

There are no user contributed notes for this page.


Realiza una implicación a nivel de bits de dos variantes

  • « variant_idiv
  • variant_int »
  • PHP Manual
  • Funciones de COM
  • Realiza una implicación a nivel de bits de dos variantes

variant_imp

(PHP 5, PHP 7, PHP 8)

variant_imp — Realiza una implicación a nivel de bits de dos variantes

Descripción

variant_imp ( mixed $left , mixed $right ) : mixed

Realiza una operación de implicación a nivel de bits.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Tabla de Implicación de Variantes
Si left es | Si right es | entonces el resultado es
true | true | true
true | false | true
true | null | true
false | true | true
false | false | true
false | null | true
null | true | true
null | false | null
null | null | null

User Contributed Notes

There are no user contributed notes for this page.


Devuelve la parte entera de una variante

  • « variant_imp
  • variant_mod »
  • PHP Manual
  • Funciones de COM
  • Devuelve la parte entera de una variante

variant_int

(PHP 5, PHP 7, PHP 8)

variant_int — Devuelve la parte entera de una variante

Descripción

variant_int ( mixed $variant ) : mixed

Obtiene la parte entera de una variante.

Parámetros

variant

La variante.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Si variant es negativo, se devuelve el primer entero negativo mayor o igual a la variante, de otro modo se devuelve la parte entera del valor de variant.

Ver también

  • variant_fix() - Devuelve la parte entera de una variante
  • variant_round() - Redondea una variante al número de lugares decimales especificado
  • floor() - Redondear fracciones hacia abajo
  • ceil() - Redondear fracciones hacia arriba
  • round() - Redondea un float

User Contributed Notes

There are no user contributed notes for this page.


Divide dos variantes y devuelve sólo el resto

  • « variant_int
  • variant_mul »
  • PHP Manual
  • Funciones de COM
  • Divide dos variantes y devuelve sólo el resto

variant_mod

(PHP 5, PHP 7, PHP 8)

variant_mod — Divide dos variantes y devuelve sólo el resto

Descripción

variant_mod ( mixed $left , mixed $right ) : mixed

Divide left entre right y devuelve el resto.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Devuelve el resto de la división.

Ver también

  • variant_div() - Devuelve el resultado de dividir dos variantes
  • variant_idiv() - Convierte variantes a enteros y después devuelve el resultado dividiéndolos

User Contributed Notes

There are no user contributed notes for this page.


Multiplica los valores de dos variantes

  • « variant_mod
  • variant_neg »
  • PHP Manual
  • Funciones de COM
  • Multiplica los valores de dos variantes

variant_mul

(PHP 5, PHP 7, PHP 8)

variant_mul — Multiplica los valores de dos variantes

Descripción

variant_mul ( mixed $left , mixed $right ) : mixed

Multiplica left por right.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Los valores booleanos son convertidos a -1 para false y 0 para true.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Reglas de Multiplicación de Variantes
Si | Entonces
Ambas expresiones son de tipo cadena, fecha, carácter, boolean | Multiplicación
Una expresión es de tipo cadena y la otra un carácter | Multiplicación
Una expresión es numérica y la otra una cadena | Multiplicación
Ambas expresiones son numéricas | Multiplicación
Alguna de las expresiones es NULL | Se devuelve NULL
Ambas expresiones están vacías | Se devuelve una cadena vacía

Ver también

  • variant_div() - Devuelve el resultado de dividir dos variantes
  • variant_idiv() - Convierte variantes a enteros y después devuelve el resultado dividiéndolos

User Contributed Notes

There are no user contributed notes for this page.


Realiza una negación lógica de una variante

  • « variant_mul
  • variant_not »
  • PHP Manual
  • Funciones de COM
  • Realiza una negación lógica de una variante

variant_neg

(PHP 5, PHP 7, PHP 8)

variant_neg — Realiza una negación lógica de una variante

Descripción

variant_neg ( mixed $variant ) : mixed

Realiza una negación lógica de variant.

Parámetros

variant

La variante.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Devuelve el resultado de la negación lógica.

User Contributed Notes

There are no user contributed notes for this page.


Realiza una negación NOT a nivel de bits en una variante

  • « variant_neg
  • variant_or »
  • PHP Manual
  • Funciones de COM
  • Realiza una negación NOT a nivel de bits en una variante

variant_not

(PHP 5, PHP 7, PHP 8)

variant_not — Realiza una negación NOT a nivel de bits en una variante

Descripción

variant_not ( mixed $variant ) : mixed

Realiza una negación NOT a nivel de bits en variant y devuelve el resultado.

Parámetros

variant

La variante.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Devuelve la negación NOT a nivel de bits. Si variant es null, el resultado también será null.

User Contributed Notes

There are no user contributed notes for this page.


Realiza una disyunción lógica de dos variantes

  • « variant_not
  • variant_pow »
  • PHP Manual
  • Funciones de COM
  • Realiza una disyunción lógica de dos variantes

variant_or

(PHP 5, PHP 7, PHP 8)

variant_or — Realiza una disyunción lógica de dos variantes

Descripción

variant_or ( mixed $left , mixed $right ) : mixed

Realiza una operación OR a nivel de bits. Observer que esto difiere ligeramente de una operación OR normal.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Reglas del uso de OR de Variantes
Si left es | Si right es | entonces el resultado es
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

Ver también

  • variant_and() - Realiza una operación AND a nivel de bits entre dos variantes
  • variant_xor() - Realiza una exclución lógica de dos variantes

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el resultado de realizar la exponenciación con dos variantes

  • « variant_or
  • variant_round »
  • PHP Manual
  • Funciones de COM
  • Devuelve el resultado de realizar la exponenciación con dos variantes

variant_pow

(PHP 5, PHP 7, PHP 8)

variant_pow — Devuelve el resultado de realizar la exponenciación con dos variantes

Descripción

variant_pow ( mixed $left , mixed $right ) : mixed

Devuelve el resultado de left a la potencia de right.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Devuelve el resultado de left a la potencia right.

Ver también

  • pow() - Expresión exponencial

User Contributed Notes

There are no user contributed notes for this page.


Redondea una variante al número de lugares decimales especificado

  • « variant_pow
  • variant_set_type »
  • PHP Manual
  • Funciones de COM
  • Redondea una variante al número de lugares decimales especificado

variant_round

(PHP 5, PHP 7, PHP 8)

variant_round — Redondea una variante al número de lugares decimales especificado

Descripción

variant_round ( mixed $variant , int $decimals ) : mixed

Devuelve el valor de variant redondeado a decimals lugares decimales.

Parámetros

variant

La variante.

decimals

Número de luguras decimales.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Devuelve el valor redondeado.

Ver también

  • round() - Redondea un float

User Contributed Notes

There are no user contributed notes for this page.


Convierte una variante en otro tipo "in situ"

  • « variant_round
  • variant_set »
  • PHP Manual
  • Funciones de COM
  • Convierte una variante en otro tipo "in situ"

variant_set_type

(PHP 5, PHP 7, PHP 8)

variant_set_type — Convierte una variante en otro tipo "in situ"

Descripción

variant_set_type ( variant $variant , int $type ) : void

Esta función es similar a variant_cast() excepto que la variante es modificada "in situ"; no se crea una nueva variante. Los parámetros para esta función tienen significados idénticos para aquellos de variant_cast().

Parámetros

variant

La variante.

type

Valores devueltos

No devuelve ningún valor.

Ver también

  • variant_cast() - Convertir una variante en un nuevo objeto variante de otro tipo

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.


Asigna un nuevo valor para un objeto variante

  • « variant_set_type
  • variant_sub »
  • PHP Manual
  • Funciones de COM
  • Asigna un nuevo valor para un objeto variante

variant_set

(PHP 5, PHP 7, PHP 8)

variant_set — Asigna un nuevo valor para un objeto variante

Descripción

variant_set ( variant $variant , mixed $value ) : void

Convierte value a una variante y lo asigna al objeto variant; no se crean un nuevo objeto variante, y el valor antiguo de variant es liberado.

Parámetros

variant

La variante.

value

Valores devueltos

No devuelve ningún valor.

User Contributed Notes

There are no user contributed notes for this page.


Resta el valor de la variante derecha del valor de la varienta izquierda

  • « variant_set
  • variant_xor »
  • PHP Manual
  • Funciones de COM
  • Resta el valor de la variante derecha del valor de la varienta izquierda

variant_sub

(PHP 5, PHP 7, PHP 8)

variant_sub — Resta el valor de la variante derecha del valor de la varienta izquierda

Descripción

variant_sub ( mixed $left , mixed $right ) : mixed

Resta right de left.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Reglas de Sustracción de Variantes
Si | Entonces
Ambas expresiones son de tipo cadena | Resta
Una expresión es de tipo cadena y la otra un carácter | Resta
Una expresión es numérica y la otra una cadena | Resta
Ambas expresiones son numéricas | Resta
Alguna de las expresiones es NULL | Se devuelve NULL
Ambas expresiones están vacías | Se devuelve una cadena vacía

Ver también

  • variant_add() - "Suma" dos variantes y devuelve el resultado

User Contributed Notes

There are no user contributed notes for this page.


Realiza una exclución lógica de dos variantes

  • « variant_sub
  • win32service »
  • PHP Manual
  • Funciones de COM
  • Realiza una exclución lógica de dos variantes

variant_xor

(PHP 5, PHP 7, PHP 8)

variant_xor — Realiza una exclución lógica de dos variantes

Descripción

variant_xor ( mixed $left , mixed $right ) : mixed

Realiza una exclución lógica.

Parámetros

left

El operando izquierdo.

right

El operando derecho.

Nota:

Al igual que con todas las funciones aritméticas variantes, los parámetros de esta función pueden ser tanto un tipo nativo de PHP (integer, string, de punto flotante, boolean o null), o una instancia de una clase COM, VARIANT o DOTNET. Los tipos nativos de PHP serán convertidos en variantes usando las mismas reglas tal como se encuentran en el constructor para la clase VARIANT. Los objetos COM y DOTNET tomarán el valor de sus propiedades predeterminadas adoptadas y lo utilizarán como el valor variante.

Las funciones aritméticas variantes son wrappers alrededor de las funciones con nombres similares en la librería COM; para más información sobre estas funciones, consulte la librería MSDN. Las funciones de PHP tienen nombres ligeramente diferentes; por ejemplo, variant_add() en PHP corresponde a VarAdd() en la documentación MSDN.

Valores devueltos

Reglas de Exclusión de Variantes
Si left es | Si right es | entonces el resultado es
true | true | false
true | false | true
false | true | true
false | false | false
null | null | null

Ver también

  • variant_or() - Realiza una disyunción lógica de dos variantes
  • variant_and() - Realiza una operación AND a nivel de bits entre dos variantes

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

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
    • Máscara de Bits de Tipo Servicio de Win32Service
    • Constantes de Estado de Servicio de Win32Service
    • Constantes de Mensajes de Control de Servicio de Win32Service
    • Máscaras de Bits Aceptadas de Mensajes de Control de Servicio de Win32Service
    • Constantes de Tipo Inicio de Servicio de Win32Service
    • Constantes de Control de Errores de Servicio de Win32Service
    • Constantes de Banderas de Servicio de Win32Service
    • Códigos de Error de Win32
    • Clases base de prioridad Win32
  • Ejemplos
  • Funciones win32service
    • win32_continue_service — Reanuda un servicio pausado
    • win32_create_service — Crea una nueva entrada de servicio en la base de datos del ACS
    • win32_delete_service — Borra una entrada de servicio de la base de datos del ACS
    • win32_get_last_control_message — Devuelve el último mensaje de control que fue enviado a este servicio
    • win32_pause_service — Pausa un servicio
    • win32_query_service_status — Pregunta sobre el estado de un servicio
    • win32_send_custom_control — Enviar un control personalizado al servicio
    • win32_set_service_exit_code — Define o devuelve el código de salida para el servicio en curso
    • win32_set_service_exit_mode — Define o devuelve el modo de salida para el servicio en curso
    • win32_set_service_status — Actualiza el estado del servicio
    • win32_start_service_ctrl_dispatcher — Registra el script con el ACS, por lo que puede actuar como el servicio con el nombre dado
    • win32_start_service — Inicia un servicio
    • win32_stop_service — Detiene un servicio

User Contributed Notes

jbnahan at php dot net 12-Jun-2019 11:45
The version 0.4 allow now to send and receive a custom control code.
gospodin dot p dot zh at gmail dot com 04-Oct-2012 06:49
win32service extension does not realize very important (as for me) method of ServiceBase::OnCustomCommand
----
http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.oncustomcommand.aspx
"OnCustomCommand lets you specify additional functionality beyond starting, stopping, pausing and continuing services."


Introducción

La extensión win32service es una extensión específica de Windows que permite a PHP comunicarse con el Administrador de Control de Servicios para iniciar, detener, registrar y dejar de registrar servicios, e incluso permite a los scripts de PHP ejecutarse como un servicio.

User Contributed Notes

There are no user contributed notes for this page.


Requerimientos

Windows NT, Windows 2000, Windows XP o Windows Server 2003. Cualquier versión de Windows derivada de Windows NT debería ser compatible.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

Se puede encontrar información para la instalación de esta extensión PECL en el capítulo del manual titulado Instalación de extensiones PECL. Se puede encontrar información adicional, tal como nuevos lanzamientos, descargas, ficheros fuente, información de mantenimiento, y un CHANGELOG, aquí: » 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.


Constantes predefinidas

Tabla de contenidos

  • Máscara de Bits de Tipo Servicio de Win32Service
  • Constantes de Estado de Servicio de Win32Service
  • Constantes de Mensajes de Control de Servicio de Win32Service
  • Máscaras de Bits Aceptadas de Mensajes de Control de Servicio de Win32Service
  • Constantes de Tipo Inicio de Servicio de Win32Service
  • Constantes de Control de Errores de Servicio de Win32Service
  • Constantes de Banderas de Servicio de Win32Service
  • Códigos de Error de Win32
  • Clases base de prioridad Win32

Estas constantes están definidas por esta extensión y estarán disponibles sólo cuando la extensión haya sido compilada con PHP, o bien sea cargada dinámicamente en ejecución.

User Contributed Notes

There are no user contributed notes for this page.


Máscara de Bits de Tipo Servicio de Win32Service

  • « Constantes predefinidas
  • Constantes de Estado de Servicio de Win32Service »
  • PHP Manual
  • Constantes predefinidas
  • Máscara de Bits de Tipo Servicio de Win32Service
Máscara de Bits de Tipo Servicio de Win32Service
Constante | Valor | Descripción
WIN32_SERVICE_WIN32_OWN_PROCESS | 0x00000010 | El servicio se ejecuta en su propio proceso.
WIN32_SERVICE_INTERACTIVE_PROCESS | 0x00000100 | El servicio puede interactuar con el escritorio. Esta opción no está disponible en Windows Vista o posterior.
WIN32_SERVICE_WIN32_OWN_PROCESS_INTERACTIVE | 0x00000110 | El servicio se ejecuta en su propio procso y puede interactuar con el escritorio. Esta opción no está disponible en Windows Vista o posterior.

User Contributed Notes

There are no user contributed notes for this page.


Constantes de Estado de Servicio de Win32Service

  • « Máscara de Bits de Tipo Servicio de Win32Service
  • Constantes de Mensajes de Control de Servicio de Win32Service »
  • PHP Manual
  • Constantes predefinidas
  • Constantes de Estado de Servicio de Win32Service
Constantes de Estado de Servicio de Win32Service
Constante | Valor | Descripción
WIN32_SERVICE_CONTINUE_PENDING | 0x00000005 | La continuación del servicio está pendiente.
WIN32_SERVICE_PAUSE_PENDING | 0x00000006 | La pausa del servicio está pendiente.
WIN32_SERVICE_PAUSED | 0x00000007 | El servicio está pausado.
WIN32_SERVICE_RUNNING | 0x00000004 | El servicio está en ejecución.
WIN32_SERVICE_START_PENDING | 0x00000002 | El servicio está iniciado.
WIN32_SERVICE_STOP_PENDING | 0x00000003 | El servicio está detenido.
WIN32_SERVICE_STOPPED | 0x00000001 | El servicio no está en ejecución.

User Contributed Notes

There are no user contributed notes for this page.


Constantes de Mensajes de Control de Servicio de Win32Service

  • « Constantes de Estado de Servicio de Win32Service
  • Máscaras de Bits Aceptadas de Mensajes de Control de Servicio de Win32Service »
  • PHP Manual
  • Constantes predefinidas
  • Constantes de Mensajes de Control de Servicio de Win32Service
Constantes de Mensajes de Control de Servicio de Win32Service
Constante | Valor | Descripción
WIN32_SERVICE_CONTROL_CONTINUE | 0x00000003 | Notifica a un servicio pausado que debería reanudarse.
WIN32_SERVICE_CONTROL_INTERROGATE | 0x00000004 | Notifica a un servicio que debería informar de su información de estado al administrador de control de servicios.
WIN32_SERVICE_CONTROL_PAUSE | 0x00000002 | Notifica a un servicio que debería pausarse.
WIN32_SERVICE_CONTROL_PRESHUTDOWN | 0x0000000F | Notifica a un servicio que el sistema se apagará. Un servicio que maneja esta notificación bloquea el apagado del systema hasta que el servicio se detenga o el intervalo de tiempo límite de pre-apagado expira. Este valor no está soportado por Windows Server 2003 y Windows XP/2000.
WIN32_SERVICE_CONTROL_SHUTDOWN | 0x00000005 | Notifica a un servicio que el sistema se está apagando, por lo que el servicio puede realizar tareas de limpieza. Si un servicio acepta este código de cotrol, debe detenerse después de realizar sus tareas de limpieza. Después de que el SCM envíe este código de control, no se enviarán otros códigos de control al servicio.
WIN32_SERVICE_CONTROL_STOP | 0x00000001 | Notifica a un servicio que debería detenerse.

User Contributed Notes

There are no user contributed notes for this page.


Máscaras de Bits Aceptadas de Mensajes de Control de Servicio de Win32Service

  • « Constantes de Mensajes de Control de Servicio de Win32Service
  • Constantes de Tipo Inicio de Servicio de Win32Service »
  • PHP Manual
  • Constantes predefinidas
  • Máscaras de Bits Aceptadas de Mensajes de Control de Servicio de Win32Service
Máscaras de Bits Aceptadas de Mensajes de Control de Servicio de Win32Service
Constante | Valor | Descripción
WIN32_SERVICE_ACCEPT_PAUSE_CONTINUE | 0x00000002 | El servicio puede ser pausado y continuado. Este código de control permite al servicio recibir notificaciones WIN32_SERVICE_CONTROL_PAUSE y WIN32_SERVICE_CONTROL_CONTINUE.
WIN32_SERVICE_ACCEPT_PRESHUTDOWN | 0x00000100 | El servicio puede realizar tareas de pre-apagado. Este código de control habilita al servicio a recibir notificaciones WIN32_SERVICE_CONTROL_PRESHUTDOWN. Este valor no está soportado por Windows Server 2003 y Windows XP/2000.
WIN32_SERVICE_ACCEPT_SHUTDOWN | 0x00000004 | El servicio es notificado cuando sucede el apagado del systema. Este código de control permite al servicio recibir notificaciones WIN32_SERVICE_CONTROL_SHUTDOWN.
WIN32_SERVICE_ACCEPT_STOP | 0x00000001 | El servicio puede ser detenido. Este código de control permite al servicio recibir notificaciones WIN32_SERVICE_CONTROL_STOP.

User Contributed Notes

There are no user contributed notes for this page.


Constantes de Tipo Inicio de Servicio de Win32Service

  • « Máscaras de Bits Aceptadas de Mensajes de Control de Servicio de Win32Service
  • Constantes de Control de Errores de Servicio de Win32Service »
  • PHP Manual
  • Constantes predefinidas
  • Constantes de Tipo Inicio de Servicio de Win32Service
Constantes de Tipo Inicio de Servicio de Win32Service
Constante | Valor | Descripción
WIN32_SERVICE_AUTO_START | 0x00000002 | Un servicio iniciado automáticamente por el administrador de control de servicios durante el inicio del sistema.
WIN32_SERVICE_DEMAND_START | 0x00000003 | Un servicio iniciado por el administrador de control de servicios cuando un proceso llama a la función StartService.
WIN32_SERVICE_DISABLED | 0x00000004 | Un servicio que no puede ser iniciado. Intentar iniciar el servicio resulta en el código de error WIN32_ERROR_SERVICE_DISABLED.

User Contributed Notes

There are no user contributed notes for this page.


Constantes de Control de Errores de Servicio de Win32Service

  • « Constantes de Tipo Inicio de Servicio de Win32Service
  • Constantes de Banderas de Servicio de Win32Service »
  • PHP Manual
  • Constantes predefinidas
  • Constantes de Control de Errores de Servicio de Win32Service
Constantes de Control de Errores de Servicio de Win32Service
Constante | Valor | Descripción
WIN32_SERVICE_ERROR_IGNORE | 0x00000000 | El programa de inicio ignora el error y continua la operación de inicio.
WIN32_SERVICE_ERROR_NORMAL | 0x00000001 | El programa de inicio registra el error en el registro de sucesos pero continua la operación de inicio.

User Contributed Notes

There are no user contributed notes for this page.


Constantes de Banderas de Servicio de Win32Service

  • « Constantes de Control de Errores de Servicio de Win32Service
  • Códigos de Error de Win32 »
  • PHP Manual
  • Constantes predefinidas
  • Constantes de Banderas de Servicio de Win32Service
Constantes de Banderas de Servicio de Win32Service
Constante | Valor | Descripción
WIN32_SERVICE_RUNS_IN_SYSTEM_PROCESS | 0x00000001 | El servicio de ejecuta en un proceso de sistema que siempre debe estar ejecutándose.

User Contributed Notes

There are no user contributed notes for this page.


Códigos de Error de Win32

  • « Constantes de Banderas de Servicio de Win32Service
  • Clases base de prioridad Win32 »
  • PHP Manual
  • Constantes predefinidas
  • Códigos de Error de Win32
Códigos de Error de Win32
Constante | Valor | Descripción
WIN32_ERROR_ACCESS_DENIED | 0x00000005 | El gestor a la base de datos de SCM no tiene los derechos de acceso apropiados.
WIN32_ERROR_CIRCULAR_DEPENDENCY | 0x00000423 | Se especificó una dependencia de servicio circular.
WIN32_ERROR_DATABASE_DOES_NOT_EXIST | 0x00000429 | La base de datos especificada no existe.
WIN32_ERROR_DEPENDENT_SERVICES_RUNNING | 0x0000041B | El servicio no puede ser detenido porque otros servicios en ejecución dependen de él.
WIN32_ERROR_DUPLICATE_SERVICE_NAME | 0x00000436 | El nombre mostrado ya existe en la base de datos del administrador de control de servicios como nombre de servicio o como otro nombre mostrado.
WIN32_ERROR_FAILED_SERVICE_CONTROLLER_CONNECT | 0x00000427 | El error es devuelto si el programa está siendo ejecutado como aplicación de consola en vez de como servicio. Si el programa será ejecutado como aplicación de consola para propósitos de depuración, estructúrelo de tal manera que el código específico de servicio no sea llamado.
WIN32_ERROR_INSUFFICIENT_BUFFER | 0x0000007A | El buffer es demasiado pequeño para la estructura de estado del servicio. No se escribió nada a la estructura.
WIN32_ERROR_INVALID_DATA | 0x0000000D | La estructura de estado del servicio especificado no es válida.
WIN32_ERROR_INVALID_HANDLE | 0x00000006 | El gestor a la base de datos del administrador de control de servicios especificada no es válida.
WIN32_ERROR_INVALID_LEVEL | 0x0000007C | El parámetro InfoLevel contiene un valor no soportado.
WIN32_ERROR_INVALID_NAME | 0x0000007B | El nombre del servicio especificado no es válido.
WIN32_ERROR_INVALID_PARAMETER | 0x00000057 | Se especificó un parámetro no válido.
WIN32_ERROR_INVALID_SERVICE_ACCOUNT | 0x00000421 | El nombre de cuenta de usuario especificado en el parámero user no existe. Véase win32-create_service().
WIN32_ERROR_INVALID_SERVICE_CONTROL | 0x0000041C | El código de control solicitado no es válido, o es inaceptable para el servicio.
WIN32_ERROR_PATH_NOT_FOUND | 0x00000003 | No se pudo encontrar el fichero binario del servicio.
WIN32_ERROR_SERVICE_ALREADY_RUNNING | 0x00000420 | Ya se está ejecutando una instancia del servicio.
WIN32_ERROR_SERVICE_CANNOT_ACCEPT_CTRL | 0x00000425 | El código de control solicitado no puede ser enviado al servicio porque el estado del servicio es WIN32_SERVICE_STOPPED, WIN32_SERVICE_START_PENDING, o WIN32_SERVICE_STOP_PENDING.
WIN32_ERROR_SERVICE_DATABASE_LOCKED | 0x0000041F | La base de datos está bloqueada.
WIN32_ERROR_SERVICE_DEPENDENCY_DELETED | 0x00000433 | El servicio depende de un servicio que no existe o que ha sido marcado para su eleminación.
WIN32_ERROR_SERVICE_DEPENDENCY_FAIL | 0x0000042C | El servicio depende de otro servicio que falló al iniciarse.
WIN32_ERROR_SERVICE_DISABLED | 0x00000422 | El servicio ha sido deshabilitado.
WIN32_ERROR_SERVICE_DOES_NOT_EXIST | 0x00000424 | El servicio especificado no existe como servicio instalado.
WIN32_ERROR_SERVICE_EXISTS | 0x00000431 | El servicio especificado ya existe en esta base de datos.
WIN32_ERROR_SERVICE_LOGON_FAILED | 0x0000042D | El servicio no se inició debeido a un fallo de identificación. Este error sucede si el servicio está configurado para ejecutarse bajo una cuenta que no tiene el derecho "Log on as a service".
WIN32_ERROR_SERVICE_MARKED_FOR_DELETE | 0x00000430 | El servicio especificado ya ha sido marcado para su eliminación.
WIN32_ERROR_SERVICE_NO_THREAD | 0x0000041E | No se pudo crear un hilo para el servicio.
WIN32_ERROR_SERVICE_NOT_ACTIVE | 0x00000426 | El servicio no ha sido iniciado.
WIN32_ERROR_SERVICE_REQUEST_TIMEOUT | 0x0000041D | El proceso para el servicio se inició, pero no llamó a StartServiceCtrlDispatcher, o el hilo que llamó a StartServiceCtrlDispatcher puede estar bloqueado en una función de gestor de control.
WIN32_ERROR_SHUTDOWN_IN_PROGRESS | 0x0000045B | El sistema se está apagando; esta función no puede ser llamada.
WIN32_NO_ERROR | 0x00000000 | Sin error.

User Contributed Notes

There are no user contributed notes for this page.


Clases base de prioridad Win32

  • « Códigos de Error de Win32
  • Ejemplos »
  • PHP Manual
  • Constantes predefinidas
  • Clases base de prioridad Win32
Clases base de prioridad Win32
Constante | Valor | Descripción
WIN32_ABOVE_NORMAL_PRIORITY_CLASS | 0x00008000 | Procesos que tienen una prioridad superior a WIN32_NORMAL_PRIORITY_CLASS pero inferior a WIN32_HIGH_PRIORITY_CLASS.
WIN32_BELOW_NORMAL_PRIORITY_CLASS | 0x00004000 | Procesos que tienen una prioridad superior a WIN32_IDLE_PRIORITY_CLASS pero inferior a WIN32_NORMAL_PRIORITY_CLASS.
WIN32_HIGH_PRIORITY_CLASS | 0x00000080 | Procesos que realizan tareas de tiempo crítico que deben ser ejecutadas inmediatamente. Los hilos de procesos anticipan a los hilos normales o procesos inactivos. Un ejemplo es la lista de procesos, que debe responder rápidamente cuando es llamado por el usuario, sin importar la carga del sistema operativo. Tenga mucho cuidado cuando use clases de procesos de alta prioridad, debido aque puede requerir un alto consumo de CPU disponible todo el tiempo.
WIN32_IDLE_PRIORITY_CLASS | 0x00000040 | Procesos cuyos hilos de ejecución corren sólo cuando el sistema está inactivo. Los hilo del proceso son antepuestos por los hilos de cualquier otro proceso corriendo en una clase de prioridad superior. Un ejemplo es el Protector de Pantallas. La clase de prioridad inactiva es heredado por sus procesos derivados.
WIN32_NORMAL_PRIORITY_CLASS | 0x00000020 | Procesos sin necesidad de establecer prioridades especiales.
WIN32_REALTIME_PRIORITY_CLASS | 0x00000100 | Procesos que tienen la mayor prioridad posible. Los hilos del proceso se anteponen a los hilos de todas los otros procesos, incluyendo los procesos del sistema operativo para realizar tareas importantes. Por ejemplo, un proceso en tiempo real que ejecuta por más que un breve intervalo puede causar que el cache del disco no se vacíe o provoque que el ratón no responda.

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

Ejemplo #1 Registrar un script de PHP para ejecutarlo como un servicio

<?php
win32_create_service(array(
    'service'     => 'dummyphp',                                          # el nombre de su servicio
    'display'     => 'ejemplo de servicio PHP',                           # descripción abreviada
    'description' => 'Este es un servicio de Windows creado usando PHP.', # descripción larga
    'params'      => '"' . __FILE__ . '"  run',                           # ruta del script y parámetros
));
?>

Ejemplo #2 Dejar de registrar un servicio

<?php
win32_delete_service('dummyphp');
?>

Ejemplo #3 Ejecutar como un servicio

<?php
if ($argv[1] == 'run') {
  win32_start_service_ctrl_dispatcher('dummyphp');

  while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
    # hacer su trabajo aquí.
    # intente no tomar más de 30 segundos antes de ejecutar de nuevo
    # el bucle
  }
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Funciones win32service

Tabla de contenidos

  • win32_continue_service — Reanuda un servicio pausado
  • win32_create_service — Crea una nueva entrada de servicio en la base de datos del ACS
  • win32_delete_service — Borra una entrada de servicio de la base de datos del ACS
  • win32_get_last_control_message — Devuelve el último mensaje de control que fue enviado a este servicio
  • win32_pause_service — Pausa un servicio
  • win32_query_service_status — Pregunta sobre el estado de un servicio
  • win32_send_custom_control — Enviar un control personalizado al servicio
  • win32_set_service_exit_code — Define o devuelve el código de salida para el servicio en curso
  • win32_set_service_exit_mode — Define o devuelve el modo de salida para el servicio en curso
  • win32_set_service_status — Actualiza el estado del servicio
  • win32_start_service_ctrl_dispatcher — Registra el script con el ACS, por lo que puede actuar como el servicio con el nombre dado
  • win32_start_service — Inicia un servicio
  • win32_stop_service — Detiene un servicio

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

?>


Reanuda un servicio pausado

  • « Funciones win32service
  • win32_create_service »
  • PHP Manual
  • Funciones win32service
  • Reanuda un servicio pausado

win32_continue_service

(PECL win32service >=0.1.0)

win32_continue_service — Reanuda un servicio pausado

Descripción

win32_continue_service ( string $servicename , string $machine = ? ) : int

Reanua un servicio pausado nominado. Se necesitan privilegios administrativos.

Parámetros

servicename

El nombre corto del servicio.

machine

Nombre opcional de la máquina. Si se omite, se usa el nombre de la máquina local.

Valores devueltos

Devuelve WIN32_NO_ERROR en caso de éxito, false si hay un problema con los parámetros o Código de error Win32 en caso de error.

Ver también

  • win32_start_service() - Inicia un servicio
  • Códigos de Error Win32

User Contributed Notes

There are no user contributed notes for this page.


Crea una nueva entrada de servicio en la base de datos del ACS

  • « win32_continue_service
  • win32_delete_service »
  • PHP Manual
  • Funciones win32service
  • Crea una nueva entrada de servicio en la base de datos del ACS

win32_create_service

(PECL win32service >=0.1.0)

win32_create_service — Crea una nueva entrada de servicio en la base de datos del ACS

Descripción

win32_create_service ( array $details , string $machine = ? ) : mixed

Parámetros

details

Una matriz con los detalles del servicio:

service

El nombre corto del servicio. Éste es el nombre que se debe usar para controlar el servicio utilizando el comando net. El servicio debe ser único (dos servicios no pueden compartir el mismo nombre), y lo ideal sería evitar que el nombre contenga espacios.

display

El nombre para mostrar del servicio. Éste es el nombre que se verá en la Aplicación de Servicios.

description

La descripción larga del servicio. Ésta es la descripción que verá en el Services Applet.

user

El nombre de la cuenta de usuario bajo la cuál se quiere ejecutar el servicio. Si se omite, el servicio se ejecutará como la cuenta LocalSystem. Si se especifica el nombre de usuario, también se debe proporcionar una contraseña.

password

La contraseña que se corresponde con user.

path

La ruta completa de módulo ejecutable que será lanzado cuando el servicio es iniciado. Si se omite, se usará la ruta del proceso de PHP actual.

params

Parámetros de línea de comandos a pasar al servicio cuando se inicia. Si quiere ejecutar un script de PHP como un servicio, el primer parámetro debería ser la ruta completa del script de PHP que intenta ejecutar. Si el nombre del script o la ruta contiene espacios encierre la ruta completa del script PHP con ".

load_order

Controla el orden de carga. Ésto aún no está completamente soportado.

svc_type

Establece el tipo de servicio. Si se omite, el valor por defecto es WIN32_SERVICE_WIN32_OWN_PROCESS. No cambie esto a menos que sepa lo que está haciendo.

start_type

Especifica cómo debería iniciarse el servicio. Por defecto es WIN32_SERVICE_AUTO_START lo que significa que el servicio será lanzado cuando se encienda la máquina.

error_control

Informa al ACS qué debería hacer cuando detecta un problema con el servicio. Por defecto es WIN32_SERVER_ERROR_IGNORE. El cambio de este valor no está aún soportado completamente.

delayed_start

Si delayed_start está establecido a true, informará al SCM que este servicio debería ser iniciado después que otros servicios con autoinicio, más una pequeña demora.

Cualquier servicio puede ser marcado como un servicio con autoinicio demorado; sin embargo este ajuste no tiene efecto a menos que el parámetro start_type del servicio sea WIN32_SERVICE_AUTO_START.

Este ajuste sólo es aplicable en Windows Vista y Windows Server 2008 o superior.

base_priority

Para reducir el impacto en el uso del procesador, puede ser necesario para establecer una prioridad base más baja de lo normal.

base_priority puede establecerse a una de las constantes definidas en Clases de Prioridad Base de Win32.

machine

El nombre opcional de la máquina en la que quiere crear el servicio. Si se omite, se usará la máquina local.

Valores devueltos

Devuelve WIN32_NO_ERROR en caso de éxito, false si hay un problema con los parámetros o Código de error Win32 en caso de error.

Ejemplos

Ejemplo #1 Un ejemplo de win32_create_service()

Crear un servicio con el nombre abreviado 'dummyphp'.

<?php
$x = win32_create_service(array(
    'service'     => 'dummyphp',                                          # el nombre de su servicio
    'display'     => 'ejemplo de servicio PHP',                           # descripción abreviada
    'description' => 'Este es un servicio de Windows creado usando PHP.', # descripción larga
    'params'      => '"' . __FILE__ . '"  run',                           # ruta del script y parámetros
));
debug_zval_dump($x);
?>

Ver también

  • win32_delete_service() - Borra una entrada de servicio de la base de datos del ACS
  • Clases de Prioridad Base de Win32
  • Códigos de Error de 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


Borra una entrada de servicio de la base de datos del ACS

  • « win32_create_service
  • win32_get_last_control_message »
  • PHP Manual
  • Funciones win32service
  • Borra una entrada de servicio de la base de datos del ACS

win32_delete_service

(PECL win32service >=0.1.0)

win32_delete_service — Borra una entrada de servicio de la base de datos del ACS

Descripción

win32_delete_service ( string $servicename , string $machine = ? ) : mixed

Intenta borrar un servicio de la base de datos del ACS. Se necesitan privilegios adminstrativos para que esto suceda.

Esta función en realidad marca el servicio para su eliminación. Si otro proceso (tal como la Aplicación de Servicios) está abierto, el borrado será aplazado hasta que tales aplicaciones se cierren. Si un servicio es marcado para su eliminación, más intentos de borrarlo fallarán, y los intentos de crear un nuevo servicio con ese nombre también fallarán.

Parámetros

servicename

El nombre corto del servicio.

machine

El nombre opcional de la máquina. Si se omite, será usada la máquina local.

Valores devueltos

Devuelve WIN32_NO_ERROR en caso de éxito, false si hay un problema con los parámetros o Código de error Win32 en caso de error.

Ejemplos

Ejemplo #1 Un ejemplo de win32_delete_service()

Borra el servicio dummyphp.

<?php
win32_delete_service('dummyphp');
?>

Ver también

  • win32_create_service() - Crea una nueva entrada de servicio en la base de datos del ACS
  • Códigos de Error de Win32

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el último mensaje de control que fue enviado a este servicio

  • « win32_delete_service
  • win32_pause_service »
  • PHP Manual
  • Funciones win32service
  • Devuelve el último mensaje de control que fue enviado a este servicio

win32_get_last_control_message

(PECL win32service >=0.1.0)

win32_get_last_control_message — Devuelve el último mensaje de control que fue enviado a este servicio

Descripción

win32_get_last_control_message ( ) : int

Devuelve el código de control que fue el último enviado a este proceso de servicio. Cuando se ejecuta como un servicio lo debería comprobar periódicamente para determinar si su servicio necesita detenerse.

Valores devueltos

Devuelve una constante de control que puede ser una de las Constantes de Mensajes de Control de Servicio de Win32Service: WIN32_SERVICE_CONTROL_CONTINUE, WIN32_SERVICE_CONTROL_INTERROGATE, WIN32_SERVICE_CONTROL_PAUSE, WIN32_SERVICE_CONTROL_PRESHUTDOWN, WIN32_SERVICE_CONTROL_SHUTDOWN, WIN32_SERVICE_CONTROL_STOP.

Ver también

  • win32_start_service_ctrl_dispatcher() - Registra el script con el ACS, por lo que puede actuar como el servicio con el nombre dado
  • Constantes de Mensajes de Control de Servicio de Win32Service

User Contributed Notes

There are no user contributed notes for this page.


Pausa un servicio

  • « win32_get_last_control_message
  • win32_query_service_status »
  • PHP Manual
  • Funciones win32service
  • Pausa un servicio

win32_pause_service

(PECL win32service >=0.1.0)

win32_pause_service — Pausa un servicio

Descripción

win32_pause_service ( string $servicename , string $machine = ? ) : int

Pausa un servicio nominado. Se necesitan privilegios administrativos.

Parámetros

servicename

El nombre corto del servicio.

machine

Nombre opcional de la máquina. Si se omite, se usa el nombre de la máquina local.

Valores devueltos

Devuelve WIN32_NO_ERROR en caso de éxito, false si hay un problema con los parámetros o Código de error Win32 en caso de error.

Ver también

  • win32_start_service() - Inicia un servicio
  • Códigos de Error Win32

User Contributed Notes

There are no user contributed notes for this page.


Pregunta sobre el estado de un servicio

  • « win32_pause_service
  • win32_send_custom_control »
  • PHP Manual
  • Funciones win32service
  • Pregunta sobre el estado de un servicio

win32_query_service_status

(PECL win32service >=0.1.0)

win32_query_service_status — Pregunta sobre el estado de un servicio

Descripción

win32_query_service_status ( string $servicename , string $machine = ? ) : mixed

Pregunta sobre el estado actual de un servicio, devolviendo una matriz de información.

Parámetros

servicename

El nombre corto del servicio.

machine

El nombre opcional de la máquina. Si se omite, será usada la máquina local.

Valores devueltos

Devuelve una matriz que consiste en la sigiente información sobre , false si hay un problema con los parámetros o Código de error Win32 en caso de error.

ServiceType

El dwServiceType. Véase Máscaras de Bits de Tipo Servicio de Win32Service.

CurrentState

El dwCurrentState. Véase Constantes de Estado de Servicio de Win32Service.

ControlsAccepted

Qué controles de servicio son aceptados por el servicio. Véase Máscaras de Bits Aceptadas de Mensajes de Control de Servicios de Win32Service.

Win32ExitCode

Si se sale del servicio, el código de retorno del proceso.

ServiceSpecificExitCode

Si se sale del servicio con una condición de error, el código específico de servicio que es registrado en el registro de eventos es visible aquí.

CheckPoint

Si el servicio se apaga, mantiene el número del punto de control actual. Ésto es usado por el ACS como un tipo de pulso para detectar un proceso de servicio estancado. El valor del punto de control se interpreta mejor junto con el valor WaitHint.

WaitHint

Si el servicio se apaga se establecerá WaitHint a un valor del punto de control que indicará 100% de finalización. Esto se puede usar para implementar un indicador de progreso.

ProcessId

El indentificador de proceso de Windows. Si es 0, el proceso no se está ejecutando.

ServiceFlags

El dwServiceFlags. Véase Constantes de Banderas de Servicio de Win32Service.

Ver también

  • Constantes Predefinidas de Win32Service

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.


Enviar un control personalizado al servicio

  • « win32_query_service_status
  • win32_set_service_exit_code »
  • PHP Manual
  • Funciones win32service
  • Enviar un control personalizado al servicio

win32_send_custom_control

(PECL win32service >=0.4.0)

win32_send_custom_control — Enviar un control personalizado al servicio

Descripción

win32_send_custom_control ( string $servicename , int $control , string $machine = ? ) : int

Véase » Microsoft ControlService function para más detalles

Parámetros

servicename

El nombre corto del servicio.

control

El valor del contorno personalizado entre 128 y 255.

machine

Nombre de la máquina opcional. Si se omite, se utiliza la máquina local.

Valores devueltos

Devuelve WIN32_NO_ERROR en caso de éxito, false si hay un problema con los parámetros o Código de error Win32 en caso de error.

Errores/Excepciones

Si el valor de control no está entre 128 y 255, esta función emite un error de nivel E_ERROR.

Ver también

  • win32_start_service() - Inicia un servicio
  • win32_stop_service() - Detiene un servicio
  • win32_pause_service() - Pausa un servicio
  • win32_continue_service() - Reanuda un servicio pausado
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Define o devuelve el código de salida para el servicio en curso

  • « win32_send_custom_control
  • win32_set_service_exit_mode »
  • PHP Manual
  • Funciones win32service
  • Define o devuelve el código de salida para el servicio en curso

win32_set_service_exit_code

(PECL win32service >=0.4.0)

win32_set_service_exit_code — Define o devuelve el código de salida para el servicio en curso

Descripción

win32_set_service_exit_code ( int $exitCode = 1 ) : int

Cambia o devuelve el código de salida. El código de salida se utiliza sólo si el modo de salida no es ágil. Si el valor no es cero, la configuración de recuperación se puede utilizar después de el fallo de servicio. Véase » Microsoft system error codes para más detalles

Precaución

Esta función sólo funciona en el SAPI "cli". En otro SAPI esta función está desactivada.

Parámetros

exitCode

El código de retorno usado en la salida.

Valores devueltos

Devuelve el código de salida actual o antiguo.

Errores/Excepciones

Si el SAPI no es "cli", esta función emite un error de nivel E_ERROR.

Ver también

  • win32_start_service_ctrl_dispatcher() - Registra el script con el ACS, por lo que puede actuar como el servicio con el nombre dado
  • win32_set_service_status() - Actualiza el estado del servicio
  • win32_set_service_exit_mode() - Define o devuelve el modo de salida para el servicio en curso

User Contributed Notes

There are no user contributed notes for this page.


Define o devuelve el modo de salida para el servicio en curso

  • « win32_set_service_exit_code
  • win32_set_service_status »
  • PHP Manual
  • Funciones win32service
  • Define o devuelve el modo de salida para el servicio en curso

win32_set_service_exit_mode

(PECL win32service >=0.4.0)

win32_set_service_exit_mode — Define o devuelve el modo de salida para el servicio en curso

Descripción

win32_set_service_exit_mode ( bool $gracefulMode = true ) : bool

Si se proporciona el parámetro gracefulMode, se cambia el modo de salida. Cuando el modo de salida no es ágil, el código de salida utilizado puede ser configurado con la función win32_set_service_exit_code().

Precaución

Esta función sólo funciona en el SAPI "cli". En otro SAPI esta función está desactivada.

Parámetros

gracefulMode

true para salir con agilidad. false para la salida con error.

Valores devueltos

Devuelve el modo de salida actual o antiguo.

Errores/Excepciones

Si el SAPI no es "cli", esta función emite un error de nivel E_ERROR.

Ver también

  • win32_start_service_ctrl_dispatcher() - Registra el script con el ACS, por lo que puede actuar como el servicio con el nombre dado
  • win32_set_service_status() - Actualiza el estado del servicio
  • win32_set_service_exit_code() - Define o devuelve el código de salida para el servicio en curso

User Contributed Notes

There are no user contributed notes for this page.


Actualiza el estado del servicio

  • « win32_set_service_exit_mode
  • win32_start_service_ctrl_dispatcher »
  • PHP Manual
  • Funciones win32service
  • Actualiza el estado del servicio

win32_set_service_status

(PECL win32service >=0.1.0)

win32_set_service_status — Actualiza el estado del servicio

Descripción

win32_set_service_status ( int $status , int $checkpoint = 0 ) : bool

Informa al ACS del estado actual de un servicio que se está ejecutado. Esta llamada sólo es válida para un proceso de servicio que se esté ejecutando.

Parámetros

status

El código de estado de servicio, uno de los siguientes: 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

El valor del punto de control del servicio aumenta periódicamente para notificar su progreso durante una operación prolongada de inicio, parada, pausa o continuación. Por ejemplo, el servicio debería aumentar este valor al completar cada paso de su inicialización cuando se inicia.

checkpoint sólo es válido cuando status es WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING o WIN32_SERVICE_PAUSE_PENDING.

Valores devueltos

Devuelve true en caso de éxito, false si hay un problema con los parámetros o Código de error Win32 en caso de error.

Ver también

  • win32_start_service_ctrl_dispatcher() - Registra el script con el ACS, por lo que puede actuar como el servicio con el nombre dado
  • Constantes de Estado de Servicio de 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;
}

?>


Registra el script con el ACS, por lo que puede actuar como el servicio con el nombre dado

  • « win32_set_service_status
  • win32_start_service »
  • PHP Manual
  • Funciones win32service
  • Registra el script con el ACS, por lo que puede actuar como el servicio con el nombre dado

win32_start_service_ctrl_dispatcher

(PECL win32service >=0.1.0)

win32_start_service_ctrl_dispatcher — Registra el script con el ACS, por lo que puede actuar como el servicio con el nombre dado

Descripción

win32_start_service_ctrl_dispatcher ( string $name ) : mixed

Cuando de lanza mediante el Administrador de Control de Servicios, se requiere un porceso de servicio para "registralo" con él para establecer la supervisión del servicio y las características de comunicación. Esta función lleva a cabo el registro produciendo un hilo para manejar la comunicación a bajo nivel con el adminstrador de control de servicios.

Una vez iniciado, el proceso de servicio debería hacer 2 cosas. La primera es llamar al Administrador de Control de Servicios que esté ejecutando el servicio. Esto se lleva a cabo llamando a win32_set_service_status() con la constante WIN32_SERVICE_RUNNING. Si necesita realizar algún proceso prolongado antes de que el servicio esté realmente ejecutándose, puede usar la constante WIN32_SERVICE_START_PENDING. Lo segundo es continuar registrando con el administrador de control de servicios por lo que puede determinar si debería finalizarse. Esto se lleva a cabo llamando periódicamente a win32_get_last_control_message() y manteniendo el código devuelto de manera apropiada.

Parámetros

name

El nombre corto del servicio, como se registró mediante win32_create_service().

Valores devueltos

Devuelve true en caso de éxito, false si hay un problema con los parámetros o Código de error Win32 en caso de error.

Ejemplos

Ejemplo #1 Un ejemplo de win32_start_service_ctrl_dispatcher()

Comprobar si el servicio se está ejecutando bajo el ACS.

<?php
if (!win32_start_service_ctrl_dispatcher('dummyphp')) {
  die("Probablemente no esté ejecutándome bajo el administrador de control de servicios");
}

win32_set_service_status(WIN32_SERVICE_START_PENDING);

// Algún proceso prolongado para levantar este servicio y ejecutar.

win32_set_service_status(WIN32_SERVICE_RUNNING);

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
  # hacer su trabajo aquí, intentando no tomar más de 30 segundos
  # antes de ejecutar de nuevo el bucle
}
?>

Ver también

  • win32_set_service_status() - Actualiza el estado del servicio
  • win32_get_last_control_message() - Devuelve el último mensaje de control que fue enviado a este servicio
  • Códigos de Error de 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.


Inicia un servicio

  • « win32_start_service_ctrl_dispatcher
  • win32_stop_service »
  • PHP Manual
  • Funciones win32service
  • Inicia un servicio

win32_start_service

(PECL win32service >=0.1.0)

win32_start_service — Inicia un servicio

Descripción

win32_start_service ( string $servicename , string $machine = ? ) : int

Intenta iniciar un servicio con nombre. Normalmente requiere privilegios administrativos.

Parámetros

servicename

El nombre corto del servicio.

machine

El nombre opcional de la máquina. Si se omite, será usada la máquina local.

Valores devueltos

Devuelve WIN32_NO_ERROR en caso de éxito, false si hay un problema con los parámetros o Código de error Win32 en caso de error.

Ver también

  • win32_stop_service() - Detiene un servicio
  • Códigos de Error de Win32

User Contributed Notes

There are no user contributed notes for this page.


Detiene un servicio

  • « win32_start_service
  • Manipulación de XML »
  • PHP Manual
  • Funciones win32service
  • Detiene un servicio

win32_stop_service

(PECL win32service >=0.1.0)

win32_stop_service — Detiene un servicio

Descripción

win32_stop_service ( string $servicename , string $machine = ? ) : int

Detiene un servicio con nombre. Requiere privilegios administrativos.

Parámetros

servicename

El nombre corto del servicio.

machine

El nombre opcional de la máquina. Si se omite, se usa la máquina local.

Valores devueltos

Devuelve WIN32_NO_ERROR en caso de éxito, false si hay un problema con los parámetros o Código de error Win32 en caso de error.

Ver también

  • win32_start_service() - Inicia un servicio
  • Códigos de Error de Win32

User Contributed Notes

There are no user contributed notes for this page.


Manipulación de XML

  • DOM — Modelo de Objetos de Documento
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Ejemplos
    • DOMAttr — La clase DOMAttr
    • DOMCdataSection — La clase DOMCdataSection
    • DOMCharacterData — La clase DOMCharacterData
    • DOMComment — Clase DOMComment
    • DOMDocument — Clase DOMDocument
    • DOMDocumentFragment — La clase DOMDocumentFragment
    • DOMDocumentType — La clase DOMDocumentType
    • DOMElement — La clase DOMElement
    • DOMEntity — La clase DOMEntity
    • DOMEntityReference — La clase DOMEntityReference
    • DOMException — La clase DOMException
    • DOMImplementation — La clase DOMImplementation
    • DOMNamedNodeMap — La clase DOMNamedNodeMap
    • DOMNode — La clase DOMNode
    • DOMNodeList — La clase DOMNodeList
    • DOMNotation — La clase DOMNotation
    • DOMProcessingInstruction — La clase DOMProcessingInstruction
    • DOMText — La clase DOMText
    • DOMXPath — La clase DOMXPath
    • Funciones de DOM
  • libxml
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • libXMLError — La clase libXMLError
    • Funciones de libxml
  • SimpleXML
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Ejemplos
    • SimpleXMLElement — Clase SimpleXMLElement
    • SimpleXMLIterator — La clase SimpleXMLIterator
    • Funciones de SimpleXML
  • WDDX
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Ejemplos
    • Funciones de WDDX
  • XMLDiff — Diferencias y fusión de documentos XML
    • Introducción
    • Instalación/Configuración
    • XMLDiff\Base — La clase XMLDiff\Base
    • XMLDiff\DOM — La clase XMLDiff\DOM
    • XMLDiff\Memory — La clase XMLDiff\Memory
    • XMLDiff\File — La clase XMLDiff\File
  • Analizador XML
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Manejadores de eventos
    • Case Folding
    • Error Codes
    • Codificación de caracteres
    • Ejemplos
    • Funciones del Intérprete XML
  • XMLReader
    • Introducción
    • Instalación/Configuración
    • XMLReader — The XMLReader class
  • XMLWriter
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Ejemplos
    • XMLWriter — La clase XMLWriter
  • XSL
    • Introducción
    • Instalación/Configuración
    • Constantes predefinidas
    • Ejemplos
    • XSLTProcessor — Clase XSLTProcessor

User Contributed Notes

There are no user contributed notes for this page.


Modelo de Objetos de Documento

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Ejemplos
  • DOMAttr — La clase DOMAttr
    • DOMAttr::__construct — Crea un nuevo objeto DOMAttr
    • DOMAttr::isId — Verifica si un atributo es un ID definido.
  • DOMCdataSection — La clase DOMCdataSection
    • DOMCdataSection::__construct — Construye un nuevo objeto DOMCdataSection
  • DOMCharacterData — La clase DOMCharacterData
    • DOMCharacterData::appendData — Añade el string de caracteres al final de los datos de carácter del nodo.
    • DOMCharacterData::deleteData — Eliminar una serie de caracteres del nodo
    • DOMCharacterData::insertData — Inserta un string en la posición de 16-bit especificada
    • DOMCharacterData::replaceData — Reemplaza un substring dentro de un nodo DOMCharacterData
    • DOMCharacterData::substringData — Extrae una serie de datos del nodo
  • DOMComment — Clase DOMComment
    • DOMComment::__construct — Crea un nuevo objeto DOMComment
  • DOMDocument — Clase DOMDocument
    • DOMDocument::__construct — Crea un nuevo objeto DOMDocument
    • DOMDocument::createAttribute — Crear nuevo attribute
    • DOMDocument::createAttributeNS — Crea un nuevo nodo atributo con un namespace asociado.
    • DOMDocument::createCDATASection — Crea un nuevo nodo cdata
    • DOMDocument::createComment — Crea un nuevo nodo de comentario
    • DOMDocument::createDocumentFragment — Crea un nuevo fragmento de documento
    • DOMDocument::createElement — Crea un nuevo nodo elemento
    • DOMDocument::createElementNS — Crea un nuevo nodo elemento con el nombre de espacio asociado
    • DOMDocument::createEntityReference — Create new entity reference node
    • DOMDocument::createProcessingInstruction — Crea un nuevo nodo PI
    • DOMDocument::createTextNode — Crea un nuevo nodo de texto
    • DOMDocument::getElementById — Busca un elemento con cierto id
    • DOMDocument::getElementsByTagName — Busca todos los elementos con el nombre de etiqueta local dado
    • DOMDocument::getElementsByTagNameNS — Busca todos los elementos con el nombre de etiqueta dado en el espacio de nombre especificado.
    • DOMDocument::importNode — Importa un nodo dentro del documento actual
    • DOMDocument::load — Cargar un documento XML de un archivo.
    • DOMDocument::loadHTML — Cargar HTML de una cadena
    • DOMDocument::loadHTMLFile — Cargar HTML desde un fichero
    • DOMDocument::loadXML — Cargar XML desde una cadena
    • DOMDocument::normalizeDocument — Normaliza el documento
    • DOMDocument::registerNodeClass — Registra una clase extendida usada para crear tipos de nodos base
    • DOMDocument::relaxNGValidate — Realiza una validación relaxNG del documento
    • DOMDocument::relaxNGValidateSource — Realiza una validación relaxNG del documento
    • DOMDocument::save — Copia el árbol XML interno a un archivo
    • DOMDocument::saveHTML — Copia el documento interno a una cadena usando el formato HTML
    • DOMDocument::saveHTMLFile — Copia el documento interno a un fichero usando el formato HTML
    • DOMDocument::saveXML — Copia el arbol XML interno a un string
    • DOMDocument::schemaValidate — Valida un documento basado en un esquema
    • DOMDocument::schemaValidateSource — Valida un documento basado en un esquema
    • DOMDocument::validate — Valida el documento basado en su DTD
    • DOMDocument::xinclude — Sustituye XIncludes en un objeto DOMDocument
  • DOMDocumentFragment — La clase DOMDocumentFragment
    • DOMDocumentFragment::appendXML — Añade información XML sin formato
  • DOMDocumentType — La clase DOMDocumentType
  • DOMElement — La clase DOMElement
    • DOMElement::__construct — Crea un nuevo objeto DOMElement
    • DOMElement::getAttribute — Devuelve el valor de un atributo
    • DOMElement::getAttributeNode — Devuelve el nodo de un atributo
    • DOMElement::getAttributeNodeNS — Devuelve el nodo de un atributo
    • DOMElement::getAttributeNS — Devuelve el valor de un atributo
    • DOMElement::getElementsByTagName — Obtiene los elementos por nombre de etiqueta
    • DOMElement::getElementsByTagNameNS — Obtener los elementos por la URI del espacio de nombres y el nombre local
    • DOMElement::hasAttribute — Comprueba si existe un atributo
    • DOMElement::hasAttributeNS — Comprueba si un atributo existe
    • DOMElement::removeAttribute — Elimina un atributo
    • DOMElement::removeAttributeNode — Elimina un atributo
    • DOMElement::removeAttributeNS — Elimina un atributo
    • DOMElement::setAttribute — Añade un nuevo atributo
    • DOMElement::setAttributeNode — Añade un nuevo nodo de atributo al elemento
    • DOMElement::setAttributeNodeNS — Aña de un nuevo nodo de atributo al elemento
    • DOMElement::setAttributeNS — Añade un nuevo atributo
    • DOMElement::setIdAttribute — Declara el atributo especificado por su nombre como de tipo ID
    • DOMElement::setIdAttributeNode — Declara el atributo especificado por su nodo como de tipo ID
    • DOMElement::setIdAttributeNS — Declara el atributo especificado por su nombre local y su URI del espacio de nombres como de tipo ID
  • DOMEntity — La clase DOMEntity
  • DOMEntityReference — La clase DOMEntityReference
    • DOMEntityReference::__construct — Crea un nuevo objeto DOMEntityReference
  • DOMException — La clase DOMException
  • DOMImplementation — La clase DOMImplementation
    • DOMImplementation::__construct — Crea un nuevo objeto DOMImplementation
    • DOMImplementation::createDocument — Crea un objeto DOMDocument del tipo especificado con su elemento documento
    • DOMImplementation::createDocumentType — Crear un objeto DOMDocumentType vacío
    • DOMImplementation::hasFeature — Comprueba si la implementación de DOM implementa una característica específica
  • DOMNamedNodeMap — La clase DOMNamedNodeMap
    • DOMNamedNodeMap::count — Get number of nodes in the map
    • DOMNamedNodeMap::getNamedItem — Recupera un nodo especificado por su nombre
    • DOMNamedNodeMap::getNamedItemNS — Recupera un nodo especificado por el nombre local y la URI del espacio de nombres
    • DOMNamedNodeMap::item — Recupera un nodo especificado por su índice
  • DOMNode — La clase DOMNode
    • DOMNode::appendChild — Añade un nuevo hijo al final de los hijos
    • DOMNode::C14N — Canonizar nodos a una cadena
    • DOMNode::C14NFile — Canonizar nodos a un fichero
    • DOMNode::cloneNode — Clona un nodo
    • DOMNode::getLineNo — Obtener el número de línea de un nodo
    • DOMNode::getNodePath — Obtener un XPath de un nodo
    • DOMNode::hasAttributes — Comprueba si un nodo tiene atributos
    • DOMNode::hasChildNodes — Comprueba si el nodo tiene hijos
    • DOMNode::insertBefore — Añade un nuevo hijo antes del nodo de referencia
    • DOMNode::isDefaultNamespace — Comprueba si la URI del espacio de nombres especificada es el espacio de nombres predeterminado
    • DOMNode::isSameNode — Indica si dos nodos son el mismo nodo
    • DOMNode::isSupported — Comprueba si una característica está soportada para la versión especificada
    • DOMNode::lookupNamespaceUri — Obtiene la URI del espacio de nombres del nodo basado en el prefijo
    • DOMNode::lookupPrefix — Obtiene el prefijo del espacio de nombres del nodo basándoes en la URI del espacio de nombres
    • DOMNode::normalize — Normaliza el nodo
    • DOMNode::removeChild — Elimina un hijo de la lista de hijos.
    • DOMNode::replaceChild — Reemplaza un hijo
  • DOMNodeList — La clase DOMNodeList
    • DOMNodeList::count — Obtiene el número de nodos en la lista
    • DOMNodeList::item — Recupera un nodo especificado por un índice
  • DOMNotation — La clase DOMNotation
  • DOMProcessingInstruction — La clase DOMProcessingInstruction
    • DOMProcessingInstruction::__construct — Crea un nuevo objeto DOMProcessingInstruction
  • DOMText — La clase DOMText
    • DOMText::__construct — Crea un nuevo objeto DOMText
    • DOMText::isElementContentWhitespace — Devuelve si este nodo de texto contiene espacios en blanco en el contenido del elemento
    • DOMText::isWhitespaceInElementContent — Indica si este nodo de texto contiene espacios en blanco
    • DOMText::splitText — Rompe este nodo en dos nodos en el índice especificado
  • DOMXPath — La clase DOMXPath
    • DOMXPath::__construct — Crea un nuevo objeto DOMXPath
    • DOMXPath::evaluate — Evalúa la expresión XPath dada y devuelve un resultado escrito si es posible
    • DOMXPath::query — Evalúa la expresión XPath dada
    • DOMXPath::registerNamespace — Registra el espacio de nombres con el objeto DOMXPath
    • DOMXPath::registerPhpFunctions — Registra funciones de PHP como funciones XPath
  • Funciones de DOM
    • dom_import_simplexml — Obtiene un objeto DOMElement desde un objeto SimpleXMLElement

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


Introducción

La extension DOM (siglas en inglés de Document Object Model) permite manipular documentos XML mediante la API DOM con PHP.

Nota:

The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode() to work with texts in ISO-8859-1 encoding or iconv for other encodings.

User Contributed Notes

Anonymous 15-Apr-2020 06:01
On some linux package managers, namely apt, this is called 'xml' for example as in:

sudo apt-get install -y php7.3-xml
captainjester at hotmail dot com 27-Mar-2020 12:59
Be careful when using this for partial HTML. This will only take complete HTML documents with at least an HTML element and a BODY element. If you are working on partial HTML and you fill in the missing elements around it and don't specify in META elements the character encoding then it will be treated as ISO-8859-1 and will mangle UTF-8 strings. Example:

<?php
$body = getHtmlBody();
$doc = new DOMDocument();
$doc->loadHtml("<html><body>".$body."</body></html>");
// $doc will treat your HTML ISO-8859-1.
// this is correct but may not be what you want if your source is UTF-8
?>

<?php
$body = getHtmlBody();
$doc = new DOMDocument();
$doc->loadHtml("<html><head><meta charset=\"UTF-8\"><meta http-equiv=\"Content-Type\" content=\"text/html; CHARSET=Windows-1252\"></head><body>".$body."</body></html>");
// $doc will treat your HTML correctly as UTF-8.
?>


Instalación/Configuración

Tabla de contenidos

  • Requerimientos
  • Instalación
  • Configuración en tiempo de ejecución
  • Tipos de recursos

User Contributed Notes

d at duane dot com 10-May-2012 05:02
On Fedora 16, you can use
yum -y install php-xml
and then be sure to add
extension=dom.so
in the php.ini file for this to work.
Anonymous 05-Oct-2011 07:40
In Redhat 5.5 using php53 you need to not only install php53-xml but php53-devel as well to install DOMDocument
eugenekay at kashpureff dot org 24-Jan-2011 10:08
Certain Linux distributions do not have this extension included in the minimum PHP package. It can usually be found in one of the "optional" php-* packages.

For CentOS, you will need to run "yum install php-xml", which provides this extension.
Sergey A. 05-Apr-2010 05:38
don't forget
extension=dom.so
in extensions.ini
on freebsd
z1mok at yahoo dot com 22-Apr-2009 05:45
You need the DOM MODULE installed if you want to use Youtube Data Api with the Zend GData Library.

Otherwise you cannot obtain a valid Upload Form Token.


Requerimientos

Esta extensión requiere la extensión libxml de PHP. Esto significa que también es necesario pasar la opción --enable-libxml, aunque esto se realiza implícitamente debido a que libxml está habilitada de forma predeterminada.

User Contributed Notes

david at brayworth dot com dot au 12-Jun-2011 05:55
Under Fedora packaging ssystems you will need php-xml
 => yum install php-xml
James 18-Apr-2010 10:58
You also need to check libxml is installed. Check phpinfo() > Dom to see if it is. Bug report filed to get this added here.


Instalación

Esta extensión está habilitada de forma predeterminada. Se puede deshabilitar empleando la siguiente opción durante la compilación: --disable-dom

User Contributed Notes

smleimberg at NOSPAM dot gmail dot com 26-Dec-2017 10:08
For Ubuntu:
sudo apt-get install php7.0-xml

For Fedora:
yum -y install php-xml


Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles sólo cuando la extensión haya sido compilada con PHP, o bien sea cargada dinámicamente en ejecución.

Constantes XML
Constante | Valor | Descripción
XML_ELEMENT_NODE (integer) | 1 | Nodo es un DOMElement
XML_ATTRIBUTE_NODE (integer) | 2 | Nodo es un DOMAttr
XML_TEXT_NODE (integer) | 3 | Nodo es un DOMText
XML_CDATA_SECTION_NODE (integer) | 4 | Nodo es un DOMCharacterData
XML_ENTITY_REF_NODE (integer) | 5 | Nodo es un DOMEntityReference
XML_ENTITY_NODE (integer) | 6 | Nodo es un DOMEntity
XML_PI_NODE (integer) | 7 | Nodo es un DOMProcessingInstruction
XML_COMMENT_NODE (integer) | 8 | Nodo es un DOMComment
XML_DOCUMENT_NODE (integer) | 9 | Nodo es un DOMDocument
XML_DOCUMENT_TYPE_NODE (integer) | 10 | Nodo es un DOMDocumentType
XML_DOCUMENT_FRAG_NODE (integer) | 11 | Nodo es un DOMDocumentFragment
XML_NOTATION_NODE (integer) | 12 | Nodo es un DOMNotation
XML_HTML_DOCUMENT_NODE (integer) | 13 |
XML_DTD_NODE (integer) | 14 |
XML_ELEMENT_DECL_NODE (integer) | 15 |
XML_ATTRIBUTE_DECL_NODE (integer) | 16 |
XML_ENTITY_DECL_NODE (integer) | 17 |
XML_NAMESPACE_DECL_NODE (integer) | 18 |
XML_ATTRIBUTE_CDATA (integer) | 1 |
XML_ATTRIBUTE_ID (integer) | 2 |
XML_ATTRIBUTE_IDREF (integer) | 3 |
XML_ATTRIBUTE_IDREFS (integer) | 4 |
XML_ATTRIBUTE_ENTITY (integer) | 5 |
XML_ATTRIBUTE_NMTOKEN (integer) | 7 |
XML_ATTRIBUTE_NMTOKENS (integer) | 8 |
XML_ATTRIBUTE_ENUMERATION (integer) | 9 |
XML_ATTRIBUTE_NOTATION (integer) | 10 |
DOMException constantes
Constante | Valor | Descripción
DOM_PHP_ERR (integer) | 0 | El código de Error no forma parte de la especificación DOM. Significado para errores PHP.
DOM_INDEX_SIZE_ERR (integer) | 1 | Si el índice o el tamaño es negativo, o mayor que el valor permitido.
DOMSTRING_SIZE_ERR (integer) | 2 | Si el rango especificado de texto no cabe en un DOMString.
DOM_HIERARCHY_REQUEST_ERR (integer) | 3 | Si un nodo es insertado en un lugar al que no pertenece
DOM_WRONG_DOCUMENT_ERR (integer) | 4 | Si un nodo es usado en un documento diferente al que lo creó.
DOM_INVALID_CHARACTER_ERR (integer) | 5 | Si un carácter ilegal o inválido es especificado, como en un nombre.
DOM_NO_DATA_ALLOWED_ERR (integer) | 6 | Si la data es especificada para un nodo que no la soporta.
DOM_NO_MODIFICATION_ALLOWED_ERR (integer) | 7 | Si se intenta modificar un objeto donde las modificaciones no están permitidas.
DOM_NOT_FOUND_ERR (integer) | 8 | Si se intenta referenciar un nodo en un contexto en el que no existe.
DOM_NOT_SUPPORTED_ERR (integer) | 9 | Si la implementación no soporta el tipo de objeto u operación solicitado.
DOM_INUSE_ATTRIBUTE_ERR (integer) | 10 | Si se intenta agregar un atributo que esta siendo usado en otro lugar.
DOM_INVALID_STATE_ERR (integer) | 11 | Si se intenta utilizar un objeto que no es o ha dejado de ser usable.
DOM_SYNTAX_ERR (integer) | 12 | Si una cadena ilegal o inválida es especificada.
DOM_INVALID_MODIFICATION_ERR (integer) | 13 | Si se intenta modificar el tipo de dato del objeto subyacente.
DOM_NAMESPACE_ERR (integer) | 14 | Si se intenta crear o modificar un objeto de una manera que es incorrecta con respecto a su espacio de nombre (namespace).
DOM_INVALID_ACCESS_ERR (integer) | 15 | Si un parámetro u operación no es soportado por el objeto subyacente.
DOM_VALIDATION_ERR (integer) | 16 | Si la llamada a un método como insertBefore o removeChild invalidará el Nodo con respecto a la "validez parcial", esta excepción sera lanzada y la operación no se realizará.

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

Muchos ejemplos en esta referencia requieren un fichero XML. Utilizaremos book.xml que contiene lo siguiente:

Ejemplo #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>Mis listas</title>
 <chapter id="books">
  <title>Mis libros</title>
  <para>
   <informaltable>
    <tgroup cols="4">
     <thead>
      <row>
       <entry>Título</entry>
       <entry>Autor</entry>
       <entry>Idioma</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: Tengo muchos libros pendientes de añadir.. -->
     </tbody>
    </tgroup>
   </informaltable>
  </para>
 </chapter>
</book>

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMAttr

(PHP 5, PHP 7)

Introducción

DOMAttr representa un atributo en el objeto DOMElement.

Sinopsis de la Clase

DOMAttr extends DOMNode {
/* Propiedades */
public readonly string $name ;
public readonly DOMElement $ownerElement ;
public readonly bool $schemaTypeInfo ;
public readonly bool $specified ;
public string $value ;
/* Propiedades heredadas */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
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 DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Métodos */
public __construct ( string $name , string $value = ? )
public isId ( ) : bool
/* Métodos heredados */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Propiedades

name

El nombre del atributo.

ownerElement

El elemento que contiene el atributo.

schemaTypeInfo

Aún no implementado, siempre es null

specified

Aún no implementado, siempre es null

value

El valor del atributo.

Ver también

  • » Especificación W3C de Attr

Tabla de contenidos

  • DOMAttr::__construct — Crea un nuevo objeto DOMAttr
  • DOMAttr::isId — Verifica si un atributo es un ID definido.

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


Crea un nuevo objeto DOMAttr

  • « DOMAttr
  • DOMAttr::isId »
  • PHP Manual
  • DOMAttr
  • Crea un nuevo objeto DOMAttr

DOMAttr::__construct

(PHP 5, PHP 7)

DOMAttr::__construct — Crea un nuevo objeto DOMAttr

Descripción

public DOMAttr::__construct ( string $name , string $value = ? )

Crea un nuevo objeto DOMAttr. Este objeto es de sólo lectura. Puede ser anexado a un documento, pero no se le podrán anexar nodos adicionales a este hasta que sea asociado con un documento. Para crear un nodo modificable utilice DOMDocument::createAttribute.

Parámetros

name

El nombre de etiqueta del atributo.

value

El valor de atributo.

Ejemplos

Ejemplo #1 Creación de un nuevo objeto 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();

?>

El resultado del ejemplo sería:

<?xml version="1.0" encoding="utf-8"?>
<root attr="attrvalue" />

Ver también

  • DOMDocument::createAttribute() - Crear nuevo attribute

User Contributed Notes

Anonymous 18-Sep-2014 10:48
The output should be:

<?xml version="1.0" encoding="iso-8859-1"?>
<root attr="attrvalue"/>


Verifica si un atributo es un ID definido.

  • « DOMAttr::__construct
  • DOMCdataSection »
  • PHP Manual
  • DOMAttr
  • Verifica si un atributo es un ID definido.

DOMAttr::isId

(PHP 5, PHP 7)

DOMAttr::isId — Verifica si un atributo es un ID definido.

Descripción

public DOMAttr::isId ( ) : bool

Esta función verifica si el atributo es un ID definido.

De acuerdo al estándar DOM esto requiere una DTD que defina que el atributo ID sea de tipo ID. Necesitará validar su documento con DOMDocument::validate o DOMDocument::validateOnParse antes de utilizar esta función.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de DOMAttr::isId()

<?php

$doc = new DomDocument;

// Necesitaremos validar nuestro documento antes de referir el id
$doc->validateOnParse = true;
$doc->Load('book.xml');

// Devolvemos el atributo llamado id del elemento 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 clase DOMCdataSection

(PHP 5, PHP 7)

Introducción

DOMCdataSection hereda de DOMText para la representación textural de constructores CData.

Sinopsis de la Clase

DOMCdataSection extends DOMText {
/* Propiedades heredadas */
readonly public string $wholeText ;
public string $data ;
public readonly int $length ;
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
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 DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Métodos */
public __construct ( string $value )
/* Métodos heredados */
public DOMText::isElementContentWhitespace ( ) : bool
public DOMText::isWhitespaceInElementContent ( ) : bool
public DOMText::splitText ( int $offset ) : DOMText
public DOMCharacterData::appendData ( string $data ) : void
public DOMCharacterData::deleteData ( int $offset , int $count ) : void
public DOMCharacterData::insertData ( int $offset , string $data ) : void
public DOMCharacterData::replaceData ( int $offset , int $count , string $data ) : void
public DOMCharacterData::substringData ( int $offset , int $count ) : string
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Tabla de contenidos

  • DOMCdataSection::__construct — Construye un nuevo objeto DOMCdataSection

User Contributed Notes

There are no user contributed notes for this page.


Construye un nuevo objeto DOMCdataSection

  • « DOMCdataSection
  • DOMCharacterData »
  • PHP Manual
  • DOMCdataSection
  • Construye un nuevo objeto DOMCdataSection

DOMCdataSection::__construct

(PHP 5, PHP 7)

DOMCdataSection::__construct — Construye un nuevo objeto DOMCdataSection

Descripción

public DOMCdataSection::__construct ( string $value )

Construye un nuevo nodo CDATA. Funciona igual que la clase DOMText.

Parámetros

value

El valor del nodo CDATA. Si no se proporciona, se crea un nodo CDATA vacío.

Ejemplos

Ejemplo #1 Crear un nuevo objeto DOMCdataSection

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$elemento = $dom->appendChild(new DOMElement('root'));
$texto = $elemento->appendChild(new DOMCdataSection('root value'));
echo $dom->saveXML();

?>

El resultado del ejemplo sería:

<?xml version="1.0" encoding="utf-8"?>
<root><![CDATA[root value]]></root>

Ver también

  • DOMText::__construct() - Crea un nuevo objeto DOMText
  • DOMDocument::createTextNode() - Crea un nuevo nodo de texto

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMCharacterData

(PHP 5, PHP 7)

Introducción

Representa nodos con datos de caracteres. Ningún nodo corresponde directamente a esta clase pero otros nodos pueden heredar de ella.

Sinopsis de la Clase

DOMCharacterData extends DOMNode {
/* Propiedades */
public string $data ;
public readonly int $length ;
/* Propiedades heredadas */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
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 DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Métodos */
public appendData ( string $data ) : void
public deleteData ( int $offset , int $count ) : void
public insertData ( int $offset , string $data ) : void
public replaceData ( int $offset , int $count , string $data ) : void
public substringData ( int $offset , int $count ) : string
/* Métodos heredados */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Propiedades

data

El contenido del nodo.

length

La longitud del contenido.

Ver también

  • » Especificacion W3C specificatión de CharacterData

Tabla de contenidos

  • DOMCharacterData::appendData — Añade el string de caracteres al final de los datos de carácter del nodo.
  • DOMCharacterData::deleteData — Eliminar una serie de caracteres del nodo
  • DOMCharacterData::insertData — Inserta un string en la posición de 16-bit especificada
  • DOMCharacterData::replaceData — Reemplaza un substring dentro de un nodo DOMCharacterData
  • DOMCharacterData::substringData — Extrae una serie de datos del nodo

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


Añade el string de caracteres al final de los datos de carácter del nodo.

  • « DOMCharacterData
  • DOMCharacterData::deleteData »
  • PHP Manual
  • DOMCharacterData
  • Añade el string de caracteres al final de los datos de carácter del nodo.

DOMCharacterData::appendData

(PHP 5, PHP 7)

DOMCharacterData::appendData — Añade el string de caracteres al final de los datos de carácter del nodo.

Descripción

public DOMCharacterData::appendData ( string $data ) : void

Añade el string data hasta el final de los datos de carácter del nodo.

Parámetros

data

El string de caracteres a añadir.

Valores devueltos

No devuelve ningún valor.

Ver también

  • DOMCharacterData::deleteData() - Eliminar una serie de caracteres del nodo
  • DOMCharacterData::insertData() - Inserta un string en la posición de 16-bit especificada
  • DOMCharacterData::replaceData() - Reemplaza un substring dentro de un nodo DOMCharacterData
  • DOMCharacterData::substringData() - Extrae una serie de datos del nodo

User Contributed Notes

There are no user contributed notes for this page.


Eliminar una serie de caracteres del nodo

  • « DOMCharacterData::appendData
  • DOMCharacterData::insertData »
  • PHP Manual
  • DOMCharacterData
  • Eliminar una serie de caracteres del nodo

DOMCharacterData::deleteData

(PHP 5, PHP 7)

DOMCharacterData::deleteData — Eliminar una serie de caracteres del nodo

Descripción

public DOMCharacterData::deleteData ( int $offset , int $count ) : void

Elimina count caracteres comenzando desde la posición offset.

Parámetros

offset

El índice desde el cual se comenzará a remover.

count

La cantidad de caracteres a eliminar. Si la suma de offset y count excede la longitud, entonces todos los caracteres al final de la data son eliminados.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

DOM_INDEX_SIZE_ERR

Lanzada si offset es negativo o mayor que el número de unidades de 16-bit en la data, o si count es negativo.

Ver también

  • DOMCharacterData::appendData() - Añade el string de caracteres al final de los datos de carácter del nodo.
  • DOMCharacterData::insertData() - Inserta un string en la posición de 16-bit especificada
  • DOMCharacterData::replaceData() - Reemplaza un substring dentro de un nodo DOMCharacterData
  • DOMCharacterData::substringData() - Extrae una serie de datos del nodo

User Contributed Notes

There are no user contributed notes for this page.


Inserta un string en la posición de 16-bit especificada

  • « DOMCharacterData::deleteData
  • DOMCharacterData::replaceData »
  • PHP Manual
  • DOMCharacterData
  • Inserta un string en la posición de 16-bit especificada

DOMCharacterData::insertData

(PHP 5, PHP 7)

DOMCharacterData::insertData — Inserta un string en la posición de 16-bit especificada

Descripción

public DOMCharacterData::insertData ( int $offset , string $data ) : void

Inserta el string data en la posición offset.

Parámetros

offset

La posición en la cual se insertará.

data

El string a insertar.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

DOM_INDEX_SIZE_ERR

Lanzado si offset es negativo o mayor que el número de unidades de 16-bit en la data.

Ver también

  • DOMCharacterData::appendData() - Añade el string de caracteres al final de los datos de carácter del nodo.
  • DOMCharacterData::deleteData() - Eliminar una serie de caracteres del nodo
  • DOMCharacterData::replaceData() - Reemplaza un substring dentro de un nodo DOMCharacterData
  • DOMCharacterData::substringData() - Extrae una serie de datos del nodo

User Contributed Notes

There are no user contributed notes for this page.


Reemplaza un substring dentro de un nodo DOMCharacterData

  • « DOMCharacterData::insertData
  • DOMCharacterData::substringData »
  • PHP Manual
  • DOMCharacterData
  • Reemplaza un substring dentro de un nodo DOMCharacterData

DOMCharacterData::replaceData

(PHP 5, PHP 7)

DOMCharacterData::replaceData — Reemplaza un substring dentro de un nodo DOMCharacterData

Descripción

public DOMCharacterData::replaceData ( int $offset , int $count , string $data ) : void

Reemplaza count caracteres comenzando en la posicion offset con data.

Parámetros

offset

La posición inicial a partir de la cual se iniciara el reemplazo.

count

El número de carácteres a reemplazar. Si la suma de offset y count excede la longitud, entonces todos los carácteres al final de la data son reemplazados.

data

El string con el cual el rango debe ser reemplazado.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

DOM_INDEX_SIZE_ERR

Lanzado si offset es negativo o mayor que el número de unidades de 16-bit en la data, o si count es negativo.

Ver también

  • DOMCharacterData::appendData() - Añade el string de caracteres al final de los datos de carácter del nodo.
  • DOMCharacterData::deleteData() - Eliminar una serie de caracteres del nodo
  • DOMCharacterData::insertData() - Inserta un string en la posición de 16-bit especificada
  • DOMCharacterData::substringData() - Extrae una serie de datos del nodo

User Contributed Notes

There are no user contributed notes for this page.


Extrae una serie de datos del nodo

  • « DOMCharacterData::replaceData
  • DOMComment »
  • PHP Manual
  • DOMCharacterData
  • Extrae una serie de datos del nodo

DOMCharacterData::substringData

(PHP 5, PHP 7)

DOMCharacterData::substringData — Extrae una serie de datos del nodo

Descripción

public DOMCharacterData::substringData ( int $offset , int $count ) : string

Devuelve el substring especificado.

Parámetros

offset

Posición de inicio del substring a extraer.

count

El número de carácteres a extraer.

Valores devueltos

El substring especificado. Si la suma de offset y count excede la longitud, entonces todas las unidades de 16-bit hasta el final de la cadena son devueltas.

Errores/Excepciones

DOM_INDEX_SIZE_ERR

Lanzado si offset es negativo o mayor que el numero de unidades de 16-bit en la data, o si count es negativo.

Ver también

  • DOMCharacterData::appendData() - Añade el string de caracteres al final de los datos de carácter del nodo.
  • DOMCharacterData::deleteData() - Eliminar una serie de caracteres del nodo
  • DOMCharacterData::insertData() - Inserta un string en la posición de 16-bit especificada
  • DOMCharacterData::replaceData() - Reemplaza un substring dentro de un nodo DOMCharacterData

User Contributed Notes

There are no user contributed notes for this page.


Clase DOMComment

(PHP 5, PHP 7)

Introducción

Representa nodos comentario, caracteres delimitados por <!-- y -->.

Sinopsis de la Clase

DOMComment extends DOMCharacterData {
/* Propiedades heredadas */
public string $data ;
public readonly int $length ;
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
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 DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Métodos */
public __construct ( string $value = ? )
/* Métodos heredados */
public DOMCharacterData::appendData ( string $data ) : void
public DOMCharacterData::deleteData ( int $offset , int $count ) : void
public DOMCharacterData::insertData ( int $offset , string $data ) : void
public DOMCharacterData::replaceData ( int $offset , int $count , string $data ) : void
public DOMCharacterData::substringData ( int $offset , int $count ) : string
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Ver también

  • » Especificación W3C de Comment

Tabla de contenidos

  • DOMComment::__construct — Crea un nuevo objeto DOMComment

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo objeto DOMComment

  • « DOMComment
  • DOMDocument »
  • PHP Manual
  • DOMComment
  • Crea un nuevo objeto DOMComment

DOMComment::__construct

(PHP 5, PHP 7)

DOMComment::__construct — Crea un nuevo objeto DOMComment

Descripción

public DOMComment::__construct ( string $value = ? )

Crea un nuevo objeto DOMComment . Este objeto es de solo lectura. Puede ser anexado a un documento, pero nodos adicionales no pueden ser anexados a este nodo hasta tando no haya sido asociado con un documento. Para crear un nodo modificable utilice DOMDocument::createComment.

Parámetros

value

El valor del comentario.

Ejemplos

Ejemplo #1 Creando un nuevo 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> */

?>

Ver también

  • DOMDocument::createComment() - Crea un nuevo nodo de comentario

User Contributed Notes

There are no user contributed notes for this page.


Clase DOMDocument

(PHP 5, PHP 7)

Introducción

Representa un documento HTML o XML en su totalidad; sirve como raíz del árbol de documento.

Sinopsis de la Clase

DOMDocument extends DOMNode {
/* Propiedades */
readonly public string $actualEncoding ;
readonly public DOMConfiguration $config ;
readonly public DOMDocumentType $doctype ;
readonly public DOMElement $documentElement ;
public string $documentURI ;
public string $encoding ;
public bool $formatOutput ;
readonly public DOMImplementation $implementation ;
public bool $preserveWhiteSpace = true ;
public bool $recover ;
public bool $resolveExternals ;
public bool $standalone ;
public bool $strictErrorChecking = true ;
public bool $substituteEntities ;
public bool $validateOnParse = false ;
public string $version ;
readonly public string $xmlEncoding ;
public bool $xmlStandalone ;
public string $xmlVersion ;
/* Métodos */
public __construct ( string $version = ? , string $encoding = ? )
public createAttribute ( string $name ) : DOMAttr
public createAttributeNS ( string $namespaceURI , string $qualifiedName ) : DOMAttr
public createCDATASection ( string $data ) : DOMCDATASection
public createComment ( string $data ) : DOMComment
public createDocumentFragment ( ) : DOMDocumentFragment
public createElement ( string $name , string $value = ? ) : DOMElement
public createElementNS ( string $namespaceURI , string $qualifiedName , string $value = ? ) : DOMElement
public createEntityReference ( string $name ) : DOMEntityReference
public createProcessingInstruction ( string $target , string $data = ? ) : DOMProcessingInstruction
public createTextNode ( string $content ) : DOMText
public getElementById ( string $elementId ) : DOMElement
public getElementsByTagName ( string $name ) : DOMNodeList
public getElementsByTagNameNS ( string $namespaceURI , string $localName ) : DOMNodeList
public importNode ( DOMNode $importedNode , bool $deep = false ) : DOMNode
public load ( string $filename , int $options = 0 ) : mixed
public loadHTML ( string $source , int $options = 0 ) : bool
public loadHTMLFile ( string $filename , int $options = 0 ) : bool
public loadXML ( string $source , int $options = 0 ) : mixed
public normalizeDocument ( ) : void
public registerNodeClass ( string $baseclass , string $extendedclass ) : bool
public relaxNGValidate ( string $filename ) : bool
public relaxNGValidateSource ( string $source ) : bool
public save ( string $filename , int $options = 0 ) : int
public saveHTML ( DOMNode $node = NULL ) : string
public saveHTMLFile ( string $filename ) : int
public saveXML ( DOMNode $node = ? , int $options = 0 ) : string
public schemaValidate ( string $filename , int $flags = 0 ) : bool
public schemaValidateSource ( string $source , int $flags = ? ) : bool
public validate ( ) : bool
public xinclude ( int $options = 0 ) : int
/* Métodos heredados */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Propiedades

actualEncoding

Obsoleto. Codificación actual del documento, es el equivalente de solo lectura de encoding.

config

Obsoleto. Configuración utilizada cuando DOMDocument::normalizeDocument() es invocado.

doctype

La declaración de tipo de documento asociada con este documento.

documentElement

Este es un atributo de conveniencia que permite acceso directo al nodo hijo que es el elemento documento del documento.

documentURI

La ubicación del documento o null si es indefinida.

encoding

Codificación del documento, como ha sido especificada en la declaración XML. Este atributo no está presente en la especificación DOM Nivel 3, pero es la única manera de manipular la codificación de un documento XML en esta implementación.

formatOutput

Da formato a la salida con identación y espacios extra.

implementation

El objeto DOMImplementation que maneja este documento.

preserveWhiteSpace

No remover espacios en blanco redundantes. Predeterminado a true.

recover

Proprietario. Activa el modo de recuperación. Ejemplo: intentar analizar documentos mal formados. Este atributo no es parte de la especificación DOM y es especifica para libxml.

resolveExternals

Asigne true para cargar entidades externas a una declaración doctype. Es útil para incluir entidades de caracteres en su documento XML.

standalone

Obsoleto. Si este documento es o no independiente, tal como ha sido especificado por la declaración XML, corresponde a xmlStandalone.

strictErrorChecking

Lanzar DOMException en caso de errores. Predeterminado a true.

substituteEntities

Proprietario.Si se substituyen o no las entidades. Este atributo no forma parte de la especificación DOM y es específico para libxml.

validateOnParse

Cargar y validar contra la DTD. Predeterminado a false.

version

Obsoleto. Versión de XML, corresponde a xmlVersion.

xmlEncoding

Un atributo que forma parte de la declaración XML y especifica la codificación de este documento. Es null cuando no ha sido especificado o se desconoce, como cuando el documento fue creado en memoria.

xmlStandalone

Un atributo que forma parte de la declaración XML y especifica cuando este documento es independiente. Es false cuando no ha sido especificado.

xmlVersion

Un atributo que forma parte de la declaracion XML y especifica el número de versión de este documento. Si no hay declaración y este documento soporta la característica "XML" el valor es "1.0".

Notas

Nota:

La extensión DOM utiliza la codificación UTF-8. Use utf8_encode() y utf8_decode() para trabajar con textos con codificación ISO-8859-1 o Iconv para otras codificaciones.

Ver también

  • » Especificación W3C para Document

Tabla de contenidos

  • DOMDocument::__construct — Crea un nuevo objeto DOMDocument
  • DOMDocument::createAttribute — Crear nuevo attribute
  • DOMDocument::createAttributeNS — Crea un nuevo nodo atributo con un namespace asociado.
  • DOMDocument::createCDATASection — Crea un nuevo nodo cdata
  • DOMDocument::createComment — Crea un nuevo nodo de comentario
  • DOMDocument::createDocumentFragment — Crea un nuevo fragmento de documento
  • DOMDocument::createElement — Crea un nuevo nodo elemento
  • DOMDocument::createElementNS — Crea un nuevo nodo elemento con el nombre de espacio asociado
  • DOMDocument::createEntityReference — Create new entity reference node
  • DOMDocument::createProcessingInstruction — Crea un nuevo nodo PI
  • DOMDocument::createTextNode — Crea un nuevo nodo de texto
  • DOMDocument::getElementById — Busca un elemento con cierto id
  • DOMDocument::getElementsByTagName — Busca todos los elementos con el nombre de etiqueta local dado
  • DOMDocument::getElementsByTagNameNS — Busca todos los elementos con el nombre de etiqueta dado en el espacio de nombre especificado.
  • DOMDocument::importNode — Importa un nodo dentro del documento actual
  • DOMDocument::load — Cargar un documento XML de un archivo.
  • DOMDocument::loadHTML — Cargar HTML de una cadena
  • DOMDocument::loadHTMLFile — Cargar HTML desde un fichero
  • DOMDocument::loadXML — Cargar XML desde una cadena
  • DOMDocument::normalizeDocument — Normaliza el documento
  • DOMDocument::registerNodeClass — Registra una clase extendida usada para crear tipos de nodos base
  • DOMDocument::relaxNGValidate — Realiza una validación relaxNG del documento
  • DOMDocument::relaxNGValidateSource — Realiza una validación relaxNG del documento
  • DOMDocument::save — Copia el árbol XML interno a un archivo
  • DOMDocument::saveHTML — Copia el documento interno a una cadena usando el formato HTML
  • DOMDocument::saveHTMLFile — Copia el documento interno a un fichero usando el formato HTML
  • DOMDocument::saveXML — Copia el arbol XML interno a un string
  • DOMDocument::schemaValidate — Valida un documento basado en un esquema
  • DOMDocument::schemaValidateSource — Valida un documento basado en un esquema
  • DOMDocument::validate — Valida el documento basado en su DTD
  • DOMDocument::xinclude — Sustituye XIncludes en un objeto DOMDocument

User Contributed Notes

pastormontesinos at gmail dot com 04-Mar-2021 10:34
For using safely with script nodes when parsing, best option is extending DOMDocument, keeping script tags while DOMDocument process and rearrange them just after saveHTML function is called. Here is my custom class.

<?php

class SafeDOMDocument extends \DOMDocument
{
    const REGEX_JS            = '#(\s*<!--(\[if[^\n]*>)?\s*(<script.*</script>)+\s*(<!\[endif\])?-->)|(\s*<script.*</script>)#isU';
    const SUBSTITUTION_FORMAT = '<!--<script class="script_%s"></script>-->';
    private $matchedScripts = [];

    public function loadHTML($source, $options = 0)
    {
        $this->formatOutput        = false;
        $this->preserveWhiteSpace  = true;
        $this->validateOnParse     = false;
        $this->strictErrorChecking = false;
        $this->recover             = false;
        $this->resolveExternals    = false;
        $this->substituteEntities  = false;
        $matches = [];
        $success = preg_match_all(self::REGEX_JS, $source, $matches);

        if ($success && !empty($matches)) {
            foreach ($matches[0] as $match) {
                $storedScript = rtrim(ltrim($match, "\n\r\t "), "\n\r\t ");
                $scriptId = md5($storedScript);
                $key = sprintf(self::SUBSTITUTION_FORMAT, $scriptId);
                $source = str_replace($match, $key, $source);
                $this->matchedScripts[$key] = $storedScript;
            }
        }

        return parent::loadHTML($source, $options);
    }

    public function saveHTML(DOMNode $node = null)
    {
        $output = parent::saveHTML($node);

        if (count($this->matchedScripts)) {
            foreach ($this->matchedScripts as $substitution => $originalSnippet) {
                $output = str_replace($substitution, $originalSnippet, $output);
            }
        }

        return $output;
    }
}
?>
ashjkshdu283 at gmail dot com 07-Jul-2018 11:39
/* Function evolved from jay at jaygilford dot com post
  * This function will return an array of the values of the specified
  * attribute ($attr) for all the Dom Document object's elements
  */

<?php

function getAttrData(string $attr, DomDocument $dom) {
    // Empty array to hold all classes to return
    $attrData = array();

    //Loop through each tag in the dom and add it's attribute data to the array
    foreach($dom->getElementsByTagName('*') as $tag) {
        if(empty($tag->getAttribute($attr)) === false) {
            array_push($attrData, $tag->getAttribute($attr));
        }
    }

    //Return the array of attribute data
    return array_unique($attrData);
}

$html = '
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<a href="#someLink" id="someLink" class="link-class">Some Link</a>
<a href="#someOtherLink" id="someOtherLink" class="link-class">Some Other Link</a>
<h1 id="header1" class="header-class">My First Heading</h1>
<p id="para1" class="para-class">My first paragraph.</p>
</body>
</html>';
$dom = new DOMDocument();
$dom->loadHtml($html);
$dom->saveHTML();
var_dump(getAttrData('class', $dom));
biker dot mike at gmx dot com 22-Aug-2016 01:36
Look out for the following gotcha when loading XML from a string:

<?php
$doc = new \DOMDocument;
$doc->documentURI = $myXmlFilename;
$doc->loadXML($myXmlString);
?>

documentURI is now set to the value of $myXmlFilename, right?

Wrong!

It's set to the current working directory.  If you want to manually set documentURI to something other than the CWD, do so AFTER the call to loadXML().

E.g.:
<?php
$doc = new \DOMDocument;
$doc->loadXML($myXmlString);
$doc->documentURI = $myXmlFilename;
?>

documentURI really is now set to the value of $myXmlFilename.
developer at nabtron dot com 17-Dec-2015 07:34
For those landing here and checking for encoding issue with utf-8 characteres, it's pretty easy to correct it, without adding any additional output tag to your html.

We'll be utilizing: mb_convert_encoding

Thanks to the user who shared: SmartDOMDocument in previous comments, I got the idea of solving it. However I truly wish that he shared the method instead of giving a link.

Anyway coming back to the solution, you can simply use:

<?php

            // checks if the content we're receiving isn't empty, to avoid the warning
            if ( empty( $content ) ) {
                return false;
            }

            // converts all special characters to utf-8
            $content = mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8');

            // creating new document
            $doc = new DOMDocument('1.0', 'utf-8');

            //turning off some errors
            libxml_use_internal_errors(true);

            // it loads the content without adding enclosing html/body tags and also the doctype declaration
            $doc->LoadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

            // do whatever you want to do with this code now

?>

I hope it solves the issue for someone! If you need my help or service to fix your code, you can reach me on nabtron.com or contact me at the email mentioned with this comment.
ingjetel at gmail dot com 13-May-2015 11:54
Easy function for basic output of XML file via DOM parsing

<?php
$dom = new DomDocument();
$dom->load("./file.xml") or die("error");
$start = $dom->documentElement;
fc($start);

function fc($node) {
  $child = $node->childNodes;
  foreach($child as $item) {
    if ($item->nodeType == XML_TEXT_NODE) {
      if (strlen(trim($item->nodeValue))) echo trim($item->nodeValue)."<br/>";
    }
    else if ($item->nodeType == XML_ELEMENT_NODE) fc($item);
  }
}
?>
qrworld.net 11-Nov-2014 04:35
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
danny dot nunez15 at gmail dot com 28-Oct-2013 02:54
A simple function to grab all links in a page.

    function get_links($url) {

        // Create a new DOM Document to hold our webpage structure
        $xml = new DOMDocument();

        // Load the url's contents into the DOM

        $xml->loadHTMLFile($url);

        // Empty array to hold all links to return
        $links = array();

        //Loop through each <a> tag in the dom and add it to the link array
        foreach ($xml->getElementsByTagName('a') as $link) {
            $url = $link->getAttribute('href');
            if (!empty($url)) {
                $links[] = $link->getAttribute('href');
            }
        }

        //Return the links
        return $links;
    }
sites.sitesbr.net 22-Jan-2013 12:37
How to objetify a DomDocument with hierarchy like:
<root>
    <item>
          <prop1>info1</prop1>
          <prop2>info2</prop2>
          <prop3>info3</prop3>
     </item>
    <item>
          <prop1>info1</prop1>
          <prop2>info2</prop2>
          <prop3>info3</prop3>
     </item>
</root>

It's possible to use in object style to retrieve information, as:

<?php
     $theNodeValue = $aitem->prop1;
?>

Here is the code: one Class and 2 functions.

<?php
 class ArrayNode{
       public $nodeName, $nodeValue;
 }

 function getChildNodeElements( $domNode ){
     $nodes = array();
     for( $i=0; $i < $domNode->childNodes->length; $i++){
       $cn = $domNode->childNodes->item($i);
       if( $cn->nodeType == 1){
           $nodes[] = $cn;
           }
     }
    return $nodes;
 }

 function getArrayNodes( $domDoc ){
     $res = array();

       for( $i=0; $i < $domDoc->childNodes->length; $i++){
       $cn = $domDoc->childNodes->item($i);
       # The first is the root tag...
          if( $cn->nodeType == 1){
               # But we want it's childNodes.
                $sub_cn = getChildNodeElements( $cn);
                # Found the tagName:
                $baseItemTagName = $sub_cn[0]->nodeName;
                break;
            }
        }

       $dnl = $domDoc->getElementsByTagName( $baseItemTagName);

       for( $i=0; $i< $dnl->length; $i++){
          $arrayNode = new ArrayNode();

      # Summary
      $arrayNode->nodeName = $dnl->item($i)->nodeName;
      $arrayNode->nodeValue = $dnl->item($i)->nodeValue;

      # Child Nodes
      $cn = $dnl->item($i)->childNodes;
      for( $k=0; $k<$cn->length; $k++){
           if( $cn->item($k)->nodeName == "#text" && trim($cn->item($k)->nodeValue) == "") continue;
           $arrayNode->{$cn->item($k)->nodeName} = $cn->item($k)->nodeValue;
      }

      # Attributes
      $attr = $dnl->item($i)->attributes;
      for( $k=0; $k < $attr->length; $k++){
           if(! is_null($attr)){
            if( $attr->item($k)->nodeName == "#text" && trim($attr->item($k)->nodeValue) == "") continue;
            $arrayNode->{$attr->item($k)->nodeName} = $attr->item($k)->nodeValue;
           }
      }

      $res[] = $arrayNode;

       }

     return $res;
 }
?>

To use it:

<?php

  # First you load a XML in a DomDocument variable.

   $url = "/path/to/yourxmlfile.xml";
   $domSrc = file_get_contents($url);
   $dom = new DomDocument();
   $dom->loadXML( $domSrc );

  # Then, you get the ArrayNodes from the DomDocument.

    $ans = getArrayNodes( $dom );

    for( $i=0; $i < count( $ans ) ; $i++){

    $cn =  $ans[ $i];

    $info1 =  $cn->prop1;
    $info2 =  $cn->prop2;
    $info3 =  $cn->prop3;

         // ...

   }

?>
Nick M 01-Jun-2011 10:16
You may need to save all or part of a DOMDocument as an XHTML-friendly string, something compliant with both XML and HTML 4. Here's the DOMDocument class extended with a saveXHTML method:

<?php

/**
 * XHTML Document
 *
 * Represents an entire XHTML DOM document; serves as the root of the document tree.
 */
class XHTMLDocument extends DOMDocument {

  /**
   * These tags must always self-terminate. Anything else must never self-terminate.
   *
   * @var array
   */
  public $selfTerminate = array(
      'area','base','basefont','br','col','frame','hr','img','input','link','meta','param'
  );

  /**
   * saveXHTML
   *
   * Dumps the internal XML tree back into an XHTML-friendly string.
   *
   * @param DOMNode $node
   *         Use this parameter to output only a specific node rather than the entire document.
   */
  public function saveXHTML(DOMNode $node=null) {

    if (!$node) $node = $this->firstChild;

    $doc = new DOMDocument('1.0');
    $clone = $doc->importNode($node->cloneNode(false), true);
    $term = in_array(strtolower($clone->nodeName), $this->selfTerminate);
    $inner='';

    if (!$term) {
      $clone->appendChild(new DOMText(''));
      if ($node->childNodes) foreach ($node->childNodes as $child) {
        $inner .= $this->saveXHTML($child);
      }
    }

    $doc->appendChild($clone);
    $out = $doc->saveXML($clone);

    return $term ? substr($out, 0, -2) . ' />' : str_replace('><', ">$inner<", $out);

  }

}

?>

This hasn't been benchmarked, but is probably significantly slower than saveXML or saveHTML and should be used sparingly.
evert at er dot nl 20-Nov-2010 02:17
A nice and simple node 2 array I wrote, worth a try ;)

<?php
function getArray($node)
{
    $array = false;

    if ($node->hasAttributes())
    {
        foreach ($node->attributes as $attr)
        {
            $array[$attr->nodeName] = $attr->nodeValue;
        }
    }

    if ($node->hasChildNodes())
    {
        if ($node->childNodes->length == 1)
        {
            $array[$node->firstChild->nodeName] = $node->firstChild->nodeValue;
        }
        else
        {
            foreach ($node->childNodes as $childNode)
            {
                if ($childNode->nodeType != XML_TEXT_NODE)
                {
                    $array[$childNode->nodeName][] = $this->getArray($childNode);
                }
            }
        }
    }

    return $array;
}
?>
admin at beerpla dot net 12-Mar-2010 02:12
After seeing many complaints about certain DOMDocument shortcomings, such as bad handling of encodings and always saving HTML fragments with <html>, <head>, and DOCTYPE, I decided that a better solution is needed.

So here it is: SmartDOMDocument. You can find it at http://beerpla.net/projects/smartdomdocument/

Currently, the main highlights are:

- SmartDOMDocument inherits from DOMDocument, so it's very easy to use - just declare an object of type SmartDOMDocument instead of DOMDocument and enjoy the new behavior on top of all existing functionality (see example below).

- saveHTMLExact() - DOMDocument has an extremely badly designed "feature" where if the HTML code you are loading does not contain <html> and <body> tags, it adds them automatically (yup, there are no flags to turn this behavior off).
Thus, when you call $doc->saveHTML(), your newly saved content now has <html><body> and DOCTYPE in it. Not very handy when trying to work with code fragments (XML has a similar problem).
SmartDOMDocument contains a new function called saveHTMLExact() which does exactly what you would want - it saves HTML without adding that extra garbage that DOMDocument does.

- encoding fix - DOMDocument notoriously doesn't handle encoding (at least UTF-8) correctly and garbles the output.
SmartDOMDocument tries to work around this problem by enhancing loadHTML() to deal with encoding correctly. This behavior is transparent to you - just use loadHTML() as you would normally.

- SmartDOMDocument Object As String - you can use a SmartDOMDocument object as a string which will print out its contents.
For example:
<?php
echo "Here is the HTML: $smart_dom_doc";
?>

I'm going to maintain this code and try to fix bugs as they come in.

Enjoy.
tloach at gmail dot com 05-Feb-2010 10:01
For anyone else who has been having issues with formatOuput not working, here is a work-around:

rather than just doing something like:

<?php
$outXML = $xml->saveXML();
?>

force it to reload the XML from scratch, then it will format correctly:

<?php
$outXML = $xml->saveXML();
$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML($outXML);
$outXML = $xml->saveXML();
?>
jay at jaygilford dot com 27-Jan-2010 08:46
Here's a small function I wrote to get all page links using the DOMDocument which will hopefully be of use to others

<?php
/**
 * @author Jay Gilford
 */

/**
 * get_links()
 *
 * @param string $url
 * @return array
 */
function get_links($url) {

    // Create a new DOM Document to hold our webpage structure
    $xml = new DOMDocument();

    // Load the url's contents into the DOM
    $xml->loadHTMLFile($url);

    // Empty array to hold all links to return
    $links = array();

    //Loop through each <a> tag in the dom and add it to the link array
    foreach($xml->getElementsByTagName('a') as $link) {
        $links[] = array('url' => $link->getAttribute('href'), 'text' => $link->nodeValue);
    }

    //Return the links
    return $links;
}
?>
fcartegnie 31-Oct-2009 01:30
Be careful with formatOutput().

Creating an empty node like this:
createElement('foo','')
instead of
createElement('foo')
will break formatOutput.
PhilipWayneRollins at gmail dot com 15-Aug-2009 01:32
If you want to use the DOMDocument to create xHTML documents here is a simple class

Note this is designed for creating xHTML documents from scratch but could be easily extended to work with xHTML documents. Also this is for xHTML not XML.

<?php
    class Document
    {
        public $doctype;
        public $head;
        public $title = 'Sensei Ninja';
        public $body;
        private $styles;
        private $metas;
        private $scripts;
        private $document;

        function __construct (  )
        {
            $this->document = new DOMDocument( );
            $this->head = $this->document->createElement( 'head', ' ' );
            $this->body = $this->document->createElement( 'body', ' ' );
        }

        public function addStyleSheet ( $url, $media='all' )
        {
            $element = $this->document->createElement( 'link' );
            $element->setAttribute( 'type', 'text/css' );
            $element->setAttribute( 'href', $url );
            $element->setAttribute( 'media', $media );
            $this->styles[] = $element;
        }

        public function addScript ( $url )
        {
            $element = $this->document->createElement( 'script', ' ' );
            $element->setAttribute( 'type', 'text/javascript' );
            $element->setAttribute( 'src', $url );
            $this->scripts[] = $element;
        }

        public function addMetaTag ( $name, $content )
        {
            $element = $this->document->createElement( 'meta' );
            $element->setAttribute( 'name', $name );
            $element->setAttribute( 'content', $content );
            $this->metas[] = $element;
        }

        public function setDescription ( $dec )
        {
            $this->addMetaTag( 'description', $dec );
        }

        public function setKeywords ( $keywords )
        {
            $this->addMetaTag( 'keywords', $keywords );
        }

        public function createElement ( $nodeName, $nodeValue=null )
        {
          return $this->document->createElement( $nodeName, $nodeValue );
        }

        public function assemble ( )
        {
            // Doctype creation
            $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML TRANSITIONAL 1.0//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';

            // Create the head element
            $title = $this->document->createElement( 'title', $this->title );
            // Add stylesheets if needed
            if ( is_array( $this->styles ))
                foreach ( $this->styles as $element )
                    $this->head->appendChild( $element );
            // Add scripts if needed
            if(  is_array( $this->scripts ))
                foreach ( $this->scripts as $element )
                    $this->head->appendChild( $element );
            // Add meta tags if needed
            if ( is_array( $this->metas ))
                foreach ( $this->metas as $element )
                    $this->head->appendChild( $element );
            $this->head->appendChild( $title );

            // Create the document
            $html = $this->document->createElement( 'html' );
            $html->setAttribute( 'xmlns', 'http://www.w3.org/1999/xhtml' );
            $html->setAttribute( 'xml:lang', 'en' );
            $html->setAttribute( 'lang', 'en' );
            $html->appendChild( $this->head );
            $html->appendChild( $this->body );

            $this->document->appendChild( $html );
            return $doctype . $this->document->saveXML( );
        }

    }

?>

Small example

<?php
        $document = new Document( );
    $document->title = 'Hello';
    $document->addStyleSheet( 'StyleSheets/main.css' );
    $div = $document->createElement( 'div' );
    $div->nodeValue = 'Hello, world!';
    $div->setAttribute( 'style', 'color: red;' );
    $document->body->appendChild( $div );
    printf( '%s', $document->assemble( ) );
?>
cmyk777 at gmail dot com 23-May-2009 12:31
This function may help to debug current dom element:

<?php
function dom_dump($obj) {
    if ($classname = get_class($obj)) {
        $retval = "Instance of $classname, node list: \n";
        switch (true) {
            case ($obj instanceof DOMDocument):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->saveXML($obj);
                break;
            case ($obj instanceof DOMElement):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->ownerDocument->saveXML($obj);
                break;
            case ($obj instanceof DOMAttr):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->ownerDocument->saveXML($obj);
                //$retval .= $obj->ownerDocument->saveXML($obj);
                break;
            case ($obj instanceof DOMNodeList):
                for ($i = 0; $i < $obj->length; $i++) {
                    $retval .= "Item #$i, XPath: {$obj->item($i)->getNodePath()}\n".
"{$obj->item($i)->ownerDocument->saveXML($obj->item($i))}\n";
                }
                break;
            default:
                return "Instance of unknown class";
        }
    } else {
        return 'no elements...';
    }
    return htmlspecialchars($retval);
}
?>

Example usage:

<?php
$dom = new DomDocument();
$dom->load('test.xml');
$body = $dom->documentElement->getElementsByTagName('book');
echo '<pre>'.dom_dump($body).'<pre>';
?>

Output:

Instance of DOMNodeList, node list:
Item #0, XPath: /library/book[1]
<book isbn="0345342968">
<title>Fahrenheit 451</title>
<author>R. Bradbury</author>
<publisher>Del Rey</publisher>
</book>
Item #1, XPath: /library/book[2]
<book isbn="0048231398">
<title>The Silmarillion</title>
<author>J.R.R. Tolkien</author>
<publisher>G. Allen &amp; Unwin</publisher>
</book>
Item #2, XPath: /library/book[3]
<book isbn="0451524934">
<title>1984</title>
<author>G. Orwell</author>
<publisher>Signet</publisher>
</book>
Item #3, XPath: /library/book[4]
<book isbn="031219126X">
<title>Frankenstein</title>
<author>M. Shelley</author>
<publisher>Bedford</publisher>
</book>
Item #4, XPath: /library/book[5]
<book isbn="0312863551">
<title>The Moon Is a Harsh Mistress</title>
<author>R. A. Heinlein</author>
<publisher>Orb</publisher>
</book>
Fernando H 11-Apr-2008 12:48
Showing a quick example of how to use this class, just so that new users can get a quick start without having to figure it all out by themself. ( At the day of posting, this documentation just got added and is lacking examples. )

<?php

// Set the content type to be XML, so that the browser will   recognise it as XML.
header( "content-type: application/xml; charset=ISO-8859-15" );

// "Create" the document.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );

// Create some elements.
$xml_album = $xml->createElement( "Album" );
$xml_track = $xml->createElement( "Track", "The ninth symphony" );

// Set the attributes.
$xml_track->setAttribute( "length", "0:01:15" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );

// Create another element, just to show you can add any (realistic to computer) number of sublevels.
$xml_note = $xml->createElement( "Note", "The last symphony composed by Ludwig van Beethoven." );

// Append the whole bunch.
$xml_track->appendChild( $xml_note );
$xml_album->appendChild( $xml_track );

// Repeat the above with some different values..
$xml_track = $xml->createElement( "Track", "Highway Blues" );

$xml_track->setAttribute( "length", "0:01:33" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );
$xml_album->appendChild( $xml_track );

$xml->appendChild( $xml_album );

// Parse the XML.
print $xml->saveXML();

?>

Output:
<Album>
  <Track length="0:01:15" bitrate="64kb/s" channels="2">
    The ninth symphony
    <Note>
      The last symphony composed by Ludwig van Beethoven.
    </Note>
  </Track>
  <Track length="0:01:33" bitrate="64kb/s" channels="2">Highway Blues</Track>
</Album>

If you want your PHP->DOM code to run under the .xml extension, you should set your webserver up to run the .xml extension with PHP ( Refer to the installation/configuration configuration for PHP on how to do this ).

Note that this:
<?php
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = $xml->createElement( "Album" );
$xml_track = $xml->createElement( "Track" );
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
?>

is NOT the same as this:
<?php
// Will NOT work.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = new DOMElement( "Album" );
$xml_track = new DOMElement( "Track" );
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
?>

although this will work:
<?php
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = new DOMElement( "Album" );
$xml->appendChild( $xml_album );
?>


Crea un nuevo objeto DOMDocument

  • « DOMDocument
  • DOMDocument::createAttribute »
  • PHP Manual
  • DOMDocument
  • Crea un nuevo objeto DOMDocument

DOMDocument::__construct

(PHP 5, PHP 7)

DOMDocument::__construct — Crea un nuevo objeto DOMDocument

Descripción

public DOMDocument::__construct ( string $version = ? , string $encoding = ? )

Crea un nuevo objeto DOMDocument .

Parámetros

version

El numero de versión del documento como parte de la declaración XML.

encoding

La codificación del documento como parte de la declaración XML.

Ejemplos

Ejemplo #1 Creando un nuevo DOMDocument

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?> */

?>

Ver también

  • DOMImplementation::createDocument() - Crea un objeto DOMDocument del tipo especificado con su elemento documento

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.


Crear nuevo attribute

  • « DOMDocument::__construct
  • DOMDocument::createAttributeNS »
  • PHP Manual
  • DOMDocument
  • Crear nuevo attribute

DOMDocument::createAttribute

(PHP 5, PHP 7)

DOMDocument::createAttribute — Crear nuevo attribute

Descripción

public DOMDocument::createAttribute ( string $name ) : DOMAttr

Esta función crea una nueva instancia de la clase DOMAttr. Este nodo no se mostrará en el documento a no ser que sea insertado con (p.e.j.) DOMNode::appendChild().

Parámetros

name

El nombre del atributo.

Valores devueltos

El nuevo DOMAttr o false si ha ocurrido un error.

Errores/Excepciones

DOM_INVALID_CHARACTER_ERR

Lanzado si name contiene un carácter inválido.

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMDocument::createAttributeNS() - Crea un nuevo nodo atributo con un namespace asociado.
  • DOMDocument::createCDATASection() - Crea un nuevo nodo cdata
  • DOMDocument::createComment() - Crea un nuevo nodo de comentario
  • DOMDocument::createDocumentFragment() - Crea un nuevo fragmento de documento
  • DOMDocument::createElement() - Crea un nuevo nodo elemento
  • DOMDocument::createElementNS() - Crea un nuevo nodo elemento con el nombre de espacio asociado
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Crea un nuevo nodo PI
  • DOMDocument::createTextNode() - Crea un nuevo nodo de texto

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>


Crea un nuevo nodo atributo con un namespace asociado.

  • « DOMDocument::createAttribute
  • DOMDocument::createCDATASection »
  • PHP Manual
  • DOMDocument
  • Crea un nuevo nodo atributo con un namespace asociado.

DOMDocument::createAttributeNS

(PHP 5, PHP 7)

DOMDocument::createAttributeNS — Crea un nuevo nodo atributo con un namespace asociado.

Descripción

public DOMDocument::createAttributeNS ( string $namespaceURI , string $qualifiedName ) : DOMAttr

Esta función crea una nueva instancia de la clase DOMAttr. Este nodo no se mostrará en el documento a no ser que sea insertado con (p.e.j.) DOMNode::appendChild().

Parámetros

namespaceURI

El URI del namespace.

qualifiedName

El nombre de etiqueta y prefijo del atributo, como prefix:tagname.

Valores devueltos

El nuevo DOMAttr o false si ha ocurrido un error.

Errores/Excepciones

DOM_INVALID_CHARACTER_ERR

Lanzado siqualifiedName contiene un carácter inválido.

DOM_NAMESPACE_ERR

Lanzado si qualifiedName es un nombre calificado mal formado , o si qualifiedName tiene un prefijo y namespaceURI es null.

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMDocument::createAttribute() - Crear nuevo attribute
  • DOMDocument::createCDATASection() - Crea un nuevo nodo cdata
  • DOMDocument::createComment() - Crea un nuevo nodo de comentario
  • DOMDocument::createDocumentFragment() - Crea un nuevo fragmento de documento
  • DOMDocument::createElement() - Crea un nuevo nodo elemento
  • DOMDocument::createElementNS() - Crea un nuevo nodo elemento con el nombre de espacio asociado
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Crea un nuevo nodo PI
  • DOMDocument::createTextNode() - Crea un nuevo nodo de texto

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>

    */

?>


Crea un nuevo nodo cdata

  • « DOMDocument::createAttributeNS
  • DOMDocument::createComment »
  • PHP Manual
  • DOMDocument
  • Crea un nuevo nodo cdata

DOMDocument::createCDATASection

(PHP 5, PHP 7)

DOMDocument::createCDATASection — Crea un nuevo nodo cdata

Descripción

public DOMDocument::createCDATASection ( string $data ) : DOMCDATASection

Esta función crea una nueva instancia de la clase DOMCDATASection. Este nodo no se mostrará en el documento a no ser que sea insertado con (p.e.j.) DOMNode::appendChild().

Parámetros

data

El contenido del cdata.

Valores devueltos

El nuevo DOMCDATASection o false si ha ocurrido un error.

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMDocument::createAttribute() - Crear nuevo attribute
  • DOMDocument::createAttributeNS() - Crea un nuevo nodo atributo con un namespace asociado.
  • DOMDocument::createComment() - Crea un nuevo nodo de comentario
  • DOMDocument::createDocumentFragment() - Crea un nuevo fragmento de documento
  • DOMDocument::createElement() - Crea un nuevo nodo elemento
  • DOMDocument::createElementNS() - Crea un nuevo nodo elemento con el nombre de espacio asociado
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Crea un nuevo nodo PI
  • DOMDocument::createTextNode() - Crea un nuevo nodo de texto

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


Crea un nuevo nodo de comentario

  • « DOMDocument::createCDATASection
  • DOMDocument::createDocumentFragment »
  • PHP Manual
  • DOMDocument
  • Crea un nuevo nodo de comentario

DOMDocument::createComment

(PHP 5, PHP 7)

DOMDocument::createComment — Crea un nuevo nodo de comentario

Descripción

public DOMDocument::createComment ( string $data ) : DOMComment

Esta función crea una nueva instancia de la clase DOMComment. Este nodo no se mostrará en el documento a no ser que sea insertado con (p.e.j.) DOMNode::appendChild().

Parámetros

data

El contenido del comentario.

Valores devueltos

El nuevo DOMComment o false si ha ocurrido un error.

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMDocument::createAttribute() - Crear nuevo attribute
  • DOMDocument::createAttributeNS() - Crea un nuevo nodo atributo con un namespace asociado.
  • DOMDocument::createCDATASection() - Crea un nuevo nodo cdata
  • DOMDocument::createDocumentFragment() - Crea un nuevo fragmento de documento
  • DOMDocument::createElement() - Crea un nuevo nodo elemento
  • DOMDocument::createElementNS() - Crea un nuevo nodo elemento con el nombre de espacio asociado
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Crea un nuevo nodo PI
  • DOMDocument::createTextNode() - Crea un nuevo nodo de texto

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.


Crea un nuevo fragmento de documento

  • « DOMDocument::createComment
  • DOMDocument::createElement »
  • PHP Manual
  • DOMDocument
  • Crea un nuevo fragmento de documento

DOMDocument::createDocumentFragment

(PHP 5, PHP 7)

DOMDocument::createDocumentFragment — Crea un nuevo fragmento de documento

Descripción

public DOMDocument::createDocumentFragment ( ) : DOMDocumentFragment

Esta función crea una nueva instancia de la clase DOMDocumentFragment. Este nodo no se mostrará en el documento a no ser que sea insertado con (p.e.j.) DOMNode::appendChild().

Valores devueltos

El nuevo DOMDocumentFragment o false si ha ocurrido un error.

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMDocument::createAttribute() - Crear nuevo attribute
  • DOMDocument::createAttributeNS() - Crea un nuevo nodo atributo con un namespace asociado.
  • DOMDocument::createCDATASection() - Crea un nuevo nodo cdata
  • DOMDocument::createComment() - Crea un nuevo nodo de comentario
  • DOMDocument::createElement() - Crea un nuevo nodo elemento
  • DOMDocument::createElementNS() - Crea un nuevo nodo elemento con el nombre de espacio asociado
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Crea un nuevo nodo PI
  • DOMDocument::createTextNode() - Crea un nuevo nodo de texto

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo nodo elemento

  • « DOMDocument::createDocumentFragment
  • DOMDocument::createElementNS »
  • PHP Manual
  • DOMDocument
  • Crea un nuevo nodo elemento

DOMDocument::createElement

(PHP 5, PHP 7)

DOMDocument::createElement — Crea un nuevo nodo elemento

Descripción

public DOMDocument::createElement ( string $name , string $value = ? ) : DOMElement

Esta función crea una nueva instancia de la clase DOMElement. Este nodo no se mostrará en el documento a no ser que sea insertado con (p.e.j.) DOMNode::appendChild().

Parámetros

name

El nombre de etiqueta del elemento.

value

El valor del elemento. De manera predeterminada se creará un elemento vacio. El valor también puede ser asignado más tarde con DOMElement::$nodeValue.

El valor es usado al pie de la letra, excepto que las referencias de entidad < y > se escaparán. Tenga en cuenta que & tiene que ser escapado manualmente; de lo contrario, se tomará como inicio de una referencia de entidad. Además " no sera escapado.

Valores devueltos

Devuelve una nueva instanca de la clase DOMElement o false si ha ocurrido un error.

Errores/Excepciones

DOM_INVALID_CHARACTER_ERR

Lanzado si name contiene un carácter inválido.

Ejemplos

Ejemplo #1 Crear un nuevo elemento e insertarlo como raíz

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElement('test', 'This is the root element!');

// Insertamos el nuevo elemento como raíz (hijo del documento)
$dom->appendChild($element);

echo $dom->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0" encoding="utf-8"?>
<test>This is the root element!</test>

Ejemplo #2 Pasando texto que contiene un & sin escapar como valor

<?php
$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->createElement('foo', 'me & you');
$dom->appendChild($element);
echo $dom->saveXML();
?>

El resultado del ejemplo sería algo similar a:

Warning: DOMDocument::createElement(): unterminated entity reference             you in /in/BjTCg on line 4
<?xml version="1.0" encoding="utf-8"?>
<foo/>

Notas

Nota:

El parámetro value no será escapado. Utilice DOMDocument::createTextNode() para crear un nodo de texto con soporte para escape de carácteres.

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMDocument::createAttribute() - Crear nuevo attribute
  • DOMDocument::createAttributeNS() - Crea un nuevo nodo atributo con un namespace asociado.
  • DOMDocument::createCDATASection() - Crea un nuevo nodo cdata
  • DOMDocument::createComment() - Crea un nuevo nodo de comentario
  • DOMDocument::createDocumentFragment() - Crea un nuevo fragmento de documento
  • DOMDocument::createElementNS() - Crea un nuevo nodo elemento con el nombre de espacio asociado
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Crea un nuevo nodo PI
  • DOMDocument::createTextNode() - Crea un nuevo nodo de texto

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


Crea un nuevo nodo elemento con el nombre de espacio asociado

  • « DOMDocument::createElement
  • DOMDocument::createEntityReference »
  • PHP Manual
  • DOMDocument
  • Crea un nuevo nodo elemento con el nombre de espacio asociado

DOMDocument::createElementNS

(PHP 5, PHP 7)

DOMDocument::createElementNS — Crea un nuevo nodo elemento con el nombre de espacio asociado

Descripción

public DOMDocument::createElementNS ( string $namespaceURI , string $qualifiedName , string $value = ? ) : DOMElement

Esta función crea un nuevo nodo elemento con el nombre de espacio asociado. Este nodo no se mostrará en el documento a no ser que sea insertado con (p.e.j.) DOMNode::appendChild().

Parámetros

namespaceURI

El URI del nombre de espacio.

qualifiedName

Elo nombre cualificado del elemento, como prefix:tagname.

value

El valor del elemento. De manera predeterminada se creará un elemento vacio. El valor también puede ser asignado más tarde con DOMElement::$nodeValue.

Valores devueltos

El nuevo DOMElement o false si ha ocurrido un error.

Errores/Excepciones

DOM_INVALID_CHARACTER_ERR

Lanzado si qualifiedName contiene un carácter inválido.

DOM_NAMESPACE_ERR

Lanzado si qualifiedName es un nombre cualificado mal formado.

Ejemplos

Ejemplo #1 Crear un nuevo elemento e insertarlo como raíz

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');

// Insertamos el nuevo elemento como raíz (hijo del documento)
$dom->appendChild($element);

echo $dom->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0" encoding="utf-8"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

Ejemplo #2 Un ejemplo de prefijo de nombre de espacio

<?php
$doc  = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElementNS('http://www.w3.org/2005/Atom', 'element');
$doc->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:g', 'http://base.google.com/ns/1.0');
$item = $doc->createElementNS('http://base.google.com/ns/1.0', 'g:item_type', 'house');
$root->appendChild($item);

echo $doc->saveXML(), "\n";

echo $item->namespaceURI, "\n"; // Outputs: http://base.google.com/ns/1.0
echo $item->prefix, "\n";       // Outputs: g
echo $item->localName, "\n";    // Outputs: item_type
?>

El resultado del ejemplo sería:

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

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMDocument::createAttribute() - Crear nuevo attribute
  • DOMDocument::createAttributeNS() - Crea un nuevo nodo atributo con un namespace asociado.
  • DOMDocument::createCDATASection() - Crea un nuevo nodo cdata
  • DOMDocument::createComment() - Crea un nuevo nodo de comentario
  • DOMDocument::createDocumentFragment() - Crea un nuevo fragmento de documento
  • DOMDocument::createElement() - Crea un nuevo nodo elemento
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Crea un nuevo nodo PI
  • DOMDocument::createTextNode() - Crea un nuevo nodo de texto

User Contributed Notes

Martin 27-Dec-2011 09:39
To avoid multiple xmlns re-declaration, make sure you appending ElementNS into actual DOMDocument tree (not into some currently-assembed derelict element).


Create new entity reference node

  • « DOMDocument::createElementNS
  • DOMDocument::createProcessingInstruction »
  • PHP Manual
  • DOMDocument
  • Create new entity reference node

DOMDocument::createEntityReference

(PHP 5, PHP 7)

DOMDocument::createEntityReference — Create new entity reference node

Descripción

public DOMDocument::createEntityReference ( string $name ) : DOMEntityReference

Esta función crea una nueva instancia de la clase DOMEntityReference. Este nodo no se mostrará en el documento a no ser que sea insertado con (p.e.j.) DOMNode::appendChild().

Parámetros

name

El contenido de la entidad referencia, p.ej. la entidad referencia menos los carácteres & inicial y el ; final.

Valores devueltos

El nuevo DOMEntityReference o false si ha ocurrido un error.

Errores/Excepciones

DOM_INVALID_CHARACTER_ERR

Lanzado si name contiene un carácter inválido.

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMDocument::createAttribute() - Crear nuevo attribute
  • DOMDocument::createAttributeNS() - Crea un nuevo nodo atributo con un namespace asociado.
  • DOMDocument::createCDATASection() - Crea un nuevo nodo cdata
  • DOMDocument::createComment() - Crea un nuevo nodo de comentario
  • DOMDocument::createDocumentFragment() - Crea un nuevo fragmento de documento
  • DOMDocument::createElement() - Crea un nuevo nodo elemento
  • DOMDocument::createElementNS() - Crea un nuevo nodo elemento con el nombre de espacio asociado
  • DOMDocument::createProcessingInstruction() - Crea un nuevo nodo PI
  • DOMDocument::createTextNode() - Crea un nuevo nodo de texto

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 ©


Crea un nuevo nodo PI

  • « DOMDocument::createEntityReference
  • DOMDocument::createTextNode »
  • PHP Manual
  • DOMDocument
  • Crea un nuevo nodo PI

DOMDocument::createProcessingInstruction

(PHP 5, PHP 7)

DOMDocument::createProcessingInstruction — Crea un nuevo nodo PI

Descripción

public DOMDocument::createProcessingInstruction ( string $target , string $data = ? ) : DOMProcessingInstruction

Esta función crea una nueva instancia de la clase DOMProcessingInstruction. Este nodo no se mostrará en el documento a no ser que sea insertado con (p.e.j.) DOMNode::appendChild().

Parámetros

target

El objetivo de la instrucción de procesamiento.

data

El contenido de la instrucción de procesamiento.

Valores devueltos

El nuevo DOMProcessingInstruction o false si ha ocurrido un error.

Errores/Excepciones

DOM_INVALID_CHARACTER_ERR

Lanzado si target contiene un carácter inválido.

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMDocument::createAttribute() - Crear nuevo attribute
  • DOMDocument::createAttributeNS() - Crea un nuevo nodo atributo con un namespace asociado.
  • DOMDocument::createCDATASection() - Crea un nuevo nodo cdata
  • DOMDocument::createComment() - Crea un nuevo nodo de comentario
  • DOMDocument::createDocumentFragment() - Crea un nuevo fragmento de documento
  • DOMDocument::createElement() - Crea un nuevo nodo elemento
  • DOMDocument::createElementNS() - Crea un nuevo nodo elemento con el nombre de espacio asociado
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createTextNode() - Crea un nuevo nodo de texto

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>


Crea un nuevo nodo de texto

  • « DOMDocument::createProcessingInstruction
  • DOMDocument::getElementById »
  • PHP Manual
  • DOMDocument
  • Crea un nuevo nodo de texto

DOMDocument::createTextNode

(PHP 5, PHP 7)

DOMDocument::createTextNode — Crea un nuevo nodo de texto

Descripción

public DOMDocument::createTextNode ( string $content ) : DOMText

Esta función crea una nueva instancia de la clase DOMText. Este nodo no se mostrará en el documento a no ser que sea insertado con (p.e.j.) DOMNode::appendChild().

Parámetros

content

El contenido del texto.

Valores devueltos

El nuevo DOMText o false si ha ocurrido un error.

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMDocument::createAttribute() - Crear nuevo attribute
  • DOMDocument::createAttributeNS() - Crea un nuevo nodo atributo con un namespace asociado.
  • DOMDocument::createCDATASection() - Crea un nuevo nodo cdata
  • DOMDocument::createComment() - Crea un nuevo nodo de comentario
  • DOMDocument::createDocumentFragment() - Crea un nuevo fragmento de documento
  • DOMDocument::createElement() - Crea un nuevo nodo elemento
  • DOMDocument::createElementNS() - Crea un nuevo nodo elemento con el nombre de espacio asociado
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Crea un nuevo nodo 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);
?>


Busca un elemento con cierto id

  • « DOMDocument::createTextNode
  • DOMDocument::getElementsByTagName »
  • PHP Manual
  • DOMDocument
  • Busca un elemento con cierto id

DOMDocument::getElementById

(PHP 5, PHP 7)

DOMDocument::getElementById — Busca un elemento con cierto id

Descripción

public DOMDocument::getElementById ( string $elementId ) : DOMElement

Esta función es similar a DOMDocument::getElementsByTagNamepero busca un elemento con el id dado.

Para que esta función trabaje, necesitará asignar algunos atributos ID con DOMElement::setIdAttribute o un DTD que defina un atributo de tipo ID. En el último caso necesitará validar el documento con DOMDocument::validate o DOMDocument::$validateOnParse antes de utilizar esta función.

Parámetros

elementId

El valor de id único para un elemento.

Valores devueltos

Devuelve el DOMElement o null si el elemento no ha sido encontrado.

Ejemplos

Ejemplo #1 Ejemplo de DOMDocument::getElementById()

Los siguientes ejemplos usan book.xml, cuyo contenido es el siguiente:

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

// Necesitamos validar nuestro documento antes de referirnos al id
$doc->validateOnParse = true;
$doc->Load('book.xml');

echo "The element whose id is 'php-basics' is: " . $doc->getElementById('php-basics')->tagName . "\n";

?>

El resultado del ejemplo sería:

The element whose id is 'php-basics' is: book

Ver también

  • DOMDocument::getElementsByTagName() - Busca todos los elementos con el nombre de etiqueta local dado

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.


Busca todos los elementos con el nombre de etiqueta local dado

  • « DOMDocument::getElementById
  • DOMDocument::getElementsByTagNameNS »
  • PHP Manual
  • DOMDocument
  • Busca todos los elementos con el nombre de etiqueta local dado

DOMDocument::getElementsByTagName

(PHP 5, PHP 7)

DOMDocument::getElementsByTagName — Busca todos los elementos con el nombre de etiqueta local dado

Descripción

public DOMDocument::getElementsByTagName ( string $name ) : DOMNodeList

Esta función devuelve una nueva instancia de la clase DOMNodeList que contiene los elementos con el nombre de etiqueta local buscado.

Parámetros

name

El nombre local (sin namespace) de la etiqueta con el cual se hará comparación. El valor especial * coincindirá con todas las etiquetas.

Valores devueltos

Un nuevo objeto DOMNodeList que contiene todos los elementos coincidentes.

Ejemplos

Ejemplo #1 Ejemplo de uso básico

<?php
$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<books>
 <book>Patrones de Arquitectura de Aplicaciones Empresariales</book>
 <book>Patrones de diseño: elementos de diseño de software reutilizable</book>
 <book>Código limpio</book>
</books>
XML;

$dom = new DOMDocument;
$dom->loadXML($xml);
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
    echo $book->nodeValue, PHP_EOL;
}
?>

El resultado del ejemplo sería:

Patrones de Arquitectura de Aplicaciones Empresariales
Patrones de diseño: elementos de diseño de software reutilizable
Código limpio

Ver también

  • DOMDocument::getElementsByTagNameNS() - Busca todos los elementos con el nombre de etiqueta dado en el espacio de nombre especificado.

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


Busca todos los elementos con el nombre de etiqueta dado en el espacio de nombre especificado.

  • « DOMDocument::getElementsByTagName
  • DOMDocument::importNode »
  • PHP Manual
  • DOMDocument
  • Busca todos los elementos con el nombre de etiqueta dado en el espacio de nombre especificado.

DOMDocument::getElementsByTagNameNS

(PHP 5, PHP 7)

DOMDocument::getElementsByTagNameNS — Busca todos los elementos con el nombre de etiqueta dado en el espacio de nombre especificado.

Descripción

public DOMDocument::getElementsByTagNameNS ( string $namespaceURI , string $localName ) : DOMNodeList

Devuelve un DOMNodeList de todos los elementos con el nombre local dado y el URI del espacio de nombre.

Parámetros

namespaceURI

El URI del espacio de nombre de los elementos en los que se buscara. El valor especial * coincide con todos los espacios de nombre.

localName

El nombre local de los elementos buscados. El valor especial * coincide con todos los nombres locales.

Valores devueltos

Un nuevo objeto DOMNodeList que contiene todos los elementos coincidentes.

Ejemplos

Ejemplo #1 Obtener todos los elementos 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";
}
?>

El resultado del ejemplo sería:

local name: include, prefix: xi
local name: fallback, prefix: xi

Ver también

  • DOMDocument::getElementsByTagName() - Busca todos los elementos con el nombre de etiqueta local dado

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


Importa un nodo dentro del documento actual

  • « DOMDocument::getElementsByTagNameNS
  • DOMDocument::load »
  • PHP Manual
  • DOMDocument
  • Importa un nodo dentro del documento actual

DOMDocument::importNode

(PHP 5, PHP 7)

DOMDocument::importNode — Importa un nodo dentro del documento actual

Descripción

public DOMDocument::importNode ( DOMNode $importedNode , bool $deep = false ) : DOMNode

Esta función devuelve una copia del nodo a importar y le asocia con el documento actual.

Parámetros

importedNode

El nodo que desea importar

deep

Si se establece en true, este método importará de forma recursiva el subárbol bajo el importedNode.

Nota:

Para copiar los atributos de los nodos deep debe establecerse a true

Valores devueltos

El nodo copiado o false, si no puede ser copiado.

Errores/Excepciones

DOMException es lanzado si el nodo no puede ser importado.

Ejemplos

Ejemplo #1 DOMDocument::importNode() ejemplo

Copiando nodos entre documentos.

<?php

$orgdoc = new DOMDocument;
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>");

// El nodo que se quiere importar al nuevo documento
$node = $orgdoc->getElementsByTagName("element")->item(0);

// Crear un nuevo documento
$newdoc = new DOMDocument;
$newdoc->formatOutput = true;

// Agregar marcado
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>");

echo "The 'new document' before copying nodes into it:\n";
echo $newdoc->saveXML();

// Importar el nodo y todos sus hijos al documento
$node = $newdoc->importNode($node, true);
// y entonces anexarlo a el nodo "<root>"
$newdoc->documentElement->appendChild($node);

echo "\nThe 'new document' after copying the nodes into it:\n";
echo $newdoc->saveXML();
?>

El resultado del ejemplo sería:

The 'new document' before copying nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
</root>

The 'new document' after copying the nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
  <element>
    <child>text in child</child>
  </element>
</root>

User Contributed Notes

rikdnua at mail dot ru 11-Sep-2013 01:54
The behavior of importNode($node, false) is different in PHP 5.2.9-2 and PHP 5.2.17.
The second option is explicitly set to false. In PHP 5.2.9-2 importNode() imports the elements WITHOUT attributes. In PHP 5.2.17 the elements imported ALONG with their attributes.
<?php
$xml="
<html>
<a href='yandex.com'>Yandex.com</a>
<a href='rik.dn.ua'>RiK.dn.ua</a>
</html>
";
$doc=new domDocument('1.0');
$doc->loadXML($xml);
$list=$doc->getElementsByTagName('a');
$doc1=new domDocument('1.0');
$doc1->formatOutput=true;
for($i=0; $i<$list->length; $i++) $doc1->appendChild($doc1->importNode($list->item($i), false));
$doc1->save('file.xml');
?>

file.xml PHP 5.2.9-2
<?xml version="1.0"?>
<a/>
<a/>

file.xml PHP 5.2.17
<?xml version="1.0"?>
<a href="yandex.com"/>
<a href="rik.dn.ua"/>
c dot 1 at smithies dot org 19-Oct-2009 06:40
Assume that $source and $dest are instances of DOMDocument. Assume that $sourcedoc contains an element with ID 'sourceID' and that $destdoc contains an element with ID 'destID'. Assume that we have already set up source and destination element variables thus:

<?php
 $src = $sourcedoc->getElementById('sourceID');
 $dst = $destdoc->getElementById('destID');
?>

Finally, assume that $sel has more than one child node.

In order to import the child elements of $src as children of $dst, you might do something like this:

<?php
$src = $dest->importNode($src, TRUE);

foreach ($src->childNodes as $el) $dst->appendChild($el);
?>

But this does not work. foreach gets confused, because (as noted below) appending an imported element to another existing element in the same document causes it to be removed from its current parent element.

Therefore, the following technique should be used:

<?php
foreach ($src->childNodes as $el) $dst->appendChild($destdoc->importNode($el, TRUE));
?>
p dot reisinger at gmail dot com 29-Dec-2008 03:43
When you use function/method below, php automaticaly inserts namespaces (if you have some). If you want to join xml files exactly, then you can just use placeholders and treat xml as a string.
<?php
function joinXMLStrings($file1, $file2)
{
    //remove xml declaration
    $file2 = trim(preg_replace('/<\?xml.*\?>/', '', $file2, 1));

    //insert file2 in the place of placeholder in the first file
    $file1 = trim(preg_replace('/<\?file2\s\?>/', $file2, $file1, 1));
}
?>

so function looks like this and you insert two xml files. First file has to have placeholder (where you insert file2). Placeholder in this case will be <?file2 ?>

!!!this is only for ilustration - test before you use it
p dot reisinger at gmail dot com 23-Dec-2008 07:32
method (can be used as a function as well) that joins two xml files. first argument is parent xml (the one to be inserted into), second child (the one to be inserted) and third is optional argument that specifies the parent's tag where to insert children xml. If not specified then children is inserted as the last element, just before end of the root
<?php
    protected function joinXML($parent, $child, $tag = null)
    {
        $DOMChild = new DOMDocument;
        $DOMChild->loadXML($child);
        $node = $DOMChild->documentElement;

        $DOMParent = new DOMDocument;
        $DOMParent->formatOutput = true;
        $DOMParent->loadXML($parent);

        $node = $DOMParent->importNode($node, true);

        if ($tag !== null) {
            $tag = $DOMParent->getElementsByTagName($tag)->item(0);
            $tag->appendChild($node);
        } else {
            $DOMParent->documentElement->appendChild($node);
        }

        return $DOMParent->saveXML();
    }
?>
mailme at sove dot nl 11-Jun-2008 05:29
DOMDocument->importNode with seconds argument false will leave attributes behind. To fix this:

$__DOM->importNode
   (
      $__INPUT->cloneNode(false), true
   );

$__DOM (DOMDocument) will import the $__INPUT node (DOMElement) INCLUDING attributes.
mark at 4inloop dot de 05-Apr-2007 05:51
When you left out the second argument or enter false, not only the child nodes are ommited. The attributes of the node are also cut off.
adjwilli 05-Oct-2006 01:08
Editing XML with PHP can be a pain in the Secretary of State Powell, so here's a script to replace an XML node with a user-provided one through the POST. It's usually a good idea to run the $_POST['xml'] through a validation check and clean it for other thing before running this.

Pretty much this script expects a user-provided node called $_POST['xml'] and the XPath of the node in the original document that you want to replace called $_POST['XPath']. It also loads the original XML document from $xml. The function nodeRunner begins with the root node of the document you're editting and the XPath for the root element (these are more to make recursion easy than anything else).

$doc = new DOMDocument();
$doc->loadXML($xml); // $xml expects an XML string

function nodeRunner ($node,$xpath) {
    global $doc;
    if ($xpath == $_POST['XPath']) {

        $xmlPost = new DOMDocument();
        $xmlPost->loadXML($_POST['xml']);

        $newNode = $doc->importNode($xmlPost->firstChild,true);

        $node->parentNode->replaceChild($newNode,$node);
    } else {

        $page = 1;
        $section = 1;

        if ($node->hasChildNodes()) {
            foreach ($node->childNodes as $nodling) {
                $nodeName = $nodling->nodeName;
                if ($nodeName == 'page' || $nodeName == 'section') {
                    nodeRunner ($nodling,$xpath."/".$nodeName."[".$$nodeName."]");
                    $$nodeName++;
                }
            }
        }
    }
}

nodeRunner ($doc->documentElement,"/root[1]"); // /root should be explicit name of the root  element of the XPath

$doc->saveXML();
stomas 19-Sep-2006 06:14
I think this should do the same:

<?
 // Import $b into $a's document
 function myimport($a, $b)
 {
   if ($a->ownerDocument->isSameNode($b->ownerDocument))
   {
    return $b->cloneNode(TRUE);
   }
   else
   {
    return $a->ownerDocument->importNode($b, TRUE);
   }
 }
 ?>
Colin 12-Sep-2006 09:11
As of PHP 5.1.6 with libxml 2.6.26 and DOM/XML API version 20031129, importNode() does nothing if attempting to import from the same document.  Meaning, if you do an $ret = importNode and then appendChild($ret) or insertBefore($ret, ...) then you will end up *moving* the node instead of ending up with a copy.

If you expect importNode to give you a copy of the source (in this case, a deep copy) then you must account for them being from the same document.  This function addresses this:

<?
// Import $b into $a's document
function myimport($a, $b)
{
  if ($a->ownerDocument->isSameNode($b->ownerDocument))
  {
    $temp = new DOMDocument();
    $ret = $temp->importNode($b, TRUE);
    return $a->ownerDocument->importNode($ret, TRUE);
  }
  else
  {
    return $a->ownerDocument->importNode($b, TRUE);
  }
}
?>

(Function was freshly coded for this note but I based it off another, working function of mine.)

This function checks if the documents are the same and uses a new document (guaranteed to be different this way) to force a copy into $temp and then force a copy back into $a->ownerDocument.

Obviously, no error checking has been done.
andy dot clark at dial dot pipex dot com 15-Aug-2006 08:20
One useful use of importNode is to copy one node onto another.

function CopyXMLNode($SourceNode,$DestNode)
 {
  if ($SourceNode->nodeName != '#text')
   {
     //Copy this node
    $node = $DestNode->ownerDocument->importNode($SourceNode, true);
    $node = $DestNode->appendChild($node);
    //Now copy the child nodes
    foreach ($SourceNode->childNodes AS $item)
     {
     $this->CopyXMLNode($item,$node);
     }
    }
  }
Fitopaldi 03-Aug-2005 11:29
importNode returns a copy of the node to import and associates it with the current document, but not import the node to the current DOMDocument. Use appendChild for import the copy of the node to current DOMDocument.

<?
 $domNode = $dom->importNode($aDomNode, true);
 $currentDomDocument->appendChild($domNode);
?>


Cargar un documento XML de un archivo.

  • « DOMDocument::importNode
  • DOMDocument::loadHTML »
  • PHP Manual
  • DOMDocument
  • Cargar un documento XML de un archivo.

DOMDocument::load

(PHP 5, PHP 7)

DOMDocument::load — Cargar un documento XML de un archivo.

Descripción

public DOMDocument::load ( string $filename , int $options = 0 ) : mixed

Carga un documento XML de un archivo.

Advertencia

Rutas tipo Unix con barras inclinadas hacia a delante, pueden causar una degradacion significativa de rendimiento en sistemas Windows, si es el caso, asegúrese de llamar realpath().

Parámetros

filename

La ruta al documento XML.

options

Bitwise OR de las constantes de opción libxml.constants.html.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error. Si se llama estáticamente, devuelve un DOMDocument o false en caso de error.

Errores/Excepciones

Si una cadena vacia es pasada como el filename o se pasa el nombre de un archivo vacío, se generará una advertencia. Esta advertencia no es generada por libxml y no puede ser manejada utilizando las funciones de manejo de erro de libxml.

Este método puede ser llamado de forma estática, pero lanzará un error E_STRICT.

Ejemplos

Ejemplo #1 Creando un Documento

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

Ver también

  • DOMDocument::loadXML() - Cargar XML desde una cadena
  • DOMDocument::save() - Copia el árbol XML interno a un archivo
  • DOMDocument::saveXML() - Copia el arbol XML interno a un string

User Contributed Notes

sainthyoga2003 at gmail dot com 09-Feb-2012 03:37
in the default example:

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

you must enter the absolute path for book.xml due for get a false result in load function.
sainthyoga2003 at gmail dot com 25-Feb-2011 05:38
i've found the partial solution for xml:id warning,is explained at this address: https://fosswiki.liip.ch/display/BLOG/GetElementById+Pitfalls

there explains that:
The ID does have to be a valid NCName, which for example means, that the first letter can't be a number.

and in my xml:id i had a number. :D
sainthyoga2003 at gmail dot com 16-Feb-2011 09:31
adding an id for a child, when i use abstract mode i get the following warning:

[quote]Warning: DOMDocument::load() [domdocument.load]: xml:id : attribute value xx is not an NCName in /fake/path/to/xmlfile[/quote]
_ michael 01-Jun-2010 08:34
load() will handle non-ASCII characters depending on the details of the XML declaration, but in a somewhat surprising way. One would assume that the declarations '<?xml version="1.0" encoding="UTF-8"?>' and '<?xml version="1.0"?>' are treated in the same way because UTF-8 is the default encoding anyway. But not so.

* If there is an XML declaration defining the encoding *explicitly*, the non-ASCII characters remain unchanged.
* If the XML declaration does not define the encoding explicitly, or if the XML declaration is missing, non-ASCII characters are converted into numeric entities.

So the document

    <?xml version="1.0"?>
    <root><nonascii>ä</nonascii></root>

will be converted to

    <?xml version="1.0"?>
    <root><nonascii>&#xE4;</nonascii></root>

The same happens if there is no XML declaration at all. On the other hand, the document

    <?xml version="1.0" encoding="UTF-8"?>
    <root><nonascii>ä</nonascii></root>

will remain as it is.

This behaviour applies to loadXML() as well.
_ michael 19-Apr-2010 07:50
XHTML and entities: The solution proposed below by zachatwork at gmail dot com didn't work for me. I checked on a number of servers (both LAMPP and WAMPP) - on each of them, calling loadXML() with the LIBXML_DTDLOAD option triggered an external request for the DTD. And that's bad news.

If allow_url_fopen is turned off, the request for the DTD fails with a warning. If it is turned on, the request fails because these w3c URLs return a 503 Service Unavailable.

HTML entities still generate a warning in either case.

The best solution, as far as I can tell, is simply to ignore the warnings and suppress them using '@'. I can't recommend parsing XHTML with loadHTML() instead of loadXML() - yes, you get rid of the entity problem, but loadHTML() changes the source while parsing it (tries to 'fix' it even though there is nothing to fix).
zachatwork at gmail dot com 30-Jun-2009 11:28
You can easily avoid the warning about &nbsp; references by using the LIBXML_DTDLOAD option.

<?php

$html = <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  </head>
  <body>
    <p>&nbsp;</p>
  </body>
</html>
EOF;

// This one works perfectly.
$dom = new DOMDocument();
$dom->loadXML($html, LIBXML_DTDLOAD);
print $dom->saveXML();

// This one produces a warning.
$dom = new DOMDocument();
$dom->loadXML($html);
print $dom->saveXML();

?>

See also: http://www.php.net/manual/en/libxml.constants.php

Note that libxml will detect that your DTD is locally available via /etc/xml/catalog. So there is no worry about this causing your DOM loads to make external network requests.
Jonas Due Vesterheden 09-Jun-2009 08:18
I had a problem with loading documents over HTTP. I would get errors looking like this:

Warning: DOMDocument::load(http://external/document.xml): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error

The document would load fine in browsers and using wget. The problem is that DOMDocument::load() on my systems (both OS X and Linux) didn't send any User-Agent header which for some weird reason made Microsoft-IIS/6.0 respond with the 500 error.

The solution is found on http://php.net/manual/en/function.libxml-set-streams-context.php :

<?php
$opts = array(
    'http' => array(
        'user_agent' => 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');
?>
syntaxiko 04-Apr-2009 10:16
Function will not work if using XML DOM PECL module
darren at viamedia dot co dot za 05-Aug-2008 07:17
If you are loading xml with the intention of validating it against an internal dtd and you have experienced issues with the validation it could be related to missing LIBXML constants.

I found this post by "aidan at php dot net" in root level dom docs and thought it might be more useful here:
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:
<?php
$dom = new DOMDocument;
// Resolve externals
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);
// OR
// Validate against DTD
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
$dom->validate();
?>
the_N_Channel 15-Jul-2008 04:53
NOTE, will not load successfully if there is a comment at the beginning of the file before the <?xml version="1.0" ?> declaration!
hh dot lohmann at yahoo dot de 30-Aug-2007 03:48
BadGuy´s note may be confusing since what he depicts is no special property of the relevant method. PHP works always in and on a local file system which means that if you want to use resources from other systems or - what is, indeed, BadGuy´s problem - need resources that have been dealt with by other programs or processes, you have to state and manage that explicitly in your code. PHP is just a quite normal program in that.

BadGuy´s solution is using the "http wrapper" to get output from another process (see "wrappers" in the PHP manual). Doing this, the appropriate syntax for http calls has to be respected.
admin at tijnema dot tijnema dot info 02-Jun-2007 04:39
In reply to BadGuy [at] BadGuy [dot] nl

When the news.php file is located on the same server, like you said in the first example then http://my.beautiful-website.com/xmlsource/news.php wouldn't work, but you should use http://localhost/xmlsource/news.php or http://127.0.0.1/xmlsource/news.php
BadGuy [at] BadGuy [dot] nl 18-Jan-2007 08:50
Note that this method uses the local file system before doing anything remote. The 'disadvantage' would be that if you would do the following:
<?php
$xml = new DOMDocument;
$xml->load("xmlsource/news.php");
?>

This would not make the method read the actual output of the news.php file --presumably valid xml data--, but the file contents --obviously this would be php code. So this will return an error saying news.php is missing the xml declaration and maybe the xml start-tag

What would work is the following:

<?php
$xml = new DOMDocument;
$xml->load("http://my.beautiful-website.com/xmlsource/news.php");
?>

This will force a http request to be used to get this file instead of just locally reading it and the file just returning code
daevid at daevid dot com 18-Oct-2005 05:08
Suppose you wanted to dynamically load an array from an .XSD file. This method is your guy. just remember to use the actual xs: portion in xpaths and such.

All the other "load" methods will error out.

<?php
$attributes = array();
$xsdstring = "/htdocs/api/xsd/common.xsd";
$XSDDOC = new DOMDocument();
$XSDDOC->preserveWhiteSpace = false;
if ($XSDDOC->load($xsdstring))
{
    $xsdpath = new DOMXPath($XSDDOC);
    $attributeNodes =
              $xsdpath->
              query('//xs:simpleType[@name="attributeType"]')
              ->item(0);
    foreach ($attributeNodes->childNodes as $attr)
    {
        $attributes[ $attr->getAttribute('value') ] = $attr->getAttribute('name');
    }
    unset($xsdpath);
}
print_r($attributes);
?>


Cargar HTML de una cadena

  • « DOMDocument::load
  • DOMDocument::loadHTMLFile »
  • PHP Manual
  • DOMDocument
  • Cargar HTML de una cadena

DOMDocument::loadHTML

(PHP 5, PHP 7)

DOMDocument::loadHTML — Cargar HTML de una cadena

Descripción

public DOMDocument::loadHTML ( string $source , int $options = 0 ) : bool

Esta función procesa el HTML contenido en la cadena source. De manera distinta a cargar XML, HTML no tiene que estar bien formado para cargarse. Esta función también puede llamarse estáticamente para cargar y crear un objeto DOMDocument. La invocación estática puede utilizarse aún cuando ninguna propiedad de DOMDocument haya sido establecida antes de la lectura.

Parámetros

source

La cadena HTML.

options

Desde PHP 5.4.0 y Libxml 2.6.0, se puede usar el parámetro options para especificar parámetros de Libxml adicionales.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error. Si es llamada de manera estática devuelve un objeto DOMDocument o false en caso de error.

Errores/Excepciones

Si una cadena vacía es pasada como el source o se pasa el nombre de un archivo vacío, se generará una advertencia. Esta advertencia no es generada por libxml y no puede ser manejada utilizando las funciones de manejo de errores de libxml.

Este método puede ser llamado de forma estática, pero lanzará un error E_STRICT.

Aunque el HTML malformado debería cargar con éxito, esta función puede generar errores E_WARNING al encontrarse con marcado erróneo. Se pueden usar las funciones de manejo de errores de libxml para manejar estos errores.

Ejemplos

Ejemplo #1 Creando un Documento

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();
?>

Historial de cambios

Versión | Descripción
5.4.0 | Se añadió el parámero options.

Ver también

  • DOMDocument::loadHTMLFile() - Cargar HTML desde un fichero
  • DOMDocument::saveHTML() - Copia el documento interno a una cadena usando el formato HTML
  • DOMDocument::saveHTMLFile() - Copia el documento interno a un fichero usando el formato HTML

User Contributed Notes

deepakrajpal dot com at gmail dot com 20-Nov-2020 06:16
If we are loading html5 tags such as <section>, <svg> there is following error:

DOMDocument::loadHTML(): Tag section invalid in Entity

We can disable standard libxml errors (and enable user error handling) using libxml_use_internal_errors(true); before loadHTML();

This is quite useful in phpunit custom assertions as given in following example (if using phpunit test cases):

// Create a DOMDocument
$dom = new DOMDocument();

// fix html5/svg errors
libxml_use_internal_errors(true);

// Load html
$dom->loadHTML("<section></section>");
$htmlNodes = $dom->getElementsByTagName('section');

if ($htmlNodes->length == 0) {
    $this->assertFalse(TRUE);
} else {
    $this->assertTrue(TRUE);
}
divinity76+spam at gmail dot com 14-Sep-2020 09:25
if you want to get rid of all the "DOMText elements containing ONLY whitespace", maybe try

<?php

function loadHTML_noemptywhitespace(string $html, int $extra_flags = 0, int $exclude_flags = 0): DOMDocument
{
    $flags = LIBXML_HTML_NODEFDTD | LIBXML_NOBLANKS | LIBXML_NONET;
    $flags = ($flags | $extra_flags) & ~ $exclude_flags;

    $domd = new DOMDocument();
    $domd->preserveWhiteSpace = false;
    @$domd->loadHTML('<?xml encoding="UTF-8">' . $html, $flags);
    $removeAnnoyingWhitespaceTextNodes = function (\DOMNode $node) use (&$removeAnnoyingWhitespaceTextNodes): void {
        if ($node->hasChildNodes()) {
            // Warning: it's important to do it backwards; if you do it forwards, the index for DOMNodeList might become invalidated;
            // that's why i don't use foreach() - don't change it (unless you know what you're doing, ofc)
            for ($i = $node->childNodes->length - 1; $i >= 0; --$i) {
                $removeAnnoyingWhitespaceTextNodes($node->childNodes->item($i));
            }
        }
        if ($node->nodeType === XML_TEXT_NODE && !$node->hasChildNodes() && !$node->hasAttributes() && empty(trim($node->textContent))) {
            //echo "Removing annoying POS";
            // var_dump($node);
            $node->parentNode->removeChild($node);
        } //elseif ($node instanceof DOMText) { echo "not removed"; var_dump($node, $node->hasChildNodes(), $node->hasAttributes(), trim($node->textContent)); }
    };
    $removeAnnoyingWhitespaceTextNodes($domd);
    return $domd;
}
BychkovVV at mail dot ru 03-Apr-2020 08:30
If you are loading html content from any website, in "utf-8" encoding, when meta width content-type is not first child of HEAD, it would not be acknowledged by parser (encoding); So you can make this fix:
  function domLoadHTML($html)
           {$testDOM = new DOMDocument('1.0', 'UTF-8');
            $testDOM->loadHTML($html);
            $charset = NULL;
            $searchInElemnt = function(&$item) use (&$searchInElemnt, &$charset)
              {if($item->childNodes)
                 {foreach($item->childNodes as $childItem)
                    {switch($childItem->nodeName)
                       {case 'html':
                        case 'head':
                          $searchInElemnt($childItem);
                          break;
                        case 'meta':
                          $attributes = array();
                          foreach ($childItem->attributes as $attr)
                            {$attributes[mb_strtoupper($attr->localName)] = $attr->nodeValue;
                            }
                          if(array_key_exists('HTTP-EQUIV', $attributes) && (mb_strtoupper($attributes['HTTP-EQUIV']) == 'CONTENT-TYPE') && array_key_exists('CONTENT', $attributes) && preg_match('~[\s]*;[\s]*charset[\s]*=[\s]*([^\s]+)~', $attributes['CONTENT'], $matches))
                            {$charset = preg_replace('~[\s\']~', '', $matches[1]);
                            }
                       }
                    }
                 }
              };
            $searchInElemnt($testDOM);
            if(isset($charset))
              {$dom = new DOMDocument('1.0', $charset);
               $dom->loadHTML('<?xml encoding="'.$charset.'">'.$html);
               foreach ($dom->childNodes as $item)
               if($item->nodeType == XML_PI_NODE)
                 {$dom->removeChild($item);
                 }
               $dom->encoding = $charset;
              }
            else
              {$dom = $testDOM;
              }
            return $dom;
           };
kerim-yagmurcu at gmx dot de 24-Dec-2016 03:13
For those of you who want to get an external URL's class element, I have 2 usefull functions. In this example we get the '<h3 class="r">'
 elements back (search result headers) from google search:

1. Check the URL (if it is reachable, existing)
<?php
# URL Check
function url_check($url) {
    $headers = @get_headers($url);
    return is_array($headers) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$headers[0]) : false;
};
?>

2. Clean the element you want to get (remove all tags, tabs, new-lines etc.)
<?php
# Function to clean a string
function clean($text){
    $clean = html_entity_decode(trim(str_replace(';','-',preg_replace('/\s+/S', " ", strip_tags($text)))));// remove everything
    return $clean;
    echo '\n';// throw a new line
}
?>

After doing that, we can output the search result headers with following method:
<?php
$searchstring = 'djceejay';
$url = 'http://www.google.de/webhp#q='.$searchstring;
if(url_check($url)){
    $doc = new DomDocument;
    $doc->validateOnParse = true;
    $doc->loadHtml(file_get_contents($url));
    $output = clean($doc->getElementByClass('r')->textContent);
    echo $output . '<br>';
}else{
    echo 'URL not reachable!';// Throw message when URL not be called
}
?>
fr at felix-riesterer dot de 13-Feb-2016 01:43
Remember: If you use an HTML5 doctype and a meta element like so

<meta CHARSET=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.


Cargar HTML desde un fichero

  • « DOMDocument::loadHTML
  • DOMDocument::loadXML »
  • PHP Manual
  • DOMDocument
  • Cargar HTML desde un fichero

DOMDocument::loadHTMLFile

(PHP 5, PHP 7)

DOMDocument::loadHTMLFile — Cargar HTML desde un fichero

Descripción

public DOMDocument::loadHTMLFile ( string $filename , int $options = 0 ) : bool

Esta función analiza el documento HTML del fichero llamado filename. A diferencia de cargar XML, HTML no tiene que estar bien formado para cargarse.

Parámetros

filename

La ruta al fichero HTML.

options

Desde PHP 5.4.0 y Libxml 2.6.0, se puede usar el parámetro options para especificar parámetros de Libxml adicionales.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error. Si se llama estáticamente, devuelve un DOMDocument o false en caso de error.

Errores/Excepciones

Si se pasa una cadena vacía a filename o se nombra un fichero vacío, se generará una advertencia. Esta advertencia no es generada por libxml y no se puede tratar usando funciones de manejo de errores de libxml.

Este método puede ser llamado de forma estática, pero lanzará un error E_STRICT.

Aunque el HTML malformado debería cargar con éxito, esta función puede generar errores E_WARNING al encontrarse con marcado erróneo. Se pueden usar las funciones de manejo de errores de libxml para manejar estos errores.

Ejemplos

Ejemplo #1 Crear un Documento

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
echo $doc->saveHTML();
?>

Historial de cambios

Versión | Descripción
5.4.0 | Se añadió el parámero options.

Ver también

  • DOMDocument::loadHTML() - Cargar HTML de una cadena
  • DOMDocument::saveHTML() - Copia el documento interno a una cadena usando el formato HTML
  • DOMDocument::saveHTMLFile() - Copia el documento interno a un fichero usando el formato 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.


Cargar XML desde una cadena

  • « DOMDocument::loadHTMLFile
  • DOMDocument::normalizeDocument »
  • PHP Manual
  • DOMDocument
  • Cargar XML desde una cadena

DOMDocument::loadXML

(PHP 5, PHP 7)

DOMDocument::loadXML — Cargar XML desde una cadena

Descripción

public DOMDocument::loadXML ( string $source , int $options = 0 ) : mixed

Carga un documento XML desde una cadena.

Parámetros

source

La cadena que contiene el XML.

options

Operador a nivel de bits OR de las constantes de opciones libxml.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error. Si se llama estáticamente, devuelve un DOMDocument o false en caso de error.

Errores/Excepciones

Si se pasa una cadena vacía a source, se generará una advertencia. Esta advertencia no es generada por libxml y no puede ser tratada usando funciones de manejo de errores de libxml.

Ejemplos

Ejemplo #1 Crear un Documento

<?php
$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Ejemplo #2 Invocación estática de loadXML

<?php
$doc = DOMDocument::loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Ver también

  • DOMDocument::load() - Cargar un documento XML de un archivo.
  • DOMDocument::save() - Copia el árbol XML interno a un archivo
  • DOMDocument::saveXML() - Copia el arbol XML interno a un string

User Contributed Notes

Adrian Wiik 13-Nov-2019 09:02
A call to loadXML() will overwrite the XML declaration previously created in the constructor of DOMDocument. This can cause encoding problems if there is no XML declaration in the loaded XML and you don't have control over the source (e.g. if the XML is coming from a webservice). To fix this, set encoding AFTER loading the XML using the 'encoding' class property of DOMDocument. Example:

Bad situation:

test.xml:
<test>
    <hello>hi</hello>
    <field>ø</field>
</test>

test.php:
$xmlDoc = new DOMDocument("1.0", "utf-8"); // Parameters here are overwritten anyway when using loadXML(), and are not really relevant
$testXML = file_get_contents("test.xml");
$xmlDoc->loadXML($testXML);
// Print the contents to a file or in a log function to get the output, using $xmlDoc->saveXML()

Output:
<?xml version="1.0"?>
<test>
    <hello>hi</hello>
    <field>&#xF8;</field>
</test>

Good situation:

test.xml:
<test>
    <hello>hi</hello>
    <field>ø</field>
</test>

test.php:
$xmlDoc = new DOMDocument("1.0", "utf-8"); // Parameters here are overwritten anyway when using loadXML(), and are not really relevant
$testXML = file_get_contents("test.xml");
$xmlDoc->loadXML($testXML);
$xmlDoc->encoding = "utf-8";
// Print the contents to a file or in a log function to get the output, using $xmlDoc->saveXML()

Output:
<?xml version="1.0" encoding="utf-8"?>
<test>
    <hello>hi</hello>
    <field>ø</field>
</test>
Gustavo L. Fabro 14-Nov-2013 04:41
Always remember that with the default parameters this function doesn't handle well large files, i.e. if a text node is longer than 10Mb it can raise an exception stating:

DOMDocument::loadXML(): internal error Extra content at the end of the document in Entity

even though the XML is fine.

The cause is a definition in parserInternals.h of lixml:
#define XML_MAX_TEXT_LENGTH 10000000

To allow the function to process larger files, pass the LIBXML_PARSEHUGE as an option and it will work just fine:

$domDocument->loadXML($xml, LIBXML_PARSEHUGE);
szalma dot laszlo at zengo dot eu 27-Oct-2009 08:14
Loading from a string works fine without the <?xml version="1.0" encoding="utf-8"?> header, but in this case the xmlEncoding won't be set, and this makes the utf-8 characters (international, and special characters) to be encoded as hexa entities when saved with saveXML()!
remacg 26-Feb-2009 07:33
Instead of doing this:

<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$dd2->loadXML($str);

echo $dd2->saveXML();
?>

simply use:

loadHTML() rather than loadXML().
olalonde at NOSPAM dot gmail dot com 21-Mar-2008 05:00
For some reason, when you set DOMDocument's property 'recover' to true, using '@' to mask errors thrown by loadXml() won't work.

Here's my workaround:

function maskErrors() {}
set_error_handler('maskErrors');
$dom->loadXml($xml);
restore_error_handler();

You could also simply do this: error_reporting(0); and then set back error_reporting to its original state.
Stuart Grimshaw 26-Jun-2007 01:57
Possible values for the options parameter can be found here:

http://us3.php.net/manual/en/ref.libxml.php#libxml.constants
Marc Liyanage 18-Jun-2007 07:08
The documentation states that loadXML can be called statically, but this is misleading. This feature seems to be a special case hack and its use seems to be discouraged according to http://bugs.php.net/bug.php?id=41398.

Calling the method statically will fail with an error if the code runs with E_STRICT error reporting enabled.

The documentation should be changed to make it clear that a static call is against recommended practice and won't work with E_STRICT.
jazzslider at hotmail dot com 30-Apr-2007 01:14
When using loadXML() to parse a string that contains entity references (e.g., &nbsp;), be sure that those entity references are properly declared through the use of a DOCTYPE declaration; otherwise, loadXML() will not be able to interpret the string.

Example:
<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd1 = new DOMDocument();
$dd1->loadXML($str);

echo $dd1->saveXML();
?>

Given the above code, PHP will issue a Warning about the entity 'nbsp' not being properly declared.  Also, the call to saveXML() will return nothing but a trimmed-down version of the original processing instruction...everything else is gone, and all because of the undeclared entity.

Instead, explicitly declare the entity first:
<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$dd2->loadXML($str);

echo $dd2->saveXML();
?>

Since the 'nbsp' entity is defined in the DOCTYPE, PHP no longer issues that Warning; the string is now well-formed, and loadXML() understands it perfectly.

You can also use references to external DTDs in the same way (e.g., <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">), which is particularly important if you need to do this for many different documents with many different possible entities.

Also, as a sidenote...entity references created by createEntityReference() do not need this kind of explicit declaration.
shaoyu73 at gmail dot com 15-Mar-2007 08:53
earth at anonymous dot com,

preserveWhiteSpace property needs to be set to false for formatOutput to work properly, for some reason.

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadXML($xmlStr);
...
$element->appendChild(...);
...
$dom->formatOutput = true;
$xmlStr = $dom->saveXML();
echo $xmlStr;

This would format the output nicely.
Gavin Sinai gsinai at gmx dot net 30-Aug-2006 07:34
loadXml reports an error instead of throwing an exception when the xml is not well formed. This is annoying if you are trying to to loadXml() in a try...catch statement. Apparently its a feature, not a bug, because this conforms to a spefication.

If you want to catch an exception instead of generating a report, you could do something like

<?php
function HandleXmlError($errno, $errstr, $errfile, $errline)
{
    if ($errno==E_WARNING && (substr_count($errstr,"DOMDocument::loadXML()")>0))
    {
        throw new DOMException($errstr);
    }
    else
        return false;
}

function XmlLoader($strXml)
{
    set_error_handler('HandleXmlError');
    $dom = new DOMDocument();
    $dom->loadXml($strXml);
    restore_error_handler();
    return $dom;
 }

?>

Returning false in function HandleXmlError() causes a fallback to the default error handler.
mp at webfactory dot de 08-Aug-2006 08:26
While loadXML() expects its input to have a leading XML processing instruction to deduce the encoding used, there's no such concept in (non-XML) HTML documents. Thus, the libxml library underlying the DOM functions peeks at the <META> tags to figure out the encoding used.

See http://xmlsoft.org/encoding.html.
earth at anonymous dot com 12-Apr-2006 02:28
Note that loadXML crops off beginning and trailing whitespace and linebreaks.

When using loadXML and appendChild to add a chunk of XML to an existing document, you may want to force a linebreak between the end of the XML chunk and the next line (usually a close tag) in the output file:

$childDocument = new DOMDocument;
$childDocument>preserveWhiteSpace = true;
$childDocument->loadXML(..XML-Chunk..);
$mNewNode = $mainDOcument->importNode($childDocument->documentElement, true);
$ParentNode->appendChild($mNewNode);
$ParentNode->appendChild($mainDocument->createTextNode("\\n  ");

Although it is said that DOM should not be used to make 'pretty' XML output, it is something I struggled with to get something that was readable for testing.  Another solution is to use the createDocumentFragment()->appendXML(..XML-Chunk..) instead, which seems not to trim off linebreaks like DOMDocument->loadXML() does.


Normaliza el documento

  • « DOMDocument::loadXML
  • DOMDocument::registerNodeClass »
  • PHP Manual
  • DOMDocument
  • Normaliza el documento

DOMDocument::normalizeDocument

(PHP 5, PHP 7)

DOMDocument::normalizeDocument — Normaliza el documento

Descripción

public DOMDocument::normalizeDocument ( ) : void

Este método actúa como si guardara y después cargara el documento, poniendo el el documento en una forma "normal".

Valores devueltos

No devuelve ningún valor.

Ver también

  • » La Especificación DOM
  • DOMNode::normalize() - Normaliza el nodo

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.


Registra una clase extendida usada para crear tipos de nodos base

  • « DOMDocument::normalizeDocument
  • DOMDocument::relaxNGValidate »
  • PHP Manual
  • DOMDocument
  • Registra una clase extendida usada para crear tipos de nodos base

DOMDocument::registerNodeClass

(PHP 5 >= 5.2.0, PHP 7)

DOMDocument::registerNodeClass — Registra una clase extendida usada para crear tipos de nodos base

Descripción

public DOMDocument::registerNodeClass ( string $baseclass , string $extendedclass ) : bool

Este método permite registrar su propia clase DOM extendida para usarla después por la extensión DOM de PHP.

Este método no es parte del estándar DOM.

Parámetros

baseclass

La clase DOM que se quiere extender. Se puede encontrar una lista de estas clases en el capítulo introducción.

extendedclass

El nombre de la clase extendida. Si se proporciona null, cualquier clase registrada previamente que extienda baseclass será eliminada.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
5.2.2 | Antes de 5.2.2, una extendedclass previamente registrada teniá que ser desregistrada antes de poder registrar una nueva clase que extendiese a la misma baseclass.

Ejemplos

Ejemplo #1 Añadir un nuevo método a DOMElement para facilitar su código

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

// A partir de ahora, ¡ añadir un elemento a otro sólo cuesta una llamada al método !
$root = $doc->setRoot('root');
$child = $root->appendElement('child');
$child->setAttribute('foo', 'bar');

echo $doc->saveXML();

?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<root><child foo="bar"/></root>

Ejemplo #2 Recuperar elementos como clase personalizada

<?php
class myElement extends DOMElement {
    public function __toString() {
        return $this->nodeValue;
    }
}

$doc = new DOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");
$doc->registerNodeClass("DOMElement", "myElement");

$element = $doc->getElementsByTagName("child")->item(0);
var_dump(get_class($element));

// Y tomar ventaja del método __toString ...
echo $element;
?>

El resultado del ejemplo sería:

string(9) "myElement"
text in child

Ejemplo #3 Recuperar un propio documento

Al instanciar un DOMDocument personalizado, la propiedad ownerDocument se referirá a la clase instanciada, lo que significa que no hay necesidad (y de hecho no es posible) de usar DOMDocument::registerNodeClass() con DOMDocument

<?php
class myDOMDocument extends DOMDocument {
}

class myOtherDOMDocument extends DOMDocument {
}

// Crear myDOMDocument con algo de XML
$doc = new myDOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");

$child = $doc->getElementsByTagName("child")->item(0);

// El actual propietario del nodo es myDOMDocument
var_dump(get_class($child->ownerDocument));

// Importar un nodo desde myDOMDocument
$newdoc = new myOtherDOMDocument;
$child = $newdoc->importNode($child);

// El propietario del nodo ha cambiado a myOtherDOMDocument
var_dump(get_class($child->ownerDocument));
?>

El resultado del ejemplo sería:

string(13) "myDOMDocument"
string(18) "myOtherDOMDocument"

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().


Realiza una validación relaxNG del documento

  • « DOMDocument::registerNodeClass
  • DOMDocument::relaxNGValidateSource »
  • PHP Manual
  • DOMDocument
  • Realiza una validación relaxNG del documento

DOMDocument::relaxNGValidate

(PHP 5, PHP 7)

DOMDocument::relaxNGValidate — Realiza una validación relaxNG del documento

Descripción

public DOMDocument::relaxNGValidate ( string $filename ) : bool

Realiza una validación » relaxNG del documento basándose en el esquema RNG dado.

Parámetros

filename

El fichero RNG.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • DOMDocument::relaxNGValidateSource() - Realiza una validación relaxNG del documento
  • DOMDocument::schemaValidate() - Valida un documento basado en un esquema
  • DOMDocument::schemaValidateSource() - Valida un documento basado en un esquema
  • DOMDocument::validate() - Valida el documento basado en su DTD

User Contributed Notes

scarywound at gmail dot com 17-Oct-2012 11:39
Keep in mind that this method can't handle schemas in compact syntax!
mitchell dot beaumont at mitchellbeaumont dot com 26-Aug-2007 07:28
It's worth noting that when validation fails this function also triggers a warning.

You can suppress the warning using the set_error_handler and restore_error_handler functions.


Realiza una validación relaxNG del documento

  • « DOMDocument::relaxNGValidate
  • DOMDocument::save »
  • PHP Manual
  • DOMDocument
  • Realiza una validación relaxNG del documento

DOMDocument::relaxNGValidateSource

(PHP 5, PHP 7)

DOMDocument::relaxNGValidateSource — Realiza una validación relaxNG del documento

Descripción

public DOMDocument::relaxNGValidateSource ( string $source ) : bool

Realiza una validación » relaxNG del documento basándose en la fuente RNG dada.

Parámetros

source

Una cadena que contiene el esquema RNG.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • DOMDocument::relaxNGValidate() - Realiza una validación relaxNG del documento
  • DOMDocument::schemaValidate() - Valida un documento basado en un esquema
  • DOMDocument::schemaValidateSource() - Valida un documento basado en un esquema
  • DOMDocument::validate() - Valida el documento basado en su DTD

User Contributed Notes

There are no user contributed notes for this page.


Copia el árbol XML interno a un archivo

  • « DOMDocument::relaxNGValidateSource
  • DOMDocument::saveHTML »
  • PHP Manual
  • DOMDocument
  • Copia el árbol XML interno a un archivo

DOMDocument::save

(PHP 5, PHP 7)

DOMDocument::save — Copia el árbol XML interno a un archivo

Descripción

public DOMDocument::save ( string $filename , int $options = 0 ) : int

Crea un documento XML desde la representación DOM. Esta función normalmente se llama después de construir un nuevo documento desde ceros, como en el ejemplo de abajo.

Parámetros

filename

La ruta al documento XML guardado.

options

Opciones Adicionales. Actualmente sólo está soportada LIBXML_NOEMPTYTAG.

Valores devueltos

Devuelve el número de bytes escritos o false si ocurrió un error.

Historial de cambios

Versión | Descripción
5.1.0 | Se añadió el parámetro options

Ejemplos

Ejemplo #1 Guardar un árbol DOM en un fichero

<?php

$doc = new DOMDocument('1.0');
// queremos una impresión buena
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('Este es el título');
$text = $title->appendChild($text);

echo 'Escrito: ' . $doc->save("/tmp/test.xml") . ' bytes'; // Escrito: 72 bytes

?>

Ver también

  • DOMDocument::saveXML() - Copia el arbol XML interno a un string
  • DOMDocument::load() - Cargar un documento XML de un archivo.
  • DOMDocument::loadXML() - Cargar XML desde una cadena

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


Copia el documento interno a una cadena usando el formato HTML

  • « DOMDocument::save
  • DOMDocument::saveHTMLFile »
  • PHP Manual
  • DOMDocument
  • Copia el documento interno a una cadena usando el formato HTML

DOMDocument::saveHTML

(PHP 5, PHP 7)

DOMDocument::saveHTML — Copia el documento interno a una cadena usando el formato HTML

Descripción

public DOMDocument::saveHTML ( DOMNode $node = NULL ) : string

Crea un documento HTML desde la representación DOM. Esta función normalmente se llama después de construir un nuevo documento desde cero, como en el ejemplo de abajo.

Parámetros

node

Parámetro opcional que devuelve una parte del documento.

Valores devueltos

Devuelve el HTML, o false si ocurrió un error.

Historial de cambios

Versión | Descripción
5.3.6 | El parámetro node fue añadido.

Ejemplos

Ejemplo #1 Salvar un árbol HTML en una cadena

<?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('Este es el título');
$text = $title->appendChild($text);

echo $doc->saveHTML();

?>

Ver también

  • DOMDocument::saveHTMLFile() - Copia el documento interno a un fichero usando el formato HTML
  • DOMDocument::loadHTML() - Cargar HTML de una cadena
  • DOMDocument::loadHTMLFile() - Cargar HTML desde un fichero

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.
RiKdnUA at mail dot ru 29-Apr-2015 03:49
Tested in PHP 5.2.9-2 and PHP 5.2.17.
saveHTML() ?????????? ???????? DOMDocument->encoding. ????? saveHTML() ????????? html-???????? ? ?????????, ??????? ??????? ? ???? <meta> ????????? (????????????) html-?????????.
saveHTML() ignores property DOMDocument->encoding. Method saveHTML() saves the html-document encoding, which is specified in the tag <meta> source (downloaded) html-document.
Example:
file.html. ????????? ????? ?????? ????????? ? ????????? ? ???? <meta>. The encoding of the file must match the specified tag <meta>.
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<title>Russian language</title></head>
<body>??????? ????</body></html>

<?php
error_reporting(-1);
$document=new domDocument('1.0', 'UTF-8');
$document->preserveWhiteSpace=false;
$document->loadHTMLFile('file.html');
$document->formatOutput=true;
$document->encoding='UTF-8';
$htm=$document->saveHTML();
echo"???????? ????. Recorded bytes: ".file_put_contents('file_new.html', $htm);
?>
file_new.html ????? ? ????????? Windows-1251 (?? ? UTF-8).
file_new.html will be encoded in Windows-1251 (not in UTF-8).

saveHTML() ? file_put_contents() ????????? ?????????? ?????????? ?????? saveHTMLFile().
???????? ??? ??????????? ? ?????? saveHTMLFile().
saveHTML() and file_put_contents() allows you to overcome the lack of a method saveHTMLFile().
See my comment on the method saveHTMLFile().
http://php.net/manual/ru/domdocument.savehtmlfile.php
qrworld.net 11-Nov-2014 04:34
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
alvaro at demogracia dot com 29-Mar-2011 11:04
Since PHP/5.3.6, DOMDocument->saveHTML() accepts an optional DOMNode parameter similarly to DOMDocument->saveXML():

http://bugs.php.net/bug.php?id=39771
Yajo 24-Nov-2010 07:21
Another way to workaround the <script/> problem is putting a semicolon (;) inside the script element.
Anonymous 09-Feb-2010 07:52
If you want a simpler way to get around the <script> tag problem try:

<?php

  $script = $doc->createElement ('script');\
  // Creating an empty text node forces <script></script>
  $script->appendChild ($doc->createTextNode (''));
  $head->appendChild ($script);

?>
Anonymous 12-May-2009 07:35
To avoid script tags from being output as <script />, you can use the DOMDocumentFragment class:

<?php

$doc = new DOMDocument();
$doc -> loadXML($xmlstring);
$fragment = $doc->createDocumentFragment();
/* Append the script element to the fragment using raw XML strings (will be preserved in their raw form) and if succesful proceed to insert it in the DOM tree */
if($fragment->appendXML("<script type='text/javascript' src='$source'></script>") {
  $xpath = new DOMXpath($doc);
  $resultlist = $xpath->query("//*[local-name() = 'html']/*[local-name() = 'head']"); /* namespace-safe method to find all head elements which are childs of the html element, should only return 1 match */
  foreach($resultlist as $headnode)  // insert the script tag
     $headnode->appendChild($fragment);
}
$doc->saveXML(); /* and our script tags will still be <script></script> */

?>
Bart Feenstra 18-Jan-2009 10:17
I am using this solution to prevent tags and the doctype from being added to the HTML string automatically:

<?php
$html = '<h1>Hello world!</h1>';
$html = '<div>' . $html . '</div>';
$doc = new DOMDocument;
$doc->loadHTML($html);
echo substr($doc->saveXML($doc->getElementsByTagName('div')->item(0)), 5, -6)

// Outputs: "<h1>Hello world!</h1>"
?>
m at hbblogs daught calm 18-Aug-2008 08:41
This method, as of 5.2.6, will automatically add <html><body> and <!DOCTYPE> tags to the document if they are missing, without asking whether you want them. In my application, I needed to use the DOM methods to manipulate just a fragment of html, so these tags were rather unhelpful.

Here's a simple hack to remove them in case, like me, all you wanted to do was perform a few operations on an HTML fragment.

$html_fragment = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
Anonymous 25-Apr-2008 08:15
<?php
function getDOMString($retNode) {
  if (!$retNode) return null;
  $retval = strtr($retNode-->ownerDocument->saveXML($retNode),
  array(
    '></area>' => ' />',
    '></base>' => ' />',
    '></basefont>' => ' />',
    '></br>' => ' />',
    '></col>' => ' />',
    '></frame>' => ' />',
    '></hr>' => ' />',
    '></img>' => ' />',
    '></input>' => ' />',
    '></isindex>' => ' />',
    '></link>' => ' />',
    '></meta>' => ' />',
    '></param>' => ' />',
    'default:' => '',
    // sometimes, you have to decode entities too...
    '&quot;' => '&#34;',
    '&amp;' =>  '&#38;',
    '&apos;' => '&#39;',
    '&lt;' =>   '&#60;',
    '&gt;' =>   '&#62;',
    '&nbsp;' => '&#160;',
    '&copy;' => '&#169;',
    '&laquo;' => '&#171;',
    '&reg;' =>   '&#174;',
    '&raquo;' => '&#187;',
    '&trade;' => '&#8482;'
  ));
  return $retval;
}
?>
mjaque at ilkebenson dot com 19-Feb-2008 11:34
DOMDocument->saveXML() doesn't generate a proper XHTML format either.

There is a problem with "script" empty elements. For example:

This will be the code generated by saveXML, with an empty script tag.

<html>
  <head>
    <script type="text/JavaScript" src="myScript.js"/>
  </head>
  <body>
    <p>I will not appear</p>
    <script type="text/JavaScript">
    alert("Not working");
    </script>
  </body>
</html>

I don't know if this is valid XHTML (W3C Validator doesn't complain), but both FF 2.0 and IE 6 will not render it properly. Both will use </script> as the closing tag for the first script causing js errors and ignoring in between elements.

You can post-process saveXML string in order to close empty tags with the following function:

<?php
    function cerrarTag($tag, $xml){
        $indice = 0;
        while ($indice< strlen($xml)){
            $pos = strpos($xml, "<$tag ", $indice);
            if ($pos){
                $posCierre = strpos($xml, ">", $pos);
                if ($xml[$posCierre-1] == "/"){
                    $xml = substr_replace($xml, "></$tag>", $posCierre-1, 2);
                }
                $indice = $posCierre;
            }
            else break;
        }
        return $xml;
    }
?>

At least script and select empty elements should be closed. This example shows how it can be used:

<?php
    define("CABECERA_XHTML", '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');

  $xhtml = $docXML->saveXML($docXML->documentElement);
  $xhtml = cerrarTag("script", $xhtml);
  $xhtml = cerrarTag("select", $xhtml);
  $xhtml = CABECERA_XHTML."\n".$xhtml;
  echo $xhtml;
?>
archanglmr at yahoo dot com 27-Nov-2007 03:28
If created your DOMDocument object using loadHTML() (where the source is from another site) and want to pass your changes back to the browser you should make sure the HTTP Content-Type header matches your meta content-type tags value because modern browsers seem to ignore the meta tag and trust just the HTTP header. For example if you're reading an ISO-8859-1 document and your web server is claiming UTF-8 you need to correct it using the header() function.

<?php
header('Content-Type: text/html; charset=iso-8859-1');
?>
xoplqox 20-Nov-2007 11:07
XHTML:

If the output is XHTML use the function saveXML().

Output example for saveHTML:

<select name="pet" size="3" multiple>
    <option selected>mouse</option>
    <option>bird</option>
    <option>cat</option>
</select>

XHTML conform output using saveXML:

<select name="pet" size="3" multiple="multiple">
    <option selected="selected">mouse</option>
    <option>bird</option>
    <option>cat</option>
</select>
tyson at clugg dot net 21-Apr-2005 05:44
<?php
// Using DOM to fix sloppy HTML.
// An example by Tyson Clugg <tyson@clugg.net>
//
// vim: syntax=php expandtab tabstop=2

function tidyHTML($buffer)
{
  // load our document into a DOM object
  $dom = @DOMDocument::loadHTML($buffer);
  // we want nice output
  $dom->formatOutput = true;
  return($dom->saveHTML());
}

// start output buffering, using our nice
// callback funtion to format the output.
ob_start("tidyHTML");

?>
<html>
<p>It's like comparing apples to oranges.
</html>
<?php

// this will be called implicitly, but we'll
// call it manually to illustrate the point.
ob_end_flush();

?>

The above code takes out sloppy HTML:
 <html>
 <p>It's like comparing apples to oranges.
 </html>

And cleans it up to the following:
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
 <html><body><p>It's like comparing apples to oranges.
 </p></body></html>


Copia el documento interno a un fichero usando el formato HTML

  • « DOMDocument::saveHTML
  • DOMDocument::saveXML »
  • PHP Manual
  • DOMDocument
  • Copia el documento interno a un fichero usando el formato HTML

DOMDocument::saveHTMLFile

(PHP 5, PHP 7)

DOMDocument::saveHTMLFile — Copia el documento interno a un fichero usando el formato HTML

Descripción

public DOMDocument::saveHTMLFile ( string $filename ) : int

Crea un documento HTML desde la representación DOM. Esta función normalmente se llama después de construir un nuevo documento desde cero, como en el ejemplo de abajo.

Parámetros

filename

La ruta al documento HTML guardado.

Valores devueltos

Devuelve el número de bytes escritos o false si ocurrió un error.

Ejemplos

Ejemplo #1 Guardar un árbol HTML en un archivo

<?php

$doc = new DOMDocument('1.0');
// queremos una impresión buena
$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('Este es el título');
$text = $title->appendChild($text);

echo 'EScrito: ' . $doc->saveHTMLFile("/tmp/test.html") . ' bytes'; // Escrito: 129 bytes

?>

Ver también

  • DOMDocument::saveHTML() - Copia el documento interno a una cadena usando el formato HTML
  • DOMDocument::loadHTML() - Cargar HTML de una cadena
  • DOMDocument::loadHTMLFile() - Cargar HTML desde un fichero

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.


Copia el arbol XML interno a un string

  • « DOMDocument::saveHTMLFile
  • DOMDocument::schemaValidate »
  • PHP Manual
  • DOMDocument
  • Copia el arbol XML interno a un string

DOMDocument::saveXML

(PHP 5, PHP 7)

DOMDocument::saveXML — Copia el arbol XML interno a un string

Descripción

public DOMDocument::saveXML ( DOMNode $node = ? , int $options = 0 ) : string

Crea un documento XML desde la representación DOM. Esta función normalmente se llama después de construir un nuevo documento desde cero, como en el ejemplo de abajo.

Parámetros

node

Use este parámetro para imprimir sólo un nodo especifico sin la declaración XML en vez del documento completo.

options

Opciones Adicionales. Actualmente sólo está soportada LIBXML_NOEMPTYTAG.

Valores devueltos

Devuelve el XML, o false en caso de error.

Errores/Excepciones

DOM_WRONG_DOCUMENT_ERR

Lanzado si node es de otro documento.

Historial de cambios

Versión | Descripción
5.1.0 | Se añadió el parámetro options

Ejemplos

Ejemplo #1 Guardar un árbol DOM en un string

<?php

$doc = new DOMDocument('1.0');
// queremos una impresión buena
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('Este es el título');
$text = $title->appendChild($text);

echo "Guardando todo el documento:\n";
echo $doc->saveXML() . "\n";

echo "Guardando sólo la parte del título:\n";
echo $doc->saveXML($title);

?>

El resultado del ejemplo sería:

Guardando todo el documento:
<?xml version="1.0"?>
<book>
  <title>Este es el título</title>
</book>

Guardando sólo la parte del título:
<title>Este es el título</title>

Ver también

  • DOMDocument::save() - Copia el árbol XML interno a un archivo
  • DOMDocument::load() - Cargar un documento XML de un archivo.
  • DOMDocument::loadXML() - Cargar XML desde una cadena

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.


Valida un documento basado en un esquema

  • « DOMDocument::saveXML
  • DOMDocument::schemaValidateSource »
  • PHP Manual
  • DOMDocument
  • Valida un documento basado en un esquema

DOMDocument::schemaValidate

(PHP 5, PHP 7)

DOMDocument::schemaValidate — Valida un documento basado en un esquema

Descripción

public DOMDocument::schemaValidate ( string $filename , int $flags = 0 ) : bool

Valida un documento basado en el fichero de esquema dado.

Parámetros

filename

La ruta al esquema.

flags

Una máscara de bits de banderas de validación de esquemas de Libxml. Actualmente el único valor admitido es LIBXML_SCHEMA_CREATE. Disponible desde PHP 5.5.2 y Libxml 2.6.14.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
5.5.2 | Se añadió el parámetro flags

Ver también

  • DOMDocument::schemaValidateSource() - Valida un documento basado en un esquema
  • DOMDocument::relaxNGValidate() - Realiza una validación relaxNG del documento
  • DOMDocument::relaxNGValidateSource() - Realiza una validación relaxNG del documento
  • DOMDocument::validate() - Valida el documento basado en su 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


Valida un documento basado en un esquema

  • « DOMDocument::schemaValidate
  • DOMDocument::validate »
  • PHP Manual
  • DOMDocument
  • Valida un documento basado en un esquema

DOMDocument::schemaValidateSource

(PHP 5, PHP 7)

DOMDocument::schemaValidateSource — Valida un documento basado en un esquema

Descripción

public DOMDocument::schemaValidateSource ( string $source , int $flags = ? ) : bool

Valida un documento basado en un esquema definido en la cadena dada.

Parámetros

source

Una cadena que contiene el esquema.

flags

Una máscara de bits de banderas de validación de esquemas de Libxml. Actualmente el único valor admitido es LIBXML_SCHEMA_CREATE. Disponible desde PHP 5.5.2 y Libxml 2.6.14.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
5.5.2 | Se añadió el parámetro flags

Ver también

  • DOMDocument::schemaValidate() - Valida un documento basado en un esquema
  • DOMDocument::relaxNGValidate() - Realiza una validación relaxNG del documento
  • DOMDocument::relaxNGValidateSource() - Realiza una validación relaxNG del documento
  • DOMDocument::validate() - Valida el documento basado en su DTD

User Contributed Notes

There are no user contributed notes for this page.


Valida el documento basado en su DTD

  • « DOMDocument::schemaValidateSource
  • DOMDocument::xinclude »
  • PHP Manual
  • DOMDocument
  • Valida el documento basado en su DTD

DOMDocument::validate

(PHP 5, PHP 7)

DOMDocument::validate — Valida el documento basado en su DTD

Descripción

public DOMDocument::validate ( ) : bool

Valida el documento basado en su DTD.

También se puede usar la propiedad validateOnParse de DOMDocument para realizar la validación de DTD.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error. Si el documento no tiene el DTD adjunto, este método devolverá false.

Ejemplos

Ejemplo #1 Ejemplo de validación de DTD

<?php
$dom = new DOMDocument;
$dom->load('book.xml');
if ($dom->validate()) {
    echo "¡Este documento es válido!\n";
}
?>

También se puede validar un fichero XML mientras se carga:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->load('book.xml');
?>

Ver también

  • DOMDocument::schemaValidate() - Valida un documento basado en un esquema
  • DOMDocument::schemaValidateSource() - Valida un documento basado en un esquema
  • DOMDocument::relaxNGValidate() - Realiza una validación relaxNG del documento
  • DOMDocument::relaxNGValidateSource() - Realiza una validación relaxNG del documento

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


Sustituye XIncludes en un objeto DOMDocument

  • « DOMDocument::validate
  • DOMDocumentFragment »
  • PHP Manual
  • DOMDocument
  • Sustituye XIncludes en un objeto DOMDocument

DOMDocument::xinclude

(PHP 5, PHP 7)

DOMDocument::xinclude — Sustituye XIncludes en un objeto DOMDocument

Descripción

public DOMDocument::xinclude ( int $options = 0 ) : int

Este método sustituye » XIncludes en un objeto DOMDocument.

Nota:

Debido a que libxml2 resuelve automáticamente entidades, este método producirá resultados inesperados si el fichero XML incluido tiene un DTD adjunto.

Parámetros

options

Parámetros de libxml. Disponible desde PHP 5.1.0 y Libxml 2.6.7.

Valores devueltos

Devuelve el número de XIncludes del documento, -1 si falló algún proceso, o false si no hubo sustituciones.

Ejemplos

Ejemplo #1 Ejemplo de DOMDocument::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>
 </para>
</chapter>
EOD;

$dom = new DOMDocument;

// vamos a tener una impresión buena
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// cargar la cadena XML definida arriba
$dom->loadXML($xml);

// sustituir xincludes
$dom->xinclude();

echo $dom->saveXML();

?>

El resultado del ejemplo sería algo similar a:

<?xml version="1.0"?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Books of the other guy..</title>
  <para>
    <row xml:base="/home/didou/book.xml">
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
  </para>
</chapter>

User Contributed Notes

nicolas_rainardNOSPAM at yahoo dot fr 12-Jul-2007 04:56
If you use the loadXML() method instead of the load() one (let's say, to process the XML string before loading and parsing it), you will have problems with xinclude(), because the parser will not know where to find the files to include.
Using chdir() before xinclude() will not help.

The solution is to set the documentURI property of the DOMDocument object accordingly to it's original filename, and everything will work fine !

<?php

$xml = file_get_contents($file);
$xml = do_something_with($xml);

$doc = new DOMDocument;
$doc->documentURI = $file;
$doc->loadXML($xml);
$doc->xinclude();

?>


La clase DOMDocumentFragment

(PHP 5, PHP 7)

Sinopsis de la Clase

DOMDocumentFragment extends DOMNode {
/* Propiedades */
/* Propiedades heredadas */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
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 DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Métodos */
public appendXML ( string $data ) : bool
/* Métodos heredados */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Tabla de contenidos

  • DOMDocumentFragment::appendXML — Añade información XML sin formato

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


Añade información XML sin formato

  • « DOMDocumentFragment
  • DOMDocumentType »
  • PHP Manual
  • DOMDocumentFragment
  • Añade información XML sin formato

DOMDocumentFragment::appendXML

(PHP 5 >= 5.1.0, PHP 7)

DOMDocumentFragment::appendXML — Añade información XML sin formato

Descripción

public DOMDocumentFragment::appendXML ( string $data ) : bool

Añade información XML sin formato a un DOMDocumentFragment.

Este método no es parte del estándar DOM. Fue creado como enfoque más sencillo para añadir un DocumentFragment de XML a un DOMDocument.

Si quiere mantener los estándares, tendrá que crear un DOMDocument temporal con una raíz cualquiera y después ir a través de los nodos hijo de la raíz de su información XML para añadirlos.

Parámetros

data

XML a añadir.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Añadir información XML a su documento

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

El resultado del ejemplo sería:

<?xml version="1.0"?>
<root><foo>text</foo><bar>text2</bar></root>

User Contributed Notes

lpetrov(AT)axisvista.com 20-Jul-2007 05:45
Here is (maybe) a better example:
/**
* Helper function for replacing $node (DOMNode)
* with an XML code (string)
*
* @var DOMNode $node
* @var string $xml
*/
public function replaceNodeXML(&$node,$xml) {
 $f = $this->dom->createDocumentFragment();
 $f->appendXML($xml);
 $node->parentNode->replaceChild($f,$node);
}

Copied from the "PHP5 Dom Based Template" article at:
http://blog.axisvista.com/?p=35


La clase DOMDocumentType

(PHP 5, PHP 7)

Introducción

Cada DOMDocument tiene un atributo doctype cuyo valor es null o un objeto DOMDocumentType.

Sinopsis de la Clase

DOMDocumentType extends DOMNode {
/* Propiedades */
readonly public string $publicId ;
readonly public string $systemId ;
readonly public string $name ;
readonly public DOMNamedNodeMap $entities ;
readonly public DOMNamedNodeMap $notations ;
readonly public string $internalSubset ;
/* Métodos heredados */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Propiedades

publicId

El identificador público del subconjunto externo.

systemId

El identificador de sistema del subconjunto externo. Puede ser o no una URI absoluta.

name

El nombre del DTD; es decir, el nombre que siguie inmediatemante a la palabra clave DOCTYPE.

entities

Un objeto DOMNamedNodeMap que contiene las entidades generales, externas e internas, declaradas en el DTD.

notations

Un objeto DOMNamedNodeMap que contiene las notaciones declaradas en el DTD.

internalSubset

El subconjunto interno como cadena, o null si no hay ninguno. No contiene los corchetes delimitadores.

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMElement

(PHP 5, PHP 7)

Sinopsis de la Clase

DOMElement extends DOMNode {
/* Propiedades */
readonly public bool $schemaTypeInfo ;
readonly public string $tagName ;
/* Métodos */
public __construct ( string $name , string $value = ? , string $namespaceURI = ? )
public getAttribute ( string $name ) : string
public getAttributeNode ( string $name ) : DOMAttr
public getAttributeNodeNS ( string $namespaceURI , string $localName ) : DOMAttr
public getAttributeNS ( string $namespaceURI , string $localName ) : string
public getElementsByTagName ( string $name ) : DOMNodeList
public getElementsByTagNameNS ( string $namespaceURI , string $localName ) : DOMNodeList
public hasAttribute ( string $name ) : bool
public hasAttributeNS ( string $namespaceURI , string $localName ) : bool
public removeAttribute ( string $name ) : bool
public removeAttributeNode ( DOMAttr $oldnode ) : bool
public removeAttributeNS ( string $namespaceURI , string $localName ) : bool
public setAttribute ( string $name , string $value ) : DOMAttr
public setAttributeNode ( DOMAttr $attr ) : DOMAttr
public setAttributeNodeNS ( DOMAttr $attr ) : DOMAttr
public setAttributeNS ( string $namespaceURI , string $qualifiedName , string $value ) : void
public setIdAttribute ( string $name , bool $isId ) : void
public setIdAttributeNode ( DOMAttr $attr , bool $isId ) : void
public setIdAttributeNS ( string $namespaceURI , string $localName , bool $isId ) : void
/* Métodos heredados */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Propiedades

schemaTypeInfo

Aún no implementado, siempre devuelve null

tagName

El nombre del elemento

Notas

Nota:

La extensión DOM utiliza la codificación UTF-8. Use utf8_encode() y utf8_decode() para trabajar con textos con codificación ISO-8859-1 o Iconv para otras codificaciones.

Tabla de contenidos

  • DOMElement::__construct — Crea un nuevo objeto DOMElement
  • DOMElement::getAttribute — Devuelve el valor de un atributo
  • DOMElement::getAttributeNode — Devuelve el nodo de un atributo
  • DOMElement::getAttributeNodeNS — Devuelve el nodo de un atributo
  • DOMElement::getAttributeNS — Devuelve el valor de un atributo
  • DOMElement::getElementsByTagName — Obtiene los elementos por nombre de etiqueta
  • DOMElement::getElementsByTagNameNS — Obtener los elementos por la URI del espacio de nombres y el nombre local
  • DOMElement::hasAttribute — Comprueba si existe un atributo
  • DOMElement::hasAttributeNS — Comprueba si un atributo existe
  • DOMElement::removeAttribute — Elimina un atributo
  • DOMElement::removeAttributeNode — Elimina un atributo
  • DOMElement::removeAttributeNS — Elimina un atributo
  • DOMElement::setAttribute — Añade un nuevo atributo
  • DOMElement::setAttributeNode — Añade un nuevo nodo de atributo al elemento
  • DOMElement::setAttributeNodeNS — Aña de un nuevo nodo de atributo al elemento
  • DOMElement::setAttributeNS — Añade un nuevo atributo
  • DOMElement::setIdAttribute — Declara el atributo especificado por su nombre como de tipo ID
  • DOMElement::setIdAttributeNode — Declara el atributo especificado por su nodo como de tipo ID
  • DOMElement::setIdAttributeNS — Declara el atributo especificado por su nombre local y su URI del espacio de nombres como de tipo ID

User Contributed Notes

johnny 03-Mar-2014 03:48
Get html of a node
 $html .= $dom->saveHTML($node);
Janne Enberg 07-Nov-2013 11:02
This page doesn't list the inherited properties from DOMNode, e.g. the quite important textContent property. It would be immensely helpful if it would list those as well.
felix dot klee at inka dot de 26-Feb-2013 03:23
How to rename an element and preserve attributes:

<?php

// Changes the name of element $element to $newName.
function renameElement($element, $newName) {
  $newElement = $element->ownerDocument->createElement($newName);
  $parentElement = $element->parentNode;
  $parentElement->insertBefore($newElement, $element);

  $childNodes = $element->childNodes;
  while ($childNodes->length > 0) {
    $newElement->appendChild($childNodes->item(0));
  }

  $attributes = $element->attributes;
  while ($attributes->length > 0) {
    $attribute = $attributes->item(0);
    if (!is_null($attribute->namespaceURI)) {
      $newElement->setAttributeNS('http://www.w3.org/2000/xmlns/',
                                  'xmlns:'.$attribute->prefix,
                                  $attribute->namespaceURI);
    }
    $newElement->setAttributeNode($attribute);
  }

  $parentElement->removeChild($element);
}

function prettyPrint($d) {
  $d->formatOutput = true;
  echo '<pre>'.htmlspecialchars($d->saveXML()).'</pre>';
}

$d = new DOMDocument( '1.0' );
$d->loadXML('<?xml version="1.0"?>
<library>
  <data a:foo="1" x="bar" xmlns:a="http://example.com/a">
    <invite>
      <username>jmansa</username>
      <userid>1</userid>
    </invite>
    <update>1</update>
  </data>
</library>');

$xpath = new DOMXPath($d);
$elements = $xpath->query('/library/data');
if ($elements->length == 1) {
  $element = $elements->item(0);
  renameElement($element, 'invites');
}

prettyPrint($d);

?>
loopduplicate at burningtoken dot com 22-Apr-2011 02:34
This works perfect for me as well:

<?php $xml = $domElement->ownerDocument->saveXML($domElement); ?>
Anonymous 24-Dec-2010 08:22
you can use DOMNode::nodeValue
DOMElement inherits this public property.

$elem->nodeValue
dpetroff ( at ) gmail.com 04-Dec-2010 11:24
Hi!

Combining all th comments, the easiest way to get inner HTML of the node is to use this function:

<?php
function get_inner_html( $node ) {
    $innerHTML= '';
    $children = $node->childNodes;
    foreach ($children as $child) {
        $innerHTML .= $child->ownerDocument->saveXML( $child );
    }

    return $innerHTML;
}
?>
nawaman at gmail dot com 03-Sep-2009 08:08
The following code shows can text-only content be extracted from a document.

<?php
function getTextFromNode($Node, $Text = "") {
    if ($Node->tagName == null)
        return $Text.$Node->textContent;

    $Node = $Node->firstChild;
    if ($Node != null)
        $Text = getTextFromNode($Node, $Text);

    while($Node->nextSibling != null) {
        $Text = getTextFromNode($Node->nextSibling, $Text);
        $Node = $Node->nextSibling;
    }
    return $Text;
}

function getTextFromDocument($DOMDoc) {
    return getTextFromNode($DOMDoc->documentElement);
}

$Doc = new DOMDocument();
$Doc->loadHTMLFile("Test.html");
echo getTextFromDocument($Doc)."\n";
?>
Daniel Morlock 07-May-2009 09:22
It would be nice to have a function which converts a document/node/element into a string.

Anyways, I use the following code snippet to get the innerHTML value of a DOMNode:

<?php
function getInnerHTML($Node)
{
     $Body = $Node->ownerDocument->documentElement->firstChild->firstChild;
     $Document = new DOMDocument();
     $Document->appendChild($Document->importNode($Body,true));
     return $Document->saveHTML();
}
?>
patrick smith 04-Nov-2008 08:14
Although it may be preferable to use the dom to manipulate elements, sometimes it's useful to actually get the innerHTML from a document element (e.g. to load into a client-side editor).

To get the innerHTML of a specific element ($elem_id) in a specific html file ($filepath):

<?php
$innerHTML = '';
$doc = new DOMDocument();
$doc->loadHTMLFile($filepath);
$elem = $doc->getElementById($elem_id);

// loop through all childNodes, getting html
$children = $elem->childNodes;
foreach ($children as $child) {
    $tmp_doc = new DOMDocument();
    $tmp_doc->appendChild($tmp_doc->importNode($child,true));
    $innerHTML .= $tmp_doc->saveHTML();
}
?>
Pinochet 25-Oct-2008 05:33
Hi to get the value of DOMElement just get the nodeValue public parameter (it is inherited from DOMNode):
<?php
echo $domElement->nodeValue;
?>
Everything is obvious if you now about this thing ;-)
j DOT wagner ( AT ) medieninnovation.com 08-Oct-2008 09:11
Caveat!
It took me almost an hour to figure this out, so I hope it saves at least one of you some time.

If you want to debug your DOM tree and try var_dump() or similar you will be fooled into thinking the DOMElement that you are looking at is empty, because var_dump() says: object(DOMElement)#1 (0) { }

After much debugging I found out that all DOM objects are invisible to var_dump() and print_r(), my guess is because they are C objects and not PHP objects. So I tried saveXML(), which works fine on DOMDocument, but is not implemented on DOMElement.

The solution is simple (if you know it):
$xml = $domElement->ownerDocument->saveXML($domElement);

This will give you an XML representation of $domElement.
Severin 14-Sep-2008 06:18
I wanted to find similar Elements - thats why I built an Xpath-String like this - maybe somebody needs it... its not very pretty - but neither is domdocument :)

<?php

$dom->load($xmlFile))

$xpathQuery = '//*';
$xmlNodes = $xpath->query($xpathQuery);

$pathlist = array();
$attrlist = array();
foreach ($xmlNodes as $node) {

  $depth = $this->_getDomDepth($node);   //get Path-Depth (for array key)
  $pathlist[$depth] = $node->tagName;     // tagname

  $attrs = $node->attributes;
  $attr='';
  $a=0;
  foreach ($attrs as $attrName => $attrNode)  // attributes
            {
              if ($attrName !='reg')
              {
                if ($a++!=0) $attr .= ' and ';
                $attr .= '@'.$attrName.'='."'".$attrNode->value."'";
              }
            }

          $attrlist[$depth] = $attr?'['.$attr.']':'';

          $path = ''; for ($i=0;$i<=$depth;$i++) $path .= '/'.$pathlist[$i].$attrlist[$i];  // the xpath of the actual Element

    // ... now you can go on and user $path to find similar elements
    }
  }
}

 private function _getDomDepth(DomNode $node)
   {
     $r = -2;
     while ($node) {
       $r++;
       $node = $node->parentNode;
     }
     return  $r;
   }
?>
ae.fxx 18-Jul-2008 01:49
Hi there.

Remember to append a DOMNode (or any of its descendants) to a DOMDocument __BEFORE__ you try to append a child to it.

I don't know why it has to be this way but it can't be done without it.

bye


Crea un nuevo objeto DOMElement

  • « DOMElement
  • DOMElement::getAttribute »
  • PHP Manual
  • DOMElement
  • Crea un nuevo objeto DOMElement

DOMElement::__construct

(PHP 5, PHP 7)

DOMElement::__construct — Crea un nuevo objeto DOMElement

Descripción

public DOMElement::__construct ( string $name , string $value = ? , string $namespaceURI = ? )

Crea un nuevo objeto DOMElement. Este objeto es de sólo lectura. Puede ser añadido a un documento, pero no se pueden añadir nodos adicionales a este nodo hasta que el nodo esté asociado con un documento. Para crear un nodo modificable, use DOMDocument::createElement o DOMDocument::createElementNS.

Parámetros

name

El nombre de la etiqueta del elemento. Cuando también se pasa en namespaceURI, el nombre del elemento puede tomar un prefijo para asociarlo con la URI.

value

El valor del elemento.

namespaceURI

Una URI del espacio de nombres para crear el elemento dentro de un espacio de nombres especificado.

Ejemplos

Ejemplo #1 Crear un nuevo objeto DOMElement

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$element_ns = new DOMElement('pr:node1', 'thisvalue', 'http://xyz');
$element->appendChild($element_ns);
echo $dom->saveXML(); /* <?xml version="1.0" encoding="utf-8"?>
<root><pr:node1 xmlns:pr="http://xyz">thisvalue</pr:node1></root> */

?>

Ver también

  • DOMDocument::createElement() - Crea un nuevo nodo elemento
  • DOMDocument::createElementNS() - Crea un nuevo nodo elemento con el nombre de espacio asociado

User Contributed Notes

Fabian dot Blech at gmx dot de 22-Jul-2010 08:30
Remember, Dom-Nodes mustn't start with a number:

allowed:
<t12345t4>Value</t12345t4>

Not allowed:
<12345t4>VALUE</12345t4>
troelskn at gmail dot com 03-Jun-2008 07:46
Note that this function is buggy. You have to manually escape the $value argument with htmlspecialchars.
See: http://bugs.php.net/bug.php?id=31191
adar at darkpoetry dot de 07-May-2007 01:27
If you like to view an element simply do:

<?php
echo htmlentities($element->C14N());
?>

Undocumented but found ;)


Devuelve el valor de un atributo

  • « DOMElement::__construct
  • DOMElement::getAttributeNode »
  • PHP Manual
  • DOMElement
  • Devuelve el valor de un atributo

DOMElement::getAttribute

(PHP 5, PHP 7)

DOMElement::getAttribute — Devuelve el valor de un atributo

Descripción

public DOMElement::getAttribute ( string $name ) : string

Obtiene el valor del atributo de nombre name para el nodo actual.

Parámetros

name

El nombre del atributo.

Valores devueltos

El valor del atributo, o una cadena vacía si no se encuentra un atributo con el nombre dado por name.

Ver también

  • DOMElement::hasAttribute() - Comprueba si existe un atributo
  • DOMElement::setAttribute() - Añade un nuevo atributo
  • DOMElement::removeAttribute() - Elimina un atributo

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

- - - - - - - - - - - - - -


Devuelve el nodo de un atributo

  • « DOMElement::getAttribute
  • DOMElement::getAttributeNodeNS »
  • PHP Manual
  • DOMElement
  • Devuelve el nodo de un atributo

DOMElement::getAttributeNode

(PHP 5, PHP 7)

DOMElement::getAttributeNode — Devuelve el nodo de un atributo

Descripción

public DOMElement::getAttributeNode ( string $name ) : DOMAttr

Devuelve el nodo del atributo con nombre name para el elemento actual.

Parámetros

name

El nombre del atributo.

Valores devueltos

El nodo de atributos. Observe que para los atributos de las declaraciones del espacio de nombres XML (xmlns y xmlns:*) una instancia de DOMNameSpaceNode es devuelta en vez de una instancia de DOMAttr.

Ver también

  • DOMElement::hasAttribute() - Comprueba si existe un atributo
  • DOMElement::setAttributeNode() - Añade un nuevo nodo de atributo al elemento
  • DOMElement::removeAttributeNode() - Elimina un atributo

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


Devuelve el nodo de un atributo

  • « DOMElement::getAttributeNode
  • DOMElement::getAttributeNS »
  • PHP Manual
  • DOMElement
  • Devuelve el nodo de un atributo

DOMElement::getAttributeNodeNS

(PHP 5, PHP 7)

DOMElement::getAttributeNodeNS — Devuelve el nodo de un atributo

Descripción

public DOMElement::getAttributeNodeNS ( string $namespaceURI , string $localName ) : DOMAttr

Devuelve el nodo del atributo en el espacio de nombres namespaceURI con el nombre local localName para el nodo actual.

Parámetros

namespaceURI

La URI del espacio de nombres.

localName

El nombre local.

Valores devueltos

El nodo de atributos. Observe que para los atributos de las declaraciones del espacio de nombres XML (xmlns y xmlns:*) una instancia de DOMNameSpaceNode es devuelta en vez de una instancia de DOMAttr.

Ver también

  • DOMElement::hasAttributeNS() - Comprueba si un atributo existe
  • DOMElement::setAttributeNodeNS() - Aña de un nuevo nodo de atributo al elemento
  • DOMElement::removeAttributeNode() - Elimina un atributo

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el valor de un atributo

  • « DOMElement::getAttributeNodeNS
  • DOMElement::getElementsByTagName »
  • PHP Manual
  • DOMElement
  • Devuelve el valor de un atributo

DOMElement::getAttributeNS

(PHP 5, PHP 7)

DOMElement::getAttributeNS — Devuelve el valor de un atributo

Descripción

public DOMElement::getAttributeNS ( string $namespaceURI , string $localName ) : string

Obtiene el valor del atributo en el espacio de nombres namespaceURI con el nombre local localName para el nodo actual.

Parámetros

namespaceURI

La URI del espacio de nombres.

localName

El nombre local.

Valores devueltos

El valor del atributo, o una cadena vacía si no se ecuentra el atributo con los localName y namespaceURI dados.

Ver también

  • DOMElement::hasAttributeNS() - Comprueba si un atributo existe
  • DOMElement::setAttributeNS() - Añade un nuevo atributo
  • DOMElement::removeAttributeNS() - Elimina un atributo

User Contributed Notes

There are no user contributed notes for this page.


Obtiene los elementos por nombre de etiqueta

  • « DOMElement::getAttributeNS
  • DOMElement::getElementsByTagNameNS »
  • PHP Manual
  • DOMElement
  • Obtiene los elementos por nombre de etiqueta

DOMElement::getElementsByTagName

(PHP 5, PHP 7)

DOMElement::getElementsByTagName — Obtiene los elementos por nombre de etiqueta

Descripción

public DOMElement::getElementsByTagName ( string $name ) : DOMNodeList

Esta función devuelve una nueva instancia de la clase DOMNodeList con todos los elementos descendientes con un nombre de etiqueta dado por name, en el orden en que fueron encontrados en un recorrido preorden de este elemento árbol.

Parámetros

name

El nombre de la etiqueta. Use * para devolver todos los elementos dentro del elemento árbol.

Valores devueltos

Esta función devuelve una nueva instancia de la clase DOMNodeList con todos los elementos coincidentes.

Ver también

  • DOMElement::getElementsByTagNameNS() - Obtener los elementos por la URI del espacio de nombres y el nombre local

User Contributed Notes

rudiger at greatdealsenterprises dot com 12-Jun-2019 11:45
Note that even though getElementsByTagName returns a NodeList which is defined as a list of DOMNodes, you're actually getting a list of DOMElements. That allows to call getElementsByTagName on each of the results.

$tables = $doc->getElementsByTagName('table');
foreach ($tables as $table) {
  $trs = $table->getElementsByTagName('tr');
  // etc...
}
Brennon Brimhall 18-Jan-2017 11:51
Be aware that this function returns all descendants, not just immediate children.
ddkkdd twenty twenty at gmail dot com 08-Sep-2010 03:15
A simple function that uses this method to print the nodes it finds in an xml document. Improvements welcomed.

<?php
function printTags($tag){

  $node = $this->doc->getElementsByTagName($tag);
   for($c = 0; $c<$node->length; $c++){
     $text[$c] =$this->doc->saveXML($node->item($c));
     echo $text[$c];

   }

}
?>


Obtener los elementos por la URI del espacio de nombres y el nombre local

  • « DOMElement::getElementsByTagName
  • DOMElement::hasAttribute »
  • PHP Manual
  • DOMElement
  • Obtener los elementos por la URI del espacio de nombres y el nombre local

DOMElement::getElementsByTagNameNS

(PHP 5, PHP 7)

DOMElement::getElementsByTagNameNS — Obtener los elementos por la URI del espacio de nombres y el nombre local

Descripción

public DOMElement::getElementsByTagNameNS ( string $namespaceURI , string $localName ) : DOMNodeList

Esta función trae todos los elementos descendientes con unos localName y namespaceURI dados.

Parámetros

namespaceURI

La URI del espacio de nombres.

localName

EL nombre local. Use * para devolver todos los elementos dentro del elemento árbol.

Valores devueltos

Esta función devuelve una nueva instancia de la clase DOMNodeList con todos los elementos coincidentes en el orden en que fueron encontrados en un recorriendo en preorden este elemento árbol.

Ver también

  • DOMElement::getElementsByTagName() - Obtiene los elementos por nombre de etiqueta

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.


Comprueba si existe un atributo

  • « DOMElement::getElementsByTagNameNS
  • DOMElement::hasAttributeNS »
  • PHP Manual
  • DOMElement
  • Comprueba si existe un atributo

DOMElement::hasAttribute

(PHP 5, PHP 7)

DOMElement::hasAttribute — Comprueba si existe un atributo

Descripción

public DOMElement::hasAttribute ( string $name ) : bool

Indica si un atributo llamado name existe como miembro del elemento.

Parámetros

name

El nombre del atributo.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • DOMElement::hasAttributeNS() - Comprueba si un atributo existe
  • DOMElement::getAttribute() - Devuelve el valor de un atributo
  • DOMElement::setAttribute() - Añade un nuevo atributo
  • DOMElement::removeAttribute() - Elimina un atributo

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si un atributo existe

  • « DOMElement::hasAttribute
  • DOMElement::removeAttribute »
  • PHP Manual
  • DOMElement
  • Comprueba si un atributo existe

DOMElement::hasAttributeNS

(PHP 5, PHP 7)

DOMElement::hasAttributeNS — Comprueba si un atributo existe

Descripción

public DOMElement::hasAttributeNS ( string $namespaceURI , string $localName ) : bool

Indica si un atributo en el espacio de nombres namespaceURI llamado localName existe como miembro del elemento.

Parámetros

namespaceURI

La URI del espacio de nombres.

localName

El nombre local.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • DOMElement::hasAttribute() - Comprueba si existe un atributo
  • DOMElement::getAttributeNS() - Devuelve el valor de un atributo
  • DOMElement::setAttributeNS() - Añade un nuevo atributo
  • DOMElement::removeAttributeNS() - Elimina un atributo

User Contributed Notes

There are no user contributed notes for this page.


Elimina un atributo

  • « DOMElement::hasAttributeNS
  • DOMElement::removeAttributeNode »
  • PHP Manual
  • DOMElement
  • Elimina un atributo

DOMElement::removeAttribute

(PHP 5, PHP 7)

DOMElement::removeAttribute — Elimina un atributo

Descripción

public DOMElement::removeAttribute ( string $name ) : bool

Elimina el atributo llamado name del elemento.

Parámetros

name

El nombre del atributo.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si el nodo es de sólo lectura.

Ver también

  • DOMElement::hasAttribute() - Comprueba si existe un atributo
  • DOMElement::getAttribute() - Devuelve el valor de un atributo
  • DOMElement::setAttribute() - Añade un nuevo atributo

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;

?>


Elimina un atributo

  • « DOMElement::removeAttribute
  • DOMElement::removeAttributeNS »
  • PHP Manual
  • DOMElement
  • Elimina un atributo

DOMElement::removeAttributeNode

(PHP 5, PHP 7)

DOMElement::removeAttributeNode — Elimina un atributo

Descripción

public DOMElement::removeAttributeNode ( DOMAttr $oldnode ) : bool

Elimina el atributo oldnode del elemento.

Parámetros

oldnode

El nodo atributo.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si el nodo es de sólo lectura.

DOM_NOT_FOUND_ERROR

Lanzado si oldnode no es un atributo del elemento.

Ver también

  • DOMElement::hasAttribute() - Comprueba si existe un atributo
  • DOMElement::getAttributeNode() - Devuelve el nodo de un atributo
  • DOMElement::setAttributeNode() - Añade un nuevo nodo de atributo al elemento

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.


Elimina un atributo

  • « DOMElement::removeAttributeNode
  • DOMElement::setAttribute »
  • PHP Manual
  • DOMElement
  • Elimina un atributo

DOMElement::removeAttributeNS

(PHP 5, PHP 7)

DOMElement::removeAttributeNS — Elimina un atributo

Descripción

public DOMElement::removeAttributeNS ( string $namespaceURI , string $localName ) : bool

Elimina el atributo localName en el espacio de nombre namespaceURI de el elemento.

Parámetros

namespaceURI

La URI del espacio de nombres.

localName

El nombre local.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si el nodo es de sólo lectura.

Ver también

  • DOMElement::hasAttributeNS() - Comprueba si un atributo existe
  • DOMElement::getAttributeNS() - Devuelve el valor de un atributo
  • DOMElement::setAttributeNS() - Añade un nuevo atributo

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

?>


Añade un nuevo atributo

  • « DOMElement::removeAttributeNS
  • DOMElement::setAttributeNode »
  • PHP Manual
  • DOMElement
  • Añade un nuevo atributo

DOMElement::setAttribute

(PHP 5, PHP 7)

DOMElement::setAttribute — Añade un nuevo atributo

Descripción

public DOMElement::setAttribute ( string $name , string $value ) : DOMAttr

Establece un atributo con nombre name al valor dado. Si el atributo no existe, se creará.

Parámetros

name

El nombre del atributo.

value

El valor del atributo.

Valores devueltos

El nuevo objeto DOMAttr o false si ocurrió un error.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si el nodo es de sólo lectura.

Ejemplos

Ejemplo #1 Establecer un atributo

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

Ver también

  • DOMElement::hasAttribute() - Comprueba si existe un atributo
  • DOMElement::getAttribute() - Devuelve el valor de un atributo
  • DOMElement::removeAttribute() - Elimina un atributo

User Contributed Notes

lehal2@hotmail 06-Jun-2013 09:44
The use of Dom to first remove and then add the width and height to the first img tag from the text.I hope it help you to save your time
<?php
$html = '

            <img src="http://www.example.com/images/header.jpg" width="898" height="223" style="border-bottom:5px solid #cccccc;"/>
        <img src="http://www.example.com/images/header2.jpg" width="898" height="223" style="border-bottom:5px solid #cccccc;"/>
        ';

$doc = DOMDocument::loadHTML($html);
$c =0;
foreach($doc->getElementsByTagName('img') as $image){
    if ($c>0) continue;
    foreach(array('width', 'height') as $attribute_to_remove){
        echo $attribute_to_remove;
        if($image->hasAttribute($attribute_to_remove)){
            $image->removeAttribute($attribute_to_remove);

        }
        if($attribute_to_remove=='height'){
            if(!$image->hasAttribute($attribute_to_remove)){
                $image->setAttribute($attribute_to_remove,'220');

            }}
        if($attribute_to_remove=='width'){
      if(!$image->hasAttribute($attribute_to_remove)){
            $image->setAttribute($attribute_to_remove,'700');

        }}
        $c = $c+1;
    }
}
echo $doc->saveHTML();
Rakesh Verma - rakeshnsony at gmail dot com 10-Nov-2010 11:27
<?php
//Store your html into $html variable.
$html="
<html>
<head>
<title>Untitled Document</title>
</head>

<body>
    <a href='http://example.com'>Example</a><br>
    <a href='http://google.com'>Google</a><br>

    <a href='http://www.yahoo.com'>Yahoo</a><br>
</body>

</html>";

$dom = new DOMDocument();
$dom->loadHTML($html);

//Evaluate Anchor tag in HTML
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');

        //remove and set target attribute
        $href->removeAttribute('target');
        $href->setAttribute("target", "_blank");

        $newURL=$url."/newurl";

        //remove and set href attribute
        $href->removeAttribute('href');
        $href->setAttribute("href", $newURL);
}

// save html
$html=$dom->saveHTML();

echo $html;

?>
address at gmail dot com 03-Jul-2008 07:25
If wanting to set an attribute of an element with unique id of "1"

<?php
$dom = new DomDocument();
$dom->load('test.xml');
$xp = new DomXPath($dom);
$res = $xp->query("//*[@id = '1']");
$res->item(0)->setAttribute('title','2');
$dom->save('test.xml');
?>
Vasil Rangelov 31-Jul-2007 04:44
@karvjorm,
Using this method is not exactly a good practice. Infact, I think it may be a bug.
Names beginning with "xml" are reserved (for namespaces in this case).
setAttribute() should return false in this case I think, but I suppose it doesn't.

Still, the right way to do it is with createElementNS().
It lets you specify the namespace when creating the element node.

So the equivalent to yours ($html added to allow word wrapping) is:

$dom = new DomDocument('1.0','iso-8859-15');
$html = $dom->createElementNS('http://www.w3.org/1999/xhtml', 'html');
$ht_ml = $dom->appendChild($html);
$ht_ml->setAttribute('xml:lang','fi');
$ht_ml->setAttribute('lang','fi');
karvjorm at users.sourceforge.net 02-Mar-2007 03:05
$dom = new DomDocument('1.0','iso-8859-15');

$ht_ml = $dom->appendChild($dom->createElement('html'));
$ht_ml->setAttribute('xmlns','http://www.w3.org/1999/xhtml');
$ht_ml->setAttribute('xml:lang','fi');
$ht_ml->setAttribute('lang','fi');

Result:

<?xml version="1.0" encoding="iso-8859-15"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi" lang="fi">


Añade un nuevo nodo de atributo al elemento

  • « DOMElement::setAttribute
  • DOMElement::setAttributeNodeNS »
  • PHP Manual
  • DOMElement
  • Añade un nuevo nodo de atributo al elemento

DOMElement::setAttributeNode

(PHP 5, PHP 7)

DOMElement::setAttributeNode — Añade un nuevo nodo de atributo al elemento

Descripción

public DOMElement::setAttributeNode ( DOMAttr $attr ) : DOMAttr

Añade el nuevo nodo de atributo dado por attr al elemento.

Parámetros

attr

El nodo de atributo.

Valores devueltos

Devuelve el nodo antiguo si el atributo ha sido reemplazado o null.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si el nodo es de sólo lectura.

Ver también

  • DOMElement::hasAttribute() - Comprueba si existe un atributo
  • DOMElement::getAttributeNode() - Devuelve el nodo de un atributo
  • DOMElement::removeAttributeNode() - Elimina un atributo

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>


Aña de un nuevo nodo de atributo al elemento

  • « DOMElement::setAttributeNode
  • DOMElement::setAttributeNS »
  • PHP Manual
  • DOMElement
  • Aña de un nuevo nodo de atributo al elemento

DOMElement::setAttributeNodeNS

(PHP 5, PHP 7)

DOMElement::setAttributeNodeNS — Aña de un nuevo nodo de atributo al elemento

Descripción

public DOMElement::setAttributeNodeNS ( DOMAttr $attr ) : DOMAttr

Añade el nuevo nodo atributo attr al elemento.

Parámetros

attr

El nodo atributo.

Valores devueltos

Devuelve el antiguo nodo si el atributo ya sido reemplazado.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si el nodo es de sólo lectura.

Ver también

  • DOMElement::hasAttributeNS() - Comprueba si un atributo existe
  • DOMElement::getAttributeNodeNS() - Devuelve el nodo de un atributo
  • DOMElement::removeAttributeNode() - Elimina un atributo

User Contributed Notes

There are no user contributed notes for this page.


Añade un nuevo atributo

  • « DOMElement::setAttributeNodeNS
  • DOMElement::setIdAttribute »
  • PHP Manual
  • DOMElement
  • Añade un nuevo atributo

DOMElement::setAttributeNS

(PHP 5, PHP 7)

DOMElement::setAttributeNS — Añade un nuevo atributo

Descripción

public DOMElement::setAttributeNS ( string $namespaceURI , string $qualifiedName , string $value ) : void

Establece un atributo con el espacio de nombres namespaceURI y el nombre name al valor dado. Si el atributo no existe, se creará.

Parámetros

namespaceURI

La URI del espacio de nombres.

qualifiedName

El nombre cualificado del atributo, como prefijo:nombre_etiqueta.

value

El valor del atributo.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si el nodo es de sólo lectura.

DOM_NAMESPACE_ERR

Lanzado si qualifiedName es un nombre cualificado malformado, o si qualifiedName tienen un prefijo y namespaceURI es null.

Ver también

  • DOMElement::hasAttributeNS() - Comprueba si un atributo existe
  • DOMElement::getAttributeNS() - Devuelve el valor de un atributo
  • DOMElement::removeAttributeNS() - Elimina un atributo

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


Declara el atributo especificado por su nombre como de tipo ID

  • « DOMElement::setAttributeNS
  • DOMElement::setIdAttributeNode »
  • PHP Manual
  • DOMElement
  • Declara el atributo especificado por su nombre como de tipo ID

DOMElement::setIdAttribute

(PHP 5, PHP 7)

DOMElement::setIdAttribute — Declara el atributo especificado por su nombre como de tipo ID

Descripción

public DOMElement::setIdAttribute ( string $name , bool $isId ) : void

Declara el atributo name como de tipo ID.

Parámetros

name

El nombre del atributo.

isId

Establecer a true si se quiere que name sea de tipo ID, false si no.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si el nodo es de sólo lectura.

DOM_NOT_FOUND

Lanzado si name no es un atributo de este elemento.

Ver también

  • DOMDocument::getElementById() - Busca un elemento con cierto id
  • DOMElement::setIdAttributeNode() - Declara el atributo especificado por su nodo como de tipo ID
  • DOMElement::setIdAttributeNS() - Declara el atributo especificado por su nombre local y su URI del espacio de nombres como de tipo ID

User Contributed Notes

There are no user contributed notes for this page.


Declara el atributo especificado por su nodo como de tipo ID

  • « DOMElement::setIdAttribute
  • DOMElement::setIdAttributeNS »
  • PHP Manual
  • DOMElement
  • Declara el atributo especificado por su nodo como de tipo ID

DOMElement::setIdAttributeNode

(PHP 5, PHP 7)

DOMElement::setIdAttributeNode — Declara el atributo especificado por su nodo como de tipo ID

Descripción

public DOMElement::setIdAttributeNode ( DOMAttr $attr , bool $isId ) : void

Declara el atributo especificado por attr como de tipo ID.

Parámetros

attr

El nodo atributo.

isId

Establecer a true si se quiere que name sea de tipo ID, false si no.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si el nodo es de sólo lectura.

DOM_NOT_FOUND

Lanzado si name no es un atributo de este elemento.

Ver también

  • DOMDocument::getElementById() - Busca un elemento con cierto id
  • DOMElement::setIdAttribute() - Declara el atributo especificado por su nombre como de tipo ID
  • DOMElement::setIdAttributeNS() - Declara el atributo especificado por su nombre local y su URI del espacio de nombres como de tipo ID

User Contributed Notes

There are no user contributed notes for this page.


Declara el atributo especificado por su nombre local y su URI del espacio de nombres como de tipo ID

  • « DOMElement::setIdAttributeNode
  • DOMEntity »
  • PHP Manual
  • DOMElement
  • Declara el atributo especificado por su nombre local y su URI del espacio de nombres como de tipo ID

DOMElement::setIdAttributeNS

(PHP 5, PHP 7)

DOMElement::setIdAttributeNS — Declara el atributo especificado por su nombre local y su URI del espacio de nombres como de tipo ID

Descripción

public DOMElement::setIdAttributeNS ( string $namespaceURI , string $localName , bool $isId ) : void

Declara el atributo especificado por localName y namespaceURI como de tipo ID.

Parámetros

namespaceURI

La URI del espacio de nombres del atributo.

localName

El nombre local del atributo, como prefijo:nombre_etiqueta.

isId

Establecer a true si se quiere que name sea de tipo ID, false si no.

Valores devueltos

No devuelve ningún valor.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si el nodo es de sólo lectura.

DOM_NOT_FOUND

Lanzado si name no es un atributo de este elemento.

Ver también

  • DOMDocument::getElementById() - Busca un elemento con cierto id
  • DOMElement::setIdAttribute() - Declara el atributo especificado por su nombre como de tipo ID
  • DOMElement::setIdAttributeNode() - Declara el atributo especificado por su nodo como de tipo ID

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMEntity

(PHP 5, PHP 7)

Introducción

Esta interfaz representa una entidad conocida, analizada o sin analizar, de un documento XML.

Sinopsis de la Clase

DOMEntity extends DOMNode {
/* Propiedades */
readonly public string $publicId ;
readonly public string $systemId ;
readonly public string $notationName ;
public string $actualEncoding ;
readonly public string $encoding ;
readonly public string $version ;
/* Métodos heredados */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Propiedades

publicId

El identificador público asociado con la entidad si se especifica, y si no null.

systemId

El identificador de sistema asociado con la entidad si se especifica, y si no null. Puede ser o no una URI absoluta.

notationName

Para entidades no analizadas, el nombre de la notación de la entidad. Para entidades analizadas es null.

actualEncoding

Un atributo que especifica la codificación usada para esta entidad en el momento de analizar, cuando es una entidad analizada externa. Es null si es una entidad de un subconjunto interno o si es desconocida.

encoding

Un atributo que especifica, como parte de la declaración de texto, la codificación de esta entirdad, cuando es una entidad analizada externa. Si no, es null.

version

Un atributo que especifica, como parte de la declaración de texto, el número de versión de esta entidad, cuando es una entidad analizada externa. Si no, es null.

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMEntityReference

(PHP 5, PHP 7)

Sinopsis de la Clase

DOMEntityReference extends DOMNode {
/* Propiedades */
/* Métodos */
public __construct ( string $name )
/* Métodos heredados */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Tabla de contenidos

  • DOMEntityReference::__construct — Crea un nuevo objeto DOMEntityReference

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo objeto DOMEntityReference

  • « DOMEntityReference
  • DOMException »
  • PHP Manual
  • DOMEntityReference
  • Crea un nuevo objeto DOMEntityReference

DOMEntityReference::__construct

(PHP 5, PHP 7)

DOMEntityReference::__construct — Crea un nuevo objeto DOMEntityReference

Descripción

public DOMEntityReference::__construct ( string $name )

Crea un nuevo objeto DOMEntityReference.

Parámetros

name

El nombre de la referencia de entidad.

Ejemplos

Ejemplo #1 Crear un nuevo objeto DOMEntityReference

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$elemento = $dom->appendChild(new DOMElement('root'));
$entidad = $elemento->appendChild(new DOMEntityReference('nbsp'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="utf-8"?><root></root> */

?>

Ver también

  • DOMDocument::createEntityReference() - Create new entity reference node

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMException

(PHP 5, PHP 7)

Introducción

Las operaciones DOM lanzan excepciones bajo circunstancias particulares, esto es, cuando es imposible de realizar una operación por razones lógicas.

Véase también Excepciones.

Sinopsis de la Clase

DOMException extends Exception {
/* Propiedades */
readonly public int $code ;
/* Métodos heredados */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

Propiedades

code

Un integer que indica el tipo de error generado

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMImplementation

(PHP 5, PHP 7)

Introducción

La interfaz DOMImplementation proporciona varios métodos para realizar operaciones que son independientes de cualquier instancia en particular del modelo de objetos del documento.

Sinopsis de la Clase

DOMImplementation {
/* Propiedades */
/* Métodos */
__construct ( )
public createDocument ( string $namespaceURI = null , string $qualifiedName = null , DOMDocumentType $doctype = null ) : DOMDocument
public createDocumentType ( string $qualifiedName = null , string $publicId = null , string $systemId = null ) : DOMDocumentType
public hasFeature ( string $feature , string $version ) : bool
}

Tabla de contenidos

  • DOMImplementation::__construct — Crea un nuevo objeto DOMImplementation
  • DOMImplementation::createDocument — Crea un objeto DOMDocument del tipo especificado con su elemento documento
  • DOMImplementation::createDocumentType — Crear un objeto DOMDocumentType vacío
  • DOMImplementation::hasFeature — Comprueba si la implementación de DOM implementa una característica específica

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


Crea un nuevo objeto DOMImplementation

  • « DOMImplementation
  • DOMImplementation::createDocument »
  • PHP Manual
  • DOMImplementation
  • Crea un nuevo objeto DOMImplementation

DOMImplementation::__construct

(PHP 5, PHP 7)

DOMImplementation::__construct — Crea un nuevo objeto DOMImplementation

Descripción

DOMImplementation::__construct ( )

Crea un nuevo objeto DOMImplementation.

User Contributed Notes

There are no user contributed notes for this page.


Crea un objeto DOMDocument del tipo especificado con su elemento documento

  • « DOMImplementation::__construct
  • DOMImplementation::createDocumentType »
  • PHP Manual
  • DOMImplementation
  • Crea un objeto DOMDocument del tipo especificado con su elemento documento

DOMImplementation::createDocument

(PHP 5, PHP 7)

DOMImplementation::createDocument — Crea un objeto DOMDocument del tipo especificado con su elemento documento

Descripción

public DOMImplementation::createDocument ( string $namespaceURI = null , string $qualifiedName = null , DOMDocumentType $doctype = null ) : DOMDocument

Crea un objeto DOMDocument del tipo especificado con su elemento documento.

Parámetros

namespaceURI

La URI del espacio de nombres del elemento documento a crear.

qualifiedName

El nombre cualificado del elemento documento a crear.

doctype

El tipo de documento a crear o null.

Valores devueltos

Un nuevo objeto DOMDocument. Si namespaceURI, qualifiedName, y doctype son null, el DOMDocument devuelto está vacío sin elemento documento

Errores/Excepciones

DOM_WRONG_DOCUMENT_ERR

Lanzado si doctype ya ha sido usado con un documento diferente o fue creado desde una implementación diferente.

DOM_NAMESPACE_ERR

Lanzado si hay un error con el espacio de nombres, como determina namespaceURI y qualifiedName.

Este método puede ser llamado de forma estática, pero lanzará un error E_STRICT.

Ver también

  • DOMDocument::__construct() - Crea un nuevo objeto DOMDocument
  • DOMImplementation::createDocumentType() - Crear un objeto DOMDocumentType vacío

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


Crear un objeto DOMDocumentType vacío

  • « DOMImplementation::createDocument
  • DOMImplementation::hasFeature »
  • PHP Manual
  • DOMImplementation
  • Crear un objeto DOMDocumentType vacío

DOMImplementation::createDocumentType

(PHP 5, PHP 7)

DOMImplementation::createDocumentType — Crear un objeto DOMDocumentType vacío

Descripción

public DOMImplementation::createDocumentType ( string $qualifiedName = null , string $publicId = null , string $systemId = null ) : DOMDocumentType

Crea un objeto DOMDocumentType vacío. Las declaraciones de entidades y las notaciones no están disponibles. Las expansiones de referencias de entidades y la adición de atributos por defecto no ocurren.

Parámetros

qualifiedName

El nombre cualificado del tipo de documente a crear.

publicId

El identificador público del subconjunto externo.

systemId

El identificador de sistema del subconjunto externo.

Valores devueltos

Un nuevo nodo DOMDocumentType con su ownerDocument establecido a null.

Errores/Excepciones

DOM_NAMESPACE_ERR

Se produce si hay un error con el espacio de nombres, como determina qualifiedName.

Este método puede ser llamado de forma estática, pero lanzará un error E_STRICT.

Ejemplos

Ejemplo #1 Crear un documento con un DTD adjunto

<?php

// Crear una instancia de la clase DOMImplementation
$imp = new DOMImplementation;

// Crear una instancia de DOMDocumentType
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Crear una instancia de DOMDocument
$dom = $imp->createDocument("", "", $dtd);

// Establecer otras propiedades
$dom->encoding = 'UTF-8';
$dom->standalone = false;

// Crear un elemento vacío
$element = $dom->createElement('graph');

// Añadir el elemento
$dom->appendChild($element);

// Retrieve and print the document
echo $dom->saveXML();

?>

El resultado del ejemplo sería:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

Ver también

  • DOMImplementation::createDocument() - Crea un objeto DOMDocument del tipo especificado con su elemento documento

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.


Comprueba si la implementación de DOM implementa una característica específica

  • « DOMImplementation::createDocumentType
  • DOMNamedNodeMap »
  • PHP Manual
  • DOMImplementation
  • Comprueba si la implementación de DOM implementa una característica específica

DOMImplementation::hasFeature

(PHP 5, PHP 7)

DOMImplementation::hasFeature — Comprueba si la implementación de DOM implementa una característica específica

Descripción

public DOMImplementation::hasFeature ( string $feature , string $version ) : bool

Comprueba si la implementación de DOM implementa una característica específica dada por feature.

Se puede encontrar una lista de todas las características en la sección » Conformance de la especificación DOM.

Parámetros

feature

La característica a comprobar.

version

El número de versión de feature a comprobar. En el nivel 2 puede ser 2.0 o 1.0.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

Este método puede ser llamado de forma estática, pero lanzará un error E_STRICT.

Ejemplos

Ejemplo #1 Comprobar su Implementación 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 $clave => $nombre) {
  if (DOMImplementation::hasFeature($clave, '2.0')) {
    echo "Tiene la característica $nombre\n";
  } else {
    echo "Falta la característica $nombre\n";
  }
}

?>

Ver también

  • DOMNode::isSupported() - Comprueba si una característica está soportada para la versión especificada

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMNamedNodeMap

(PHP 5, PHP 7)

Sinopsis de la Clase

DOMNamedNodeMap implements Traversable {
/* Propiedades */
readonly public int $length ;
/* Métodos */
public count ( ) : int|false
getNamedItem ( string $name ) : DOMNode
getNamedItemNS ( string $namespaceURI , string $localName ) : DOMNode
item ( int $index ) : DOMNode
}

Propiedades

length

El número de nodos del mapa. El rango de los índice del nodo hijo válido es de 0 a length - 1 inclusive.

Tabla de contenidos

  • DOMNamedNodeMap::count — Get number of nodes in the map
  • DOMNamedNodeMap::getNamedItem — Recupera un nodo especificado por su nombre
  • DOMNamedNodeMap::getNamedItemNS — Recupera un nodo especificado por el nombre local y la URI del espacio de nombres
  • DOMNamedNodeMap::item — Recupera un nodo especificado por su índice

User Contributed Notes

sirajshaikh96 at yahoo dot com 01-Jan-2021 02:48
I have tried to solve the general problem occurs in DOMNamedNodeMap that during executing for/foreachloop after executing removeAttribute('$name') for item(0), item(1) is not executing and warning occurs. Following codes give the solution of this problem that in loop item(0) should be applied rather than item($i) because after removing first attribute node now present element has only one attribute node.

<?php
$html  = '<h1 id="h1test" class="h2test">Heading</h1>';
$html .= '<p align="left" class="right">Hello World</p>';

$doc = new DOMDocument();
$doc->loadHTML($html);

// remove attributes from  the h1 element
$h1 = $doc->getElementsByTagName('h1')->item(0);
$length = $h1->attributes->length;
for ($i = 0; $i < $length; $i++) {
    $name = $h1->attributes->item(0)->nodeName;
    $value = $h1->attributes->item(0)->nodeValue;
    $h1->removeAttribute($name);
    echo "h1: removed attribute name :- " .$name."</br>";
    echo "h1: removed attribute value :- " .$value."</br>";
    }
// remove attributes from the p element
$p = $doc->getElementsByTagName('p')->item(0);
for ($i = 0; $i < $length; $i++) {
    $name = $p->attributes->item(0)->nodeName;
    $value = $p->attributes->item(0)->nodeValue;
    $p->removeAttribute($name);
    echo "p: removed attribute name :- " .$name."</br>";
    echo "p: removed attribute value :- " .$value."</br>";
}
?>

OUTPUT:

h1: removed attribute name :- id
h1: removed attribute value :- h1test
h1: removed attribute name :- class
h1: removed attribute value :- h2test
p: removed attribute name :- align
p: removed attribute value :- left
p: removed attribute name :- class
p: removed attribute value :- right
kendsnyder at gmail dot com 29-Oct-2009 07:55
To add to xafford's comment. When iterating a named node map collection using ->item() or using foreach, removing a attribute with DOMNode->removeAttribute() or DOMNode->removeAttributeNode() alters the collection as if it were a stack. To illustrate, the code below tries to remove all attributes from each element but only removes the first. One work around is to copy the named node map into an array before removing attributes. Using PHP 5.2.9 on Windows XP.

<?php
error_reporting(E_ALL);
$html  = '<h1 id="h1test" class="h1test">Heading</h1>';
$html .= '<p align="left" class="ptest">Hello World</p>';

$doc = new DOMDocument();
$doc->loadHTML($html);

// remove attributes from  the h1 element
$h1 = $doc->getElementsByTagName('h1')->item(0);
$length = $h1->attributes->length;
for ($i = 0; $i < $length; ++$i) {
    $name = $h1->attributes->item($i)->name;
    $h1->removeAttribute($name);
    echo "h1: removed attribute `$name`<br>";
}
// remove attributes from the p element
$p = $doc->getElementsByTagName('p')->item(0);
foreach ($p->attributes as $name => $attrNode) {
    $p->removeAttribute($name);
    echo "p: removed attribute `$name`<br>";
}

?>

OUTPUT:
-------
h1: removed attribute `id`

Notice: Trying to get property of non-object in nodemap.php on line 13
h1: removed attribute ``
p: removed attribute `align`
xafford 15-Oct-2009 03:16
I stumbled upon a problem with DOMNamedNodeMap. If you iterate over a DOMNamedNodeMap, representing the attributes of a DOMElement with foreach and you use DOMElement::removeAttributeNode only the first attribute will be handled.

Example (not complete):

<?php

/*
 * Imagine you got a node like this:
 * <a onclick="alert('evil')" href="http://example.com">evil</a>
 * and onclick should be removed, href would not be tested.
 */

foreach ( $node->attributes as $attribute )
{

    echo 'checking attribute ', $attribute->name, '<br />';

    if ( ! in_array ( $attribute->name, $allowed_attributes ) )
    {
        $node->removeAttributeNode ( $attribute );
    }

}

?>

The output would be:

checking attribute onclick


Get number of nodes in the map

  • « DOMNamedNodeMap
  • DOMNamedNodeMap::getNamedItem »
  • PHP Manual
  • DOMNamedNodeMap
  • Get number of nodes in the map

DOMNamedNodeMap::count

(PHP 7 >= 7.2.0)

DOMNamedNodeMap::count — Get number of nodes in the map

Descripción

public DOMNamedNodeMap::count ( ) : int|false

Gets the number of nodes in the map.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the number of nodes in the map, which is identical to the length property.

User Contributed Notes

There are no user contributed notes for this page.


Recupera un nodo especificado por su nombre

  • « DOMNamedNodeMap::count
  • DOMNamedNodeMap::getNamedItemNS »
  • PHP Manual
  • DOMNamedNodeMap
  • Recupera un nodo especificado por su nombre

DOMNamedNodeMap::getNamedItem

(PHP 5, PHP 7)

DOMNamedNodeMap::getNamedItem — Recupera un nodo especificado por su nombre

Descripción

DOMNamedNodeMap::getNamedItem ( string $name ) : DOMNode

Recupera un nodo especificado por su nodeName.

Parámetros

name

El nodeName del nodo a recuperar.

Valores devueltos

Un nodo (de cualquier tipo) con el nodeName especificado, o null si no se encuentra ningún nodo.

Ver también

  • DOMNamedNodeMap::getNamedItemNS() - Recupera un nodo especificado por el nombre local y la URI del espacio de nombres

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


Recupera un nodo especificado por el nombre local y la URI del espacio de nombres

  • « DOMNamedNodeMap::getNamedItem
  • DOMNamedNodeMap::item »
  • PHP Manual
  • DOMNamedNodeMap
  • Recupera un nodo especificado por el nombre local y la URI del espacio de nombres

DOMNamedNodeMap::getNamedItemNS

(PHP 5, PHP 7)

DOMNamedNodeMap::getNamedItemNS — Recupera un nodo especificado por el nombre local y la URI del espacio de nombres

Descripción

DOMNamedNodeMap::getNamedItemNS ( string $namespaceURI , string $localName ) : DOMNode

Recupera un nodo especificado por localName y namespaceURI.

Parámetros

namespaceURI

La URI del espacio de nombres del nodo a recuperar.

localName

El nombre local del nodo a recuperar.

Valores devueltos

Un nodo (de cualquier tipo) con el nombre local y la URI del espacio de nombres especificados, o null si no se encuentra ningún nodo.

Ver también

  • DOMNamedNodeMap::getNamedItem() - Recupera un nodo especificado por su nombre

User Contributed Notes

There are no user contributed notes for this page.


Recupera un nodo especificado por su índice

  • « DOMNamedNodeMap::getNamedItemNS
  • DOMNode »
  • PHP Manual
  • DOMNamedNodeMap
  • Recupera un nodo especificado por su índice

DOMNamedNodeMap::item

(PHP 5, PHP 7)

DOMNamedNodeMap::item — Recupera un nodo especificado por su índice

Descripción

DOMNamedNodeMap::item ( int $index ) : DOMNode

Recupera un nodo especificado por index dentro del objeto DOMNamedNodeMap.

Parámetros

index

Índice dentro de este mapa.

Valores devueltos

El nodo en la posición marcada por index en el mapa, o null si no es un índice válido (mayor o igual que el número de nodos de este mapa).

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 clase DOMNode

(PHP 5, PHP 7)

Sinopsis de la Clase

DOMNode {
/* Propiedades */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
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 DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Métodos */
public appendChild ( DOMNode $newnode ) : DOMNode
public C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public cloneNode ( bool $deep = ? ) : DOMNode
public getLineNo ( ) : int
public getNodePath ( ) : string
public hasAttributes ( ) : bool
public hasChildNodes ( ) : bool
public insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public isDefaultNamespace ( string $namespaceURI ) : bool
public isSameNode ( DOMNode $node ) : bool
public isSupported ( string $feature , string $version ) : bool
public lookupNamespaceUri ( string $prefix ) : string
public lookupPrefix ( string $namespaceURI ) : string
public normalize ( ) : void
public removeChild ( DOMNode $oldnode ) : DOMNode
public replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Propiedades

nodeName

Devuelve el nombre más exacto del tipo de nodo actual

nodeValue

El valor de este nodo, dependiendo de su tipo. A diferencia de al especificación del W3C, el valor de los nodos DOMElement es igual a DOMNode::textContent en lugar de null.

nodeType

Obtiene el tipo del nodo. Una de las constantes XML_xxx_NODE predefinidas

parentNode

El padre de este nodo. Si no existe tal nodo, devuelve null.

childNodes

Un objeto DOMNodeList que contiene todos los hijos de este nodo. Si no existieran hijos, es un objeto DOMNodeList vacío.

firstChild

El primer hijo de este nodo. Si no existiera tal nodo devuelve null.

lastChild

El último hijo de este nodo. Si no existiera tal nodo devuelve null.

previousSibling

El nodo que precede inmediatamente a este ndo. Si no existiera tal nodo devuelve null.

nextSibling

El siguiente nodo inmediato a este nodo. Si no existiera tal nodo devuelve null.

attributes

Un objeto DOMNamedNodeMap que contiene los atributos de este nodo (si es un objeto DOMElement), o de lo contrario null.

ownerDocument

El objeto DOMDocument asociado con este nodo.

namespaceURI

El URI del espacio de nombres de este nodo, o null si no está especificado.

prefix

El prefijo del espacio de nombres de este nodo, o null si no está especificado.

localName

Devuelve la parte local del nombre cualificado de este nodo.

baseURI

El URI base absoluto de este nodo o null si la implementación no pudo obtener un URI absoluto.

textContent

El contenido de texto de este nodo y sus descendientes.

Notas

Nota:

La extensión DOM utiliza la codificación UTF-8. Use utf8_encode() y utf8_decode() para trabajar con textos con codificación ISO-8859-1 o Iconv para otras codificaciones.

Historial de cambios

Versión | Descripción
5.6.1 | La propiedad textContent ahora es escribible (anteriormente era de solo lectura).

Ver también

  • » Especificaión de Nodo del W3C

Tabla de contenidos

  • DOMNode::appendChild — Añade un nuevo hijo al final de los hijos
  • DOMNode::C14N — Canonizar nodos a una cadena
  • DOMNode::C14NFile — Canonizar nodos a un fichero
  • DOMNode::cloneNode — Clona un nodo
  • DOMNode::getLineNo — Obtener el número de línea de un nodo
  • DOMNode::getNodePath — Obtener un XPath de un nodo
  • DOMNode::hasAttributes — Comprueba si un nodo tiene atributos
  • DOMNode::hasChildNodes — Comprueba si el nodo tiene hijos
  • DOMNode::insertBefore — Añade un nuevo hijo antes del nodo de referencia
  • DOMNode::isDefaultNamespace — Comprueba si la URI del espacio de nombres especificada es el espacio de nombres predeterminado
  • DOMNode::isSameNode — Indica si dos nodos son el mismo nodo
  • DOMNode::isSupported — Comprueba si una característica está soportada para la versión especificada
  • DOMNode::lookupNamespaceUri — Obtiene la URI del espacio de nombres del nodo basado en el prefijo
  • DOMNode::lookupPrefix — Obtiene el prefijo del espacio de nombres del nodo basándoes en la URI del espacio de nombres
  • DOMNode::normalize — Normaliza el nodo
  • DOMNode::removeChild — Elimina un hijo de la lista de hijos.
  • DOMNode::replaceChild — Reemplaza un hijo

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.


Añade un nuevo hijo al final de los hijos

  • « DOMNode
  • DOMNode::C14N »
  • PHP Manual
  • DOMNode
  • Añade un nuevo hijo al final de los hijos

DOMNode::appendChild

(PHP 5, PHP 7)

DOMNode::appendChild — Añade un nuevo hijo al final de los hijos

Descripción

public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode

Esta función agrega un hijo a una lista existente de hijos o crea una nueva lista de hijos. El hijo se puede crear con, p.ej., DOMDocument::createElement(), DOMDocument::createTextNode() etc. o simplemente usando cualquier otro nodo.

Parámetros

newnode

El hijo añadido.

Valores devueltos

El nodo añadido.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si este nodo es de sólo lectura o si el padre previo del nodo a ser insertado es de sólo lectura.

DOM_HIERARCHY_REQUEST_ERR

Lanzado si este nodo es de un tipo de no permite hijos del tipo del nodo newnode, o si el nodo a añadir es uno de los progenitores del nodo o si es el nodo en sí.

DOM_WRONG_DOCUMENT_ERR

Lanzado si newnode fue creado desde un documento diferente del que creó este nodo.

Ejemplos

El siguiente ejemplo añadirá un nuevo nodo elemento a un nuevo documento.

Ejemplo #1 Añadiendo un hijo

<?php

$doc = new DOMDocument;

$nodo = $doc->createElement("para");
$nuevo_nodo = $doc->appendChild($nodo);

echo $doc->saveXML();
?>

Ejemplo #2 Hijos anidados

<?php

$doc = new DOMDocument;

$headNode = $doc->createElement("head");
$doc->appendChild($headNode);

$titleNode = $doc->createElement("title");
$headNode->appendChild($titleNode);

echo $doc->saveXML();
?>

Ver también

  • DOMNode::insertBefore() - Añade un nuevo hijo antes del nodo de referencia
  • DOMNode::removeChild() - Elimina un hijo de la lista de hijos.
  • DOMNode::replaceChild() - Reemplaza un hijo

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>


Canonizar nodos a una cadena

  • « DOMNode::appendChild
  • DOMNode::C14NFile »
  • PHP Manual
  • DOMNode
  • Canonizar nodos a una cadena

DOMNode::C14N

(PHP 5 >= 5.2.0, PHP 7)

DOMNode::C14N — Canonizar nodos a una cadena

Descripción

public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string

Canoniza nodos a una cadena

Parámetros

exclusive

Habilita el análisis exclusivo de los nodos que coincidan únicamente con el xpath o los prefijos de nombres de espacio proporcionados.

with_comments

Conservar los comentarios en la salida.

xpath

Un array de xpaths por los que filtrar los nodos.

ns_prefixes

Un array de prefijos de nombres de espacio por los que filtrar los nodos.

Valores devueltos

Devuelve los nodos canonizados como cadenas o false en caso de error

Ver también

  • DOMNode::C14NFile() - Canonizar nodos a un fichero

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


Canonizar nodos a un fichero

  • « DOMNode::C14N
  • DOMNode::cloneNode »
  • PHP Manual
  • DOMNode
  • Canonizar nodos a un fichero

DOMNode::C14NFile

(PHP 5 >= 5.2.0, PHP 7)

DOMNode::C14NFile — Canonizar nodos a un fichero

Descripción

public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int

Canoniza nodos a un fichero

Parámetros

uri

La ruta en la que escribir la salida.

exclusive

Habilita el análisis exclusivo de los nodos que coincidan únicamente con el xpath o los prefijos de nombres de espacio proporcionados.

with_comments

Conservar los comentarios en la salida.

xpath

Un array de xpaths por los que filtrar los nodos.

ns_prefixes

Un array de prefijos de nombres de espacio por los que filtrar los nodos.

Valores devueltos

El número de bytes escritos o false en caso de error

Ver también

  • DOMNode::C14N() - Canonizar nodos a una cadena

User Contributed Notes

There are no user contributed notes for this page.


Clona un nodo

  • « DOMNode::C14NFile
  • DOMNode::getLineNo »
  • PHP Manual
  • DOMNode
  • Clona un nodo

DOMNode::cloneNode

(PHP 5, PHP 7)

DOMNode::cloneNode — Clona un nodo

Descripción

public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode

Crea una copia del nodo.

Parámetros

deep

Indica si copiar todos los nodos descendientes. Este parámetro es false de manera predeterminada.

Valores devueltos

El nodo clonado.

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

?>


Obtener el número de línea de un nodo

  • « DOMNode::cloneNode
  • DOMNode::getNodePath »
  • PHP Manual
  • DOMNode
  • Obtener el número de línea de un nodo

DOMNode::getLineNo

(PHP 5 >= 5.3.0, PHP 7)

DOMNode::getLineNo — Obtener el número de línea de un nodo

Descripción

public DOMNode::getLineNo ( ) : int

Obtiene el número de línea donde está definido el nodo.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Siempre devuelve el número de línea donde está definido el nodo.

Ejemplos

Ejemplo #1 Ejemplo de DOMNode::getLineNo()

<?php
// XML dump for below example
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
    <node />
</root>
XML;

// Crear una nueva instancia de DOMDocument
$dom = new DOMDocument;

// Cargar el XML
$dom->loadXML($xml);

// Imprimir la línea donde el elemento 'node' fue definido
printf('La etiqueta <node> está definida en la línea %d', $dom->getElementsByTagName('node')->item(0)->getLineNo());
?>

El resultado del ejemplo sería:

La etiqueta <node> está definida en la línea 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.


Obtener un XPath de un nodo

  • « DOMNode::getLineNo
  • DOMNode::hasAttributes »
  • PHP Manual
  • DOMNode
  • Obtener un XPath de un nodo

DOMNode::getNodePath

(PHP 5 >= 5.2.0, PHP 7)

DOMNode::getNodePath — Obtener un XPath de un nodo

Descripción

public DOMNode::getNodePath ( ) : string

Obtiene una ruta de ubicación XPath del nodo.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve un string que contiene el XPath, o null en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de DOMNode::getNodePath()

<?php
// Crear una nueva instancia de DOMDocument
$dom = new DOMDocument;

// Cargar el XML
$dom->loadXML('
<frutas>
 <manzanas>
  <manzana>braeburn</manzana>
  <manzana>granny smith</manzana>
 </manzanas>
 <peras>
  <pera>conference</pera>
 </peras>
</frutas>
');

// Imprimir el XPath para cada elemento
foreach ($dom->getElementsByTagName('*') as $nodo) {
    echo $nodo->getNodePath() . "\n";
}
?>

El resultado del ejemplo sería:

/frutas
/frutas/manzanas
/frutas/manzanas/manzana[1]
/frutas/manzanas/manzana[2]
/frutas/peras
/frutas/peras/pera

Ver también

  • DOMXPath

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si un nodo tiene atributos

  • « DOMNode::getNodePath
  • DOMNode::hasChildNodes »
  • PHP Manual
  • DOMNode
  • Comprueba si un nodo tiene atributos

DOMNode::hasAttributes

(PHP 5, PHP 7)

DOMNode::hasAttributes — Comprueba si un nodo tiene atributos

Descripción

public DOMNode::hasAttributes ( ) : bool

Este método comprueba si el nodo tiene atributos. El nodo comprobado tiene que ser un XML_ELEMENT_NODE.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • DOMNode::hasChildNodes() - Comprueba si el nodo tiene hijos

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el nodo tiene hijos

  • « DOMNode::hasAttributes
  • DOMNode::insertBefore »
  • PHP Manual
  • DOMNode
  • Comprueba si el nodo tiene hijos

DOMNode::hasChildNodes

(PHP 5, PHP 7)

DOMNode::hasChildNodes — Comprueba si el nodo tiene hijos

Descripción

public DOMNode::hasChildNodes ( ) : bool

Esta función comprueba si el nodo tiene hijos.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • DOMNode::hasAttributes() - Comprueba si un nodo tiene atributos

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

- - - - - - - - - - - - - -


Añade un nuevo hijo antes del nodo de referencia

  • « DOMNode::hasChildNodes
  • DOMNode::isDefaultNamespace »
  • PHP Manual
  • DOMNode
  • Añade un nuevo hijo antes del nodo de referencia

DOMNode::insertBefore

(PHP 5, PHP 7)

DOMNode::insertBefore — Añade un nuevo hijo antes del nodo de referencia

Descripción

public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode

Esta función inserta un nuevo nodo justo antes que el nodo de referencia. Si planea hacer modificaciones posteriores al hijo añadido debe usar el nodo devuelto.

Parámetros

newnode

El nuevo nodo.

refnode

El nodo de referencia. Si no se proporciona, newnode es añadido al hijo.

Valores devueltos

El nodo insertado.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si este nodo es de sólo lectura o si el padre previo del nodo que va a ser insertado es de sólo lectura.

DOM_HIERARCHY_REQUEST_ERR

Lanzado si este nodo es de un tipo de no permite hijos del tipo del nodo newnode, o si el nodo a añadir es uno de los progenitores del nodo o si es el nodo en sí.

DOM_WRONG_DOCUMENT_ERR

Lanzado si newnode fue creado desde un documento diferente del que creó este nodo.

DOM_NOT_FOUND

Lanzado si refnode no es un hijo de este nodo.

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos

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


Comprueba si la URI del espacio de nombres especificada es el espacio de nombres predeterminado

  • « DOMNode::insertBefore
  • DOMNode::isSameNode »
  • PHP Manual
  • DOMNode
  • Comprueba si la URI del espacio de nombres especificada es el espacio de nombres predeterminado

DOMNode::isDefaultNamespace

(PHP 5, PHP 7)

DOMNode::isDefaultNamespace — Comprueba si la URI del espacio de nombres especificada es el espacio de nombres predeterminado

Descripción

public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool

Indica si namespaceURI es el espacio de nombres especificado.

Parámetros

namespaceURI

La URI del espacio de nombres a buscar.

Valores devueltos

Devuelve true si namespaceURI es el espacio de nombres predeterminado, false si no.

User Contributed Notes

There are no user contributed notes for this page.


Indica si dos nodos son el mismo nodo

  • « DOMNode::isDefaultNamespace
  • DOMNode::isSupported »
  • PHP Manual
  • DOMNode
  • Indica si dos nodos son el mismo nodo

DOMNode::isSameNode

(PHP 5, PHP 7)

DOMNode::isSameNode — Indica si dos nodos son el mismo nodo

Descripción

public DOMNode::isSameNode ( DOMNode $node ) : bool

Esta función indica si dos nodos son el mismo nodo. La comparación no está basada en el contenido

Parámetros

node

El nodo comparado.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si una característica está soportada para la versión especificada

  • « DOMNode::isSameNode
  • DOMNode::lookupNamespaceUri »
  • PHP Manual
  • DOMNode
  • Comprueba si una característica está soportada para la versión especificada

DOMNode::isSupported

(PHP 5, PHP 7)

DOMNode::isSupported — Comprueba si una característica está soportada para la versión especificada

Descripción

public DOMNode::isSupported ( string $feature , string $version ) : bool

Comprueba si la característica solicitada dada por feature está soportada para la versión especificada dada por version.

Parámetros

feature

La característica a comprobar. Véase el ejemplo de DOMImplementation::hasFeature() para una lista de características.

version

El número de versión de feature a comprobar.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • DOMImplementation::hasFeature() - Comprueba si la implementación de DOM implementa una característica específica

User Contributed Notes

There are no user contributed notes for this page.


Obtiene la URI del espacio de nombres del nodo basado en el prefijo

  • « DOMNode::isSupported
  • DOMNode::lookupPrefix »
  • PHP Manual
  • DOMNode
  • Obtiene la URI del espacio de nombres del nodo basado en el prefijo

DOMNode::lookupNamespaceUri

(PHP 5, PHP 7)

DOMNode::lookupNamespaceUri — Obtiene la URI del espacio de nombres del nodo basado en el prefijo

Descripción

public DOMNode::lookupNamespaceUri ( string $prefix ) : string

Obtiene la URI del espacio de nombres del nodo basado en prefix.

Parámetros

prefix

El prefijo del espacio de nombres.

Valores devueltos

La URI del espacio de nombres del nodo.

Ver también

  • DOMNode::lookupPrefix() - Obtiene el prefijo del espacio de nombres del nodo basándoes en la URI del espacio de nombres

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


Obtiene el prefijo del espacio de nombres del nodo basándoes en la URI del espacio de nombres

  • « DOMNode::lookupNamespaceUri
  • DOMNode::normalize »
  • PHP Manual
  • DOMNode
  • Obtiene el prefijo del espacio de nombres del nodo basándoes en la URI del espacio de nombres

DOMNode::lookupPrefix

(PHP 5, PHP 7)

DOMNode::lookupPrefix — Obtiene el prefijo del espacio de nombres del nodo basándoes en la URI del espacio de nombres

Descripción

public DOMNode::lookupPrefix ( string $namespaceURI ) : string

Obtiene el prefijo del espacio de nombres del nodo basándoes en la URI del espacio de nombres.

Parámetros

namespaceURI

La URI del espacio de nombres.

Valores devueltos

El prefijo del espacio de nombres.

Ver también

  • DOMNode::lookupNamespaceUri() - Obtiene la URI del espacio de nombres del nodo basado en el prefijo

User Contributed Notes

There are no user contributed notes for this page.


Normaliza el nodo

  • « DOMNode::lookupPrefix
  • DOMNode::removeChild »
  • PHP Manual
  • DOMNode
  • Normaliza el nodo

DOMNode::normalize

(PHP 5, PHP 7)

DOMNode::normalize — Normaliza el nodo

Descripción

public DOMNode::normalize ( ) : void

Elimina nodos de texto vacíos y une nodos de texto adyacentes en este nodo y todos sus hijos.

Valores devueltos

No devuelve ningún valor.

Ver también

  • » La Especificación DOM
  • DOMDocument::normalizeDocument() - Normaliza el documento

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.


Elimina un hijo de la lista de hijos.

  • « DOMNode::normalize
  • DOMNode::replaceChild »
  • PHP Manual
  • DOMNode
  • Elimina un hijo de la lista de hijos.

DOMNode::removeChild

(PHP 5, PHP 7)

DOMNode::removeChild — Elimina un hijo de la lista de hijos.

Descripción

public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode

Esta función elimina un hijo de la lista de hijos.

Parámetros

oldnode

El hijo eliminado.

Valores devueltos

Si el hijo ha podido ser eliminado la función devuelve el hijo antiguo.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanzado si el nodo es de sólo lectura.

DOM_NOT_FOUND

Lanzado si oldnode no es un hijo de este nodo.

Ejemplos

El siguiente ejemplo eliminará el elemento chapter de nuestro documento XML.

Ejemplo #1 Eliminar un hijo

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// recuperamos el capítulo y lo eliminamos del libro
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
          "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
<book id="listing">
 <title>My lists</title>

</book>

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMNode::replaceChild() - Reemplaza un hijo

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


Reemplaza un hijo

  • « DOMNode::removeChild
  • DOMNodeList »
  • PHP Manual
  • DOMNode
  • Reemplaza un hijo

DOMNode::replaceChild

(PHP 5, PHP 7)

DOMNode::replaceChild — Reemplaza un hijo

Descripción

public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode

Esta función reemplaza el hijo oldnode con es nuevo nodo newnode proporcionado. Si el nuevo nodo ya es un hijo no será añadido una segunda vez. Si el reemplazo tiene éxito se devuelve el nodo antiguo.

Parámetros

newnode

El nuevo nodo. Debe ser un miembro del documento objetivo, es decir, creado con uno de los métodos DOMDocument->createXXX() o importado al documento por DOMDocument::importNode.

oldnode

El nodo antiguo.

Valores devueltos

El nodo antiguo o false si ocurrió un error.

Errores/Excepciones

DOM_NO_MODIFICATION_ALLOWED_ERR

Lanazado si este nodo es de sólo lectura o si el padre anterior del nodo al que va a ser insertado es de sólo lectura.

DOM_HIERARCHY_REQUEST_ERR

Lanzado si el nodo es de un tipo que no permite hijos del tipo del nodo newnode, o si el nodo a colocar es uno de los progenitores de este nodo o es este nodo en sí.

DOM_WRONG_DOCUMENT_ERR

Lanzado si newnode fue creado desde un documento diferente que el que creó este nodo.

DOM_NOT_FOUND

Lanzado si oldnode no es un hijo de este nodo.

Ver también

  • DOMNode::appendChild() - Añade un nuevo hijo al final de los hijos
  • DOMNode::removeChild() - Elimina un hijo de la lista de hijos.

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 clase DOMNodeList

(PHP 5, PHP 7)

Sinopsis de la Clase

DOMNodeList implements Traversable {
/* Propiedades */
readonly public int $length ;
/* Métodos */
public count ( ) : int
item ( int $index ) : DOMNode
}

Propiedades

length

El número de nodos de la lista. El rango de índices válidos de nodo hijo es de 0 a length - 1, ambos inclusive.

Ver también

  • » Especificación W3C de NodeList

Tabla de contenidos

  • DOMNodeList::count — Obtiene el número de nodos en la lista
  • DOMNodeList::item — Recupera un nodo especificado por un índice

User Contributed Notes

ignitedfirestarter at gmail dot com 04-Jul-2012 10:39
If you want to recurse over a DOM then this might help:
<?php

/**
 * PHP's DOM classes are recursive but don't provide an implementation of
 * RecursiveIterator. This class provides a RecursiveIterator for looping over DOMNodeList
 */
class DOMNodeRecursiveIterator extends ArrayIterator implements RecursiveIterator {

  public function __construct (DOMNodeList $node_list) {

    $nodes = array();
    foreach($node_list as $node) {
      $nodes[] = $node;
    }

    parent::__construct($nodes);

  }

  public function getRecursiveIterator(){
    return new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST);
  }

  public function hasChildren () {
    return $this->current()->hasChildNodes();
  }

  public function getChildren () {
    return new self($this->current()->childNodes);
  }

}
?>
geompse at gmail dot com 19-May-2010 08:39
Note that $length is calculated (php5.3.2).
Iterating over a large NodeList may be time expensive.

Prefer :
$nb = $nodelist->length;
for($pos=0; $pos<$nb; $pos++)

Than:
for($pos=0; $pos<$nodelist->length; $pos++)

I had a hard time figuring that out...
bobvandell at hotmail dot com 26-Aug-2008 09:12
That's actually incorrect. You can use function results as objects. It makes building an API for your database very clean and neat. For example:

Our code:

$articles = Node::screate('tags', 123456)->assets('like:title:test')->articles;

We use the above code to get articles that are linked to assets that are linked to a specific tag in our database.
c dot 1 at smithies dot org 23-May-2008 05:43
You can modify, and even delete, nodes from a DOMNodeList if you iterate backwards:

$els = $document->getElementsByTagName('input');
for ($i = $els->length; --$i >= 0; ) {
  $el = $els->item($i);
  switch ($el->getAttribute('name')) {
    case 'MAX_FILE_SIZE' :
      $el->parentNode->removeChild($el);
    break;
    case 'inputfile' :
      $el->setAttribute('type', 'text');
    //break;
  }
}
drichter at muvicom dot de 14-May-2008 06:11
Addition to my first note:

An traditional for-loop does not allow you to change the DOM-tree while looping - the effects are the nearly the same as with foreach. So you have to collect the nodes in an array and do the tree-altering stuff within a second loop (looping the array this time ...)
drichter at muvicom dot de 14-May-2008 04:56
I have done some testing and have found 2 results:
(My System: Win XP with PHP 5.2.1)

1) Iteration with foreach does function correctly as "james dot j dot hackett at gmail dot com" writes, _if_ you only do readonly stuff with foreach or minor writings of some attributes.

2) foreach does not function, if you are doing some DOM-Operations while iterating. In my situation it was adding the iterated $node as an child to an new node:

$newNode = $dom->createElement('newNode') ;
foreach ($nodeList as $node) {
  echo $node->nodeValue ;
  $newNode->appendChild($node) ;
}

This only gives you the first element ...

I'm interpreting it as an confusing but correct behavior because of the changes within the $dom-object while appending the node at an additional place ...

So, if you want to do something like 2) use for, length and item() :)
james dot j dot hackett at gmail dot com 08-May-2008 09:47
In Response to 'kassah at gmail'

You don't need to convert a DOMNodeList to an array in order iterate through it using 'foreach'.  You can use foreach directly with the DOMNodeList.

$nodeList = $someDomDocument->getElementsbytagname('user');

foreach ($nodeList as $node) {
    echo $node->nodeValue;
}
brack at wjp dot de 21-Apr-2008 02:35
In PHP 5.2.5 (Windows) it is not possible to iterate correctly over the DOMNodeList object returned by DOMNode->childNodes using foreach. Instead I had to use the for loop in conjunction with the item() method of DOMNodeList for iterating over all child nodes correctly.

I don't know whether this is really a bug, but apparently it is.


Obtiene el número de nodos en la lista

  • « DOMNodeList
  • DOMNodeList::item »
  • PHP Manual
  • DOMNodeList
  • Obtiene el número de nodos en la lista

DOMNodeList::count

(PHP 7 >= 7.2.0)

DOMNodeList::count — Obtiene el número de nodos en la lista

Descripción

public DOMNodeList::count ( ) : int

Obtiene el número de nodos de la lista.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve el número de nodos de la lista, que es idéntica a la propiedad 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


Recupera un nodo especificado por un índice

  • « DOMNodeList::count
  • DOMNotation »
  • PHP Manual
  • DOMNodeList
  • Recupera un nodo especificado por un índice

DOMNodeList::item

(PHP 5, PHP 7)

DOMNodeList::item — Recupera un nodo especificado por un índice

Descripción

DOMNodeList::item ( int $index ) : DOMNode

Recupera un nodo especificado por index dentro del objeto DOMNodeList.

Sugerencia

Si necesita conocer el número de nodos de la colección, use la propiedad length del objeto DOMNodeList.

Parámetros

index

Índice del nodo de la colección.

Valores devueltos

El nodo en la posición marcada por index del objeto DOMNodeList, o null si no es un índice válido.

Ejemplos

Ejemplo #1 Atravesar todas las entradas de una tabla

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

?>

De manera alternativa, se puede usar foreach, que es una manera mucho más conveniente:

<?php

foreach ($items as $item) {
    echo $item->nodeValue . "\n";
}

?>

El resultado del ejemplo sería:

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 clase DOMNotation

(PHP 5, PHP 7)

Sinopsis de la Clase

DOMNotation extends DOMNode {
/* Propiedades */
readonly public string $publicId ;
readonly public string $systemId ;
/* Métodos heredados */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Propiedades

publicId

systemId

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMProcessingInstruction

(PHP 5, PHP 7)

Sinopsis de la Clase

DOMProcessingInstruction extends DOMNode {
/* Propiedades */
readonly public string $target ;
public string $data ;
/* Métodos */
public __construct ( string $name , string $value = ? )
/* Métodos heredados */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Propiedades

target

data

Tabla de contenidos

  • DOMProcessingInstruction::__construct — Crea un nuevo objeto DOMProcessingInstruction

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo objeto DOMProcessingInstruction

  • « DOMProcessingInstruction
  • DOMText »
  • PHP Manual
  • DOMProcessingInstruction
  • Crea un nuevo objeto DOMProcessingInstruction

DOMProcessingInstruction::__construct

(PHP 5, PHP 7)

DOMProcessingInstruction::__construct — Crea un nuevo objeto DOMProcessingInstruction

Descripción

public DOMProcessingInstruction::__construct ( string $name , string $value = ? )

Crea un nuevo objeto DOMProcessingInstruction. Este objeto es de sólo lectura. Se puede añadir a un documento, pero no se pueden añadir nodos adicionales a este nodo hata que el nodo esté asociado con un documento. Para crear un nodo modificable, use DOMDocument::createProcessingInstruction.

Parámetros

name

El nombre de la etiqueta de la instrucción en proceso.

value

El valor de la intrucción en proceso.

Ejemplos

Ejemplo #1 Crear un nuevo objeto 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 "Hola Mundo"; ');
$body->appendChild($pinode);
echo $dom->saveXML();

?>

El resultado del ejemplo sería:

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hola Mundo"; ?></body></html>

Ver también

  • DOMDocument::createProcessingInstruction() - Crea un nuevo nodo PI

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMText

(PHP 5, PHP 7)

Introducción

La clase DOMText hereda de DOMCharacterData y representa el contenido textual de un objeto DOMElement o DOMAttr.

Sinopsis de la Clase

DOMText extends DOMCharacterData {
/* Propiedades */
readonly public string $wholeText ;
/* Métodos */
public __construct ( string $value = ? )
public isElementContentWhitespace ( ) : bool
public isWhitespaceInElementContent ( ) : bool
public splitText ( int $offset ) : DOMText
/* Métodos heredados */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ( bool $exclusive = ? , bool $with_comments = ? , array $xpath = ? , array $ns_prefixes = ? ) : string
public DOMNode::C14NFile ( string $uri , bool $exclusive = false , bool $with_comments = false , array $xpath = ? , array $ns_prefixes = ? ) : int
public DOMNode::cloneNode ( bool $deep = ? ) : DOMNode
public DOMNode::getLineNo ( ) : int
public DOMNode::getNodePath ( ) : string
public DOMNode::hasAttributes ( ) : bool
public DOMNode::hasChildNodes ( ) : bool
public DOMNode::insertBefore ( DOMNode $newnode , DOMNode $refnode = ? ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Propiedades

wholeText

Mantiene todo el texto de los nodos Text adyacentes de forma lógica (sin estar separados por Element, Comment o Processing Instruction).

Tabla de contenidos

  • DOMText::__construct — Crea un nuevo objeto DOMText
  • DOMText::isElementContentWhitespace — Devuelve si este nodo de texto contiene espacios en blanco en el contenido del elemento
  • DOMText::isWhitespaceInElementContent — Indica si este nodo de texto contiene espacios en blanco
  • DOMText::splitText — Rompe este nodo en dos nodos en el índice especificado

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


Crea un nuevo objeto DOMText

  • « DOMText
  • DOMText::isElementContentWhitespace »
  • PHP Manual
  • DOMText
  • Crea un nuevo objeto DOMText

DOMText::__construct

(PHP 5, PHP 7)

DOMText::__construct — Crea un nuevo objeto DOMText

Descripción

public DOMText::__construct ( string $value = ? )

Crea un nuevo objeto DOMText.

Parámetros

value

El valor del nodo de texto. Si no se proporciona, se crea un nodo de texto vacío.

Ejemplos

Ejemplo #1 Crear un nuevo objeto 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="utf-8"?><root>root value</root> */

?>

Ver también

  • DOMDocument::createTextNode() - Crea un nuevo nodo de texto

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.


Devuelve si este nodo de texto contiene espacios en blanco en el contenido del elemento

  • « DOMText::__construct
  • DOMText::isWhitespaceInElementContent »
  • PHP Manual
  • DOMText
  • Devuelve si este nodo de texto contiene espacios en blanco en el contenido del elemento

DOMText::isElementContentWhitespace

(No hay información de versión disponible, podría estar únicamente en Git)

DOMText::isElementContentWhitespace — Devuelve si este nodo de texto contiene espacios en blanco en el contenido del elemento

Descripción

public DOMText::isElementContentWhitespace ( ) : bool

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

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.


Indica si este nodo de texto contiene espacios en blanco

  • « DOMText::isElementContentWhitespace
  • DOMText::splitText »
  • PHP Manual
  • DOMText
  • Indica si este nodo de texto contiene espacios en blanco

DOMText::isWhitespaceInElementContent

(PHP 5, PHP 7)

DOMText::isWhitespaceInElementContent — Indica si este nodo de texto contiene espacios en blanco

Descripción

public DOMText::isWhitespaceInElementContent ( ) : bool

Indica si este nodo de texto contiene únicamente espacios en blanco o si está vacío. El nodo de texto está determinado a contener espacios en blanco en el contenido del elemento durante la carga del documento.

Valores devueltos

Devuelve true si el nodo contiene cero o más carecteres espacio en blanco y nada más. De lo contrario deveulve false.

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


Rompe este nodo en dos nodos en el índice especificado

  • « DOMText::isWhitespaceInElementContent
  • DOMXPath »
  • PHP Manual
  • DOMText
  • Rompe este nodo en dos nodos en el índice especificado

DOMText::splitText

(PHP 5, PHP 7)

DOMText::splitText — Rompe este nodo en dos nodos en el índice especificado

Descripción

public DOMText::splitText ( int $offset ) : DOMText

Rompe este nodo en dos nodos en el índice especificado por offset, manteniéndolos en el árbol como hermanos.

Después de la separación, este nodo contendrá todos el contenido hata offset. Si el nodo original tenía un nodo padre, el nuevo nodo se inserta como el hermano siguiente del nodo original. Cuando offset es igual a la longitud de este nodo, el nuevo nodo no tendrá información.

Parámetros

offset

El índice en el que se hace la separación, comenzando en 0.

Valores devueltos

El nuevo nodo del mismo tipo, que contiene todo el contenido desde y después de 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 clase DOMXPath

(PHP 5, PHP 7)

Introducción

Soporta XPath 1.0

Sinopsis de la Clase

DOMXPath {
/* Propiedades */
public DOMDocument $document ;
/* Métodos */
public __construct ( DOMDocument $doc )
public evaluate ( string $expression , DOMNode $contextnode = ? , bool $registerNodeNS = true ) : mixed
public query ( string $expression , DOMNode $contextnode = ? , bool $registerNodeNS = true ) : DOMNodeList
public registerNamespace ( string $prefix , string $namespaceURI ) : bool
public registerPhpFunctions ( mixed $restrict = ? ) : void
}

Propiedades

document

Tabla de contenidos

  • DOMXPath::__construct — Crea un nuevo objeto DOMXPath
  • DOMXPath::evaluate — Evalúa la expresión XPath dada y devuelve un resultado escrito si es posible
  • DOMXPath::query — Evalúa la expresión XPath dada
  • DOMXPath::registerNamespace — Registra el espacio de nombres con el objeto DOMXPath
  • DOMXPath::registerPhpFunctions — Registra funciones de PHP como funciones 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.
david at lionhead dot nl 11-Aug-2009 06:33
When using DOMXPath and having a default namespace. Consider using an intermediate function to add the default namespace to all queries:

<?php
// The default namespace: x:xmlns="http://..."
$path="/Book/Title";
$path=preg_replace("\/([a-zA-Z])","/x:$1",$path);

// Result: /x:Book/x:Title
?>
Mark Omohundro, ajamyajax dot com 14-Dec-2008 09:15
<?php
// to retrieve selected html data, try these DomXPath examples:

$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

$xpath = new DOMXpath($doc);

// example 1: for everything with an id
//$elements = $xpath->query("//*[@id]");

// example 2: for node data in a selected id
//$elements = $xpath->query("/html/body/div[@id='yourTagIdHere']");

// example 3: same as above with wildcard
$elements = $xpath->query("*/div[@id='yourTagIdHere']");

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>[". $element->nodeName. "]";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}
?>


Crea un nuevo objeto DOMXPath

  • « DOMXPath
  • DOMXPath::evaluate »
  • PHP Manual
  • DOMXPath
  • Crea un nuevo objeto DOMXPath

DOMXPath::__construct

(PHP 5, PHP 7)

DOMXPath::__construct — Crea un nuevo objeto DOMXPath

Descripción

public DOMXPath::__construct ( DOMDocument $doc )

Crea un nuevo objeto DOMXPath.

Parámetros

doc

El objeto DOMDocument asociado con el objeto 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.


Evalúa la expresión XPath dada y devuelve un resultado escrito si es posible

  • « DOMXPath::__construct
  • DOMXPath::query »
  • PHP Manual
  • DOMXPath
  • Evalúa la expresión XPath dada y devuelve un resultado escrito si es posible

DOMXPath::evaluate

(PHP 5 >= 5.1.0, PHP 7)

DOMXPath::evaluate — Evalúa la expresión XPath dada y devuelve un resultado escrito si es posible

Descripción

public DOMXPath::evaluate ( string $expression , DOMNode $contextnode = ? , bool $registerNodeNS = true ) : mixed

Ejecuta la expresión XPath dada por expression y devuelve un resultado escrito si es posible.

Parámetros

expression

La expresión XPath a ejecutar.

contextnode

El parámetro opcional contextnode se puede especificar para hacer consultas XPath relativas. Por omisión, las consultas son relativas al elemento raíz.

registerNodeNS

El parámetro opcional registerNodeNS puede ser especificado para deshabilitar el registro automático del nodo de contexto.

Valores devueltos

Devuelve un resultado escrito si es posible o un objeto DOMNodeList que contiene todos los nodos coincidentes con la expresión XPath dada por expression.

Si el parámetro expression está malformado o el parámetro contextnode es inválido, DOMXPath::evaluate() devuelve false.

Historial de cambios

Versión | Descripción
5.3.3 | Se añadió el parámetro registerNodeNS.

Ejemplos

Ejemplo #1 Obtener el número de todos los libros en inglés

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// nuestra consulta es relativa al nodo tbody
$consulta = 'count(row/entry[. = "en"])';

$entradas = $xpath->evaluate($consulta, $tbody);
echo "Hay $entradas libros en inglés\n";

?>

El resultado del ejemplo sería:

Hay 2 libros en inglés

Ver también

  • DOMXPath::query() - Evalúa la expresión XPath dada

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

            }
        }
    }
?>


Evalúa la expresión XPath dada

  • « DOMXPath::evaluate
  • DOMXPath::registerNamespace »
  • PHP Manual
  • DOMXPath
  • Evalúa la expresión XPath dada

DOMXPath::query

(PHP 5, PHP 7)

DOMXPath::query — Evalúa la expresión XPath dada

Descripción

public DOMXPath::query ( string $expression , DOMNode $contextnode = ? , bool $registerNodeNS = true ) : DOMNodeList

Ejecuta la expresión XPath dada por expression.

Parámetros

expression

La expresión XPath a ejecutar.

contextnode

El parámetro opcional contextnode se puede especificar para hacer consultas XPath relativas. Por omisión, las consultas son relativas al elemento raíz.

registerNodeNS

El parámetro opcional registerNodeNS puede ser especificado para deshabilitar el registro automático del nodo de contexto.

Valores devueltos

Devuelve un objeto DOMNodeList que contiene todos los nodos coincidentes con la expresión XPath dada por expression. Cualquier expresión que no devuelva nodos devolverá un objeto DOMNodeList vacío.

Si el parámetro expression está malformado o el parámetro contextnode es inválido, DOMXPath::query() devuelve false.

Historial de cambios

Versión | Descripción
5.3.3 | Se añadió el parámetro registerNodeNS.

Ejemplos

Ejemplo #1 Obtener todos los libros en inglés

<?php

$doc = new DOMDocument;

// No queremos molestar con espacios en blanco
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Empezamos desde el elemento root
$consulta = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entradas = $xpath->query($consulta);

foreach ($entradas as $entrada) {
    echo "Se encotró {$entrada->previousSibling->previousSibling->nodeValue}," .
         " por {$entrada->previousSibling->nodeValue}\n";
}
?>

El resultado del ejemplo sería:

Se encontró The Grapes of Wrath, por John Steinbeck
Se encontró The Pearl, por John Steinbeck

También podemos usar el parámetro contextnode para acortar nuestra expresión:

<?php

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// nuestra consulta es relativa al nodo tbody
$consulta = 'row/entry[. = "en"]';

$entradas = $xpath->query($consulta, $tbody);

foreach ($entradas as $entrada) {
    echo "Se encontró {$entrada->previousSibling->previousSibling->nodeValue}," .
         " por {$entrada->previousSibling->nodeValue}\n";
}
?>

Ver también

  • DOMXPath::evaluate() - Evalúa la expresión XPath dada y devuelve un resultado escrito si es posible

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


Registra el espacio de nombres con el objeto DOMXPath

  • « DOMXPath::query
  • DOMXPath::registerPhpFunctions »
  • PHP Manual
  • DOMXPath
  • Registra el espacio de nombres con el objeto DOMXPath

DOMXPath::registerNamespace

(PHP 5, PHP 7)

DOMXPath::registerNamespace — Registra el espacio de nombres con el objeto DOMXPath

Descripción

public DOMXPath::registerNamespace ( string $prefix , string $namespaceURI ) : bool

Registra namespaceURI y prefix con el objeto DOMXPath.

Parámetros

prefix

El prefijo.

namespaceURI

La URI del espacio de nombres.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

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.


Registra funciones de PHP como funciones XPath

  • « DOMXPath::registerNamespace
  • Funciones de DOM »
  • PHP Manual
  • DOMXPath
  • Registra funciones de PHP como funciones XPath

DOMXPath::registerPhpFunctions

(PHP 5 >= 5.3.0, PHP 7)

DOMXPath::registerPhpFunctions — Registra funciones de PHP como funciones XPath

Descripción

public DOMXPath::registerPhpFunctions ( mixed $restrict = ? ) : void

Este método habilita la capacidad de usar funciones de PHP dentro de expresiones XPath.

Parámetros

restrict

Use este parámetro para permitir solamente que ciertas funciones sean llamadas desde XPath.

Este parámetro puede ser un string (un nombre de función) o un array de nombres de funciones.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Los siguientes ejemplos usan book.xml que contiene lo siguiente:

Ejemplo #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>

Ejemplo #2 DOMXPath::registerPHPFunctions() con php:functionString

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Registrar el espacio de nombres php: namespace (requerido)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Registrar funciones de PHP (sin restricciones)
$xpath->registerPHPFunctions();

// Llamar a la función substr en el título del libro
$nodos = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');

echo "Se encontró {$nodos->length} libros que empiezan con 'PHP':\n";
foreach ($nodos as $nodo) {
    $title  = $nodo->getElementsByTagName("title")->item(0)->nodeValue;
    $author = $nodo->getElementsByTagName("author")->item(0)->nodeValue;
    echo "$title por $author\n";
}

?>

El resultado del ejemplo sería algo similar a:

Se encontró 2 libros que empiezan con 'PHP':
PHP Basics por Jim Smith
PHP Secrets por Jenny Smythe

Ejemplo #3 DOMXPath::registerPHPFunctions() con php:function

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Registrar el espacio de nombres php: namespace (requerido)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Registrar funciones de PHP (sólo has_multiple)
$xpath->registerPHPFunctions("has_multiple");

function has_multiple($nodos) {
    // Return true if more than one author
    return count($nodos) > 1;
}
// Filtrar libros con múltiples autores
$libros = $xpath->query('//book[php:function("has_multiple", author)]');

echo "Libros con múltiples autores:\n";
foreach ($libros as $libro) {
    echo $libro->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}

?>

El resultado del ejemplo sería algo similar a:

Libros con múltiples autores:
PHP Basics

Ver también

  • DOMXPath::registerNamespace() - Registra el espacio de nombres con el objeto DOMXPath
  • DOMXPath::query() - Evalúa la expresión XPath dada
  • DOMXPath::evaluate() - Evalúa la expresión XPath dada y devuelve un resultado escrito si es posible

User Contributed Notes

There are no user contributed notes for this page.


Funciones de DOM

Tabla de contenidos

  • dom_import_simplexml — Obtiene un objeto DOMElement desde un objeto SimpleXMLElement

User Contributed Notes

There are no user contributed notes for this page.


Obtiene un objeto DOMElement desde un objeto SimpleXMLElement

  • « Funciones de DOM
  • libxml »
  • PHP Manual
  • Funciones de DOM
  • Obtiene un objeto DOMElement desde un objeto SimpleXMLElement

dom_import_simplexml

(PHP 5, PHP 7)

dom_import_simplexml — Obtiene un objeto DOMElement desde un objeto SimpleXMLElement

Descripción

dom_import_simplexml ( SimpleXMLElement $node ) : DOMElement

Esta función toma el nodo node de la clase SimpleXML y lo convierte en un nodod DOMElement. Este nuevo objeto se puede usar como un nodo DOMElement nativo.

Parámetros

node

El nodo SimpleXMLElement.

Valores devueltos

El nodo DOMElement añdido o false si ocurrió un error.

Ejemplos

Ejemplo #1 Importar SimpleXML a DOM con dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

if ($sxe === false) {
    echo 'Error al analizar el documento';
    exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
    echo 'Error al convertir a XML';
    exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

?>

Ver también

  • simplexml_import_dom() - Obtiene un objeto SimpleXMLElement de un nodo 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

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • libXMLError — La clase libXMLError
  • Funciones de libxml
    • libxml_clear_errors — Limpia el buffer de errores de libxml
    • libxml_disable_entity_loader — Deshabilita la capacidad de cargar entidades externas
    • libxml_get_errors — Recupera un array de errores
    • libxml_get_last_error — Recupera el último error de libxml
    • libxml_set_external_entity_loader — Cambia el cargador externo por defecto de entidades
    • libxml_set_streams_context — Configura el contexto de flujo para el próximo documento libxml cargado o escrito
    • libxml_use_internal_errors — Deshabilita errores libxml y permite al usuario extraer información de errores según sea necesario

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Estas funciones/constantes están disponibles a partir de PHP 5.1.0. Las siguientes extensiones del núcleo dependen de esta extensión libxml: DOM, libxml, SimpleXML, SOAP, WDDX, XSL, XML, XMLReader, XMLRPC y XMLWriter.

User Contributed Notes

There are no user contributed notes for this page.


Requerimientos

Esta estensión requiere » libxml >= 2.6.0.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

La extensión libxml está habilitada por defecto, aún asi es posible deshabilitarla con la directiva --disable-libxml.

La directiva --with-libxml-dir opcional es utilizada para especificar la ubicación de libxml dentro del sistema en el que PHP está siendo compilado, de lo contrario solo las ubicaciones por defecto son escaneadas. El proceso configure chequea por libxml (específicamente, xml2-config) en el siguiente orden:

  1. La ubicación ([DIR]) especificada con --with-libxml-dir ([DIR]=/bin/xml2-config)

  2. /usr/local/bin/xml2-config

  3. /usr/bin/xml2-config

Si configure no puede encontrar xml2-config en el directorio especificado por --with-libxml-dir, entonces continuará y comprobará las ubicaciones por defecto.

User Contributed Notes

fred5 at no dot spam dot co dot za 31-Jul-2014 10:29
(I tried to enter a bug but the PHP version selection drop down isn't working so I have entered here)

This documentation is very confusing as it refers to xml2-config as a directory and file interchangeably (it is a file) ...so I'm not clear whether to use the containing directory or the actual file in the switch


Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles sólo cuando la extensión haya sido compilada con PHP, o bien sea cargada dinámicamente en ejecución.

LIBXML_COMPACT (integer)
Activa la optimización de asignación de nodos pequeños. Esto puede acelerar la aplicación sin la necesidad de cambiar el código.

Nota:

Solo disponible en Libxml >= 2.6.21

LIBXML_DTDATTR (integer)
Atributos DTD por defecto
LIBXML_DTDLOAD (integer)
Carga el subconjunto externo
LIBXML_DTDVALID (integer)
Valida con el DTD
LIBXML_HTML_NOIMPLIED (integer)
Establece el indicador HTML_PARSE_NOIMPLIED flag, el cual desactiva la adición automática de elementos html/body... implicados.

Nota:

Solamente disponible en Libxml >= 2.7.7 (a partir de PHP >= 5.4.0)

LIBXML_HTML_NODEFDTD (integer)
Establece el indicador HTML_PARSE_NODEFDTD, el cual previente que se añada un tipo de documento predeterminado cuando no se encuentra uno.

Nota:

Solamente disponible en Libxml >= 2.7.8 (a partir de PHP >= 5.4.0)

LIBXML_NOBLANKS (integer)
Elimina nodos en blanco
LIBXML_NOCDATA (integer)
Combina CDATA como nodos de texto
LIBXML_NOEMPTYTAG (integer)
Expande etiquetas vacías (por ej. de <br/> a <br></br>)

Nota:

Esta opción está actualmente disponible solo en las funciones DOMDocument::save y DOMDocument::saveXML.

LIBXML_NOENT (integer)
Sustituye entidades
LIBXML_NOERROR (integer)
Suprime reportes de errores
LIBXML_NONET (integer)
Deshabilita el acceso a red cuando se cargan documentos
LIBXML_NOWARNING (integer)
Suprime reportes de advertencias
LIBXML_NOXMLDECL (integer)
Omite la declaración XML cuando se guarda un documento

Nota:

Solo disponible en Libxml >= 2.6.21

LIBXML_NSCLEAN (integer)
Eliminar declaraciones de nombre de espacios redundantes
LIBXML_PARSEHUGE (integer)
Establece la bandera XML_PARSE_HUGE, que hace más flexible cualquier límite hardcode del analizador. Esto afecta a los límites tales como la profundidad máxima de un documento o la recursión de entidades, así como los límites de tamaño de los nodos de texto.

Nota:

Solamente está disponible en Libxml >= 2.7.0 (a partir de PHP >= 5.3.2 y PHP >= 5.2.12)

LIBXML_PEDANTIC (integer)
Establece el indicador XML_PARSE_PEDANTIC, el cual habilita el informe de errores pedante.

Nota:

Disponible a partir de PHP >= 5.4.0

LIBXML_XINCLUDE (integer)
Implementa la sustitución XInclude
LIBXML_ERR_ERROR (integer)
Un error recuperable
LIBXML_ERR_FATAL (integer)
Un error fatal
LIBXML_ERR_NONE (integer)
Sin errores
LIBXML_ERR_WARNING (integer)
Una simple advertencia
LIBXML_VERSION (integer)
La versión de libxml, como 20605 o 20617
LIBXML_DOTTED_VERSION (string)
La versión de libxml, como 2.6.5 o 2.6.17
LIBXML_SCHEMA_CREATE (integer)
Crear nodos de valor predeterminado/fijo durante la validación del esquema XSD

Nota:

Solamente disponible en Libxml >= 2.6.14 (a partir de PHP >= 5.5.2)

User Contributed Notes

vetalstar at mail dot ru 16-Nov-2017 12:26
LIBXML_DOTTED_VERSION option doesn't work.
libxml version: 2.9.4

<?php

echo LIBXML_DOTTED_VERSION;
$xml = new SimpleXMLElement('<fasa_request id="1234567"/>', LIBXML_NOXMLDECL);

?>
@oneseventeen 05-Feb-2011 11:51
When inserting XML DOM Elements inside existing XML DOM Elements that I loaded from an XML file using the following code, none of my new elements were formatted correctly, they just showed up on one line:

<?php
$dom = DOMDocument::load('file.xml');
$dom->formatOutput = true;
//$dom->add some new elements with child nodes somewhere inside the loaded XML using insertBefore();
$dom->saveXML();
//output: everything looks normal but the new nodes are all on one line.
?>

I found I could pass LIBXML_NOBLANKS to the load method and it would reformat the whole document, including my added stuff:
<?php
$dom = DOMDocument::load('file.xml', LIBXML_NOBLANKS);
$dom->formatOutput = true;
//$dom->add some new elements with child nodes somewhere inside the loaded XML using insertBefore();
$dom->saveXML();
//output: everything looks newly formatted, including new nodes
?>

Hope this helps, took me hours of trial and error to figure this out!
zachatwork at gmail dot com 09-Feb-2010 11:30
Note: The LIBXML_NOXMLDECL constant is defined in this library but is not supported by DOMDocument (yet).

See also: http://bugs.php.net/bug.php?id=47137

<?php

print "PHP_VERSION:      ".PHP_VERSION."\n";
print "LIBXML_VERSION:   ".LIBXML_VERSION."\n";
print "LIBXML_NOXMLDECL: ".LIBXML_NOXMLDECL."\n";

$dom = new DomDocument();
$dom->loadXML("<foo />");

# This should work but doesn't.

print "DOMDocument doesn't honor LIBXML_NOXMLDECL:\n";
print $dom->saveXML(null,LIBXML_NOXMLDECL);

# This works, and will still work after the above is fixed.

print "Forwards compatible workaround:\n";
$lines = explode("\n", $dom->saveXML(null, LIBXML_NOXMLDECL), 2);
if(!preg_match('/^\<\?xml/', $lines[0]))
    print $lines[0];
print $lines[1];

?>

PHP_VERSION:      5.3.1-0.dotdeb.1
LIBXML_VERSION:   20632
LIBXML_NOXMLDECL: 2
DOMDocument doesn't honor LIBXML_NOXMLDECL:
<?xml version="1.0"?>
<foo/>
Forwards compatible workaround:
<foo/>


La clase libXMLError

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

Introducción

Contiene diversa información sobre los errores lanzados por libxml. Los códigos de error son descritos en la » documentación de la API xmlError oficial.

Sinopsis de la Clase

libXMLError {
/* Propiedades */
public int $level ;
public int $code ;
public int $column ;
public string $message ;
public string $file ;
public int $line ;
}

Propiedades

level

La gravedad del error (una de las siguientes constantes: LIBXML_ERR_WARNING, LIBXML_ERR_ERROR o LIBXML_ERR_FATAL)

code

El código del error.

column

La columna donde ocurrió el error.

Nota:

Esta propiedad no está completamente implementada en libxml y por tanto a menudo devuelve 0.

message

El mensaje del error, si es que hay.

file

El nombre del fichero, o vacio si el XML fue cargado desde una cadena.

line

La línea en la que ocurrió el error.

User Contributed Notes

There are no user contributed notes for this page.


Funciones de libxml

Tabla de contenidos

  • libxml_clear_errors — Limpia el buffer de errores de libxml
  • libxml_disable_entity_loader — Deshabilita la capacidad de cargar entidades externas
  • libxml_get_errors — Recupera un array de errores
  • libxml_get_last_error — Recupera el último error de libxml
  • libxml_set_external_entity_loader — Cambia el cargador externo por defecto de entidades
  • libxml_set_streams_context — Configura el contexto de flujo para el próximo documento libxml cargado o escrito
  • libxml_use_internal_errors — Deshabilita errores libxml y permite al usuario extraer información de errores según sea necesario

User Contributed Notes

There are no user contributed notes for this page.


Limpia el buffer de errores de libxml

  • « Funciones de libxml
  • libxml_disable_entity_loader »
  • PHP Manual
  • Funciones de libxml
  • Limpia el buffer de errores de libxml

libxml_clear_errors

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

libxml_clear_errors — Limpia el buffer de errores de libxml

Descripción

libxml_clear_errors ( ) : void

libxml_clear_errors() limpia el buffer de errores de libxml.

Valores devueltos

No devuelve ningún valor.

Ver también

  • libxml_get_errors() - Recupera un array de errores
  • libxml_get_last_error() - Recupera el último error de libxml

User Contributed Notes

There are no user contributed notes for this page.


Deshabilita la capacidad de cargar entidades externas

  • « libxml_clear_errors
  • libxml_get_errors »
  • PHP Manual
  • Funciones de libxml
  • Deshabilita la capacidad de cargar entidades externas

libxml_disable_entity_loader

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

libxml_disable_entity_loader — Deshabilita la capacidad de cargar entidades externas

Descripción

libxml_disable_entity_loader ( bool $disable = true ) : bool

Habilita/deshabilita la capacidad de cargar entidades externas.

Parámetros

disable

Deshabilita (true) o habilita (false) extensiones libxml (tal como DOM, XMLWriter y XMLReader) para cargar entidades externas.

Valores devueltos

Devuelve el valor anterior.

Ver también

  • libxml_use_internal_errors() - Deshabilita errores libxml y permite al usuario extraer información de errores según sea necesario
  • La constante LIBXML_NONET

User Contributed Notes

suconghou at gmail dot com 07-Jan-2021 10:27
In PHP 8.0 and later, PHP uses libxml versions from 2.9.0, libxml_disable_entity_loader is deprecated.
so it is now safe to remove all `libxml_disable_entity_loader` calls on php8

if you want Backwards Compatibility

use this snippet

if (\PHP_VERSION_ID < 80000) {
    libxml_disable_entity_loader(true);
}
vavra at 602 dot cz 04-Jan-2018 09:48
If is called
libxml_disable_entity_loader(true);

, it causes that new SoapClient(.) fails with

SOAP-ERROR: Parsing WSDL: Couldn't load from 'D:\path/dm_operations.wsdl' : failed to load external entity "D:\path/dm_operations.wsdl

because this wsdl imports a xsd as an another external file.
Tested on php 7.1.12, win x64.
brendan at bloodbone dot ws 25-Mar-2014 10:23
This also seems to have an impact on <xsl:import /> statements if this is applied when loading XSLT for the XSLTProcessor class.
phofstetter at sensational dot ch 27-Jan-2014 04:36
Be mindful that this also disables url loading in simplexml_load_file() and likely other libxml based functions that deal with URLs
daschtour at me dot com 25-Dec-2013 11:56
This function was reported to be not thread safe. So this might affect php-scripts on the same server.
simonsimcity 29-Feb-2012 06:23
Using this function you can prevent a vulnerable to Local and Remote File Inclusion attacks.

You'll see it in an example where I load and validate the following string:

<!DOCTYPE scan [<!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource=/etc/passwd">]>
<scan>&test;</scan>

One way to prevent that the file in given back is to set this value to 0.
Please take a closer look at the release of symfony 2.0.11


Recupera un array de errores

  • « libxml_disable_entity_loader
  • libxml_get_last_error »
  • PHP Manual
  • Funciones de libxml
  • Recupera un array de errores

libxml_get_errors

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

libxml_get_errors — Recupera un array de errores

Descripción

libxml_get_errors ( ) : array

Recupera un array de errores.

Valores devueltos

Recupera un array con objetos de tipo LibXMLError si hay errores en el buffer, o un array vacío en caso contrario.

Ejemplos

Ejemplo #1 Ejemplo de libxml_get_errors()

Este ejemplo demuestra cómo contruir un gestor de errores libxml simple.

<?php

libxml_use_internal_errors(true);

$xmlstr = <<< XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <titles>PHP: Detrás del analizador sintáctico</title>
 </movie>
</movies>
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if (!$doc) {
    $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";
}

?>

El resultado del ejemplo sería:

  <titles>PHP: Detrás del analizador sintáctico</title>
----------------------------------------------^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46

--------------------------------------------

Ver también

  • libxml_get_last_error() - Recupera el último error de libxml
  • libxml_clear_errors() - Limpia el buffer de errores de 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)


Recupera el último error de libxml

  • « libxml_get_errors
  • libxml_set_external_entity_loader »
  • PHP Manual
  • Funciones de libxml
  • Recupera el último error de libxml

libxml_get_last_error

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

libxml_get_last_error — Recupera el último error de libxml

Descripción

libxml_get_last_error ( ) : LibXMLError

Recupera el último error de libxml.

Valores devueltos

Devuelve un objeto de tipo LibXMLError si hay algún error en el buffer, o false en caso contrario.

Ver también

  • libxml_get_errors() - Recupera un array de errores
  • libxml_clear_errors() - Limpia el buffer de errores de libxml

User Contributed Notes

There are no user contributed notes for this page.


Cambia el cargador externo por defecto de entidades

  • « libxml_get_last_error
  • libxml_set_streams_context »
  • PHP Manual
  • Funciones de libxml
  • Cambia el cargador externo por defecto de entidades

libxml_set_external_entity_loader

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

libxml_set_external_entity_loader — Cambia el cargador externo por defecto de entidades

Descripción

libxml_set_external_entity_loader ( callable $resolver_function ) : bool

Cambia el cargador externo por defecto de entidades.

Parámetros

resolver_function

Un callable que acepte tres argumentos. Dos strings: una id pública y una id de sistema, y un contexto (un array con cuatro elementos) como tercer argumento. Este callback debe devolver un resource, una cadena a partir de la cual s epueda abrir un resource, o null.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de 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());
?>

El resultado del ejemplo sería:

string(10) "-//FOO/BAR"
string(25) "http://example.com/foobar"
array(4) {
    ["directory"]    => NULL
    ["intSubName"]   => NULL
    ["extSubURI"]    => NULL
    ["extSubSystem"] => NULL
}
bool(true)

Ver también

  • libxml_disable_entity_loader() - Deshabilita la capacidad de cargar entidades externas

User Contributed Notes

There are no user contributed notes for this page.


Configura el contexto de flujo para el próximo documento libxml cargado o escrito

  • « libxml_set_external_entity_loader
  • libxml_use_internal_errors »
  • PHP Manual
  • Funciones de libxml
  • Configura el contexto de flujo para el próximo documento libxml cargado o escrito

libxml_set_streams_context

(PHP 5, PHP 7, PHP 8)

libxml_set_streams_context — Configura el contexto de flujo para el próximo documento libxml cargado o escrito

Descripción

libxml_set_streams_context ( resource $streams_context ) : void

Configura el contexto de flujo para el próximo documento libxml cargado o escrito.

Parámetros

streams_context

El contexto de flujo de tipo resource (creado con la función stream_context_create())

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Ejemplo de libxml_set_streams_context()

<?php

$opts = array(
    'http' => array(
        'user_agent' => 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// peticiona un archivo a través de HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');

?>

Ver también

  • stream_context_create() - Crear un contexto de flujo

User Contributed Notes

There are no user contributed notes for this page.


Deshabilita errores libxml y permite al usuario extraer información de errores según sea necesario

  • « libxml_set_streams_context
  • SimpleXML »
  • PHP Manual
  • Funciones de libxml
  • Deshabilita errores libxml y permite al usuario extraer información de errores según sea necesario

libxml_use_internal_errors

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

libxml_use_internal_errors — Deshabilita errores libxml y permite al usuario extraer información de errores según sea necesario

Descripción

libxml_use_internal_errors ( bool $use_errors = false ) : bool

libxml_use_internal_errors() permite deshabilitar errores libxml estándares y habilitar el manejo de errores del usuario.

Parámetros

use_errors

Habilita (true) o deshabilita (false) el manejo de errores por parte del usuario. La deshabilitación también borrará cualquier error libxml existente.

Valores devueltos

Esta función devuelve el valor anterior de use_errors.

Ejemplos

Ejemplo #1 Ejemplo de libxml_use_internal_errors()

Este ejemplo demuestra el uso básico de los errores libxml y el valor devuelto por esta función.

<?php

// habilita el manejo de errores del usuario
var_dump(libxml_use_internal_errors(true));

// carga el documento
$doc = new DOMDocument;

if (!$doc->load('file.xml')) {
    foreach (libxml_get_errors() as $error) {
        // Aquí se manejan los errores
    }

    libxml_clear_errors();
}

?>

El resultado del ejemplo sería:

bool(false)

Ver también

  • libxml_clear_errors() - Limpia el buffer de errores de libxml
  • libxml_get_errors() - Recupera un array de errores

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

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Ejemplos
    • Uso básico de SimpleXML
    • Tratar con los errores XML
  • SimpleXMLElement — Clase SimpleXMLElement
    • SimpleXMLElement::addAttribute — Añade un atributo al elemento SimpleXML
    • SimpleXMLElement::addChild — Añade un elemento hijo al nodo XML
    • SimpleXMLElement::asXML — Retorna un string XML correcto basado en un elemento SimpleXML
    • SimpleXMLElement::attributes — Identifica el atributo de un elemento
    • SimpleXMLElement::children — Encuentra los hijos del nodo dado
    • SimpleXMLElement::__construct — Crea un nuevo objeto SimpleXMLElement
    • SimpleXMLElement::count — Cuenta los hijos de un elemento
    • SimpleXMLElement::getDocNamespaces — Devuelve los espacios de nombre declarados en el documento
    • SimpleXMLElement::getName — Retorna el nombre del elemento XML
    • SimpleXMLElement::getNamespaces — Devuelve los espacios de nombre usados en el documento
    • SimpleXMLElement::registerXPathNamespace — Crea un contexto prefijo/ns para la siguiente petición XPath
    • SimpleXMLElement::saveXML — Alias de SimpleXMLElement::asXML
    • SimpleXMLElement::__toString — Returns the string content
    • SimpleXMLElement::xpath — Ejecuta una petición XPath sobre los datos XML
  • SimpleXMLIterator — La clase SimpleXMLIterator
    • SimpleXMLIterator::current — Devuelve el elemento actual
    • SimpleXMLIterator::getChildren — Devuelve los sub elementos de el elemento actual
    • SimpleXMLIterator::hasChildren — Comprueba si el elemento actual tiene sub elementos
    • SimpleXMLIterator::key — Devuelve la clave actual
    • SimpleXMLIterator::next — Mueve al siguiente elemento
    • SimpleXMLIterator::rewind — Rebobina hasta el primer elemento
    • SimpleXMLIterator::valid — Comprueba si el elemento actual es válido
  • Funciones de SimpleXML
    • simplexml_import_dom — Obtiene un objeto SimpleXMLElement de un nodo DOM
    • simplexml_load_file — Interpreta un fichero XML en un objeto
    • simplexml_load_string — Interpreta un string de XML en un objeto

User Contributed Notes

Anonymous 25-Dec-2019 09:10
<?php
function array_to_xml( $array, $xml = null ) {
  if ( is_array( $array ) ) {
    foreach( $array as $key => $value ) {
      if ( is_int( $key ) ) {
        if ( $key == 0 ) {
          $node = $xml;
        } else {
          $parent = $xml->xpath( ".." )[0];
          $node = $parent->addChild( $xml->getName() );
        }
      } else {
        $node = $xml->addChild( $key );
      }
      array_to_xml( $value, $node );
    }
  } else {
    $xml[0] = $array;
  }
}

$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><root></root>" );

array_to_xml( $array, $xml );
echo $xml->asXML();
?>
charles dot a dot dacosta at gmail dot com 15-Nov-2016 09:49
I had to do the following to catch the fact that my simplexml_load_string call was not working right (it was returning empty objects).

$statistik = simplexml_load_string($record,"SimpleXMLElement",LIBXML_NSCLEAN,$ns,TRUE);

    if (($statistik === FALSE) or ($statistik === NULL) or empty($statistik))
    {
        echo "$ctr) STATISTIK ERROR---\n";
        var_dump($statistik);
        echo "\n\n";
        echo "Failed loading XML\n";
        foreach(libxml_get_errors() as $error)
        {
            echo "\n", $error->message;
        }
        die();
    }

before I put the check for "empty()" I was not catching the error.
oleg at mastak dot fi 30-Mar-2016 09:57
Two lines xml2array:

<?php

$xml = simplexml_load_string($xmlstring);
$array = (array) $xml;

?>
Serge 26-Feb-2015 10:58
XML data values should not contain "&" and that need to be replaced by html-entity "&amp;"

You can use this code to replace lonely "&" to "&amp;":

<?php
$sText = preg_replace('#&(?![a-z]{1,6};)#i', '&amp;', $sText);
?>

This will replace just "&" into "&amp;" but dont touches other html-entities like "&nbsp;", "&lt;" etc and, of course, "&amp;".

P.S. In regexp max length is 6 becouse I found that is the maximum length of possible html entity using this code:
<?php
max(array_map('strlen', array_values(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5)))) - 2
?>
minus two is for first "&" and last ";" in an any html entity.
Tim Adam Perez 23-Jan-2014 08:22
XML to Array in a single line:
$array = (array) simplexml_load_string($xml);

Enjoy!
maikel at yuluma dot com 17-Oct-2013 09:02
In reply to  soloman at textgrid dot com,

2 line XML2Array:

$xml = simplexml_load_string($file);
$array = (array)$xml;
dkrnl at yandex dot ru 30-Sep-2013 02:57
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

Usage example: http://github.com/dkrnl/SimpleXMLReader/blob/master/examples/example1.php

<?php

/**
 * Simple XML Reader
 *
 * @license Public Domain
 * @author Dmitry Pyatkov(aka dkrnl) <dkrnl@yandex.ru>
 * @url http://github.com/dkrnl/SimpleXMLReader
 */
class SimpleXMLReader extends XMLReader
{

    /**
     * Callbacks
     *
     * @var array
     */
    protected $callback = array();

    /**
     * Add node callback
     *
     * @param  string   $name
     * @param  callback $callback
     * @param  integer  $nodeType
     * @return SimpleXMLReader
     */
    public function registerCallback($name, $callback, $nodeType = XMLREADER::ELEMENT)
    {
        if (isset($this->callback[$nodeType][$name])) {
            throw new Exception("Already exists callback $name($nodeType).");
        }
        if (!is_callable($callback)) {
            throw new Exception("Already exists parser callback $name($nodeType).");
        }
        $this->callback[$nodeType][$name] = $callback;
        return $this;
    }

    /**
     * Remove node callback
     *
     * @param  string  $name
     * @param  integer $nodeType
     * @return SimpleXMLReader
     */
    public function unRegisterCallback($name, $nodeType = XMLREADER::ELEMENT)
    {
        if (!isset($this->callback[$nodeType][$name])) {
            throw new Exception("Unknow parser callback $name($nodeType).");
        }
        unset($this->callback[$nodeType][$name]);
        return $this;
    }

    /**
     * Run parser
     *
     * @return void
     */
    public function parse()
    {
        if (empty($this->callback)) {
            throw new Exception("Empty parser callback.");
        }
        $continue = true;
        while ($continue && $this->read()) {
            if (isset($this->callback[$this->nodeType][$this->name])) {
                $continue = call_user_func($this->callback[$this->nodeType][$this->name], $this);
            }
        }
    }

    /**
     * Run XPath query on current node
     *
     * @param  string $path
     * @param  string $version
     * @param  string $encoding
     * @return array(SimpleXMLElement)
     */
    public function expandXpath($path, $version = "1.0", $encoding = "UTF-8")
    {
        return $this->expandSimpleXml($version, $encoding)->xpath($path);
    }

    /**
     * Expand current node to string
     *
     * @param  string $version
     * @param  string $encoding
     * @return SimpleXMLElement
     */
    public function expandString($version = "1.0", $encoding = "UTF-8")
    {
        return $this->expandSimpleXml($version, $encoding)->asXML();
    }

    /**
     * Expand current node to SimpleXMLElement
     *
     * @param  string $version
     * @param  string $encoding
     * @param  string $className
     * @return SimpleXMLElement
     */
    public function expandSimpleXml($version = "1.0", $encoding = "UTF-8", $className = null)
    {
        $element = $this->expand();
        $document = new DomDocument($version, $encoding);
        $node = $document->importNode($element, true);
        $document->appendChild($node);
        return simplexml_import_dom($node, $className);
    }

    /**
     * Expand current node to DomDocument
     *
     * @param  string $version
     * @param  string $encoding
     * @return DomDocument
     */
    public function expandDomDocument($version = "1.0", $encoding = "UTF-8")
    {
        $element = $this->expand();
        $document = new DomDocument($version, $encoding);
        $node = $document->importNode($element, true);
        $document->appendChild($node);
        return $document;
    }

}
?>
whyme 28-Dec-2012 09:55
Simple means simple.  If you know the structure and just want the value of a tag:

<?php
$xml = simplexml_load_file($xmlfile);
print $xml->City->Street->Address->HouseColor;
?>

Warning, numbers can come out as strings, empty elements like <HouseColor></HouseColor> come out as array(0)
Laurent Vervisch 24-Jun-2012 10:57
Here is an example of an easy mapping between xml and classes defined by user.

<?php
class XmlClass extends SimpleXMLElement
{
    /**
     * Returns this object as an instance of the given class.
     */
    public function asInstanceOf($class_name)
    {
        // should check that class_name is valid

        return simplexml_import_dom(dom_import_simplexml($this), $class_name);
    }

    public function __call($name, array $arguments)
    {
        echo "magic __call called for method $name on instance of ".get_class()."\n";

        // class could be mapped according $this->getName()
        $class_name = 'Test';

        $instance = $this->asInstanceOf($class_name);
        return call_user_func_array(array($instance, $name), $arguments);
    }
}

class Test extends XmlClass
{
    public function setValue($string)
    {
        $this->{0} = $string;
    }
}

$xml = new XmlClass('<example><test/></example>');
$test = $xml->test->asInstanceOf('Test');
echo get_class($xml->test), "\n";
echo get_class($test), "\n";

$test->setValue('value set directly by instance of Test');
echo (string)$xml->test, "\n";
echo (string)$test, "\n";

$xml->test->setValue('value set by instance of XmlClass and magic __call');
echo (string)$xml->test, "\n";
echo (string)$test, "\n";
?>

XmlClass
Test
value set directly by instance of Test
value set directly by instance of Test
magic __call called for method setValue on instance of XmlClass
value set by instance of XmlClass and magic __call
value set by instance of XmlClass and magic __call
xaviered at gmail dot com 17-May-2012 07:00
Here is a recursive function that will convert a given SimpleXMLElement object into an array, preserving namespaces and attributes.

<?php
function xmlObjToArr($obj) {
        $namespace = $obj->getDocNamespaces(true);
        $namespace[NULL] = NULL;

        $children = array();
        $attributes = array();
        $name = strtolower((string)$obj->getName());

        $text = trim((string)$obj);
        if( strlen($text) <= 0 ) {
            $text = NULL;
        }

        // get info for all namespaces
        if(is_object($obj)) {
            foreach( $namespace as $ns=>$nsUrl ) {
                // atributes
                $objAttributes = $obj->attributes($ns, true);
                foreach( $objAttributes as $attributeName => $attributeValue ) {
                    $attribName = strtolower(trim((string)$attributeName));
                    $attribVal = trim((string)$attributeValue);
                    if (!empty($ns)) {
                        $attribName = $ns . ':' . $attribName;
                    }
                    $attributes[$attribName] = $attribVal;
                }

                // children
                $objChildren = $obj->children($ns, true);
                foreach( $objChildren as $childName=>$child ) {
                    $childName = strtolower((string)$childName);
                    if( !empty($ns) ) {
                        $childName = $ns.':'.$childName;
                    }
                    $children[$childName][] = xmlObjToArr($child);
                }
            }
        }

        return array(
            'name'=>$name,
            'text'=>$text,
            'attributes'=>$attributes,
            'children'=>$children
        );
    }
?>
thedoc8786 at gmail dot com 23-Mar-2012 07:42
FAIL! This function works better than the one I posted below:

<?php
    function toArray($xml) {
        $array = json_decode(json_encode($xml), TRUE);

        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( empty($value) ) $array[$key] = NULL;
            elseif ( is_array($value) ) $array[$key] = toArray($value);
        }

        return $array;
    }
thedoc8786 at gmail dot com 23-Mar-2012 04:19
I know it is over-done, but the following is a super-short example of a XML to Array conversion function (recursive):

<?php
    function toArray(SimpleXMLElement $xml) {
        $array = (array)$xml;

        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( $value instanceof SimpleXMLElement ) {
                $array[$key] = empty($value) ? NULL : toArray($value);
            }
        }
        return $array;
    }
xananax at yelostudio dot com 07-Sep-2011 06:25
None of the XML2Array functions that I found satisfied me completely; Their results did not always fit the project I was working on, and I found none that would account for repeating XML elements (such as
<fields><field/><field/><field/></fields>)
So I rolled out my own; hope it helps someone.
<?php
/**
 * Converts a simpleXML element into an array. Preserves attributes.<br/>
 * You can choose to get your elements either flattened, or stored in a custom
 * index that you define.<br/>
 * For example, for a given element
 * <code>
 * <field name="someName" type="someType"/>
 * </code>
 * <br>
 * if you choose to flatten attributes, you would get:
 * <code>
 * $array['field']['name'] = 'someName';
 * $array['field']['type'] = 'someType';
 * </code>
 * If you choose not to flatten, you get:
 * <code>
 * $array['field']['@attributes']['name'] = 'someName';
 * </code>
 * <br>__________________________________________________________<br>
 * Repeating fields are stored in indexed arrays. so for a markup such as:
 * <code>
 * <parent>
 *     <child>a</child>
 *     <child>b</child>
 *     <child>c</child>
 * ...
 * </code>
 * you array would be:
 * <code>
 * $array['parent']['child'][0] = 'a';
 * $array['parent']['child'][1] = 'b';
 * ...And so on.
 * </code>
 * @param simpleXMLElement    $xml            the XML to convert
 * @param boolean|string    $attributesKey    if you pass TRUE, all values will be
 *                                            stored under an '@attributes' index.
 *                                            Note that you can also pass a string
 *                                            to change the default index.<br/>
 *                                            defaults to null.
 * @param boolean|string    $childrenKey    if you pass TRUE, all values will be
 *                                            stored under an '@children' index.
 *                                            Note that you can also pass a string
 *                                            to change the default index.<br/>
 *                                            defaults to null.
 * @param boolean|string    $valueKey        if you pass TRUE, all values will be
 *                                            stored under an '@values' index. Note
 *                                            that you can also pass a string to
 *                                            change the default index.<br/>
 *                                            defaults to null.
 * @return array the resulting array.
 */
function simpleXMLToArray(SimpleXMLElement $xml,$attributesKey=null,$childrenKey=null,$valueKey=null){

    if($childrenKey && !is_string($childrenKey)){$childrenKey = '@children';}
    if($attributesKey && !is_string($attributesKey)){$attributesKey = '@attributes';}
    if($valueKey && !is_string($valueKey)){$valueKey = '@values';}

    $return = array();
    $name = $xml->getName();
    $_value = trim((string)$xml);
    if(!strlen($_value)){$_value = null;};

    if($_value!==null){
        if($valueKey){$return[$valueKey] = $_value;}
        else{$return = $_value;}
    }

    $children = array();
    $first = true;
    foreach($xml->children() as $elementName => $child){
        $value = simpleXMLToArray($child,$attributesKey, $childrenKey,$valueKey);
        if(isset($children[$elementName])){
            if(is_array($children[$elementName])){
                if($first){
                    $temp = $children[$elementName];
                    unset($children[$elementName]);
                    $children[$elementName][] = $temp;
                    $first=false;
                }
                $children[$elementName][] = $value;
            }else{
                $children[$elementName] = array($children[$elementName],$value);
            }
        }
        else{
            $children[$elementName] = $value;
        }
    }
    if($children){
        if($childrenKey){$return[$childrenKey] = $children;}
        else{$return = array_merge($return,$children);}
    }

    $attributes = array();
    foreach($xml->attributes() as $name=>$value){
        $attributes[$name] = trim($value);
    }
    if($attributes){
        if($attributesKey){$return[$attributesKey] = $attributes;}
        else{$return = array_merge($return, $attributes);}
    }

    return $return;
}
?>
soloman at textgrid dot com 09-Aug-2011 05:06
Three line xml2array:

<?php

$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

?>

Ta da!
streaver91 at gmail dot com 04-May-2011 08:49
The BIGGEST differece between an XML and a PHP array is that in an XML file, the name of elements can be the same even if they are siblings, eg. "<pa><ch /><ch /><ch /></pa>", while in an PHP array, the key of which must be different.

I think the array structure developed by svdmeer can fit for XML, and fits well.

here is an example array converted from an xml file:
array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@text"=>"some text",
)

or if it has childrens, that can be:

array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@items"=>array(
    0=>array(
        "@tag"=>"name","@text"=>"some text"
    )
)

Also, I wrote a function that can change that array back to XML.

<?php
function array2XML($arr,$root) {
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><{$root}></{$root}>");
$f = create_function('$f,$c,$a','
        foreach($a as $v) {
            if(isset($v["@text"])) {
                $ch = $c->addChild($v["@tag"],$v["@text"]);
            } else {
                $ch = $c->addChild($v["@tag"]);
                if(isset($v["@items"])) {
                    $f($f,$ch,$v["@items"]);
                }
            }
            if(isset($v["@attr"])) {
                foreach($v["@attr"] as $attr => $val) {
                    $ch->addAttribute($attr,$val);
                }
            }
        }');
$f($f,$xml,$arr);
return $xml->asXML();
}
?>
phil at dier dot us 19-Jan-2011 11:37
Here's a function I came up with to convert an associative array to XML.  Works for multidimensional arrays as well.

<?php
function assocArrayToXML($root_element_name,$ar)
{
    $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
    $f = create_function('$f,$c,$a','
            foreach($a as $k=>$v) {
                if(is_array($v)) {
                    $ch=$c->addChild($k);
                    $f($f,$ch,$v);
                } else {
                    $c->addChild($k,$v);
                }
            }');
    $f($f,$xml,$ar);
    return $xml->asXML();
}
?>
philipp at strazny dot com 23-Nov-2010 05:33
Here's a quick way to dump the nodeValues from SimpleXML into an array using the path to each nodeValue as key. The paths are compatible with e.g. DOMXPath. I use this when I need to update values externally (i.e. in code that doesn't know about the underlying xml). Then I use DOMXPath to find the node containing the original value and update it.

<?php
function XMLToArrayFlat($xml, &$return, $path='', $root=false)
{
    $children = array();
    if ($xml instanceof SimpleXMLElement) {
        $children = $xml->children();
        if ($root){ // we're at root
            $path .= '/'.$xml->getName();
        }
    }
    if ( count($children) == 0 ){
        $return[$path] = (string)$xml;
        return;
    }
    $seen=array();
    foreach ($children as $child => $value) {
        $childname = ($child instanceof SimpleXMLElement)?$child->getName():$child;
        if ( !isset($seen[$childname])){
            $seen[$childname]=0;
        }
        $seen[$childname]++;
        XMLToArrayFlat($value, $return, $path.'/'.$child.'['.$seen[$childname].']');
    }
}
?>

Use like this:

<?php
$xml = simplexml_load_string(...some xml string...);
$xmlarray = array(); // this will hold the flattened data
XMLToArrayFlat($xml, $xmlarray, '', true);
?>

You can also pull multiple files in one array:

<?php
foreach($files as $file){
    $xml = simplexml_load_file($file);
    XMLToArrayFlat($xml, $xmlarray, $file.':', true);
}
?>
The respective filename/path is thus prefixed to each key.
kristof at viewranger dot com 18-Nov-2010 05:14
If you tried to load an XML file with this, but the CDATA parts were not loaded for some reason, is because you should do it this way:

$xml = simplexml_load_file($this->filename, 'SimpleXMLElement', LIBXML_NOCDATA);

This converts CDATA to String in the returning object.
sherwinterunez at yahoo dot com 01-Sep-2010 11:15
<?php

// Sherwin R. Terunez
//
// This is my own version of XML Object to Array
//

function amstore_xmlobj2array($obj, $level=0) {

    $items = array();

    if(!is_object($obj)) return $items;

    $child = (array)$obj;

    if(sizeof($child)>1) {
        foreach($child as $aa=>$bb) {
            if(is_array($bb)) {
                foreach($bb as $ee=>$ff) {
                    if(!is_object($ff)) {
                        $items[$aa][$ee] = $ff;
                    } else
                    if(get_class($ff)=='SimpleXMLElement') {
                        $items[$aa][$ee] = amstore_xmlobj2array($ff,$level+1);
                    }
                }
            } else
            if(!is_object($bb)) {
                $items[$aa] = $bb;
            } else
            if(get_class($bb)=='SimpleXMLElement') {
                $items[$aa] = amstore_xmlobj2array($bb,$level+1);
            }
        }
    } else
    if(sizeof($child)>0) {
        foreach($child as $aa=>$bb) {
            if(!is_array($bb)&&!is_object($bb)) {
                $items[$aa] = $bb;
            } else
            if(is_object($bb)) {
                $items[$aa] = amstore_xmlobj2array($bb,$level+1);
            } else {
                foreach($bb as $cc=>$dd) {
                    if(!is_object($dd)) {
                        $items[$obj->getName()][$cc] = $dd;
                    } else
                    if(get_class($dd)=='SimpleXMLElement') {
                        $items[$obj->getName()][$cc] = amstore_xmlobj2array($dd,$level+1);
                    }
                }
            }
        }
    }

    return $items;
}

?>
michael dot allen at emp dot shentel dot com 15-Apr-2010 11:06
Here is a very robust SimpleXML parser.  Can be used to load files, strings, or DOM into SimpleXML, or can be used to perform the reverse when handed SimpleXML.

<?php
/**
 * XMLParser Class File
 *
 * This class loads an XML document into a SimpleXMLElement that can
 * be processed by the calling application.  This accepts xml strings,
 * files, and DOM objects.  It can also perform the reverse, converting
 * an SimpleXMLElement back into a string, file, or DOM object.
 */
class XMLParser {
    /**
     * While parsing, parse the supplied XML document.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML document file.
     *
     * @param string $doc the xml document location path
     * @return object
     */
    public static function loadFile($doc) {
        if (file_exists($doc)) {
            return simplexml_load_file($doc);
        } else {
            throw new Exception ("Unable to load the xml file " .
                                 "using: \"$doc\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML string.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML string.
     *
     * @param string $string the xml document string
     * @return object
     */
    public static function loadString($string) {
        if (isset($string)) {
            return simplexml_load_string($string);
        } else {
            throw new Exception ("Unable to load the xml string " .
                                 "using: \"$string\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML DOM node.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML DOM node.
     *
     * @param object $dom the xml DOM node
     * @return object
     */
    public static function loadDOM($dom) {
        if (isset($dom)) {
            return simplexml_import_dom($dom);
        } else {
            throw new Exception ("Unable to load the xml DOM node " .
                                 "using: \"$dom\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the SimpleXMLElement.
     *
     * Sets up a XML file, string, or DOM object based on success of
     * parsing the XML DOM node.
     *
     * @param object $path the xml document location path
     * @param string $type the return type (string, file, dom)
     * @param object $simplexml the simple xml element
     * @return mixed
     */
    public static function loadSXML($simplexml, $type, $path) {
        if (isset($simplexml) && isset($type)) {
        switch ($type) {
            case 'string':
                return $simplexml->asXML();
            break;
            case 'file':
                if (isset($path)) {
                    return $simplexml->asXML($path);
                } else {
                    throw new Exception ("Unable to create the XML file. Path is missing or" .
                                         "is invalid: \"$path\"", E_USER_ERROR);
                }
            break;
            case 'dom':
                return dom_import_simplexml($simplexml);
            break;
        }
        } else {
            throw new Exception ("Unable to load the simple XML element " .
                                 "using: \"$simplexml\"", E_USER_ERROR);
        }
    }
}
?>
emmanuel 17-Feb-2010 10:21
dynamic sql in php using xml:

test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<sql>
    <statement>
        SELECT * FROM USERS
        <call criteria="byId">WHERE id = %d</call>
        <call criteria="byUsername">WHERE username = "%s"</call>;
    </statement>
</sql>

index.php:
<?php
function callMe($param) {
    $search = array('byUsername' => 'dynsql');

    if (isset($search[$param[1]])) {
        return sprintf($param[2], $search[$param[1]]);
    }

    return "";
}

$xml = simplexml_load_file("test.xml");
$string = $xml->statement->asXML();
$string = preg_replace_callback('/<call criteria="(\w+)">(.*?)<\/call>/', 'callMe', $string);
$node = simplexml_load_string($string);
echo $node;
?>

obviously, this example can be improved [in your own code.]
mahmutta at gmail dot com 20-Jan-2010 12:58
while using simple xml and get double or float int value from xml object for using math operations (+ * - / ) some errors happens on the operation, this is because of simple xml returns everythings to objects.
exmple;

<?php

$name = "somestring";
$size = 11.45;
$xml = '
<xml>
 <name>somestring</name>
 <size>11.45</size>
</xml>';

$xmlget = simplexml_load_string($xml)

echo $xml->size*2;    // 20  its false
// ($xml->size is an object (int)11 and  (45) )

// this is true
echo $size*2;            // 22.90
echo (float)$size*2;   // 22.90
?>
antoine dot rabanes at gmail dot com 16-Oct-2009 07:22
if for some reasons you need the string value instead of the simpleXML Object you can cast the return value as a string.

exemple:

<?php
$all_api_call = simplexml_load_file($url);
$all_api = array();
$all_api = $all_api_call->result;
$list_all_api_name = array();
$i = 0;
foreach ($all_api->children() as $funcky_function)
{
    $string_tmp = (string )$funcky_function->function;
    $list_all_api_name[$i++] = $putain;
}
?>

...
walter 12-Jun-2009 07:58
Working fix for the infamous SimpleXML + memcache bug.

Improves code at http://tinyurl.com/bmoon-simplexml to actually work for arbitrary-depth structures.  (Because neither the function nor the json_decode(json_encode($obj)) hack listed there worked for me.)

There's probably some superfluous code in here that could be improved on -- but it works!

<?php
 # convert a structure that may include objects to a pure
 # array-based structure (that can be stored in memcache)
 #  ... includes support for simplexml!
 # (nb: may have problems with infinite recursive structs)
 function enforce_array($obj) {
  $array = (array)$obj;
  if(empty($array)) {
   $array = '';
  }
  else {
   foreach($array as $key=>$value) {
    if(!is_scalar($value)) {
     if(is_a($value,'SimpleXMLElement')) {
      $tmp = memcache_objects_to_array($value);
      if(!is_array($tmp)) {
       $tmp = ''.$value;
      }
      $array[$key] = $tmp;
     }
     else {
      $array[$key] = enforce_array($value);
     }
    }
    else {
     $array[$key] = $value;
    }
   }
  }
  return $array;
 }
?>
mail at kleineedv dot de 28-Apr-2009 12:37
I had a problem with simplexml reading nodes from an xml file. It always return an SimpleXML-Object but not the text inside the node.

Example:
<?xml version="1.0" encoding="UTF-8"?>
<Test>
    <Id>123</Id>
</Test>

Reading this xml into a variable called $xml and then doing the following
<?php
$myId = $xml->Id;
?>
Did not return 123 in $myId, but instead I got a SimpleXMLElement Object.

The solution is simple, when you know it. Use explicit string conversion.
<?php
$myId = (string)$xml->Id;
?>
oscargodson at gmail dot com 25-Jan-2009 03:05
To add to what others have said, you can't directly put a $_GET or $_POST value into a variable then into an attribute using SimpleXML. You must first convert it to an integer.

This will NOT work

<?php
      $page_id = $_GET['id'];
      echo $xml->page[$page_id]
?>

You will get something like:
Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/mysite/index.php on line 10

However, this WILL work and is much simpler then using (string) or other methods.
<?php
   $page_id = intval($_GET['id']);
   echo $xml->page[$page_id]
?>
bxt at die-optimisten dot net 26-Nov-2008 07:47
Addition to QLeap's post:
SimpleXML will return a reference to an object containing the node value and you can't use references in session variables as there is no feasible way to restore a reference to another variable.

This won't work too:
$val=$this->xml->node->attributes()->name;
echo $array[$val]; // will cause a warning because of the wrong index type.

You have to convert/cast to a String first:
echo $array[(string)$val];

This will work as expected, because converting will call the __toString() method. Therefor echo works too:
echo $val; // will display the name
QLeap 18-Nov-2008 02:27
Storing SimpleXMLElement values in $_SESSION does not work. Saving the results as an object or individual elements of the object will result in the dreaded "Warning: session_start() [function.session-start]: Node no longer exists" error.

For example, this does not work:

    $xml  = new SimpleXMLElement($page);
    $country  = $xml->Response->Placemark->AddressDetails->Country->CountryNameCode;
    $_SESSION['country'] = $country;

This will work:

    $_SESSION['country'] = (string) $country;
gwhitescarver at yahoo dot com 11-Sep-2008 01:02
Moving some code from a PHP 5.2.6 / Windows environment to a 5.2.0 / Linux environment, I somehow lost access to a plain text node within a SimpleXML Object.  On a var_dump of $xml_node, a [0] element was shown as the string '12'.  However, $xml_node[0] was evaluating NULL in 5.2.0.  You can see below the code change I made, pulling my data out of the raw XML with a regular expression.  Hope this is useful to someone.

//In some versions of PHP it seems we cannot access the [0] element of a SimpleXML Object.  Doesn't work in 5.2.0:
//$count = $xml_node[0];
//grab the raw XML:
$count = ($xml_node->asXML());
//pull out the number between the closing and opening brace of the xml:
$count = preg_replace('/.*>(\d*)<.*/', '$1', $count);
charlie at blankcanvasstudios dot com 14-Aug-2008 11:21
Optimizing aalaap at gmail dot com's php

<?php
function is_rss($feedxml) {
    @$feed = simplexml_load_string($feedxml);

    return ($feed->channel->item)?true:false;
}

function is_atom($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);
    ($feed->entry):true:false;
}
?>
aalaap at gmail dot com 30-Jun-2008 06:58
Here are two quick and dirty functions that use SimpleXML to detect if a feed xml is RSS or ATOM:

<?php
function is_rss($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);

    if ($feed->channel->item) {
        return true;
    } else {
        return false;
    }
}

function is_atom($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);

    if ($feed->entry) {
        return true;
    } else {
        return false;
    }
}
?>

The functions take in the full text feed (retrieved via cURL, for example) and return a true or a false based on the result.


Introducción

La extensión SimpleXML proporciona un conjunto de herramientas muy simple y fácil de usar para convertir XML a un objeto que pueda ser procesado con selectores de propiedades normales e iteradores de arrays.

User Contributed Notes

There are no user contributed notes for this page.


Requerimientos

Esta extensión requiere la extensión libxml de PHP. Esto significa que también es necesario pasar la opción --enable-libxml, aunque esto se realiza implícitamente debido a que libxml está habilitada de forma predeterminada.

La extensión SimpleXML requiere PHP 5.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

Esta extensión está habilitada de forma predeterminada. Se puede deshabilitar empleando la siguiente opción durante la compilación: --disable-simplexml

Nota: Para versiones anteriores a PHP 5.1.2, es necesario usar --enable-simplexml para activar esta extensión.

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


Ejemplos

Tabla de contenidos

  • Uso básico de SimpleXML
  • Tratar con los errores 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.


Uso básico de SimpleXML

Muchos ejemplos en esta referencia requieren un string XML. En vez de repetir este string en cada ejemplo, se ha puesto en un fichero que se incluye en cada ejemplo. Este fichero se muestra en la siguiente sección de ejemplo. Alternativamente, puede crearse un documento XML y leerlo con simplexml_load_file().

Ejemplo #1 El fichero ejemplo.php a incluir con el string XML

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<peliculas>
 <pelicula>
  <titulo>PHP: Tras el Analilzador</titulo>
  <personajes>
   <personaje>
    <nombre>Srta. Programadora</nombre>
    <actor>Onlivia Actora</actor>
   </personaje>
   <personaje>
    <nombre>Sr. Programador</nombre>
    <actor>El Act&#211;r</actor>
   </personaje>
  </personajes>
  <argumento>
   Así que, este lenguaje. Es como, un lenguaje de programación. ¿O es un
   lenguaje de script? Lo descubrirás en esta intrigante y temible parodia
   de un documental.
  </argumento>
  <grandes-frases>
   <frase>PHP soluciona todos los problemas web</frase>
  </grandes-frases>
  <puntuacion tipo="votos">7</puntuacion>
  <puntuacion tipo="estrellas">5</puntuacion>
 </pelicula>
</peliculas>
XML;
?>

La simplicidad de SimpleXML se ve claramente cuando se extrae un string o un número de un documento XMl básico.

Ejemplo #2 Obtener <argumento>

<?php
include 'ejemplo.php';

$peliculas = new SimpleXMLElement($xmlstr);

echo $peliculas->pelicula[0]->argumento;
?>

El resultado del ejemplo sería:

   Así que, este lenguaje. Es como, un lenguaje de programación. ¿O es un
   lenguaje de script? Lo descubrirás en esta intrigante y temible parodia
   de un documental.

El acceso a elementos dentro de un documento XML que contiene caracteres no permitidos por la convención de nombres de PHP (p.ej., el guión) puede realizarse encapsulando el nombre del elemento dentro de un par de llaves y comillas simples.

Ejemplo #3 Obtener <frase>

<?php
include 'ejemplo.php';

$peliculas = new SimpleXMLElement($xmlstr);

echo $peliculas->pelicula->{'grandes-frases'}->frase;
?>

El resultado del ejemplo sería:

PHP soluciona todos los problemas web

Ejemplo #4 Acceder a elementos no únicos en SimpleXML

Cuando existen múltiples instancias de un elemento como hijos de un único elemento padre, se aplican las técnicas normales de iteración.

<?php
include 'ejemplo.php';

$peliculas = new SimpleXMLElement($xmlstr);

/* Para cada <personaje>, se muestra cada <nombre>. */
foreach ($peliculas->pelicula->personajes->personaje as $personaje) {
   echo $personaje->nombre, ' interpretado por ', $personaje->actor, PHP_EOL;
}

?>

El resultado del ejemplo sería:

Srta. Programadora interpretado por Onlivia Actora
Sr. Programador interpretado por El ActÓr

Nota:

Las propiedades ($peliculas->pelicula en el ejemplo anterior) no son arrays. Son objetos iterables y accesibles.

Ejemplo #5 Utilizar atributos

Hasta aquí, únicamente se ha cubierto el trabajo de leer nombres de elementos y sus valores. SimpleXML puede también acceder a los atributos de los elementos. Para acceder a ellos, se realiza como si fuesen elementos de un array.

<?php
include 'ejemplo.php';

$peliculas = new SimpleXMLElement($xmlstr);

/* Acceder a los nodos <puntuacion> de la primera película.
 * Mostrar la escala de puntuación también. */
foreach ($peliculas->pelicula[0]->puntuacion as $puntuacion) {
    switch((string) $puntuacion['tipo']) { // Obtener los atributos como índices del elemento
    case 'votos':
        echo $puntuacion, ' votos positivos';
        break;
    case 'estrellas':
        echo $puntuacion, ' estrellas';
        break;
    }
}
?>

El resultado del ejemplo sería:

7 votos positivos5 estrellas

Ejemplo #6 Comparar elementos y atributos con texto

Para comparar un elemento o atributo con un string o pasarlo a una función que requiera un string, debe realizarse una conversión a string empleando (string). De lo contrario, PHP trata al elemento como un objeto.

<?php
include 'ejemplo.php';

$peliculas = new SimpleXMLElement($xmlstr);

if ((string) $peliculas->pelicula->titulo == 'PHP: Tras el Analilzador') {
    print 'Mi película favorita.';
}

echo htmlentities((string) $peliculas->pelicula->titulo);
?>

El resultado del ejemplo sería:

Mi película favorita.PHP: Tras el Analilzador

Ejemplo #7 Comparar dos elementos

Dos SimpleXMLElements son considerados distintos incluso cuando ambos apuntan al mismo elemento desde PHP 5.2.0.

<?php
include 'ejemplo.php';

$pelicula1 = new SimpleXMLElement($xmlstr);
$pelicula2 = new SimpleXMLElement($xmlstr);
var_dump($pelicula1 == $pelicula2); // falso desde PHP 5.2.0
?>

El resultado del ejemplo sería:

bool(false)

Ejemplo #8 Utilizar XPath

SimpleXML incorpora soporte para XPath. Para encontrar todos los elementos <personaje>:

<?php
include 'ejemplo.php';

$peliculas = new SimpleXMLElement($xmlstr);

foreach ($peliculas->xpath('//personaje') as $personaje) {
    echo $personaje->nombre . ' interpretado por ' . $personaje->actor, PHP_EOL;
}
?>

'//' actúa como un comodín. Para especificar una ruta absoluta, hay que omitir una de las dos barras.

El resultado del ejemplo sería:

Srta. Programadora interpretado por Onlivia Actora
Sr. Programador interpretado por El ActÓr

Ejemplo #9 Establecer valores

Los datos en SimpleXML no tienen que ser constantes. El objeto permite que se manipulen todos sus elementos.

<?php
include 'ejemplo.php';
$peliculas = new SimpleXMLElement($xmlstr);

$peliculas->pelicula[0]->personajes->personaje[0]->nombre = 'Srta. Programadora';

echo $peliculas->asXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0" standalone="yes"?>
<peliculas>
 <pelicula>
  <titulo>PHP: Tras el Analilzador</titulo>
  <personajes>
   <personaje>
    <nombre>Srta. Programadora</nombre>
    <actor>Onlivia Actora</actor>
   </personaje>
   <personaje>
    <nombre>Sr. Programador</nombre>
    <actor>El Act&#xD3;r</actor>
   </personaje>
  </personajes>
  <argumento>
   Así que, este lenguaje. Es como, un lenguaje de programación. ¿O es un
   lenguaje de script? Lo descubrirás en esta intrigante y temible parodia
   de un documental.
  </argumento>
  <grandes-frases>
   <frase>PHP soluciona todos los problemas web</frase>
  </grandes-frases>
  <puntuacion tipo="votos">7</puntuacion>
  <puntuacion tipo="estrellas">5</puntuacion>
 </pelicula>
</peliculas>
+

Ejemplo #10 Añadir elementos y atributos

Desde PHP 5.1.3, SimpleXML tiene la capacidad de añadir fácilmente hijos y atributos.

<?php
include 'ejemplo.php';
$peliculas = new SimpleXMLElement($xmlstr);

$personaje = $peliculas->pelicula[0]->personajes->addChild('personaje');
$personaje->addChild('nombre', 'Sr. Analizador');
$personaje->addChild('actor', 'John Doe');

$puntuacion = $peliculas->pelicula[0]->addChild('puntuacion', 'Todos los públicos');
$puntuacion->addAttribute('tipo', 'clasificacion');

echo $peliculas->asXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0" standalone="yes"?>
<peliculas>
 <pelicula>
  <titulo>PHP: Tras el Analizador</titulo>
  <personajes>
   <personaje>
    <nombre>Srta. Programadora</nombre>
    <actor>Onlivia Actora</actor>
   </personaje>
   <personaje>
    <nombre>Sr. Programador</nombre>
    <actor>El Actor</actor>
   </personaje>
  <personaje><nombre>Sr. Analizador</nombre><actor>John Doe</actor></personaje></personajes>
  <argumento>
   Así que, este lenguaje. Es como, un lenguaje de programación. ¿O es un
   lenguaje de script? Lo descubrirás en esta intrigante y temible parodia
   de un documental.
  </argumento>
  <grandes-frases>
   <frase>PHP soluciona todos los problemas web</frase>
  </grandes-frases>
  <puntuacion tipo="votos">7</puntuacion>
  <puntuacion tipo="estrellas">5</puntuacion>
  <puntuacion tipo="clasificacion">Todos los públicos</puntuacion>
 </pelicula>
</peliculas>

Ejemplo #11 Interoperatibilidad con DOM

PHP tiene un mecanismo para convertir nodos XML entre los formatos SimpleXML y DOM. Este ejemplo muestra cómo cambiar un elemento DOM a SimpleXML.

<?php
$dom = new DOMDocument;
$dom->loadXML('<libros><libro><titulo>bla</titulo></libro></libros>');
if (!$dom) {
    echo 'Error al analizar el documento');
    exit;
}

$s = simplexml_import_dom($dom);

echo $s->libro[0]->titulo;
?>

El resultado del ejemplo sería:

bla

User Contributed Notes

dianarusu21 at gmail dot com 20-Oct-2017 09:16
Quick start with xml.

//PHP file:
<?php
$xml = simplexml_load_file("simpleXml.xml");

foreach ($xml as $key => $value) {
  foreach ($value as $key => $value) {
    echo $key.": ".$value."</br>";
  }
}
?>

//XML file:
<?xml version="1.0" encoding="UTF-8"?>
<locations>
  <country>
    <name>Romania</name>
    <capital>Bucharest</capital>
    <language>Romanian</language>
  </country>
  <country>
    <name>Frace</name>
    <capital>Paris</capital>
    <language>France</language>
  </country>
  <country>
    <name>Spain</name>
    <capital>Madrid</capital>
    <language>Spanish</language>
  </country>
</locations>

//Output:
// name: Romania
// capital: Bucharest
// language: Romanian
// name: Frace
// capital: Paris
// language: France
// name: Spain
// capital: Madrid
// language: Spanish

NOTE: You don't need to include the xml file in the php file..
Anonymous 22-Aug-2017 12:35
If your xml string contains booleans encoded with "0" and "1", you will run into problems when you cast the element directly to bool:

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<values>
    <truevalue>1</truevalue>
    <falsevalue>0</falsevalue>
</values>
XML;
$values = new SimpleXMLElement($xmlstr);
$truevalue = (bool)$values->truevalue; // true
$falsevalue = (bool)$values->falsevalue; // also true!!!

Instead you need to cast to string or int first:

$truevalue = (bool)(int)$values->truevalue; // true
$falsevalue = (bool)(int)$values->falsevalue; // false
rowan dot collins at gmail dot com 04-Jun-2015 06:58
There is a common "trick" often proposed to convert a SimpleXML object to an array, by running it through json_encode() and then json_decode(). I'd like to explain why this is a bad idea.

Most simply, because the whole point of SimpleXML is to be easier to use and more powerful than a plain array. For instance, you can write <?php $foo->bar->baz['bing'] ?> and it means the same thing as <?php $foo->bar[0]->baz[0]['bing'] ?>, regardless of how many bar or baz elements there are in the XML; and if you write <?php (string)$foo->bar[0]->baz[0] ?> you get all the string content of that node - including CDATA sections - regardless of whether it also has child elements or attributes. You also have access to namespace information, the ability to make simple edits to the XML, and even the ability to "import" into a DOM object, for much more powerful manipulation. All of this is lost by turning the object into an array rather than reading understanding the examples on this page.

Additionally, because it is not designed for this purpose, the conversion to JSON and back will actually lose information in some situations. For instance, any elements or attributes in a namespace will simply be discarded, and any text content will be discarded if an element also has children or attributes. Sometimes, this won't matter, but if you get in the habit of converting everything to arrays, it's going to sting you eventually.

Of course, you could write a smarter conversion, which didn't have these limitations, but at that point, you are getting no value out of SimpleXML at all, and should just use the lower level XML Parser functions, or the XMLReader class, to create your structure. You still won't have the extra convenience functionality of SimpleXML, but that's your loss.
mymymymy at mymymymy dot com 02-Jan-2015 09:41
$children = $xml->children();
var_dump($children[0]["@attributes"]);//"NULL"
var_dump($children[0]);//(2) ["@attributes"]=>array(1) {['x']=> string(1) '2'}

no faithfully (not true)
------
example:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [name] => USA
        )
)

print_r($xml->country->attributes()->name);
show:
 SimpleXMLElement Object
(
    [0] => USA
)

print_r((string)$xml->country->attributes()->name);
show:
USA
RiKdnUA at mail dot ru 02-Dec-2013 09:40
???? ????????? XML-????????? ?????????? ?? UTF-8, ?????????? ????????? ?????? ????????? ????? ????? version='...' ? ????? standalone='...'. ??? ?????????? ????????? XML.

If encoding XML-document differs from UTF-8. Encoding declaration should follow immediately after the version = '...' and before standalone = '...'. This requirement is standard XML.

<?xml version='1.0' encoding='windows-1251' standalone='yes'?>
Ok
<?xml version='1.0' standalone='yes' encoding='windows-1251'?>
<body>??????? ????. Russian language</body>
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in...
eng dot emad_2010 at yahoo dot com 08-Oct-2013 11:46
Example #  DOM Interoperability ??????? ??????
PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML  .
The simplexml_import_dom() function returns a SimpleXMLElement object from a DOM node.
DOM         object

<?php
//create DOM  document $dom that contain XML
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}
//convert DOM document $dom to object $books
$books = simplexml_import_dom($dom);

//access object $books
echo $books->book[0]->title;
?>
jishcem at gmail dot com 12-Mar-2013 07:31
For me it was easier to use arrays than objects,

So, I used this code,

$xml = simplexml_load_file('xml_file.xml');

$json_string = json_encode($xml);

$result_array = json_decode($json_string, TRUE);

Hope it would help someone
gkokmdam at zonnet dot nl 23-Feb-2011 01:54
A quick tip on xpath queries and default namespaces. It looks like the XML-system behind SimpleXML has the same workings as I believe the XML-system .NET uses: when one needs to address something in the default namespace, one will have to declare the namespace using registerXPathNamespace and then use its prefix to address the otherwise in the default namespace living element.

<?php
$string = <<<XML
<?xml version='1.0'?>
<document xmlns="http://www.w3.org/2005/Atom">
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);
$xml->registerXPathNamespace("def", "http://www.w3.org/2005/Atom");

$nodes = $xml->xpath("//def:document/def:title");

?>
kdos 31-Jan-2011 05:32
Using stuff like: is_object($xml->module->admin) to check if there actually is a node called "admin", doesn't seem to work as expected, since simplexml always returns an object- in that case an empty one  - even if a particular node does not exist.
For me good old empty() function seems to work just fine in such cases.

Cheers
Max K. 20-Jun-2010 02:38
From the README file:

SimpleXML is meant to be an easy way to access XML data.

SimpleXML objects follow four basic rules:

1) properties denote element iterators
2) numeric indices denote elements
3) non numeric indices denote attributes
4) string conversion allows to access TEXT data

When iterating properties then the extension always iterates over
all nodes with that element name. Thus method children() must be
called to iterate over subnodes. But also doing the following:
foreach ($obj->node_name as $elem) {
  // do something with $elem
}
always results in iteration of 'node_name' elements. So no further
check is needed to distinguish the number of nodes of that type.

When an elements TEXT data is being accessed through a property
then the result does not include the TEXT data of subelements.

Known issues
============

Due to engine problems it is currently not possible to access
a subelement by index 0: $object->property[0].
ie dot raymond at gmail dot com 01-Apr-2010 03:07
If you need to output valid xml in your response, don't forget to set your header content type to xml in addition to echoing out the result of asXML():

<?php

$xml=simplexml_load_file('...');
...
...xml stuff
...

//output xml in your response:
header('Content-Type: text/xml');
echo $xml->asXML();
?>
php at keith tyler dot com 23-Dec-2009 12:57
[Editor's Note: The SimpleXMLIterator class, however, does implement these methods.]

While SimpleXMLElement claims to be iterable, it does not seem to implement the standard Iterator interface functions like ::next and ::reset properly. Therefore while foreach() works, functions like next(), current(), or each() don't seem to work as you would expect -- the pointer never seems to move or keeps getting reset.
bjorn at xQmail dot eu 31-Aug-2009 07:48
If you're not sure the XML will be valid you'd better use:

<?php
$xmlObject = simplexml_load_string($xml);
// or
$xmlObject = simplexml_load_file(xml);
?>

Both of these return a SimpleXMLElement Object or a libXMLError Object.
radams at circlepix com 24-Apr-2009 10:52
To test whether an element exists:

<?php

    $xml = <<<EOT
<?xml version='1.0' standalone='yes'?>
<root>
    <test1></test1>
    <test2 />
    <test4> </test4>
</root>
EOT;

    $xmlDoc = new SimpleXMLElement($xml);

echo "Test1: \n";
var_dump($xmlDoc->test1);
echo "\n(" . (bool)$xmlDoc->test1 . ")";
echo "\n\n";

echo "Test2: \n";
var_dump($xmlDoc->test2);
echo "\n(" . (bool)$xmlDoc->test2 . ")";
echo "\n\n";

echo "Test3: \n";
var_dump($xmlDoc->test3);
echo "\n(" . (bool)$xmlDoc->test3 . ")";
echo "\n\n";

echo "Test4: \n";
var_dump($xmlDoc->test4);
echo "\n(" . (bool)$xmlDoc->test4 . ")";
echo "\n\n";

?>

The var_dumps for test1, test2, and test3 are identical, but the (bool) test gives a '1' for test1 and test2, and a '' for test3.


Tratar con los errores XML

Tratar con los errores XML cuando se cargan documentos es una tarea muy sencilla. Utilizando la funcionalidad de libxml es posible suprimir todos los errores XML cuando se carga un documento para luego recorrerlos.

El objeto libXMLError, retornado por libxml_get_errors(), contiene varias propiedades, incluyendo el mensaje, línea y columna (posición) del error.

Ejemplo #1 Cargar un string XML erróneo

<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><roto><xml></roto>");
if ($sxe === false) {
    echo "Error cargando XML\n";
    foreach(libxml_get_errors() as $error) {
        echo "\t", $error->message;
    }
}
?>

El resultado del ejemplo sería:

Error cargando 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

Ver también

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


Clase SimpleXMLElement

(PHP 5, PHP 7, PHP 8)

Introducción

Representa un elemento en un documento XML.

Sinopsis de la Clase

SimpleXMLElement {
/* Métodos */
final public __construct ( string $data , int $options = 0 , bool $data_is_url = false , string $ns = "" , bool $is_prefix = false )
public addAttribute ( string $name , string $value = ? , string $namespace = ? ) : void
public addChild ( string $name , string $value = ? , string $namespace = ? ) : SimpleXMLElement
public asXML ( string $filename = ? ) : mixed
public attributes ( string $ns = null , bool $is_prefix = false ) : SimpleXMLElement
public children ( string $ns = ? , bool $is_prefix = false ) : SimpleXMLElement
public count ( ) : int
public getDocNamespaces ( bool $recursive = false , bool $from_root = true ) : array
public getName ( ) : string
public getNamespaces ( bool $recursive = false ) : array
public registerXPathNamespace ( string $prefix , string $ns ) : bool
public __toString ( ) : string
public xpath ( string $path ) : array
}

Tabla de contenidos

  • SimpleXMLElement::addAttribute — Añade un atributo al elemento SimpleXML
  • SimpleXMLElement::addChild — Añade un elemento hijo al nodo XML
  • SimpleXMLElement::asXML — Retorna un string XML correcto basado en un elemento SimpleXML
  • SimpleXMLElement::attributes — Identifica el atributo de un elemento
  • SimpleXMLElement::children — Encuentra los hijos del nodo dado
  • SimpleXMLElement::__construct — Crea un nuevo objeto SimpleXMLElement
  • SimpleXMLElement::count — Cuenta los hijos de un elemento
  • SimpleXMLElement::getDocNamespaces — Devuelve los espacios de nombre declarados en el documento
  • SimpleXMLElement::getName — Retorna el nombre del elemento XML
  • SimpleXMLElement::getNamespaces — Devuelve los espacios de nombre usados en el documento
  • SimpleXMLElement::registerXPathNamespace — Crea un contexto prefijo/ns para la siguiente petición XPath
  • SimpleXMLElement::saveXML — Alias de SimpleXMLElement::asXML
  • SimpleXMLElement::__toString — Returns the string content
  • SimpleXMLElement::xpath — Ejecuta una petición XPath sobre los datos XML

User Contributed Notes

Patanjali 15-Oct-2020 02:20
Further to rmirabelle's comment, to compare two SimpleXML elements, do the comparison between the objects returned by the dom_import_simplexml function, as per:

<?php
if(dom_import_simplexml($simplexml_element_1)===dom_import_simplexml($simplexml_element_2)){
  ...
 }
?>

You must ensure that both are SimpleXML elements before conversion to DOM objects.
guilhermeasn at yahoo dot com dot br 15-Jan-2020 08:09
Class with a method to transform array or object to XML:

class MakeXML {

    public static function array_obj_to_xml($data, \SimpleXMLElement &$xmlObj) {
        foreach((array) $data as $key => $value) {
            if(is_numeric($key)) {
                $key = "n" . $key;
            }
            if(is_array($value) or is_object($value)) {
                $subnode = $xmlObj->addChild($key);
                self::array_obj_to_xml($value, $subnode);
            } else {
                $xmlObj->addChild($key, htmlspecialchars($value));
            }
        }
    }

}

Example:

$object = new \stdClass();
$object->example = "Try this class";

$objxml = new \SimpleXMLElement('<API/>');
MakeXML::array_obj_to_xml($objxml, $objxml);
echo $objxml->asXML();
Budu 13-May-2018 07:17
public function crearXml(){
        $pruebaXml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<Root></Root>
XML;
$example = new SimpleXMLElement($pruebaXml); //Crea un nuevo objeto SimpleXMLElement
        $example->addAttribute('id', '1');//Añade un elemento hijo al nodo XML

        while( $nodo = $this->iteraciones->iterate()){
            $nodos = $example->addChild('Nodo');
            $nodos->addAttribute('id',$nodo->getId());
            $acierto = $nodos->addChild('nuevoHijo', $nodo->getX());
        }
        $miFichero = $example->asXML();//Retorna un string XML correcto basado en un elemento SimpleXML
        $miArchivo = fopen("xml/example.xml", "w+");//Abre un fichero o un URL
        fwrite($miArchivo, $miFichero);//Escritura archivo
    }
CameronXie 11-Dec-2017 10:48
Map xml to array (with attributes)

<?php declare(strict_types=1);

/**
 * @param SimpleXMLElement $xml
 * @return array
 */
function xmlToArray(SimpleXMLElement $xml): array
{
    $parser = function (SimpleXMLElement $xml, array $collection = []) use (&$parser) {
        $nodes = $xml->children();
        $attributes = $xml->attributes();

        if (0 !== count($attributes)) {
            foreach ($attributes as $attrName => $attrValue) {
                $collection['attributes'][$attrName] = strval($attrValue);
            }
        }

        if (0 === $nodes->count()) {
            $collection['value'] = strval($xml);
            return $collection;
        }

        foreach ($nodes as $nodeName => $nodeValue) {
            if (count($nodeValue->xpath('../' . $nodeName)) < 2) {
                $collection[$nodeName] = $parser($nodeValue);
                continue;
            }

            $collection[$nodeName][] = $parser($nodeValue);
        }

        return $collection;
    };

    return [
        $xml->getName() => $parser($xml)
    ];
}
kurtbr at gmail dot com 31-May-2017 02:58
Here is a helper class to convert a PHP array to XML
You would call it doing the following:

<?php
$xml = new Xml();
$xml-> generateXmlFromArray($array, 'entities', 'entity');
?>

<?php
class Xml
{
    public function getXmlFromArray($value, \SimpleXMLElement &$xmlElement, $entity, $starting = null)
    {

        $handleValue = function($value){
            if(is_string($value)){
                $value = htmlspecialchars($value);
            }
            return $value;
        };
        $addChild = function($name, $value, &$subNode = null)use(&$xmlElement, $handleValue, $entity){
            if(is_array($value)){
                if(!$subNode instanceof \SimpleXMLElement){
                    $currentKey = key($value);
                    $initialValue = null;
                    if(is_numeric($currentKey)){
                        if(!is_array($value[$currentKey])){
                            $initialValue = $value[$currentKey];
                            unset($value[$currentKey]);
                        }
                    }
                    $subNode = $xmlElement->addChild($name, $initialValue);
                }
                $this->getXmlFromArray($handleValue($value), $subNode, $name);
            } else {
                $xmlElement->addChild($name, $handleValue($value));
            }
        };

        if(is_array($value))
        {
            if(is_numeric(key($value))){
                $setSubNodePrimitiveValue = function($value)use(&$xmlElement, $entity, $handleValue){
                    $value = $handleValue($value);
                    $children = $xmlElement->children();
                    $children[] = $value;
                };
                foreach ($value as $item)
                {
                    if(!is_array($item)){
                        $setSubNodePrimitiveValue($item);
                    } else {
                        if($starting === true){
                            $addChild($entity, $item);
                        } else {
                            $addChild($entity, $item, $xmlElement);
                        }
                    }
                }
            } else {
                foreach ($value as $subEntity => $subEntityItem)
                {
                    $addChild($subEntity, $subEntityItem);
                }
            }
        } else {
            $xmlElement->addChild($entity, $handleValue($value));
        }
    }

    /**
     * @param array $array
     * @param string $openingTag
     * @param string $entity
     * @param string $nameSpace
     * @param bool $isPrefixed
     * @return \SimpleXMLElement
     */
    public function generateXmlFromArray(array $array, string $openingTag, string $entity, $nameSpace = '', $isPrefixed = false)
    {
        $xmlString = '<'.$openingTag.'></'.$openingTag.'>';
        $xml = new \SimpleXMLElement($xmlString, LIBXML_NOERROR, false, $nameSpace, $isPrefixed);
        $this->getXmlFromArray($array, $xml, $entity, true);
        return $xml;
    }

    /**
     * @param string $xml
     * @return bool
     */
    public function validateXml(string $xml)
    {
        $dom = new \DOMDocument();
        $dom->loadXML($xml);
        return $dom->validate();
    }

    public function loadXmlPathAsArray(string $xmlPath)
    {
        $xml   = simplexml_load_file($xmlPath);
        $array = json_decode(json_encode($xml), TRUE);
        return (array)$array;
    }

    /**
     * @param string $xmlString
     * @return array
     */
    public function loadXmlStringAsArray(string $xmlString)
    {
        $array = (array) @simplexml_load_string($xmlString);
        if(!$array){
            $array = (array) @json_decode($xmlString, true);
        } else{
            $array = (array)@json_decode(json_encode($array), true);
        }
        return $array;
    }

    /**
     * @param string $xmlString
     * @return \SimpleXMLElement
     */
    public function loadXmlString(string $xmlString)
    {
        return @simplexml_load_string($xmlString);
    }
}
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:54
See previous two parts to get better understanding of how these tricks works. Example shown here refers to part two. (Sorry, length limitation)

3. Tricks
<?php
        // The real profit is in combination of property and array accesses and unset($someNode->{0}) trick -
        // it allows you to remove whatever node you want:
        unset($rootNode->{'div'}[2]);   // remove node with * mark (text*)

        // Another trick is removing child node using child node object
        $newChildNode = $rootNode->addChild('div','text**');    // Create
        unset($newChildNode->{0});      // Remove, node removed from parent object too!

        echo "--2--\n".$rootNode->asXML();
        /*
        <xml_root>complex node
                <type_one>renewed node 1</type_one>
                <type_two>node 3</type_two>
                <type_one>node 2</type_one>
                <div>text</div>
                <div>text</div>
                <div>text</div>
        </xml_root>
        */
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:48
How to view, edit and remove elements.
Speaking in terms of CRUD style, there is no methods to read, edit and remove nodes. But it is possible.

2. How child nodes works (understanding)
<?php
        echo "Exercise 2 \n";

        $rootNode = new SimpleXMLElement('<xml_root>complex node</xml_root>');  // Create root node
        $childNode1 = $rootNode->addChild('type_one','node 1');                 // Create child node 1 with name 'type_one'
        $childNode2 = new SimpleXMLElement('<type_one>node 2</type_one>');      // Create child node 2 with name 'type_one'
        $childNode3 = new SimpleXMLElement('<type_two>node 3</type_two>');      // Create child node 3 with name 'type_two' (different!)
        // Now $rootNode has only one children because other child nodes was created separately
        // Lets paste child node to root node
        echo $childNode1;

        $rootNode->{'type_one'} = $childNode2;      // Note that the property name is 'type_one'
        $rootNode->{'type_two'} = $childNode3;      // Note that the property name is 'type_two'
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            string(6) "node 2"
            ["type_two"]=>
            string(6) "node 3"
        }
        */
        // We see that "node 1" disappeared, that's because assigning one node to some property of another in not a magic.
        // To be clear, the real calls looks like:
        $rootNode->{'type_one'}[0] = (string) $childNode2;
        $rootNode->{'type_two'}[0] = (string) $childNode3;
        // Explanation:
        // A: (string)
        // It means that you can't assign node itself, only its string representation because assigned node will be casted to string anyway.
        // It also means that tag name of assigned node doesn't matter - its name will be whatever name you specified in {} braces.
        // B: [0]
        // The array access operator ([0]) means that each tag name (type_one and type_two) has its own collection with integer indexes.
        // If you want to add another tag with same name, you should increment index:
        $rootNode->{'type_one'}[1] = $childNode2;
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            array(2) {
                [0]=>
                string(6) "node 2"
                [1]=>
                string(6) "node 2"
            }
            ["type_two"]=>
            string(6) "node 3"
        }
        */

        // Note 1. The value of $childNode1 has been changed to "node 1" - that's because the child node, returned from addChild() method
        // is referenced with parent node. If you change its content in one side - it changes in other side too:
        $childNode1->{0} = 'renewed node 1';
        // But it won't happen with $childNode2 - it is single and has no reference with parent node:
        $childNode2->{0} = 'renewed node 2';
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            array(2) {
                [0]=>
                string(14) "renewed node 1"
                [1]=>
                string(6) "node 2"
            }
            ["type_two"]=>
            string(6) "node 3"
        }
        */

        // Note 2. When you added child nodes, the parent node's string content is still alive, var_dump doesn't show it,
        // but you can see through echoing XML:
        echo "--1--\n".$rootNode->asXML();
        /*
        <xml_root>complex node <--------- here!
                <type_one>renewed node 1</type_one>
                <type_two>node 3</type_two>
                <type_one>node 2</type_one>
        </xml_root>
        */
        // See 'complex node'? Bad news that you can't change string content anymore, if we try to call `$rootNode->{0} = 'something'` -
        // it overrides all content - both string and child nodes! I don't know how to write to string content only in that case.
        // But still you can read string content and remove entire node as described above.

        // So the following statements gives same result, except $result variable value:
        $someNode = new SimpleXMLElement('<div>text</div>');
        $result = $rootNode->addChild('div','text');                    // $result is SimpleXMLElement
        $result = $rootNode->addChild($someNode->getName(),$someNode);  // $result is SimpleXMLElement
        $result = $rootNode->{'div'}[] = 'text*';                       // $result is string 'text*'
        $result = $rootNode->{$someNode->getName()}[] = $someNode;      // $result is string 'text'
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:45
How to view, edit and remove elements.
Speaking in terms of CRUD style, there is no methods to read, edit and remove nodes. But it is possible.

1. How to work with single node and its value (basics)
<?php
        echo "Exercise 1 \n";
        // Create
        $someNode = new SimpleXMLElement('<xml_root>simple node</xml_root>');
        // Read
        echo $someNode->{0} ."\n";      // Echoes "simple node"
        echo $someNode ."\n";           // Echoes "simple node", might be used for read case too
        // Edit
        $someNode->{0} = 'new value';
        echo $someNode->{0} ."\n";      // Echoes "new value", value is changed!
        // Remove
        unset($someNode->{0});

        // Don't touch this node anymore otherwise it will throw a warning:
        // "Warning:  SimpleXMLElement::asXML(): Node no longer exists in <...> on line <...>"
        // echo $someNode ."\n";      // Throws the warning

        // Recap: property access to zero property ($someNode->{0}) is the way to read and edit string content of the node AND
        // to remove the node itself
?>
frame at dynamiccreated dot de 14-Jun-2013 01:36
Important note I miss here in the documentation:

SimpleXML supports Array/Iteration-Methods. Therefore it is possible to

add attributes
edit attributes
remove attributes

add nodes
edit nodes
remove nodes

This is the reason why SimpleXML provides only add-methods not deleting- or editing-methods. We also need this methods because SimpleXML acts as a normal class and
new member will not converted to a new node.

Deleting a node seems not to be possible within a foreach-loop. The reason is simple. To do that we need a valid key, but the Iterator only gives us a "understandable feedback" on which node we are working on: the tag name.

So this will not work:

<?php
foreach($doc->seg as $key => $seg)
{
    if((string)$seg['id'] === 'whatever')
    {
        unset($seg); // only clears local copy
        unset($seg[$key]); // wrong index "seg"
    }
}
?>

But this, eg. will work:
<?php
unset($doc->seg[2]);
?>

In case of doubt always do a print_r/var_dump(). It nicely shows the real linked indexes.
Yukull 15-Feb-2013 01:59
xml to object conversion function :
<?php
/**
    @param:
        $xml: SimpleXMLElement
        $force: set to true to always create 'text', 'attribute', and 'children' even if empty
    @return
        object with attributs:
            (string) name: XML tag name
            (string) text: text content of the attribut name
            (array) attributes: array witch keys are attribute key and values are attribute value
            (array) children: array of objects made with xml2obj() on each child
**/
function xml2obj($xml,$force = false){

    $obj = new StdClass();

    $obj->name = $xml->getName();

    $text = trim((string)$xml);
    $attributes = array();
    $children = array();

    foreach($xml->attributes() as $k => $v){
        $attributes[$k]  = (string)$v;
    }

    foreach($xml->children() as $k => $v){
        $children[] = xml2obj($v,$force);
    }

    if($force or $text !== '')
        $obj->text = $text;

    if($force or count($attributes) > 0)
        $obj->attributes = $attributes;

    if($force or count($children) > 0)
        $obj->children = $children;

    return $obj;
}
?>
heaver 31-May-2012 07:33
XML to JSON conversion without '@attributes'
<?php
function XML2JSON($xml) {

        function normalizeSimpleXML($obj, &$result) {
            $data = $obj;
            if (is_object($data)) {
                $data = get_object_vars($data);
            }
            if (is_array($data)) {
                foreach ($data as $key => $value) {
                    $res = null;
                    normalizeSimpleXML($value, $res);
                    if (($key == '@attributes') && ($key)) {
                        $result = $res;
                    } else {
                        $result[$key] = $res;
                    }
                }
            } else {
                $result = $data;
            }
        }
        normalizeSimpleXML(simplexml_load_string($xml), $result);
        return json_encode($result);
    }
?>
demian dot katz at villanova dot edu 29-Mar-2012 05:50
Here is a more namespace-aware version of the earlier function for attaching one SimpleXMLElement to another.  I'm sure it could still be further improved (right now it generates some redundant xmlns definitions), but it seems to be working well enough for my purposes so far.

function SimpleXMLElement_append($parent, $child)
{
    // get all namespaces for document
    $namespaces = $child->getNamespaces(true);

    // check if there is a default namespace for the current node
    $currentNs = $child->getNamespaces();
    $defaultNs = count($currentNs) > 0 ? current($currentNs) : null;
    $prefix = (count($currentNs) > 0) ? current(array_keys($currentNs)) : '';
    $childName = strlen($prefix) > 1
        ? $prefix . ':' . $child->getName() : $child->getName();

    // check if the value is string value / data
    if (trim((string) $child) == '') {
        $element = $parent->addChild($childName, null, $defaultNs);
    } else {
        $element = $parent->addChild(
            $childName, htmlspecialchars((string)$child), $defaultNs
        );
    }

    foreach ($child->attributes() as $attKey => $attValue) {
        $element->addAttribute($attKey, $attValue);
    }
    foreach ($namespaces as $nskey => $nsurl) {
        foreach ($child->attributes($nsurl) as $attKey => $attValue) {
            $element->addAttribute($nskey . ':' . $attKey, $attValue, $nsurl);
        }
    }

    // add children -- try with namespaces first, but default to all children
    // if no namespaced children are found.
    $children = 0;
    foreach ($namespaces as $nskey => $nsurl) {
        foreach ($child->children($nsurl) as $currChild) {
            SimpleXMLElement_append($element, $currChild);
            $children++;
        }
    }
    if ($children == 0) {
        foreach ($child->children() as $currChild) {
            SimpleXMLElement_append($element, $currChild);
        }
    }
}
saganmarketing.com 12-Mar-2012 12:27
Parsing an invalid XML string through SimpleXML causes the script to crash completely (usually) therefore it is best to make sure the XML is valid before parsing with something like this:

// Must be tested with ===, as in if(isXML($xml) === true){}
// Returns the error message on improper XML
function isXML($xml){
    libxml_use_internal_errors(true);

    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->loadXML($xml);

    $errors = libxml_get_errors();

    if(empty($errors)){
        return true;
    }

    $error = $errors[0];
    if($error->level < 3){
        return true;
    }

    $explodedxml = explode("r", $xml);
    $badxml = $explodedxml[($error->line)-1];

    $message = $error->message . ' at line ' . $error->line . '. Bad XML: ' . htmlentities($badxml);
    return $message;
}
Anonymous 14-Nov-2011 12:34
Warning to anyone trying to parse XML with a key name that includes a hyphen ie.)
<subscribe>
    <callback-url>example url</callback-url>
</subscribe>

In order to access the callback-url you will need to do something like the following:
<?php
$xml = simplexml_load_string($input);
$callback = $xml->{"callback-url"};
?>
If you attempt to do it without the curly braces and quotes you will find out that you are returned a 0 instead of what you want.
juanfhj at gmail dot spam dot me dot not dot com 13-Aug-2011 11:01
To access the underlying element as a string, it's necessary to make the cast $x = (string)$my_xml_element.
dans at dansheps dot com 22-Apr-2011 12:06
I created a little function to parse the simple XML into a structure which is easier to iterate(I believe anyways) than the simpleXML node structure.

<?php
function parseSimpleXML($xmldata)
    {
        $childNames = array();
        $children = array();

        if( $xmldata->count() !== 0 )
        {
            foreach( $xmldata->children() AS $child )
            {
                $name = $child->getName();

                if( !isset($childNames[$name]) )
                {
                    $childNames[$name] = 0;
                }

                $childNames[$name]++;
                $children[$name][] = $this->parseSimpleXML($child);
            }
        }

        $returndata = new XMLNode();
        if( $xmldata->attributes()->count() > 0 )
        {
            $returndata->{'@attributes'} = new XMLAttribute();
            foreach( $xmldata->attributes() AS $name => $attrib )
            {
                $returndata->{'@attributes'}->{$name} = (string)$attrib;
            }
        }

        if( count($childNames) > 0 )
        {
            foreach( $childNames AS $name => $count )
            {
                if( $count === 1 )
                {
                    $returndata->{$name} = $children[$name][0];
                }
                else
                {
                    $returndata->{$name} = new XMLMultiNode();
                    $counter = 0;
                    foreach( $children[$name] AS $data )
                    {
                        $returndata->{$name}->{$counter} = $data;
                        $counter++;
                    }
                }
            }
        }
        else
        {
            if( (string)$xmldata !== '' )
            {
                $returndata->{'@innerXML'} = (string)$xmldata;
            }
        }
        return $returndata;
    }
?>
ms dot n at 163 dot com 11-Feb-2011 10:50
Adds a new function for SimpleXMLElement class, in order to output HTML code.

<?php
class CeiXML extends SimpleXMLElement{
public function asHTML(){
$ele=dom_import_simplexml($this);
$dom = new DOMDocument('1.0', 'utf-8');
$element=$dom->importNode($ele,true);
$dom->appendChild($element);
return $dom->saveHTML();
}
}
?>
Pavel Musil pavel dot musil at gmail dot com 10-Feb-2011 03:18
Simple recursive function to append XML object into SimpleXMLElement node:

<?php
// root: parent element - SimpleXMLElement instance
// append: XML object from simplexml_load_string

function xml_join($root, $append) {
    if ($append) {
        if (strlen(trim((string) $append))==0) {
            $xml = $root->addChild($append->getName());
            foreach($append->children() as $child) {
                xml_join($xml, $child);
            }
        } else {
            $xml = $root->addChild($append->getName(), (string) $append);
        }
        foreach($append->attributes() as $n => $v) {
            $xml->addAttribute($n, $v);
        }
    }
}

$xml_append = simplexml_load_string('<data><items><item id="1">value</item></items></data>');
$xml_root = new SimpleXMLElement('<result></result>');

$cxml = $xml_root->addChild('clone');
xml_join($cxml, $xml_append->items->item[0]);

print $xml_root->asXML();
?>

Result:
<?xml version="1.0"?>
<result>
    <clone>
        <item id="1">
            value
        </item>
    </clone>
</result>
rmirabelle 08-Nov-2010 09:42
To further previous comments and drive the point home:

What makes SimpleXMLElement tricky to work with is that it feels and behaves like an object, but is actually a system RESOURCE,  (specifically a libxml resource).

That's why you can't store a SimpleXMLElement to $_SESSION or perform straight comparison operations on node values without first casting them to some type of object.  $_SESSION expects to store 'an object' and comparison operators expect to compare 2 'objects' and SimpleXMLElements are not objects.

When you echo or print a node's value, PHP converts the value (a resource) into a string object for you.  It's a time saver for sure, but can fool you into thinking that your SimpleXMLElement is an object.

Hope this helps clarify
joshduck at gmail dot com 28-Sep-2010 05:00
You should cast elements to a float (or even string) if you plan on using them in addition, multiplication, etc. If you don't then PHP will incorrectly treat the node values as an integer.

<?php
$obj = new SimpleXMLElement('<root>
    <a>1.9</a>
    <b>1.9</b>
</root>');

var_dump($obj->a + $obj->b);
var_dump((float)$obj->a + (float)$obj->b);
var_dump((string)$obj->a + (string)$obj->b);
?>

The first line gives: int(2)
The second and third give the expected result: float(3.8)
francs at seznam dot cz 23-Sep-2010 05:28
Be aware when you trying to cast some attribute to boolean.

(boolean)$xml->attributes()->someAtt;

returns TRUE if attribute is array([0] => 0);

use (boolean)(int) instead.
kweij at lsg dot nl 26-Jul-2010 04:47
I'm using SimpleXML for, ofcourse, it's simplicity, however I did wanted to manipulate the xml and combining one SimpleXMLElement with any other, so I wrote this function to add a SimpleXMLElement-child.

<?php
function SimpleXMLElement_append($key, $value) {
    // check class
    if ((get_class($key) == 'SimpleXMLElement') && (get_class($value) == 'SimpleXMLElement')) {
        // check if the value is string value / data
        if (trim((string) $value) == '') {
            // add element and attributes
            $element = $key->addChild($value->getName());
            foreach ($value->attributes() as $attKey => $attValue) {
                $element->addAttribute($attKey, $attValue);
            }
            // add children
            foreach ($value->children() as $child) {
                SimpleXMLElement_append($element, $child);
            }
        } else {
            // set the value of this item
            $element = $key->addChild($value->getName(), trim((string) $value));
        }
    } else {
        // throw an error
        throw new Exception('Wrong type of input parameters, expected SimpleXMLElement');
    }
}
?>

I'd recommend SimpleXMLElement to extend it's addChild() function with the functionalitity above.
cherubangel at gmail dot com 02-Jul-2010 04:28
Note that changing attributes from within a foreach loop, especially namespaced attributes, can be very tricky.

For example, when trying to change the value of an existing xlink:href attribute:
<?php
foreach($xmlelement -> attributes('xlink', true) as $attribute => $attribvalue){
    $attribvalue[0] = 'value'; // Throws an error
    $attribvalue = 'value'; // Does not change your XML
    $xmlelement -> addAttribute($attribute, 'value', 'http://www.w3.org/1999/xlink'); // Adds an attribute, does not change existing one.
    $xmlelement[$attribute] = 'value'; // Adds an attribute, does not change existing one.
}
?>

Instead, you should access the array returned by the attributes() function directly, like this:
<?php
    $xmlelement -> attributes('xlink', true) -> href = 'value'; // Works!
?>
php at keith tyler dot com 19-Feb-2010 06:23
The root node element of your input XML string is not retrievable as a property.

<?php
$xml="<foo>bar</foo>";
$sxe=new SimpleXMLElement($xml);
print $sxe->foo;
?>

prints nothing. You can only get to the root element via the array index method ($sxe[0]).

Also, you may not have two (or more) root elements -- that is apparently not well-formed XML.

<?php
$xml="<foo/><bar/>";
$sxe=new SimpleXMLElement($xml);
?>

throws an exception. A Q&D is to append an arbitraty root node structure to both ends of the input:

<?php
$xml="<foo/><bar/>";
$sxe=new SimpleXMLElement("<z>".$xml."</z>");
?>

Doing this also solves the above problem of root node property accessibility. (It may not work if your XML string includes a declaration.)
triplepoint at gmail dot com 19-Dec-2009 04:19
It's occasionally useful to add an XML processing instruction to a SimpleXMLElement (treating it as if it were a full document).
<?php
class SimpleXMLElement_Plus extends SimpleXMLElement {

    public function addProcessingInstruction( $name, $value )
    {
        // Create a DomElement from this simpleXML object
        $dom_sxe = dom_import_simplexml($this);

        // Create a handle to the owner doc of this xml
        $dom_parent = $dom_sxe->ownerDocument;

        // Find the topmost element of the domDocument
        $xpath = new DOMXPath($dom_parent);
        $first_element = $xpath->evaluate('/*[1]')->item(0);

        // Add the processing instruction before the topmost element
        $pi = $dom_parent->createProcessingInstruction($name, $value);
        $dom_parent->insertBefore($pi, $first_element);
    }
}
?>

For example, if you had a simpleXMLElement_Plus object made out of the xml fragment:
<xml><content /></xml>

And you needed the output to be:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="xsl/xsl.xsl"?>
<xml><content/></xml>

you could do (using the class above):
<?php
$xml = new SimpleXMLElement_Plus('<xml><content /></xml>');
$xml->addProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="xsl/xsl.xsl"');
echo $xml->asXML();
?>
ivandosreisandrade at gmail dot com 19-Nov-2009 06:55
Hello,

here goes my contribution for those whom are struggling to understand how SimpleXMLElement works.

After some time trying to figure out how this works, I've came up to this small example:

<?php
    $xmlstr = "<?xml version='1.0' ?>\n".
              // optionally you can specify a xml-stylesheet for presenting the results. just uncoment the following line and change the stylesheet name.
              /* "<?xml-stylesheet type='text/xsl' href='xml_style.xsl' ?>\n". */
              "<book></book>";

    // create the SimpleXMLElement object with an empty <book> element
    $xml = new SimpleXMLElement($xmlstr);

    // add some child nodes
    $xml->addChild("title", "Title of my book");
    $xml->addChild("abstract", "My book is about learning to work with SimpleXMLElement");

    // add some more child nodes
    $chapter1 = $xml->addChild("chapter_1");
    // add an attribute to child chapter_1
    $chapter1->addAttribute("chapter_title", "Introduction to my book");

    $chapter2 = $xml->addChild("chapter_2");
    $chapter2->addAttribute("chapter_title", "Development of my book");

    $chapter3 = $xml->addChild("chapter_3");
    $chapter3->addAttribute("chapter_title", "Another chapter of my book");

    $conclusion = $xml->addChild("conclusion", "The ending of my book");

    // insert the header to tell the browser how to read the document
    header("Content-type: text/xml");
    // print the SimpleXMLElement as a XML well-formed string
    echo $xml->asXML();
?>

With this script you can just copy-paste and try to understand how it works.
I hope it can help somebody :)
brett at brettbrewer dot com 27-Oct-2009 04:53
Figuring out how to access the properties of a SimpleXmlElement object was a little tricky for me. In particular, it took a while to discover that I needed to cast my SimpleXmlElement properties to be of type "string" to print them or do comparisons on them. For instance, assuming you already have a string of xml in $xmlstr...

<?php
$sxml= new SimpleXmlElement($xmlstr);

if ((string) $sxml->property== "somevalue") {
    echo (string) $sxml->property;
}
?>
The properties of a SimpleXmlElement object are objects themselves, so you need to put "(string)" before them, which casts their values to a string instead of an object. I assume if you were doing a numeric comparison you'd want to cast to an (int) or something numeric instead.


Añade un atributo al elemento SimpleXML

  • « SimpleXMLElement
  • SimpleXMLElement::addChild »
  • PHP Manual
  • SimpleXMLElement
  • Añade un atributo al elemento SimpleXML

SimpleXMLElement::addAttribute

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

SimpleXMLElement::addAttribute — Añade un atributo al elemento SimpleXML

Descripción

public SimpleXMLElement::addAttribute ( string $name , string $value = ? , string $namespace = ? ) : void

Añade un atributo al elemento SimpleXML.

Parámetros

name

El nombre del atributo a añadir.

value

El valor del atributo.

namespace

Si se especifica, indica el espacio de nombres al que pertenece el atributo.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Nota:

Los ejemplos enumerados podrían incluir example.php, que hace referencia al string XML encontrado en el primer ejemplo de la guía de uso básico.

Ejemplo #1 Añadir atributos e hijos a un elemento SimpleXML

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('tipo', 'documental');

$pelicula = $sxe->addChild('pelicula');
$pelicula->addChild('titulo', 'PHP2: Más historias del Parser');
$pelicula->addChild('argumento', 'Todo sobre la gente que lo hace funcionar.');

$personajes = $pelicula->addChild('personajes');
$personaje  = $personajes->addChild('personaje');
$personaje->addChild('nombre', 'Sr. Parser');
$personaje->addChild('actor', 'John Doe');

$puntuacion = $pelicula->addChild('puntuacion', '5');
$puntuacion->addAttribute('tipo', 'estrellas');

echo $sxe->asXML();

?>

El resultado del ejemplo sería algo similar a:

<?xml version="1.0" standalone="yes"?>
<peliculas tipo="documental">
 <pelicula>
  <titulo>PHP: Tras el Parser</titulo>
  <personajes>
   <personaje>
    <nombre>Srta. Programadora</nombre>
    <actor>Onlivia Actora</actor>
   </personaje>
   <personaje>
    <nombre>Sr. Programador</nombre>
    <actor>El Actor</actor>
   </personaje>
  </personajes>
  <argumento>
   Así que, este lenguaje. Es como, un lenguaje de programación. ¿O es un
   lenguaje interpretado? Lo descubrirás en esta intrigante y temible parodia
   de un documental.
  </argumento>
  <grandes-lineas>
   <linea>PHP soluciona todos los problemas web</linea>
  </grandes-lineas>
  <puntuacion tipo="pulgares">7</puntuacion>
  <puntuacion tipo="estrellas">5</puntuacion>
 </pelicula>
 <pelicula>
  <titulo>PHP2: Más historias del Parser</titulo>
  <argumento>Todo sobre la gente que lo hace funcionar.</argumento>
  <personajes>
   <personaje>
    <nombre>Sr. Parser</nombre>
    <actor>John Doe</actor>
   </personaje>
  </personajes>
  <puntuacion tipo="estrellas">5</puntuacion>
 </pelicula>
</peliculas>

Ver también

  • SimpleXMLElement::addChild() - Añade un elemento hijo al nodo XML
  • Uso básico de SimpleXML

User Contributed Notes

Patanjali 10-Apr-2016 10:37
You cannot use this to update an existing attribute's value.

Instead, get a DOM version of the SimpleXMLElement and use setAttribute, as per:

$XML = '<element a="aa">Text</element>';
$snode = new simple_xml_element($XML);

$dnode = dom_import_simplexml($snode);
$dnode->setAttribute('a', 'bb');

Resulting XML for the node is:
<element a="bb">Text</element>
p.servus 18-Nov-2011 05:42
If you need an Namespace, you must write a Prefix of the Namespace + the Name of the Attribute ("prefix:name") as the first parameter AND the uri as the third one. (I don't know why?!)

Example code:
<?php
$xml = new SimpleXMLElement("<packagedElement></packagedElement>");
$xml->addAttribute("xmi:type", "uml:Class", "http://schema.omg.org/spec/XMI/2.1");
echo $xml->asXml();
?>

Output:
<packagedElement xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmi:type="uml:Class"></packagedElement>
sarlak 07-May-2011 07:49
You can access a node child with his name this way :

<?php
$root = new SimpleXMLElement($filePath);
echo $root->nodeName->attributes;

// It works recursivly so this will work too
echo $root->nodeName->subNodeName->attributes();
?>

But if you want to ADD an attribute to a children you MUST use the children() method to access and modfiy it or it will modify the parent's attributes.

<?php
// Add a subnode
$element->nodeName->addChild('subNodeName', "whatever you want");

// Get the pos in the childrens of the parent node
$lastNodePos = $element->nodeName->count()-1;

// Get the parents node childrens
$nodeChildrens = $element->nodeName->children();

// Add an attribute to the last created
$nodeChildrens[$lastNodePos]->addAttribute('attributeName', "The attribute value);
?>
booleer at yahoo dot it 16-Dec-2010 09:44
If the attribute already exists, addAttribute does nothing.

example:
<?php
$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>
XML;

$xml = simplexml_load_string($xml_string);
$xml->item->addAttribute('id', 'bar');
echo $xml->asXML();
?>

The above examples will output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>


Añade un elemento hijo al nodo XML

  • « SimpleXMLElement::addAttribute
  • SimpleXMLElement::asXML »
  • PHP Manual
  • SimpleXMLElement
  • Añade un elemento hijo al nodo XML

SimpleXMLElement::addChild

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

SimpleXMLElement::addChild — Añade un elemento hijo al nodo XML

Descripción

public SimpleXMLElement::addChild ( string $name , string $value = ? , string $namespace = ? ) : SimpleXMLElement

Añade un elemento hijo al nodo y retorna un SimpleXMLElement del hijo.

Parámetros

name

Nombre del elemento hijo a añadir.

value

Si se especifica, valor del elemento hijo.

namespace

Si se especifica, el namespace al que pertenece el elemento hijo.

Valores devueltos

El método addChild retorna un objeto SimpleXMLElement representando el hijo añadido al nodo XML.

Ejemplos

Nota:

Los ejemplos listados quizá incluyen example.php, que hacen referencia a la cadena XML encontrada en el primer ejemplo de la guía de uso básico.

Ejemplo #1 Añade atributos e hijos a un elemento SimpleXML

<?php
include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('tipo', 'documental');

$pelicula = $sxe->addChild('pelicula');
$pelicula->addChild('titulo', 'PHP2: Más historias sobre Parser');
$pelicula->addChild('argumento', 'Todo sobre las personas que hacen que funcione.');

$personajes = $pelicula->addChild('personajes');
$personaje  = $personajes->addChild('personaje');
$personaje->addChild('nombre', 'Sr. Parser');
$personaje->addChild('actor', 'John Doe');

$puntuacion = $pelicula->addChild('puntuacion', '5');
$puntuacion->addAttribute('tipo', 'estrellas');

echo $sxe->asXML();

?>

El resultado del ejemplo sería algo similar a:

<?xml version="1.0" standalone="yes"?>
<peliculas tipo="documental">
 <pelicula>
  <titulo>PHP: Tras el Parser</titulo>
  <personajes>
   <personaje>
    <nombre>Srta. Programadora</nombre>
    <actor>Onlivia Actora</actor>
   </personaje>
   <personaje>
    <nombre>Sr. Programador</nombre>
    <actor>El Actor</actor>
   </personaje>
  </personajes>
  <argumento>
   Así que, este lenguaje. Es como, un lenguaje de programación. ¿O es un
   lenguaje interpretado? Lo descubrirás en esta intrigante y temible parodia
   de un documental.
  </argumento>
  <grandes-lineas>
   <linea>PHP soluciona todos los problemas web</linea>
  </grandes-lineas>
  <puntuacion tipo="pulgares">7</puntuacion>
  <puntuacion tipo="estrellas">5</puntuacion>
 </pelicula>
 <pelicula>
  <titulo>PHP2: Más historias del Parser</titulo>
  <argumento>Todo sobre la gente que lo hace funcionar.</argumento>
  <personajes>
   <personaje>
    <nombre>Sr. Parser</nombre>
    <actor>John Doe</actor>
   </personaje>
  </personajes>
  <puntuacion type="estrellas">5</puntuacion>
 </pelicula>
</peliculas>

Ver también

  • SimpleXMLElement::addAttribute() - Añade un atributo al elemento SimpleXML
  • Uso básico de SimpleXML

User Contributed Notes

nwarap 07-Nov-2017 02:46
Want to continue the ampersand (&) chain problem.

Sometimes, you would want to assign  (=) addChild.
This trick will helps you to do this.

<?php
$webOrders = new SimpleXMLElement('<?xml version="1.0"?><WebOrders></WebOrders>');
$webOrder = $webOrders->addChild('WebOrder');
$product = $webOrder->addChild('Product');
$product[0] = 'T&M';
$product->addAttribute('price', 19.99);
$product->addAttribute('qty', 2);
var_dump($webOrders->asXML());
?>

OUTPUT would be:

<?xml version="1.0" encoding="UTF-8"?>
<WebOrders>
    <WebOrder>
        <Product price="19.99" qty="2">T&amp;M</Product>
    </WebOrder>
</WebOrders>
johninen at gmail dot com 14-Sep-2015 01:27
In the docs for google sitemaps it is required an element for mobile sitemaps that looks like this: <mobile:mobile/>

I used some time to figure out how to make it, but it is quite simple when understood.

$mobile_schema = 'http://www.google.com/schemas/sitemap-mobile/1.0';

//Create root element
$xml_mobile = new SimpleXMLElement('
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="'.$mobile_schema.'"></urlset>
');

//Add required children
$url_mobile = $xml_b_list_mobile->addChild('url');
$url_mobile->addChild('loc', 'your-mobile-site-url');
$url_mobile->addChild('mobile:mobile', null, $mobile_schema);

For this to work properly the attribute xmlns:mobile must be set in the root node, and then used as namespace(third argument) when creating the mobile:mobile child with null as value.
thallisphp at gmail dot com 07-May-2014 07:35
<?php
class MySimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     *
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string)$append)) == 0) {
                $xml = $this->addChild($append->getName());
            } else {
                $xml = $this->addChild($append->getName(), (string)$append);
            }

            foreach ($append->children() as $child) {
                $xml->appendXML($child);
            }

            foreach ($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
frosty dot z at freesbee dot fr 16-May-2013 02:31
To complete Volker Grabsch's comment, stating :
"Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&"."

To work around that problem, you can use direct property assignment such as :

<?php
$xmlelement->value = 'my value < > &';
// results in <value>my value &lt; &gt; &amp;</value>
?>

instead of doing :

<?php
$xmlelement->addChild('value', 'my value < > &');
// results in <value>my value &lt; &gt; &</value> (invalid XML)
?>

See also: http://stackoverflow.com/questions/552957 (Rationale behind SimpleXMLElement's handling of text values in addChild and addAttribute)

HTH
passerbyxp at gmail dot com 27-Mar-2013 03:59
Be aware that simply because you can <?php $dom->addChild();?> doesn't mean your XML is valid under simple XML itself:

<?php
$dom=simplexml_load_string("<test></test>");
$dom->addChild("3D","1,2,3");
$xml=$dom->asXML();
echo $xml;
/* echos:
<?xml version="1.0"?>
<test><3D>1,2,3</3D></test>
*/

$dom=simplexml_load_string($xml);
/*
generates a whole lots of warnings,
and refuses to create an object.
*/
?>

Same in PHP 5.3 and 5.4
ivan dot kakurov at gmail dot com 13-Jan-2013 04:09
Here's my solution for creating XML from Multidimensional Array.
<?php
//DATA
        $xmlDAta = array(
            array(
                "name"  => "nameVal",
                "value" => "valVal",
                "css"   => "cssVal"
            ),
            array(
                "name"  => "name1Val",
                "value" => "val1Val",
                "css"   => "css1Val"
            ),
            "tname" => array(
                array(
                    "iTname"   => "iTname",
                    "iTname2"  => "iTname1",
                    "iTname2"  => "iTname2",
                    "iTbname3" => array(
                        "iiTbname"  => "tbName",
                        "iiTbname1" => "tbName1",
                    ),
                ),
            ),
            "tdata" => "otheerDAta"
        );

   /**
     * Create XML using string or array
     *
     * @param mixed $data input data
     * @param SimpleXMLElement $xml
     * @param string $child name of first level child
     *
     * @return adding Xml formated data into SimpleXmlElement
     */

function data2XML(array $data, SimpleXMLElement $xml, $child = "items")
    {

        foreach($data as $key => $val) {
            if(is_array($val)) {

                if(is_numeric($key)) {
                    $node  = $xml->addChild($child);
                    $nodes = $node->getName($child);
                } else {

                    $node  = $xml->addChild($key);
                    $nodes = $node->getName($key);
                }

                $node->addChild($nodes, self::data2Xml($val, $node));
            } else {
                $xml->addChild($key, $val);
            }
        }

    }

//Use

        $xml    = new SimpleXMLElement("<root/>");
        Util::data2XML($xmlDAta, $xml, "Items");

?>
jerikojerk 31-Jul-2011 07:32
If you're looking for a way to append children you may be interested in this:

<?php
$x = new SimpleXMLElement('<root name="toplevel"></root>');
$f1 = new SimpleXMLElement('<child pos="1">alpha</child>');
$f2 = new SimpleXMLElement('<child pos="2">beta</child>');
$f3 = new SimpleXMLElement('<child pos="3">gamma</child>');

$x->{$f1->getName()} = $f1;
$x->{$f2->getName()}[] = $f2;
$x->{$f3->getName()}[] = $f3;

echo 'count child=',$x->count(),"\n";
echo $x->asXML();

foreach ( $x->children() as $foo )
{
    var_dump($foo);
}

?>
alex dot feraud at gmail dot com 16-Jun-2011 02:52
Here is a class with more functions for SimpleXMLElement :

<?php
/**
 *
 * Extension for SimpleXMLElement
 * @author Alexandre FERAUD
 *
 */
class ExSimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add CDATA text in a node
     * @param string $cdata_text The CDATA value  to add
     */
  private function addCData($cdata_text)
  {
   $node= dom_import_simplexml($this);
   $no = $node->ownerDocument;
   $node->appendChild($no->createCDATASection($cdata_text));
  }

  /**
   * Create a child with CDATA value
   * @param string $name The name of the child element to add.
   * @param string $cdata_text The CDATA value of the child element.
   */
    public function addChildCData($name,$cdata_text)
    {
        $child = $this->addChild($name);
        $child->addCData($cdata_text);
    }

    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string) $append))==0) {
                $xml = $this->addChild($append->getName());
                foreach($append->children() as $child) {
                    $xml->appendXML($child);
                }
            } else {
                $xml = $this->addChild($append->getName(), (string) $append);
            }
            foreach($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
Volker Grabsch 21-Apr-2011 06:17
Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&".

So addChild() is unsuited to handle user-defined input!

Instead, you will have to replace all "&" with "&amp;" before calling addChild().

Or, use htmlspecialchars() which also replaces other characters, but won't do any harm as addChild() won't replace those again.
felipenmoura at gmail dot com 11-Apr-2011 06:06
This method returns a reference to the specific SimpleXMLElement.
If you use:
<?php
    $xml= new SimpleXMLElement('<root></root>');
    $xml->father['name']= 'Fathers name'; // creates automatically a father tag with attribute name
    $son= $xml->father->addChild('son'); // uses the first father tag
    $son['name']= 'first son';
    $otherSon= $xml->father->addChild('son'); // uses the first father tag but now, in a second son tag
    $otherSon['name']= 'second son';

    echo htmlentities($xml->asXML());
?>

The result will be
<root>
    <father>
        <son name='first son' />
        <son name='second son' />
    </father>
</root>

So, once you change something to the just added child, you are actually accessing the element inside the SimpleXMLElement as a reference.


Retorna un string XML correcto basado en un elemento SimpleXML

  • « SimpleXMLElement::addChild
  • SimpleXMLElement::attributes »
  • PHP Manual
  • SimpleXMLElement
  • Retorna un string XML correcto basado en un elemento SimpleXML

SimpleXMLElement::asXML

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::asXML — Retorna un string XML correcto basado en un elemento SimpleXML

Descripción

public SimpleXMLElement::asXML ( string $filename = ? ) : mixed

El método asXML formatea los datos del objeto padre en XML versión 1.0.

Parámetros

filename

Si se especifica, la función escribe los datos al fichero en vez de retornarlo.

Valores devueltos

Si no se especifica filename, esta función retorna un string si no hay errores y false si lo hay. Si se especifica el parámetro, retorna true si el fichero se escribió correctamente y false en caso contrario.

Ejemplos

Ejemplo #1 Retornar XML

<?php
$string = <<<XML
<a>
 <b>
  <c>texto</c>
  <c>cosas</c>
 </b>
 <d>
  <c>codigo</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

echo $xml->asXML();

?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<a>
 <b>
  <c>texto</c>
  <c>cosas</c>
 </b>
 <d>
  <c>codigo</c>
 </d>
</a>

asXML también trabaja con resultados Xpath:

Ejemplo #2 Usando asXML() en resultados SimpleXMLElement::xpath()

<?php
// Continuación del ejemplo XML anterior.

/* Buscar <a><b><c> */
$resultado = $xml->xpath('/a/b/c');

foreach ($result as $node) {
    echo $node->asXML();
}
?>

El resultado del ejemplo sería:

<c>texto</c><c>cosas</c>

Ver también

  • SimpleXMLElement::__toString() - Returns the string content
  • Uso básico de 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');
jcr at di dot uminho dot pt 25-Jan-2011 02:32
Code snippet to load a XML document, increment an attribute and store it again.
My XML looks like:
<?xml version="1.0" encoding="ISO-8859-1"?>
<doctypes counter="16">
    <doctype id="d1">
        <name>Carta</name>
        <acro>CA</acro>
    </doctype>
...
</doctypes>

I want to retrieve the counter attribute, increment it, and store the new document at the end:

<?php
  $document = simplexml_load_file("mydoc.xml");
  $cont = (integer) $document['counter'];
  $document['counter'] = $cont+1;
  $document->asXML("mydoc.xml");
?>


Identifica el atributo de un elemento

  • « SimpleXMLElement::asXML
  • SimpleXMLElement::children »
  • PHP Manual
  • SimpleXMLElement
  • Identifica el atributo de un elemento

SimpleXMLElement::attributes

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::attributes — Identifica el atributo de un elemento

Descripción

public SimpleXMLElement::attributes ( string $ns = null , bool $is_prefix = false ) : SimpleXMLElement

Esta función provee de los atributos y valores definidos dentro de una etiqueta XML.

Nota: SimpleXML ha desarrollado una regla para el añadido de propiedades iterativas a la mayoría de métodos. No pueden ser examinados usando var_dump() ni con cualquier otra función que examine objetos.

Parámetros

ns

Un namespace opcional para los atributos recuperados

is_prefix

Por defecto false

Valores devueltos

Devuelve un objeto SimpleXMLElement que puede ser iterado a través de los atributos en la etiqueta.

Devuelve null si se invoca sobre un objeto SimpleXMLElement que ya representa un atributo y no una etiqueta.

Historial de cambios

Versión | Descripción
5.2.0 | Se añadió el parámetro opcional is_prefix.

Ejemplos

Ejemplo #1 Interpreta un string XML

<?php
$string = <<<XML
<a>
 <prueba nombre="uno" juego="solitario">1</prueba>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->prueba[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
?>

El resultado del ejemplo sería:

nombre="uno"
juego="solitario"

Ver también

  • Uso básico de 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;
  }
}
?>


Encuentra los hijos del nodo dado

  • « SimpleXMLElement::attributes
  • SimpleXMLElement::__construct »
  • PHP Manual
  • SimpleXMLElement
  • Encuentra los hijos del nodo dado

SimpleXMLElement::children

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::children — Encuentra los hijos del nodo dado

Descripción

public SimpleXMLElement::children ( string $ns = ? , bool $is_prefix = false ) : SimpleXMLElement

Este método encuentra el hijo de un elemento. El resultado cumple las reglas normales de iteración.

Nota: SimpleXML ha desarrollado una regla para el añadido de propiedades iterativas a la mayoría de métodos. No pueden ser examinados usando var_dump() ni con cualquier otra función que examine objetos.

Parámetros

ns

Un nombre de espacio XML.

is_prefix

Si is_prefix es true, ns será considerado como un prefijo. Si es false ns será considerado como un espacio de nombres URL.

Valores devueltos

Devuelve un elemento SimpleXMLElement, tanto si el nodo tiene hijos o no.

Historial de cambios

Versión | Descripción
5.2.0 | Se añade el parámetro opcional is_prefix.

Ejemplos

Ejemplo #1 Recorre el pseudo-array children()

<?php
$xml = new SimpleXMLElement(
'<persona>
 <hijo rol="hijo">
  <hijo rol="hija"/>
 </hijo>
 <hijo rol="hija">
  <hijo rol="hijo">
   <hijo rol="hijo"/>
  </hijo>
 </hijo>
</persona>');

foreach ($xml->children() as $segunda_gen) {
    echo 'La persona engendra un/a ' . $segunda_gen['role'];

    foreach ($second_gen->children() as $tercera_gen) {
        echo ' quien engendra un/a ' . $tercera_gen['role'] . ';';

        foreach ($tercera_gen->children() as $cuarta_gen) {
            echo ' y ese/a ' . $tercera_gen['role'] .
                ' engendra un/a ' . $cuarta_gen['role'];
        }
    }
}
?>

El resultado del ejemplo sería:

La persona engendra un/a hijo quien engendra un/a hija; La persona engendra
un/a hija quien engendra a un/a hijo; y ese/a hijo engendra un/a hijo

Ejemplo #2 Usando espacio de nombres

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

Notas

SimpleXMLElement::children() devuleve un nodo de objeto no impotando si el nodo actuali tiene un hijo o no. Use SimpleXMLElement::count() en el valor retornado para comprobar si hay algún hijo. Como en PHP 5.3.0, SimpleXMLElement::count() puede usarse en su lugar.

Ver también

  • SimpleXMLElement::count() - Cuenta los hijos de un elemento
  • count() - Cuenta todos los elementos de un array o algo de un objeto

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


Crea un nuevo objeto SimpleXMLElement

  • « SimpleXMLElement::children
  • SimpleXMLElement::count »
  • PHP Manual
  • SimpleXMLElement
  • Crea un nuevo objeto SimpleXMLElement

SimpleXMLElement::__construct

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::__construct — Crea un nuevo objeto SimpleXMLElement

Descripción

final public SimpleXMLElement::__construct ( string $data , int $options = 0 , bool $data_is_url = false , string $ns = "" , bool $is_prefix = false )

Crea un nuevo objeto SimpleXMLElement.

Parámetros

data

Un string XML correcto o la ruta o URL a un documento XML si data_is_url es true.

options

Se utiliza opcionalmente para especificar parámetros adicionales de Libxml, que afectan a la lectura de los documentos XML. Las opciones que afectan a la salida de los documentos XML (p.e. LIBXML_NOEMPTYTAG) son silenciosamente ignoradas.

Nota:

Puede ser necesario pasar LIBXML_PARSEHUGE para poder procesar XML profundamente anidados o nodos de texto muy grandes.

data_is_url

Por defecto, data_is_url es false. Usar true para precisar que data es una ruta o URL a un documento XML en vez de un string de datos.

ns

Prefijo de espacio de nombres o URI.

is_prefix

true si ns es un prefijo, false si es una URI; por omisión, false.

Valores devueltos

Retorna un objeto SimpleXMLElement representando data.

Errores/Excepciones

Produce un mensaje de error E_WARNING por cada error encontrado en los datos XML y adicionalmente lanza una Exception si no se han podido analizar correctamente los datos XML.

Sugerencia

Debe usarse libxml_use_internal_errors() para eliminar todos los errores XML y libxml_get_errors() para iterar sobre ellos después.

Historial de cambios

Versión | Descripción
5.2.0 | Añadidos los parámetros ns y is_prefix.
5.1.2 | Añadidos los parámetros options y data_is_url.

Ejemplos

Nota:

Los ejemplos listados quizá incluyen example.php, que hacen referencia a la cadena XML encontrada en el primer ejemplo de la guía de uso básico.

Ejemplo #1 Crea un objeto SimpleXMLElement

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->pelicula[0]->titulo;

?>

El resultado del ejemplo sería:

PHP: Tras el Parser

Ejemplo #2 Crea un objeto SimpleXMLElement a partir de una URL

<?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe->asXML();

?>

Ver también

  • Uso básico de SimpleXML
  • simplexml_load_string() - Interpreta un string de XML en un objeto
  • simplexml_load_file() - Interpreta un fichero XML en un objeto
  • Tratar con los errores XML
  • libxml_use_internal_errors() - Deshabilita errores libxml y permite al usuario extraer información de errores según sea necesario

User Contributed Notes

rowan dot collins at gmail dot com 22-Apr-2017 03:23
The manual doesn't really explain what the $ns argument (and the accompanying $is_prefix) are for.

What they do is similar to the ->children() method: they set the context of the returned object to that namespace, so that access via ->elementName and ['attributeName'] refer to elements and attributes in that namespace.

In particular, they do *not* change the namespaces which exist on the document.

See this example:

<?php
// This XML contains two elements called <child>
// One is in the namespace http://example.com, with local prefix 'ws'
// The other has no namespace (no prefix, and no default namespace declared)
$xml = '<ws:example xmlns:ws="http://example.com"><child>Not in namespace</child><ws:child>In example namespace</ws:child></ws:example>';

$sx0 = new SimpleXMLElement($xml, 0, false);
$sx1 = new SimpleXMLElement($xml, 0, false, 'http://example.com');
$sx2 = new SimpleXMLElement($xml, 0, false, 'ws', true);

echo "
    Without: {$sx0->child}
    By namespace: {$sx1->child}
    By prefix: {$sx2->child}
";
?>

Output:

 Without: Not in namespace
 By namespace: In example namespace
 By prefix: In example namespace
ahmad dot mayahi at gmail dot com 07-Jun-2016 09:36
You won't be able to load an XML file without root element:

//This will throw an exception
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>', null, false);

//Here is the solution
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>', null, false);
Phil Cross 01-Sep-2014 11:39
It's worth noting, that you need to typecast dynamic property names to string in order to retrieve there value, for example:

<?php
    $xml = new SimpleXMLElement('records.xml', 0, true);

    // This will work as expected because its a hard coded property value
    foreach($xml as $record){
        echo $record->id;    // Will output the ID fine
    }

    // Dynamic properties require typecasting to string
    $xml_field = 'id';
    foreach($xml as $record){

        // This will dump a SimpleXMLElement object
        var_dump($record->$xml_field);

        // This will output the value as expected
        echo (string)$record->$xml_field;
    }
?>
bertolini dot cedric at me dot com 16-Jun-2014 11:07
It's worth noting that the behavior of SimpleXmlElement::__construct is not exactly the same as simplexml_load_string, regarding libxml_use_internal_errors().

In my case,

<?php
libxml_use_internal_errors(true);
new \SimpleXmlElement($data);
?>

was still throwing error. But as soon as I switched to

<?php
libxml_use_internal_errors(true);
simplexml_load_string($data);
?>

everything worked fine and I stopped getting an error.
kumarldh at gmail dot com 22-Mar-2011 10:50
Using libxml_use_internal_errors() may suppress errors but Exception still requires decent handling. I used following code snippet.

<?php
libxml_use_internal_errors(true);
try{
    $xmlToObject = new SimpleXMLElement($notSoWellFormedXML);
} catch (Exception $e){
    echo 'Please try again later...';
    exit();
}
?>
uramihsayibok, gmail, com 16-Aug-2009 06:52
As I was filling out a bug report, I realized why (speculation here) the constructor is final: so that functions like simplexml_load_file and simplexml_load_string can work. I imagine the PHP-ized code looks something like

<?php

function simplexml_load_file($filename, $class_name = "SimpleXMLElement", $options = 0, $ns = "", $is_prefix = false) {
    return new $class_name($filename, $options, true, $ns, $is_prefix);
}

?>

If we were to use a different $class_name and change the constructor's definition these functions wouldn't work.

There's no easy, sensible solution that keeps simplexml_load_file and simplexml_load_string.
tudor at culise dot net 20-Nov-2007 03:35
This class is extendable, but it's too bad that its constructor cannot be overriden (PHP says it's a final method). Thus the class should be wrapped using the delegation principle rather that extended.


Cuenta los hijos de un elemento

  • « SimpleXMLElement::__construct
  • SimpleXMLElement::getDocNamespaces »
  • PHP Manual
  • SimpleXMLElement
  • Cuenta los hijos de un elemento

SimpleXMLElement::count

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

SimpleXMLElement::count — Cuenta los hijos de un elemento

Descripción

public SimpleXMLElement::count ( ) : int

Este método cuenta el número de hijos de un elemento.

Valores devueltos

Devuelve el número de elementos de un elemento.

Ejemplos

Ejemplo #1 Cuenta el número de hijos

<?php
$xml = <<<EOF
<people>
 <person name="Persona 1">
  <child/>
  <child/>
  <child/>
 </person>
 <person name="Persona 2">
  <child/>
  <child/>
  <child/>
  <child/>
  <child/>
 </person>
</people>
EOF;

$elem = new SimpleXMLElement($xml);

foreach ($elem as $person) {
    printf("%s tiene %d hijos.\n", $person['name'], $person->count());
}
?>

El resultado del ejemplo sería:

Persona 1 tiene 3 hijos.
Persona 2 tiene 5 hijos.

Ver también

  • SimpleXMLElement::children() - Encuentra los hijos del nodo dado

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


Devuelve los espacios de nombre declarados en el documento

  • « SimpleXMLElement::count
  • SimpleXMLElement::getName »
  • PHP Manual
  • SimpleXMLElement
  • Devuelve los espacios de nombre declarados en el documento

SimpleXMLElement::getDocNamespaces

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

SimpleXMLElement::getDocNamespaces — Devuelve los espacios de nombre declarados en el documento

Descripción

public SimpleXMLElement::getDocNamespaces ( bool $recursive = false , bool $from_root = true ) : array

Devuelve los espacios de nombres declarados en el documento

Parámetros

recursive

Si se especifica, devuelve todos los espacios de nombre declarados en los nodos padre e hijos. De lo contrario, devuelve únicamente el espacio de nombre declarado en el nodo raíz.

from_root

Permite comprobar recursivamente espacios de nombre bajo un nodo hijo en lugar de desde la raíz del documento XML.

Valores devueltos

El método getDocNamespaces devuelve un array de nombres de espacios de nombre con sus URIs asociadas.

Ejemplos

Ejemplo #1 Obtener los espacios de nombres del documento

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<gente xmlns:p="http://example.org/ns">
    <p:persona id="1">John Doe</p:persona>
    <p:persona id="2">Susie Q. Public</p:persona>
</gente>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces();
var_dump($namespaces);

?>

El resultado del ejemplo sería:

array(1) {
   ["p"]=>
   string(21) "http://example.org/ns"
}

Ejemplo #2 Trabajando con múltiples espacios de nombre

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<gente xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:persona t:id="1">John Doe</p:persona>
    <p:persona t:id="2" a:direccion="Calle 123" xmlns:a="http://example.org/addr">
        Susie Q. Public
    </p:person>
</gente>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces(TRUE);
var_dump($namespaces);

?>

El resultado del ejemplo sería:

array(3) {
  ["p"]=>
  string(21) "http://example.org/ns"
  ["t"]=>
  string(23) "http://example.org/test"
  ["a"]=>
  string(23) "http://example.org/addr"
}

Historial de cambios

Versión | Descripción
5.4.0 | Se añadió el parámetro from_root.

Ver también

  • SimpleXMLElement::getNamespaces() - Devuelve los espacios de nombre usados en el documento
  • SimpleXMLElement::registerXPathNamespace() - Crea un contexto prefijo/ns para la siguiente petición XPath

User Contributed Notes

There are no user contributed notes for this page.


Retorna el nombre del elemento XML

  • « SimpleXMLElement::getDocNamespaces
  • SimpleXMLElement::getNamespaces »
  • PHP Manual
  • SimpleXMLElement
  • Retorna el nombre del elemento XML

SimpleXMLElement::getName

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

SimpleXMLElement::getName — Retorna el nombre del elemento XML

Descripción

public SimpleXMLElement::getName ( ) : string

Retorna el nombre del elemento XML.

Valores devueltos

El método getName retorna como string el nombre de la etiqueta XML referenciada por el objeto SimpleXMLElement.

Ejemplos

Nota:

Los ejemplos listados quizá incluyen example.php, que hacen referencia a la cadena XML encontrada en el primer ejemplo de la guía de uso básico.

Ejemplo #1 Retornar el nombre del elemento XML

<?php

include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $hijo)
{
    echo $hijo->getName() . "\n";
}

?>

El resultado del ejemplo sería:

peliculas
pelicula

User Contributed Notes

There are no user contributed notes for this page.


Devuelve los espacios de nombre usados en el documento

  • « SimpleXMLElement::getName
  • SimpleXMLElement::registerXPathNamespace »
  • PHP Manual
  • SimpleXMLElement
  • Devuelve los espacios de nombre usados en el documento

SimpleXMLElement::getNamespaces

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

SimpleXMLElement::getNamespaces — Devuelve los espacios de nombre usados en el documento

Descripción

public SimpleXMLElement::getNamespaces ( bool $recursive = false ) : array

Devuelve los espacios de nombre usados en el documento

Parámetros

recursive

Si se especifica, devuelve todos los espacios de nombre usados en los nodos padre e hijos. De lo contrario, devuelve sólo los espacios de nombre usados en el nodo raíz.

Valores devueltos

El método getNamespaces devuelve un array de nombres de espacios de nombre con sus URIs asociadas.

Ejemplos

Ejemplo #1 Obtener el nombre de espacio del documento en uso

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<gente xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:persona id="1">John Doe</p:persona>
    <p:persona id="2">Susie Q. Public</p:persona>
</gente>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getNamespaces(true);
var_dump($namespaces);

?>

El resultado del ejemplo sería:

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

Ver también

  • SimpleXMLElement::getDocNamespaces() - Devuelve los espacios de nombre declarados en el documento
  • SimpleXMLElement::registerXPathNamespace() - Crea un contexto prefijo/ns para la siguiente petición 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;
}

?>


Crea un contexto prefijo/ns para la siguiente petición XPath

  • « SimpleXMLElement::getNamespaces
  • SimpleXMLElement::saveXML »
  • PHP Manual
  • SimpleXMLElement
  • Crea un contexto prefijo/ns para la siguiente petición XPath

SimpleXMLElement::registerXPathNamespace

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

SimpleXMLElement::registerXPathNamespace — Crea un contexto prefijo/ns para la siguiente petición XPath

Descripción

public SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns ) : bool

Crea un contexto de prefijo/ns para la siguiente petición XPath. En particular, ésto es útil si el proveedor del documento XML proporcionado altera los prefijos del namespace. registerXPathNamespace creará un prefijo para el namespace asociado, permitiendo el acceso a los nodos en ese namespace sin necesidad de cambiar el código para tener en cuenta los nuevos prefijos dictados por el proveedor.

Parámetros

prefix

El prefijo del namespace a usar en la petición XPath para el namespace dado en ns.

ns

El namespace a usar para la petición XPath. Debe coincidir con un namespace en uso por el documento XML o la petición XPath usando prefix no retornará ningún resultado.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Estableciendo un prefijo para el namespace a usar en una petición XPath

<?php

$xml = <<<EOD
<book xmlns:chap="http://example.org/titulo-capitulo">
    <title>My Book</title>
    <chapter id="1">
        <chap:titulo>Chapter 1</chap:titulo>
        <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:titulo>Chapter 2</chap:titulo>
        <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/titulo-capitulo');
$resultado = $sxe->xpath('//c:titulo');

foreach ($resultado as $titulo) {
  echo $titulo . "\n";
}

?>

El resultado del ejemplo sería:

Chapter 1
Chapter 2

Notar como el documento XML mostrado en el ejemplo establece un namespace con un prefijo de chap. En el caso de que este documento (u otro como este) hubiera usado un prefijo de c, como este ha cambiado, la petición XPath no retornará los resultados adecuados y la petición requerirá modificación. Usando registerXPathNamespace evita futuras modificaciones de la petición incluso si el proveedor cambia el prefijo del namespace.

Ver también

  • SimpleXMLElement::xpath() - Ejecuta una petición XPath sobre los datos XML
  • SimpleXMLElement::getDocNamespaces() - Devuelve los espacios de nombre declarados en el documento
  • SimpleXMLElement::getNamespaces() - Devuelve los espacios de nombre usados en el documento

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


Alias de SimpleXMLElement::asXML

  • « SimpleXMLElement::registerXPathNamespace
  • 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()

Descripción

Este método es un alias de: SimpleXMLElement::asXML()

User Contributed Notes

There are no user contributed notes for this page.


Returns the string content

  • « SimpleXMLElement::saveXML
  • SimpleXMLElement::xpath »
  • PHP Manual
  • SimpleXMLElement
  • Returns the string content

SimpleXMLElement::__toString

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

SimpleXMLElement::__toString — Returns the string content

Descripción

public SimpleXMLElement::__toString ( ) : string

Returns text content that is directly in this element. Does not return text content that is inside this element's children.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the string content on success or an empty string on failure.

Ejemplos

Ejemplo #1 Get string content

<?php
$xml = new SimpleXMLElement('<a>1 <b>2 </b>3</a>');
echo $xml;
?>

El resultado del ejemplo sería:

1 3

Ver también

  • SimpleXMLElement::asXML() - Retorna un string XML correcto basado en un elemento 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.


Ejecuta una petición XPath sobre los datos XML

  • « SimpleXMLElement::__toString
  • SimpleXMLIterator »
  • PHP Manual
  • SimpleXMLElement
  • Ejecuta una petición XPath sobre los datos XML

SimpleXMLElement::xpath

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::xpath — Ejecuta una petición XPath sobre los datos XML

Descripción

public SimpleXMLElement::xpath ( string $path ) : array

El método xpath busca el nodo SimpleXML para los hijos que cumplan la path XPath.

Parámetros

path

Una ruta XPath

Valores devueltos

Retorna un array de objetos SimpleXMLElement o false en caso de error.

Ejemplos

Ejemplo #1 Xpath

<?php
$string = <<<XML
<a>
 <b>
  <c>texto</c>
  <c>cosas</c>
 </b>
 <d>
  <c>código</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

/* Busca <a><b><c> */
$resultado = $xml->xpath('/a/b/c');

while(list( , $nodo) = each($resultado)) {
    echo '/a/b/c: ',$nodo,"\n";
}

/* Rutas relativas también funcionan... */
$resultado = $xml->xpath('b/c');

while(list( , $nodo) = each($resultado)) {
    echo 'b/c: ',$nodo,"\n";
}
?>

El resultado del ejemplo sería:

/a/b/c: texto
/a/b/c: cosas
b/c: texto
b/c: cosas

Notar que los dos resultados son iguales.

Ver también

  • SimpleXMLElement::registerXPathNamespace() - Crea un contexto prefijo/ns para la siguiente petición XPath
  • SimpleXMLElement::getDocNamespaces() - Devuelve los espacios de nombre declarados en el documento
  • SimpleXMLElement::getNamespaces() - Devuelve los espacios de nombre usados en el documento
  • Uso básico de SimpleXML

User Contributed Notes

awoerl at contentserv dot com 31-Jan-2017 12:43
I tried to use string functions in the xpath statements I'm passing, like

$oXml->xpath('substring(/foo/bar/text(), 0, 4)');

But no matter which syntax I'm trying I never the string functions to work.

Is it possible, that the xpath method does not support function calls?
Alexis Peters 11-Oct-2016 09:11
If you want this behavior for an multidimensional array you can use this:

<?php
function apath(&$a, $path, $value = NULL) {
    $pathes = explode('/',$path);

    if(count($pathes) > 1) {
        $firstPart = array_shift($pathes);
        if(!isset($a[$firstPart])) {
            $a[$firstPart] = array();
        }
        return apath($a[$firstPart], implode('/', $pathes), $value);
    } else {
        if($value){
            $a[$path] = $value;
        } else {
            return $a[$path];
        }
    }
}

apath($a, 'user/name', array('prename' => 'foo', 'lastname' => 'bar'));

$a = array();
var_dump($a);
var_dump(apath($a, 'user/name/lastname'));

?>
Gives you this:

array(1) {
  ["user"]=>
  array(1) {
    ["name"]=>
    array(2) {
      ["prename"]=>
      string(5) "foo"
      ["lastname"]=>
      string(8) "bar"
    }
  }
}
string(8) "bar"
Anonymous 30-Jan-2015 05:30
As mentioned already xpath will fail is the default namespace 'xmlns' is used like in:

<?php

$xmlstring = $string = <<<XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <fileVersion appName="xl" />
</workbook>
XML;
?>

xpath cannot search through the xml without explicitly specifying a namespace.
There are 2 options :
1. rename the 'xmlns' into something else to trick xpath into believing that no default namespace is defined.
2. register a string as the default namespace and use that string in all your queries. Unfortunatly, an empty space will not work.
No other option currently exist until XPath2.0 becomes the default library.
leonjanzen at gmail dot com 19-Oct-2014 07:48
To run an xpath query on an XML document that has a namespace, the namespace must be registered with SimpleXMLElement::registerXPathNamespace() before running the query. If the XML document namespace does not include a prefix, you must make up an arbitrary one, and then use it in your query.

<?php
$strXml= <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<mydoc xmlns="http://www.url.com/myns">
    <message>Test message</message>
</mydoc>
XML;

$xmlDoc=new \SimpleXMLElement($strXml);

foreach($xmlDoc->getDocNamespaces() as $strPrefix => $strNamespace) {
    if(strlen($strPrefix)==0) {
        $strPrefix="a"; //Assign an arbitrary namespace prefix.
    }
    $xmlDoc->registerXPathNamespace($strPrefix,$strNamespace);
}

print($xmlDoc->xpath("//a:message")[0]); //Use the arbitrary namespace prefix in the query.
?>

This will output:

Test message
BenjaminBeck at gmx dot de 13-Sep-2014 01:36
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $v = $row->xpath('./country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
yetihehe at yetihehe dot com 12-Jan-2011 02:21
Xpath actually knows which element is root regardless of element on which you execute it. Example:

<?php

$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <b>
  <c>code</c>
 </b>
</a>
XML;

header('content-type: text/plain');

$xml = new SimpleXMLElement($string);

//relative to root
$b0=$xml->b[0]->xpath('//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: //c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: //c: ',$node,"\n";
}

echo "\n";

//relative to current element
$b0=$xml->b[0]->xpath('.//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: .//c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('.//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: .//c: ',$node,"\n";
}

?>

Will return:
b[0]: //c: text
b[0]: //c: stuff
b[0]: //c: code
b[1]: //c: text
b[1]: //c: stuff
b[1]: //c: code

b[0]: .//c: text
b[0]: .//c: stuff
b[1]: .//c: code
stefan at efectos dot nl 09-Nov-2010 02:33
Having problems selecting information through xpath when there are namespaces in the XML?

Try this quick and dirty solution, but it works:

<?php
$objImageXml = new SimpleXMLElement($objImageXml->asXML());
?>
grummfy at gmail dot com 11-Feb-2010 04:08
On a xml that have namespace you need to do this before your xpath request (or empty array will be return) :

<?php
$string = str_replace('xmlns=', 'ns=', $string); //$string is a string that contains xml...
?>
DrupalFocus at earthlink dot net 02-Dec-2009 12:27
Looks like the relative path is relative to the SimpleXMLElement object that you call the Xpath() method on.  Basically chopping off the root element.

<?php
$string = <<<XML
<foo>
  <bar>
    <a>
     <b>
      <c>text</c>
      <c>stuff</c>
     </b>
     <d>
      <c>code</c>
     </d>
    </a>
  </bar>
</foo>
XML;

$xml = new SimpleXMLElement($string);
/* Search for children using 2nds level relative <bar><a><b><c> */
$result = $xml->xpath('a/b/c');
if ($result)
foreach($result as $node) {
    drupal_set_message(t('a/b/c: @node.', array('@node' => $node)));
}
else
  drupal_set_message(t('a/b/c: failed.'));

/* it relative to the SimpleXMLElement Search for 2nds level relative <bar><a><b><c> but where is foo */
$bar = $xml->bar;
$result = $bar->xpath('a/b/c');
foreach($result as $node) {
    drupal_set_message(t('bar->a/b/c: @node.', array('@node' => $node)));
}
?>

results in :
#
# a/b/c: failed.
# bar->a/b/c: text.
# bar->a/b/c: stuff.
behnam@zwnj 24-Sep-2009 01:34
Seems like this function cannot return the result of XPath string() [1] function.  For example if you query xpath("string(a/@b)") you will get bool(false) although the node "a" may have the attribute "b" set to a non-empty string.

[1] http://www.w3.org/TR/xpath#section-String-Functions
Anti Veeranna 17-Jun-2009 03:50
Whether it returns a false or empty array for a non-existing path seems to depend on libxml version.

I tried the following code:

<?php
$data = '<foo><bar></bar></foo>';
$xml = simplexml_load_string($data);
print gettype($xml->xpath('/first/second'));
?>

On a machine with libxml 2.6.16 and PHP 5.2.8 I got back boolean. On a different machine with libxml 2.7.3 and PHP 5.2.8/5.2.9 I got back empty array.

You can check the libxml version from command line by executing: php --ri libxml

or simply look at phpinfo() output
arealzone-czernobyl at yahoo dot de 11-Jun-2009 03:23
The simplest way to count nodes in a XML doc:

<?php
$xml = new SimpleXMLElement($xmlstr);

$xmlNode = $xml->xpath('root/yourNodeName');
$nodeCount = count($xmlNode);

echo $nodeCount;
?>
anemik 02-Jul-2008 03:46
If you want to find easly all records satisfying some condition in XML data like

....
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
   </book>
...

try example below

<?php

$xmlStr = file_get_contents('data/books.xml');
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find all book records with price higher than 40$
$res = $xml->xpath("book/price[.>'40']/parent::*");
print_r($res);

?>

You will see response like:
Array (
[0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => bk101
                )

            [author] => Gambardella, Matthew
            [title] => XML Developer's Guide
            [genre] => Computer
            [price] => 44.95
            [publish_date] => 2000-10-01
            [description] => An in-depth look at creating applications
      with XML.
        )
...
paul at pmtlogic dot com 18-Jun-2008 12:17
xpath doesn't seem to be able to handle single quotes embedded in the query itself. For instance, I want to find geo coordinates in an xml file based on country name.

xml snippet:

<zones>
<zone country="Cote d'Ivoire" fullName="Yamoussoukro" geo="6.82,-5.28" id="1050"><url prefix="1001" value="fiji.html" /><url prefix="1002" value="C" /></zone>
</zones>

The following code does not work:

<?php
$xml = simplexml_load_file("my.xml");
$result = $xml->xpath("//zone[@country='Cote d\'Ivoire']");

foreach ( $result[0]->attributes() as $key => $val ) {
    print "<div class='coords'>$key: $val</div>\n";
}
?>

I have tried many variations on the embedded single quote (i.e. escape codes) but with no result. W3C offers no explanation either.

In addition, there doesn't seem to be any way of embedding wildcards in the attribute value (you can embed wildcards in the attribute name). Otherwise the following might be a reasonable substitute in this context:

<?php $result = $xml->xpath("//zone[@country='Cote d*Ivoire']"); ?>
canuemail at gmail dot com 05-May-2008 05:05
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $row = simplexml_load_string($item->asXML());
    $v = $row->xpath('//country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
Hugh 18-Dec-2005 03:23
Note that this function does not ALWAYS return an array. It seems that if the specified path is not found in the document, it will return false. You need to check for the false value before using foreach, if you wish to avoid a warning (and often to handle errors or control program flow in this situation).
drewish at katherinehouse dot com 10-Jul-2005 06:16
xpath() can also be used to select elements by their attributes. For a good XPath reference check out: http://www.w3schools.com/xpath/xpath_syntax.asp

<?php
$string = <<<XML
<sizes>
    <size label="Square" width="75" height="75" />
    <size label="Thumbnail" width="100" height="62" />
    <size label="Small" width="112" height="69" />
    <size label="Large" width="112" height="69" />
</sizes>
XML;

$xml = simplexml_load_string($string);
$result = $xml->xpath("//size[@label='Large']");

// print the first (and only) member of the array
echo $result[0]->asXml();
?>

The script would print:
<size label="Large" width="112" height="69"/>


La clase SimpleXMLIterator

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

Introducción

El clase SimpleXMLIterator proporciona una iteración recursiva sobre todos los nodos de un objeto SimpleXMLElement.

Sinopsis de la Clase

SimpleXMLIterator extends SimpleXMLElement implements RecursiveIterator , Countable {
/* Métodos */
public current ( ) : mixed
public getChildren ( ) : SimpleXMLIterator
public hasChildren ( ) : bool
public key ( ) : mixed
public next ( ) : void
public rewind ( ) : void
public valid ( ) : bool
/* Métodos heredados */
final public SimpleXMLElement::__construct ( string $data , int $options = 0 , bool $data_is_url = false , string $ns = "" , bool $is_prefix = false )
public SimpleXMLElement::addAttribute ( string $name , string $value = ? , string $namespace = ? ) : void
public SimpleXMLElement::addChild ( string $name , string $value = ? , string $namespace = ? ) : SimpleXMLElement
public SimpleXMLElement::asXML ( string $filename = ? ) : mixed
public SimpleXMLElement::attributes ( string $ns = null , bool $is_prefix = false ) : SimpleXMLElement
public SimpleXMLElement::children ( string $ns = ? , bool $is_prefix = false ) : SimpleXMLElement
public SimpleXMLElement::count ( ) : int
public SimpleXMLElement::getDocNamespaces ( bool $recursive = false , bool $from_root = true ) : array
public SimpleXMLElement::getName ( ) : string
public SimpleXMLElement::getNamespaces ( bool $recursive = false ) : array
public SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns ) : bool
public SimpleXMLElement::__toString ( ) : string
public SimpleXMLElement::xpath ( string $path ) : array
}

Tabla de contenidos

  • SimpleXMLIterator::current — Devuelve el elemento actual
  • SimpleXMLIterator::getChildren — Devuelve los sub elementos de el elemento actual
  • SimpleXMLIterator::hasChildren — Comprueba si el elemento actual tiene sub elementos
  • SimpleXMLIterator::key — Devuelve la clave actual
  • SimpleXMLIterator::next — Mueve al siguiente elemento
  • SimpleXMLIterator::rewind — Rebobina hasta el primer elemento
  • SimpleXMLIterator::valid — Comprueba si el elemento actual es válido

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


Devuelve el elemento actual

  • « SimpleXMLIterator
  • SimpleXMLIterator::getChildren »
  • PHP Manual
  • SimpleXMLIterator
  • Devuelve el elemento actual

SimpleXMLIterator::current

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::current — Devuelve el elemento actual

Descripción

public SimpleXMLIterator::current ( ) : mixed

Este método devuelve el elemento actual como un objeto SimpleXMLIterator o null.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve el elemento actual como un objeto SimpleXMLIterator o null en caso de error.

Ejemplos

Ejemplo #1 Devuelve el elemento actual

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP básico</book><book>XML básico</book></books>');
var_dump($xmlIterator->current());

$xmlIterator->rewind(); // reiniciar al primer elemento
var_dump($xmlIterator->current());
?>

El resultado del ejemplo sería:

NULL
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "PHP básico"
}

Ver también

  • SimpleXMLIterator::key() - Devuelve la clave actual
  • SimpleXMLIterator::next() - Mueve al siguiente elemento
  • SimpleXMLIterator::rewind() - Rebobina hasta el primer elemento
  • SimpleXMLIterator::valid() - Comprueba si el elemento actual es válido
  • SimpleXMLElement

User Contributed Notes

bmafzallmahmud at gmail dot com 02-Dec-2017 05:51
<?php
$note=<<<XML
<note>
<to>Afzall</to>
<from>Hasan</from>
<heading>Reminder</heading>
<body>Don't forget your parents</body>
</note>
XML;

$xmlIterator = new SimpleXMLIterator($note);
var_dump($xmlIterator->current()); //out put : NULL
var_dump($xmlIterator->rewind()); //out put null
$xmlIterator->rewind(); //beacse of rewind to first element then show "$xmlIterator->current()""
var_dump($xmlIterator->current());
 //out put : object(SimpleXMLIterator)#2 (1) { [0]=> string(6) "Afzall" }
?>


Devuelve los sub elementos de el elemento actual

  • « SimpleXMLIterator::current
  • SimpleXMLIterator::hasChildren »
  • PHP Manual
  • SimpleXMLIterator
  • Devuelve los sub elementos de el elemento actual

SimpleXMLIterator::getChildren

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::getChildren — Devuelve los sub elementos de el elemento actual

Descripción

public SimpleXMLIterator::getChildren ( ) : SimpleXMLIterator

Este método devuelve un objeto SimpleXMLIterator que contiene sub elementos de el elemento SimpleXMLIterator actual.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve un objeto SimpleXMLIterator que contiene los sub elementos de el elemento actual.

Ejemplos

Ejemplo #1 Devuelve los sub elementos de el elemento actual

<?php
$xml = <<<XML
<books>
    <book>
        <title>PHP Básico</title>
        <author>Jim Smith</author>
    </book>
    <book>XML básico</book>
</books>
XML;

$xmlIterator = new SimpleXMLIterator($xml);
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
    foreach($xmlIterator->getChildren() as $name => $data) {
    echo "El $name es '$data' de la clase " . get_class($data) . "\n";
    }
}
?>

El resultado del ejemplo sería:

El título es 'PHP Básico' de la clase SimpleXMLIterator
El autor es 'Jim Smith' de la clase SimpleXMLIterator

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el elemento actual tiene sub elementos

  • « SimpleXMLIterator::getChildren
  • SimpleXMLIterator::key »
  • PHP Manual
  • SimpleXMLIterator
  • Comprueba si el elemento actual tiene sub elementos

SimpleXMLIterator::hasChildren

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::hasChildren — Comprueba si el elemento actual tiene sub elementos

Descripción

public SimpleXMLIterator::hasChildren ( ) : bool

Este método comprueba si el elemento SimpleXMLIterator actual tiene sub elementos.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true si el elemento actual tiene sub elementos, en caso contrario false

Ejemplos

Ejemplo #1 Comprobar si el elemento actual tiene sub elementos

<?php
$xml = <<<XML
<books>
    <book>
        <title>PHP Básico</title>
        <author>Jim Smith</author>
    </book>
    <book>XML básico</book>
</books>
XML;

$xmlIterator = new SimpleXMLIterator( $xml );
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
    if($xmlIterator->hasChildren()) {
        var_dump($xmlIterator->current());
    }
}
?>

El resultado del ejemplo sería:

object(SimpleXMLIterator)#2 (2) {
  ["title"]=>
  string(10) "PHP Básico"
  ["author"]=>
  string(9) "Jim Smith"
}

User Contributed Notes

grummfy at gmail dot com 12-Feb-2010 01:01
Hello,

just a note for people like me who encounter the problems :

<?php
foreach($xmlIterator as $x)
{
    if($x->hasChildren())
    {
        //never reach
        echo 'x : ';
        var_dump($x->current());
    }
    if($xmlIterator->hasChildren())
    {
        echo 'iterator : ';
        var_dump($x->current()); //all time null
        var_dump($xmlIterator->current());
    }
}
?>


Devuelve la clave actual

  • « SimpleXMLIterator::hasChildren
  • SimpleXMLIterator::next »
  • PHP Manual
  • SimpleXMLIterator
  • Devuelve la clave actual

SimpleXMLIterator::key

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::key — Devuelve la clave actual

Descripción

public SimpleXMLIterator::key ( ) : mixed

Este método obtiene el nombre de la etiqueta XML del elemento actual.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve el nombre de la etiqueta XML del elemento referenciado por el objeto SimpleXMLIterator actual o false

Ejemplos

Ejemplo #1 Obtener la clave actual de etiquetas XML

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP básico</book><book>XML básico</book></books>');

echo var_dump($xmlIterator->key());
$xmlIterator->rewind(); // rebobinar hasta el primer elemento
echo var_dump($xmlIterator->key());

?>

El resultado del ejemplo sería:

bool(false)
string(4) "book"

User Contributed Notes

bmafzallmahmud at gmail dot com 01-Dec-2017 09:04
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML;

$xmlIterator = new SimpleXMLIterator($note);
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
      echo "<pre>";
     echo var_dump($xmlIterator->key());

}
?>
out put :
string(2) "to"
string(4) "from"
string(7) "heading"
string(4) "body"


Mueve al siguiente elemento

  • « SimpleXMLIterator::key
  • SimpleXMLIterator::rewind »
  • PHP Manual
  • SimpleXMLIterator
  • Mueve al siguiente elemento

SimpleXMLIterator::next

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::next — Mueve al siguiente elemento

Descripción

public SimpleXMLIterator::next ( ) : void

Este método mueve el SimpleXMLIterator a el siguiente elemento.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Mover a el siguiente elemento

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP Básico</book><book>XML básico</book></books>');
$xmlIterator->rewind(); // rebobinar hasta el primer elemento
$xmlIterator->next();

var_dump($xmlIterator->current());
?>

El resultado del ejemplo sería:

object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "XML básico"
}

User Contributed Notes

bmafzallmahmud at gmail dot com 01-Dec-2017 09:39
<?php
$note=<<<XML
<note>
<to>Afzall</to>
<from>Sumon</from>
<heading>Reminder</heading>
<body>Don't forget go to kishorgong</body>
</note>
XML;

$xmlIterator = new SimpleXMLIterator($note);
$xmlIterator->rewind();
var_dump($xmlIterator->current());
$xmlIterator->next();
var_dump($xmlIterator->current());
$xmlIterator->next();
var_dump($xmlIterator->current());
?>
out put :
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(6) "Afzall"
}
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(5) "Sumon"
}
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(8) "Reminder"
}


Rebobina hasta el primer elemento

  • « SimpleXMLIterator::next
  • SimpleXMLIterator::valid »
  • PHP Manual
  • SimpleXMLIterator
  • Rebobina hasta el primer elemento

SimpleXMLIterator::rewind

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::rewind — Rebobina hasta el primer elemento

Descripción

public SimpleXMLIterator::rewind ( ) : void

Este método rebobina el SimpleXMLIterator a el primer elemento.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Rebobinar hasta el primer elemento

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP Básico</book><book>XML Básico</book></books>');
$xmlIterator->rewind();

var_dump($xmlIterator->current());
?>

El resultado del ejemplo sería:

object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "PHP Básico"
}

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si el elemento actual es válido

  • « SimpleXMLIterator::rewind
  • Funciones de SimpleXML »
  • PHP Manual
  • SimpleXMLIterator
  • Comprueba si el elemento actual es válido

SimpleXMLIterator::valid

(PHP 5, PHP 7, PHP 8)

SimpleXMLIterator::valid — Comprueba si el elemento actual es válido

Descripción

public SimpleXMLIterator::valid ( ) : bool

Este mñetodo comprueba si el elemento actual es válido después de llamar a SimpleXMLIterator::rewind() o SimpleXMLIterator::next().

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve true si el elemento actual es válido, en caso contrario false

Ejemplos

Ejemplo #1 Comprobar si el elemento actual es válido

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>SQL Básico</book></books>');

$xmlIterator->rewind(); // rebobinar hasta el primer elemento
echo var_dump($xmlIterator->valid()); // bool(true)

$xmlIterator->next(); // avanzar al siguiente elemento
echo var_dump($xmlIterator->valid()); // bool(false) porque sólo hay un elemento
?>

User Contributed Notes

There are no user contributed notes for this page.


Funciones de SimpleXML

Tabla de contenidos

  • simplexml_import_dom — Obtiene un objeto SimpleXMLElement de un nodo DOM
  • simplexml_load_file — Interpreta un fichero XML en un objeto
  • simplexml_load_string — Interpreta un string de XML en un objeto

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.


Obtiene un objeto SimpleXMLElement de un nodo DOM

  • « Funciones de SimpleXML
  • simplexml_load_file »
  • PHP Manual
  • Funciones de SimpleXML
  • Obtiene un objeto SimpleXMLElement de un nodo DOM

simplexml_import_dom

(PHP 5, PHP 7, PHP 8)

simplexml_import_dom — Obtiene un objeto SimpleXMLElement de un nodo DOM

Descripción

simplexml_import_dom ( DOMNode $node , string $class_name = "SimpleXMLElement" ) : SimpleXMLElement

Esta función toma un nodo de un documento DOM y lo convierte en un nodo SimpleXML. Este nuevo objeto puede ser usado como un elemento SimpleXML nativo.

Parámetros

node

Un nodo del elemento DOM

class_name

Este parámetro opcional debe usarse cuando se necesite que simplexml_import_dom() retorne un objeto de la clase indicada. Esa clase debe extender de la clase SimpleXMLElement.

Valores devueltos

Devuelve un SimpleXMLElement o false en caso de error.

Advertencia

Esta función puede devolver el valor booleano false, pero también puede devolver un valor no booleano que se evalúa como false. Por favor lea la sección sobre Booleanos para más información. Use el operador === para comprobar el valor devuelto por esta función.

Ejemplos

Ejemplo #1 Importando desde DOM

<?php
$dom = new DOMDocument;
$dom->loadXML('<libros><libro><titulo>blah</titulo></libro></libros>');
if (!$dom) {
    echo 'Error analizando el documento';
    exit;
}

$s = simplexml_import_dom($dom);

echo $s->libro[0]->titulo;
?>

El resultado del ejemplo sería:

blah

Ver también

  • dom_import_simplexml() - Obtiene un objeto DOMElement desde un objeto SimpleXMLElement
  • Uso básico de SimpleXML

User Contributed Notes

shirkaen at gmail dot com 10-Nov-2016 06:58
/*If tags in DOM have text and some part of this text is surrounded by other tag, simple_import_dom object doesn't contain position of child tag, so rendering it back to html/xml can be a problem. Printing such a node is also peculiar. Eg.*/

//////////////////////
$text = "<body><p>Some text before <em>italic </em>and after text.</p></body>";
$dom = new DOMDocument;
$dom->loadHTML($text);
$result = simplexml_import_dom($dom);
echo $result->p;

//////////////////////
//Prints :
//Some text before and after text.

print_r($result->p);
//Prints:
//SimpleXMLElement Object ( [em] => italic )

print_r($result->p->em)
//does more or less the same:
//SimpleXMLElement Object ( [0] => italic )

var_dump($result->p);
//Prints:
//object(SimpleXMLElement)#8 (1) { ["em"]=> string(7) "italic " }

var_dump($result->p->em)
//object(SimpleXMLElement)#9 (1) { [0]=> string(7) "italic " }

//but
echo $result->p->em;
//prints:
//italic
brandonkirsch at perceptionilluminates dot com 14-Aug-2013 03:38
simplexml_import_dom() will accept DOMNodes or other SimpleXMLElements.  This has a useful purpose if you are extending the SimpleXMLElement class and would prefer the xpath() method to return your class extension instead of basic SimpleXMLElements.  For example:

class MySimpleXML extends SimpleXMLElement{
    public function xpath($xpath){
        $return = array();
        $simpleXmls = parent::xpath($xpath); // run SimpleXMLElement xpath, returning an array of SimpleXMLElements
        foreach($simpleXmls as $xml){
            $return[] = simplexml_import_dom($xml,'MySimpleXML'); // copy SimpleXMLElement, returning as MySimpleXML instance
        }
        return $return;
    }
}

Now I can create an instance of MySimpleXML, run an xpath, and get my results back as an array of MySimpleXML elements instead of the native SimpleXMLElement:

$mySimpleXml = new mySimpleXml('<root><node/></root>');

$array = $mySimpleXml->xpath('/root/node'); // returns array with a single MySimpleXml object


Interpreta un fichero XML en un objeto

  • « simplexml_import_dom
  • simplexml_load_string »
  • PHP Manual
  • Funciones de SimpleXML
  • Interpreta un fichero XML en un objeto

simplexml_load_file

(PHP 5, PHP 7, PHP 8)

simplexml_load_file — Interpreta un fichero XML en un objeto

Descripción

simplexml_load_file ( string $filename , string $class_name = "SimpleXMLElement" , int $options = 0 , string $ns = "" , bool $is_prefix = false ) : SimpleXMLElement

Convierte el documento correcto XML del fichero dado en un objeto.

Parámetros

filename

Ruta al fichero XML

Nota:

Libxml 2 no escapa la URI, así que si es necesario pasar, por ejemplo b&c, como parámetro a de la URI, hay que llamar a simplexml_load_file(rawurlencode('http://example.com/?a=' . urlencode('b&c'))). Desde PHP 5.1.0 no es necesario hacer esto porque PHP lo hará automáticamente.

class_name

Este parámetro opcional puede ser usado cuando se necesita que simplexml_load_file() retorne un objeto de la clase especificada. Esa clase debe extender de la clase SimpleXMLElement.

options

Desde PHP 5.1.0 y Libxml 2.6.0 puede usarse options para especificar parámetros Libxml adicionales.

ns

El prefijo del espacio de nombres o un URI.

is_prefix

true si ns es un prefijo, false si es un URI; por defecto es false.

Valores devueltos

Devuelve un object de tipo SimpleXMLElement cuyas propiedades contienen los datos del documento XML, o false en caso de error.

Advertencia

Esta función puede devolver el valor booleano false, pero también puede devolver un valor no booleano que se evalúa como false. Por favor lea la sección sobre Booleanos para más información. Use el operador === para comprobar el valor devuelto por esta función.

Errores/Excepciones

Produce un mensaje de error E_WARNING para cada error encontrado en los datos XML.

Sugerencia

Usar libxml_use_internal_errors() para suprimir todos los errores XML y libxml_get_errors() para iterar sobre cada uno de ellos posteriormente.

Historial de cambios

Versión | Descripción
5.2.0 | Se añadió el parámetro opcional is_prefix.

Ejemplos

Ejemplo #1 Interpreta un documento XML

<?php
// El fichero test.xml contiene un documento XML con un elemento raíz y, al
// menos, un elemento /[raiz]/titulo.

if (file_exists('test.xml')) {
    $xml = simplexml_load_file('test.xml');

    print_r($xml);
} else {
    exit('Error abriendo test.xml.');
}
?>

Este script mostrará, si no hay errores:

SimpleXMLElement Object
(
  [titulo] => Título ejemplo
  ...
)

En este punto, se puede seguir recorriendo usando $xml->titulo y cualquier otro elemento.

Ver también

  • simplexml_load_string() - Interpreta un string de XML en un objeto
  • SimpleXMLElement::__construct() - Crea un nuevo objeto SimpleXMLElement
  • Tratar con los errores XML
  • libxml_use_internal_errors() - Deshabilita errores libxml y permite al usuario extraer información de errores según sea necesario
  • Uso básico de SimpleXML

User Contributed Notes

sirgrayjn at gmail dot com 22-Sep-2016 09:51
// Be carefull if you migrate or use local machine
// for test/development.

// Windows directory separators: "\" and "/"
// You may mix separators "C:\somedir\www/img/bg.jpg".

// Mixed separators path work fine in other functions
// But simplexml_load_file() failed with mixed separators.

// Examples:
include("C:\dir\my.php");    // work (windows)
include("C:\dir/my.php");    // work (windows) with mixed
include("C:/dir/my.php");    // work (windows, linux)
simplexml_load_file("C:\dir\my.php");    // work
simplexml_load_file("C:\dir/my.php");    // failed with mixed
simplexml_load_file("C:/dir/my.php");    // work
rex111 at bigmir dot net 08-Sep-2016 03:02
Get all tags and their values. (recursive)

<?php
$xml = simplexml_load_file('settings.xml');

function all_tag($xml){
    $i=0; $name = "";
    foreach ($xml as $k){
        $tag = $k->getName();
        $tag_value = $xml->$tag;
        if ($name == $tag){ $i++;    }
                $name = $tag;
            echo $tag .' '.$tag_value[$i].'<br />';
        // recursive
           all_tag($xml->$tag->children());
    }
}

all_tag($xml);
?>
Rich 24-Nov-2015 02:51
I stumbled on this: a single element with a simple string in it becomes a string, but a single element with a *space* in it becomes an Array, with one element, the string space.

I'm sure to XML mystics this is wise and wonderful but it really confused me,  and I thought it might confuse others.

<?php
$parsed = simplexml_load_string('<container><space> </space><blank></blank><string>hello</string></container>');
$content = json_decode(json_encode($parsed),TRUE);
var_dump($content);
/* Output is:
array(3) {
  'space' => array(1) {           ? did NOT expect this!
    [0] => string(1) " "
  }
  'blank' => array(0) { }
  'string' => string(5) "hello"
}
 */
tuxedobob 30-Jun-2015 01:25
Occasionally you may try to load a file and have it complain about an entity and throw a parser error.

If this is the case, check to make sure that the file in question does not contain an ampersand (&) without a corresponding entity reference.

If it does, or if you want to err on the side of caution, then instead of using simplexml_load_file, try this:

$file = file_get_contents('stuff.xml');
$temp = preg_replace('/&(?!(quot|amp|pos|lt|gt);)/', '&amp;', $file);
$xml = simplexml_load_string($temp) or die("xml not loading");

Read the file into a string, add 'amp;' after any '&' that is not part of a character entity, then parse the string as xml.
kannan at 99deals dot in 04-Sep-2012 06:27
If you have some nodes which are having special characters, it would not load properly

for an instance see the nodes below
<node:number>1538-7445</node:number>
<node:coverDisplayDate>Sep  1 2012 12:00:00:000AM</node:coverDisplayDate>

either you have to change the : to other special characters like '-' in order to convert it properly

Correct Node
<node-number>1538-7445</node-number>
<node-coverDisplayDate>Sep  1 2012 12:00:00:000AM</node-coverDisplayDate>

I have wasted my precious time while debugging this. Please aware about this. ?
ricardo at ricardomartins dot info 21-Aug-2012 05:49
Sometimes we have xml's with hyphens nodes, like

<my_xml>
 <some-node>value</some-node>
</my_xml>

You'll need to use
<?php
$simpleXmlObj->{'some-node'}
?>

instead of
<?php
$simpleXmlObj->some-node;
?>
fusionstream at gmail dot com 05-Apr-2012 04:15
If you are loading many files, this may slow down your page load time.

To set a timeout, use file_get_context and then simplexml_load_string

<?php

$fp = fopen('http://www.example.com/rss', false, stream_create_context(array('http' => array('timeout', '1.5'))));

if ($fp) {
    print_r( simplexml_load_string($fp) );
} else {
    echo "The request timed out";
}
?>
sean at aliencreations dot com 17-Mar-2011 10:59
If you find that you are receiving 500 errors with simplexml_load_file() but you can access the xml/rss feed manually through a browser, your script is probably being blocked by a user agent sniffer.

Add this code before your xml call to remedy this issue

<?php

ini_set("user_agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
ini_set("max_execution_time", 0);
ini_set("memory_limit", "10000M");

$rss = simplexml_load_file($feed_url);

?>
Nanuit at ossi dot at 08-Feb-2011 01:51
A little function very helpfull in using simplexml_load_file behind a proxy

<?php
function getXMLfromURL($url) {
      $Proxy = getenv("HTTP_PROXY");

      if (strlen($Proxy) > 1) {
        $r_default_context = stream_context_get_default ( array
                    ('http' => array(
                        'proxy' => $Proxy,
                        'request_fulluri' => True,
                    ),
                )
            );
        libxml_set_streams_context($r_default_context);
      }
      $daten = simplexml_load_file($url);
      return ($daten);
    }
?>

where HTTP_PROXY is set to e.g.: tcp://proxy:8080
guego dot ol at ig dot com dot br 12-Nov-2010 03:26
Analyze fully XML.

<?php
$xml = simplexml_load_file('file.xml');

foreach($xml as $key0 => $value){
echo "..1..[$key0] => $value";
foreach($value->attributes() as $attributeskey0 => $attributesvalue1){
echo "________[$attributeskey0] = $attributesvalue1";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value as $key => $value2){
echo "....2.....[$key] => $value2";
foreach($value2->attributes() as $attributeskey => $attributesvalue2){
echo "________[$attributeskey] = $attributesvalue2";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value2 as $key2 => $value3){
echo ".........3..........[$key2] => $value3";
foreach($value3->attributes() as $attributeskey2 => $attributesvalue3){
echo "________[$attributeskey2] = $attributesvalue3";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value3 as $key3 => $value4){
echo "...................4....................[$key3] => $value4";
foreach($value4->attributes() as $attributeskey3 => $attributesvalue4){
echo "________[$attributeskey3] = $attributesvalue4";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value4 as $key4 => $value5){
echo ".....................5......................[$key4] => $value5";
foreach($value5->attributes() as $attributeskey4 => $attributesvalue5){
echo "________[$attributeskey4] = $attributesvalue5";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value5 as $key5 => $value6){
echo "......................6.......................[$key5] => $value6";
foreach($value6->attributes() as $attributeskey5 => $attributesvalue6){
echo "________[$attributeskey5] = $attributesvalue6";
}
echo '<br />';
}}}}}
echo '<br />';
}
?>
raduispas at gmail dot com 21-Oct-2010 06:12
if you want to check when this function fails,make sure to compare the return value with ===  instead of == :

<?php
$url = 'http://www.example.com';
$xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);
if($xml ===  FALSE)
{
   //deal with error
}
else { //do stuff }
?>

Otherwise you may end up with FALSE all the time even if the document is ok. Hope this helps someone ;)
jamie at splooshmedia dot co dot uk 31-Mar-2010 06:17
A wrapper around simplexml_load_file to circumvent nasty error messages when the xml server times out or gives a 500 error etc.

<?php
function loadXML2($domain, $path, $timeout = 30) {

    /*
        Usage:

        $xml = loadXML2("127.0.0.1", "/path/to/xml/server.php?code=do_something");
        if($xml) {
            // xml doc loaded
        } else {
            // failed. show friendly error message.
        }
    */

    $fp = fsockopen($domain, 80, $errno, $errstr, $timeout);
    if($fp) {
        // make request
        $out = "GET $path HTTP/1.1\r\n";
        $out .= "Host: $domain\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);

        // get response
        $resp = "";
        while (!feof($fp)) {
            $resp .= fgets($fp, 128);
        }
        fclose($fp);
        // check status is 200
        $status_regex = "/HTTP\/1\.\d\s(\d+)/";
        if(preg_match($status_regex, $resp, $matches) && $matches[1] == 200) {
            // load xml as object
            $parts = explode("\r\n\r\n", $resp);
            return simplexml_load_string($parts[1]);
        }
    }
    return false;

}
?>
Smokey 14-Mar-2010 10:16
for nested and same name values i'v made up this little bit for getting and displaying multiable values from google's geocode when a exact match is not found it returns all close matches in the following format(this is an abriged version of there output)

<Response>
  <Placemark id="1">
    <address> New York 24, NY, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.5850086,40.7207442,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="2">
    <address>New York 27, NY, USA</address>
    <AddressDetails>
      ...................
    </AddressDetails>
    <Point>
      <coordinates>-72.8987835,40.8003588,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="3">
    <address>Cedar Place School, 20 Cedar Pl, Yonkers, NY 10705, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.8966320,40.9256520,0</coordinates>
    </Point>
  </Placemark>
</Response>

<?php
// get and breakdown the results then store them in $var's
$Address = "99999 parkplace, new york, NY";
$urladdress = urlencode($Address);
$Base_url = "http://maps.google.com/maps/geo?q=";
$urlParts = "&output=xml";
$urlrequest = $Base_url . $urladdress . $urlParts;
$xml = simplexml_load_file($urlrequest);
$num = "0";
foreach ($xml->Response->Placemark as $value){
    $num++;
    $GeoFindAdd{$num} = $value->address;
    $GeoFindCords{$num} = $value->Point->coordinates;
}

// a simple display for the results
echo "Found ",$num," Possable Geo Data Sets <br>";
$CountNumResults = "0";
for ( ; $num > 0; $num--){
    $CountNumResults++;
    echo $countnum,"<br> Address = ",$GeoFindAdd{$num},"<br> Coordinates = ",$GeoFindCords{$num},"<br>";
}
echo "END";
?>
knl at bitflop dot com 11-Sep-2009 12:02
If you need to parse the data from SimpleXML into a session variable remember to define the data as a string first.

If you don't you will get warnings of "Node no longer exists" pointing to your session_start() function.

This will work:

<?php

    $new_version = simplexml_load_file('http://example.com/version.xml');
    $_SESSION['current_version'] = (string)$new_version->version;

?>
neil art neilanddeb dort com 17-Aug-2009 06:00
Because the encoding of my XML file is UTF-8 and the
encoding of my web page is iso-8859-1 I was getting strange characters such as â€™ 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;
}
?>


Interpreta un string de XML en un objeto

  • « simplexml_load_file
  • WDDX »
  • PHP Manual
  • Funciones de SimpleXML
  • Interpreta un string de XML en un objeto

simplexml_load_string

(PHP 5, PHP 7, PHP 8)

simplexml_load_string — Interpreta un string de XML en un objeto

Descripción

simplexml_load_string ( string $data , string $class_name = "SimpleXMLElement" , int $options = 0 , string $ns = "" , bool $is_prefix = false ) : SimpleXMLElement

Toma un string XML correcto y lo retorna como objeto.

Parámetros

data

Un string XML correcto

class_name

Este parámetro opcional puede ser usado cuando se necesita que simplexml_load_file() retorne un objeto de la clase especificada. Esa clase debe extender de la clase SimpleXMLElement.

options

Desde PHP 5.1.0 y Libxml 2.6.0 puede usarse options para especificar parámetros Libxml adicionales.

ns

El prefijo del espacio de nombres o un URI.

is_prefix

true si ns es un prefijo, false si es un URI; por defecto es false.

Valores devueltos

Devuelve un object de tipo SimpleXMLElement cuyas propiedades contienen los datos del documento XML, o false en caso de error.

Advertencia

Esta función puede devolver el valor booleano false, pero también puede devolver un valor no booleano que se evalúa como false. Por favor lea la sección sobre Booleanos para más información. Use el operador === para comprobar el valor devuelto por esta función.

Errores/Excepciones

Produce un mensaje de error E_WARNING para cada error encontrado en los datos XML.

Sugerencia

Usar libxml_use_internal_errors() para suprimir todos los errores XML y libxml_get_errors() para iterar sobre cada uno de ellos posteriormente.

Historial de cambios

Versión | Descripción
5.2.0 | Se añadió el parámetro opcional is_prefix.

Ejemplos

Ejemplo #1 Interpreta un string XML

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
 <title>¿Cuarenta qué?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  Sé que esa es la respuesta pero, ¿cuál es la pregunta?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);

print_r($xml);
?>

El resultado del ejemplo sería:

SimpleXMLElement Object
(
  [titulo] => ¿Cuarenta qué?
  [de] => Joe
  [para] => Jane
  [mensaje] => Sé que esa es la respuesta pero, ¿cuál es la pregunta?
)

En este punto, se puede usar $xml->mensaje y similares.

Ver también

  • simplexml_load_file() - Interpreta un fichero XML en un objeto
  • SimpleXMLElement::__construct() - Crea un nuevo objeto SimpleXMLElement
  • Tratar con los errores XML
  • libxml_use_internal_errors() - Deshabilita errores libxml y permite al usuario extraer información de errores según sea necesario
  • Uso básico de 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

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Ejemplos
    • Ejemplos de wddx
  • Funciones de WDDX
    • wddx_add_vars — Agrega variables a un paquete WDDX con un ID específico
    • wddx_deserialize — Deserializa un packet WDDX
    • wddx_packet_end — Finaliza un paquete WDDX con un ID específico
    • wddx_packet_start — Inicia un nuevo paquete WDDX con una estructura a dentro
    • wddx_serialize_value — Serializa una simple valor dentro de un paquete WDDX
    • wddx_serialize_vars — Serializa variables en un paquete WDDX

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Estas funciones están previstas para trabajar con » WDDX.

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


Requerimientos

Esta extensión requiere la extensión libxml de PHP. Esto significa que también es necesario pasar la opción --enable-libxml, aunque esto se realiza implícitamente debido a que libxml está habilitada de forma predeterminada.

A fin de utilizar WDDX, se necesita instalar la librería expat (la cual viene con Apache 1.3.7 o superior).

User Contributed Notes

There are no user contributed notes for this page.


Instalación

Despúes de instalar la librería requerida expat, compile PHP con --enable-wddx, y use --with-libexpat-dir para expat.

La versión de PHP para Windows tiene soporte nativo para esta extensión. No se requiere cargar extensiones adicionales para utilizar estas funciones.

User Contributed Notes

There are no user contributed notes for this page.


Tipos de recursos

Esta extensión define un identificador de paquete WDDX devuelto por wddx_packet_start().

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

Tabla de contenidos

  • Ejemplos de 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>


Ejemplos de wddx

Todas las funciones que serializan variables utilizan el primer elemento de un array para determinar si el array ha sido serializado en una estructura o un array. Si el primer elemento tiene una cadena como llave, entonces es serializado como estructura, de lo contrario, en un array.

Ejemplo #1 Serializando un simple valor con WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

Este ejemplo producirá:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Ejemplo #2 Usando paquetes incrementales con WDDX

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo $packet;
?>

Este ejemplo producirá:

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

Nota:

Si se desea serializar caracteres distintos al ASCII se debe convertir los datos a UTF-8 primero (ver utf8_encode() e iconv()).

User Contributed Notes

There are no user contributed notes for this page.


Funciones de WDDX

Tabla de contenidos

  • wddx_add_vars — Agrega variables a un paquete WDDX con un ID específico
  • wddx_deserialize — Deserializa un packet WDDX
  • wddx_packet_end — Finaliza un paquete WDDX con un ID específico
  • wddx_packet_start — Inicia un nuevo paquete WDDX con una estructura a dentro
  • wddx_serialize_value — Serializa una simple valor dentro de un paquete WDDX
  • wddx_serialize_vars — Serializa variables en un paquete 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>


Agrega variables a un paquete WDDX con un ID específico

  • « Funciones de WDDX
  • wddx_deserialize »
  • PHP Manual
  • Funciones de WDDX
  • Agrega variables a un paquete WDDX con un ID específico

wddx_add_vars

(PHP 4, PHP 5, PHP 7)

wddx_add_vars — Agrega variables a un paquete WDDX con un ID específico

Advertencia

This function was REMOVED in PHP 7.4.0.

Descripción

wddx_add_vars ( resource $packet_id , mixed $var_name , mixed $... = ? ) : bool

Serializa las variables pasadas y agrega el resultado al paquete determinado.

Parámetros

Esta función toma un número variable de parámetros.

packet_id

Un paquete WDDX, devuelto por wddx_packet_start().

var_name

Pude ser una cadena, una variable o un array conteniendo una cadena, una variable u otro array, etc.

...

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

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 !


Deserializa un packet WDDX

  • « wddx_add_vars
  • wddx_packet_end »
  • PHP Manual
  • Funciones de WDDX
  • Deserializa un packet WDDX

wddx_deserialize

(PHP 4, PHP 5, PHP 7)

wddx_deserialize — Deserializa un packet WDDX

Descripción

wddx_deserialize ( string $packet ) : mixed

Deserializa un packet WDDX.

Parámetros

packet

Un paquete WDDX, como un string o cadena.

Valores devueltos

Devuelve un valor deserializado que puede ser una cadena, un número o un array. Note que las estructuras son deserializadas en arrays asociativos.

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


Finaliza un paquete WDDX con un ID específico

  • « wddx_deserialize
  • wddx_packet_start »
  • PHP Manual
  • Funciones de WDDX
  • Finaliza un paquete WDDX con un ID específico

wddx_packet_end

(PHP 4, PHP 5, PHP 7)

wddx_packet_end — Finaliza un paquete WDDX con un ID específico

Advertencia

This function was REMOVED in PHP 7.4.0.

Descripción

wddx_packet_end ( resource $packet_id ) : string

Finaliza y devuelve el paquete WDDX.

Parámetros

packet_id

Un paquete WDDX, devuelto por wddx_packet_start().

Valores devueltos

Devuelve la cadena que contiene el paquete WDDX.

User Contributed Notes

There are no user contributed notes for this page.


Inicia un nuevo paquete WDDX con una estructura a dentro

  • « wddx_packet_end
  • wddx_serialize_value »
  • PHP Manual
  • Funciones de WDDX
  • Inicia un nuevo paquete WDDX con una estructura a dentro

wddx_packet_start

(PHP 4, PHP 5, PHP 7)

wddx_packet_start — Inicia un nuevo paquete WDDX con una estructura a dentro

Advertencia

This function was REMOVED in PHP 7.4.0.

Descripción

wddx_packet_start ( string $comment = ? ) : resource

Inicia un nuevo paquete WDDX para adición incremental de variables. Crea una definición de estructura automáticamente dentro del paquete para almacenar variables.

Parámetros

comment

Una cadena de comentario opcional.

Valores devueltos

Devuelve un ID de paquete para usar en funciones posteriores, o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Serializa una simple valor dentro de un paquete WDDX

  • « wddx_packet_start
  • wddx_serialize_vars »
  • PHP Manual
  • Funciones de WDDX
  • Serializa una simple valor dentro de un paquete WDDX

wddx_serialize_value

(PHP 4, PHP 5, PHP 7)

wddx_serialize_value — Serializa una simple valor dentro de un paquete WDDX

Advertencia

This function was REMOVED in PHP 7.4.0.

Descripción

wddx_serialize_value ( mixed $var , string $comment = ? ) : string

Crea un paquete WDDX a partir de un simple valor.

Parámetros

var

El valor que será serializado

comment

Una cadena opcional de comentario que aparecerá en la cabecera del paquete.

Valores devueltos

Devuelve el paquete WDDX, o false en caso de error.

User Contributed Notes

chris at digitalbase dot com 04-Jan-2002 04:36
When serializing JavaScript objects to interact with PHP objects, you should make the JavaScript object's first entry a php_class_name.

PHP:
class myclass {
    var $name;
    var $age;
    var $ssn;
    ...

    function myclass() {
        $this->name = "";
        $this->age = "";
        $this->ssn = "";
        ...
    }
}

JavaScript:
// serialization example code is from the
// WDDX SDK http://www.openwddx.org
function SerializeMsg(name, age, ssn, ...) {
    var MyObj = new Object;

    // the following line is necessary in order
    // to deserialize back to a PHP object
    MyObj.php_class_name = "myclass";

    MyObj.name = name;
    MyObj.age = age;
    MyObj.ssn = ssn;
    ...

    // Create a new serializer "object" to do our work for us
    MySer = new WddxSerializer;

    // Serialize the Message variable into a WDDX Packet
    MyWDDXPacket = MySer.serialize(MyObj);

    // Output WDDX Packet so we can see what it looks like
    return MyWDDXPacket;
}

Now you can use this in a page which is its own form action:
<?php
// don't forget to include the class definition from above!
if (!isSet($wddx_packet))
    $MyObj = new myclass();
else
    $MyObj = wddx_deserialize($wddx_packet);
?>

<html>
<head>
<script language="JavaScript">
<!--
function Init() {
    // sets the form's text-elements
    tmp = document.MyForm;

    tmp.name.value = "<? echo $MyObj->name ?>";
    tmp.age.value = "<? echo $MyObj->age ?>";
    tmp.ssn.value = "<? echo $MyObj->ssn ?>";
    ...
}

function SerializeMsg(name, age, ssn, ...) {
// see above!
}

function SubmitForm() {
    // sumbits the form
    tmp = document.MyForm;

    tmp.wddx_packet.value =
    SerializeMsg(tmp.name.value, tmp.age.value, tmp.ssn.value,...);
    document.submit();
}
// -->
</script>
</head>
<body>
...
<form name="MyForm"
action="<? echo $PHP_SELF ?>" method="post">
<input name="wddx_packet" type="hidden">
<input name="name" type="text">
<input name="age" type="text">
<input name="ssn" type="text">
...
<input name="SubmitBtn" type="button" onclick="SumbitForm()">
</form>
</body>
</html>

---------------------------------
If you don't provide that first 'php_class_name' in the JavaScript function, then when PHP deserializes it will deserialize into an associative array and not an object instance.

Note that this provides a way to maintain state without
using sessions or cookies - just good old HTML!

Hope this helps!
--
Chris Hansen


Serializa variables en un paquete WDDX

  • « wddx_serialize_value
  • XMLDiff »
  • PHP Manual
  • Funciones de WDDX
  • Serializa variables en un paquete WDDX

wddx_serialize_vars

(PHP 4, PHP 5, PHP 7)

wddx_serialize_vars — Serializa variables en un paquete WDDX

Advertencia

This function was REMOVED in PHP 7.4.0.

Descripción

wddx_serialize_vars ( mixed $var_name , mixed $... = ? ) : string

Crea un paquete WDDX con una estructura que contiene la representación serializada de las variables pasadas.

Parámetros

Esta función toma un número variables de parámetros.

var_name

Pude ser una cadena, una variable o un array conteniendo una cadena, una variable u otro array, etc.

...

Valores devueltos

Devuelve el paquete WDDX, o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo 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);
?>

El resultado del ejemplo sería:

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


Diferencias y fusión de documentos XML

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
  • XMLDiff\Base — La clase XMLDiff\Base
    • XMLDiff\Base::__construct — Constructor
    • XMLDiff\Base::diff — Produce diferencias de dos documentos XML
    • XMLDiff\Base::merge — Produce un nuevo documento XML basado en diferencias
  • XMLDiff\DOM — La clase XMLDiff\DOM
    • XMLDiff\DOM::diff — Diferencia dos objetos DOMDocument
    • XMLDiff\DOM::merge — Produce DOMDocument unido
  • XMLDiff\Memory — La clase XMLDiff\Memory
    • XMLDiff\Memory::diff — Diferenciar dos documentos XML
    • XMLDiff\Memory::merge — Produce un documento XML unido
  • XMLDiff\File — La clase XMLDiff\File
    • XMLDiff\File::diff — Diferencia dos archivos XML
    • XMLDiff\File::merge — Produce un documento XML unido

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Esta extensión es capaz de calcular las diferencias de dos documentos XML y luego aplicarlas en el documento de origen. El diff es un documento XML que contiene en sus nodos, en formato legible por humanos, las instruciones para copiar/insertar/eliminar. Objetos del tipo DOMDocument, ficheros locales y strings en memoria pueden ser procesados.

User Contributed Notes

There are no user contributed notes for this page.


Requerimientos

libdiffmark - la versión 0.10 se incluye con la extensión. Si diffmark está disponible en los paquetes del sistema, su uso es altamente recomendado.

Extensión libxml

Extensión DOM

User Contributed Notes

There are no user contributed notes for this page.


Instalación

Esta extensión » PECL no se distribuye con PHP.

Se puede encontrar información para la instalación de esta extensión PECL en el capítulo del manual titulado Instalación de extensiones PECL. Se puede encontrar información adicional, tal como nuevos lanzamientos, descargas, ficheros fuente, información de mantenimiento, y un CHANGELOG, aquí: » https://pecl.php.net/package/xmldiff.

Un DLL para esta extensión PECL se encuentra disponible en » http://windows.php.net/downloads/pecl/releases/xmldiff/.

User Contributed Notes

There are no user contributed notes for this page.


La clase XMLDiff\Base

(PECL xmldiff >= 0.8.0)

Introducción

Clase abstracta, base para todas las clases de comparación en la extensión.

Sinopsis de la Clase

XMLDiff\Base {
/* Métodos */
public __construct ( string $nsname )
abstract public diff ( mixed $from , mixed $to ) : mixed
abstract public merge ( mixed $src , mixed $diff ) : mixed
}

Tabla de contenidos

  • XMLDiff\Base::__construct — Constructor
  • XMLDiff\Base::diff — Produce diferencias de dos documentos XML
  • XMLDiff\Base::merge — Produce un nuevo documento XML basado en diferencias

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « XMLDiff\Base
  • XMLDiff\Base::diff »
  • PHP Manual
  • XMLDiff\Base
  • Constructor

XMLDiff\Base::__construct

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::__construct — Constructor

Descripción

public XMLDiff\Base::__construct ( string $nsname )

Constructor base para todas las clases de trabajadores en la extensión Xmldiff.

Parámetros

nsname

Nombre del espacio de nombres personalizado para el documento de diferencias. El espacio de nombres por defecto es http://www.locus.cz/diffmark y eso es suficiente para evitar conflictos de nombres. Usa este parámetro si quieres cambiarlo por alguna razón.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Produce diferencias de dos documentos XML

  • « XMLDiff\Base::__construct
  • XMLDiff\Base::merge »
  • PHP Manual
  • XMLDiff\Base
  • Produce diferencias de dos documentos XML

XMLDiff\Base::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::diff — Produce diferencias de dos documentos XML

Descripción

abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed

Método abstracto diferencial para ser aplicado por las clases hereditarias.

El propósito básico de este método es producir diferencias entre dos documentos. El orden paramétrico importa y producirá diferentes resultados.

Parámetros

from

Documento fuente XML.

to

Documento XML de destino.

Valores devueltos

Depende de la implementación.

User Contributed Notes

There are no user contributed notes for this page.


Produce un nuevo documento XML basado en diferencias

  • « XMLDiff\Base::diff
  • XMLDiff\DOM »
  • PHP Manual
  • XMLDiff\Base
  • Produce un nuevo documento XML basado en diferencias

XMLDiff\Base::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::merge — Produce un nuevo documento XML basado en diferencias

Descripción

abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed

Método de fusión abstracta para ser implementado por las clases hereditarias.

Básicamente el propósito del método es producir un nuevo documento XML basado en la información diferencial.

Parámetros

src

Documento fuente XML.

diff

Documento producido por el método diferencial.

Valores devueltos

Depende de la implementación.

User Contributed Notes

There are no user contributed notes for this page.


La clase XMLDiff\DOM

(PECL xmldiff >= 0.8.0)

Introducción

Sinopsis de la Clase

XMLDiff\DOM extends XMLDiff\Base {
/* Métodos */
public diff ( DOMDocument $from , DOMDocument $to ) : DOMDocument
public merge ( DOMDocument $src , DOMDocument $diff ) : DOMDocument
/* Métodos heredados */
public XMLDiff\Base::__construct ( string $nsname )
abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed
abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed
}

Tabla de contenidos

  • XMLDiff\DOM::diff — Diferencia dos objetos DOMDocument
  • XMLDiff\DOM::merge — Produce DOMDocument unido

User Contributed Notes

There are no user contributed notes for this page.


Diferencia dos objetos DOMDocument

  • « XMLDiff\DOM
  • XMLDiff\DOM::merge »
  • PHP Manual
  • XMLDiff\DOM
  • Diferencia dos objetos DOMDocument

XMLDiff\DOM::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::diff — Diferencia dos objetos DOMDocument

Descripción

public XMLDiff\DOM::diff ( DOMDocument $from , DOMDocument $to ) : DOMDocument

Diferencia dos instancias de DOMDocument y produce la nueva que contiene la información de la diferencia.

Parámetros

from

Fuente del objeto DOMDocument.

to

Objeto de destino DOMDocument.

Valores devueltos

DOMDocument con la información de diferencia o NULL.

User Contributed Notes

jeewiya at gmail dot com 28-Mar-2018 10:43
XMLDiff\DOM can be use like this, for compare xml files changes.

<?php

function getChangeElements($currentContent, $oldContent) {
        try {
            $currentDoc = new DOMDocument();
            $currentDoc->loadXML($currentContent);

            $oldDoc = new DOMDocument();
            $oldDoc->loadXML($oldContent);
            $xmldiff = new XMLDiff\DOM();
            return $xmldiff->diff($oldDoc, $currentDoc);
        } catch (Exception $ex) {
            throw $ex;
        }
    }

getChangeElements('updated.xml', 'old.xml');

?>


Produce DOMDocument unido

  • « XMLDiff\DOM::diff
  • XMLDiff\Memory »
  • PHP Manual
  • XMLDiff\DOM
  • Produce DOMDocument unido

XMLDiff\DOM::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::merge — Produce DOMDocument unido

Descripción

public XMLDiff\DOM::merge ( DOMDocument $src , DOMDocument $diff ) : DOMDocument

Crear un nuevo DOMDocument basado en las diferencias.

Parámetros

src

Objeto fuente DOMDocument.

diff

Objeto DOMDocument que contiene la información de diferencias.

Valores devueltos

DOMDocument unido o NULL.

User Contributed Notes

There are no user contributed notes for this page.


La clase XMLDiff\Memory

(PECL xmldiff >= 0.8.0)

Introducción

Sinopsis de la Clase

XMLDiff\Memory extends XMLDiff\Base {
/* Métodos */
public diff ( string $from , string $to ) : string
public merge ( string $src , string $diff ) : string
/* Métodos heredados */
public XMLDiff\Base::__construct ( string $nsname )
abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed
abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed
}

Tabla de contenidos

  • XMLDiff\Memory::diff — Diferenciar dos documentos XML
  • XMLDiff\Memory::merge — Produce un documento XML unido

User Contributed Notes

There are no user contributed notes for this page.


Diferenciar dos documentos XML

  • « XMLDiff\Memory
  • XMLDiff\Memory::merge »
  • PHP Manual
  • XMLDiff\Memory
  • Diferenciar dos documentos XML

XMLDiff\Memory::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::diff — Diferenciar dos documentos XML

Descripción

public XMLDiff\Memory::diff ( string $from , string $to ) : string

Diferenciar dos string que contienen documentos XML y producir la información diferencial.

Parámetros

from

Documento fuente XML.

to

Documento XML de destino.

Valores devueltos

String con el documento XML que contiene la información del diferencia o NULL.

User Contributed Notes

There are no user contributed notes for this page.


Produce un documento XML unido

  • « XMLDiff\Memory::diff
  • XMLDiff\File »
  • PHP Manual
  • XMLDiff\Memory
  • Produce un documento XML unido

XMLDiff\Memory::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::merge — Produce un documento XML unido

Descripción

public XMLDiff\Memory::merge ( string $src , string $diff ) : string

Crear un nuevo documento XML basado en diferencias y documento fuente.

Parámetros

src

Documento fuente XML.

diff

Documento XML que contiene información de diferencias.

Valores devueltos

String con el nuevo documento XML o NULL.

User Contributed Notes

There are no user contributed notes for this page.


La clase XMLDiff\File

(PECL xmldiff >= 0.8.0)

Introducción

Sinopsis de la Clase

XMLDiff\File extends XMLDiff\Base {
/* Métodos */
public diff ( string $from , string $to ) : string
public merge ( string $src , string $diff ) : string
/* Métodos heredados */
public XMLDiff\Base::__construct ( string $nsname )
abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed
abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed
}

Tabla de contenidos

  • XMLDiff\File::diff — Diferencia dos archivos XML
  • XMLDiff\File::merge — Produce un documento XML unido

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


Diferencia dos archivos XML

  • « XMLDiff\File
  • XMLDiff\File::merge »
  • PHP Manual
  • XMLDiff\File
  • Diferencia dos archivos XML

XMLDiff\File::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\File::diff — Diferencia dos archivos XML

Descripción

public XMLDiff\File::diff ( string $from , string $to ) : string

Diferencia dos archivos XML locales y produce un string con la información de diferenciación.

Parámetros

from

Path to the source document.

to

Ruta al documento fuente.

Valores devueltos

String con el documento XML que contiene la información diferencial o NULL.

User Contributed Notes

There are no user contributed notes for this page.


Produce un documento XML unido

  • « XMLDiff\File::diff
  • Analizador XML »
  • PHP Manual
  • XMLDiff\File
  • Produce un documento XML unido

XMLDiff\File::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\File::merge — Produce un documento XML unido

Descripción

public XMLDiff\File::merge ( string $src , string $diff ) : string

Crea un nuevo documento XML basado en diferencias y documento fuente.

Parámetros

src

Ruta al documento XML de origen.

diff

Ruta al documento XML con la información de diferencia.

Valores devueltos

String con el nuevo documento XML o NULL.

User Contributed Notes

There are no user contributed notes for this page.


Analizador XML

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Manejadores de eventos
  • Case Folding
  • Error Codes
  • Codificación de caracteres
  • Ejemplos
    • Ejemplo de estructura de XML
    • Ejemplo de asignación de etiquetas XML
    • Ejemplo de entidades XML externas
  • Funciones del Intérprete XML
    • utf8_decode — Convierte una cadena con los caracteres codificados ISO-8859-1 con UTF-8 a un sencillo byte ISO-8859-1
    • utf8_encode — Codifica un string ISO-8859-1 a UTF-8
    • xml_error_string — Obtiene la cadena de un error dado en un intérprete XML
    • xml_get_current_byte_index — Obtiene la indexación del byte actual en un intérprete XML
    • xml_get_current_column_number — Obtiene el número de columna actual para un intérprete XML
    • xml_get_current_line_number — Obtiene el número de línea actual para un intérprete XML
    • xml_get_error_code — Obtiene un código de error en un intérprete XML
    • xml_parse_into_struct — Interpreta datos XML en una estructura de array
    • xml_parse — Inicia un intérprete sobre un documento XML
    • xml_parser_create_ns — Crea un analizador XML con soporte para espacios de nombres
    • xml_parser_create — Crea un intérprete XML
    • xml_parser_free — Liberar una analizador XML
    • xml_parser_get_option — Obtiene el valor de las opciones de un intérprete XML
    • xml_parser_set_option — Configura las opciones en un intérprete XML
    • xml_set_character_data_handler — Configura el manejador de los datos de caracteres
    • xml_set_default_handler — Configura el manejador predeterminado
    • xml_set_element_handler — Configura los manejadores para los elementos de inicio y final
    • xml_set_end_namespace_decl_handler — Configura el manejador de declaración de final del namespace
    • xml_set_external_entity_ref_handler — Configura el manejador de referencia a entidades externas
    • xml_set_notation_decl_handler — Configura el manejador de declaraciones de notación
    • xml_set_object — Usa un intérprete XML Parser dentro de un objeto
    • xml_set_processing_instruction_handler — Configura el manejador de instrucciones de proceso (PI)
    • xml_set_start_namespace_decl_handler — Configura el manejador de declaración de inicio del namespace
    • xml_set_unparsed_entity_decl_handler — Configura el manejador de declaración de entidades no analizadas

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.


Introducción

XML (eXtensible Markup Language) es un formato de datos para el intercambio en la web de documentos estructurados. Es un estándar definido por el World Wide Web consortium (W3C). Se puede encontrar más información sobre XML y tecnologías relacionadas en » http://www.w3.org/XML/.

Esta extensión de PHP implementa el soporte para expat de James Clark en PHP. Este conjunto de herramientas permite analizar, pero no validar, documentos XML. Es compatible con tres codificaciones de caracteres fuente, también proporcionadas por PHP: US-ASCII, ISO-8859-1 y UTF-8. No está soportada UTF-16.

Esta extensión permite crear analizadores XML y luego definir gestores para los diferentes eventos XML. Cada analizador XML también tiene algunos parámetros que se pueden ajustar.

User Contributed Notes

There are no user contributed notes for this page.


Requerimientos

Esta extensión requiere la extensión libxml de PHP. Esto significa que también es necesario pasar la opción --enable-libxml, aunque esto se realiza implícitamente debido a que libxml está habilitada de forma predeterminada.

Esta extensión usa una capa de compatibilidad expat por defecto. También puede usarse expat,el cual puede encontrarse en » http://www.jclark.com/xml/expat.html. El Makefile que viene con expat no construye una libreria por defecto, puede utilizar esta regla para hacerlo:

libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@
Se puede encontrar un paquete RPM de expat en » http://sourceforge.net/projects/expat/.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

Esta extensión está habilitada de forma predeterminada. Se puede deshabilitar empleando la siguiente opción durante la compilación: --disable-xml

Estas funciones estan activadas por defecto, usando la libreria incluida de expat. Se puede desactivar el soporte XML con --disable-xml. Si se compila PHP como un módulo para Apache 1.3.9 o superior, PHP automaticamente usará la libreria incluida de expat desde Apache. Para no usar la libreria incluida de expat se configura PHP con --with-expat-dir=DIR, donde DIR apunta al directorio base de instalación de expat expat.

La versión de PHP para Windows tiene soporte nativo para esta extensión. No se requiere cargar extensiones adicionales para utilizar estas funciones.

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.


Tipos de recursos

El recurso xml tal y como lo devuelve xml_parser_create() y xml_parser_create_ns() hace referencia a una instancia de intérprete xml para ser usado con las funciones provistas por esta extensión.

User Contributed Notes

There are no user contributed notes for this page.


Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles sólo cuando la extensión haya sido compilada con PHP, o bien sea cargada dinámicamente en ejecución.

XML_ERROR_NONE (integer)
XML_ERROR_NO_MEMORY (integer)
XML_ERROR_SYNTAX (integer)
XML_ERROR_NO_ELEMENTS (integer)
XML_ERROR_INVALID_TOKEN (integer)
XML_ERROR_UNCLOSED_TOKEN (integer)
XML_ERROR_PARTIAL_CHAR (integer)
XML_ERROR_TAG_MISMATCH (integer)
XML_ERROR_DUPLICATE_ATTRIBUTE (integer)
XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)
XML_ERROR_PARAM_ENTITY_REF (integer)
XML_ERROR_UNDEFINED_ENTITY (integer)
XML_ERROR_RECURSIVE_ENTITY_REF (integer)
XML_ERROR_ASYNC_ENTITY (integer)
XML_ERROR_BAD_CHAR_REF (integer)
XML_ERROR_BINARY_ENTITY_REF (integer)
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)
XML_ERROR_MISPLACED_XML_PI (integer)
XML_ERROR_UNKNOWN_ENCODING (integer)
XML_ERROR_INCORRECT_ENCODING (integer)
XML_ERROR_UNCLOSED_CDATA_SECTION (integer)
XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)
XML_OPTION_CASE_FOLDING (integer)
XML_OPTION_TARGET_ENCODING (integer)
XML_OPTION_SKIP_TAGSTART (integer)
XML_OPTION_SKIP_WHITE (integer)
XML_SAX_IMPL (string)
Guarda el método de implementación de SAX. Puede ser libxml o expat .

User Contributed Notes

There are no user contributed notes for this page.


Manejadores de eventos

Los manejadores XML de eventos definidos son:

Manejadores XML soportados
Función PHP para configurar el manejador | Descripción del evento
xml_set_element_handler() | Los eventos de elemento se producen cada vez que el intérprete XML encuentra etiquetas de inicio o de final. Hay manejadores separados para etiquetas de inicio y final.
xml_set_character_data_handler() | Por definición los datos de caracteres es todo el contenido no marcado de los documentos XML, incluidos los espacios en blanco entre etiquetas. Tenga en cuenta que el intérprete XML no añade o elimina ningún espacio en blanco, eso depende de la aplicación (usted) decidir si el espacio en blanco es significativo.
xml_set_processing_instruction_handler() | Los programadores de PHP ya deberían estar familiarizados con las instrucciones de procesado (PI). <?php ?> es una instrucción de procesado, donde php se denomina "PI destino". El manejo de ellos es específico para cada aplicación, excepto los PI destinos que empiecen con "XML", ya que estan reservados.
xml_set_default_handler() | Lo que no va a otro manejador va al manejador predeterminado. En el controlador predeterminado se obtendran cosas como el XML y las declaraciones de tipo de documento.
xml_set_unparsed_entity_decl_handler() | Este manejador será llamado para la declaración de una entidad no analizada (NDATA).
xml_set_notation_decl_handler() | Este manejador es llamado para la declaración de una notación.
xml_set_external_entity_ref_handler() | Este manejador es llamado cuando el intérprete XML encuentra una referencia a una entidad general externa analizada. Por ejemplo puede ser una referencia a un fichero o una URL. Ver el ejemplo de entidad externa para una demostración.
xml_set_start_namespace_decl_handler() | Este manejador es llamado al principio de una declaración de namespace.
xml_set_end_namespace_decl_handler() | Este manejador es llamado al fin de un espacio de una declaración de namespace. Tenga en cuenta que este evento NO es bajo LibXML.

User Contributed Notes

There are no user contributed notes for this page.


Case Folding

Las funciones manejadoras de elementos pueden obtener sus nombres de elementos "case-folded". Case folding se define como "un proceso aplicado a una secuencia de caracteres", en el cual aquellos que son identificados como no-mayúsculas son reemplazados por sus equivalentes en mayúsculas". En otras palabras, cuando se trata de XML, case folding simplemente significa poner en mayúsculas.

Por defecto, todos los nombres de elementos que son pasados al manejador de funciones son pasados a mayúsculas. Este comportamiento puede ser consultado y controlado por el intérprete XML mediante las funciones xml_parser_get_option() y xml_parser_set_option() respectivamente.

User Contributed Notes

There are no user contributed notes for this page.


Error Codes

Las siguientes constantes se definen para códigos de error XML (como los que devuelve 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
?>


Codificación de caracteres

La extensión de PHP XML es compatible con el conjunto de caracteres » Unicode a través de diferentes codificaciones de caracteres. Hay dos tipos de codificaciones de caracteres: la codificación fuente y la codificación de destino. La representación interna de PHP del documento está siempre codificada con UTF-8.

La codificación fuente se hace cuando un documento XML es analizado. Una vez creado un intérprete XML, la codificación fuente puede ser especificada (esta codificación no puede ser cambiada más adelante en la vida del intérprete XML). Las codificaciones fuente soportadas son ISO-8859-1, US-ASCII y UTF-8. Las dos primeras son codificaciones de un solo byte, lo cual significa que cada caracter se representa por un solo byte. UTF-8 puede codificar caracteres compuestos por un número variable de bits (hasta 21) de uno a cuatro bytes. La codificación fuente por defecto usada por PHP es ISO-8859-1.

La codificación de destino se hace cuando PHP pasa datos al controlador XML de funciones. Cuando un intérprete XML se ha creado, la codificación de destino se establece igual que la que tenga la codificación fuente, pero esta puede ser cambiada en cualquier punto. La codificación de destino afectará a los caracteres de los datos como también a los nombres de etiquetas y las intrucciones de procesamiento de destino.

Si el intérprete XML encuentra caracteres fuera de rango que su codificación fuente es capaz de representar, devolverá un error.

Si PHP encuentra caracteres en el documento XML analizado que no pueden ser representados en la codificación de destino escogida, los caracteres problemáticos seran "degradados". Actualmente esto significa que tales caracteres seran reemplazados por un signo de interrogación.

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

Tabla de contenidos

  • Ejemplo de estructura de XML
  • Ejemplo de asignación de etiquetas XML
  • Ejemplo de entidades XML externas

User Contributed Notes

There are no user contributed notes for this page.


Ejemplo de estructura de XML

Este primer ejemplo muestra la estructura de los elementos en un documento con indentación.

Ejemplo #1 Mostrar la estructura de elementos XML

<?php
$file = "data.xml";
$depth = array();

function startElement($parser, $name, $attrs)
{
    global $depth;

    if (!isset($depth[$parser])) {
        $depth[$parser] = 0;
    }

    for ($i = 0; $i < $depth[$parser]; $i++) {
        echo "  ";
    }
    echo "$name\n";
    $depth[$parser]++;
}

function endElement($parser, $name)
{
    global $depth;
    $depth[$parser]--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>

User Contributed Notes

Sample at hotmail dot com 04-Jul-2013 10:32
<?php

public static function xml2array($element, $arr = array())
    {
        if(is_string($element))
        {
            $element = (strlen($element) > 5 && substr($element, -4) === '.xml')
                            ? simplexml_load_file(DATAPATH.$element)
                            : simplexml_load_string($element);
        }
         $iter = 0;
        foreach($element->children() as $b)
        {
            $a = $b->getName();
            if(!$b->children()){
                    $arr[$a] = trim($b[0]);
            }
            else{
                    $arr[$a][$iter] = array();
                    $arr[$a][$iter] = self::xml2array($b,$arr[$a][$iter]);
            }
                $iter++;
        }
        return $arr;
    }
}

?>
roan at horning dot us 30-Oct-2009 09:07
The following example will echo back an xml file using the basic event based parser.  Currently, (at least in the version of PHP5 I'm using) it will skip The XML declaration and the Doctype declaration--they don't seem to be captured by the default handler.

<?php
echo "<pre>";

$file = "test.xml";
echo $file."\n";
global $inTag;

$inTag = "";
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);
xml_set_processing_instruction_handler($xml_parser, "pi_handler");
xml_set_default_handler($xml_parser, "parseDEFAULT");
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "contents");

if (!($fp = fopen($file, "r"))) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
       die( sprintf("XML error: %s at line %d",
                            xml_error_string(xml_get_error_code($xml_parser)),
                            xml_get_current_line_number($xml_parser)));
    }
}
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
       die( sprintf("XML error: %s at line %d",
                            xml_error_string(xml_get_error_code($xml_parser)),
                            xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);

function startElement($parser, $name, $attrs) {

    global $inTag;
    global $depth;

    $padTag = str_repeat(str_pad(" ", 3), $depth);

    if (!($inTag == "")) {
        echo "&gt;";
    }
    echo "\n$padTag&lt;$name";
    foreach ($attrs as $key => $value) {
        echo "\n$padTag".str_pad(" ", 3);
        echo " $key=\"$value\"";
    }
    $inTag = $name;
    $depth++;
}

function endElement($parser, $name) {

    global $depth;
   global $inTag;
    global $closeTag;

    $depth--;

   if ($closeTag == TRUE) {
       echo "&lt/$name&gt;";
       $inTag = "";
   } elseif ($inTag == $name) {
       echo " /&gt;";
       $inTag = "";
   } else {
         $padTag = str_repeat(str_pad(" ", 3), $depth);
       echo "\n$padTag&lt/$name&gt;";
    }
}

function contents($parser, $data) {

    global $closeTag;

    $data = preg_replace("/^\s+/", "", $data);
    $data = preg_replace("/\s+$/", "", $data);

    if (!($data == ""))  {
        echo "&gt;$data";
        $closeTag = TRUE;
    } else {
        $closeTag = FALSE;
     }
}

function parseDEFAULT($parser, $data) {

    $data = preg_replace("/</", "&lt;", $data);
    $data = preg_replace("/>/", "&gt;", $data);
    echo $data;
}

function pi_handler($parser, $target, $data) {

    echo "&lt;?$target $data?&gt;\n";
}
echo "</pre>";
?>


Ejemplo de asignación de etiquetas XML

Ejemplo #1 Asignar XML a HTML

Este ejemplo asigna las etiquetas en un documento XML directamente a etiquetas HTML. Los elementos que no sean encontrados en el "map array" son ignorados. Por supuesto, este ejemplo solo funcionará con un tipo específico de documento XML.

<?php
$file = "data.xml";
$map_array = array(
    "BOLD"     => "B",
    "EMPHASIS" => "I",
    "LITERAL"  => "TT"
);

function startElement($parser, $name, $attrs)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "<$map_array[$name]>";
    }
}

function endElement($parser, $name)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "</$map_array[$name]>";
    }
}

function characterData($parser, $data)
{
    echo $data;
}

$xml_parser = xml_parser_create();
// use case-folding so we are sure to find the tag in $map_array
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>

User Contributed Notes

There are no user contributed notes for this page.


Ejemplo de entidades XML externas

Este ejemplo resalta el código XML. Muestra como usar un gestor de referencia de entidades externas para incluir y analizar otros documentos, así como cuantos PIs pueden ser procesados, y una manera de determinar "confianza" para PIs que contienen código.

Los documentos XML que pueden ser usados para este ejemplo se pueden encontrar debajo del código del ejemplo (xmltest.xml y xmltest2.xml.)

Ejemplo #1 Ejemplo de entidades XML externas

<?php
$file = "xmltest.xml";

function trustedFile($file)
{
    // only trust local files owned by ourselves
    if (!preg_match("@^([a-z]+)\:\/\/@i", $file)
        && fileowner($file) == getmyuid()) {
            return true;
    }
    return false;
}

function startElement($parser, $name, $attribs)
{
    echo "&lt;<font color=\"#0000cc\">$name</font>";
    if (count($attribs)) {
        foreach ($attribs as $k => $v) {
            echo " <font color=\"#009900\">$k</font>=\"<font
                   color=\"#990000\">$v</font>\"";
        }
    }
    echo "&gt;";
}

function endElement($parser, $name)
{
    echo "&lt;/<font color=\"#0000cc\">$name</font>&gt;";
}

function characterData($parser, $data)
{
    echo "<b>$data</b>";
}

function PIHandler($parser, $target, $data)
{
    switch (strtolower($target)) {
        case "php":
            global $parser_file;
            // If the parsed document is "trusted", we say it is safe
            // to execute PHP code inside it.  If not, display the code
            // instead.
            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);

?>

Ejemplo #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>

Este fichero se incluye desde xmltest.xml:

Ejemplo #3 xmltest2.xml

<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
   <element attrib="value"/>
   &testEnt;
   <?php echo "This is some more PHP code being executed."; ?>
</foo>

User Contributed Notes

There are no user contributed notes for this page.


Funciones del Intérprete XML

Tabla de contenidos

  • utf8_decode — Convierte una cadena con los caracteres codificados ISO-8859-1 con UTF-8 a un sencillo byte ISO-8859-1
  • utf8_encode — Codifica un string ISO-8859-1 a UTF-8
  • xml_error_string — Obtiene la cadena de un error dado en un intérprete XML
  • xml_get_current_byte_index — Obtiene la indexación del byte actual en un intérprete XML
  • xml_get_current_column_number — Obtiene el número de columna actual para un intérprete XML
  • xml_get_current_line_number — Obtiene el número de línea actual para un intérprete XML
  • xml_get_error_code — Obtiene un código de error en un intérprete XML
  • xml_parse_into_struct — Interpreta datos XML en una estructura de array
  • xml_parse — Inicia un intérprete sobre un documento XML
  • xml_parser_create_ns — Crea un analizador XML con soporte para espacios de nombres
  • xml_parser_create — Crea un intérprete XML
  • xml_parser_free — Liberar una analizador XML
  • xml_parser_get_option — Obtiene el valor de las opciones de un intérprete XML
  • xml_parser_set_option — Configura las opciones en un intérprete XML
  • xml_set_character_data_handler — Configura el manejador de los datos de caracteres
  • xml_set_default_handler — Configura el manejador predeterminado
  • xml_set_element_handler — Configura los manejadores para los elementos de inicio y final
  • xml_set_end_namespace_decl_handler — Configura el manejador de declaración de final del namespace
  • xml_set_external_entity_ref_handler — Configura el manejador de referencia a entidades externas
  • xml_set_notation_decl_handler — Configura el manejador de declaraciones de notación
  • xml_set_object — Usa un intérprete XML Parser dentro de un objeto
  • xml_set_processing_instruction_handler — Configura el manejador de instrucciones de proceso (PI)
  • xml_set_start_namespace_decl_handler — Configura el manejador de declaración de inicio del namespace
  • xml_set_unparsed_entity_decl_handler — Configura el manejador de declaración de entidades no analizadas

User Contributed Notes

filip dot rydlo at gmail dot com 18-Apr-2017 09:28
// Fix for xmlToArrayParser  .......... hope this helps somebody. :-)

// FIXED the "MULTIPLE-CALLS to callback for one string" issue of 'cdata' in  xmlToArrayParser written by:
// Glen at ITIStudios dot ca  (2012)

  private function cdata($parser, $cdata) {
    if(isset($this->pointer['cdata'])) {      // This FIXes the issue with "INCOMPLETE STRINGS" containing html-entities
      $this->pointer['cdata'] .= $cdata;
    } else {
      $this->pointer['cdata'] = $cdata;
    }
  }
anrdaemon at freemail dot ru 10-Feb-2016 06:06
You must not, never ever use utf8_encode() and utf8_decode().
If you need multibyte conversion utility, use iconv() instead. At the very least, you will get a notification, if your string can not be converted.
utf8_* crap, like other crap of this nature, is ONLY SUPPORTING ONE CONVERSION. ISO-8859-1 <=> UTF-8.
Glen at ITIStudios dot ca 15-Aug-2013 06:42
Update: concatenate element contents in function cdata()
<?php
/**
 *  XML to Associative Array Class
 *
 *  Usage:
 *     $domObj = new xmlToArrayParser($xml);
 *     $domArr = $domObj->array;
 *
 *     if($domObj->parse_error) echo $domObj->get_xml_error();
 *     else print_r($domArr);
 *
 *     On Success:
 *     eg. $domArr['top']['element2']['attrib']['var2'] => val2
 *
 *     On Error:
 *     eg. Error Code [76] "Mismatched tag", at char 58 on line 3
 */

/**
 * Convert an xml file or string to an associative array (including the tag attributes):
 * $domObj = new xmlToArrayParser($xml);
 * $elemVal = $domObj->array['element']
 * Or:  $domArr=$domObj->array;  $elemVal = $domArr['element'].
 *
 * @version  3.0
 * @param Str $xml file/string.
 */
class xmlToArrayParser {
  /** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
  public  $array = array();
  public  $parse_error = false;
  private $parser;
  private $pointer;

  /** Constructor: $domObj = new xmlToArrayParser($xml); */
  public function __construct($xml) {
    $this->pointer =& $this->array;
    $this->parser = xml_parser_create("UTF-8");
    xml_set_object($this->parser, $this);
    xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
    xml_set_element_handler($this->parser, "tag_open", "tag_close");
    xml_set_character_data_handler($this->parser, "cdata");
    $this->parse_error = xml_parse($this->parser, ltrim($xml))? false : true;
  }

  /** Free the parser. */
  public function __destruct() { xml_parser_free($this->parser);}

  /** Get the xml error if an an error in the xml file occured during parsing. */
  public function get_xml_error() {
    if($this->parse_error) {
      $errCode = xml_get_error_code ($this->parser);
      $thisError =  "Error Code [". $errCode ."] \"<strong style='color:red;'>" . xml_error_string($errCode)."</strong>\",
                            at char ".xml_get_current_column_number($this->parser) . "
                            on line ".xml_get_current_line_number($this->parser)."";
    }else $thisError = $this->parse_error;
    return $thisError;
  }

  private function tag_open($parser, $tag, $attributes) {
    $this->convert_to_array($tag, 'attrib');
    $idx=$this->convert_to_array($tag, 'cdata');
    if(isset($idx)) {
      $this->pointer[$tag][$idx] = Array('@idx' => $idx,'@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag][$idx];
    }else {
      $this->pointer[$tag] = Array('@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag];
    }
    if (!empty($attributes)) { $this->pointer['attrib'] = $attributes; }
  }

  /** Adds the current elements content to the current pointer[cdata] array. */
  private function cdata($parser, $cdata){
    if (isset($this->pointer['cdata'])) { $this->pointer['cdata'] .= $cdata;}
    else { $this->pointer['cdata'] = $cdata; }
  }

  private function tag_close($parser, $tag) {
    $current = & $this->pointer;
    if(isset($this->pointer['@idx'])) {unset($current['@idx']);}
    $this->pointer = & $this->pointer['@parent'];
    unset($current['@parent']);
    if(isset($current['cdata']) && count($current) == 1) { $current = $current['cdata'];}
    else if(empty($current['cdata'])) {unset($current['cdata']);}
  }

  /** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
  private function convert_to_array($tag, $item) {
    if(isset($this->pointer[$tag]) && !is_array($this->pointer[$tag])){
      $content = $this->pointer[$tag];
      $this->pointer[$tag] = array((0) => $content);
      $idx = 1;
    }else if (isset($this->pointer[$tag])) {
      $idx = count($this->pointer[$tag]);
      if(!isset($this->pointer[$tag][0])) {
        foreach ($this->pointer[$tag] as $key => $value) {
            unset($this->pointer[$tag][$key]);
            $this->pointer[$tag][0][$key] = $value;
    }}}else $idx = null;
    return $idx;
  }
}
?>
Glen at ITIStudios dot ca 05-Apr-2013 07:38
Update: corrected isset() in convert_to_array() function
<?php
/**
 *  XML to Associative Array Class
 *
 *  Usage:
 *     $domObj = new xmlToArrayParser($xml);
 *     $domArr = $domObj->array;
 *
 *     if($domObj->parse_error) echo $domObj->get_xml_error();
 *     else print_r($domArr);
 *
 *     On Success:
 *     eg. $domArr['top']['element2']['attrib']['var2'] => val2
 *
 *     On Error:
 *     eg. Error Code [76] "Mismatched tag", at char 58 on line 3
 */

/**
 * Convert an xml file or string to an associative array (including the tag attributes):
 * $domObj = new xmlToArrayParser($xml);
 * $elemVal = $domObj->array['element']
 * Or:  $domArr=$domObj->array;  $elemVal = $domArr['element'].
 *
 * @version  2.0
 * @param Str $xml file/string.
 */
class xmlToArrayParser {
  /** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
  public  $array = array();
  public  $parse_error = false;
  private $parser;
  private $pointer;

  /** Constructor: $domObj = new xmlToArrayParser($xml); */
  public function __construct($xml) {
    $this->pointer =& $this->array;
    $this->parser = xml_parser_create("UTF-8");
    xml_set_object($this->parser, $this);
    xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
    xml_set_element_handler($this->parser, "tag_open", "tag_close");
    xml_set_character_data_handler($this->parser, "cdata");
    $this->parse_error = xml_parse($this->parser, ltrim($xml))? false : true;
  }

  /** Free the parser. */
  public function __destruct() { xml_parser_free($this->parser);}

  /** Get the xml error if an an error in the xml file occured during parsing. */
  public function get_xml_error() {
    if($this->parse_error) {
      $errCode = xml_get_error_code ($this->parser);
      $thisError =  "Error Code [". $errCode ."] \"<strong style='color:red;'>" . xml_error_string($errCode)."</strong>\",
                            at char ".xml_get_current_column_number($this->parser) . "
                            on line ".xml_get_current_line_number($this->parser)."";
    }else $thisError = $this->parse_error;
    return $thisError;
  }

  private function tag_open($parser, $tag, $attributes) {
    $this->convert_to_array($tag, 'attrib');
    $idx=$this->convert_to_array($tag, 'cdata');
    if(isset($idx)) {
      $this->pointer[$tag][$idx] = Array('@idx' => $idx,'@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag][$idx];
    }else {
      $this->pointer[$tag] = Array('@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag];
    }
    if (!empty($attributes)) { $this->pointer['attrib'] = $attributes; }
  }

  /** Adds the current elements content to the current pointer[cdata] array. */
  private function cdata($parser, $cdata) { $this->pointer['cdata'] = trim($cdata); }

  private function tag_close($parser, $tag) {
    $current = & $this->pointer;
    if(isset($this->pointer['@idx'])) {unset($current['@idx']);}

    $this->pointer = & $this->pointer['@parent'];
    unset($current['@parent']);

    if(isset($current['cdata']) && count($current) == 1) { $current = $current['cdata'];}
    else if(empty($current['cdata'])) {unset($current['cdata']);}
  }

  /** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
  private function convert_to_array($tag, $item) {
    if(isset($this->pointer[$tag]) && !is_array($this->pointer[$tag])){
      $content = $this->pointer[$tag];
      $this->pointer[$tag] = array((0) => $content);
      $idx = 1;
    }else if (isset($this->pointer[$tag])) {
      $idx = count($this->pointer[$tag]);
      if(!isset($this->pointer[$tag][0])) {
        foreach ($this->pointer[$tag] as $key => $value) {
            unset($this->pointer[$tag][$key]);
            $this->pointer[$tag][0][$key] = $value;
    }}}else $idx = null;
    return $idx;
  }
}
?>
Glen at ITIStudios dot ca 02-Dec-2011 03:37
<?php
/**
 *  XML to Associative Array Class
 *
 *  Usage:
 *     $domObj = new xmlToArrayParser($xml);
 *     $domArr = $domObj->array;
 *
 *     if($domObj->parse_error) echo $domObj->get_xml_error();
 *     else print_r($domArr);
 *
 *     On Success:
 *     eg. $domArr['top']['element2']['attrib']['var2'] => val2
 *
 *     On Error:
 *     eg. Error Code [76] "Mismatched tag", at char 58 on line 3
 */

/**
 * Convert an xml file or string to an associative array (including the tag attributes):
 * $domObj = new xmlToArrayParser($xml);
 * $elemVal = $domObj->array['element']
 * Or:  $domArr=$domObj->array;  $elemVal = $domArr['element'].
 *
 * @version  2.0
 * @param Str $xml file/string.
 */
class xmlToArrayParser {
  /** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
  public  $array = array();
  public  $parse_error = false;
  private $parser;
  private $pointer;

  /** Constructor: $domObj = new xmlToArrayParser($xml); */
  public function __construct($xml) {
    $this->pointer =& $this->array;
    $this->parser = xml_parser_create("UTF-8");
    xml_set_object($this->parser, $this);
    xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
    xml_set_element_handler($this->parser, "tag_open", "tag_close");
    xml_set_character_data_handler($this->parser, "cdata");
    $this->parse_error = xml_parse($this->parser, ltrim($xml))? false : true;
  }

  /** Free the parser. */
  public function __destruct() { xml_parser_free($this->parser);}

  /** Get the xml error if an an error in the xml file occured during parsing. */
  public function get_xml_error() {
    if($this->parse_error) {
      $errCode = xml_get_error_code ($this->parser);
      $thisError =  "Error Code [". $errCode ."] \"<strong style='color:red;'>" . xml_error_string($errCode)."</strong>\",
                            at char ".xml_get_current_column_number($this->parser) . "
                            on line ".xml_get_current_line_number($this->parser)."";
    }else $thisError = $this->parse_error;
    return $thisError;
  }

  private function tag_open($parser, $tag, $attributes) {
    $this->convert_to_array($tag, 'attrib');
    $idx=$this->convert_to_array($tag, 'cdata');
    if(isset($idx)) {
      $this->pointer[$tag][$idx] = Array('@idx' => $idx,'@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag][$idx];
    }else {
      $this->pointer[$tag] = Array('@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag];
    }
    if (!empty($attributes)) { $this->pointer['attrib'] = $attributes; }
  }

  /** Adds the current elements content to the current pointer[cdata] array. */
  private function cdata($parser, $cdata) { $this->pointer['cdata'] = trim($cdata); }

  private function tag_close($parser, $tag) {
    $current = & $this->pointer;
    if(isset($this->pointer['@idx'])) {unset($current['@idx']);}

    $this->pointer = & $this->pointer['@parent'];
    unset($current['@parent']);

    if(isset($current['cdata']) && count($current) == 1) { $current = $current['cdata'];}
    else if(empty($current['cdata'])) {unset($current['cdata']);}
  }

  /** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
  private function convert_to_array($tag, $item) {
    if(isset($this->pointer[$tag][$item])) {
      $content = $this->pointer[$tag];
      $this->pointer[$tag] = array((0) => $content);
      $idx = 1;
    }else if (isset($this->pointer[$tag])) {
      $idx = count($this->pointer[$tag]);
      if(!isset($this->pointer[$tag][0])) {
        foreach ($this->pointer[$tag] as $key => $value) {
            unset($this->pointer[$tag][$key]);
            $this->pointer[$tag][0][$key] = $value;
    }}}else $idx = null;
    return $idx;
  }
}
?>

This is supplimental information for the "class xmlToArrayParser".
This is a fully functional error free, extensively tested php class unlike the posts that follow it.

Key phrase: Fully functional, fully tested, error free XML To Array parser.

<?php
/**
 * class xmlToArrayParser
 *
  Notes:
  1. 'attrib' and 'cdata' are keys added to the array when the element contains both attributes and content.
  2. Ignores content that is not in between it's own set of tags.
  3. Don't know if it recognizes processing instructions nor do I know about processing instructions.
     <\?some_pi some_attr="some_value"?>  This is the same as a document declaration.
  4. Empty elements are not included unless they have attributes.
  5. Version 2.0, Dec. 2, 2011, added xml error reporting.

  Usage:
    $domObj = new xmlToArrayParser($xml);
    $elemVal = $domObj->array['element']
    Or assign the entire array to its own variable:
    $domArr = $domObj->array;
    $elemVal = $domArr['element']

  Example:
    $xml = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <top>
      <element1>element content 1</element1>
      <element2 var2="val2" />
      <element3 var3="val3" var4="val4">element content 3</element3>
      <element3 var5="val5">element content 4</element3>
      <element3 var6="val6" />
      <element3>element content 7</element3>
    </top>';

    $domObj = new xmlToArrayParser($xml);
    $domArr = $domObj->array;

    if($domObj->parse_error) echo $domObj->get_xml_error();
    else print_r($domArr);

    On Success:
    $domArr['top']['element1'] => element content 1
    $domArr['top']['element2']['attrib']['var2'] => val2
    $domArr['top']['element3']['0']['attrib']['var3'] => val3
    $domArr['top']['element3']['0']['attrib']['var4'] => val4
    $domArr['top']['element3']['0']['cdata'] => element content 3
    $domArr['top']['element3']['1']['attrib']['var5'] => val5
    $domArr['top']['element3']['1']['cdata'] => element content 4
    $domArr['top']['element3']['2']['attrib']['var6'] => val6
    $domArr['top']['element3']['3'] => element content 7

    On Error:
    Error Code [76] "Mismatched tag", at char 58 on line 3
 *
 */
?>
wolfon.AT-DoG.inbox.ru 28-Jul-2008 03:09
Finally a simple xml => array class.
Functioning like SimpleXML library.

<?php
class xml  {
    private $parser;
    private $pointer;
    public $dom;

    public function __construct($data) {
        $this->pointer =& $this->dom;
        $this->parser = xml_parser_create();
        xml_set_object($this->parser, $this);
        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
        xml_parse($this->parser, $data);
    }

    private function tag_open($parser, $tag, $attributes) {
        if (isset($this->pointer[$tag]['@attributes'])) {
            $content = $this->pointer[$tag];
            $this->pointer[$tag] = array(0 => $content);
            $idx = 1;
        } else if (isset($this->pointer[$tag]))
            $idx = count($this->pointer[$tag]);

        if (isset($idx)) {
            $this->pointer[$tag][$idx] = Array(
                '@idx' => $idx,
                '@parent' => &$this->pointer);
               $this->pointer =& $this->pointer[$tag][$idx];
        } else {
            $this->pointer[$tag] = Array(
                '@parent' => &$this->pointer);
            $this->pointer =& $this->pointer[$tag];
        }
        if (!empty($attributes))
            $this->pointer['@attributes'] = $attributes;
    }

    private function cdata($parser, $cdata) {
           $this->pointer['@data'] = $cdata;
    }

    private function tag_close($parser, $tag) {
        $current = & $this->pointer;
        if (isset($this->pointer['@idx']))
            unset($current['@idx']);

        $this->pointer = & $this->pointer['@parent'];

          unset($current['@parent']);
           if (isset($current['@data']) && count($current) == 1)
               $current = $current['@data'];
           else if (empty($current['@data'])||$current['@data']==0)
               unset($current['@data']);
    }
}
?>

maybe I'll do some explanations on habr
geoff at spacevs dot com 07-Nov-2007 09:13
Reading xml into a class:

<?PHP
        class XmlData {}
        $elements = array();
        $elements[] =& new XmlData();
        function startElement($parser, $name, $attrs) {
                global $elements;
                $element =& new XMLData();
                $elements[count($elements)-1]->$name =& $element;
                $elements[] =& $element;
        }
        function endElement($parser, $name) {
                global $elements;
                array_pop($elements);
        }
        function characterData($parser, $data) {
                global $elements;
                $elements[count($elements)-1]->data = $data;
        }
        $xml_parser     = xml_parser_create();
        xml_set_element_handler($xml_parser, "startElement", "endElement");
        xml_set_character_data_handler($xml_parser, "characterData");
        xml_parse($xml_parser, $xml, true);
        xml_parser_free($xml_parser);
        $request =& array_pop($elements);

        echo $request->LOGIN->USER->data;
?>
demonpants at gmail dot com 22-Oct-2007 08:59
I wanted to access the ISBN database, and was previously parsing the HTML string generated from their main page, that is until I discovered they have an API that returns XML.

So, if anyone wants to get some information from the ISBN database, all you need to do is the following.

<?php
//Search the ISBN database for the book.
            $url = "http://www.isbndb.com/api/books.xml? access_key=KEY&index1=isbn&value1=$_GET[ISBN]";
            $p = xml_parser_create();
            xml_parse_into_struct($p,file_get_contents($url),$results,$index);
            xml_parser_free($p);

            $title = $results[$index[TITLELONG][0]][value];
            $author = $results[$index[AUTHORSTEXT][0]][value];
            $publisher = $results[$index[PUBLISHERTEXT][0]][value];
?>

You will need to get an access key from isbndb.com, but it takes two seconds and is free. When you get it, replace KEY in the URL with your own key. Also, my code above will search for the book that fits the ISBN number stored in the GET variable ISBN - you can search by other parameters and return more than one result, but my example is  for a simple ISBN search.
Zvjezdan Patz 09-Sep-2007 08:22
The problem I had was I needed to generate xml on the screen for users to actually see and copy to a file.

I'm generating the xml manually from a php file and the browser kept interpreting the xml...not very helpful.

This is how you get around it:

<?php

$file  = file_get_contents("http://example.com/xml.php?whatever=$whatever");
print nl2br(htmlentities($file));

?>

Prints all my xml quite nicely.
v9 at fakehalo dot us 13-Jul-2007 08:04
I needed this for work/personal use.  Sometimes you'll have a XML string generated as one long string and no line breaks...nusoap in the case of today/work, but there are any other number of possible things that will generate these.  Anyways, this simply takes a long XML string and returns an indented/line-breaked version of the string for display/readability.

<?php
function xmlIndent($str){
    $ret = "";
    $indent = 0;
    $indentInc = 3;
    $noIndent = false;
    while(($l = strpos($str,"<",$i))!==false){
        if($l!=$r && $indent>0){ $ret .= "\n" . str_repeat(" ",$indent) . substr($str,$r,($l-$r)); }
        $i = $l+1;
        $r = strpos($str,">",$i)+1;
        $t = substr($str,$l,($r-$l));
        if(strpos($t,"/")==1){
            $indent -= $indentInc;
            $noIndent = true;
        }
        else if(($r-$l-strpos($t,"/"))==2 || substr($t,0,2)=="<?"){ $noIndent = true; }
        if($indent<0){ $indent = 0; }
        if($ret){ $ret .= "\n"; }
        $ret .= str_repeat(" ",$indent);
        $ret .= $t;
        if(!$noIndent){ $indent += $indentInc; }
        $noIndent = false;
    }
    $ret .= "\n";
    return($ret);
}
?>

(...this was only tested for what i needed at work, could POSSIBLY need additions)
geoffers [at] gmail [dot] com 30-Dec-2006 03:27
Time to add my attempt at a very simple script that parses XML into a structure:

<?php

class Simple_Parser
{
    var $parser;
    var $error_code;
    var $error_string;
    var $current_line;
    var $current_column;
    var $data = array();
    var $datas = array();

    function parse($data)
    {
        $this->parser = xml_parser_create('UTF-8');
        xml_set_object($this->parser, $this);
        xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
        xml_set_element_handler($this->parser, 'tag_open', 'tag_close');
        xml_set_character_data_handler($this->parser, 'cdata');
        if (!xml_parse($this->parser, $data))
        {
            $this->data = array();
            $this->error_code = xml_get_error_code($this->parser);
            $this->error_string = xml_error_string($this->error_code);
            $this->current_line = xml_get_current_line_number($this->parser);
            $this->current_column = xml_get_current_column_number($this->parser);
        }
        else
        {
            $this->data = $this->data['child'];
        }
        xml_parser_free($this->parser);
    }

    function tag_open($parser, $tag, $attribs)
    {
        $this->data['child'][$tag][] = array('data' => '', 'attribs' => $attribs, 'child' => array());
        $this->datas[] =& $this->data;
        $this->data =& $this->data['child'][$tag][count($this->data['child'][$tag])-1];
    }

    function cdata($parser, $cdata)
    {
        $this->data['data'] .= $cdata;
    }

    function tag_close($parser, $tag)
    {
        $this->data =& $this->datas[count($this->datas)-1];
        array_pop($this->datas);
    }
}

$xml_parser = new Simple_Parser;
$xml_parser->parse('<foo><bar>test</bar></foo>');

?>
Didier: dlvb ** free * fr 24-Dec-2006 09:53
Hi !

After parsing the XML and modifying it, I just add a method to rebuild the XML form the internal structure (xmlp->document).
The method xmlp->toXML writes into xmlp->XML attributes. Then, you just have to output it.
I hope it helps.

<?php
class XMLParser {

var $parser;
var $filePath;
var $document;
var $currTag;
var $tagStack;
var $XML;
var $_tag_to_close = false;
var $TAG_ATTRIBUT = 'attr';
var $TAG_DATA = 'data';

function XMLParser($path) {
    $this->parser = xml_parser_create();
    $this->filePath = $path;
    $this->document = array();
    $this->currTag =& $this->document;
    $this->tagStack = array();
    $this->XML = "";
}

function parse() {
    xml_set_object($this->parser, $this);
    xml_set_character_data_handler($this->parser, 'dataHandler');
    xml_set_element_handler($this->parser, 'startHandler', 'endHandler');

   if(!($fp = fopen($this->filePath, "r"))) {
       die("Cannot open XML data file: $this->filePath");
       return false;
     }

    while($data = fread($fp, 4096)) {
        if(!xml_parse($this->parser, $data, feof($fp))) {
            die(sprintf("XML error: %s at line %d",
                xml_error_string(xml_get_error_code($this->parser)),
             xml_get_current_line_number($this->parser)));
      }
    }

    fclose($fp);
    xml_parser_free($this->parser);

    return true;
}

function startHandler($parser, $name, $attribs) {
     if(!isset($this->currTag[$name]))
          $this->currTag[$name] = array();

     $newTag = array();
     if(!empty($attribs))
          $newTag[$this->TAG_ATTRIBUT] = $attribs;
     array_push($this->currTag[$name], $newTag);

     $t =& $this->currTag[$name];
     $this->currTag =& $t[count($t)-1];
     array_push($this->tagStack, $name);
}

function dataHandler($parser, $data) {
    $data = trim($data);

    if(!empty($data)) {
      if(isset($this->currTag[$this->TAG_DATA]))
            $this->currTag[$this->TAG_DATA] .= $data;
      else
            $this->currTag[$this->TAG_DATA] = $data;
    }
}

function endHandler($parser, $name) {
     $this->currTag =& $this->document;
     array_pop($this->tagStack);

     for($i = 0; $i < count($this->tagStack); $i++) {
          $t =& $this->currTag[$this->tagStack[$i]];
          $this->currTag =& $t[count($t)-1];
     }
}

function clearOutput () {
    $this->XML = "";
}

function openTag ($tag) {
    $this->XML.="<".strtolower ($tag);
    $this->_tag_to_close = true;
}

function closeTag () {
    if ($this->_tag_to_close) {
        $this->XML.=">";
        $this->_tag_to_close = false;
    }
}

function closingTag ($tag) {
    $this->XML.="</".strtolower ($tag).">";
}

function output_attributes ($contenu_fils) {
    foreach ($contenu_fils[$this->TAG_ATTRIBUT] as $nomAttribut => $valeur) {
        $this->XML.= " ".strtolower($nomAttribut)."=\"".$valeur."\"";
    }
}

function addData ($texte) {
// to be completed
    $ca  = array ("é", "è", "ê", "à");
    $par = array ("&eacute;", "&egrave;", "&ecirc;", "agrave;");
    return htmlspecialchars(str_replace ($ca, $par, $texte), ENT_NOQUOTES);
}

function toXML ($tags="") {
    if ($tags=="") {
        $tags = $this->document;
      $this->clearOutput ();
    }

    foreach ($tags as $tag => $contenu) {
        $this->process ($tag, $contenu);
    }
}

function process ($tag, $contenu) {
     // Pour tous les TAGs
    foreach ($contenu as $indice => $contenu_fils) {
         $this->openTag ($tag);

         // Pour tous les fils (non attribut et non data)
         foreach ($contenu_fils as $tagFils => $fils) {
             switch ($tagFils) {
                 case $this->TAG_ATTRIBUT:
                         $this->output_attributes ($contenu_fils);
                        $this->closeTag ();
                         break;
                 case $this->TAG_DATA:
                        $this->closeTag ();
                         $this->XML.= $this->addData ($contenu_fils [$this->TAG_DATA]);
                         break;
                 default:
                         $this->closeTag ();
                         $this->process ($tagFils, $fils);
                         break;
             }
         }

        $this->closingTag ($tag);
    }
}

}
?>
forquan 28-Jan-2006 03:45
Here's code that will create an associative array from an xml file.  Keys are the tag data and subarrays are formed from attributes and child tags

<?php
$p =& new xmlParser();
$p->parse('/*xml file*/');
print_r($p->output);
?>

<?php
class xmlParser{
   var $xml_obj = null;
   var $output = array();
   var $attrs;

   function xmlParser(){
       $this->xml_obj = xml_parser_create();
       xml_set_object($this->xml_obj,$this);
       xml_set_character_data_handler($this->xml_obj, 'dataHandler');
       xml_set_element_handler($this->xml_obj, "startHandler", "endHandler");
   }

   function parse($path){
       if (!($fp = fopen($path, "r"))) {
           die("Cannot open XML data file: $path");
           return false;
       }

       while ($data = fread($fp, 4096)) {
           if (!xml_parse($this->xml_obj, $data, feof($fp))) {
               die(sprintf("XML error: %s at line %d",
               xml_error_string(xml_get_error_code($this->xml_obj)),
               xml_get_current_line_number($this->xml_obj)));
               xml_parser_free($this->xml_obj);
           }
       }

       return true;
   }

   function startHandler($parser, $name, $attribs){
       $_content = array();
       if(!empty($attribs))
         $_content['attrs'] = $attribs;
       array_push($this->output, $_content);
   }

   function dataHandler($parser, $data){
       if(!empty($data) && $data!="\n") {
           $_output_idx = count($this->output) - 1;
           $this->output[$_output_idx]['content'] .= $data;
       }
   }

   function endHandler($parser, $name){
       if(count($this->output) > 1) {
           $_data = array_pop($this->output);
           $_output_idx = count($this->output) - 1;
           $add = array();
           if ($_data['attrs'])
                $add['attrs'] = $_data['attrs'];
           if ($_data['child'])
                $add['child'] = $_data['child'];
           $this->output[$_output_idx]['child'][$_data['content']] = $add;
       }
   }
}
?>
Greg S 17-Nov-2005 08:56
If you need utf8_encode support and configure PHP with --disable-all you will have some trouble. Unfortunately the configure options aren't completely documented. If you need utf8 functions and have everything disabled just recompile PHP with --enable-xml and you should be good to go.
compu_global_hyper_mega_net_2 at yahoo dot com 19-Sep-2004 01:35
The documentation regarding white space was never complete I think.

The XML_OPTION_SKIP_WHITE doesn't appear to do anything.  I want to preserve the newlines in a cdata section.  Setting XML_OPTION_SKIP_WHITE to 0 or false doesn't appear to help.  My character_data_handler is getting called once for each line.  This obviously should be reflected in the documentation as well.  When/how often does the handler get called exactly?  Having to build separate test cases is very time consuming.

Inserting newlines myself in my cdata handler is no good either.  For non actual CDATA sections that cause my handler to get called, long lines are split up in multiple calls.  My handler would not be able to tell the difference whether or not the subsequent calls would be due to the fact that the data is coming from the next line or the fact that some internal buffer is long enough for it to 'flush' out and call the handler.
This behaviour also needs to be properly documented.
odders 18-Mar-2004 10:36
I wrote a simple xml parser mainly to deal with rss version 2. I found lots of examples on the net, but they were all masive and bloated and hard to manipulate.

Output is sent to an array, which holds arrays containg data for each item.

Obviously, you will have to make modifications to the code to suit your needs, but there isnt a lot of code there, so that shouldnt be a problem.

<?php

   $currentElements = array();
   $newsArray = array();

   readXml("./news.xml");

   echo("<pre>");
   print_r($newsArray);
   echo("</pre>");

   // Reads XML file into formatted html
   function readXML($xmlFile)
   {

      $xmlParser = xml_parser_create();

      xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, false);
      xml_set_element_handler($xmlParser, startElement, endElement);
      xml_set_character_data_handler($xmlParser, characterData);

      $fp = fopen($xmlFile, "r");

      while($data = fread($fp, filesize($xmlFile))){
         xml_parse($xmlParser, $data, feof($fp));}

      xml_parser_free($xmlParser);

   }

   // Sets the current XML element, and pushes itself onto the element hierarchy
   function startElement($parser, $name, $attrs)
   {

      global $currentElements, $itemCount;

      array_push($currentElements, $name);

      if($name == "item"){$itemCount += 1;}

   }

   // Prints XML data; finds highlights and links
   function characterData($parser, $data)
   {

      global $currentElements, $newsArray, $itemCount;

      $currentCount = count($currentElements);
      $parentElement = $currentElements[$currentCount-2];
      $thisElement = $currentElements[$currentCount-1];

      if($parentElement == "item"){
         $newsArray[$itemCount-1][$thisElement] = $data;}
      else{
         switch($name){
            case "title":
               break;
            case "link":
               break;
            case "description":
               break;
            case "language":
               break;
            case "item":
               break;}}

   }

   // If the XML element has ended, it is poped off the hierarchy
   function endElement($parser, $name)
   {

      global $currentElements;

      $currentCount = count($currentElements);
      if($currentElements[$currentCount-1] == $name){
         array_pop($currentElements);}

   }

?>
software at serv-a-com dot com 22-Jan-2003 02:08
use:

<?php
while ($data = str_replace("\n","",fread($fp, 4096))){
 // ...
}
?>

instead of:

<?php
while ($data = fread($fp, 4096)) {
  // ...
}
?>

[UPDATE 17-FEB-2003: This post] resulted in some of the visitors e-mailg me on the carriage return stripping issue with questions. I'll try to make the following mumble as brief and easy to understand as possible.

1. Overview of the 4096 fragmentation issue
As you know the following freads the file 4096 bytes at a time (that is 4KB) this is perhaps ok for testing expat and figuring out how things work, but it it rather dangerous in the production environment. Data may not be fully understandable due to fread fragmentation and improperly formatted due to numerous sources(formats) of data contained within (i.e. end of line delimited CDATA).

<?php
while ($data = fread($fp, 4096)) {
  if (!xml_parse($xml_parser, $data, feof($fp))) {
    // ...
  }
}
?>

Sometimes to save time one may want to load it all up into a one big variable and leave all the worries to expat. I think anything under 500 KB is ok (as long as nobody knows about it). Some may argue that larger variables are acceptable or even necessary because of the magic that take place while parsing using xml_parse. Our XML parser(expat) works and can be successfully implemented only when we know what type of XML data we are dealing with, it's average size and structure of general layout and data contained within tags. For example if the tags are followed by a line delimiter like a new line we can read it with fgets in and with minimal effort make sure that no data will be sent to the function that does not end with a end tag. But this require a fair knowledge of the file's preference for storing XML data and tags (and a bit of code between reading data and xml_parse'ing it).
It will save you a headache.

2. Pre Parser Strings and New Line Delimited Data
One important thing to note at this point is that the xml_parse function requires a string variable. You can manipulate the content of any string variable easily as we all know.

A better approach to removing newlines than:

<?php
while ($data = fread($fp, 4096)) {
$data = preg_replace("/\n|\r/","",$data); //flarp
if (!xml_parse($xml_parser, $data, feof($fp))) {...
?>

Above works across all 3 line-delimited text files  (\n, \r, \r\n). But this could potentially (or will most likely) damage or scramble data contained in for example CDATA areas. As far as I am concerned end of line characters should not be used _within_ XML tags. What seems to be the ultimate solution is to pre-parse the loaded data this would require checking the position within the XML document and adding or subtracting (using a in-between fread temporary variable) data based on conditions like: "Is within tag", "Is within CDATA" etc. before fedding it to the parser. This of course opens up a new can of worms (as in parse data for the parser...). (above procedure would take place between fread and xml_parser calls this method would be compatible with the general usage examples on top of the page)

3. The Answer to parsing arbitrary XML and Preprocessor Revisited
You can't just feed any XML document to the parser you constructed and assuming that it will work! You have to know what kind of methods for storing data are used, for example is there a end of line delimited data in the  file ?, Are there any carriage returns in the tags etc... XML files come formatted in different ways some are just a one long string of characters with out any end of line markers others have newlines, carriage returns or both (Microsloth Windows). May or may not contain space and other whitespace between tags. For this reason it is important to what I call Normalize the data before feeding it to the parser. You can perform this with regular expressions or plain old str_replace and concatenation. In many cases this can be done to the file it self sometimes to string data on the fly( as shown in the example above). But I feel it is important to normalize the data before even calling the function to call xml_parse. If you have the ability to access all data before that call you can convert it to what you fell the data should have been in the first place and omit many surprises and expensive regular expression substitution (in a tight spot) while fread'ing the data.
guy at bhaktiandvedanta dot com 27-Sep-2002 12:01
For a simple XML parser you can use this function. It doesn't require any extensions to run.

<?php
// Extracts content from XML tag

function GetElementByName ($xml, $start, $end) {

    global $pos;
    $startpos = strpos($xml, $start);
    if ($startpos === false) {
        return false;
    }
    $endpos = strpos($xml, $end);
    $endpos = $endpos+strlen($end);
    $pos = $endpos;
    $endpos = $endpos-$startpos;
    $endpos = $endpos - strlen($end);
    $tag = substr ($xml, $startpos, $endpos);
    $tag = substr ($tag, strlen($start));

    return $tag;

}

// Open and read xml file. You can replace this with your xml data.

$file = "data.xml";
$pos = 0;
$Nodes = array();

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}
while ($getline = fread($fp, 4096)) {
    $data = $data . $getline;
}

$count = 0;
$pos = 0;

// Goes throw XML file and creates an array of all <XML_TAG> tags.
while ($node = GetElementByName($data, "<XML_TAG>", "</XML_TAG>")) {
    $Nodes[$count] = $node;
    $count++;
    $data = substr($data, $pos);
}

// Gets infomation from tag siblings.
for ($i=0; $i<$count; $i++) {
$code = GetElementByName($Nodes[$i], "<Code>", "</Code>");
$desc = GetElementByName($Nodes[$i], "<Description>", "</Description>");
$price = GetElementByName($Nodes[$i], "<BasePrice>", "</BasePrice>");
}
?>

Hope this helps! :)
Guy Laor
dmarsh dot NO dot SPAM dot PLEASE at spscc dot ctc dot edu 18-Sep-2002 12:27
Some reference code I am working on as "XML Library" of which I am folding it info an object. Notice the use of the DEFINE:

Mainly Example 1 and parts of 2 & 3 re-written as an object:
--- MyXMLWalk.lib.php ---
<?php

if (!defined("PHPXMLWalk")) {
define("PHPXMLWalk",TRUE);

class XMLWalk {
 var $p; //short for xml parser;
 var $e; //short for element stack/array

  function prl($x,$i=0) {
    ob_start();
    print_r($x);
    $buf=ob_get_contents();
    ob_end_clean();
    return join("\n".str_repeat(" ",$i),split("\n",$buf));
  }

 function XMLWalk() {
  $this->p = xml_parser_create();
  $this->e = array();
  xml_parser_set_option($this->p, XML_OPTION_CASE_FOLDING, true);
  xml_set_element_handler($this->p, array(&$this, "startElement"), array(&$this, "endElement"));
  xml_set_character_data_handler($this->p, array(&$this, "dataElement"));
  register_shutdown_function(array(&$this, "free")); // make a destructor
  }

  function startElement($parser, $name, $attrs) {
    if (count($attrs)>=1) {
      $x = $this->prl($attrs, $this->e[$parser]+6);
    } else {
      $x = "";
    }

    print str_repeat(" ",$this->e[$parser]+0). "$name $x\n";
    $this->e[$parser]++;
    $this->e[$parser]++;
  }

  function dataElement($parser, $data) {
    print str_repeat(" ",$this->e[$parser]+0). htmlspecialchars($data, ENT_QUOTES) ."\n";
  }

  function endElement($parser, $name) {
    $this->e[$parser]--;
    $this->e[$parser]--;
  }
  function parse($data, $fp) {
    if (!xml_parse($this->p, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($this->p)),
                    xml_get_current_line_number($this->p)));
    }
  }

  function free() {
    xml_parser_free($this->p);
  }

} // end of class

} // end of define

?>

--- end of file ---

Calling code:
<?php

...

require("MyXMLWalk.lib.php");

$file = "x.xml";

$xme = new XMLWalk;

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
  $xme->parse($data, $fp);
}

...
?>
jon at gettys dot org 14-Aug-2002 01:59
[Editor's note: see also xml_parse_into_struct().]

Very simple routine to convert an XML file into a PHP structure. $obj->xml contains the resulting PHP structure. I would be interested if someone could suggest a cleaner method than the evals I am using.

<?php
$filename = 'sample.xml';
$obj->tree = '$obj->xml';
$obj->xml = '';

function startElement($parser, $name, $attrs) {
    global $obj;

    // If var already defined, make array
    eval('$test=isset('.$obj->tree.'->'.$name.');');
    if ($test) {
      eval('$tmp='.$obj->tree.'->'.$name.';');
      eval('$arr=is_array('.$obj->tree.'->'.$name.');');
      if (!$arr) {
        eval('unset('.$obj->tree.'->'.$name.');');
        eval($obj->tree.'->'.$name.'[0]=$tmp;');
        $cnt = 1;
      }
      else {
        eval('$cnt=count('.$obj->tree.'->'.$name.');');
      }

      $obj->tree .= '->'.$name."[$cnt]";
    }
    else {
      $obj->tree .= '->'.$name;
    }
    if (count($attrs)) {
        eval($obj->tree.'->attr=$attrs;');
    }
}

function endElement($parser, $name) {
    global $obj;
    // Strip off last ->
    for($a=strlen($obj->tree);$a>0;$a--) {
        if (substr($obj->tree, $a, 2) == '->') {
            $obj->tree = substr($obj->tree, 0, $a);
            break;
        }
    }
}

function characterData($parser, $data) {
    global $obj;

    eval($obj->tree.'->data=\''.$data.'\';');
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($filename, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
print_r($obj->xml);
return 0;

?>
hans dot schneider at bbdo-interone dot de 24-Jan-2002 08:43
I had to TRIM the data when I passed one large String containig a wellformed XML-File to xml_parse. The String was read by CURL, which aparently put a BLANK at the end of the String. This BLANK produced a "XML not wellformed"-Error in xml_parse!
sam at cwa dot co dot nz 28-Sep-2000 07:39
I've discovered some unusual behaviour in this API when ampersand entities are parsed in cdata; for some reason the parser breaks up the section around the entities, and calls the handler repeated times for each of the sections. If you don't allow for this oddity and you are trying to put the cdata into a variable, only the last part will be stored.

You can get around this with a line like:

$foo .= $cdata;

If the handler is called several times from the same tag, it will append them, rather than rewriting the variable each time. If the entire cdata section is returned, it doesn't matter.

May happen for other entities, but I haven't investigated.

Took me a while to figure out what was happening; hope this saves someone else the trouble.
Daniel dot Rendall at btinternet dot com 07-Jul-1999 10:21
When using the XML parser, make sure you're not using the magic quotes option (e.g. use set_magic_quotes_runtime(0) if it's not the compiled default), otherwise you'll get 'not well-formed' errors when dealing with tags with attributes set in them.


Convierte una cadena con los caracteres codificados ISO-8859-1 con UTF-8 a un sencillo byte ISO-8859-1

  • « Funciones del Intérprete XML
  • utf8_encode »
  • PHP Manual
  • Funciones del Intérprete XML
  • Convierte una cadena con los caracteres codificados ISO-8859-1 con UTF-8 a un sencillo byte ISO-8859-1

utf8_decode

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

utf8_decode — Convierte una cadena con los caracteres codificados ISO-8859-1 con UTF-8 a un sencillo byte ISO-8859-1

Descripción

utf8_decode ( string $data ) : string

Ésta función decodifica los data, asumidos a ser codificados por UTF-8, a ISO-8859-1.

Parámetros

data

Una cadena codificada UTF-8.

Valores devueltos

Devuelve la traducción ISO-8859-1 de los data.

Ver también

  • utf8_encode() - Codifica un string ISO-8859-1 a UTF-8 (contiene una explicación de la codificación UTF-8)

User Contributed Notes

Aleksandr 30-Jun-2017 02:46
In addition to note by yannikh at gmeil dot com, another way to decode strings with non-latin chars from unix console like

C=RU, L=\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0,

<?php preg_replace_callback('/\\\\x([0-9A-F]{2})/', function($a){ return pack('H*', $a[1]); }, $str); ?>

The code above will output:
C=RU, L=??????,
kode68 02-May-2016 06:09
Update Answer from okx dot oliver dot koenig at gmail dot com for PHP 5.6 since e/ modifier is depreciated

// This finally helped me to do the job, thanks to Blackbit, had to modify deprecated ereg:
// original comment: "Squirrelmail contains a nice function in the sources to convert unicode to entities:"

function charset_decode_utf_8($string)
    {
        /* Only do the slow convert if there are 8-bit characters */
        if ( !preg_match("/[\200-\237]/", $string) && !preg_match("/[\241-\377]/", $string) )
               return $string;

        // decode three byte unicode characters
          $string = preg_replace_callback("/([\340-\357])([\200-\277])([\200-\277])/",
                    create_function ('$matches', 'return \'&#\'.((ord($matches[1])-224)*4096+(ord($matches[2])-128)*64+(ord($matches[3])-128)).\';\';'),
                    $string);

        // decode two byte unicode characters
          $string = preg_replace_callback("/([\300-\337])([\200-\277])/",
                    create_function ('$matches', 'return \'&#\'.((ord($matches[1])-192)*64+(ord($matches[2])-128)).\';\';'),
                    $string);

        return $string;
    }

Enjoy
okx dot oliver dot koenig at gmail dot com 08-Feb-2015 11:48
// This finally helped me to do the job, thanks to Blackbit, had to modify deprecated ereg:
// original comment: "Squirrelmail contains a nice function in the sources to convert unicode to entities:"

function charset_decode_utf_8 ($string) {
    /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (!preg_match("/[\200-\237]/", $string)
     && !preg_match("/[\241-\377]/", $string)
    ) {
        return $string;
    }

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",
        "'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",
        $string
    );

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e",
        "'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'",
        $string
    );

    return $string;
}
sashott at gmail dot com 04-Dec-2014 11:57
Use of utf8_decode was not enough for me by get page content from another site. Problem appear by different alphabet from standard latin. As example some chars (corresponding to HTML codes &bdquo; , &nbsp; and others) are converted to "?" or "xA0" (hex value). You need to make some conversion before execute utf8_decode. And you can not replace simple, that they can be part of 2 bytes code for a char (UTF-8 use 2 bytes). Next is for cyrillic alphabet, but for other must be very close.

function convertMethod($text){
    //Problem is that utf8_decode convert HTML chars for &bdquo; and other to ? or &nbsp; to \xA0. And you can not replace, that they are in some char bytes and you broke cyrillic (or other alphabet) chars.
    $problem_enc=array(
        'euro',
        'sbquo',
        'bdquo',
        'hellip',
        'dagger',
        'Dagger',
        'permil',
        'lsaquo',
        'lsquo',
        'rsquo',
        'ldquo',
        'rdquo',
        'bull',
        'ndash',
        'mdash',
        'trade',
        'rsquo',
        'brvbar',
        'copy',
        'laquo',
        'reg',
        'plusmn',
        'micro',
        'para',
        'middot',
        'raquo',
        'nbsp'
    );
    $text=mb_convert_encoding($text,'HTML-ENTITIES','UTF-8');
    $text=preg_replace('#(?<!\&ETH;)\&('.implode('|',$problem_enc).');#s','--amp{$1}',$text);
    $text=mb_convert_encoding($text,'UTF-8','HTML-ENTITIES');
    $text=utf8_decode($text);
    $text=mb_convert_encoding($text,'HTML-ENTITIES','UTF-8');
    $text=preg_replace('#\-\-amp\{([^\}]+)\}#su','&$1;',$text);
    $text=mb_convert_encoding($text,'UTF-8','HTML-ENTITIES');
    return $text;
}

If this don't work, try to set "die($text);" on some places to look, what is happen to this row. Is better to test with long text. It is very possible to broke other alphabet character. In this case, it is very possible, that for you alphabet set "&ETH;" is not the right one. You need to set "die($text);" after this preg_replace and look HTML code for character before set "--amp".
christoffer 29-Oct-2012 10:35
The preferred way to use this on an array would be with the built in PHP function "array_map()", as for example:
$array = array_map("utf8_decode", $array);
deceze at gmail dot com 14-Jul-2011 07:01
Please note that utf8_decode simply converts a string encoded in UTF-8 to ISO-8859-1. A more appropriate name for it would be utf8_to_iso88591. If your text is already encoded in ISO-8859-1, you do not need this function. If you don't want to use ISO-8859-1, you do not need this function.

Note that UTF-8 can represent many more characters than ISO-8859-1. Trying to convert a UTF-8 string that contains characters that can't be represented in ISO-8859-1 to ISO-8859-1 will garble your text and/or cause characters to go missing. Trying to convert text that is not encoded in UTF-8 using this function will most likely garble the text.

If you need to convert any text from any encoding to any other encoding, look at iconv() instead.
gabriel arobase gabsoftware dot com 12-Jun-2011 08:41
If you want to retrieve some UTF-8 data from your database, you don't need utf8_decode().

Simply do the following query before any SELECT :

$result = mysql_query("SET NAMES utf8");
info at vanylla dot it 26-Jan-2009 12:21
IMPORTANT: when converting UTF8 data that contains the EURO sign DON'T USE utf_decode function.

utf_decode converts the data into ISO-8859-1 charset. But ISO-8859-1 charset does not contain the EURO sign, therefor the EURO sign will be converted into a question mark character '?'

In order to convert properly UTF8 data with EURO sign you must use:

iconv("UTF-8", "CP1252", $data)
Blackbit 12-Aug-2008 04:40
Squirrelmail contains a nice function in the sources to convert unicode to entities:

<?php
function charset_decode_utf_8 ($string) {
      /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (! ereg("[\200-\237]", $string) and ! ereg("[\241-\377]", $string))
        return $string;

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",        \
    "'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",    \
    $string);

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e", \
    "'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'", \
    $string);

    return $string;
}
?>
punchivan at gmail dot com 24-Jun-2008 02:13
EY! the bug is not in the function 'utf8_decode'. The bug is in the function 'mb_detect_encoding'. If you put a word with a special char at the end like this 'accentué', that will lead to a wrong result (UTF-8) but if you put another char at the end like this 'accentuée' you will get it right. So you should always add a ISO-8859-1 character to your string for this check. My advise is to use a blank space.
I´ve tried it and it works!

function ISO_convert($array)
{
    $array_temp = array();

    foreach($array as $name => $value)
    {
        if(is_array($value))
          $array_temp[(mb_detect_encoding($name." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($name) : $name )] = ISO_convert($value);
        else
          $array_temp[(mb_detect_encoding($name." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($name) : $name )] = (mb_detect_encoding($value." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($value) : $value );
    }

    return $array_temp;
}
haugas at gmail dot com 08-May-2008 02:11
If you don't know exactly, how many times your string is encoded, you can use this function:

<?php

function _utf8_decode($string)
{
  $tmp = $string;
  $count = 0;
  while (mb_detect_encoding($tmp)=="UTF-8")
  {
    $tmp = utf8_decode($tmp);
    $count++;
  }

  for ($i = 0; $i < $count-1 ; $i++)
  {
    $string = utf8_decode($string);

  }
  return $string;

}

?>
lukasz dot mlodzik at gmail dot com 05-Mar-2008 04:46
Update to MARC13 function utf2iso()
I'm using it to handle AJAX POST calls.
Despite using
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'; charset='utf-8');
it still code Polish letters using UTF-16

This is only for Polish letters:

<?php
function utf16_2_utf8 ($nowytekst) {
        $nowytekst = str_replace('%u0104','A',$nowytekst);    //A
        $nowytekst = str_replace('%u0106','C',$nowytekst);    //C
        $nowytekst = str_replace('%u0118','E',$nowytekst);    //E
        $nowytekst = str_replace('%u0141','L',$nowytekst);    //L
        $nowytekst = str_replace('%u0143','N',$nowytekst);    //N
        $nowytekst = str_replace('%u00D3','Ó',$nowytekst);    //Ó
        $nowytekst = str_replace('%u015A','S',$nowytekst);    //S
        $nowytekst = str_replace('%u0179','Z',$nowytekst);    //Z
        $nowytekst = str_replace('%u017B','Z',$nowytekst);    //Z

        $nowytekst = str_replace('%u0105','a',$nowytekst);    //a
        $nowytekst = str_replace('%u0107','c',$nowytekst);    //c
        $nowytekst = str_replace('%u0119','e',$nowytekst);    //e
        $nowytekst = str_replace('%u0142','l',$nowytekst);    //l
        $nowytekst = str_replace('%u0144','n',$nowytekst);    //n
        $nowytekst = str_replace('%u00F3','ó',$nowytekst);    //ó
        $nowytekst = str_replace('%u015B','s',$nowytekst);    //s
        $nowytekst = str_replace('%u017A','z',$nowytekst);    //z
        $nowytekst = str_replace('%u017C','z',$nowytekst);    //z
   return ($nowytekst);
   }
?>

Everything goes smooth, but it doesn't change '%u00D3','Ó' and '%u00F3','ó'. I dont have idea what to do with that.

Remember! File must be saved in UTF-8 coding.
ludvig dot ericson at gmail dot com 15-Jul-2007 10:52
A better way to convert would be to use iconv, see http://www.php.net/iconv -- example:

<?php
$myUnicodeString = "Åäö";
echo iconv("UTF-8", "ISO-8859-1", $myUnicodeString);
?>

Above would echo out the given variable in ISO-8859-1 encoding, you may replace it with whatever you prefer.

Another solution to the issue of misdisplayed glyphs is to simply send the document as UTF-8, and of course send UTF-8 data:

<?php
# Replace text/html with whatever MIME-type you prefer.
header("Content-Type: text/html; CHARSET=Windows-1252");
?>
MARC13 07-Jul-2007 07:50
I did this function to convert data from AJAX call to insert to my database.
It converts UTF-8 from XMLHttpRequest() to ISO-8859-2 that I use in LATIN2 MySQL database.

<?php
function utf2iso($tekst)
{
        $nowytekst = str_replace("%u0104","\xA1",$tekst);    //A
        $nowytekst = str_replace("%u0106","\xC6",$nowytekst);    //C
        $nowytekst = str_replace("%u0118","\xCA",$nowytekst);    //E
        $nowytekst = str_replace("%u0141","\xA3",$nowytekst);    //L
        $nowytekst = str_replace("%u0143","\xD1",$nowytekst);    //N
        $nowytekst = str_replace("%u00D3","\xD3",$nowytekst);    //Ó
        $nowytekst = str_replace("%u015A","\xA6",$nowytekst);    //S
        $nowytekst = str_replace("%u0179","\xAC",$nowytekst);    //Z
        $nowytekst = str_replace("%u017B","\xAF",$nowytekst);    //Z

        $nowytekst = str_replace("%u0105","\xB1",$nowytekst);    //a
        $nowytekst = str_replace("%u0107","\xE6",$nowytekst);    //c
        $nowytekst = str_replace("%u0119","\xEA",$nowytekst);    //e
        $nowytekst = str_replace("%u0142","\xB3",$nowytekst);    //l
        $nowytekst = str_replace("%u0144","\xF1",$nowytekst);    //n
        $nowytekst = str_replace("%u00D4","\xF3",$nowytekst);    //ó
        $nowytekst = str_replace("%u015B","\xB6",$nowytekst);    //s
        $nowytekst = str_replace("%u017A","\xBC",$nowytekst);    //z
        $nowytekst = str_replace("%u017C","\xBF",$nowytekst);    //z

    return ($nowytekst);
}
?>

In my case also the code file that deals with AJAX calls must be in UTF-8 coding.
visus at portsonline dot net 23-Jun-2007 09:08
Following code helped me with mixed (UTF8+ISO-8859-1(x)) encodings. In this case, I have template files made and maintained by designers who do not care about encoding and MySQL data in utf8_binary_ci encoded tables.

<?php

class Helper
{
    function strSplit($text, $split = 1)
    {
        if (!is_string($text)) return false;
        if (!is_numeric($split) && $split < 1) return false;

        $len = strlen($text);

        $array = array();

        $i = 0;

        while ($i < $len)
        {
            $key = NULL;

            for ($j = 0; $j < $split; $j += 1)
            {
                $key .= $text{$i};

                $i += 1;
            }

            $array[] = $key;
        }

        return $array;
    }

    function UTF8ToHTML($str)
    {
        $search = array();
        $search[] = "/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e";
        $search[] = "/&#228;/";
        $search[] = "/&#246;/";
        $search[] = "/&#252;/";
        $search[] = "/&#196;/";
        $search[] = "/&#214;/";
        $search[] = "/&#220;/";
        $search[] = "/&#223;/";

        $replace = array();
        $replace[] = 'Helper::_UTF8ToHTML("\\1")';
        $replace[] = "ä";
        $replace[] = "ö";
        $replace[] = "ü";
        $replace[] = "Ä";
        $replace[] = "Ö";
        $replace[] = "ü";
        $replace[] = "ß";

        $str = preg_replace($search, $replace, $str);

        return $str;
    }

    function _UTF8ToHTML($str)
    {
        $ret = 0;

        foreach((Helper::strSplit(strrev(chr((ord($str{0}) % 252 % 248 % 240 % 224 % 192) + 128).substr($str, 1)))) as $k => $v)
            $ret += (ord($v) % 128) * pow(64, $k);
        return "&#".$ret.";";
    }
}

// Usage example:

$tpl = file_get_contents("template.tpl");
/* ... */
$row = mysql_fetch_assoc($result);

print(Helper::UTF8ToHTML(str_replace("{VAR}", $row['var'], $tpl)));

?>
luka8088 at gmail dot com 22-Jun-2007 07:03
simple UTF-8 to HTML conversion:

function utf8_to_html ($data)
    {
    return preg_replace("/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e", '_utf8_to_html("\\1")', $data);
    }

function _utf8_to_html ($data)
    {
    $ret = 0;
    foreach((str_split(strrev(chr((ord($data{0}) % 252 % 248 % 240 % 224 % 192) + 128) . substr($data, 1)))) as $k => $v)
        $ret += (ord($v) % 128) * pow(64, $k);
    return "&#$ret;";
    }

Example:
echo utf8_to_html("a b c c ž ? ? ? ? ()[]{}!#$?*");

Output:
a b &#269; &#263; &#382; &#12371; &#12395; &#12385; &#12431; ()[]{}!#$?*
Sadi 13-Jun-2007 03:38
Once again about polish letters. If you use fananf's solution, make sure that PHP file is coded with cp1250 or else it won't work. It's quite obvious, however I spent some time before I finally figured that out, so I thought I post it here.
alexlevin at kvadro dot net 20-May-2007 08:20
If you running Gentoo Linux and encounter problems with some PHP4 applications saying:
Call to undefined function: utf8_decode()
Try reemerge PHP4 with 'expat' flag enabled.
sam 06-Feb-2007 08:20
In addition to yannikh's note, to convert a hex utf8 string

<?php

echo utf8_decode("\x61\xc3\xb6\x61");
// works as expected

$abc="61c3b661";
$newstr = "";
$l = strlen($abc);
for ($i=0;$i<$l;$i+=2){
    $newstr .= "\x".$abc[$i].$abc[$i+1];
}
echo utf8_decode($newstr);
// or varieties  of "\x": "\\x" etc does NOT output what you want

echo utf8_decode(pack('H*',$abc));
// this outputs the correct string, like the first line.

?>
Ajgor 28-Dec-2006 05:38
small upgrade for polish decoding:

function utf82iso88592($text) {
 $text = str_replace("\xC4\x85", 'a', $text);
 $text = str_replace("\xC4\x84", 'A', $text);
 $text = str_replace("\xC4\x87", 'c', $text);
 $text = str_replace("\xC4\x86", 'C', $text);
 $text = str_replace("\xC4\x99", 'e', $text);
 $text = str_replace("\xC4\x98", 'E', $text);
 $text = str_replace("\xC5\x82", 'l', $text);
 $text = str_replace("\xC5\x81", 'L', $text);
 $text = str_replace("\xC3\xB3", 'ó', $text);
 $text = str_replace("\xC3\x93", 'Ó', $text);
 $text = str_replace("\xC5\x9B", 's', $text);
 $text = str_replace("\xC5\x9A", 'S', $text);
 $text = str_replace("\xC5\xBC", 'z', $text);
 $text = str_replace("\xC5\xBB", 'Z', $text);
 $text = str_replace("\xC5\xBA", 'z', $text);
 $text = str_replace("\xC5\xB9", 'Z', $text);
 $text = str_replace("\xc5\x84", 'n', $text);
 $text = str_replace("\xc5\x83", 'N', $text);

return $text;
} // utf82iso88592
paul.hayes at entropedia.co.uk 27-Oct-2006 07:10
I noticed that the utf-8 to html functions below are only for 2 byte long codes. Well I wanted 3 byte support (sorry haven't done 4, 5 or 6). Also I noticed the concatination of the character codes did have the hex prefix 0x and so failed with the large 2 byte codes)

<?
  public function utf2html (&$str) {

    $ret = "";
    $max = strlen($str);
    $last = 0;  // keeps the index of the last regular character
    for ($i=0; $i<$max; $i++) {
        $c = $str{$i};
        $c1 = ord($c);
        if ($c1>>5 == 6) {  // 110x xxxx, 110 prefix for 2 bytes unicode
            $ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
            $c1 &= 31; // remove the 3 bit two bytes prefix
            $c2 = ord($str{++$i}); // the next byte
            $c2 &= 63;  // remove the 2 bit trailing byte prefix
            $c2 |= (($c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
            $c1 >>= 2; // c1 shifts 2 to the right
            $ret .= "&#" . ($c1 * 0x100 + $c2) . ";"; // this is the fastest string concatenation
            $last = $i+1;
        }
        elseif ($c1>>4 == 14) {  // 1110 xxxx, 110 prefix for 3 bytes unicode
            $ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
            $c2 = ord($str{++$i}); // the next byte
            $c3 = ord($str{++$i}); // the third byte
            $c1 &= 15; // remove the 4 bit three bytes prefix
            $c2 &= 63;  // remove the 2 bit trailing byte prefix
            $c3 &= 63;  // remove the 2 bit trailing byte prefix
            $c3 |= (($c2 & 3) << 6); // last 2 bits of c2 become first 2 of c3
            $c2 >>=2; //c2 shifts 2 to the right
            $c2 |= (($c1 & 15) << 4); // last 4 bits of c1 become first 4 of c2
            $c1 >>= 4; // c1 shifts 4 to the right
            $ret .= '&#' . (($c1 * 0x10000) + ($c2 * 0x100) + $c3) . ';'; // this is the fastest string concatenation
            $last = $i+1;
        }
    }
    $str=$ret . substr($str, $last, $i); // append the last batch of regular characters
}
?>
tobias at code-x dot de 20-Oct-2006 05:13
converting uft8-html sign &#301; to uft8

<?
function uft8html2utf8( $s ) {
        if ( !function_exists('uft8html2utf8_callback') ) {
             function uft8html2utf8_callback($t) {
                     $dec = $t[1];
            if ($dec < 128) {
              $utf = chr($dec);
            } else if ($dec < 2048) {
              $utf = chr(192 + (($dec - ($dec % 64)) / 64));
              $utf .= chr(128 + ($dec % 64));
            } else {
              $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
              $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
              $utf .= chr(128 + ($dec % 64));
            }
            return $utf;
             }
        }
        return preg_replace_callback('|&#([0-9]{1,});|', 'uft8html2utf8_callback', $s );
}
echo uft8html2utf8('test: &#301;');
?>
2ge at NO2geSPAM dot us 26-Jan-2006 01:00
Hello all,

I like to use COOL (nice) URIs, example: http://example.com/try-something
I'm using UTF8 as input, so I have to write a function UTF8toASCII to have nice URI. Here is what I come with:

<?php
function urlize($url) {
 $search = array('/[^a-z0-9]/', '/--+/', '/^-+/', '/-+$/' );
 $replace = array( '-', '-', '', '');
 return preg_replace($search, $replace, utf2ascii($url));
}

function utf2ascii($string) {
 $iso88591  = "\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7";
 $iso88591 .= "\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF";
 $iso88591 .= "\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF7";
 $iso88591 .= "\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xFF";
 $ascii = "aaaaaaaceeeeiiiidnooooooouuuuyyy";
 return strtr(mb_strtolower(utf8_decode($string), 'ISO-8859-1'),$iso88591,$ascii);
}

echo urlize("Fucking ?m?l");

?>

I hope this helps someone.
php-net at ---NOSPAM---lc dot yi dot org 08-Dec-2005 12:04
I've just created this code snippet to improve the user-customizable emails sent by one of my websites.

The goal was to use UTF-8 (Unicode) so that non-english users have all the Unicode benefits, BUT also make life seamless for English (or specifically, English MS-Outlook users).  The niggle: Outlook prior to 2003 (?)  does not properly detect unicode emails.  When "smart quotes" from MS Word were pasted into a rich text area and saved in Unicode, then sent by email to an Outlook user, more often than not, these characters were wrongly rendered as "greek".

So, the following code snippet replaces a few strategic characters into html entities which Outlook XP (and possibly earlier) will render as expected.  [Code based on bits of code from previous posts on this and the htmlenties page]
<?php
    $badwordchars=array(
        "\xe2\x80\x98", // left single quote
        "\xe2\x80\x99", // right single quote
        "\xe2\x80\x9c", // left double quote
        "\xe2\x80\x9d", // right double quote
        "\xe2\x80\x94", // em dash
        "\xe2\x80\xa6" // elipses
    );
    $fixedwordchars=array(
        "&#8216;",
        "&#8217;",
        '&#8220;',
        '&#8221;',
        '&mdash;',
        '&#8230;'
    );
    $html=str_replace($badwordchars,$fixedwordchars,$html);
?>
yannikh at gmeil dot com 07-Dec-2005 11:34
I had to tackle a very interesting problem:

I wanted to replace all \xXX in a text by it's letters. Unfortunatelly XX were ASCII and not utf8. I solved my problem that way:
<?php preg_replace ('/\\\\x([0-9a-fA-F]{2})/e', "pack('H*',utf8_decode('\\1'))",$v); ?>
thierry.bo # netcourrier point com 30-Sep-2005 12:38
In response to fhoech (22-Sep-2005 11:55), I just tried a simultaneous test with the file UTF-8-test.txt using your regexp, 'j dot dittmer' (20-Sep-2005 06:30) regexp (message #56962), `php-note-2005` (17-Feb-2005 08:57) regexp in his message on `mb-detect-encoding` page (http://us3.php.net/manual/en/function.mb-detect-encoding.php#50087) who is using a regexp from the W3C (http://w3.org/International/questions/qa-forms-utf-8.html), and PHP mb_detect_encoding function.

Here are a summarize of the results :

201 lines are valid UTF8 strings using phpnote regexp
203 lines are valid UTF8 strings using j.dittmer regexp
200 lines are valid UTF8 strings using fhoech regexp
239 lines are valid  UTF8 strings using using mb_detect_encoding

Here are the lines with differences (left to right, phpnote, j.dittmer and fhoech) :

Line #70 : NOT UTF8|IS UTF8!|IS UTF8! :2.1.1 1 byte (U-00000000): ""
Line #79 : NOT UTF8|IS UTF8!|IS UTF8! :2.2.1 1 byte (U-0000007F): ""
Line #81 : IS UTF8!|IS UTF8!|NOT UTF8 :2.2.3 3 bytes (U-0000FFFF): "&#65535;" |
Line #267 : IS UTF8!|IS UTF8!|NOT UTF8 :5.3.1 U+FFFE = ef bf be = "&#65534;" |
Line #268 : IS UTF8!|IS UTF8!|NOT UTF8 :5.3.2 U+FFFF = ef bf bf = "&#65535;" |

Interesting is that you said that your regexp corrected j.dittmer regexp that failed on 5.3 section, but it my test I have the opposite result ?!

I ran this test on windows XP with PHP 4.3.11dev. Maybe these differences come from operating system, or PHP version.

For mb_detect_encoding I used the command :

mb_detect_encoding($line, 'UTF-8, ISO-8859-1, ASCII');
fhoech 22-Sep-2005 10:55
Sorry, I had a typo in my last comment. Corrected regexp:

^([\\x00-\\x7f]|
[\\xc2-\\xdf][\\x80-\\xbf]|
\\xe0[\\xa0-\\xbf][\\x80-\\xbf]|
[\\xe1-\\xec][\\x80-\\xbf]{2}|
\\xed[\\x80-\\x9f][\\x80-\\xbf]|
\\xef[\\x80-\\xbf][\\x80-\\xbd]|
\\xee[\\x80-\\xbf]{2}|
\xf0[\\x90-\\xbf][\\x80-\\xbf]{2}|
[\\xf1-\\xf3][\\x80-\\xbf]{3}|
\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})*$
fhoech 22-Sep-2005 10:12
JF Sebastian's regex is almost perfect as far as I'm concerned. I found one error (it failed section 5.3 "Other illegal code positions" from http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt) which I corrected as follows:

^([\\x00-\\x7f]|
[\\xc2-\\xdf][\\x80-\\xbf]|
\\xe0[\\xa0-\\xbf][\\x80-\\xbf]|
[\\xe1-\\xec][\\x80-\\xbf]{2}|
\\xed[\\x80-\\x9f][\\x80-\\xbf]|
\\xef[\\x80-\\xbf][\\x80-\\xbc]|
\\xee[\\x80-\\xbf]{2}|
\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2}|
[\\xf1-\\xf3][\\x80-\\xbf]{3}|
\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})*$

(Again, concatenate to one single line to make it work)
j dot dittmer at portrix dot net 20-Sep-2005 05:30
The regex in the last comment has some typos. This is a
syntactically valid one, don't know if it's correct though.
You've to concat the expression in one long line.

^(
[\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
[\xe0][\xa0-\xbf][\x80-\xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
[\xed][\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
[\xf0][\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
[\xf4][\x80-\x8f][\x80-\xbf]{2}
)*$
rasmus at flajm dot se 19-Jan-2005 02:57
If you don't have the multibyte extension installed, here's a function to decode UTF-16 encoded strings. It support both BOM-less and BOM'ed strings, (big- and little-endian byte order.)

<?php
/**
 * Decode UTF-16 encoded strings.
 *
 * Can handle both BOM'ed data and un-BOM'ed data.
 * Assumes Big-Endian byte order if no BOM is available.
 *
 * @param   string  $str  UTF-16 encoded data to decode.
 * @return  string  UTF-8 / ISO encoded data.
 * @access  public
 * @version 0.1 / 2005-01-19
 * @author  Rasmus Andersson {@link http://rasmusandersson.se/}
 * @package Groupies
 */
function utf16_decode( $str ) {
    if( strlen($str) < 2 ) return $str;
    $bom_be = true;
    $c0 = ord($str{0});
    $c1 = ord($str{1});
    if( $c0 == 0xfe && $c1 == 0xff ) { $str = substr($str,2); }
    elseif( $c0 == 0xff && $c1 == 0xfe ) { $str = substr($str,2); $bom_be = false; }
    $len = strlen($str);
    $newstr = '';
    for($i=0;$i<$len;$i+=2) {
        if( $bom_be ) { $val = ord($str{$i})   << 4; $val += ord($str{$i+1}); }
        else {        $val = ord($str{$i+1}) << 4; $val += ord($str{$i}); }
        $newstr .= ($val == 0x228) ? "\n" : chr($val);
    }
    return $newstr;
}
?>
Aidan Kehoe <php-manual at parhasard dot net> 31-Jan-2004 05:35
The fastest way I've found to check if something is valid UTF-8 is
<?php
if (iconv('UTF-8', 'UTF-8', $input) != $input) {
        /* It's not UTF-8--for me, it's probably CP1252, the Windows
           version of Latin 1, with directed quotation marks and
           the Euro sign.  */
}
 ?>.
The iconv() C library fails if it's told a string is UTF-8 and it isn't; the PHP one doesn't, it just returns the conversion up to the point of failure, so you have to compare the result to the input to find out if the conversion succeeded.
gto at interia dot pl 25-Nov-2003 07:12
Correction to function converting utf82iso88592 and iso88592tutf8.
Janusz forgot about "&#324;", and "&#380;" exchanged from "&#378;" here and there.

GTo

function utf82iso88592($tekscik) {
     $tekscik = str_replace("\xC4\x85", "&#261;", $tekscik);
     $tekscik = str_replace("\xC4\x84", '&#260;', $tekscik);
     $tekscik = str_replace("\xC4\x87", '&#263;', $tekscik);
     $tekscik = str_replace("\xC4\x86", '&#262;', $tekscik);
     $tekscik = str_replace("\xC4\x99", '&#281;', $tekscik);
     $tekscik = str_replace("\xC4\x98", '&#280;', $tekscik);
     $tekscik = str_replace("\xC5\x82", '&#322;', $tekscik);
     $tekscik = str_replace("\xC5\x81", '&#321;', $tekscik);
     $tekscik = str_replace("\xC5\x84", '&#324;', $tekscik);
     $tekscik = str_replace("\xC5\x83", '&#323;', $tekscik);
     $tekscik = str_replace("\xC3\xB3", '?', $tekscik);
     $tekscik = str_replace("\xC3\x93", '?', $tekscik);
     $tekscik = str_replace("\xC5\x9B", '&#347;', $tekscik);
     $tekscik = str_replace("\xC5\x9A", '&#346;', $tekscik);
     $tekscik = str_replace("\xC5\xBC", '&#380;', $tekscik);
     $tekscik = str_replace("\xC5\xBB", '&#379;', $tekscik);
     $tekscik = str_replace("\xC5\xBA", '&#378;', $tekscik);
     $tekscik = str_replace("\xC5\xB9", '&#377;', $tekscik);
     return $tekscik;
} // utf82iso88592

function iso885922utf8($tekscik) {
     $tekscik = str_replace("&#261;", "\xC4\x85", $tekscik);
     $tekscik = str_replace('&#260;', "\xC4\x84", $tekscik);
     $tekscik = str_replace('&#263;', "\xC4\x87", $tekscik);
     $tekscik = str_replace('&#262;', "\xC4\x86", $tekscik);
     $tekscik = str_replace('&#281;', "\xC4\x99", $tekscik);
     $tekscik = str_replace('&#280;', "\xC4\x98", $tekscik);
     $tekscik = str_replace('&#322;', "\xC5\x82", $tekscik);
     $tekscik = str_replace('&#321;', "\xC5\x81", $tekscik);
     $tekscik = str_replace('&#324;', "\xC5\x84", $tekscik);
     $tekscik = str_replace('&#323;',"\xC5\x83", $tekscik);
     $tekscik = str_replace('?', "\xC3\xB3", $tekscik);
     $tekscik = str_replace('?', "\xC3\x93", $tekscik);
     $tekscik = str_replace('&#347;', "\xC5\x9B", $tekscik);
     $tekscik = str_replace('&#346;', "\xC5\x9A", $tekscik);
     $tekscik = str_replace('&#380;', "\xC5\xBC", $tekscik);
     $tekscik = str_replace('&#379;', "\xC5\xBB", $tekscik);
     $tekscik = str_replace('&#378;', "\xC5\xBA", $tekscik);
     $tekscik = str_replace('&#377;', "\xC5\xB9", $tekscik);
     return $tekscik;
} // iso885922utf8


Codifica un string ISO-8859-1 a UTF-8

  • « utf8_decode
  • xml_error_string »
  • PHP Manual
  • Funciones del Intérprete XML
  • Codifica un string ISO-8859-1 a UTF-8

utf8_encode

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

utf8_encode — Codifica un string ISO-8859-1 a UTF-8

Descripción

utf8_encode ( string $data ) : string

Ésta función codifica el string data a UTF-8, y devuelve una versión codificada. UTF-8 es un mecanismo estándar usado por Unicode para la codificación de los valores de caracteres anchos en un flujo de bytes. UTF-8 es transparente para caracteres ASCII puros, está autosincronizada (lo que significa que un programa puede averiguar dónde empiezan los caracteres del flujo de bytes) y puede usarse con funciones de comparación de string normal para ordenar, etc. PHP codifica los caracteres UTF-8 en hasta cuatro bytes, así:

Codificación UTF-8
bytes | bits | representation
1 | 7 | 0bbbbbbb
2 | 11 | 110bbbbb 10bbbbbb
3 | 16 | 1110bbbb 10bbbbbb 10bbbbbb
4 | 21 | 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
Cada b representa un bit que se puede usar para almacenar los datos de los caracteres.

Parámetros

data

Un string ISO-8859-1.

Valores devueltos

Devuelve la traducción UTF-8 de data.

Ver también

  • utf8_decode() - Convierte una cadena con los caracteres codificados ISO-8859-1 con UTF-8 a un sencillo byte ISO-8859-1

User Contributed Notes

rattones at gmail dot com 18-Feb-2021 03:08
/**
 * Convert all values of an array to utf8_encode
 * @author Marcelo Ratton
 * @version 1.0
 *
 * @param  array  $arr   array to encode values
 * @param  bool   $keys  true to convert keys to UTF8
 * @return array  same   array but with all values encoded to UTF8
 */
function arrayEncodeToUTF8(array $arr, bool $keys= false) : array {
  $ret= [];
  foreach ($arr as $k=>$v) {
    if (is_array($v)) {
      $ret[$k]= arrayEncodeToUTF8($v);
    } else {
      if ($keys) {
        $k= utf8_encode((string)$k);
      }
      $ret[$k]= utf8_encode((string)$v);
    }
  }

  return $ret;
}
Pini 16-Nov-2015 03:14
My version of utf8_encode_deep,
In case you need one that returns a value without changing the original.

        /**
        * Convert Anything To UTF-8
        * @param mixed $var The variable you want to convert.
        * @param boolean $deep Deep convertion? (*Default: TRUE).
        * @return mixed
        */
        function anything_to_utf8($var,$deep=TRUE){
            if(is_array($var)){
                foreach($var as $key => $value){
                    if($deep){
                        $var[$key] = anything_to_utf8($value,$deep);
                    }elseif(!is_array($value) && !is_object($value) && !mb_detect_encoding($value,'utf-8',true)){
                         $var[$key] = utf8_encode($var);
                    }
                }
                return $var;
            }elseif(is_object($var)){
                foreach($var as $key => $value){
                    if($deep){
                        $var->$key = anything_to_utf8($value,$deep);
                    }elseif(!is_array($value) && !is_object($value) && !mb_detect_encoding($value,'utf-8',true)){
                         $var->$key = utf8_encode($var);
                    }
                }
                return $var;
            }else{
                return (!mb_detect_encoding($var,'utf-8',true))?utf8_encode($var):$var;
            }
        }
a dot rueedlinger at gmail dot com 22-Jun-2013 01:06
If you need a function which converts a string array into a utf8 encoded string array then this function might be useful for you:

<?php
function utf8_string_array_encode(&$array){
    $func = function(&$value,&$key){
        if(is_string($value)){
            $value = utf8_encode($value);
        }
        if(is_string($key)){
            $key = utf8_encode($key);
        }
        if(is_array($value)){
            utf8_string_array_encode($value);
        }
    };
    array_walk($array,$func);
    return $array;
}
?>
Oscar Broman 06-Sep-2012 11:15
Walk through nested arrays/objects and utf8 encode all strings.

<?php
// Usage
class Foo {
    public $somevar = 'whoop whoop';
}

$structure = array(
    'object' => (object) array(
        'entry' => 'hello wörld',
        'another_array' => array(
            'string',
            1234,
            'another string'
        )
    ),
    'string' => 'foo',
    'foo_object' => new Foo
);

utf8_encode_deep($structure);

// $structure is now utf8 encoded
print_r($structure);

// The function
function utf8_encode_deep(&$input) {
    if (is_string($input)) {
        $input = utf8_encode($input);
    } else if (is_array($input)) {
        foreach ($input as &$value) {
            utf8_encode_deep($value);
        }

        unset($value);
    } else if (is_object($input)) {
        $vars = array_keys(get_object_vars($input));

        foreach ($vars as $var) {
            utf8_encode_deep($input->$var);
        }
    }
}
?>
deceze at gmail dot com 14-Jul-2011 06:51
Please note that utf8_encode only converts a string encoded in ISO-8859-1 to UTF-8. A more appropriate name for it would be "iso88591_to_utf8". If your text is not encoded in  ISO-8859-1, you do not need this function. If your text is already in UTF-8, you do not need this function. In fact, applying this function to text that is not encoded in ISO-8859-1 will most likely simply garble that text.

If you need to convert text from any encoding to any other encoding, look at iconv() instead.
powtac 4t gmx d0t de 11-Feb-2011 01:11
I tried a lot of things, but this seems to be the final fail save method to convert any string to proper UTF-8.

<?php
function _convert($content) {
    if(!mb_check_encoding($content, 'UTF-8')
        OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {

        $content = mb_convert_encoding($content, 'UTF-8');

        if (mb_check_encoding($content, 'UTF-8')) {
            // log('Converted to UTF-8');
        } else {
            // log('Could not converted to UTF-8');
        }
    }
    return $content;
}
?>
Yumok 15-Sep-2010 04:26
Avoiding use of preg_match to detect if utf8_encode is needed:

<?php
                $string = $string_input; // avoid being destructive

                $string = preg_replace("#[\x09\x0A\x0D\x20-\x7E]#"        ,"",$string);         // ASCII
                $string = preg_replace("#[\xC2-\xDF][\x80-\xBF]#"            ,"",$string);             // non-overlong 2-byte
                $string = preg_replace("#\xE0[\xA0-\xBF][\x80-\xBF]#"    ,"",$string);     // excluding overlongs
                $string = preg_replace("#[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}#","",$string);     // straight 3-byte
                $string = preg_replace("#\xED[\x80-\x9F][\x80-\xBF]#"    ,"",$string);     // excluding surrogates
                $string = preg_replace("#\xF0[\x90-\xBF][\x80-\xBF]{2}#","",$string);     // planes 1-3
                $string = preg_replace("#[\xF1-\xF3][\x80-\xBF]{3}#"    ,"",$string);     //  planes 4-15
                $string = preg_replace("#\xF4[\x80-\x8F][\x80-\xBF]{2}#","",$string);     // plane 16

                $rc = ($string == ""?true:false);
?>
rogeriogirodo at gmail dot com 19-Mar-2009 04:24
This function may be useful do encode array keys and values [and checks first to see if it's already in UTF format]:

<?php
public static function to_utf8($in)
{
        if (is_array($in)) {
            foreach ($in as $key => $value) {
                $out[to_utf8($key)] = to_utf8($value);
            }
        } elseif(is_string($in)) {
            if(mb_detect_encoding($in) != "UTF-8")
                return utf8_encode($in);
            else
                return $in;
        } else {
            return $in;
        }
        return $out;
}
?>

Hope this may help.

[NOTE BY danbrown AT php DOT net: Original function written by (cmyk777 AT gmail DOT com) on 28-JAN-09.]
www.tricinty.com 11-Jun-2008 03:43
<?php
    /**
    * Encodes an ISO-8859-1 mixed variable to UTF-8 (PHP 4, PHP 5 compat)
    * @param    mixed    $input An array, associative or simple
    * @param    boolean  $encode_keys optional
    * @return    mixed     ( utf-8 encoded $input)
    */

    function utf8_encode_mix($input, $encode_keys=false)
    {
        if(is_array($input))
        {
            $result = array();
            foreach($input as $k => $v)
            {
                $key = ($encode_keys)? utf8_encode($k) : $k;
                $result[$key] = utf8_encode_mix( $v, $encode_keys);
            }
        }
        else
        {
            $result = utf8_encode($input);
        }

        return $result;
    }
?>
emze at donazga dot net 17-Dec-2006 09:42
/*
Every function seen so far is incomplete or resource consumpting. Here are two -- integer 2 utf sequence (i3u) and utf sequence to integer (u3i). Below is a code snippet that checks well behavior at the range boundaries.

Someday they might be hardcoded into PHP...
*/

function i3u($i) { // returns UCS-16 or UCS-32 to UTF-8 from an integer
  $i=(int)$i; // integer?
  if ($i<0) return false; // positive?
  if ($i<=0x7f) return chr($i); // range 0
  if (($i & 0x7fffffff) <> $i) return '?'; // 31 bit?
  if ($i<=0x7ff) return chr(0xc0 | ($i >> 6)) . chr(0x80 | ($i & 0x3f));
  if ($i<=0xffff) return chr(0xe0 | ($i >> 12)) . chr(0x80 | ($i >> 6) & 0x3f)
      . chr(0x80  | $i & 0x3f);
  if ($i<=0x1fffff) return chr(0xf0 | ($i >> 18)) . chr(0x80 | ($i >> 12) & 0x3f)
      . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
  if ($i<=0x3ffffff) return chr(0xf8 | ($i >> 24)) . chr(0x80 | ($i >> 18) & 0x3f)
      . chr(0x80 | ($i >> 12) & 0x3f) . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
  return chr(0xfc | ($i >> 30)) . chr(0x80 | ($i >> 24) & 0x3f) . chr(0x80 | ($i >> 18) & 0x3f)
      . chr(0x80 | ($i >> 12) & 0x3f) . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
}

function u3i($s,$strict=1) { // returns integer on valid UTF-8 seq, NULL on empty, else FALSE
  // NOT strict: takes only DATA bits, present or not; strict: length and bits checking
  if ($s=='') return NULL;
  $l=strlen($s); $o=ord($s{0});
  if ($o <= 0x7f && $l==1) return $o;
  if ($l>6 && $strict) return false;
  if ($strict) for ($i=1;$i<$l;$i++) if (ord($s{$i}) > 0xbf || ord($s{$i})< 0x80) return false;
  if ($o < 0xc2) return false; // no-go even if strict=0
  if ($o <= 0xdf && ($l=2 && $strict)) return (($o & 0x1f) << 6 | (ord($s{1}) & 0x3f));
  if ($o <= 0xef && ($l=3 && $strict)) return (($o & 0x0f) << 12 | (ord($s{1}) & 0x3f) << 6
     |  (ord($s{2}) & 0x3f));
  if ($o <= 0xf7 && ($l=4 && $strict)) return (($o & 0x07) << 18 | (ord($s{1}) & 0x3f) << 12
     | (ord($s{2}) & 0x3f) << 6 |  (ord($s{3}) & 0x3f));
  if ($o <= 0xfb && ($l=5 && $strict)) return (($o & 0x03) << 24 | (ord($s{1}) & 0x3f) << 18
     | (ord($s{2}) & 0x3f) << 12 | (ord($s{3}) & 0x3f) << 6 |  (ord($s{4}) & 0x3f));
  if ($o <= 0xfd && ($l=6 && $strict)) return (($o & 0x01) << 30 | (ord($s{1}) & 0x3f) << 24
     | (ord($s{2}) & 0x3f) << 18 | (ord($s{3}) & 0x3f) << 12
     | (ord($s{4}) & 0x3f) << 6 |  (ord($s{5}) & 0x3f));
  return false;
}

// boundary behavior checking
$do=array(0x7f,0x7ff,0xffff,0x1fffff,0x3ffffff,0x7fffffff);
foreach ($do as $ii) for ($i=$ii;$i<=$ii+1; $i++) {
  $o=i3u($i);
  for ($j=0;$j<strlen($o);$j++) print "O[$j]=" . sprintf('%08b',ord($o{$j})) . ", ";
  print "c=$i, o=[$o].\n";
  print "Back: [$o] => [" . u3i($o) . "]\n";
}
rocketman 16-Mar-2006 04:46
If you are looking for a function to replace special characters with the hex-utf-8 value (e.g. für Webservice-Security/WSS4J compliancy) you might use this:

$textstart = "Größe";
$utf8 ='';
$max = strlen($txt);

for ($i = 0; $i < $max; $i++) {

if ($txt{i} == "&"){
$neu = "&x26;";
}
elseif ((ord($txt{$i}) < 32) or (ord($txt{$i}) > 127)){
$neu = urlencode(utf8_encode($txt{$i}));
$neu = preg_replace('#\%(..)\%(..)\%(..)#','&#x\1;&#x\2;&#x\3;',$neu);
$neu = preg_replace('#\%(..)\%(..)#','&#x\1;&#x\2;',$neu);
$neu = preg_replace('#\%(..)#','&#x\1;',$neu);
}
else {
$neu = $txt{$i};
}

$utf8 .= $neu;
} // for $i

$textnew = $utf8;

In this example $textnew will be "Gr&#xC3;&#xB6;&#xC3;&#x9F;e"
mailing at jcn50 dot com 20-Jan-2006 10:40
I recommend using this alternative for every language:

$new=mb_convert_encoding($s,"UTF-8","auto");

Don't forget to set all your pages to "utf-8" encoding, otherwise just use HTML entities.

jcn50.
04-Nov-2005 02:34
// Reads a file story.txt ascii (as typed on keyboard)
// converts it to Georgian character using utf8 encoding
// if I am correct(?) just as it should be when typed on Georgian computer
// it outputs it as an html file
//
// http://www.comweb.nl/keys_to_georgian.html
// http://www.comweb.nl/keys_to_georgian.php
// http://www.comweb.nl/story.txt

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<HTML>
<HEAD>
<TITLE>keys to unicode code</TITLE>

// this meta tag is needed
<meta http-equiv="Content-Type" content="text/html;CHARSET=Windows-1252" >

// note the sylfean font seems to be standard installed on Windows XP
// It supports Georgian

<style TYPE="text/css">
<!--
body {font-family:sylfaen; }
-->
</style>
</HEAD>

<BODY>

<?
$eng=array(97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,87,82,84,83,
67,74,90);
$geo=array(4304,4305,4330,4307,4308,4324,4306,4336,4312,4335,4313,
4314,4315,4316,4317,4318,4325,4320,4321,4322,4323,4309,
4332,4334,4327,4310,4333,4326,4311,4328,4329,4319,4331,
91,93,59,39,44,46,96);

$fc=file("story.txt");
foreach($fc as $line)
{
   $spacestart=1;
   for ($i=0; $i<strlen($line); $i+=1)
   {
      $character=ord(substr($line,$i,1));
      $found=0;
      for ($k=0; $k<count($eng); $k+=1)
      {
         if ($eng[$k]==$character)
         {
             print code2utf( $geo[$k] );
             $found=1;
         }
      }
      if ($found==0)
      {
         if ($character==126 || $character==32 || $character==10 || $character==9)
         {
            if ($character==9)  { print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; }
            if ($character==10) { print "<BR>\n"; }
            if ($character==32)
            {
               if ($spacestart==1) {print '&nbsp;'; } else { print " "; }
            }
            if ($character==126){ print "~";      }
         } else
         {
            print substr($line,$i,1);
         }
      }
      if ($character!=32) { $spacestart=0; }
   }
}

/**
 * Function coverts number of utf char into that character.
 * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
 *
 * @param int $num
 * @return utf8char
*/
function code2utf($num)
{
   if($num<128)return chr($num);
   if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
   if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
   if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
   return '';
}
?>

</BODY>
</HTML>
Janci 04-Nov-2005 04:00
I was searching for a function similar to Javascript's unescape(). In most cases it is OK to use url_decode() function but not if you've got UTF characters in the strings. They are converted into %uXXXX entities that url_decode() cannot handle.
I googled the net and found a function which actualy converts these entities into HTML entities (&#xxx;) that your browser can show correctly. If you're OK with that, the function can be found here: http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps

But it was not OK with me because I needed a string in my charset to make some comparations and other stuff. So I have modified the above function and in conjuction with code2utf() function mentioned in some other note here, I have managed to achieve my goal:

<?php
/**
 * Function converts an Javascript escaped string back into a string with specified charset (default is UTF-8).
 * Modified function from http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps
 *
 * @param string $source escaped with Javascript's escape() function
 * @param string $iconv_to destination character set will be used as second paramether in the iconv function. Default is UTF-8.
 * @return string
 */
function unescape($source, $iconv_to = 'UTF-8') {
    $decodedStr = '';
    $pos = 0;
    $len = strlen ($source);
    while ($pos < $len) {
        $charAt = substr ($source, $pos, 1);
        if ($charAt == '%') {
            $pos++;
            $charAt = substr ($source, $pos, 1);
            if ($charAt == 'u') {
                // we got a unicode character
                $pos++;
                $unicodeHexVal = substr ($source, $pos, 4);
                $unicode = hexdec ($unicodeHexVal);
                $decodedStr .= code2utf($unicode);
                $pos += 4;
            }
            else {
                // we have an escaped ascii character
                $hexVal = substr ($source, $pos, 2);
                $decodedStr .= chr (hexdec ($hexVal));
                $pos += 2;
            }
        }
        else {
            $decodedStr .= $charAt;
            $pos++;
        }
    }

    if ($iconv_to != "UTF-8") {
        $decodedStr = iconv("UTF-8", $iconv_to, $decodedStr);
    }

    return $decodedStr;
}

/**
 * Function coverts number of utf char into that character.
 * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
 *
 * @param int $num
 * @return utf8char
 */
function code2utf($num){
    if($num<128)return chr($num);
    if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
    if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
    if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
    return '';
}
?>
suttichai at ceforce dot com 28-May-2005 12:26
This function I use convert Thai font (iso-8859-11) to UTF-8. For my case, It work properly. Please try to use this function if you have a problem to convert charset iso-8859-11 to UTF-8.

function iso8859_11toUTF8($string) {

     if ( ! ereg("[\241-\377]", $string) )
         return $string;

     $iso8859_11 = array(
"\xa1" => "\xe0\xb8\x81",
"\xa2" => "\xe0\xb8\x82",
"\xa3" => "\xe0\xb8\x83",
"\xa4" => "\xe0\xb8\x84",
"\xa5" => "\xe0\xb8\x85",
"\xa6" => "\xe0\xb8\x86",
"\xa7" => "\xe0\xb8\x87",
"\xa8" => "\xe0\xb8\x88",
"\xa9" => "\xe0\xb8\x89",
"\xaa" => "\xe0\xb8\x8a",
"\xab" => "\xe0\xb8\x8b",
"\xac" => "\xe0\xb8\x8c",
"\xad" => "\xe0\xb8\x8d",
"\xae" => "\xe0\xb8\x8e",
"\xaf" => "\xe0\xb8\x8f",
"\xb0" => "\xe0\xb8\x90",
"\xb1" => "\xe0\xb8\x91",
"\xb2" => "\xe0\xb8\x92",
"\xb3" => "\xe0\xb8\x93",
"\xb4" => "\xe0\xb8\x94",
"\xb5" => "\xe0\xb8\x95",
"\xb6" => "\xe0\xb8\x96",
"\xb7" => "\xe0\xb8\x97",
"\xb8" => "\xe0\xb8\x98",
"\xb9" => "\xe0\xb8\x99",
"\xba" => "\xe0\xb8\x9a",
"\xbb" => "\xe0\xb8\x9b",
"\xbc" => "\xe0\xb8\x9c",
"\xbd" => "\xe0\xb8\x9d",
"\xbe" => "\xe0\xb8\x9e",
"\xbf" => "\xe0\xb8\x9f",
"\xc0" => "\xe0\xb8\xa0",
"\xc1" => "\xe0\xb8\xa1",
"\xc2" => "\xe0\xb8\xa2",
"\xc3" => "\xe0\xb8\xa3",
"\xc4" => "\xe0\xb8\xa4",
"\xc5" => "\xe0\xb8\xa5",
"\xc6" => "\xe0\xb8\xa6",
"\xc7" => "\xe0\xb8\xa7",
"\xc8" => "\xe0\xb8\xa8",
"\xc9" => "\xe0\xb8\xa9",
"\xca" => "\xe0\xb8\xaa",
"\xcb" => "\xe0\xb8\xab",
"\xcc" => "\xe0\xb8\xac",
"\xcd" => "\xe0\xb8\xad",
"\xce" => "\xe0\xb8\xae",
"\xcf" => "\xe0\xb8\xaf",
"\xd0" => "\xe0\xb8\xb0",
"\xd1" => "\xe0\xb8\xb1",
"\xd2" => "\xe0\xb8\xb2",
"\xd3" => "\xe0\xb8\xb3",
"\xd4" => "\xe0\xb8\xb4",
"\xd5" => "\xe0\xb8\xb5",
"\xd6" => "\xe0\xb8\xb6",
"\xd7" => "\xe0\xb8\xb7",
"\xd8" => "\xe0\xb8\xb8",
"\xd9" => "\xe0\xb8\xb9",
"\xda" => "\xe0\xb8\xba",
"\xdf" => "\xe0\xb8\xbf",
"\xe0" => "\xe0\xb9\x80",
"\xe1" => "\xe0\xb9\x81",
"\xe2" => "\xe0\xb9\x82",
"\xe3" => "\xe0\xb9\x83",
"\xe4" => "\xe0\xb9\x84",
"\xe5" => "\xe0\xb9\x85",
"\xe6" => "\xe0\xb9\x86",
"\xe7" => "\xe0\xb9\x87",
"\xe8" => "\xe0\xb9\x88",
"\xe9" => "\xe0\xb9\x89",
"\xea" => "\xe0\xb9\x8a",
"\xeb" => "\xe0\xb9\x8b",
"\xec" => "\xe0\xb9\x8c",
"\xed" => "\xe0\xb9\x8d",
"\xee" => "\xe0\xb9\x8e",
"\xef" => "\xe0\xb9\x8f",
"\xf0" => "\xe0\xb9\x90",
"\xf1" => "\xe0\xb9\x91",
"\xf2" => "\xe0\xb9\x92",
"\xf3" => "\xe0\xb9\x93",
"\xf4" => "\xe0\xb9\x94",
"\xf5" => "\xe0\xb9\x95",
"\xf6" => "\xe0\xb9\x96",
"\xf7" => "\xe0\xb9\x97",
"\xf8" => "\xe0\xb9\x98",
"\xf9" => "\xe0\xb9\x99",
"\xfa" => "\xe0\xb9\x9a",
"\xfb" => "\xe0\xb9\x9b"
 );

     $string=strtr($string,$iso8859_11);
     return $string;
 }

Suttichai Mesaard-www.ceforce.com
bisqwit at iki dot fi 20-May-2005 01:15
For reference, it may be insightful to point out that:
  utf8_encode($s)
is actually identical to:
  recode_string('latin1..utf8', $s)
and:
  iconv('iso-8859-1', 'utf-8', $s)
That is, utf8_encode is a specialized case of character set conversions.

If your string to be converted to utf-8 is something other than iso-8859-1 (such as iso-8859-2 (Polish/Croatian)), you should use recode_string() or iconv() instead rather than trying to devise complex str_replace statements.
JF Sebastian 09-Apr-2005 03:54
The following Perl regular expression tests if a string is well-formed Unicode UTF-8 (Broken up after each | since long lines are not permitted here. Please join as a single line, no spaces, before use.):

^([\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
\xe0[\xa0-\xbf][\x80-\xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
\xed[\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
f0[\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
\xf4[\x80-\x8f][\x80-\xbf]{2})*$

NOTE: This strictly follows the Unicode standard 4.0, as described in chapter 3.9, table 3-6, "Well-formed UTF-8 byte sequences" ( http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G31703 ).

ISO-10646, a super-set of Unicode, uses UTF-8 (there called "UCS", see http://www.unicode.org/faq/utf_bom.html#1 ) in a relaxed variant that supports a 31-bit space encoded into up to six bytes instead of Unicode's 21 bits in up to four bytes. To check for ISO-10646 UTF-8, use the following Perl regular expression (again, broken up, see above):

^([\x00-\x7f]|
[\xc0-\xdf][\x80-\xbf]|
[\xe0-\xef][\x80-\xbf]{2}|
[\xf0-\xf7][\x80-\xbf]{3}|
[\xf8-\xfb][\x80-\xbf]{4}|
[\xfc-\xfd][\x80-\xbf]{5})*$

The following function may be used with above expressions for a quick UTF-8 test, e.g. to distinguish ISO-8859-1-data from UTF-8-data if submitted from a <form accept-charset="utf-8,iso-8859-1" method=..>.

function is_utf8($string) {
   return (preg_match('/[insert regular expression here]/', $string) === 1);
}
hrpeters (at) gmx (dot) net 13-Dec-2004 10:46
// Validate Unicode UTF-8 Version 4
// This function takes as reference the table 3.6 found at http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf
// It also flags overlong bytes as error

function is_validUTF8($str)
{
    // values of -1 represent disalloweded values for the first bytes in current UTF-8
    static $trailing_bytes = array (
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
        -1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
        2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    );

    $ups = unpack('C*', $str);
    if (!($aCnt = count($ups))) return true; // Empty string *is* valid UTF-8
    for ($i = 1; $i <= $aCnt;)
    {
        if (!($tbytes = $trailing_bytes[($b1 = $ups[$i++])])) continue;
        if ($tbytes == -1) return false;

        $first = true;
        while ($tbytes > 0 && $i <= $aCnt)
        {
            $cbyte = $ups[$i++];
            if (($cbyte & 0xC0) != 0x80) return false;

            if ($first)
            {
                switch ($b1)
                {
                    case 0xE0:
                        if ($cbyte < 0xA0) return false;
                        break;
                    case 0xED:
                        if ($cbyte > 0x9F) return false;
                        break;
                    case 0xF0:
                        if ($cbyte < 0x90) return false;
                        break;
                    case 0xF4:
                        if ($cbyte > 0x8F) return false;
                        break;
                    default:
                        break;
                }
                $first = false;
            }
            $tbytes--;
        }
        if ($tbytes) return false; // incomplete sequence at EOS
    }
    return true;
}
Mark AT modernbill DOT com 09-Nov-2004 11:56
If you haven't guessed already: If the UTF-8 character has no representation in the ISO-8859-1 codepage, a ? will be returned. You might want to wrap a function around this to make sure you aren't saving a bunch of ???? into your database.
Aidan Kehoe <php-manual at parhasard dot net> 30-Aug-2004 07:05
Here's some code that addresses the issue that Steven describes in the previous comment;

<?php

/* This structure encodes the difference between ISO-8859-1 and Windows-1252,
   as a map from the UTF-8 encoding of some ISO-8859-1 control characters to
   the UTF-8 encoding of the non-control characters that Windows-1252 places
   at the equivalent code points. */

$cp1252_map = array(
    "\xc2\x80" => "\xe2\x82\xac", /* EURO SIGN */
    "\xc2\x82" => "\xe2\x80\x9a", /* SINGLE LOW-9 QUOTATION MARK */
    "\xc2\x83" => "\xc6\x92",     /* LATIN SMALL LETTER F WITH HOOK */
    "\xc2\x84" => "\xe2\x80\x9e", /* DOUBLE LOW-9 QUOTATION MARK */
    "\xc2\x85" => "\xe2\x80\xa6", /* HORIZONTAL ELLIPSIS */
    "\xc2\x86" => "\xe2\x80\xa0", /* DAGGER */
    "\xc2\x87" => "\xe2\x80\xa1", /* DOUBLE DAGGER */
    "\xc2\x88" => "\xcb\x86",     /* MODIFIER LETTER CIRCUMFLEX ACCENT */
    "\xc2\x89" => "\xe2\x80\xb0", /* PER MILLE SIGN */
    "\xc2\x8a" => "\xc5\xa0",     /* LATIN CAPITAL LETTER S WITH CARON */
    "\xc2\x8b" => "\xe2\x80\xb9", /* SINGLE LEFT-POINTING ANGLE QUOTATION */
    "\xc2\x8c" => "\xc5\x92",     /* LATIN CAPITAL LIGATURE OE */
    "\xc2\x8e" => "\xc5\xbd",     /* LATIN CAPITAL LETTER Z WITH CARON */
    "\xc2\x91" => "\xe2\x80\x98", /* LEFT SINGLE QUOTATION MARK */
    "\xc2\x92" => "\xe2\x80\x99", /* RIGHT SINGLE QUOTATION MARK */
    "\xc2\x93" => "\xe2\x80\x9c", /* LEFT DOUBLE QUOTATION MARK */
    "\xc2\x94" => "\xe2\x80\x9d", /* RIGHT DOUBLE QUOTATION MARK */
    "\xc2\x95" => "\xe2\x80\xa2", /* BULLET */
    "\xc2\x96" => "\xe2\x80\x93", /* EN DASH */
    "\xc2\x97" => "\xe2\x80\x94", /* EM DASH */

    "\xc2\x98" => "\xcb\x9c",     /* SMALL TILDE */
    "\xc2\x99" => "\xe2\x84\xa2", /* TRADE MARK SIGN */
    "\xc2\x9a" => "\xc5\xa1",     /* LATIN SMALL LETTER S WITH CARON */
    "\xc2\x9b" => "\xe2\x80\xba", /* SINGLE RIGHT-POINTING ANGLE QUOTATION*/
    "\xc2\x9c" => "\xc5\x93",     /* LATIN SMALL LIGATURE OE */
    "\xc2\x9e" => "\xc5\xbe",     /* LATIN SMALL LETTER Z WITH CARON */
    "\xc2\x9f" => "\xc5\xb8"      /* LATIN CAPITAL LETTER Y WITH DIAERESIS*/
);

function cp1252_to_utf8($str) {
        global $cp1252_map;
        return  strtr(utf8_encode($str), $cp1252_map);
}

?>
Net Raven 24-Jun-2004 12:58
I often need to convert multi language text sent to me for use in websites and other apps into UTF8 encoded so I can insert it into source code and databases.

I knocked up a small web page with its charset set to UTF8 then set it up so I can paste from the original doc (eg word or excel) and have the page return the UTF8 encoded version.

Of course the browser will convert the unicode to UTF8 for you as part of the submit (I use IE5 or better for this) then all you have to do in the PHP is encode the UTF8 so the browser will show it in its raw form.

Its a bit bulky but I just convert ALL character to html numbered entities (brute force and ignorance does it again.)

I've used this to encode everything from Hebrew to Japanese without problems

<?
header("Content-Type: text/plain; CHARSET=Windows-1252");
$code = (get_magic_quotes_gpc())?stripslashes($GLOBALS[code]):$GLOBALS[code];
?>
<html>
<head>
    <title>UTF8 ENCODER PAGE</title>
    <meta http-equiv="content-type" content="text/html; CHARSET=Windows-1252">
</head>
<body>
<form method=post action="?seed=<?=time()?>">
    Original Unicode<br />
    <textarea name="code" cols="80" rows="10"><?=$code?></textarea><br />
    Encoded UTF8<br />
    <textarea name="encd" cols="80" rows="10"><?
        for ($i = 0; $i < strlen($code); $i++) {
            echo '&#'.ord(substr($code,$i,1));
        }
    ?></textarea><br />
    <input type="submit" value="encode">
</form>
</body>
</html>
Karen 01-Oct-2003 12:33
Re the previous post about converting GB2312 code to Unicode code which displayed the following function:

<?
// Program by sadly (www.phpx.com)

function gb2unicode($gb)
{
   if(!trim($gb))
    return $gb;
   $filename="gb2312.txt";
   $tmp=file($filename);
   $codetable=array();
   while(list($key,$value)=each($tmp))
    $codetable[hexdec(substr($value,0,6))]=substr($value,9,4);
   $utf="";
   while($gb)
    {
      if (ord(substr($gb,0,1))>127)
     {
        $this=substr($gb,0,2);
        $gb=substr($gb,2,strlen($gb));
        $utf.="&#x".$codetable[hexdec(bin2hex($this))-0x8080].";";
      }
     else
     {
      $gb=substr($gb,1,strlen($gb));
      $utf.=substr($gb,0,1);
     }
     }
  return $utf;
}
?>

I found that a small change was needed in the code to properly handle latin characters embedded in the middle of gb2312 text, as when the text includes a URL or email address. Just reverse the two lines in the part of the statement above that handles ord vals !>127.

Change:

$gb=substr($gb,1,strlen($gb));
$utf.=substr($gb,0,1);

to:

$utf.=substr($gb,0,1);
$gb=substr($gb,1,strlen($gb));

In the original function, the first latin chacter was dropped and it was not converting the first non-latin character after the latin text (everything was shifted one character too far to the right). Reversing those two lines makes it work correctly in every example I have tried.

Also, the source of the gb2312.txt file needed for this to work has changed. You can find it a couple places:

http://tcl.apache.org/sources/tcl/tools/encoding/gb2312.txt
ftp://ftp.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/GB/GB2312.TXT
ronen at greyzone dot com 07-Mar-2002 12:01
The following function will utf-8 encode unicode entities &#nnn(nn); with n={0..9}

/**
* takes a string of unicode entities and converts it to a utf-8 encoded string
* each unicode entitiy has the form &#nnn(nn); n={0..9} and can be displayed by utf-8 supporting
* browsers.  Ascii will not be modified.
* @param $source string of unicode entities [STRING]
* @return a utf-8 encoded string [STRING]
* @access public
*/
function utf8Encode ($source) {
    $utf8Str = '';
    $entityArray = explode ("&#", $source);
    $size = count ($entityArray);
    for ($i = 0; $i < $size; $i++) {
        $subStr = $entityArray[$i];
        $nonEntity = strstr ($subStr, ';');
        if ($nonEntity !== false) {
            $unicode = intval (substr ($subStr, 0, (strpos ($subStr, ';') + 1)));
            // determine how many chars are needed to reprsent this unicode char
            if ($unicode < 128) {
                $utf8Substring = chr ($unicode);
            }
            else if ($unicode >= 128 && $unicode < 2048) {
                $binVal = str_pad (decbin ($unicode), 11, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 5);
                $binPart2 = substr ($binVal, 5);

                $char1 = chr (192 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $utf8Substring = $char1 . $char2;
            }
            else if ($unicode >= 2048 && $unicode < 65536) {
                $binVal = str_pad (decbin ($unicode), 16, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 4);
                $binPart2 = substr ($binVal, 4, 6);
                $binPart3 = substr ($binVal, 10);

                $char1 = chr (224 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $char3 = chr (128 + bindec ($binPart3));
                $utf8Substring = $char1 . $char2 . $char3;
            }
            else {
                $binVal = str_pad (decbin ($unicode), 21, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 3);
                $binPart2 = substr ($binVal, 3, 6);
                $binPart3 = substr ($binVal, 9, 6);
                $binPart4 = substr ($binVal, 15);

                $char1 = chr (240 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $char3 = chr (128 + bindec ($binPart3));
                $char4 = chr (128 + bindec ($binPart4));
                $utf8Substring = $char1 . $char2 . $char3 . $char4;
            }

            if (strlen ($nonEntity) > 1)
                $nonEntity = substr ($nonEntity, 1); // chop the first char (';')
            else
                $nonEntity = '';

            $utf8Str .= $utf8Substring . $nonEntity;
        }
        else {
            $utf8Str .= $subStr;
        }
    }

    return $utf8Str;
}

Ronen.


Obtiene la cadena de un error dado en un intérprete XML

  • « utf8_encode
  • xml_get_current_byte_index »
  • PHP Manual
  • Funciones del Intérprete XML
  • Obtiene la cadena de un error dado en un intérprete XML

xml_error_string

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

xml_error_string — Obtiene la cadena de un error dado en un intérprete XML

Descripción

xml_error_string ( int $code ) : string

Obtiene la cadena asociada a un error code dado en un intérprete XML.

Parámetros

code

Código de error como el obtenido desde xml_get_error_code().

Valores devueltos

Devuelve un string con una descripción textual del error code, o false si no se ha encontrado una descripción asociada a ese código de error.

Ver también

  • xml_get_error_code() - Obtiene un código de error en un intérprete 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;
?>


Obtiene la indexación del byte actual en un intérprete XML

  • « xml_error_string
  • xml_get_current_column_number »
  • PHP Manual
  • Funciones del Intérprete XML
  • Obtiene la indexación del byte actual en un intérprete XML

xml_get_current_byte_index

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

xml_get_current_byte_index — Obtiene la indexación del byte actual en un intérprete XML

Descripción

xml_get_current_byte_index ( resource $parser ) : int

Obtiene la indexación del byte actual en un intérprete XML dado.

Parámetros

parser

Identificador del recurso del intérprete XML sobre el que se va a obtener la indexación del byte actual.

Valores devueltos

Devuelve cual es la indexación del byte en el que se haya actualmente el intérprete en el buffer de datos (empieza siendo 0), o devuelve false si parser no se refiere a un intérprete válido.

Notas

Advertencia

Esta función devuelve la indexación de bytes de acuerdo a la codificación de texto UTF-8 texto sin tener en cuenta si la entrada está en otra codificación.

Ver también

  • xml_get_current_column_number() - Obtiene el número de columna actual para un intérprete XML
  • xml_get_current_line_number() - Obtiene el número de línea actual para un intérprete 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.


Obtiene el número de columna actual para un intérprete XML

  • « xml_get_current_byte_index
  • xml_get_current_line_number »
  • PHP Manual
  • Funciones del Intérprete XML
  • Obtiene el número de columna actual para un intérprete XML

xml_get_current_column_number

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

xml_get_current_column_number — Obtiene el número de columna actual para un intérprete XML

Descripción

xml_get_current_column_number ( resource $parser ) : int

Obtiene el número de columna actual para el intérprete XML dado.

Parámetros

parser

Identificador del recurso del intérprete XML sobre el que se va a obtener el número de columna.

Valores devueltos

Devuelve el número de columna en la línea actual (como la dada de xml_get_current_line_number()) en la que se haya el intérprete en el buffer de datos, o devuelve false si parser no se refiere a un intérprete válido.

Ver también

  • xml_get_current_byte_index() - Obtiene la indexación del byte actual en un intérprete XML
  • xml_get_current_line_number() - Obtiene el número de línea actual para un intérprete 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.


Obtiene el número de línea actual para un intérprete XML

  • « xml_get_current_column_number
  • xml_get_error_code »
  • PHP Manual
  • Funciones del Intérprete XML
  • Obtiene el número de línea actual para un intérprete XML

xml_get_current_line_number

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

xml_get_current_line_number — Obtiene el número de línea actual para un intérprete XML

Descripción

xml_get_current_line_number ( resource $parser ) : int

Obtiene el número de línea actual para el intérprete XML dado.

Parámetros

parser

Identificador del recurso del intérprete XML sobre el que se va a obtener el número de línea.

Valores devueltos

Devuelve el número de línea en el que se haya el intérprete actualmente en el buffer de datos, o devuelve false si parser no se refiere a un intérprete válido.

Ver también

  • xml_get_current_column_number() - Obtiene el número de columna actual para un intérprete XML
  • xml_get_current_byte_index() - Obtiene la indexación del byte actual en un intérprete XML

User Contributed Notes

There are no user contributed notes for this page.


Obtiene un código de error en un intérprete XML

  • « xml_get_current_line_number
  • xml_parse_into_struct »
  • PHP Manual
  • Funciones del Intérprete XML
  • Obtiene un código de error en un intérprete XML

xml_get_error_code

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

xml_get_error_code — Obtiene un código de error en un intérprete XML

Descripción

xml_get_error_code ( resource $parser ) : int

Obtiene un código de error dado en un intérprete XML.

Parámetros

parser

Identificador del recurso del intérprete XML sobre el que se va a obtener el valor de la opción.

Valores devueltos

Esta función devuelve false si parser no se refiere a un intérprete válido, si no devuelve un error de la lista: error codes section.

Ver también

  • xml_error_string() - Obtiene la cadena de un error dado en un intérprete XML

User Contributed Notes

There are no user contributed notes for this page.


Interpreta datos XML en una estructura de array

  • « xml_get_error_code
  • xml_parse »
  • PHP Manual
  • Funciones del Intérprete XML
  • Interpreta datos XML en una estructura de array

xml_parse_into_struct

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

xml_parse_into_struct — Interpreta datos XML en una estructura de array

Descripción

xml_parse_into_struct ( resource $parser , string $data , array &$values , array &$index = ? ) : int

Esta función interpreta una cadena XML en dos estructuras paralelas de array, una (index) que contiene punteros a la ubicación de los valores adecuados en el array values. Estos dos últimos parámetros deben ser pasados por referencia.

Parámetros

parser

Una referencia para el interprete de XML.

data

Una cadena que contiene los datos XML.

values

Un array que contiene los valores de los datos XML.

index

Un array que contiene apuntadores hacia la ubicación de los valores apropiados en $values.

Valores devueltos

xml_parse_into_struct() retorna 0 cuando falla y 1 si es exitoso. Esto no es lo mismo que false y true, tener cuidado con operadores tales como ===.

Ejemplos

A continuación se muestra un ejemplo que ilustra la estructura interna de los arrays que se generan por la función. Se usa una etiqueta simple note incrustada dentro de una etiqueta para y entonces esto se interpreta y se muestran las estructuras generadas:

Ejemplo #1 Ejemplo de xml_parse_into_struct()

<?php
$simple = "<para><note>Nota Simple</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);
?>

Cuando se ejecuta este código, la salida será:

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
        )

)

El análisis por eventos (basado en la biblioteca expat) puede ser más complicado cuando se tiene un documento XML que es complejo. Esta función no produce un objeto de estilo DOM, pero genera estructuras susceptibles de ser transversionadas en forma de árbol. Por lo tanto, se pueden crear objetos que representan los datos en el archivo XML con facilidad. Considere el siguiente archivo XML que representa una pequeña base de datos con información de aminoácidos:

Ejemplo #2 moldb.xml - pequeña base de datos de información molecular

<?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>
Y algo de código para interpretar el documento y generar los objetos adecuados:

Ejemplo #3 parsemoldb.php - interpreta moldb.xml dentro de un array de objetos moleculares

<?php

class AminoAcid {
    var $name;  // nombre aa
    var $symbol;    // símbolo de tres letras
    var $code;  // código de una letra
    var $type;  // hidrofóbico, cargado or neutral

    function AminoAcid ($aa)
    {
        foreach ($aa as $k=>$v)
            $this->$k = $aa[$k];
    }
}

function readDatabase($filename)
{
    // read the XML database of aminoacids
    $data = implode("", file($filename));
    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, $data, $values, $tags);
    xml_parser_free($parser);

    // repetir a través de las extructuras
    foreach ($tags as $key=>$val) {
        if ($key == "molecule") {
            $molranges = $val;
            // cada par contiguo de netradas de array son los
            // rangos altos y bajos para cada definición de molécula
            for ($i=0; $i < count($molranges); $i+=2) {
                $offset = $molranges[$i] + 1;
                $len = $molranges[$i + 1] - $offset;
                $tdb[] = parseMol(array_slice($values, $offset, $len));
            }
        } else {
            continue;
        }
    }
    return $tdb;
}

function parseMol($mvalues)
{
    for ($i=0; $i < count($mvalues); $i++) {
        $mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
    }
    return new AminoAcid($mol);
}

$db = readDatabase("moldb.xml");
echo "** Database of AminoAcid objects:\n";
print_r($db);

?>
Después de ejecutar parsemoldb.php, la variable $db contiene un array de objetos de AminoAcid y la salida del script confirma que:
** Base de datos de objetos AminoÁcidos:
Array
(
    [0] => Objeto aminoácido
        (
            [name] => Alanine
            [symbol] => ala
            [code] => A
            [type] => hydrophobic
        )

    [1] => Objeto aminoácido
        (
            [name] => Lysine
            [symbol] => lys
            [code] => K
            [type] => charged
        )

)

User Contributed Notes

Adam Tylmad 30-Apr-2009 12:58
Thanx to jukea i've upgraded the characterData-function to allow the value 0. Here is the new complete code:

<?php

class XMLParser {
    var $path;
    var $result;

    function cleanString($string) {
        return trim(str_replace("'", "&#39;", $string));
    }

    function XMLParser($encoding, $data) {
        $this->path = "\$this->result";
        $this->index = 0;

        $xml_parser = xml_parser_create($encoding);
        xml_set_object($xml_parser, &$this);
        xml_set_element_handler($xml_parser, 'startElement', 'endElement');
        xml_set_character_data_handler($xml_parser, 'characterData');

        xml_parse($xml_parser, $data, true);
        xml_parser_free($xml_parser);
    }

    function startElement($parser, $tag, $attributeList) {
        $this->path .= "->".$tag;
        eval("\$data = ".$this->path.";");
        if (is_array($data)) {
            $index = sizeof($data);
            $this->path .= "[".$index."]";
        } else if (is_object($data)) {
            eval($this->path." = array(".$this->path.");");
            $this->path .= "[1]";
        }

        foreach($attributeList as $name => $value)
            eval($this->path."->".$name. " = '".XMLParser::cleanString($value)."';");
    }

    function endElement($parser, $tag) {
        $this->path = substr($this->path, 0, strrpos($this->path, "->"));
    }

    function characterData($parser, $data) {
        if (strlen($data = XMLParser::cleanString($data)))
            eval($this->path." = '$data';");
    }
}

?>
aerik at thesylvans dot com 28-Nov-2008 03:55
Here's another attempt at dealing with rebuilding the xml from the array.  I'm basically preventing certain tags from being self closing by just checking for them explicitly (sure wish expat didn't interpret <textarea /> and <textarea></textarea> the same way (as "complete" tags).

<?php
function array2xml($xmlary){
  $o='';
  foreach($xmlary as $tag ){
    if($tag['tag'] == 'textarea' && !isset($tag['value'])){
      //fake a value so it won't self close
      $tag['value']='';
    }
    //tab space:
    $t = '';
    for($i=1; $i < $tag['level'];$i++){
      $t.="\t";
    }
    switch($tag['type']){
      case 'complete':
      case 'open':
        $o.=$t.'<'.$tag['tag'];
        if(isset($tag['attributes'])){
          foreach($tag['attributes'] as $attr=>$aval){
            $o.=' '.$attr.'="'.$aval.'"';
          }//foreach
        }//attributes
        if($tag['type'] == 'complete'){
          if(!isset($tag['value'])){
            $o .= ' />'."\n";
          } else {
            $o .= '>'."\n".$t.$tag['value']."\n".$t.'</'.$tag['tag'].'>'."\n";
          }
        }else{
          $o .= '>'."\n";
        }
        break;
      case 'close':
        $o .= $t.'</'.$tag['tag'].'>'."\n";
        break;
      case 'cdata':
        $o .= $t.$tag['value']."\n";
        break;
    }//switch
  }//foreach
}
?>
dale at ucsc dot edu 25-Sep-2008 04:16
here you can [re]assemble xml from a xml_parse_into_struct generated array: ie array2xml

<?php
$xml_parser = xml_parser_create( 'UTF-8' ); // UTF-8 or ISO-8859-1
xml_parser_set_option( $xml_parser, XML_OPTION_CASE_FOLDING, 0 );
xml_parser_set_option( $xml_parser, XML_OPTION_SKIP_WHITE, 1 );
xml_parse_into_struct( $xml_parser, $my_text_xml, $aryXML );
xml_parser_free($xml_parser);

//now use aryXML array to xml string:
        $o='';
        foreach( $aryXML as $tag ){
            //tab space:
            for($i=1; $i < $tag['level'];$i++)
                $o.="\t";
            if($tag['type']!='close'){
                if($tag['type']!='cdata')
                    $o.='<'.$tag['tag'];
                if(isset($tag['attributes'])){
                    foreach($tag['attributes'] as $attr=>$aval){
                        $o.=' '.$attr.'="'.$aval.'"';
                    }
                }
                if($tag['type']!='cdata'){
                    $o.=($tag['type']=='complete')?'/>'."\n":'>'."\n";
                }
                $o.=(isset($tag['value']))?$tag['value']:'';
            }else{
                $o.='</'.$tag['tag'].'>';
            }
        }
?>
Llorenc 09-Sep-2008 03:20
Sorry, forgot my last post below, I confused CDATA sections (<![CDATA[]]>) with the value type "cdata", which despite its name it's very different! The first allows adding markup (&,<,>) as regular text and the second is to indicate a not complete node between the open and close nodes. What is true is that the CDATA delimiters are lost after xml_parse_into_struct so it's not possible to revert the process.

Please, feel free to remove my comments or leave them if you think they can help anyone.
wickedfather at hotmail dot com 06-Jul-2008 12:33
Had a comment up that was removed saying I'd found drawbacks, but here's a class what I wrote which works fine for me.  Comments removed due to post restrictions.  Pass the xml into the parse method or in the constructor.  Php4 and 5 safe.

class XMLThing
{
    var $rawXML;
    var $valueArray = array();
    var $keyArray = array();
    var $parsed = array();
    var $index = 0;
    var $attribKey = 'attributes';
    var $valueKey = 'value';
    var $cdataKey = 'cdata';
    var $isError = false;
    var $error = '';

    function XMLThing($xml = NULL)
    {
        $this->rawXML = $xml;
    }

    function parse($xml = NULL)
    {
        if (!is_null($xml))
        {
            $this->rawXML = $xml;
        }

        $this->isError = false;

        if (!$this->parse_init())
        {
            return false;
        }

        $this->index = 0;
        $this->parsed = $this->parse_recurse();
        $this->status = 'parsing complete';

        return $this->parsed;
    }

    function parse_recurse()
    {
        $found = array();
        $tagCount = array();

        while (isset($this->valueArray[$this->index]))
        {
            $tag = $this->valueArray[$this->index];
            $this->index++;

            if ($tag['type'] == 'close')
            {
                return $found;
            }

            if ($tag['type'] == 'cdata')
            {
                $tag['tag'] = $this->cdataKey;
                $tag['type'] = 'complete';
            }

            $tagName = $tag['tag'];

            if (isset($tagCount[$tagName]))
            {
                if ($tagCount[$tagName] == 1)
                {
                    $found[$tagName] = array($found[$tagName]);
                }

                $tagRef =& $found[$tagName][$tagCount[$tagName]];
                $tagCount[$tagName]++;
            }
            else
            {
                $tagCount[$tagName] = 1;
                $tagRef =& $found[$tagName];
            }

            switch ($tag['type'])
            {
                case 'open':
                    $tagRef = $this->parse_recurse();

                    if (isset($tag['attributes']))
                    {
                        $tagRef[$this->attribKey] = $tag['attributes'];
                    }

                    if (isset($tag['value']))
                    {
                        if (isset($tagRef[$this->cdataKey]))
                        {
                            $tagRef[$this->cdataKey] = (array)$tagRef[$this->cdataKey];
                            array_unshift($tagRef[$this->cdataKey], $tag['value']);
                        }
                        else
                        {
                            $tagRef[$this->cdataKey] = $tag['value'];
                        }
                    }
                    break;

                case 'complete':
                    if (isset($tag['attributes']))
                    {
                        $tagRef[$this->attribKey] = $tag['attributes'];
                        $tagRef =& $tagRef[$this->valueKey];
                    }

                    if (isset($tag['value']))
                    {
                        $tagRef = $tag['value'];
                    }
                    break;
            }
        }

        return $found;
    }

    function parse_init()
    {
        $this->parser = xml_parser_create();

        $parser = $this->parser;
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        if (!$res = (bool)xml_parse_into_struct($parser, $this->rawXML, $this->valueArray, $this->keyArray))
        {
            $this->isError = true;
            $this->error = 'error: '.xml_error_string(xml_get_error_code($parser)).' at line '.xml_get_current_line_number($parser);
        }
        xml_parser_free($parser);

        return $res;
    }
}
jemptymethod at gmail dot com 16-Jun-2008 01:39
@wickedfather, re: beaudurrant....I just cannot concur that the latter's class is "great"....First of all, it doesn't handle attributes.  Second of all, as my code below demonstrates, there is no need waste processing by determining duplicates within their own loop.  Thirdly, when there are duplicates, it collapses the layer in the array above the duplicates.

Here is some much more consise code, though not (yet) object oriented, and also not yet handling attributes; it maintains a stack for each level:

<?php
function xml_parse_into_assoc($file) {
  $data = implode("", file($file));
  $p = xml_parser_create();

  xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);

  xml_parse_into_struct($p, $data, $vals, $index);
  xml_parser_free($p);

  $levels = array(null);

  foreach ($vals as $val) {
    if ($val['type'] == 'open' || $val['type'] == 'complete') {
      if (!array_key_exists($val['level'], $levels)) {
        $levels[$val['level']] = array();
      }
    }

    $prevLevel =& $levels[$val['level'] - 1];
    $parent = $prevLevel[sizeof($prevLevel)-1];

    if ($val['type'] == 'open') {
      $val['children'] = array();
      array_push(&$levels[$val['level']], $val);
      continue;
    }

    else if ($val['type'] == 'complete') {
      $parent['children'][$val['tag']] = $val['value'];
    }

    else if ($val['type'] == 'close') {
      $pop = array_pop($levels[$val['level']]);
      $tag = $pop['tag'];

      if ($parent) {
        if (!array_key_exists($tag, $parent['children'])) {
          $parent['children'][$tag] = $pop['children'];
        }
        else if (is_array($parent['children'][$tag])) {
          $parent['children'][$tag][] = $pop['children'];
        }
      }
      else {
        return(array($pop['tag'] => $pop['children']));
      }
    }

    $prevLevel[sizeof($prevLevel)-1] = $parent;
  }
}
?>
wickedfather at hotmail dot com 12-Apr-2008 08:36
To beaudurrant - that class is great and structures things in a very sensible way.  Only problem is that it raises an error if a tag is empty, so would suggest a simple mod to the parse method just to add an isset test.

if (isset($val['value']))
{
    $this->setArrayValue($this->output, $stack, $val['value']);
}
mathiasrav at gmail dot com 10-Mar-2008 08:42
In response to Anonymous' post at 26-Feb-2008 11:50:

Saying that you "don't understand everything" isn't going to get you very popular - you should understand the code you use.
foreach isn't *slow* in PHP, it is actually faster than the equivalent for-construct (which, in many cases, isn't available).

The reason your script is slow is simply your use of xml_parse_into_struct - it reads the whole XML-string and doesn't return until it has parsed and validated it all. If you're looking for efficiency, you'll have to use the more low-level xml_parser_create, xml_set_*_handler functions. Then make sure you don't keep everything in a huge array before outputting it (at least don't if you're going for efficiency).
beaudurrant at gmail dot com 19-Dec-2007 11:23
This is extending what Alf Marius Foss Olsen had posted above.

It takes into account array keys with the same name and uses an increment for them instead of overwriting the keys.

I am using it for SOAP requests (20K - 150K) and it parses very fast compared to PEAR.

<?

class XMLParser  {

    // raw xml
    private $rawXML;
    // xml parser
    private $parser = null;
    // array returned by the xml parser
    private $valueArray = array();
    private $keyArray = array();

    // arrays for dealing with duplicate keys
    private $duplicateKeys = array();

    // return data
    private $output = array();
    private $status;

    public function XMLParser($xml){
        $this->rawXML = $xml;
        $this->parser = xml_parser_create();
        return $this->parse();
    }

    private function parse(){

        $parser = $this->parser;

        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); // Dont mess with my cAsE sEtTings
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);     // Dont bother with empty info
        if(!xml_parse_into_struct($parser, $this->rawXML, $this->valueArray, $this->keyArray)){
            $this->status = 'error: '.xml_error_string(xml_get_error_code($parser)).' at line '.xml_get_current_line_number($parser);
            return false;
        }
        xml_parser_free($parser);

        $this->findDuplicateKeys();

        // tmp array used for stacking
        $stack = array();
        $increment = 0;

        foreach($this->valueArray as $val) {
            if($val['type'] == "open") {
                //if array key is duplicate then send in increment
                if(array_key_exists($val['tag'], $this->duplicateKeys)){
                    array_push($stack, $this->duplicateKeys[$val['tag']]);
                    $this->duplicateKeys[$val['tag']]++;
                }
                else{
                    // else send in tag
                    array_push($stack, $val['tag']);
                }
            } elseif($val['type'] == "close") {
                array_pop($stack);
                // reset the increment if they tag does not exists in the stack
                if(array_key_exists($val['tag'], $stack)){
                    $this->duplicateKeys[$val['tag']] = 0;
                }
            } elseif($val['type'] == "complete") {
                //if array key is duplicate then send in increment
                if(array_key_exists($val['tag'], $this->duplicateKeys)){
                    array_push($stack, $this->duplicateKeys[$val['tag']]);
                    $this->duplicateKeys[$val['tag']]++;
                }
                else{
                    // else send in tag
                    array_push($stack,  $val['tag']);
                }
                $this->setArrayValue($this->output, $stack, $val['value']);
                array_pop($stack);
            }
            $increment++;
        }

        $this->status = 'success: xml was parsed';
        return true;

    }

    private function findDuplicateKeys(){

        for($i=0;$i < count($this->valueArray); $i++) {
            // duplicate keys are when two complete tags are side by side
            if($this->valueArray[$i]['type'] == "complete"){
                if( $i+1 < count($this->valueArray) ){
                    if($this->valueArray[$i+1]['tag'] == $this->valueArray[$i]['tag'] && $this->valueArray[$i+1]['type'] == "complete"){
                        $this->duplicateKeys[$this->valueArray[$i]['tag']] = 0;
                    }
                }
            }
            // also when a close tag is before an open tag and the tags are the same
            if($this->valueArray[$i]['type'] == "close"){
                if( $i+1 < count($this->valueArray) ){
                    if(    $this->valueArray[$i+1]['type'] == "open" && $this->valueArray[$i+1]['tag'] == $this->valueArray[$i]['tag'])
                        $this->duplicateKeys[$this->valueArray[$i]['tag']] = 0;
                }
            }

        }

    }

    private function setArrayValue(&$array, $stack, $value){
        if ($stack) {
            $key = array_shift($stack);
            $this->setArrayValue($array[$key], $stack, $value);
            return $array;
        } else {
            $array = $value;
        }
    }

    public function getOutput(){
        return $this->output;
    }

    public function getStatus(){
        return $this->status;
    }

}

?>

Usage:

$p = new XMLParser($xml);
$p->getOutput();
Alf Marius Foss Olsen 12-Sep-2007 06:46
<?php
/*
  An easy lightweight (Array ->) XML -> Array algorithm..

  Typical case: You have an array you want to export to an external server,
                so you make XML out of it, exports it, and "on the other side"
                make it into an array again. These two functions will take care
                of that last part, ie XML -> Array

  NOTE! The function XMLToArray assumes that the XML _dont_ have nodes on the
        same level with the same name, then it just wont work. This is not a
        problem, as this case deals with Array -> XML -> Array, and an array
        cant have to identical indexes/keys.
*/

function XMLToArray($xml) {
  $parser = xml_parser_create('ISO-8859-1'); // For Latin-1 charset
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); // Dont mess with my cAsE sEtTings
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); // Dont bother with empty info
  xml_parse_into_struct($parser, $xml, $values);
  xml_parser_free($parser);

  $return = array(); // The returned array
  $stack = array(); // tmp array used for stacking
  foreach($values as $val) {
    if($val['type'] == "open") {
      array_push($stack, $val['tag']);
    } elseif($val['type'] == "close") {
      array_pop($stack);
    } elseif($val['type'] == "complete") {
      array_push($stack, $val['tag']);
      setArrayValue($return, $stack, $val['value']);
      array_pop($stack);
    }//if-elseif
  }//foreach
  return $return;
}//function XMLToArray

function setArrayValue(&$array, $stack, $value) {
  if ($stack) {
    $key = array_shift($stack);
    setArrayValue($array[$key], $stack, $value);
    return $array;
  } else {
    $array = $value;
  }//if-else
}//function setArrayValue

// USAGE:
$xml = <<<QQQ
<?xml version="1.0"?>
<root>
  <node1>Some text</node1>
  <node2a>
    <node2b>
      <node2c>Some text</node2c>
    </node2b>
  </node2a>
</root>\n
QQQ;
$array = XMLToArray($xml);
print "<pre>";
print_r($array);
print "</pre>";
//  Output:
//
//  Array
//  (
//      [root] => Array
//          (
//              [node1] => Some text
//              [node2a] => Array
//                  (
//                      [node2b] => Array
//                          (
//                              [node2c] => Some text
//                          )
//                  )
//          )
//  )
?>
vinod at citadel-soft dot com 01-Sep-2007 03:43
My previous code was having some bugs in, that is fixed now

<?php
class CSLXmlReader {
    private $tagstack;
    private $xmlvals;
    private  $xmlvarArrPos;
    private $xmlfile;
    function __construct($filename)  // constructor to intialize the stack and val array
    {

        $this->tagstack = array();   // contain the open tags till now
        $this->xmlvals = array();
        $this->xmlvarArrPos = $this->xmlvals;  // temporary variable to hold the current tag position
        $this->xmlfile = $filename;
    }
    function readDatabase()
    {
        // read the XML database
        $data = implode("", file($this->xmlfile));
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, $data, $values, $tags);
        xml_parser_free($parser);

        foreach($values as $key => $val)  //
        {
            if($val['type'] == "open")
            {
                array_push($this->tagstack, $val['tag']);
                $this->getArrayPath();
                if(count($this->xmlvarArrPos) > 0 && (!array_key_exists(0,$this->xmlvarArrPos)))
                {
                    $temp1 = $this->xmlvarArrPos;
                    $this->xmlvarArrPos =  array();
                    $this->xmlvarArrPos[0] = $temp1;
                    array_push($this->tagstack, 1);
                }
                else if( array_key_exists(0,$this->xmlvarArrPos)){
                    $opncount = count($this->xmlvarArrPos);
                    array_push($this->tagstack, $opncount);
                }
                $tagStackPointer += 1;
            }else if($val['type'] == "close")
            {
                while( $val['tag'] != ($lastOpened = array_pop($this->tagstack))){}
            }else if($val['type'] ==  "complete")
            {
                $this->getArrayPath();
                if( array_key_exists($val['tag'],$this->xmlvarArrPos))
                {
                    if(array_key_exists(0,$this->xmlvarArrPos[$val['tag']]))
                    {
                        $elementCount = count($this->xmlvarArrPos[$val['tag']]);
                        $this->xmlvarArrPos[$val['tag']][$elementCount] = $val['value'];
                    }else
                    {
                        $temp1 = $this->xmlvarArrPos[$val['tag']];
                        $this->xmlvarArrPos[$val['tag']] =  array();
                        $this->xmlvarArrPos[$val['tag']][0] = $temp1;
                        $this->xmlvarArrPos[$val['tag']][1] = $val['value'];
                    }
                } else
                {
                    $this->xmlvarArrPos[$val['tag']] = $val['value'];
                }
            }
        }
        reset($this->xmlvals);
        return $this->xmlvals;
    }
    function getArrayPath()
    {

        reset($this->xmlvals);
        $this->xmlvarArrPos = &$this->xmlvals;
        foreach($this->tagstack as $key)
        {
            $this->xmlvarArrPos = &$this->xmlvarArrPos[$key];

        }
    }

}

$readerObj  = new CSLXmlReader("test.xml");
$xmlvals = $readerObj->readDatabase();

echo "########## XML Values In array as the multidimentional array  #############\n";
echo "<pre>";
print_r($xmlvals);
echo "</pre>";

?>
siteres at gmail dot com 07-Feb-2007 01:38
PHP: XML to Array and backwards:

Here the XML with PHP solution: XML->Array and Array->XML.
Work with it as with usual array.

Sources are here:
http://mysrc.blogspot.com/2007/02/php-xml-to-array-and-backwards.html
(leave me comments:)

Example #1 (1.xml):

<ddd>
 <onemore dd="55">
  <tt>333</tt>
  <tt ss="s1">555</tt>
  <tt>777</tt>
 </onemore>
 <two>sdf rr</two>
</ddd>

The code:

$xml=xml2ary(file_get_contents('1.xml'));
print_r($xml);

Here is the Array result:

Array
(
   [ddd] => Array (
           [_c] => Array (
                   [_p] => Array *RECURSION*
                   [onemore] => Array (
                           [_a] => Array (
                                   [dd] => 55
                               )
                           [_c] => Array (
                                   [_p] => Array  *RECURSION*
                                   [tt] => Array (
                                           [0] => Array (
                                                   [_v] => 333
                                               )
                                           [1] => Array (
                                                   [_a] => Array (
                                                           [ss] => s1
                                                       )
                                                   [_v] => 555
                                               )
                                           [2] => Array (
                                                   [_v] => 777
                                               )
                                       )
                               )
                       )
                   [two] => Array (
                           [_v] => sdf rr
                       )
               )
       )
)
webmaster at after5webdesign dot com 30-Nov-2006 04:48
That parser also has a problem in which it will not parse more items than the current level it is on. That is, parsing this:  <1><2>A</2><2>B</2><2>C</2></1>
Will only result in this: A B
C is never processed.

It might be better with something like this:
          $file = get_url('http://news.search.yahoo.com/news/rss?p=current+events', URL_CONTENT);
          $data = $file['content'];
          $xml_parser = xml_parser_create();
          xml_parse_into_struct($xml_parser, $data, $vals, $index);
          xml_parser_free($xml_parser);
          //Uncomment the lines below to see the entire structure of your XML document
          //echo "<pre>INDEX: \n";
          //print_r ($index);
          //echo "\n \n \n VALUES:";
          //print_r ($vals);
          //echo "</pre>";
          $params = array();
          $level = array();
          $start_level = 1;
          foreach ($vals as $xml_elem) {
            if ($xml_elem['type'] == 'open') {
              if (array_key_exists('attributes',$xml_elem)) {
                list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
              } else {
                $level[$xml_elem['level']] = $xml_elem['tag'];
              }
            }
            if ($xml_elem['type'] == 'complete') {
              $php_stmt = '$params';
              while($start_level < $xml_elem['level']) {
                $php_stmt .= '[$level['.$start_level.']]';
                $start_level++;
              }
              $php_stmt .= '[$xml_elem[\'tag\']][] = $xml_elem[\'value\'];';
              eval($php_stmt);
              $start_level--;
            }
          }
          echo "<pre>";
          print_r ($params);
          echo "</pre>";

~Tim_Myth
A3 03-Nov-2006 05:28
XML -> Array
<?
    $data = '<root><a><b x="s" a="2">asdf</b><c></c></a></root>';

    $p = xml_parser_create();
    xml_parse_into_struct($p, $data, $vals);
    xml_parser_free($p);

    $key = $output = array();
   foreach ($vals as $id=>$item) {
      if ($item["type"]=="open" || $item["level"]>count($key)) {// && count($key)<=$item["level"])
          array_push($key, $id);
          $temp = array("tag"=>$item["tag"], "value"=>"", "attributes"=>array());
          eval("\$output[".implode("][", $key)."] = \$temp;");
      }
      if ($item["type"]=="close" || $item["level"]<count($key))// && $item["level"]>=count($key))
          array_pop($key);
      if (isset($item["attributes"]))
          eval("\$output[".implode("][", $key)."]['attributes'] = array_merge(\$output[".implode("][", $key)."]['attributes'], \$item['attributes']);");
      if (isset($item["value"]))
          eval("\$output[".implode("][", $key)."]['value'] .= \$item['value'];");
   }
?>
Elad Elrom 12-Sep-2006 02:14
This is a quick fix for parsing XML from remote URL, some of the example above will work when trying to parse on your local server without "http://" but not when trying to parse from remote server using "http://www.URL"...

<?
$file="http://www.URL.com/file.XML";

$xml_parser = xml_parser_create();

$handle = fopen($file, "rb");
$contents = '';
while (!feof($handle)) {
  $data .= fread($handle, 8192);
}
fclose($handle);

xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
   if (array_key_exists('attributes',$xml_elem)) {
     list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
   } else {
     $level[$xml_elem['level']] = $xml_elem['tag'];
   }
  }
  if ($xml_elem['type'] == 'complete') {
   $start_level = 1;
   $php_stmt = '$params';
   while($start_level < $xml_elem['level']) {
     $php_stmt .= '[$level['.$start_level.']]';
     $start_level++;
   }
   $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
   eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";
?>
efredricksen at gmail dot com 24-May-2006 12:55
Perhaps the one true parser:? I modified xademax's fine code to tidy it up, codewise and style wise, rationalize some minor crazyness, and make names fit nomenclature from the XML spec. (There are no uses of eval, and shame on you people who do.)

<?php
class XmlElement {
  var $name;
  var $attributes;
  var $content;
  var $children;
};

function xml_to_object($xml) {
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $xml, $tags);
  xml_parser_free($parser);

  $elements = array();  // the currently filling [child] XmlElement array
  $stack = array();
  foreach ($tags as $tag) {
    $index = count($elements);
    if ($tag['type'] == "complete" || $tag['type'] == "open") {
      $elements[$index] = new XmlElement;
      $elements[$index]->name = $tag['tag'];
      $elements[$index]->attributes = $tag['attributes'];
      $elements[$index]->content = $tag['value'];
      if ($tag['type'] == "open") {  // push
        $elements[$index]->children = array();
        $stack[count($stack)] = &$elements;
        $elements = &$elements[$index]->children;
      }
    }
    if ($tag['type'] == "close") {  // pop
      $elements = &$stack[count($stack) - 1];
      unset($stack[count($stack) - 1]);
    }
  }
  return $elements[0];  // the single top-level element
}

// For example:
$xml = '
<parser>
   <name language="en-us">Fred Parser</name>
   <category>
       <name>Nomenclature</name>
       <note>Noteworthy</note>
   </category>
</parser>
';
print_r(xml_to_object($xml));
?>

will give:

xmlelement Object
(
    [name] => parser
    [attributes] =>
    [content] =>
    [children] => Array
        (
            [0] => xmlelement Object
                (
                    [name] => name
                    [attributes] => Array
                        (
                            [language] => en-us
                        )

                    [content] => Fred Parser
                    [children] =>
                )

            [1] => xmlelement Object
                (
                    [name] => category
                    [attributes] =>
                    [content] =>
                    [children] => Array
                        (
                            [0] => xmlelement Object
                                (
                                    [name] => name
                                    [attributes] =>
                                    [content] => Nomenclature
                                    [children] =>
                                )

                            [1] => xmlelement Object
                                (
                                    [name] => note
                                    [attributes] =>
                                    [content] => Noteworthy
                                    [children] =>
                                )

                        )

                )

        )

)
Stuart 23-May-2006 03:26
This is a great little function for a lot of XML work, but note that this function does not handle XML entities properly.

The basic XML entities &lt; &gt; &amp; &quot; are fine, just anything else will not work:

If the entity is defined in the XML header, the parser will drop it completely from the struct it creates.

If the entity is not defined in the XML then the parser will crash out with an undefined entity error.

You should be able to work around this limitation by using a preg_replace on your XML string before passing it to the parser.

(Further details in Bug #35271; this is just a warning to those thinking of using this function for parsing real XML documents not just trivial XML examples)
xademax at gmail dot com 08-Jan-2006 12:15
This is just another simple xml parser :)

<?php

class Xml
{
    var $tag;
    var $value;
    var $attributes;
    var $next;
}

function xml2array($xml_string)
{
    $Parser = xml_parser_create();
    xml_parser_set_option($Parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($Parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($Parser, $xml_string, $Xml_Values);
    xml_parser_free($Parser);
    $XmlClass = array();
    $LastObj = array();
    $NowObj = &$XmlClass;

    foreach($Xml_Values as $Xml_Key => $Xml_Value)
    {
        $Index = count($NowObj);
        if($Xml_Value["type"] == "complete")
        {
            $NowObj[$Index] = new Xml;
            $NowObj[$Index]->tag = $Xml_Value["tag"];
            $NowObj[$Index]->value = $Xml_Value["value"];
            $NowObj[$Index]->attributes = $Xml_Value["attributes"];
        }
        elseif($Xml_Value["type"] == "open")
        {
            $NowObj[$Index] = new Xml;
            $NowObj[$Index]->tag = $Xml_Value["tag"];
            $NowObj[$Index]->value = $Xml_Value["value"];
            $NowObj[$Index]->attributes = $Xml_Value["attributes"];
            $NowObj[$Index]->next = array();
            $LastObj[count($LastObj)] = &$NowObj;
            $NowObj = &$NowObj[$Index]->next;
        }
        elseif($Xml_Value["type"] == "close")
        {
            $NowObj = &$LastObj[count($LastObj) - 1];
            unset($LastObj[count($LastObj) - 1]);
        }

    }

    return $XmlClass;
}

$String = "
<parser>
    <parseur_name>MyParser</parseur_name>
    <category>
        <name>Name 1</name>
        <note>A note 1</note>
    </category>
</parser>
";
$Xml = xml2array($String);

print_r($Xml);
?>

This exemple will show :
Array
(
    [0] => Xml Object
        (
            [tag] => parser
            [value] =>
            [attributes] =>
            [next] => Array
                (
                    [0] => Xml Object
                        (
                            [tag] => parseur_name
                            [value] => MyParser
                            [attributes] =>
                            [next] =>
                        )

                    [1] => Xml Object
                        (
                            [tag] => category
                            [value] =>
                            [attributes] =>
                            [next] => Array
                                (
                                    [0] => Xml Object
                                        (
                                            [tag] => name
                                            [value] => Name 1
                                            [attributes] =>
                                            [next] =>
                                        )

                                    [1] => Xml Object
                                        (
                                            [tag] => note
                                            [value] => A note 1
                                            [attributes] =>
                                            [next] =>
                                        )

                                )

                        )

                )

        )

)
mbirth at webwriters dot de 08-Nov-2005 03:48
Searching for a nice and working way to get a RSS feed into an array-structure, I found the solution posted by kieran but disliked those several eval()s. So I wrote my own using references/pointers.

<?php

class RSSParser {

  var $struct = array();  // holds final structure
  var $curptr;  // current branch on $struct
  var $parents = array();  // parent branches of current branch

  function RSSParser($url) {
    $this->curptr =& $this->struct;  // set ref to base
    $xmlparser = xml_parser_create();
    xml_set_object($xmlparser, $this);
    xml_set_element_handler($xmlparser, 'tag_open', 'tag_close');
    xml_set_character_data_handler($xmlparser, 'cdata');
    $fp = fopen($url, 'r');

    while ($data = fread($fp, 4096))
      xml_parse($xmlparser, $data, feof($fp))
      || die(sprintf("XML error: %s at line %d",
         xml_error_string(xml_get_error_code($xmlparser)),
         xml_get_current_line_number($xmlparser)));

    fclose($fp);
    xml_parser_free($xmlparser);
  }

  function tag_open($parser, $tag, $attr) {
    $i = count($this->curptr['children']);
    $j = count($this->parents);
    $this->curptr['children'][$i]=array();  // add new child element
    $this->parents[$j] =& $this->curptr;  // store current position as parent
    $this->curptr =& $this->curptr['children'][$i];  // submerge to newly created child element
    $this->curptr['name'] = $tag;
    if (count($attr)>0) $this->curptr['attr'] = $attr;
  }

  function tag_close($parser, $tag) {
    $i = count($this->parents);
    if ($i>0) $this->curptr =& $this->parents[$i-1];  // return to parent element
    unset($this->parents[$i-1]);  // clear from list of parents
  }

  function cdata($parser, $data) {
    $data = trim($data);
    if (!empty($data)) {
      $this->curptr['value'] .= $data;
    }
  }

}

$myparser = new RSSParser('getitems.xml');
$anotherparser = new RSSParser('http://johndoe:secret@myfeeds.com/getfeed.xml');

print_r($myparser->struct);
print_r($anotherparser->struct);

?>
kieran at kieran dot ca 20-Oct-2005 09:20
<?
/*
|
| _xml2array - another abstraction layer on xml_parse_into_struct
|              that returns a nice nested array.
|
|      @param: $xml is a string containing a full xml document
|
|     returns: a nested php array that looks like this:
|
|              array
|              (
|                  [_name] => the name of the tag
|                  [_attributes] => an array of 'attribute'=>'value' combos
|                  [_value] => the text contents of the node
|                  [_children] => an array of these arrays, one for each node.
|              )
|
|       notes: thanks to 'jeffg at activestate dot com' who inspired
|              me to essentially re-write his example code from php.net
|
|           me: Kieran Huggins < kieran[at]kieran[dot]ca >
|
*/
function _xml2array($xml){
    global $keys;
    global $level;
    if(!is_array($xml)){ // init on first run
        $raw_xml = $xml;
        $p = xml_parser_create();
        xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($p, $raw_xml, $xml, $idx);
        xml_parser_free($p);
    }
    for($i=0;$i<count($xml,1);$i++){
        // set the current level
        $level = $xml[$i]['level'];

        if($level<1)break;

        // mark this level's tag in the array
        $keys[$level] = '['.$i.']';

        // if we've come down a level, sort output and destroy the upper level
        if(count($keys)>$level) unset($keys[count($keys)]);

        // ignore close tags, they're useless
        if($xml[$i]['type']=="open" || $xml[$i]['type']=="complete"){

            // build the evalstring
            $e = '$output'.implode('[\'_children\']',$keys);

            // set the tag name
            eval($e.'[\'_name\'] = $xml[$i][\'tag\'];');

            // set the attributes
            if($xml[$i]['attributes']){
                eval($e.'[\'_attributes\'] = $xml[$i][\'attributes\'];');
            }

            // set the value
            if($xml[$i]['value']){
                eval($e.'[\'_value\'] = trim($xml[$i][\'value\']);');
            }

        }

    }

    return $output;
}
?>
Chris Hester 28-Jul-2005 05:06
The array generated from XML stores not only the elements but also any spaces and linebreaks between the tags. This results in a much longer array. (I had 24 array fields instead of 10!) To cure this use the following code when creating the parser:

<?php
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE,1);
?>
grusin at gmail dot com 19-Jul-2005 11:54
Here is a simple patch to peter's xml2array function.

Replace:

<?
case 'open':
$tag_or_id = (array_key_exists ('attributes', xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
$ptrs[$level][$tag_or_id] = array ();
$ptrs[$level+1] = & $ptrs[$level][$tag_or_id];
break;
?>

with:

<?
case 'open':
$tag_or_id = (array_key_exists ('attributes', $xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
$ptrs[$level][$tag_or_id][] = array ();
$ptrs[$level+1] = & $ptrs[$level][$tag_or_id][count($ptrs[$level][$tag_or_id])-1];
break;
?>

and now code should handle multiple element case :)
Dustin 13-Jul-2005 08:39
If you happen to have problems with weird charaters, I added this code to the first line of dUDA's function:

$XML = utf8_decode($XML);
PhF at madmac dot fr 23-Jun-2005 01:11
The code previously posted by noob at noobsrule dot com doesn't work when the same tag name is used at different levels.
(but perhaps "$php_used_prefix" was intended for that ?)
For example:
<RatedShipment>
  <TransportationCharges>
    ...
  </TransportationCharges>
  <RatedPackage>
    <TransportationCharges>
      ...
    </TransportationCharges>
  </RatedPackage>
</RatedShipment>
<?php
    $p = xml_parser_create();
    xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($p, $UPSxml, $values, $idx);
    xml_parser_free($p);

    // tracking used keys
    $usedKeys = array();
    $deepLevel = -1;

    // start a php array string (evaluated later)
    $forEvalPrefix = '$xml_array';

    // loop throught the value array
    foreach ($values as $key => $val) {
        $tagName = $val['tag']; // pass the key tag into a more friendly looking variable
        $level = $val['level']; // idem
        if($val['type'] == 'open') {
            $deepLevel++; // increase deep level
            $forEvalPrefix .= '[\''. $tagName .'\']';

            // begin used keys checks to allow multidimensionatity under the same tag
            (isset($usedKeys[$level][$tagName])) ? $usedKeys[$level][$tagName]++ : $usedKeys[$level][$tagName] = 0;
            $forEvalPrefix .= '['. $usedKeys[$level][$tagName] .']';
        }
        if($val['type'] == 'complete') {
            ($level > $deepLevel) ? $deepLevel++ : ''; // increase $deepLevel only if current level is bigger
            $tagValue = addslashes($val['value'] ); // format the value for evaluation as a string
            $forEvalSuffix = '[\''. $tagName .'\'] = \''. $tagValue .'\';'; // create a string to append to the current prefix
            $forEval = $forEvalPrefix . $forEvalSuffix; // (without "$php_used_prefix"...)
            eval($forEval); // write the string to the array structure
        }
        if($val['type'] == 'close') {
            unset($usedKeys[$deepLevel]); // Suppress tagname's keys useless
            $deepLevel--;
            $forEvalPrefix = substr($forEvalPrefix, 0, strrpos($forEvalPrefix, '[')); // cut off the used keys node
            $forEvalPrefix = substr($forEvalPrefix, 0, strrpos($forEvalPrefix, '[')); // cut off the end level of the array string prefix
        }
    }
echo '<pre>';
print_r ($xml_array);
echo '</pre>';
?>

MADmac ;-)
peter at elemental dot org 15-Jun-2005 08:46
Quick addendum to my post below... The code does *not* handle cases where multiple elements are used without attribute IDs, as is the case with the moldb example.  (It is probably worth noting that some of the other code below doesn't do this either, and is still more complex.)

It is not difficult to add that functionality, but I have yet to find an elegant way to integrate that feature, and since I don't need that functionality at the moment, I'm going leave that as an exercise to the reader.  ;-)

-p.
peter at elemental dot org 14-Jun-2005 04:09
Some of the code posted previously seemed absurdly complex, so I thought I'd see if I could simplify things a bit. Here's what I came up with.  (I'm still a PHP newbie, so perhaps I simplified too much.  ;-)  Untested for speed, but it *should* be pretty quick since it uses references instead of lookups or (gack) evals.

Enjoy!

/*
 *  Convert a string containing XML into a nested array
 *
 *  Takes a raw XML string as input
 *  Returns a nested array
 */

function xml2array ($xml_data)
{
    // parse the XML datastring
    $xml_parser = xml_parser_create ();
    xml_parse_into_struct ($xml_parser, $xml_data, $vals, $index);
    xml_parser_free ($xml_parser);

    // convert the parsed data into a PHP datatype
    $params = array();
    $ptrs[0] = & $params;
    foreach ($vals as $xml_elem) {
        $level = $xml_elem['level'] - 1;
        switch ($xml_elem['type']) {
        case 'open':
            $tag_or_id = (array_key_exists ('attributes', $xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
            $ptrs[$level][$tag_or_id] = array ();
            $ptrs[$level+1] = & $ptrs[$level][$tag_or_id];
            break;
        case 'complete':
            $ptrs[$level][$xml_elem['tag']] = (isset ($xml_elem['value'])) ? $xml_elem['value'] : '';
            break;
        }
    }

    return ($params);

}
gleber at mapnet dot pl 26-Mar-2005 03:03
XMLtoArray created by dudus at onet dot pl was not good enough for me, that's why i decided to create my own version, and here's the result:

<?php

function &last(&$array) {
if (!count($array)) return null;
end($array);
return $array[key($array)];
}

function myParseXML(&$vals, &$dom, &$lev) {
    do {
        $curr = current($vals);
        $lev = $curr['level'];
        switch ($curr['type']) {
            case 'open':
                if (isset($dom[$curr['tag']])) {
                    $tmp = $dom[$curr['tag']];
                    if (!$tmp['__multi'])
                        $dom[$curr['tag']] = array('__multi' => true, $tmp);
                    array_push($dom[$curr['tag']], array());
                    $new =& last($dom[$curr['tag']]);
                } else {
                    $dom[$curr['tag']] = array();
                    $new =& $dom[$curr['tag']];
                }
                next($vals);
                myParseXML(&$vals, $new, $lev);
                break;
            case 'cdata':
                break;
            case 'complete':
                if (!isset($dom[$curr['tag']]))
                    $dom[$curr['tag']] = $curr['value'];
                else {
                    if (is_array($dom[$curr['tag']]))
                        array_push($dom[$curr['tag']] , $curr['value']);
                    else
                        array_push($dom[$curr['tag']] = array($dom[$curr['tag']]) , $curr['value']);
                }
                break;
            case 'close':
                return;
        }
    }
    while (next($vals)!==FALSE);
}

function MyXMLtoArray($XML) {
       $xml_parser = xml_parser_create();
       xml_parse_into_struct($xml_parser, $XML, $vals);
       xml_parser_free($xml_parser);
       reset($vals);
       $dom = array(); $lev = 0;
       myParseXML($vals, $dom, $lev);
       return $dom;
}

?>

MyXMLtoArray() is that function you should call, other are for "internal" use.

P.S. It's 4-5 time faster then dudus at onet dot pl 's code
noob at noobsrule dot com 24-Jan-2005 10:59
This is my first time contributing but I found all the examples either didn't work or were beyond my comprehension.  I also wanted to maintain the XML multi-dimensionality so I could do loops based on keys I was expecting rather than numbers or some other whatnot.  This script is probably way inefficient, but should give you a multidimensional array with a depth that will match the XML source.  Great for situations when you aren't sure what you'll be getting back.  Its also only based on the values array of xml_parse_into_str() using the 3 tag types (open, complete, and close) -- hopefully it will make more sense to other noobs.

Basically it just constructs a string ($php_prefix) that is tweaked if it hits an "open" or "close" tag and evaluated if it hits a "complete" tag.

Thanks.

<?php

# initiate curl session...
$ch = curl_init( "http://yourtargethost" ) or die ( "could not initialize curl" );

# set curl options...
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $request_str );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 0 );
curl_setopt( $ch, CURLOPT_REFERER, https://foobar.com" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );

# execute curl commands...
$curl_result = curl_exec( $ch ) or die ( "could not execute the post" );
curl_close( $ch ); // close curl session

# pass the XML result into 2 arrays ( index and values )...
$p = xml_parser_create();
xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($p, $curl_result, $vals, $index);
xml_parser_free($p);

# create an empty used key tracker...
$used_keys = array();

# start a php array string (evaluated later)...
$php_prefix = "$"."my_array";

# loop through the values array...
foreach ($vals as $key => $val) {
    if( $val['type'] == "open" ) {
        $my_tag = $val['tag']; // pass the key tag into a more friendly looking variable...
        $php_prefix .= "['".$my_tag."']"; # add a new level to the array string...

        # begin used key checks to allow multidimensionality under the same tag, adds a number to the prefix if necessary...
        if( ! array_key_exists( $my_tag, $used_keys ) ) {
            $used_keys[$my_tag] = 0;
            $php_prefix .= "[".$used_keys[$my_tag]."]";
        }else {
            $used_keys[$my_tag]++; // increment the key tracker to avoid overwriting existing key...
            $php_prefix .= "[".$used_keys[$my_tag]."]";
        }
    } elseif( $val['type'] == "complete" ) {
        $my_value = addslashes( $val['value'] ); # format the value for evaluation as a string...
        $php_suffix = "['".$val['tag']."'] = \"".$my_value."\";"; # create a string with the tag and value to append to the current prefix (just used here)...
        $php_str = $php_prefix.$php_used_prefix.$php_suffix;
        eval( $php_str ); # write the string to the array structure...
    }
    if( $val['type'] == "close" ) {
        $php_prefix = substr( $php_prefix, 0, strrpos( $php_prefix, "[" ) ); # cut off the used keys node...
        $php_prefix = substr( $php_prefix, 0, strrpos( $php_prefix, "[" ) ); # cut off the end level of the array string prefix...
    }
}

echo "<pre>";
//print_r ($index);
//echo "<br><br><br>";
//print_r ($vals);
//echo "<br><br><br>";
print_r ($my_array);
echo "</pre>";

?>
dudus at onet dot pl 18-Jan-2005 06:33
This function return array from XML. Included attributes and tags in same level.
I wrote this function based on mmustafa code.

enjoy!
dUDA

-------------------------------

<?
function XMLtoArray($XML)
{
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $XML, $vals);
    xml_parser_free($xml_parser);
    // wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
    $_tmp='';
    foreach ($vals as $xml_elem)
    {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_level!=1 && $x_type == 'close')
        {
            if (isset($multi_key[$x_tag][$x_level]))
                $multi_key[$x_tag][$x_level]=1;
            else
                $multi_key[$x_tag][$x_level]=0;
        }
        if ($x_level!=1 && $x_type == 'complete')
        {
            if ($_tmp==$x_tag)
                $multi_key[$x_tag][$x_level]=1;
            $_tmp=$x_tag;
        }
    }
    // jedziemy po tablicy
    foreach ($vals as $xml_elem)
    {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_type == 'open')
            $level[$x_level] = $x_tag;
        $start_level = 1;
        $php_stmt = '$xml_array';
        if ($x_type=='close' && $x_level!=1)
            $multi_key[$x_tag][$x_level]++;
        while($start_level < $x_level)
        {
              $php_stmt .= '[$level['.$start_level.']]';
              if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
                  $php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
              $start_level++;
        }
        $add='';
        if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete'))
        {
            if (!isset($multi_key2[$x_tag][$x_level]))
                $multi_key2[$x_tag][$x_level]=0;
            else
                $multi_key2[$x_tag][$x_level]++;
             $add='['.$multi_key2[$x_tag][$x_level].']';
        }
        if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes',$xml_elem))
        {
            if ($x_type == 'open')
                $php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
            else
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
            eval($php_stmt_main);
        }
        if (array_key_exists('attributes',$xml_elem))
        {
            if (isset($xml_elem['value']))
            {
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
                eval($php_stmt_main);
            }
            foreach ($xml_elem['attributes'] as $key=>$value)
            {
                $php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
                eval($php_stmt_att);
            }
        }
    }
     return $xml_array;
}    // END XMLtoArray
?>
memandeemail at gmail dot com 03-Dec-2004 04:32
If you have de XML:
<?xml version="1.0" encoding="iso-8859-1"?>
<teste>
    <teste>
        <teste>
        </teste>
    </teste>
</teste>

this function will return this tags:
Array
(
    [teste] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 4
        )

)

With this function (right below) will convert the struc to OPEN and CLOSE concept.

The New Struct:
Array
(
    [teste] => Array
        (
            [0] => 0
            [1] => 4
            [2] => 1
            [3] => 3
            [4] => 2
        )

)
The Function:

<?php
/**
 * @return bool
 * @param xml_array $values
 * @param xml_array[reference] $tags
 * @desc Reconstruct xml_parse_into_struct
*/
function reconstruct_tag($values, &$tags) {
    unset($return);
    foreach ($tags as $tkey => $tvalue) {
        foreach ($tvalue as $vvalue) {
            if ($values[$vvalue]['type'] == 'open' or $values[$vvalue]['type'] == 'complete') {
                $return[$tkey][] = $vvalue;
            }
            if ($values[$vvalue]['type'] == 'open') {
                foreach ($tvalue as $tv_value) {
                    if ($values[$tv_value]['type'] == 'close'
                    and $values[$tv_value]['level'] == $values[$vvalue]['level']
                    and $tv_value > $vvalue) {
                        $return[$tkey][] = $tv_value;
                        break;
                    }
                }
            }
        }
    }
    $tags = $return;
    return (bool) $tags;
}
?>

Ahh, DO NOT forget this comment:

jukkaho at mail dot student dot oulu dot fi
29-Jun-2004 12:17
Everyone seems to forget the return value of this function (including people making examples!), but it is there for a reason:
0 if failed (invalid XML), 1 if succeeded.

Return value really is an integer, be careful with those === operators.
happyseb at free dot fr 24-Aug-2004 08:51
I would just add something about the solution proposed by "gordon at kanazawa dot ac dot jp".

Something went wrong about the fact that "cdata" are treated the same way as "complete" in the xml_get_children first and in the xml_get_child then.

When ?
with this method, something like this :
<tagA>
  <tagB>valueB</tagB>
  valueA
  <tagC>valueC</tagC>
</tagA>
is considered as the same thing as
<tagA>
  <tagB>valueB</tagB>
  <tagA>valueA</tagA>
  <tagC>valueC</tagC>
</tagA>

The algorithm is nomore bijective.

Even if it might not be perfect :-) i propose a little modification of the xml_get_child function :

function xml_get_child(&$v, $children=NULL) {
      $c = array(); // the "child"
      if (isset($v['tag']) && $v['type'] != 'cdata') $c['tag'] = $v['tag'];
      if (isset($v['value'])) $c['value'] = $v['value'];
      if (isset($v['attributes'])) $c['attributes'] = $v['attributes'];
      if (is_array($children)) $c['children'] = $children;
      return $c;
}

moreover, the following function will take the tree (made from the xml_get_tree function) as a parameter and build the xml content back

    /*
    // setTree
    // set xml Tree from a well-formed array
    // manage indentation
    // Parameters are :
    // $1 (needed) : Tree to transform
    // $2 (optional) : Indentation type (default is one tabulation)
    // $3 (optional) : First indent (default is empty string)
    */

    function setTree($Atree, $indentType = '    ', $Sindent = '')
    {
      if (! isset ($Atree['tag']) && isset ($Atree['value'])) return ($Sindent.trim($Atree['value'])."\r\n") ;
      else {
        $Stemp = $Sindent.'<'.$Atree['tag'].' ' ;
        if (isset ($Atree['attributes']) && is_array ($Atree['attributes'])) {
          foreach ($Atree['attributes'] as $Aattribute => $Svalue) $Stemp .= $Aattribute.'="'.$Svalue.'" ' ;
        }
        if (! isset ($Atree['children']) && ! isset ($Atree['value'])) $Stemp .= '/>'."\r\n" ;
        else {
          $Stemp .= '>'."\r\n" ;
          if (isset ($Atree['value'])) $Stemp .= $Sindent.$indentType.trim($Atree['value'])."\r\n" ;
          if (isset ($Atree['children']) && is_array ($Atree['children']))
            foreach ($Atree['children'] as $Achild) $Stemp .= $this->setTree($Achild, $indentType, $Sindent.$indentType) ;
          $Stemp .= $Sindent.'</'.$Atree['tag'].'>'."\r\n" ;
        }
        return ($Stemp) ;
      }
    }
sdh33 at cornell dot edu 13-Jun-2004 10:12
(The previous post I wrote was incorrect.  I fix that herein)
I used the algorithm from stephane for writing back to a file, but ran into the following problem.  My original XML looks like

<ENTRY id="1"> ... </ENTRY><ENTRY id="2"> ... </ENTRY>

This got saved back as

<1> ... </1><2> ... </2>,

which expat doesn't like.  So I propose the following modification:

function writeXmlToFile($data, $f, $niv = 0) {
  foreach($data as $name => $elem) {
    if (preg_match("/\A[0-9]/",$name)) {
      $open = "ENTRY id=\"$name\""; $name = "ENTRY";
    } else {
      $open = $name;
    }
    if(is_array($elem)) {
      fwrite($f, str_repeat("  ", $niv)."<".$open.">"."\n");
      writeXmlToFile($elem, $f, $niv + 1);
      fwrite($f, str_repeat("  ", $niv)."</".$name.">"."\n");
    } else {
      fwrite($f, str_repeat("  ", $niv)."<".$open.">".$elem."</".$name.">"."\n");
    }
  }
}
stephane dot dekeyzer at noemail dot com 08-Apr-2004 11:54
for writing the array of mmustafa back to a xml file, use this code:

function writeXmlFile($fileName, $struct){
  $f = fopen($fileName, "w");
  writeXmlToFile($struct, $f);
  fclose($f);
}

function writeXmlToFile($data, $f, $niv = 0){
  foreach($data as $name => $elem){
    if(is_array($elem)){
      fwrite($f, str_repeat("  ", $niv)."<".$name.">"."\n");
      writeXmlToFile($elem, $f, $niv + 1);
      fwrite($f, str_repeat("  ", $niv)."</".$name.">"."\n");
    }
    else{
      fwrite($f, str_repeat("  ", $niv)."<".$name.">".$elem."</".$name.">"."\n");
    }
  }
}
mmustafa at vsnl dot com 06-Jan-2004 12:19
A small and simple php code to convert the raw array returned by xml_parse_into_struct into a proper data structure ..

<?php
$file = "data.xml";
$xml_parser = xml_parser_create();

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

$data = fread($fp, filesize($file));
fclose($fp);
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
    if (array_key_exists('attributes',$xml_elem)) {
      list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
    } else {
      $level[$xml_elem['level']] = $xml_elem['tag'];
    }
  }
  if ($xml_elem['type'] == 'complete') {
    $start_level = 1;
    $php_stmt = '$params';
    while($start_level < $xml_elem['level']) {
      $php_stmt .= '[$level['.$start_level.']]';
      $start_level++;
    }
    $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
    eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";
?>

Converts an XML document like ..

<country id="ZZ">
<name>My Land</name>
<location>15E</location>
<area>40000</area>
<state1>
<name>Hi State</name>
<area>1000</area>
<population>2000</population>
<city1>
<location>13E</location>
<population>500</population>
<area>500</area>
</city1>
<city2>
<location>13E</location>
<population>500</population>
<area>5000</area>
</city2>
</state1>
<state2>
<name>Low State</name>
<area>3000</area>
<population>20000</population>
<city1>
<location>15E</location>
<population>5000</population>
<area>1500</area>
</city1>
</state2>
</country>

To a php datastructure like ..

Array
(
    [ZZ] => Array
        (
            [NAME] => My Land
            [LOCATION] => 15E
            [AREA] => 40000
            [STATE1] => Array
                (
                    [NAME] => Hi State
                    [AREA] => 1000
                    [POPULATION] => 2000
                    [CITY1] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 500
                        )

                    [CITY2] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 5000
                        )

                )

            [STATE2] => Array
                (
                    [NAME] => Low State
                    [AREA] => 3000
                    [POPULATION] => 20000
                    [CITY1] => Array
                        (
                            [LOCATION] => 15E
                            [POPULATION] => 5000
                            [AREA] => 1500
                        )

                )

        )

)
bisqwit at iki dot fi dot not dot for dot ads dot invalid 20-Nov-2002 08:33
I made my own xml2tree()-function.
The difference to the previously suggested ones on this manual page is that this creates a tree where the tags are keys.

Example input:

<tree>
 <leaf name="gruu"> pl?? </leaf>
 <animal type="cat" />
</tree>

Example output:

Array
( 'tree' => Array
     ( 0 => Array
          ( 'children' => Array
               ( 'leaf' => Array
                    ( 0 => Array
                         ( 'attrs' => Array('name' => 'gruu'),
                           'values' => Array(0 => ' pl?? ')
                    )    ),
                 'animal' => Array
                    ( 0 => Array
                         ( 'attrs' => Array('type' => 'cat')
)    )   )    )    )   )

function xml2tree2($string)
{
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $string, $vals, $index);
  xml_parser_free($parser);

  $stack = array( array() );
  $stacktop = 0;
  $parent = array();
  foreach($vals as $val)
  {
    $type = $val['type'];
    if($type=='open' || $type=='complete')
    {
      // open tag
      $stack[$stacktop++] = $tagi;
      $tagi = array('tag' => $val['tag']);

      if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
      if(isset($val['value']))
        $tagi['values'][] = $val['value'];
    }
    if($type=='complete' || $type=='close')
    {
      // finish tag
      $tags[] = $oldtagi = $tagi;
      $tagi = $stack[--$stacktop];
      $oldtag = $oldtagi['tag'];
      unset($oldtagi['tag']);
      $tagi['children'][$oldtag][] = $oldtagi;
      $parent = $tagi;
    }
    if($type=='cdata')
    {
      $tagi['values'][] = $val['value'];
    }
  }
  return $parent['children'];
}

Ps: Note that the xml parsing for some reason chokes if the values contain <> (even inside ""). You need to escape them as &lt; and &gt;.
Same for & (for obvious reasons). Escape it as &amp;.
For example "&nbsp;" should be written as "&amp;nbsp;".
09-Aug-2002 01:20
This is based on a comment above by mh@mainlab.de.  This version makes more sense to me and I included a few comments that might make it more usefull for specific purposes.

// Look through $vals and $index,
// generated by parse_xml_data(),
// for $location.  $location resembles a unix path.
// E.g. "my/xml/path/to/my/data".
// Note: This is NOT a full-feature xml utility.
// Your path must be unique in the xml data
// and the tags must not contain slashes.
//
// returns: cdata from last element of $location
//          or NULL.
function get_xml_values($vals, $index, $location) {
  $location = explode('/', $location);
  $location_level = count($location);
  for ($n=0; $n<$location_level; ++$n) {
    $val_indexes=$index[$location[$n]];
    $good=0;
    for ($i=0; $i<count($val_indexes); ++$i) {
      $v = $vals[$val_indexes[$i]];
      // level is 1 based, n is 0 based:
      if ($v['level']-1 == $n) {
        if ($v['type'] == 'open') {
          // We found an open tag at the correct level.
          $good=1;
          break; // Remove break to avoid 'open' hiding
                 // 'complete' at last $n. (Speed Vs. Robustness:
                 // For now, I'm going with speed).
        }
        if ($v['type'] == 'complete') {
          // We found it, after finding all the prior elements:
          // You may want to change this to
          // return $v
          // so you can call $v['value'] and $v['attributes']
          return $v['value'];
        }
      }
    }
    if (!$good) {
      return NULL;
    }
  }
}
farinspace-at-hotmail-dot-com 20-Jul-2002 06:41
Wow, took a while to consume all of this. I am a noobie at XML, in fact i just really started working with it today. I went ahead and added to the above code by gdemartini@bol.com.br. I also added the update by nyk@cowham.net.

Added 'value' => $vals[$i]['value'] to the open case, as some nodes have both cdata as well as a children node. In previous versions of the functions the cdata of a node(a) that also had children would get stored in the children's array of the parent node(a). Now only children values are in the children array and the cdata is in the value key of the parent node(a).

Added 'value' => $vals[$i]['value'] to tree array as the vals array produced by PHP includes a value to the top most node if no children exist (for completeness).

Also, using xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE,1) will strip all white space from both around the XML tags as well as inside the cdata. I added a piece of code by waldo@wh-e.com to take care of this. All SPACE characters are now only stripped from around the XML tags and cdata spacing is retained.

CODE:
***************************************

function GetChildren($vals, &$i) {

    $children = array();

    while (++$i < sizeof($vals)) {

        // compair type
        switch ($vals[$i]['type']) {

            case 'cdata':
                $children[] = $vals[$i]['value'];
                break;
            case 'complete':
                $children[] = array(
                    'tag' => $vals[$i]['tag'],
                    'attributes' => $vals[$i]['attributes'],
                    'value' => $vals[$i]['value']
                );
                break;
            case 'open':
                $children[] = array(
                    'tag' => $vals[$i]['tag'],
                    'attributes' => $vals[$i]['attributes'],
                    'value' => $vals[$i]['value'],
                    'children' => GetChildren($vals, $i)
                );
                break;
            case 'close':
                return $children;
        }
    }
}

function GetXMLTree($file) {

    $data = implode('', file($file));

    // by: waldo@wh-e.com - trim space around tags not within
    $data = eregi_replace(">"."[[:space:]]+"."<","><",$data);

    // XML functions
    $p = xml_parser_create();

    // by: anony@mous.com - meets XML 1.0 specification
    xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
    xml_parse_into_struct($p, $data, &$vals, &$index);
    xml_parser_free($p);

    $i = 0;
    $tree = array();
    $tree[] = array(
        'tag' => $vals[$i]['tag'],
        'attributes' => $vals[$i]['attributes'],
        'value' => $vals[$i]['value'],
        'children' => GetChildren($vals, $i)
    );

    return $tree;
}

***************************************
dave at ovumdesign dot com 03-Apr-2002 03:32
Here is another variation on gdemartini@bol.com.br's nice tree algorithm. I have included nyk@cowham.net's "cdata" suggestion. I made a few changes to suppress unitialized variable warnings with error_reporting(E_ALL), and made a few stylistic changes.

There are two functional modifications as well. The first is the added option to expat to turn off "case folding", since XML is technically a case-sensitive language. The second is the returned tree - instead of returning a single-element list (an array with index 0 pointing to the top node) like the original algorithm, it returns the top node itself. This saves you an unnecessary level of indirection.

function xml_get_children($vals, &$i) {
    $children = array();
    if (isset($vals[$i]['value'])) $children[] = $vals[$i]['value'];

    while (++$i < count($vals)) {
        switch ($vals[$i]['type']) {
        case 'cdata':
            $children[] = $vals[$i]['value'];
            break;

        case 'complete':
            $children[] = array(
                'tag'        => $vals[$i]['tag'],
                'attributes' => isset($vals[$i]['attributes'])?
                                $vals[$i]['attributes'] : null,
                'value'      => $vals[$i]['value'],
            );
            break;

        case 'open':
            $children[] = array(
                'tag'        => $vals[$i]['tag'],
                'attributes' => isset($vals[$i]['attributes'])?
                                $vals[$i]['attributes'] : null,
                'children'   => xml_get_children($vals, $i),
            );
            break;

        case 'close':
            return $children;
        }
    }
}

function xml_get_tree($file) {
    $data = join('', file($file));

    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE,   1);
    xml_parse_into_struct($parser, $data, $vals, $index);
    xml_parser_free($parser);

    return array(
        'tag'        => $vals[0]['tag'],
        'attributes' => isset($vals[0]['attributes'])?
                        $vals[0]['attributes'] : null,
        'children'   => xml_get_children($vals, $i = 0),
    );
}

This function takes a tree returned by xml_get_tree() and simplifies it similarly to voncken@mailandnews.com and oknapp@soly.de's suggestions. It finds any nodes that expat considered "complete" (childless) and contain no attributes, and it moves the tag name (as the key) and value into an element in the parent node's "values" array.

For example:
$tree = xml_get_tree('moldb.xml');
$tree = xml_condense_tree($tree);
echo $tree['children'][1]['values']['name'];

Outputs:
Lysine

function xml_condense_tree($tree) {
    foreach ($tree['children'] as $index => $node) {
        if (isset($node['children'])) {
            $tree['children'][$index] = xml_condense_tree($node);

        } elseif (isset($node['value']) and !$node['attributes']) {
            $tree['values'][$node['tag']] = $node['value'];
            unset($tree['children'][$index]);
        }
    }

    if (!$tree['children']) unset($tree['children']);
    return $tree;
}

Enjoy,
Dave


Inicia un intérprete sobre un documento XML

  • « xml_parse_into_struct
  • xml_parser_create_ns »
  • PHP Manual
  • Funciones del Intérprete XML
  • Inicia un intérprete sobre un documento XML

xml_parse

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

xml_parse — Inicia un intérprete sobre un documento XML

Descripción

xml_parse ( resource $parser , string $data , bool $is_final = false ) : int

xml_parse() analiza un documento XML. Los manejadores para los eventos configurados son llamados tantas veces como sea necesario.

Parámetros

parser

Identificador del recurso del intérprete XML que se va a usar.

data

Conjunto de información que se analizará. Un documento puede ser analizado por trozos llamando varias veces con nuevos trozos a xml_parse(), siempre que se establezca el parámetro is_final y sea true cuando el último dato sea analizado.

is_final

Si existe y es true, data es el último fragmento de datos enviados en este intérprete.

Valores devueltos

Devuelve 1 si el análisis se realiza con éxito o 0 en caso de error.

Para análisis fallidos, se puede recuperar información del error con
  xml_get_error_code(),
  xml_error_string(),
  xml_get_current_line_number(),
  xml_get_current_column_number() and
  xml_get_current_byte_index().

Nota:

Los errores de entidades son reportados al final de los datos, solo si is_final existe y es true.

User Contributed Notes

Programmerdude 06-Aug-2014 07:26
Due to restrictions in libxml2 the maximum length of $data is 9.5MB. If you need to process more than 9.5MB you can do so by calling the function multiple times and setting $is_final on the last call.
alejandro dot anv at gmail dot com 13-Mar-2014 01:00
Here is my array2xml function. I made it because I coudn't find a generic recursive function that generates a prety formatted XML from any array.

Usage:

<?php echo xml2array('rootname',$myarray); ?>

or if you want to specify a spacing character(s) other than TAB:

<?php echo xml2array('rootname',$myarray,'   '); ?>

or if you want avoid spacing at all

<?php echo xml2array('rootname',$myarray,''); ?>

<?php
function array2xml($nombre,$valor,$tab="\t",$nivel=0){

if ($nivel==0) $r='<?xml version="1.0" encoding="ISO-8859-1"?>';

$arr=!is_numeric($nombre);
$spacing=str_repeat($tab,$nivel);
if ($tab!='') $newline="\n";
else $newline='';

if (is_array($valor)){

   if (count($valor)>0){
      $r.=$newline;
      //$r.=str_repeat($tab,$nivel);
      foreach($valor as $k=>$v){
         if ($arr) $r.="$spacing<$nombre>";

         if (is_array($v))  $r.=array2xml($k,$v,$tab,$nivel+$arr);
         else $r.="$spacing<$k>$v</$k>$newline";

         if ($arr) $r.="$spacing</$nombre>$newline";
         }//foreach
      }//count
   else $r.="$spacing<$nombre></$nombre>"; // it's an empty array
   }
else {
     if ($arr) $r.="$spacing<$nombre>";
     $r.=$valor;
     if ($arr) $r.="</$nombre>$newline";
     }

return $r;
}
?>
Ashok dot 893 at gmail dot com 25-Apr-2010 10:52
This is very simple way to convert all applicable objects into associative array.  This works with not only SimpleXML but any kind of object. The input can be either array or object. This function also takes an options parameter as array of indices to be excluded in the return array. And keep in mind, this returns only the array of non-static and accessible variables of the object since using the function get_object_vars().

<?php
function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
    $arrData = array();

    // if input is object, convert into array
    if (is_object($arrObjData)) {
        $arrObjData = get_object_vars($arrObjData);
    }

    if (is_array($arrObjData)) {
        foreach ($arrObjData as $index => $value) {
            if (is_object($value) || is_array($value)) {
                $value = objectsIntoArray($value, $arrSkipIndices); // recursive call
            }
            if (in_array($index, $arrSkipIndices)) {
                continue;
            }
            $arrData[$index] = $value;
        }
    }
    return $arrData;
}
?>

Usage:

<?php
$xmlUrl = "feed.xml"; // XML feed file/URL
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
print_r($arrXml);
?>
lz_speedy at web dot de 30-Dec-2008 10:20
Best seen xml2array function ever
<?php
function xml2array($url, $get_attributes = 1, $priority = 'tag')
{
    $contents = "";
    if (!function_exists('xml_parser_create'))
    {
        return array ();
    }
    $parser = xml_parser_create('');
    if (!($fp = @ fopen($url, 'rb')))
    {
        return array ();
    }
    while (!feof($fp))
    {
        $contents .= fread($fp, 8192);
    }
    fclose($fp);
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);
    if (!$xml_values)
        return; //Hmm...
    $xml_array = array ();
    $parents = array ();
    $opened_tags = array ();
    $arr = array ();
    $current = & $xml_array;
    $repeated_tag_index = array ();
    foreach ($xml_values as $data)
    {
        unset ($attributes, $value);
        extract($data);
        $result = array ();
        $attributes_data = array ();
        if (isset ($value))
        {
            if ($priority == 'tag')
                $result = $value;
            else
                $result['value'] = $value;
        }
        if (isset ($attributes) and $get_attributes)
        {
            foreach ($attributes as $attr => $val)
            {
                if ($priority == 'tag')
                    $attributes_data[$attr] = $val;
                else
                    $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
            }
        }
        if ($type == "open")
        {
            $parent[$level -1] = & $current;
            if (!is_array($current) or (!in_array($tag, array_keys($current))))
            {
                $current[$tag] = $result;
                if ($attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                $current = & $current[$tag];
            }
            else
            {
                if (isset ($current[$tag][0]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 2;
                    if (isset ($current[$tag . '_attr']))
                    {
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                        unset ($current[$tag . '_attr']);
                    }
                }
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                $current = & $current[$tag][$last_item_index];
            }
        }
        elseif ($type == "complete")
        {
            if (!isset ($current[$tag]))
            {
                $current[$tag] = $result;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                if ($priority == 'tag' and $attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
            }
            else
            {
                if (isset ($current[$tag][0]) and is_array($current[$tag]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    if ($priority == 'tag' and $get_attributes and $attributes_data)
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $get_attributes)
                    {
                        if (isset ($current[$tag . '_attr']))
                        {
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset ($current[$tag . '_attr']);
                        }
                        if ($attributes_data)
                        {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                }
            }
        }
        elseif ($type == 'close')
        {
            $current = & $parent[$level -1];
        }
    }
    return ($xml_array);
}
?>

Returns a well formed array like the structure of the xml-document

<root>
 <child1>
  <child1child1/>
 </child1>
</root>

create an array like
array[root][child1][child1child1]

lg
neoyahuu at yahoo dot com 12-Dec-2007 08:18
Instead of passing a URL, we can pass the XML content to this class (either you
 want to use CURL, Socks or fopen to retrieve it first) and instead of using
 array, I'm using separator '|' to identify which data to get (in order to make
 it short to retrieve a complex XML data). Here is my class with built-in fopen
 which you can pass URL or you can pass the content instead :

p/s : thanks to this great help page.

<?php

class xx_xml {

    // XML parser variables
    var $parser;
    var $name;
    var $attr;
    var $data  = array();
    var $stack = array();
    var $keys;
    var $path;

    // either you pass url atau contents.
    // Use 'url' or 'contents' for the parameter
    var $type;

    // function with the default parameter value
    function xx_xml($url='http://www.example.com', $type='url') {
        $this->type = $type;
        $this->url  = $url;
        $this->parse();
    }

    // parse XML data
    function parse()
    {
        $data = '';
        $this->parser = xml_parser_create();
        xml_set_object($this->parser, $this);
        xml_set_element_handler($this->parser, 'startXML', 'endXML');
        xml_set_character_data_handler($this->parser, 'charXML');

        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);

        if ($this->type == 'url') {
            // if use type = 'url' now we open the XML with fopen

            if (!($fp = @fopen($this->url, 'rb'))) {
                $this->error("Cannot open {$this->url}");
            }

            while (($data = fread($fp, 8192))) {
                if (!xml_parse($this->parser, $data, feof($fp))) {
                    $this->error(sprintf('XML error at line %d column %d',
                    xml_get_current_line_number($this->parser),
                    xml_get_current_column_number($this->parser)));
                }
            }
        } else if ($this->type == 'contents') {
            // Now we can pass the contents, maybe if you want
            // to use CURL, SOCK or other method.
            $lines = explode("\n",$this->url);
            foreach ($lines as $val) {
                if (trim($val) == '')
                    continue;
                $data = $val . "\n";
                if (!xml_parse($this->parser, $data)) {
                    $this->error(sprintf('XML error at line %d column %d',
                    xml_get_current_line_number($this->parser),
                    xml_get_current_column_number($this->parser)));
                }
            }
        }
    }

    function startXML($parser, $name, $attr)    {
        $this->stack[$name] = array();
        $keys = '';
        $total = count($this->stack)-1;
        $i=0;
        foreach ($this->stack as $key => $val)    {
            if (count($this->stack) > 1) {
                if ($total == $i)
                    $keys .= $key;
                else
                    $keys .= $key . '|'; // The saparator
            }
            else
                $keys .= $key;
            $i++;
        }
        if (array_key_exists($keys, $this->data))    {
            $this->data[$keys][] = $attr;
        }    else
            $this->data[$keys] = $attr;
        $this->keys = $keys;
    }

    function endXML($parser, $name)    {
        end($this->stack);
        if (key($this->stack) == $name)
            array_pop($this->stack);
    }

    function charXML($parser, $data)    {
        if (trim($data) != '')
            $this->data[$this->keys]['data'][] = trim(str_replace("\n", '', $data));
    }

    function error($msg)    {
        echo "<div align=\"center\">
            <font color=\"red\"><b>Error: $msg</b></font>
            </div>";
        exit();
    }
}

?>

And example of retrieving XML data:
p/s: example use to retrieve weather

<?php
include_once "xx_xml.class.php";

// Im using simple curl (the original is in class) to get the contents

$pageurl = "http://xml.weather.yahoo.com/forecastrss?p=MYXX0008&u=c";
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL, $pageurl );
$thecontents = curl_exec ( $ch );
curl_close($ch);

// We want to pass only a ready XML content instead of URL
// But if you want to use URL , skip the curl functions above and use this
// $xx4 = new xx_xml("url here",'url');

$xx4 = new xx_xml($thecontents,'contents');
// As you can see, we use saparator '|' instead of long array
$Code = $xx4->data ['rss|channel|item|yweather:condition']['code'] ;
$Celcius = $xx4->data ['rss|channel|item|yweather:condition']['temp'] ;
$Text = $xx4->data ['rss|channel|item|yweather:condition']['text'] ;
$Cityname = $xx4->data ['rss|channel|yweather:location']['city'] ;

?>

Hope this helps.
joris dot landman at chello dot nl 28-Jul-2007 07:42
This page has been a great help! I've adapted the examples below to make a class to parse an X(HT)ML file to a multidimensional array.

Spaces, tabs, breaks, etc. are included in the array as TEXT_NODE, since in XHTML they may be functional. A function to trim them can easily be added if so desired.

I've written my class to store multiple tags with the same name. In order to do this I've used nested arrays with the key NODES to store the order in which tags and data were parsed. These NODES arrays can be used as a blueprint to reconstruct the X(HT)ML part of the document in it's entirity, including formatting. (Doctype will have to be added for validity).

<?php

class my_xml_object {

    var $xml_data; # raw xml data from file
    function parse_xml_file($my_uri) {
        $this->xml_data = null; # clear previously parsed file and related variables
        if (is_file($my_uri) && is_readable($my_uri)) { # existing and readable uri?
            $my_file = fopen($my_uri, "r");
            while($my_xml_input = fread($my_file, filesize($my_uri))) {
                $this->xml_data .= $my_xml_input; # add data to xml_data
            }
            fclose($my_file);
            $this->parse_xml_data($this->xml_data); # parse data
        } else {
            trigger_error("supplied argument is not a URI to a (readable) file", E_USER_ERROR);
        }
    }

    var $xml_array = Array(); # xml array from parsed data
    function parse_xml_data($my_data) { # adapted from class by randlem@gmail.com, tgrabietz@bupnet.de, bbellwfu@gmail.com, Kyle Bresin - see http://nl2.php.net/xml_parse
        $this->xml_array = Array(0 => Array()); # clear previously parsed file and related variables; populate first element
        $my_parser = xml_parser_create(); # set up parser
        xml_set_object($my_parser, $this); # enable parser within object
        xml_set_element_handler($my_parser, "xml_tag_open", "xml_tag_close");
        xml_set_character_data_handler($my_parser, "xml_tag_data");
        if (!xml_parse($my_parser, $my_data)) {
            trigger_error("data can not be parsed", E_USER_ERROR); # inspect problems #die(sprintf("<br />\n<b>Error</b>:  %s on line <b>%d</b><br />\n", xml_error_string(xml_get_error_code($my_parser)), xml_get_current_line_number($my_parser)));
        }
        xml_parser_free($my_parser); # free parser
        return $this->xml_array; # return xml array
    }

    var $my_branch = Array();
    function xml_tag_open($my_parser, $my_name, $my_attributes) {
        array_push($this->my_branch, $my_name); # add tag name to branch
        $this->xml_array[] = Array(); # nest array in xml array for data
        if (count($my_attributes)) {
            $this->xml_array[count($this->xml_array) - 1]["ATTRIBUTES"] = $my_attributes; # nest attributes array
        }
    }

    function xml_tag_data($my_parser, $my_data) {
        $this->xml_array[count($this->my_branch)]["TEXT_NODE"][] = $my_data; # add data to nested array
        $this->xml_array[count($this->my_branch)]["NODES"][] = "TEXT_NODE"; # add text node to nested NODES array
    }

    function xml_tag_close($my_parser, $my_name) {
        $this->xml_array[count($this->my_branch) - 1][$this->my_branch[count($this->my_branch) - 1]][] = $this->xml_array[count($this->xml_array) - 1]; # nest arrays to follow document structure
        array_pop($this->xml_array); # pop off element that was nested
        $this->xml_array[count($this->my_branch) - 1]["NODES"][] = $my_name; # add tag node to nested NODES array
        array_pop($this->my_branch); # update branch
    }

?>
dgrimes at scvl dot com 29-Jun-2007 06:14
One note about magic quotes: magic_quotes_runtime needs to be disabled before parsing XML. It can cause strange errors during parsing. Just add the following at the top of your program:

set_magic_quotes_runtime(0);

If you need magic quotes you can use stripslashes or save the current magic quotes setting with get_magic_quotes_runtime() then disable and parse your XML and then restore the previous magic quotes setting.
php at b635 dot com 23-Jun-2007 10:17
The suggestions below have been a great help, but there was one thing I really needed...

I'm parsing Amazon XML data, and I wanted to be able to index into the array using something like:

<?php
  print "<p>" . $strAXML->arrOutput[ITEMLOOKUPRESPONSE][ITEMS][ITEM][SMALLIMAGE][URL];
?>

To solve this, I had to push all of the open tags onto a separate stack, add any tag data to the tail end of an attributed multi-dimensional array, and then pop the tag name off of the stack once it was closed...

<?php

class xml2array {

  var $arrOutput = array();
  var $arrName = array();
  var $objParser;
  var $strXmlData;

  function parse($strInputXML) {

    // standard XML parse object setup

    $this->objParser = xml_parser_create ();
    xml_set_object($this->objParser,$this);
    xml_set_element_handler($this->objParser, "tagOpen", "tagClosed");

    xml_set_character_data_handler($this->objParser, "tagData");

    $this->strXmlData = xml_parse($this->objParser,$strInputXML );
    if(!$this->strXmlData) {
      die(sprintf("XML error: %s at line %d",
        xml_error_string(xml_get_error_code($this->objParser)),
        xml_get_current_line_number($this->objParser)));
    }

    xml_parser_free($this->objParser);

    return $this->arrOutput;
  }

  function tagOpen($parser, $name, $attrs) {
    // push the current tag name to an array of still-open tag names
    array_push ($this->arrName, $name);

    // merge the array of current attributes to the open tag
    // NOTE: this does not currently handle multiple attributes with the same name
    // (i.e. it will overwrite them with the last values)

    $strEval = "\$this->arrOutput";
    foreach ($this->arrName as $value) {
      $strEval .= "[" . $value . "]";
    }
    $strEval = $strEval . " = array_merge (" . $strEval . ",\$attrs);";

    eval ($strEval);
  }

  function tagData($parser, $tagData) {

    // set the latest open tag equal to the tag data

    $strEval = "\$this->arrOutput";
    foreach ($this->arrName as $value) {
      $strEval .= "[" . $value . "]";
    }

    $strEval = $strEval . " = \$tagData;";

    eval ($strEval);
  }

  function tagClosed($parser, $name) {

    // pop this tag (and any subsequent tags) off the stack of open tag names

    for ($i = count ($this->arrName) - 1; $i > 0; $i--) {
      $currName = $this->arrName[$i];
      array_pop ($this->arrName);
      if ($currName == $name) {
        break;
      }
    }
  }

}

?>
james @at@ mercstudio dot Com dot nospam 02-Apr-2006 12:10
hi,

i've modified bbellwfu at gmail dot com to as below:

features added:
  - toXML (convert back array to xml string)
  - changed name, according to macromedia flash xml concept : children -> childrens, tagdata -> nodevalue, name -> nodename,
  - added pointer firstchild to childrens[0] (if exists)

some findings that i would like to share:
 - <![cdata[my value here]]> (does not work on property value
 - xml file must be htmlentity based (if not using cdata)
 - xml line feed on node data seems to be double line feed on windows (still figuring why)
 - xml line feed on attribute value seems to be ignored...

here's my code below :)

class u007xml
{
   var $arrOutput = array();
   var $resParser;
   var $strXmlData;

    function u007xml($tfile = "")
    {
        if(trim($tfile) != "") { $this->loadFile($tfile);}
    }

    function loadFile($tfile)
    {
        $this->thefile = $tfile;

        $th = file($tfile);
        $tdata = implode("\n", $th);

        return $this->parse($tdata);
    }

   function parse($strInputXML)
   {
        $this->resParser = xml_parser_create ();
        xml_set_object($this->resParser,$this);
        xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");

        xml_set_character_data_handler($this->resParser, "tagData");

        $this->strXmlData = xml_parse($this->resParser,$strInputXML );

        if(!$this->strXmlData) {
           die(sprintf("XML error: %s at line %d",
        xml_error_string(xml_get_error_code($this->resParser)),
        xml_get_current_line_number($this->resParser)));
        }

        xml_parser_free($this->resParser);

        return $this->arrOutput;
   }

   //called on each xml tree
   function tagOpen($parser, $name, $attrs) {
       $tag=array("nodename"=>$name,"attributes"=>$attrs);
       array_push($this->arrOutput,$tag);
   }

  //called on data for xml
   function tagData($parser, $tagData) {
       if(trim($tagData)) {
           if(isset($this->arrOutput[count($this->arrOutput)-1]['nodevalue'])) {
               $this->arrOutput[count($this->arrOutput)-1]['nodevalue'] .= $this->parseXMLValue($tagData);
           }
           else {
               $this->arrOutput[count($this->arrOutput)-1]['nodevalue'] = $this->parseXMLValue($tagData);
           }
       }
   }

  //called when finished parsing
   function tagClosed($parser, $name) {
       $this->arrOutput[count($this->arrOutput)-2]['childrens'][] = $this->arrOutput[count($this->arrOutput)-1];

       if(count ($this->arrOutput[count($this->arrOutput)-2]['childrens'] ) == 1)
       {
            $this->arrOutput[count($this->arrOutput)-2]['firstchild'] =& $this->arrOutput[count($this->arrOutput)-2]['childrens'][0];
       }
       array_pop($this->arrOutput);
   }

    function toArray()
    {
        //not used, we can call loadString or loadFile instead...
    }

    function parseXMLValue($tvalue)
    {
        $tvalue = htmlentities($tvalue);
        return $tvalue;
    }

    function toXML($tob = null)
    {
        //return back xml
        $result = "";

        if( $tob == null)
        {
            $tob = $this->arrOutput;
        }

        if(!isset($tob))
        {
            echo "XML Array empty...";
            return null;
        }

        for($c = 0; $c < count($tob); $c++)
        {
            $result .="<" . $tob[$c]["nodename"];

            while (list($key, $value) = each($tob[$c]["attributes"]))
            {
                $result .=" " . $key."=\"" . $this->parseXMLValue($value) . "\"";
            }

            $result .= ">";

            //assign node value
            if( isset($tob[$c]["nodevalue"]) )
            {
                $result .= $tob[$c]["nodevalue"];
            }

            if( count($tob[$c]["childrens"]) > 0 )
            {
                $result .= "\r\n" . $this->toXML(&$tob[$c]["childrens"]) . "";
            }

            $result .= "</" . $tob[$c]["nodename"] . ">\r\n";

        }//end of each array...

        return $result;
    }

    function displayXML()
    {
        print_r($this->arrOutput);
    }

    function getXML($tob = null)
    {
        return "<?xml version='1.0'?>\r\n" . $this->toXML($tob);
    }

}//end of u007xml class

//examples below:

$xx = new u007xml();
$xx->loadFile("xml3.xml");

//$xx->displayXML();

print $xx->getXML();
ben at autonomic dot net 16-Mar-2006 05:12
bbellwfu's code does not handle 'text nodes' properly.
Consider the innards of a tag like <root>xxx<tag2/>yyy</root>
The 'tagData' for root will be "xxxyyy" and you have lost all information about where "tag2" was in that sequence.

Quick and dirty hack.

Replace tagData with this code :
   function tagData($parser, $tagData) {
          $last_element=count($this->arrOutput)-1;
        $this->arrOutput[$last_element]['children'][] = array("textnode",$tagData);
   }

What this does is adds 'textnodes' as children of its containing parent, *in the right sequence* (rather like the internet browsers do it). This then lets you do some more sensible secondary work like recursively looking up internal references within the document...
Kyle Bresin 19-Jan-2006 03:15
Just wanted to note a small bug in bbellwfu's class (which is really great btw).

It fails to capture any datums which are equal to numerical zero.

The problem lies in the function tagData, the first if statement should be:

if(trim($tagData) != '') {
tim at alloutinteraction dot com 01-Oct-2005 07:29
I wanted to create a really simple XML parser, but I found the array management in xml_parse a bit daunting. So I flattened my XML and parsed it using string matching. It wouldn't be difficult to add xml depth (of 2 plus levels) by modifying the parsedXML array.

<?
// here's the raw html
$xmlRaw="<order>Order data</order><label>Label data</label><control>123</control>";
// here are the xml field names
$xmlFieldNames=array("order", "label", "control");
// for each xml field...
foreach ($xmlFieldNames as $xmlField) {
    if(strpos($xmlRaw,$xmlField)!==false){
        // I've broken 1 single line into 4 for display purposes
        $parsedXML[$xmlField]=substr($xmlRaw,
        strpos($xmlRaw,"<$xmlField>")+strlen("<$xmlField>"),
        strpos($xmlRaw,"</$xmlField>")-strlen("<$xmlField>")
        -strpos($xmlRaw,"<$xmlField>"));
    }
}
print_r($parsedXML);
// prints: Array ( [order] => Order data [label] => Label data [control] => 123 )

?>

Hope you find this useful (coded it while ill in bed with streaming cold, but felt much better afterwards!)

Tim (a lazy coder)
bbellwfu at gmail dot com 05-May-2005 02:51
Just improving a little bit on the code examples from tgrabietz and randlem below... everything in one pretty class, plus some checks in place so that the element data doesnt get split up (thanks to flobee on the xml_set_character_data_handler page)

<?php

/* Usage
 Grab some XML data, either from a file, URL, etc. however you want. Assume storage in $strYourXML;

 $objXML = new xml2Array();
 $arrOutput = $objXML->parse($strYourXML);
 print_r($arrOutput); //print it out, or do whatever!

*/
class xml2Array {

    var $arrOutput = array();
    var $resParser;
    var $strXmlData;

    function parse($strInputXML) {

            $this->resParser = xml_parser_create ();
            xml_set_object($this->resParser,$this);
            xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");

            xml_set_character_data_handler($this->resParser, "tagData");

            $this->strXmlData = xml_parse($this->resParser,$strInputXML );
            if(!$this->strXmlData) {
               die(sprintf("XML error: %s at line %d",
            xml_error_string(xml_get_error_code($this->resParser)),
            xml_get_current_line_number($this->resParser)));
            }

            xml_parser_free($this->resParser);

            return $this->arrOutput;
    }
    function tagOpen($parser, $name, $attrs) {
       $tag=array("name"=>$name,"attrs"=>$attrs);
       array_push($this->arrOutput,$tag);
    }

    function tagData($parser, $tagData) {
       if(trim($tagData)) {
            if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
                $this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
            }
            else {
                $this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
            }
       }
    }

    function tagClosed($parser, $name) {
       $this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this->arrOutput)-1];
       array_pop($this->arrOutput);
    }
}
?>

Will output something like...

<snippet>
Array
(
    [0] => Array
        (
            [name] => GETMESSAGESRESPONSE
            [attrs] => Array
                (
                )

            [children] => Array
                (
                    [0] => Array
                        (
                            [name] => STATUS
                            [attrs] => Array
                                (
                                )

                        )

</snippet>
alex dot garcia at noos dot fr 14-Mar-2005 01:47
Here is the inverse function which takes parsed xml array in entry and outputs xml string

enjoy !

function getXmlFromArray($root){

        if(count($root) > 0){

            $curr_name = $root['name'];
            $attribs = $root['attrs'];
            $curr_childs = $root['children'];
            $curr_data = $root['cdata'];

            $xml .= '<'.$curr_name;

            if(count($attribs) > 0){
                $i = 1;
                foreach($attribs as $key => $value){
                    $curr_attribs .= $key.'="'.$value.'"';
                    $i++;
                    if($i <= count($attribs)){
                        $curr_attribs .= ' ';
                    }
                }
                $xml .= ' '.$curr_attribs;
            }

            if($curr_data != ''){
                $xml .= '><![CDATA['.$curr_data.']]></'.$curr_name.'>';
            } else {
                if(count($curr_childs) > 0){
                    $xml .= '>';
                    foreach($curr_childs as $child){
                        $xml .= getXmlFromArray($child);
                    }
                    $xml .= '</'.$curr_name.'>';
                } else {
                    $xml .= '/>';
                }
            }

        }
        return $xml;
    }
tgrabietz at bupnet dot de 22-Sep-2004 08:05
it's like randlem at gmail dot com's great code, without using a "class container" but parsing cdata. The script returns the tree-structure in a single array.

<?php
$file = 'simple.xml';
$stack = array();

function startTag($parser, $name, $attrs)
{
   global $stack;
   $tag=array("name"=>$name,"attrs"=>$attrs);
   array_push($stack,$tag);

}

function cdata($parser, $cdata)
{
    global $stack,$i;

    if(trim($cdata))
    {
        $stack[count($stack)-1]['cdata']=$cdata;
    }
}

function endTag($parser, $name)
{
   global $stack;
   $stack[count($stack)-2]['children'][] = $stack[count($stack)-1];
   array_pop($stack);
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");
xml_set_character_data_handler($xml_parser, "cdata");

$data = xml_parse($xml_parser,file_get_contents($file));
if(!$data) {
   die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}

xml_parser_free($xml_parser);

print("<pre>\n");
print_r($stack);
print("</pre>\n");
?>
ByK 16-Sep-2004 08:12
modified from yours code. I think it's work!!.
class CXml
{
    var $xml_data;
    var $obj_data;
    var $pointer;

    function CXml() { }

    function Set_xml_data( &$xml_data )
    {
        $this->index = 0;
        $this->pointer[] = &$this->obj_data;

        //strip white space between tags
        $this->xml_data = eregi_replace(">"."[[:space:]]+"."<","><",$xml_data);
        $this->xml_parser = xml_parser_create( "UTF-8" );

        xml_parser_set_option( $this->xml_parser, XML_OPTION_CASE_FOLDING, false );
        xml_set_object( $this->xml_parser, &$this );
        xml_set_element_handler( $this->xml_parser, "_startElement", "_endElement");
        xml_set_character_data_handler( $this->xml_parser, "_cData" );

        xml_parse( $this->xml_parser, $this->xml_data, true );
        xml_parser_free( $this->xml_parser );
    }

    function _startElement( $parser, $tag, $attributeList )
    {
        foreach( $attributeList as $name => $value )
        {
            $value = $this->_cleanString( $value );
            $object->$name = $value;
        }
        //replaces the special characters with the underscore (_) in tag name
        $tag = preg_replace("/[:\-\. ]/", "_", $tag);
        eval( "\$this->pointer[\$this->index]->" . $tag . "[] = \$object;" );
        eval( "\$size = sizeof( \$this->pointer[\$this->index]->" . $tag . " );" );
        eval( "\$this->pointer[] = &\$this->pointer[\$this->index]->" . $tag . "[\$size-1];" );

        $this->index++;
    }

    function _endElement( $parser, $tag )
    {
        array_pop( $this->pointer );
        $this->index--;
    }

    function _cData( $parser, $data )
    {
        if (empty($this->pointer[$this->index])) {
            if (rtrim($data, "\n"))
                $this->pointer[$this->index] = $data;
        } else {
            $this->pointer[$this->index] .= $data;
        }
    }

    function _cleanString( $string )
    {
        return utf8_decode( trim( $string ) );
    }
}

$m_xml = new CXml();
$xml_data = file_get_contents( $filename );

$m_xml->Set_XML_data( $xml_data );

$newsid = $m_xml->obj_data->root[0]->NewsID[0];
randlem at gmail dot com 15-Sep-2004 08:43
Here's a handy way to generate a tree that can be can be decended easily.

<?php
$file = 'xmltest.xml';

$tag_tree = array();
$stack = array();

class tag {
    var $name;
    var $attrs;
    var $children;
    function tag($name, $attrs, $children) {
        $this->name = $name;
        $this->attrs = $attrs;
        $this->children = $children;
    }
}

function startTag($parser, $name, $attrs) {
    global $tag_tree, $stack;
    $tag = new tag($name,$attrs,'');
    array_push($stack,$tag);
}

function endTag($parser, $name) {
    global $stack;
    $stack[count($stack)-2]->children[] = $stack[count($stack)-1];
    array_pop($stack);
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");

$data = xml_parse($xml_parser,file_get_contents($file));
if(!$data) {
    die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}

xml_parser_free($xml_parser);

print("\n");
print_r($stack);
print("\n");
?>
michelek 26-Oct-2003 10:42
its maybe not better, but me thinks its more stright-forward

--INPUT:

<?xml version="1.0" encoding="UTF-8"?>
<world>
    <country name="sweden">
        <city name="stockholm">
            <user>Adam</user>
            <user>Eva</user>
        </city>
        <city name="g?teborg">
            <user>God</user>
        </city>
    </country>
    <country name="usa">
        <city name="new york">
            <user>Clinton</user>
            <user>Bush</user>
        </city>
    </country>
</world>

--CODE:
<?
/**
 * m_i_h_k_e_l_AT_w_w_DOT_e_e
 * 26.10.2003
**/
$filename = "m.m.xml";
$xmlC = new XmlC();
$xml_data = file_get_contents( $filename );

$xmlC->Set_XML_data( $xml_data );

echo( "<pre>\n" );
print_r( $xmlC->obj_data );
echo( "</pre>\n" );

class XmlC
{
  var $xml_data;
  var $obj_data;
  var $pointer;

  function XmlC()
  {
  }

  function Set_xml_data( &$xml_data )
  {
    $this->index = 0;
    $this->pointer[] = &$this->obj_data;

    $this->xml_data = $xml_data;
    $this->xml_parser = xml_parser_create( "UTF-8" );

    xml_parser_set_option( $this->xml_parser, XML_OPTION_CASE_FOLDING, false );
    xml_set_object( $this->xml_parser, &$this );
    xml_set_element_handler( $this->xml_parser, "_startElement", "_endElement");
    xml_set_character_data_handler( $this->xml_parser, "_cData" );

    xml_parse( $this->xml_parser, $this->xml_data, true );
    xml_parser_free( $this->xml_parser );
  }

  function _startElement( $parser, $tag, $attributeList )
  {
    foreach( $attributeList as $name => $value )
    {
      $value = $this->_cleanString( $value );
      $object->$name = $value;
    }
    eval( "\$this->pointer[\$this->index]->" . $tag . "[] = \$object;" );
    eval( "\$size = sizeof( \$this->pointer[\$this->index]->" . $tag . " );" );
    eval( "\$this->pointer[] = &\$this->pointer[\$this->index]->" . $tag . "[\$size-1];" );

    $this->index++;
  }

  function _endElement( $parser, $tag )
  {
    array_pop( $this->pointer );
    $this->index--;
  }

  function _cData( $parser, $data )
  {
    if( trim( $data ) )
    {
      $this->pointer[$this->index] = trim( $data );
    }
  }

  function _cleanString( $string )
  {
    return utf8_decode( trim( $string ) );
  }

}
?>
Adam Tylmad 11-Sep-2003 01:11
I've created a parser that returns an
object based on a xml document.

example:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<country name="sweden">
    <city name="stockholm">
        <user>Adam</user>
        <user>Eve</user>
    </city>
    <city name="g?teborg">
        <user>God</user>
    </city>
</country>
<country name="usa">
    <city name="new york">
        <user>Clinton</user>
        <user>Bush</user>
    </city>
</country>

generates the following object structure:
[country] => Array
(
    [0] => stdClass Object
        (
            [name] => sweden
            [city] => Array
                (
                    [0] => stdClass Object
                        (
                            [name] => stockholm
                            [user] => Array
                                (
                                    [0] => Adam
                                    [1] => Eve
                                )
                        )
                    [1] => stdClass Object
                        (
                            [name] => g?teborg
                            [user] => God
                        )
                )
        )
    [1] => stdClass Object
        (
            [name] => usa
            [city] => stdClass
                (
                    [name] => new york
                    [user] => Array
                        (
                            [0] => Clinton
                            [1] => Bush
                        )
                )
        )
)

Here is the code:

class XMLParser {
    var $path;
    var $result;

    function XMLParser($encoding, $data) {
        $this->path = "\$this->result";
        $this->index = 0;

        $xml_parser = xml_parser_create($encoding);
        xml_set_object($xml_parser, &$this);
        xml_set_element_handler($xml_parser, 'startElement', 'endElement');
        xml_set_character_data_handler($xml_parser, 'characterData');

        xml_parse($xml_parser, $data, true);
        xml_parser_free($xml_parser);
    }

        function startElement($parser, $tag, $attributeList) {
            eval("\$vars = get_object_vars(".$this->path.");");
            $this->path .= "->".$tag;
            if ($vars and array_key_exists($tag, $vars)) {
                 eval("\$data = ".$this->path.";");
                     if (is_array($data)) {
                           $index = sizeof($data);
                           $this->path .= "[".$index."]";
                     } else if (is_object($data)) {
                           eval($this->path." = array(".$this->path.");");
                           $this->path .= "[1]";
                     }
            }
            eval($this->path." = null;");

            foreach($attributeList as $name => $value)
                eval($this->path."->".$name. " = '".XMLParser::cleanString($value)."';");
        }

    function endElement($parser, $tag) {
        $this->path = substr($this->path, 0, strrpos($this->path, "->"));
    }

    function characterData($parser, $data) {
        eval($this->path." = '".trim($data)."';");
    }
}

enjoy! And please make it better if you can ;-)


Crea un analizador XML con soporte para espacios de nombres

  • « xml_parse
  • xml_parser_create »
  • PHP Manual
  • Funciones del Intérprete XML
  • Crea un analizador XML con soporte para espacios de nombres

xml_parser_create_ns

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

xml_parser_create_ns — Crea un analizador XML con soporte para espacios de nombres

Descripción

xml_parser_create_ns ( string $encoding = ? , string $separator = ":" ) : resource

xml_parser_create_ns() crea un nuevo analizador XML con soporte para espacios de nombres XML y devuelve un gestor de recurso que hace referencia al mismo, para poder utilizarlo con las demás funciones de XML.

Parámetros

encoding

El parámetro opcional encoding especifica la codificación de caracteres para la entrada y salida en PHP4. A partir de PHP5, la codificación de entrada es detectada automáticamente, así que el parámetro encoding especifica sólo la codificación de salida. En PHP 4, la codificación de salida predeterminada es la misma que la del juego de caracteres de la entrada. En PHP 5.0.0 y 5.0.1, el juego de caracteres predeterminado es ISO-8859-1, mientras que en PHP 5.0.2 y posterior es UTF-8. Las codificaciones soportadas son ISO-8859-1, UTF-8 y US-ASCII.

separator

Con un analizador que tiene en cuenta los espacios de nombres, los parámetros de etiquetas pasados a las diferentes funciones gestoras consistirán en el espacio de nombres y el nombre de la etiqueta separado por el string especificado en separator.

Valores devueltos

Devuelve un gestor de recurso para el nuevo analizador XML.

Ver también

  • xml_parser_create() - Crea un intérprete XML
  • xml_parser_free() - Liberar una analizador 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.


Crea un intérprete XML

  • « xml_parser_create_ns
  • xml_parser_free »
  • PHP Manual
  • Funciones del Intérprete XML
  • Crea un intérprete XML

xml_parser_create

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

xml_parser_create — Crea un intérprete XML

Descripción

xml_parser_create ( string $encoding = ? ) : resource

xml_parser_create() crea un nuevo intérprete XML y devuelve un identificador del recurso al que hace referencia, para ser usado por otras funciones XML.

Parámetros

encoding

El parámetro opcional encoding especifica la codificación de caracteres para entrada y salida en PHP4. A partir de PHP5, la codificación de entrada se detecta automaticamente, así que el parámetro encoding especifica solo la codificación de salida. En PHP 4, la codificación por defecto de salida es la misma que la del juego de caracteres de la entrada. Si se le pasa una cadena vacia, el intérprete intenta identificar cual es la codificación del documento mirando los 3 o 4 primeros bytes. En PHP 5.0.0 y 5.0.1, el juego de caracteres por defecto es ISO-8859-1, mientras que en PHP 5.0.2 y superior es UTF-8. Las codificaciones soportadas son ISO-8859-1, UTF-8 y US-ASCII.

Valores devueltos

Devuelve un identificador del recurso para el nuevo intérprete XML.

Ver también

  • xml_parser_create_ns() - Crea un analizador XML con soporte para espacios de nombres
  • xml_parser_free() - Liberar una analizador 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.


Liberar una analizador XML

  • « xml_parser_create
  • xml_parser_get_option »
  • PHP Manual
  • Funciones del Intérprete XML
  • Liberar una analizador XML

xml_parser_free

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

xml_parser_free — Liberar una analizador XML

Descripción

xml_parser_free ( resource $parser ) : bool

Liberar el parser XML dado.

Parámetros

parser
Una referencia a el analizador a liberar.

Valores devueltos

Ésta función devuelve false si parser no refiere a un analizador valido, o sino lo libera al analizador y devuelve true.

User Contributed Notes

nidzho 27-Aug-2016 08:12
Unset the parser after calling xml_parser_free() to prevent memory leaks:

<?php
xml_parser_free($parser);
unset($parser);
?>
dio at edu dot uni-klu dot ac dot at 01-Oct-2005 09:56
If you try to free an XML parser while it is still parsing, strange things will happen - your script will "hang" and no output will be sent to the browser. Consider this pseudo-code example:

-------

...
if (!xml_parse($parser)) echo 'XML error';

xml_parser_free($parser);

...

function SomeCallbackWhichWasSetBefore(...)
{
global $parser;

...

if (some_error_happened) xml_parser_free($parser);  //problem!

...

}

------

It would be logical that xml_parse would return false if the parser was freed while parsing, right? Wrong! Instead, everything hangs and no output will be sent out (no matter whether output buffering is on or not). It took me more than an hour to figure out why: you cannot free a parser handle that is currently parsing. A simple solution:

-------

$xml_error = false;
if (!xml_parse($parser))
echo 'XML error (directly from parser)';
else if ($xml_error)
echo 'XML error (from some callback function);

xml_parser_free($parser);

...

function SomeCallbackWhichWasSetBefore(...)
{
global $parser;
global $xml_error;

if ($xml_error)
return;

...

if (some_error_occured)
{
$xml_error = false;
return;
}

...

}

-------

If you use this solution you will have to check for $xml_error in every callback function. Essentially what you're doing is that, in case you want to stop parsing because of an error, you continue until xml_parse() is finished (without actually doing anything) and then free the parser and act on the error.

Of course the underlying problem is that you cannot stop a parser while it is parsing. There should be some function like xml_throw_error() or xml_parser_stop() or whatever, but unfortunately there isn't.
php dot net at gwprogramming dot com (George Webb) 30-Oct-2003 06:56
I found that with PHP 4.3.4RC1, if you don't call xml_parser_free() before your script ends, some sort of ugliness occurs with the webserver; i.e. the HTTP connection is closed.  (The apache error_log says "exit signal Segmentation fault (11)".)

Usually PHP tends to clean up connections you don't explicitly close (e.g. database connections), but in this case apparently it doesn't.

Some web browsers (MSIE for one) do not actually show this problem, so you may not actually notice it.  Opera 7.11 does show it, which is how I discovered it.

So don't forget to call xml_parser_free() ... always!


Obtiene el valor de las opciones de un intérprete XML

  • « xml_parser_free
  • xml_parser_set_option »
  • PHP Manual
  • Funciones del Intérprete XML
  • Obtiene el valor de las opciones de un intérprete XML

xml_parser_get_option

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

xml_parser_get_option — Obtiene el valor de las opciones de un intérprete XML

Descripción

xml_parser_get_option ( resource $parser , int $option ) : mixed

Obtiene el valor de una opción de un intérprete XML.

Parámetros

parser
Identificador del recurso del intéprete XML sobre el que se va a obtener el valor de la opción.
option
Indica cual es la opción para ir a buscar. Estan disponibles XML_OPTION_CASE_FOLDING y XML_OPTION_TARGET_ENCODING. Para su descripción ver xml_parser_set_option() .

Valores devueltos

Devuelve el valor de la opción. Puede devolver false si: parser no se refiere a un intérprete válido o si option no es válido, también generará un E_WARNING en ambos casos.

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


Configura las opciones en un intérprete XML

  • « xml_parser_get_option
  • xml_set_character_data_handler »
  • PHP Manual
  • Funciones del Intérprete XML
  • Configura las opciones en un intérprete XML

xml_parser_set_option

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

xml_parser_set_option — Configura las opciones en un intérprete XML

Descripción

xml_parser_set_option ( resource $parser , int $option , mixed $value ) : bool

Configura una opción en un intérprete XML.

Parámetros

parser

Identificador del recurso del intérprete XML sobre el que se va a configurar el valor de la opción.

option

Cual es la opción para configurar. Véase más abajo.

Estan disponibles las siguientes opciones:

Opciones del intérprete XML
Option constant | Data type | Description
XML_OPTION_CASE_FOLDING | integer | Controla si case-folding está activada para este intérprete XML. Por defecto activado.
XML_OPTION_SKIP_TAGSTART | integer | Especifica el número de caracteres que seran omitidos al principio del nombre de una etiqueta.
XML_OPTION_SKIP_WHITE | integer | Especifica si hay que omitir los valores que consistan en espacios en blanco.
XML_OPTION_TARGET_ENCODING | string | Configura cual será el target encoding (codificación de caracteres de salida) para usar en este intérprete XML. Por defecto se establece la misma codificación de la fuente fuente usada por xml_parser_create(). Las codificaciones de destino soportadas son ISO-8859-1, US-ASCII y UTF-8.

value

El nuevo valor para la opción.

Valores devueltos

Devuelve true si se ha establecido el nuevo valor para la opción. Puede devolver false si: parser no se refiere a un intérprete válido, o si la opción no se ha podido configurar.

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.


Configura el manejador de los datos de caracteres

  • « xml_parser_set_option
  • xml_set_default_handler »
  • PHP Manual
  • Funciones del Intérprete XML
  • Configura el manejador de los datos de caracteres

xml_set_character_data_handler

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

xml_set_character_data_handler — Configura el manejador de los datos de caracteres

Descripción

xml_set_character_data_handler ( resource $parser , callable $handler ) : bool

Configura la función del manejador de los datos de caracteres para el intérprete XML parser.

Parámetros

parser

Identificador del recurso del intérprete XML para el que se va a configurar la función del manejador de datos de caracteres.

handler

handler es un string que contiene el nombre de una función que debe existir cuando xml_parse() es llamado por parser.

La función llamada mediante handler debe aceptar dos parámetros:

handler ( resource $parser , string $data )
parser
El primer parámetro, parser, hace referencia al intérprete XML que llama al manejador.
data
El segundo parámetro, data, contiene los datos de caracteres como un string.

El manejador de datos de caracteres es llamado para cada pieza de un texto en el documento XML. Puede ser llamado multiples veces dentro de cada fragmento (por ejemplo, para strings que no son ASCII).

Si la función del manejador se configura como una cadena vacia, o false, el manejador en cuestión se deshabilita.

Nota: En lugar del nombre de una función, se puede asignar un array que contenga la referencia a un objeto o el nombre de un método.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

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.


Configura el manejador predeterminado

  • « xml_set_character_data_handler
  • xml_set_element_handler »
  • PHP Manual
  • Funciones del Intérprete XML
  • Configura el manejador predeterminado

xml_set_default_handler

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

xml_set_default_handler — Configura el manejador predeterminado

Descripción

xml_set_default_handler ( resource $parser , callable $handler ) : bool

Configura la función del manejador predeterminado para el intérprete XML parser.

Parámetros

parser

Identificador del recurso del intérprete XML para el que se va a configurar la función del manejador predeterminado.

handler

handler es un string que contiene el nombre de una función que debe existir cuando xml_parse() es llamado por parser.

La función llamada mediante handler debe aceptar dos parámetros:

handler ( resource $parser , string $data )
parser
El primer parámetro, parser, hace referencia al intérprete XML que llama al manejador.
data
El segundo parámetro, data, contiene los datos de carateres. Esto puede ser la declaración XML, las declaraciones DOCTYPE, entidades u otros datos para los cuales no exista otro manejador.

Si la función del manejador se configura como una cadena vacia, o false, el manejador en cuestión se deshabilita.

Nota: En lugar del nombre de una función, se puede asignar un array que contenga la referencia a un objeto o el nombre de un método.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

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.


Configura los manejadores para los elementos de inicio y final

  • « xml_set_default_handler
  • xml_set_end_namespace_decl_handler »
  • PHP Manual
  • Funciones del Intérprete XML
  • Configura los manejadores para los elementos de inicio y final

xml_set_element_handler

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

xml_set_element_handler — Configura los manejadores para los elementos de inicio y final

Descripción

xml_set_element_handler ( resource $parser , callable $start_element_handler , callable $end_element_handler ) : bool

Configura las funciones de los manejadores de elementos. start_element_handler y end_element_handler son strings que contienen los nombres de funciones que deben existir cuando xml_parse() sea llamado por parser.

Parámetros

parser

Identificador del recurso del intérprete XML para el que se van a configurar las funciones del manejador de elementos de inicio y final.

start_element_handler

La función llamada mediante start_element_handler debe aceptar tres parámetros:

start_element_handler ( resource $parser , string $name , array $attribs )
parser
El primer parámetro, parser, hace referencia al intérprete XML que llama al manejador.
name
El segundo parámetro, name, contiene el nombre del elemento por el cual el manejador es llamado. Si case-folding está activado para este intérprete, el elemento name estará en letras mayúsculas.
attribs
El tercer parámetroattribs, contiene un array asociativo con los atributos del elemento (si hay alguno). Las claves de este array son los nombres de atributo, los valores son los valores de los atributos. Los nombres de los atributos están en mayúsculas case-folded siguiendo el mismo criterio que los nombres de los elementos. Los valores de los atributos no sufren las consecuencias de case-folding. El orden original de los atributos puede ser recuperado recorriendo attribs de manera normal, usando each(). La primera clave en el array es el primer atributo, y así sucesivamente.

Nota: En lugar del nombre de una función, se puede asignar un array que contenga la referencia a un objeto o el nombre de un método.

end_element_handler

La función llamada mediante end_element_handler debe aceptar dos parámetros:

end_element_handler ( resource $parser , string $name )
parser
El primer parámetro, parser, hace referencia al intérprete XML que llama al manejador.
name
El segundo parámetro, name, contiene el nombre del elemento por el cual el manejador es llamado. Si case-folding está activado para este intérprete, el elemento name estará en letras mayúsculas.

Si la función del manejador se configura como una cadena vacia, o false, el manejador en cuestión se deshabilita.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

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.


Configura el manejador de declaración de final del namespace

  • « xml_set_element_handler
  • xml_set_external_entity_ref_handler »
  • PHP Manual
  • Funciones del Intérprete XML
  • Configura el manejador de declaración de final del namespace

xml_set_end_namespace_decl_handler

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

xml_set_end_namespace_decl_handler — Configura el manejador de declaración de final del namespace

Descripción

xml_set_end_namespace_decl_handler ( resource $parser , callable $handler ) : bool

Configura un manejador para ser llamado cuando se salga del alcance de una declaración de namespace. Se llamará por cada declaración de namespace, después del manejador de etiqueta final del elemento en el cual el namespace fue declarado.

Parámetros

parser

Identificador del recurso del intérprete XML.

handler

handler es una cadena que contiene el nombre de una función que debe existir cuando xml_parse() es llamado por parser.

La función llamada mediante handler debe aceptar dos parámetros, y deberia devolver un número entero. Si el valor devuelto desde el manejador es false (lo cual ocurrirá si no se devulve un valor), el intérprete XML detendrá el analizado y xml_get_error_code() devolverá XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $prefix )
parser
El primer parámetro, parser, es una referencia al intérprete XML que llama al manejador.
prefix
El prefijo es una cadena que se utiliza para hacer referencia al namespace dentro de un objeto XML.

Si la función del manejador se configura como una cadena vacía, o false, el manejador en cuestión es deshabilitado.

Nota: En lugar del nombre de una función, se puede asignar un array que contenga la referencia a un objeto o el nombre de un método.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Notas

Nota:

Este evento no es soportado bajo LibXML.

Ver también

  • xml_set_start_namespace_decl_handler() - Configura el manejador de declaración de inicio del namespace

User Contributed Notes

There are no user contributed notes for this page.


Configura el manejador de referencia a entidades externas

  • « xml_set_end_namespace_decl_handler
  • xml_set_notation_decl_handler »
  • PHP Manual
  • Funciones del Intérprete XML
  • Configura el manejador de referencia a entidades externas

xml_set_external_entity_ref_handler

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

xml_set_external_entity_ref_handler — Configura el manejador de referencia a entidades externas

Descripción

xml_set_external_entity_ref_handler ( resource $parser , callable $handler ) : bool

Configura la función del manejador de referencia a entidades externas para el intérprete XML parser.

Parámetros

parser

Identificador del recurso del intérprete XML para el que se va a configurar la función del manejador de referencia a entidades externas

handler

handler es un string que contiene el nombre de una función que debe existir cuando xml_parse() es llamado por parser.

La función llamada mediante handler debe aceptar cinco parámetros, y deberia devolver un número entero. Si el valor devuelto desde el manejador es false (lo cual ocurrirá si no se devulve un valor), el intérprete XML detendrá el analizado y xml_get_error_code() devolverá XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $open_entity_names , string $base , string $system_id , string $public_id )
parser
El primer parámetro, parser, hace referencia al intérprete XML que llama al manejador.
open_entity_names
El segundo parámetro, open_entity_names, es una lista separada por espacios de los nombres de las entidades que estan abiertas para el análisis de esta entidad (incluyendo el nombre de la entidad referenciada).
base
Esta es la base para resolver el identificador de sistema (system_id) de la declaración de notación. Actualmente este parámetro siempre se establecerá como una cadena vacia.
system_id
El cuarto parámetro, system_id, es el identificador de sistema tal como se especifica en la declaración de entidad.
public_id
El quinto parámetro, public_id, es el identificador público tal como se especifica en la declaración de entidad, o una cadena vacia si no se habia especificado; en el identificador público el espacio en blanco se habrá normalizado como lo requerido mediante las especificaciones XML.

Si la función del manejador se configura como una cadena vacia, o false, el manejador en cuestión se deshabilita.

Nota: En lugar del nombre de una función, se puede asignar un array que contenga la referencia a un objeto o el nombre de un método.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Configura el manejador de declaraciones de notación

  • « xml_set_external_entity_ref_handler
  • xml_set_object »
  • PHP Manual
  • Funciones del Intérprete XML
  • Configura el manejador de declaraciones de notación

xml_set_notation_decl_handler

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

xml_set_notation_decl_handler — Configura el manejador de declaraciones de notación

Descripción

xml_set_notation_decl_handler ( resource $parser , callable $handler ) : bool

Configura la función del manejador de declaraciones de notación (NOTATION) para el intérprete XML parser.

Una declaración de notación es parte del DTD del documento y tiene el siguiente formato:

<!NOTATION <parameter>name</parameter>
      { <parameter>systemId</parameter> | <parameter>publicId</parameter>?>
Para la definición de declaraciones de notación ver » sección 4.7 de las especificaciones XML 1.0 .

Parámetros

parser

Identificador del recurso del intérprete XML para el que se va a configurar la función del manejador de declaración de notación.

handler

handler es un string que contiene el nombre de una función que debe existir cuando xml_parse() es llamado por parser.

La función llamada mediante handler debe aceptar cinco parámetros:

handler ( resource $parser , string $notation_name , string $base , string $system_id , string $public_id )
parser
El primer parámetro, parser, hace referencia al intérprete XML que llama al manejador.
notation_name
Esto es el name de la notación, como se describió arriba en el formato de notación.
base
Esta es la base para resolver el identificador de sistema (system_id) de la declaración de notación. Actualmente este parámetro siempre se establecerá como una cadena vacia.
system_id
Identificador de sistema de la declaración de notación externa.
public_id
Identificador público de la declaración de notación externa.

Si la función del manejador se configura como una cadena vacia, o false, el manejador en cuestión se deshabilita.

Nota: En lugar del nombre de una función, se puede asignar un array que contenga la referencia a un objeto o el nombre de un método.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Usa un intérprete XML Parser dentro de un objeto

  • « xml_set_notation_decl_handler
  • xml_set_processing_instruction_handler »
  • PHP Manual
  • Funciones del Intérprete XML
  • Usa un intérprete XML Parser dentro de un objeto

xml_set_object

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_object — Usa un intérprete XML Parser dentro de un objeto

Descripción

xml_set_object ( resource $parser , object &$object ) : bool

Esta función permite usar parser dentro de object. Todas las funciones de retorno se podrian establecer con xml_set_element_handler(), etc y asumirlas como métodos de object.

Parámetros

parser

Identificador del recurso del intérprete XML para usar dentro del objeto.

object

El objeto donde usar el intérprete XML.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo xml_set_object()

<?php
class xml  {
    var $parser;

    function xml()
    {
        $this->parser = xml_parser_create();

        xml_set_object($this->parser, $this);
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
    }

    function parse($data)
    {
        xml_parse($this->parser, $data);
    }

    function tag_open($parser, $tag, $attributes)
    {
        var_dump($parser, $tag, $attributes);
    }

    function cdata($parser, $cdata)
    {
        var_dump($parser, $cdata);
    }

    function tag_close($parser, $tag)
    {
        var_dump($parser, $tag);
    }

} // end of class xml

$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
?>

User Contributed Notes

joey at gimo dot co dot uk 10-Aug-2016 10:32
This function seems to be of very limited use when [$object_instance, "method_name"] is a callable.
wake dot shinigami at gmail dot com 23-Nov-2005 08:28
I finally managed to get xml_set_object() to work, after much documentation searching.  As the solution I found has been hinted at, the focus has been wrong.

There have been many problems getting class contained XML parsers to make changes to the members of an instance.  This is because, from what I'm guessing, the functions are using a either a new annonymous instance of the class or an uninstanced version of the class.

What we want to make sure it does it that the parser is accessing its handlers as member methods of a particular instance of a class.  This can be done using the array method for passing a callback, setting the object as a reference to this instance.  This way, you know that the parser is going to call the function properly.

Ex:
<?php
class Parser {

 private $parser;
 private $data;

 public function __construct() {
  $this->parser = NULL;
  $this->data = '';
 }

 private function ParseElementStart($parser, $name, $attrs) {
  // Code
 }
 private function ParseElementEnd($parser, $name) {
  // Code
 }

 public function Parse($XMLdata) {
  $this->parser = xml_parser_create();
  xml_set_object($this->parser, $this);
  xml_set_element_handler($this->parser,
                          array(&$this, 'ParseElementStart'),
                          array(&$this, 'ParseElementEnd'));
  xml_parse($this->parser, $XMLdata);
  xml_parser_free($this->parser);
 }
}
?>

With this, when you call the Parse method, the data in that instance can be modified.  I'm not sure if xml_set_object becomes unneccissary when using the array callbacks, but I leave it in just to make sure that the xml_parse function knows it's in the object.

As above, I'd recommend for memory sake, that the XML parser be created, used, and freed all in the same function, to ensure that everything is cleaned up correctly.
bettmenn at gmx dot de 16-Oct-2004 02:03
Adding to 'lmfe at mega dot ist dot utl dot pt' contribution below, I have to say that this behaviour is very usual for PHP if MemberVars of an Object arent initialized from the constructor.
What worked best for me so far was something like this:
<?php
class foo {
  var $bar
  // the constructor
  function foo() {
    unset($this->bar);  // with every instanciation, the variable is cleared for the object
  }
}
?>
lmfe at mega dot ist dot utl dot pt 29-Sep-2004 10:51
Using PHP 4.3.0, I got this strange behaviour:

<?php
class xml  {

     /* (as specified in the documentation above) */

} // end of class xml

/* This code works */
$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo'>PHP</A>");

/* This code works */
$xml_parser2 = new xml();
$xml_parser2->parse("<A ID='hallo2'>PHP2</A>");

/* This code DON'T work */
$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo3'>PHP3</A>");
?>

In the third block of code, php complains it can't find the handlers it needs.
It seems this problem only happens if the variable is used more than once.
Calling xml_parser_free doesn't help
hwheinzen at t-online dot de 14-Aug-2004 03:38
(Adding to zitan's note)
It seems easy enough to provide output functions for callback handler classes too.

Example:

<?php
class CallBack {
    var $name = 'Callback';
    var $info = 'Information!';
    function toString() {
        return $this->name.': '.$this->info;
    }
}
class Main {
    var $name = 'Main';
    var $callBackObject;
    function setCallBack(&$cBIn) { $this->callBackObject = $cBIn; }
    function toString() {
        return $this->name.': '.$this->callBackObject->toString();
    }
}

$cb = & new CallBack;
$m = & new Main;
$m->setCallBack(&$cb);
echo $cb->toString();
echo $m->toString();
?>

So, after collecting information during the parse operation within the callback handler class, e.g. in tag_close(), retrieving them is possible.
zitan at mediasculpt dot net 01-Sep-2003 09:05
Just a note about creating abstract "call back handlers" as mentioned in some of the other notes.  In this case I recommend extending the base XML class and overwritting the handler methods.  The reason I wanted to do this, is that if you have a separate callback method class it causes problems, for example if you want to collect information out of the XML file and store it in an array.  You can get around it with global variables, but I prefer to use them only when required ;)

Example:

<?php
class xml_output extends xml{

  var $output = array();

   function xml_output(){
    $this->xml();
   }

    //overwrite base methods
    function tag_open($parser, $tag, $attributes)
    {
        array_push($this->output, "<$tag, attributes>");
    }

    function cdata($parser, $cdata)
    {
         array_push($this->output, "$cdata");
    }

    function tag_close($parser, $tag)
    {
         array_push($this->output, "</$tag>");
    }

}

$xml_parser = & new xml_output();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
echo("$xml_parser->output");
?>
sbeam at syxyz dot net 12-Nov-2002 09:34
passing the object as a call-time ref (&$this) as in the example will create a warning in php 4.1+. Pass xml_set_object($xp,$this); instead. This does not seem to break anything - but I dont know for sure.
chiefgeek at ecodedesign.com 04-Aug-2002 10:37
Just adding a little note about my above written example.  It needs some improvements.

Because PHP passes by VALUE by default, when you pass an array like this:
array($callback_handler, 'handler_method')
PHP makes a copy of the callback_handler object and uses the handler_method in the copy.

This is not an ideal situation for many reasons...which I will not get into here...but you should have an idea by now.

The best way to fix this is to change a few things. In the function declaration change the parameter from $callback_handler to &$callback_handler. So now your declaration should look like this

function set_callback_handler(&$callback_handler)
{
  ...
}

Now each time you reference $callback_handler change it to &$callback_handler.  For example:

xml_set_element_handler(
          $this->xml_parser,
          array(&$callback_handler, 'start_element'),
          array(&$callback_handler, 'close_Element' ));

This ensures that PHP will always use the same object.
chiefgeek at ecodedesign.com 03-Aug-2002 08:25
xml_set_object is great, if you want to hard code your start_element, end_element, etc functions within your xml class.

But what if you want to increase the modularity of your application?

Solution, create one generic XMLParser class that handles everything *except* the callback funtions.  Then create an abstract XMLCallbackHandler class which you can extend to provide any customization you want.

So how do you tell the php's xml_parser that you want to use this other class to handle the callback functions.

xml_set_object?  This only works if the functions are *within* the object you called this method from.

The solution lies in the xml_set_element_handler() function.
Take a look at this sample source...

class XMLParser
{

  ...

  function set_callback_handler($callback_handler)
  {
    // Assign the startElement endElement functions
    xml_set_element_handler(
          $this->xml_parser,
          array($callback_handler, 'start_element'),
          array($callback_handler, 'close_Element' ));

    /* By passing an array with this ($object, 'function_name') structure
       to the 2nd and 3rd parameters.  We are able to tell the parser to
       look in another object for these callback functions.
    */

    // Assign the character data function
    xml_set_character_data_handler(
          $this->xml_parser,
          array($callback_handler, 'character_data'));
    }
}

class myCallBackHandler
{
  function start_element(...)
  {
    //code goes here
  }

  function end_element(...)
  {
    //code goes here
  }

  function character_data(...)
  {
    //code goes here
  }
}

Now all thats left to do is use these classes..

$parser = new XMLParser();
$parser->set_callback_handler(new myCallbackHandler());
dfoesch at cs dot nmsu dot edu 12-Apr-2002 05:38
English explaination of why you do: $xml = & new xml();

Ok, when PHP executes "new xml()" it creates an anonymous variable (one that you can't reference with any name) which it then runs the constructor function on.  Ok, now once that's done, it then assigns by VALUE in the example above.  This means that that lovely pointer to your parser is pointing to the anonymous instance of your class, and not the used instance of your class... thus making a "shadow" of all your variables, where assignments inside the parser access different variables than outside the parser.  What PHP _SHOULD_ be doing (similar to C++) is have this statement execute such that the assignment is done by REFERENCE, so that you assign the new name to the class that actually got constructed, and not just a copy of the class that you constructed.

If they did it right, this code wouldn't be broken.
14-Feb-2002 11:10
Call-time pass-by-reference has been deprecated, so the example is buggy as was already mentionned. However since 4.04 (I think) "new" can return objects by reference. So the clean way to have both the parser initialised in the constructor, and to save the result in your object is to do

$xml_parser = & new xml();

see http://www.php.net/manual/en/language.oop.newref.php

Ivan
pete dot nelson at serverSXPYAZMsolved dot com 27-Aug-2001 10:15
<p>in reply to jon9mm's question, I have found the same problem (function 'startElement' does not exist).  I finally found the way around this, by re-reading this doc for xml_set_object.  You HAVE to use the xml_set_object($this->parser, &$this) within your parser function.</p> <p>When that function is called, your object temporarily becomes the parser object and shares scope (so it can see 'startElement', etc).   Once that function is done, the xml_set_object(...) call goes out of scope, and your object is no longer bound to the parser.  So the simplist solution is to call xml_set_object(...), do any parsing, and then call xml_parser_free(...) all within the same function.</p>
<p>And remember, don't call xml_set_object(...) in your object's constructor - your object will be forever bound to the parser object and you'll loose all access to your object's member functions.</p>
<p>This is all explained in the examples above, but it took me reading it a couple of times to grok how it all works.</p>
nick at category4 dot com 14-May-2001 01:45
If you're using the XML parser within an object, be careful not to accidentally call any methods that don't exist within the object. Instead of complaining that the missing method doesn't exist, PHP will say it's not able to find the handler routines, even if you've indicated them correctly. (PHP version 4.0.5 on FreeBSD).
williams at cse dot unl dot edu 06-Dec-2000 12:42
If xml_set_object is not called in the constructor of an object, the values that the parser modifies will be saved. Else, the values do not seem to be saved as stated by "i_sofer" above.
--- Start Example Code ---
class foo {
var xmlparser;
function foo() { \\the constructor
$this->xmlparser=xmlparser_create();
}
function parse() {
xml_set_object($this->xmlparser,&$this);
\\also include data handler
\\and element handlers here
}
}
--- End Example Code ---
i_sofer at yahoo dot com 18-Nov-2000 04:15
Using xml parser in objects seem to have a problem that values modified(even of the object itself) get lost as soon as parsing ends...
malcontent at msgto dot com 20-Aug-2000 12:11
The example will generate a warning unless allow_call_time_pass_reference is set to true in your INI file. It also will not accept a call by value.
robert at webmotion dot com 18-Apr-2000 10:58
While true that there is no automatic destructor for PHP class objects, it is quite simple to create a method called destroy and perform the destruction manually. In the example above it may not be necessary to free the xml parser immediately... it would appear from the example that the object is re-useable.


Configura el manejador de instrucciones de proceso (PI)

  • « xml_set_object
  • xml_set_start_namespace_decl_handler »
  • PHP Manual
  • Funciones del Intérprete XML
  • Configura el manejador de instrucciones de proceso (PI)

xml_set_processing_instruction_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_processing_instruction_handler — Configura el manejador de instrucciones de proceso (PI)

Descripción

xml_set_processing_instruction_handler ( resource $parser , callable $handler ) : bool

Configura la función del manejador de instrucciones de proceso para el intérprete XML. parser.

Una instrucción de proceso tiene el siguiente formato:

<?
target data
?>
Se puede poner código PHP dentro de esa etiqueta, pero ser consciente de una limitación: en un XML PI, la etiqueta de cierre PI tag (?>) no puede ser entrecomillada, por lo que esta secuencia de caracteres no deberia aparecer en el código PHP embebido con PIs en documentos XML. Si esto sucede, el resto del código PHP, así como la etiqueta de cierre de PI "real", serán tratados como datos de caracteres.

Parámetros

parser

Identificador del recurso del intérprete XML para el que se va a configurar la función del manejador de instrucción de proceso.

handler

handler es un string que contiene el nombre de una función que debe existir cuando xml_parse() es llamado por parser.

La función llamada mediante handler debe aceptar tres parámetros:

handler ( resource $parser , string $target , string $data )
parser
El primer parámetro, parser, hace referencia al intérprete XML que llama al manejador.
target
El segundo parámetro, target, contiene el PI destino.
data
El tercer parámetro, data, contiene los datos del PI

Si la función del manejador se configura como una cadena vacia, o false, el manejador en cuestión se deshabilita.

Nota: En lugar del nombre de una función, se puede asignar un array que contenga la referencia a un objeto o el nombre de un método.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Configura el manejador de declaración de inicio del namespace

  • « xml_set_processing_instruction_handler
  • xml_set_unparsed_entity_decl_handler »
  • PHP Manual
  • Funciones del Intérprete XML
  • Configura el manejador de declaración de inicio del namespace

xml_set_start_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

xml_set_start_namespace_decl_handler — Configura el manejador de declaración de inicio del namespace

Descripción

xml_set_start_namespace_decl_handler ( resource $parser , callable $handler ) : bool

Configura un manejador para ser llamado cuando un namespace es declarado. La declaración de namespace ocurre dentro de las etiquetas de inicio. Sin embargo, el manejador inicial de declaración del namespace es llamado antes del manejador de etiqueta inicial para cada namespace declarado en esa etiqueta de inicio.

Parámetros

parser

Identificador del recurso del intérprete XML.

handler

handler es una cadena que contiene el nombre de una función que debe existir cuando xml_parse() es llamado por parser.

La función llamada mediante handler debe aceptar tres parámetros, y deberia devolver un número entero. Si el valor devuelto desde el manejador es false (lo cual ocurrirá si no se devulve un valor), el intérprete XML detendrá el analizado y xml_get_error_code() devolverá XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $prefix , string $uri )
parser
El primer parámetro, parser, es una referencia al intérprete XML que llama al manejador.
prefix
El prefijo es una cadena que se utiliza para hacer referencia al namespace dentro de un objeto XML.
uri
Identificador de Recurso Uniforme (URI, por sus siglas en inglés) del namespace.

Si una función del manejador se configura como una cadena vacía, o false, el manejador en cuestión es deshabilitado.

Nota: En lugar del nombre de una función, se puede asignar un array que contenga la referencia a un objeto o el nombre de un método.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • xml_set_end_namespace_decl_handler() - Configura el manejador de declaración de final del namespace

User Contributed Notes

There are no user contributed notes for this page.


Configura el manejador de declaración de entidades no analizadas

  • « xml_set_start_namespace_decl_handler
  • XMLReader »
  • PHP Manual
  • Funciones del Intérprete XML
  • Configura el manejador de declaración de entidades no analizadas

xml_set_unparsed_entity_decl_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

xml_set_unparsed_entity_decl_handler — Configura el manejador de declaración de entidades no analizadas

Descripción

xml_set_unparsed_entity_decl_handler ( resource $parser , callable $handler ) : bool

Configura la función del manejador de declaración de entidades no analizadas para el intérprete XML parser.

El handler será llamado si el intérprete XML encuentra una declaración de entidad externa con una declaración NDATA, como la siguiente:

<!ENTITY <parameter>name</parameter> {<parameter>publicId</parameter> | <parameter>systemId</parameter>}
        NDATA <parameter>notationName</parameter>

Para la definición de notación de NDATA ver » sección 4.2.2 de las especificaciones XML 1.0.

Parámetros

parser

Identificador del recurso del intérprete XML para el que se va a configurar la función del manejador de declaración de entidades no analizadas.

handler

handler es un string que contiene el nombre de una función que debe existir cuando xml_parse() es llamado por parser.

La función llamada mediante handler debe aceptar seis parámetros:

handler ( resource $parser , string $entity_name , string $base , string $system_id , string $public_id , string $notation_name )
parser
El primer parámetro, parser, hace referencia al intérprete XML que llama al manejador.
entity_name
El nombre de la entidad que está a punto de definirse.
base
Esta es la base para resolver el identificador de sistema (system_id) de la declaración de notación. Actualmente este parámetro siempre se establecerá como una cadena vacia.
system_id
Identificador de sistema de la declaración de notación externa.
public_id
Identificador público de la declaración de notación externa.
notation_name
Nombre de la notación de esta entidad (ver xml_set_notation_decl_handler()).

Si la función del manejador se configura como una cadena vacia, o false, el manejador en cuestión se deshabilita.

Nota: En lugar del nombre de una función, se puede asignar un array que contenga la referencia a un objeto o el nombre de un método.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


XMLReader

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • XMLReader — The XMLReader class
    • XMLReader::close — Cierra la entrada del XMLReader
    • XMLReader::expand — Devuelve una copia del actual nodo como un objeto DOM
    • XMLReader::getAttribute — Obtiener el valor del atributo nombrado
    • XMLReader::getAttributeNo — Obtiene el valor de un atributo por el indice
    • XMLReader::getAttributeNs — Obtiene el valor de un atributo por su nombre local y URI
    • XMLReader::getParserProperty — Indica si la porpiedad especificada ha sido establecida
    • XMLReader::isValid — Indica si el documento analizado es válido
    • XMLReader::lookupNamespace — Busca el namespace para un prefijo
    • XMLReader::moveToAttribute — Mueve el cursor a un atributo nombrado
    • XMLReader::moveToAttributeNo — Mueve el cursor a un atributo por su índice
    • XMLReader::moveToAttributeNs — Mover el cursor a un atributo dado
    • XMLReader::moveToElement — Posiciona el cursor en el eleménto padre del actual atributo
    • XMLReader::moveToFirstAttribute — Posiciona el cursor en el primer atributo
    • XMLReader::moveToNextAttribute — Posiciona el cursor en el siguiente atributo
    • XMLReader::next — Mueve el cursor al siguiente nodo saltandose todos los subárboles
    • XMLReader::open — Establece el URI conteniendo el XML a analizar
    • XMLReader::read — Se mueve al siguiente nodo en el documento
    • XMLReader::readInnerXML — Recupera el XML del actual nodo
    • XMLReader::readOuterXML — Recupera el XML del actual nodo, incluyendo él mismo
    • XMLReader::readString — Lee el contenido del nodo actual como string
    • XMLReader::setParserProperty — Establecer las opciones del analizador
    • XMLReader::setRelaxNGSchema — Establece el nomb re del archivo o el URI para un esquema RelaxNG
    • XMLReader::setRelaxNGSchemaSource — Establece los datos contenidos en un esquema RelaxNG
    • XMLReader::setSchema — Valida el documento en contra del XSD
    • XMLReader::XML — Establece el contenido del XML a analizar

User Contributed Notes

kraussInode at yahoo dot com 27-Mar-2010 12:54
See also XMLWriter: XMLReader and XMLWriter complement each other.


Introducción

La extensión XMLReader es un analizador de XML. El lector actúa como un cursor yendo hacia delante en el flujo del documento y deteniéndose en cada nodo del camino.

Codificación

Es importante observar que, internamente, libxml usa la codificación UTF-8, y por lo tanto, la codificación de los contenidos recuperados estará siempre en la codificación UTF-8.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

La extensión XMLReader inicialmente era una extensión PECL para PHP 5. Posteriormente se movió al código fuente de PHP a partir de PHP 5.1.0, y se habilitó de forma predeterminada a partir de PHP 5.1.2.

Esta extensión está habilitada de forma predeterminada. Se puede deshabilitar empleando la siguiente opción durante la compilación: --disable-xmlreader

User Contributed Notes

Miguel Cruz 11-Jun-2012 01:06
If you are having trouble loading this extension (perhaps with a log message like 'Undefined symbol "dom_node_class_entry"'), make sure that you have xmlreader.so listed AFTER dom.so in php.ini.
alvaro at digdib dot com 02-Jan-2009 02:33
Gentoo users: emerge does not compile dev-lang/php with --enable-xmlreader by default. To enable this option, add the flag xmlreader to your USE variable and recompile php.


The XMLReader class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Introducción

La extensión XMLReader es un analizador de XML. El lector actúa como un cursor yendo hacia adelante en la corriente del documento y deteniéndose en cada nodo del camino.

Sinopsis de la Clase

XMLReader {
/* Constantes */
const int NONE = 0 ;
const int ELEMENT = 1 ;
const int ATTRIBUTE = 2 ;
const int TEXT = 3 ;
const int CDATA = 4 ;
const int ENTITY_REF = 5 ;
const int ENTITY = 6 ;
const int PI = 7 ;
const int COMMENT = 8 ;
const int DOC = 9 ;
const int DOC_TYPE = 10 ;
const int DOC_FRAGMENT = 11 ;
const int NOTATION = 12 ;
const int WHITESPACE = 13 ;
const int SIGNIFICANT_WHITESPACE = 14 ;
const int END_ELEMENT = 15 ;
const int END_ENTITY = 16 ;
const int XML_DECLARATION = 17 ;
const int LOADDTD = 1 ;
const int DEFAULTATTRS = 2 ;
const int VALIDATE = 3 ;
const int SUBST_ENTITIES = 4 ;
/* Propiedades */
public readonly int $attributeCount ;
public readonly string $baseURI ;
public readonly int $depth ;
public readonly bool $hasAttributes ;
public readonly bool $hasValue ;
public readonly bool $isDefault ;
public readonly bool $isEmptyElement ;
public readonly string $localName ;
public readonly string $name ;
public readonly string $namespaceURI ;
public readonly int $nodeType ;
public readonly string $prefix ;
public readonly string $value ;
public readonly string $xmlLang ;
/* Métodos */
public close ( ) : bool
public expand ( DOMNode $basenode = ? ) : DOMNode
public getAttribute ( string $name ) : string
public getAttributeNo ( int $index ) : string
public getAttributeNs ( string $localName , string $namespaceURI ) : string
public getParserProperty ( int $property ) : bool
public isValid ( ) : bool
public lookupNamespace ( string $prefix ) : bool
public moveToAttribute ( string $name ) : bool
public moveToAttributeNo ( int $index ) : bool
public moveToAttributeNs ( string $localName , string $namespaceURI ) : bool
public moveToElement ( ) : bool
public moveToFirstAttribute ( ) : bool
public moveToNextAttribute ( ) : bool
public next ( string $localname = ? ) : bool
public open ( string $URI , string $encoding = ? , int $options = 0 ) : bool
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 xml ( string $source , string $encoding = ? , int $options = 0 ) : bool
}

Propiedades

attributeCount

El número de atributos en el nodo

baseURI

La base URI del nodo

depth

La profundidad del nodo en el árbol, empezando en 0

hasAttributes

Indica si el nodo tiene atributos

hasValue

Indica si el nodo tiene un valor de texto

isDefault

Indica si el atributo está por defecto del DTD

isEmptyElement

Indica si el nodo es un elemento vacio de etiqueta

localName

El nombre local del nodo

name

El nombre calificado del nodo

namespaceURI

El URI del namespace asociado con el nodo

nodeType

El tipo de nodo para el nodo

prefix

El prefijo del namespace asociado con el nodo

value

El valor de texto del nodo

xmlLang

El xml: El lang scope el cual el nodo reside

Constantes predefinidas

XMLReader Node Types

XMLReader::NONE

Sin tipo de nodo

XMLReader::ELEMENT

Empieza el eleménto

XMLReader::ATTRIBUTE

El atributo del nodo

XMLReader::TEXT

El nodo de texto

XMLReader::CDATA

El CDATA del nodo

XMLReader::ENTITY_REF

La entidad de refencia del nodo

XMLReader::ENTITY

La entidad de declaración del nodo

XMLReader::PI

La instrucción de proceso del nodo

XMLReader::COMMENT

El comentario del nodo

XMLReader::DOC

El documento del nodo

XMLReader::DOC_TYPE

El tipo de documento del nodo

XMLReader::DOC_FRAGMENT

El fragmento del documento del nodo

XMLReader::NOTATION

La notación del nodo

XMLReader::WHITESPACE

El espacio en blanco del nodo

XMLReader::SIGNIFICANT_WHITESPACE

El espacio en blanco significante del nodo

XMLReader::END_ELEMENT

El fin del eleménto

XMLReader::END_ENTITY

La entidad final

XMLReader::XML_DECLARATION

La declaración XML del nodo

XMLReader Parser Options

XMLReader::LOADDTD

Carga el DTD pero no lo valida

XMLReader::DEFAULTATTRS

Carga el DTD y los atributos por defecto pero no los valida

XMLReader::VALIDATE

Carga el DTD y valida el analizado en blanco

XMLReader::SUBST_ENTITIES

Substituye las entidades y expande las referencias

Tabla de contenidos

  • XMLReader::close — Cierra la entrada del XMLReader
  • XMLReader::expand — Devuelve una copia del actual nodo como un objeto DOM
  • XMLReader::getAttribute — Obtiener el valor del atributo nombrado
  • XMLReader::getAttributeNo — Obtiene el valor de un atributo por el indice
  • XMLReader::getAttributeNs — Obtiene el valor de un atributo por su nombre local y URI
  • XMLReader::getParserProperty — Indica si la porpiedad especificada ha sido establecida
  • XMLReader::isValid — Indica si el documento analizado es válido
  • XMLReader::lookupNamespace — Busca el namespace para un prefijo
  • XMLReader::moveToAttribute — Mueve el cursor a un atributo nombrado
  • XMLReader::moveToAttributeNo — Mueve el cursor a un atributo por su índice
  • XMLReader::moveToAttributeNs — Mover el cursor a un atributo dado
  • XMLReader::moveToElement — Posiciona el cursor en el eleménto padre del actual atributo
  • XMLReader::moveToFirstAttribute — Posiciona el cursor en el primer atributo
  • XMLReader::moveToNextAttribute — Posiciona el cursor en el siguiente atributo
  • XMLReader::next — Mueve el cursor al siguiente nodo saltandose todos los subárboles
  • XMLReader::open — Establece el URI conteniendo el XML a analizar
  • XMLReader::read — Se mueve al siguiente nodo en el documento
  • XMLReader::readInnerXML — Recupera el XML del actual nodo
  • XMLReader::readOuterXML — Recupera el XML del actual nodo, incluyendo él mismo
  • XMLReader::readString — Lee el contenido del nodo actual como string
  • XMLReader::setParserProperty — Establecer las opciones del analizador
  • XMLReader::setRelaxNGSchema — Establece el nomb re del archivo o el URI para un esquema RelaxNG
  • XMLReader::setRelaxNGSchemaSource — Establece los datos contenidos en un esquema RelaxNG
  • XMLReader::setSchema — Valida el documento en contra del XSD
  • XMLReader::XML — Establece el contenido del XML a analizar

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>


Cierra la entrada del XMLReader

  • « XMLReader
  • XMLReader::expand »
  • PHP Manual
  • XMLReader
  • Cierra la entrada del XMLReader

XMLReader::close

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::close — Cierra la entrada del XMLReader

Descripción

public XMLReader::close ( ) : bool

Cierra la entrada del objeto XMLReader que es actualmente análizado.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLReader::open() - Establece el URI conteniendo el XML a analizar
  • XMLReader::xml() - Establece el contenido del XML a analizar

User Contributed Notes

There are no user contributed notes for this page.


Devuelve una copia del actual nodo como un objeto DOM

  • « XMLReader::close
  • XMLReader::getAttribute »
  • PHP Manual
  • XMLReader
  • Devuelve una copia del actual nodo como un objeto DOM

XMLReader::expand

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::expand — Devuelve una copia del actual nodo como un objeto DOM

Descripción

public XMLReader::expand ( DOMNode $basenode = ? ) : DOMNode

Éste metodo copia el nodo actual y devuelve el apropiado objeto DOM.

Valores devueltos

El resultante DOMNode o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Obtiener el valor del atributo nombrado

  • « XMLReader::expand
  • XMLReader::getAttributeNo »
  • PHP Manual
  • XMLReader
  • Obtiener el valor del atributo nombrado

XMLReader::getAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getAttribute — Obtiener el valor del atributo nombrado

Descripción

public XMLReader::getAttribute ( string $name ) : string

Devuelve el valor del atributo nombrado o null si el atributo no existe o no está posicionado en un eleménto del nodo.

Parámetros

name

El nombre del atributo.

Valores devueltos

El valor del atributo, o null si no se encuetra un atributo con el nombre dado por name o no está posicionado en un nodo de elemento.

Historial de cambios

Versión | Descripción
5.1.3 | Devuelve null si no se encuentra ningún atributo. Antes, devolvía una cadena de texto vacía.

Ver también

  • XMLReader::getAttributeNo() - Obtiene el valor de un atributo por el indice
  • XMLReader::getAttributeNs() - Obtiene el valor de un atributo por su nombre local y URI

User Contributed Notes

Anonymous 16-Feb-2011 09:02
Or use XMLReader::ELEMENT and XMLReader::END_ELEMENT rather than the numbers 1 and 15.
Gabi 02-Jul-2007 08:15
might be obvious, but not to everyone ;-) ... when reading attributes from a node that has sub-nodes (and creating an output from this node), the output will be issued twice, once on the <ELEMENT> tag and once on the end tag </ELEMENT>. To avoid this, you can test on which part of the node you are using the property nodeType.
It'll be 1 for the element, 15 for the end element.


Obtiene el valor de un atributo por el indice

  • « XMLReader::getAttribute
  • XMLReader::getAttributeNs »
  • PHP Manual
  • XMLReader
  • Obtiene el valor de un atributo por el indice

XMLReader::getAttributeNo

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getAttributeNo — Obtiene el valor de un atributo por el indice

Descripción

public XMLReader::getAttributeNo ( int $index ) : string

Devuelve el valor de un atributo basado en su posición o una cadena vacia si el atributo no existe o no está posicionado en un eleménto del nodo.

Parámetros

index

La posición del atributo.

Valores devueltos

El valor del atributo, o una cadena vacia si el atributo no existe en el index o no está posicionado en el eleménto.

Ver también

  • XMLReader::getAttribute() - Obtiener el valor del atributo nombrado
  • XMLReader::getAttributeNs() - Obtiene el valor de un atributo por su nombre local y URI

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el valor de un atributo por su nombre local y URI

  • « XMLReader::getAttributeNo
  • XMLReader::getParserProperty »
  • PHP Manual
  • XMLReader
  • Obtiene el valor de un atributo por su nombre local y URI

XMLReader::getAttributeNs

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getAttributeNs — Obtiene el valor de un atributo por su nombre local y URI

Descripción

public XMLReader::getAttributeNs ( string $localName , string $namespaceURI ) : string

Devuelve el valor de un atributo por su nombre y URI del namespace o una cadena vacia si el atributo no existe o no está posicionado en el eleménto.

Parámetros

localName

El nombre local.

namespaceURI

El URI del namespace.

Valores devueltos

El valor del atributo, o una cadena vacia si ningun atributo con el localName dado y el namespaceURI es encontrado o no está posicionado en el eleménto.

Ver también

  • XMLReader::getAttribute() - Obtiener el valor del atributo nombrado
  • XMLReader::getAttributeNo() - Obtiene el valor de un atributo por el indice

User Contributed Notes

There are no user contributed notes for this page.


Indica si la porpiedad especificada ha sido establecida

  • « XMLReader::getAttributeNs
  • XMLReader::isValid »
  • PHP Manual
  • XMLReader
  • Indica si la porpiedad especificada ha sido establecida

XMLReader::getParserProperty

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::getParserProperty — Indica si la porpiedad especificada ha sido establecida

Descripción

public XMLReader::getParserProperty ( int $property ) : bool

Indica si la porpiedad especificada ha sido establecida.

Parámetros

property

Una de las constantes analizadoras de opción.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLReader::setParserProperty() - Establecer las opciones del analizador

User Contributed Notes

There are no user contributed notes for this page.


Indica si el documento analizado es válido

  • « XMLReader::getParserProperty
  • XMLReader::lookupNamespace »
  • PHP Manual
  • XMLReader
  • Indica si el documento analizado es válido

XMLReader::isValid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::isValid — Indica si el documento analizado es válido

Descripción

public XMLReader::isValid ( ) : bool

Devuelve un booleano indicando si el documento siendo analizado es actualmente válido.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Validando el XML

<?php
$xml = XMLReader::open('test.xml');

// Debe estar habilitada la opción del analizador para
// que este método funcione correctamente
$xml->setParserProperty(XMLReader::VALIDATE, true);

var_dump($xml->isValid());
?>

Notas

Nota: Esto comprueba el nodo actual, no el documento completo.

Ver también

  • XMLReader::setParserProperty() - Establecer las opciones del analizador
  • XMLReader::setRelaxNGSchema() - Establece el nomb re del archivo o el URI para un esquema RelaxNG
  • XMLReader::setRelaxNGSchemaSource() - Establece los datos contenidos en un esquema RelaxNG
  • XMLReader::setSchema() - Valida el documento en contra del XSD

User Contributed Notes

zubin at trattonuovo dot com 20-Jan-2010 03:00
I encountered some problems to use isValid method with xml2assoc function.
I use this way to validate the entire xml file and put it into an associative array.

$xml = new XMLReader();
if (!$xml->xml($xml_string, NULL, LIBXML_DTDVALID)) {
  echo "XML not valid: load error";
  exit();
}

libxml_use_internal_errors(TRUE);

$xml_array = xml2assoc($xml);

$arErrors = libxml_get_errors();
$xml_errors = "";
foreach ($arErrors AS $xmlError) $xml_errors .= $xmlError->message;
if ($xml_errors != "") {
  echo "XML not valid: ".$xml_errors;
  exit();
}

//all ok
remy dot damour at laposte dot net 31-Dec-2008 03:27
1. If you validate against relax-ng, no need to call $xml->setParserProperty(XMLReader::VALIDATE, true);

2. Be aware that $xml->isValid() will return validity for currently active node (ie. node currently positioned using $xml->read()). It won't check validity of your entire tree at once, but rather on a step by step basis
anzenews at volja dot net 22-Jan-2008 10:50
This comment is only partially correct:
"isValid() always returns false unless you enable checking for validity by $reader->setParserProperty(XMLReader::VALIDATE, true);"
This enables DTD checking, but you can also check by using RelaxNG (see setRelaxNGSchema() and setRelaxNGSchemaSource()).

And also, this is NOT correct:
"If you just need to check if XML file is well formed, successful loading into XMLReader object is usually enough."
It is not enough. Pull parsers operate on stream and if you have a large enough file they will not know it is well formed until it is read to the end. If you need to know if it is well formed or/and valid, read it till the end or validation error (you can use next() for fast reading if you don't care about contents).


Busca el namespace para un prefijo

  • « XMLReader::isValid
  • XMLReader::moveToAttribute »
  • PHP Manual
  • XMLReader
  • Busca el namespace para un prefijo

XMLReader::lookupNamespace

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::lookupNamespace — Busca el namespace para un prefijo

Descripción

public XMLReader::lookupNamespace ( string $prefix ) : bool

Busca el ámbito del namespace para un prefijo dado.

Parámetros

prefix

La cadena conteniendo el prefijo.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Mueve el cursor a un atributo nombrado

  • « XMLReader::lookupNamespace
  • XMLReader::moveToAttributeNo »
  • PHP Manual
  • XMLReader
  • Mueve el cursor a un atributo nombrado

XMLReader::moveToAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToAttribute — Mueve el cursor a un atributo nombrado

Descripción

public XMLReader::moveToAttribute ( string $name ) : bool

Posciciona el cursor a un atributo nombrado.

Parámetros

name

El nombre del atributo.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLReader::moveToElement() - Posiciona el cursor en el eleménto padre del actual atributo
  • XMLReader::moveToAttributeNo() - Mueve el cursor a un atributo por su índice
  • XMLReader::moveToAttributeNs() - Mover el cursor a un atributo dado
  • XMLReader::moveToFirstAttribute() - Posiciona el cursor en el primer atributo

User Contributed Notes

There are no user contributed notes for this page.


Mueve el cursor a un atributo por su índice

  • « XMLReader::moveToAttribute
  • XMLReader::moveToAttributeNs »
  • PHP Manual
  • XMLReader
  • Mueve el cursor a un atributo por su índice

XMLReader::moveToAttributeNo

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToAttributeNo — Mueve el cursor a un atributo por su índice

Descripción

public XMLReader::moveToAttributeNo ( int $index ) : bool

Coloca el cursor en el atributo en función de su posición.

Parámetros

index

La posición de el atributo.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLReader::moveToElement() - Posiciona el cursor en el eleménto padre del actual atributo
  • XMLReader::moveToAttribute() - Mueve el cursor a un atributo nombrado
  • XMLReader::moveToAttributeNs() - Mover el cursor a un atributo dado
  • XMLReader::moveToFirstAttribute() - Posiciona el cursor en el primer atributo

User Contributed Notes

There are no user contributed notes for this page.


Mover el cursor a un atributo dado

  • « XMLReader::moveToAttributeNo
  • XMLReader::moveToElement »
  • PHP Manual
  • XMLReader
  • Mover el cursor a un atributo dado

XMLReader::moveToAttributeNs

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToAttributeNs — Mover el cursor a un atributo dado

Descripción

public XMLReader::moveToAttributeNs ( string $localName , string $namespaceURI ) : bool

Posiciona el cursor en el atributo dado en el espacio de nombres especificado.

Parámetros

localName

El nombre local.

namespaceURI

El URI namespace.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLReader::moveToElement() - Posiciona el cursor en el eleménto padre del actual atributo
  • XMLReader::moveToAttribute() - Mueve el cursor a un atributo nombrado
  • XMLReader::moveToAttributeNo() - Mueve el cursor a un atributo por su índice
  • XMLReader::moveToFirstAttribute() - Posiciona el cursor en el primer atributo

User Contributed Notes

There are no user contributed notes for this page.


Posiciona el cursor en el eleménto padre del actual atributo

  • « XMLReader::moveToAttributeNs
  • XMLReader::moveToFirstAttribute »
  • PHP Manual
  • XMLReader
  • Posiciona el cursor en el eleménto padre del actual atributo

XMLReader::moveToElement

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToElement — Posiciona el cursor en el eleménto padre del actual atributo

Descripción

public XMLReader::moveToElement ( ) : bool

Posiciona el cursor en el eleménto padre del actual atributo.

Valores devueltos

Devuelve true si es satisfactorio y false si falla o no está posicionado en el atributo cuando éste método es llamado.

Ver también

  • XMLReader::moveToAttribute() - Mueve el cursor a un atributo nombrado
  • XMLReader::moveToAttributeNo() - Mueve el cursor a un atributo por su índice
  • XMLReader::moveToAttributeNs() - Mover el cursor a un atributo dado
  • XMLReader::moveToFirstAttribute() - Posiciona el cursor en el primer atributo

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.


Posiciona el cursor en el primer atributo

  • « XMLReader::moveToElement
  • XMLReader::moveToNextAttribute »
  • PHP Manual
  • XMLReader
  • Posiciona el cursor en el primer atributo

XMLReader::moveToFirstAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToFirstAttribute — Posiciona el cursor en el primer atributo

Descripción

public XMLReader::moveToFirstAttribute ( ) : bool

Mueve el cursor al primer atributo.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLReader::moveToElement() - Posiciona el cursor en el eleménto padre del actual atributo
  • XMLReader::moveToAttribute() - Mueve el cursor a un atributo nombrado
  • XMLReader::moveToAttributeNo() - Mueve el cursor a un atributo por su índice
  • XMLReader::moveToAttributeNs() - Mover el cursor a un atributo dado
  • XMLReader::moveToNextAttribute() - Posiciona el cursor en el siguiente atributo

User Contributed Notes

There are no user contributed notes for this page.


Posiciona el cursor en el siguiente atributo

  • « XMLReader::moveToFirstAttribute
  • XMLReader::next »
  • PHP Manual
  • XMLReader
  • Posiciona el cursor en el siguiente atributo

XMLReader::moveToNextAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::moveToNextAttribute — Posiciona el cursor en el siguiente atributo

Descripción

public XMLReader::moveToNextAttribute ( ) : bool

Posiciona el cursor en el siguiente atributo si se encuentra en un atributo o lo mueve al primer atributo si se encuentrae un eleménto.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLReader::moveToElement() - Posiciona el cursor en el eleménto padre del actual atributo
  • XMLReader::moveToAttribute() - Mueve el cursor a un atributo nombrado
  • XMLReader::moveToAttributeNo() - Mueve el cursor a un atributo por su índice
  • XMLReader::moveToAttributeNs() - Mover el cursor a un atributo dado
  • XMLReader::moveToFirstAttribute() - Posiciona el cursor en el primer atributo

User Contributed Notes

There are no user contributed notes for this page.


Mueve el cursor al siguiente nodo saltandose todos los subárboles

  • « XMLReader::moveToNextAttribute
  • XMLReader::open »
  • PHP Manual
  • XMLReader
  • Mueve el cursor al siguiente nodo saltandose todos los subárboles

XMLReader::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::next — Mueve el cursor al siguiente nodo saltandose todos los subárboles

Descripción

public XMLReader::next ( string $localname = ? ) : bool

Posiciona el cursor al siguiente nodo saltandose todos los subárboles.

Parámetros

localname

El nodo del siguiente nodoa mover el cursor.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLReader::moveToNextAttribute() - Posiciona el cursor en el siguiente atributo
  • XMLReader::moveToElement() - Posiciona el cursor en el eleménto padre del actual atributo
  • XMLReader::moveToAttribute() - Mueve el cursor a un atributo nombrado

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();}


Establece el URI conteniendo el XML a analizar

  • « XMLReader::next
  • XMLReader::read »
  • PHP Manual
  • XMLReader
  • Establece el URI conteniendo el XML a analizar

XMLReader::open

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::open — Establece el URI conteniendo el XML a analizar

Descripción

public XMLReader::open ( string $URI , string $encoding = ? , int $options = 0 ) : bool

Establece el URI que contiene el XML a ser analizado.

Parámetros

URI

El URI señalado para el documento.

encoding

El documento codificado o null.

options

Una mascara de bit de las contantes de LIBXML_*.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error. Si es llamado de forma estática, devuelve un XMLReader o false en caso de error.

Errores/Excepciones

Este método puede ser llamado de forma estática, pero lanzará un error E_STRICT.

Historial de cambios

Versión | Descripción
5.2.0 | encoding y options fueron agregadas.

Ver también

  • XMLReader::xml() - Establece el contenido del XML a analizar
  • XMLReader::close() - Cierra la entrada del 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.


Se mueve al siguiente nodo en el documento

  • « XMLReader::open
  • XMLReader::readInnerXML »
  • PHP Manual
  • XMLReader
  • Se mueve al siguiente nodo en el documento

XMLReader::read

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::read — Se mueve al siguiente nodo en el documento

Descripción

public XMLReader::read ( ) : bool

Mueve el cursor al siguiente nodo en el documento.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLReader::moveToElement() - Posiciona el cursor en el eleménto padre del actual atributo
  • XMLReader::moveToAttribute() - Mueve el cursor a un atributo nombrado
  • XMLReader::next() - Mueve el cursor al siguiente nodo saltandose todos los subárboles

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.


Recupera el XML del actual nodo

  • « XMLReader::read
  • XMLReader::readOuterXML »
  • PHP Manual
  • XMLReader
  • Recupera el XML del actual nodo

XMLReader::readInnerXML

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::readInnerXML — Recupera el XML del actual nodo

Descripción

public XMLReader::readInnerXML ( ) : string

Lee el contenido del actual nodo, incluyendo notas pequeñas y marcado.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the contents of the current node as a string. Empty string on failure.

Notas

Precaución

Esta función sólo esta disponible cuando PHP ha sido compilado con libxml 20620 o superior.

Ver también

  • XMLReader::readString() - Lee el contenido del nodo actual como string
  • XMLReader::readOuterXML() - Recupera el XML del actual nodo, incluyendo él mismo
  • XMLReader::expand() - Devuelve una copia del actual nodo como un objeto DOM

User Contributed Notes

Evert Pot 20-Mar-2015 08:26
Disregard my other comment.

readInnerXml does not advance the cursor, so you can call it more than once. I made a mistake testing this.
Evert Pot 20-Mar-2015 08:21
Note that readInnerXml() also advances the cursor.


Recupera el XML del actual nodo, incluyendo él mismo

  • « XMLReader::readInnerXML
  • XMLReader::readString »
  • PHP Manual
  • XMLReader
  • Recupera el XML del actual nodo, incluyendo él mismo

XMLReader::readOuterXML

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::readOuterXML — Recupera el XML del actual nodo, incluyendo él mismo

Descripción

public XMLReader::readOuterXML ( ) : string

Lee el contenido del actual nodo, incluyendo el nodo mismo.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve el contenido del actual nodo, incluyendo el de él mismo, como una cadena. Cadena vacía en fallo.

Notas

Precaución

Esta función sólo esta disponible cuando PHP ha sido compilado con libxml 20620 o superior.

Ver también

  • XMLReader::readString() - Lee el contenido del nodo actual como string
  • XMLReader::readInnerXML() - Recupera el XML del actual nodo
  • XMLReader::expand() - Devuelve una copia del actual nodo como un objeto 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.


Lee el contenido del nodo actual como string

  • « XMLReader::readOuterXML
  • XMLReader::setParserProperty »
  • PHP Manual
  • XMLReader
  • Lee el contenido del nodo actual como string

XMLReader::readString

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::readString — Lee el contenido del nodo actual como string

Descripción

public XMLReader::readString ( ) : string

Lee el contenido del nodo actual como string.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve el contenido del nodo actual como cadena. En caso de error devuelve una cadena vacía.

Notas

Precaución

Esta función sólo esta disponible cuando PHP ha sido compilado con libxml 20620 o superior.

Ver también

  • XMLReader::readOuterXML() - Recupera el XML del actual nodo, incluyendo él mismo
  • XMLReader::readInnerXML() - Recupera el XML del actual nodo
  • XMLReader::expand() - Devuelve una copia del actual nodo como un objeto 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>


Establecer las opciones del analizador

  • « XMLReader::readString
  • XMLReader::setRelaxNGSchema »
  • PHP Manual
  • XMLReader
  • Establecer las opciones del analizador

XMLReader::setParserProperty

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::setParserProperty — Establecer las opciones del analizador

Descripción

public XMLReader::setParserProperty ( int $property , bool $value ) : bool

Establece las opciones del analizador. Las opciones deben ser establecidas después de
llamar a XMLReader::open() o
a XMLReader::xml(), y antes
de la primera llamada a XMLReader::read().

Parámetros

property

Una de las constantes de opción del analizador.

value

Si se establece a true la opción será habilitada, de otra manera será deshabilitada.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

User Contributed Notes

There are no user contributed notes for this page.


Establece el nomb re del archivo o el URI para un esquema RelaxNG

  • « XMLReader::setParserProperty
  • XMLReader::setRelaxNGSchemaSource »
  • PHP Manual
  • XMLReader
  • Establece el nomb re del archivo o el URI para un esquema RelaxNG

XMLReader::setRelaxNGSchema

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::setRelaxNGSchema — Establece el nomb re del archivo o el URI para un esquema RelaxNG

Descripción

public XMLReader::setRelaxNGSchema ( string $filename ) : bool

Establece el nomb re del archivo o el URI para un esquema RelaxNG a usar para validación.

Parámetros

filename

El nombre del archivo o apuntador URI a un esquema RelaxNG.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLReader::setRelaxNGSchemaSource() - Establece los datos contenidos en un esquema RelaxNG
  • XMLReader::setSchema() - Valida el documento en contra del XSD
  • XMLReader::isValid() - Indica si el documento analizado es válido

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


Establece los datos contenidos en un esquema RelaxNG

  • « XMLReader::setRelaxNGSchema
  • XMLReader::setSchema »
  • PHP Manual
  • XMLReader
  • Establece los datos contenidos en un esquema RelaxNG

XMLReader::setRelaxNGSchemaSource

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::setRelaxNGSchemaSource — Establece los datos contenidos en un esquema RelaxNG

Descripción

public XMLReader::setRelaxNGSchemaSource ( string $source ) : bool

Establece los datos contenidos en un esquema RelaxNG a usar para validación.

Parámetros

source

SCadena que contiene el esquema RelaxNG.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLReader::setRelaxNGSchema() - Establece el nomb re del archivo o el URI para un esquema RelaxNG
  • XMLReader::setSchema() - Valida el documento en contra del XSD
  • XMLReader::isValid() - Indica si el documento analizado es válido

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();
?>


Valida el documento en contra del XSD

  • « XMLReader::setRelaxNGSchemaSource
  • XMLReader::XML »
  • PHP Manual
  • XMLReader
  • Valida el documento en contra del XSD

XMLReader::setSchema

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

XMLReader::setSchema — Valida el documento en contra del XSD

Descripción

public XMLReader::setSchema ( string $filename ) : bool

Usa el esquema W3C XSD para validar el documento como es procesado. La activación solo es posible antes de la primera lectura o Read().

Parámetros

filename

El nombre del archivo del esquema XSD.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

Las cuestiones E_WARNING si la libxml fue construida sin el esquema de soporte, el esquema contiene errores si el XMLReader::read() ya ha sido llamado.

Notas

Precaución

Esta función sólo esta disponible cuando PHP ha sido compilado con libxml 20620 o superior.

Ver también

  • XMLReader::setRelaxNGSchema() - Establece el nomb re del archivo o el URI para un esquema RelaxNG
  • XMLReader::setRelaxNGSchemaSource() - Establece los datos contenidos en un esquema RelaxNG
  • XMLReader::isValid() - Indica si el documento analizado es válido

User Contributed Notes

There are no user contributed notes for this page.


Establece el contenido del XML a analizar

  • « XMLReader::setSchema
  • XMLWriter »
  • PHP Manual
  • XMLReader
  • Establece el contenido del XML a analizar

XMLReader::XML

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

XMLReader::XML — Establece el contenido del XML a analizar

Descripción

public XMLReader::xml ( string $source , string $encoding = ? , int $options = 0 ) : bool

Establece el contenido del XML a analizar.

Parámetros

source

La cadena que contiene el XML a ser analizado.

encoding

La codificación del documento o null.

options

Una mascara bit de la constante LIBXML_*.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error. Si es llamado de forma estática, devuelve un XMLReader o false en caso de error.

Errores/Excepciones

Este método puede ser llamado de forma estática, pero lanzará un error E_STRICT.

Historial de cambios

Versión | Descripción
5.2.0 | encoding ay options fueron agregados.

Ver también

  • XMLReader::open() - Establece el URI conteniendo el XML a analizar
  • XMLReader::close() - Cierra la entrada del XMLReader

User Contributed Notes

There are no user contributed notes for this page.


XMLWriter

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Ejemplos
    • Crear un simple documento XML
    • Trabajar con espacios de nombres XML
    • Trabajando con el OO API
  • XMLWriter — La clase XMLWriter
    • XMLWriter::endAttribute — End attribute
    • XMLWriter::endCdata — End current CDATA
    • XMLWriter::endComment — Create end comment
    • XMLWriter::endDocument — End current document
    • XMLWriter::endDtd — End current DTD
    • XMLWriter::endDtdAttlist — End current DTD AttList
    • XMLWriter::endDtdElement — End current DTD element
    • XMLWriter::endDtdEntity — End current DTD Entity
    • XMLWriter::endElement — End current element
    • XMLWriter::endPi — End current PI
    • XMLWriter::flush — Flush current buffer
    • XMLWriter::fullEndElement — End current element
    • XMLWriter::openMemory — Create new xmlwriter using memory for string output
    • XMLWriter::openUri — Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory — Returns current buffer
    • XMLWriter::setIndent — Toggle indentation on/off
    • XMLWriter::setIndentString — Set string used for indenting
    • XMLWriter::startAttribute — Create start attribute
    • XMLWriter::startAttributeNs — Create start namespaced attribute
    • XMLWriter::startCdata — Create start CDATA tag
    • XMLWriter::startComment — Create start comment
    • XMLWriter::startDocument — Create document tag
    • XMLWriter::startDtd — Create start DTD tag
    • XMLWriter::startDtdAttlist — Create start DTD AttList
    • XMLWriter::startDtdElement — Create start DTD element
    • XMLWriter::startDtdEntity — Create start DTD Entity
    • XMLWriter::startElement — Create start element tag
    • XMLWriter::startElementNs — Create start namespaced element tag
    • XMLWriter::startPi — Create start PI tag
    • XMLWriter::text — Write text
    • XMLWriter::writeAttribute — Write full attribute
    • XMLWriter::writeAttributeNs — Write full namespaced attribute
    • XMLWriter::writeCdata — Write full CDATA tag
    • XMLWriter::writeComment — Write full comment tag
    • XMLWriter::writeDtd — Write full DTD tag
    • XMLWriter::writeDtdAttlist — Write full DTD AttList tag
    • XMLWriter::writeDtdElement — Write full DTD element tag
    • XMLWriter::writeDtdEntity — Write full DTD Entity tag
    • XMLWriter::writeElement — Write full element tag
    • XMLWriter::writeElementNs — Write full namespaced element tag
    • XMLWriter::writePi — Writes a PI
    • XMLWriter::writeRaw — Write a raw XML text

User Contributed Notes

lingtalfi 08-Oct-2015 08:35
The single quote predefined entity is not escaped.
The other predefined entities are but not the single quote, so you will have to do it yourself.

That's what you would expect:

Ampersand     &     &amp;
Single Quote     '     &apos;
Double Quote     "     &quot;
Greater Than     >     &gt;
Less Than     <     &lt;

That's what you get with \XmlWriter:

Ampersand     &     &amp;
Single Quote     '     '
Double Quote     "     &quot;
Greater Than     >     &gt;
Less Than     <     &lt;
Alexey Zakhlestin 09-Jun-2008 03:47
important: XMLWriter expects UTF-8 data from you. It can output xml in various encodings, but input should be strictly utf-8!


Introducción

Esta es la extensión XMLWriter. Envuelve a la API xmlWriter de libxml.

Esta extensión representa un escritor que provee medios no almacenados en caché de sólo avance para la generación de flujos o ficheros con datos XML.

Esta extensión se puede usar con el estilo orientado a objetos o con el procedimental. Cada método documentado describe la llamada procedimental alternativa.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

La extensión XMLWriter inicialmente era una extensión PECL para PHP 5. Posteriormente se añadió al código fuente de PHP a partir de PHP 5.1.2. Esta extensión está habilitada de forma predeterminada.

Esta extensión está habilitada de forma predeterminada. Se puede deshabilitar empleando la siguiente opción durante la compilación: --disable-xmlwriter

User Contributed Notes

There are no user contributed notes for this page.


Tipos de recursos

Hay un recurso usado por la versión procedimental de la extensión XMLWriter: el devuelto por xmlwriter_open_memory() o xmlwriter_open_uri().

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

Tabla de contenidos

  • Crear un simple documento XML
  • Trabajar con espacios de nombres XML
  • Trabajando con el OO API

User Contributed Notes

There are no user contributed notes for this page.


Crear un simple documento XML

Este ejemplo muestra cómo utilizar XMLWriter para crear un documento XML en memoria.

Ejemplo #1 Crear un simple documento 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($xw, 'tag1');

// Attribute 'att1' for element 'tag1'
xmlwriter_start_attribute($xw, 'att1');
xmlwriter_text($xw, 'valueofatt1');
xmlwriter_end_attribute($xw);

xmlwriter_write_comment($xw, 'this is a comment.');

// Start a child element
xmlwriter_start_element($xw, 'tag11');
xmlwriter_text($xw, 'This is a sample text, ä');
xmlwriter_end_element($xw); // tag11

xmlwriter_end_element($xw); // tag1

// CDATA
xmlwriter_start_element($xw, 'testc');
xmlwriter_write_cdata($xw, "This is cdata content");
xmlwriter_end_element($xw); // testc

xmlwriter_start_element($xw, 'testc');
xmlwriter_start_cdata($xw);
xmlwriter_text($xw, "test cdata2");
xmlwriter_end_cdata($xw);
xmlwriter_end_element($xw); // testc

// A processing instruction
xmlwriter_start_pi($xw, 'php');
xmlwriter_text($xw, '$foo=2;echo $foo;');
xmlwriter_end_pi($xw);

xmlwriter_end_document($xw);

echo xmlwriter_output_memory($xw);

El resultado del ejemplo sería:

<?xml version="1.0" encoding="UTF-8"?>
<tag1 att1="valueofatt1">
 <!--this is a comment.-->
 <tag11>This is a sample text, ä</tag11>
</tag1>
<testc><![CDATA[This is cdata content]]></testc>
<testc><![CDATA[test cdata2]]></testc>
<?php $foo=2;echo $foo;?>

User Contributed Notes

There are no user contributed notes for this page.


Trabajar con espacios de nombres XML

Este ejemplo muestra cómo crear elementos XML con espacio de nombres.

Ejemplo #1 Trabajar con espacios de nombres 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);

El resultado del ejemplo sería:

<?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.


Trabajando con el OO API

Este ejemplo muestra cómo trabajar con la API orientada a objetos de XMLWriter.

Ejemplo #1 Trabajando con el OO API

<?php

$xw = new XMLWriter();
$xw->openMemory();
$xw->startDocument("1.0");
$xw->startElement("book");
$xw->text("example");
$xw->endElement();
$xw->endDocument();
echo $xw->outputMemory();

El resultado del ejemplo sería:

<?xml version="1.0"?>
<book>example</book>

User Contributed Notes

There are no user contributed notes for this page.


La clase XMLWriter

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

Introducción

Sinopsis de la Clase

XMLWriter {
/* Métodos */
public endAttribute ( ) : bool
public endCdata ( ) : bool
public endComment ( ) : bool
public endDocument ( ) : bool
public endDtd ( ) : bool
public endDtdAttlist ( ) : bool
public endDtdElement ( ) : bool
public endDtdEntity ( ) : bool
public endElement ( ) : bool
public endPi ( ) : bool
public flush ( bool $empty = true ) : string|int
public fullEndElement ( ) : bool
public openMemory ( ) : bool
public openUri ( string $uri ) : bool
public outputMemory ( bool $flush = true ) : string
public setIndent ( bool $enable ) : bool
public setIndentString ( string $indentation ) : bool
public startAttribute ( string $name ) : bool
public startAttributeNs ( string|null $prefix , string $name , string|null $namespace ) : bool
public startCdata ( ) : bool
public startComment ( ) : bool
public startDocument ( string|null $version = "1.0" , string|null $encoding = null , string|null $standalone = null ) : bool
public startDtd ( string $qualifiedName , string|null $publicId = null , string|null $systemId = null ) : bool
public startDtdAttlist ( string $name ) : bool
public startDtdElement ( string $qualifiedName ) : bool
public startDtdEntity ( string $name , bool $isParam ) : bool
public startElement ( string $name ) : bool
public startElementNs ( string|null $prefix , string $name , string|null $namespace ) : bool
public startPi ( string $target ) : bool
public text ( string $content ) : bool
public writeAttribute ( string $name , string $value ) : bool
public writeAttributeNs ( string|null $prefix , string $name , string|null $namespace , string $value ) : bool
public writeCdata ( string $content ) : bool
public writeComment ( string $content ) : bool
public writeDtd ( string $name , string|null $publicId = null , string|null $systemId = null , string|null $content = null ) : bool
public writeDtdAttlist ( string $name , string $content ) : bool
public writeDtdElement ( string $name , string $content ) : bool
public writeDtdEntity ( string $name , string $content , bool $isParam = false , string|null $publicId = null , string|null $systemId = null , string|null $notationData = null ) : bool
public writeElement ( string $name , string|null $content = null ) : bool
public writeElementNs ( string|null $prefix , string $name , string|null $namespace , string|null $content = null ) : bool
public writePi ( string $target , string $content ) : bool
public writeRaw ( string $content ) : bool
}

Tabla de contenidos

  • XMLWriter::endAttribute — End attribute
  • XMLWriter::endCdata — End current CDATA
  • XMLWriter::endComment — Create end comment
  • XMLWriter::endDocument — End current document
  • XMLWriter::endDtd — End current DTD
  • XMLWriter::endDtdAttlist — End current DTD AttList
  • XMLWriter::endDtdElement — End current DTD element
  • XMLWriter::endDtdEntity — End current DTD Entity
  • XMLWriter::endElement — End current element
  • XMLWriter::endPi — End current PI
  • XMLWriter::flush — Flush current buffer
  • XMLWriter::fullEndElement — End current element
  • XMLWriter::openMemory — Create new xmlwriter using memory for string output
  • XMLWriter::openUri — Create new xmlwriter using source uri for output
  • XMLWriter::outputMemory — Returns current buffer
  • XMLWriter::setIndent — Toggle indentation on/off
  • XMLWriter::setIndentString — Set string used for indenting
  • XMLWriter::startAttribute — Create start attribute
  • XMLWriter::startAttributeNs — Create start namespaced attribute
  • XMLWriter::startCdata — Create start CDATA tag
  • XMLWriter::startComment — Create start comment
  • XMLWriter::startDocument — Create document tag
  • XMLWriter::startDtd — Create start DTD tag
  • XMLWriter::startDtdAttlist — Create start DTD AttList
  • XMLWriter::startDtdElement — Create start DTD element
  • XMLWriter::startDtdEntity — Create start DTD Entity
  • XMLWriter::startElement — Create start element tag
  • XMLWriter::startElementNs — Create start namespaced element tag
  • XMLWriter::startPi — Create start PI tag
  • XMLWriter::text — Write text
  • XMLWriter::writeAttribute — Write full attribute
  • XMLWriter::writeAttributeNs — Write full namespaced attribute
  • XMLWriter::writeCdata — Write full CDATA tag
  • XMLWriter::writeComment — Write full comment tag
  • XMLWriter::writeDtd — Write full DTD tag
  • XMLWriter::writeDtdAttlist — Write full DTD AttList tag
  • XMLWriter::writeDtdElement — Write full DTD element tag
  • XMLWriter::writeDtdEntity — Write full DTD Entity tag
  • XMLWriter::writeElement — Write full element tag
  • XMLWriter::writeElementNs — Write full namespaced element tag
  • XMLWriter::writePi — Writes a PI
  • XMLWriter::writeRaw — Write a raw XML text

User Contributed Notes

There are no user contributed notes for this page.


End attribute

  • « XMLWriter
  • XMLWriter::endCdata »
  • PHP Manual
  • XMLWriter
  • End attribute

XMLWriter::endAttribute

xmlwriter_end_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endAttribute -- xmlwriter_end_attribute — End attribute

Descripción

Estilo orientado a objetos

public XMLWriter::endAttribute ( ) : bool

Estilo por procedimientos

xmlwriter_end_attribute ( XMLWriter $writer ) : bool

Ends the current attribute.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


End current CDATA

  • « XMLWriter::endAttribute
  • XMLWriter::endComment »
  • PHP Manual
  • XMLWriter
  • End current CDATA

XMLWriter::endCdata

xmlwriter_end_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endCdata -- xmlwriter_end_cdata — End current CDATA

Descripción

Estilo orientado a objetos

public XMLWriter::endCdata ( ) : bool

Estilo por procedimientos

xmlwriter_end_cdata ( XMLWriter $writer ) : bool

Ends the current CDATA section.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startCdata() - Create start CDATA tag
  • XMLWriter::writeCdata() - Write full CDATA tag

User Contributed Notes

There are no user contributed notes for this page.


Create end comment

  • « XMLWriter::endCdata
  • XMLWriter::endDocument »
  • PHP Manual
  • XMLWriter
  • Create end comment

XMLWriter::endComment

xmlwriter_end_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::endComment -- xmlwriter_end_comment — Create end comment

Descripción

Estilo orientado a objetos

public XMLWriter::endComment ( ) : bool

Estilo por procedimientos

xmlwriter_end_comment ( XMLWriter $writer ) : bool

Ends the current comment.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::writeComment() - Write full comment tag

User Contributed Notes

There are no user contributed notes for this page.


End current document

  • « XMLWriter::endComment
  • XMLWriter::endDtd »
  • PHP Manual
  • XMLWriter
  • End current document

XMLWriter::endDocument

xmlwriter_end_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDocument -- xmlwriter_end_document — End current document

Descripción

Estilo orientado a objetos

public XMLWriter::endDocument ( ) : bool

Estilo por procedimientos

xmlwriter_end_document ( XMLWriter $writer ) : bool

Ends the current document.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startDocument() - Create document tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD

  • « XMLWriter::endDocument
  • XMLWriter::endDtdAttlist »
  • PHP Manual
  • XMLWriter
  • End current DTD

XMLWriter::endDtd

xmlwriter_end_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtd -- xmlwriter_end_dtd — End current DTD

Descripción

Estilo orientado a objetos

public XMLWriter::endDtd ( ) : bool

Estilo por procedimientos

xmlwriter_end_dtd ( XMLWriter $writer ) : bool

Ends the DTD of the document.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startDtd() - Create start DTD tag
  • XMLWriter::writeDtd() - Write full DTD tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD AttList

  • « XMLWriter::endDtd
  • XMLWriter::endDtdElement »
  • PHP Manual
  • XMLWriter
  • End current DTD AttList

XMLWriter::endDtdAttlist

xmlwriter_end_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdAttlist -- xmlwriter_end_dtd_attlist — End current DTD AttList

Descripción

Estilo orientado a objetos

public XMLWriter::endDtdAttlist ( ) : bool

Estilo por procedimientos

xmlwriter_end_dtd_attlist ( XMLWriter $writer ) : bool

Ends the current DTD attribute list.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startDtdAttlist() - Create start DTD AttList
  • XMLWriter::writeDtdAttlist() - Write full DTD AttList tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD element

  • « XMLWriter::endDtdAttlist
  • XMLWriter::endDtdEntity »
  • PHP Manual
  • XMLWriter
  • End current DTD element

XMLWriter::endDtdElement

xmlwriter_end_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdElement -- xmlwriter_end_dtd_element — End current DTD element

Descripción

Estilo orientado a objetos

public XMLWriter::endDtdElement ( ) : bool

Estilo por procedimientos

xmlwriter_end_dtd_element ( XMLWriter $writer ) : bool

Ends the current DTD element.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startDtdElement() - Create start DTD element
  • XMLWriter::writeDtdElement() - Write full DTD element tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD Entity

  • « XMLWriter::endDtdElement
  • XMLWriter::endElement »
  • PHP Manual
  • XMLWriter
  • End current DTD Entity

XMLWriter::endDtdEntity

xmlwriter_end_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdEntity -- xmlwriter_end_dtd_entity — End current DTD Entity

Descripción

Estilo orientado a objetos

public XMLWriter::endDtdEntity ( ) : bool

Estilo por procedimientos

xmlwriter_end_dtd_entity ( XMLWriter $writer ) : bool

Ends the current DTD entity.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startDtdEntity() - Create start DTD Entity
  • XMLWriter::writeDtdEntity() - Write full DTD Entity tag

User Contributed Notes

There are no user contributed notes for this page.


End current element

  • « XMLWriter::endDtdEntity
  • XMLWriter::endPi »
  • PHP Manual
  • XMLWriter
  • End current element

XMLWriter::endElement

xmlwriter_end_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endElement -- xmlwriter_end_element — End current element

Descripción

Estilo orientado a objetos

public XMLWriter::endElement ( ) : bool

Estilo por procedimientos

xmlwriter_end_element ( XMLWriter $writer ) : bool

Ends the current element.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


End current PI

  • « XMLWriter::endElement
  • XMLWriter::flush »
  • PHP Manual
  • XMLWriter
  • End current PI

XMLWriter::endPi

xmlwriter_end_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endPi -- xmlwriter_end_pi — End current PI

Descripción

Estilo orientado a objetos

public XMLWriter::endPi ( ) : bool

Estilo por procedimientos

xmlwriter_end_pi ( XMLWriter $writer ) : bool

Ends the current processing instruction.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startPi() - Create start PI tag
  • XMLWriter::writePi() - Writes a PI

User Contributed Notes

There are no user contributed notes for this page.


Flush current buffer

  • « XMLWriter::endPi
  • XMLWriter::fullEndElement »
  • PHP Manual
  • XMLWriter
  • Flush current buffer

XMLWriter::flush

xmlwriter_flush

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::flush -- xmlwriter_flush — Flush current buffer

Descripción

Estilo orientado a objetos

public XMLWriter::flush ( bool $empty = true ) : string|int

Estilo por procedimientos

xmlwriter_flush ( XMLWriter $writer , bool $empty = true ) : string|int

Flushes the current buffer.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

empty

Whether to empty the buffer or not. Default is true.

Valores devueltos

If you opened the writer in memory, this function returns the generated XML buffer, Else, if using URI, this function will write the buffer and return the number of written bytes.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.
8.0.0 | This function can no longer return false.

User Contributed Notes

There are no user contributed notes for this page.


End current element

  • « XMLWriter::flush
  • XMLWriter::openMemory »
  • PHP Manual
  • XMLWriter
  • End current element

XMLWriter::fullEndElement

xmlwriter_full_end_element

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4)

XMLWriter::fullEndElement -- xmlwriter_full_end_element — End current element

Descripción

Estilo orientado a objetos

public XMLWriter::fullEndElement ( ) : bool

Estilo por procedimientos

xmlwriter_full_end_element ( XMLWriter $writer ) : bool

End the current xml element. Writes an end tag even if the element is empty.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::endElement() - End current element

User Contributed Notes

There are no user contributed notes for this page.


Create new xmlwriter using memory for string output

  • « XMLWriter::fullEndElement
  • XMLWriter::openUri »
  • PHP Manual
  • XMLWriter
  • Create new xmlwriter using memory for string output

XMLWriter::openMemory

xmlwriter_open_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openMemory -- xmlwriter_open_memory — Create new xmlwriter using memory for string output

Descripción

Estilo orientado a objetos

public XMLWriter::openMemory ( ) : bool

Estilo por procedimientos

xmlwriter_open_memory ( ) : XMLWriter|false

Creates a new XMLWriter using memory for string output.

Parámetros

Valores devueltos

Estilo orientado a objetos: Devuelve true en caso de éxito o false en caso de error.

Estilo por procedimientos: Returns a new XMLWriter for later use with the xmlwriter functions on success, o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | This function returns now an XMLWriter instance on success. Previouly, a recurso has been returned in this case.

Ver también

  • XMLWriter::openUri() - Create new xmlwriter using source uri for output

User Contributed Notes

There are no user contributed notes for this page.


Create new xmlwriter using source uri for output

  • « XMLWriter::openMemory
  • XMLWriter::outputMemory »
  • PHP Manual
  • XMLWriter
  • Create new xmlwriter using source uri for output

XMLWriter::openUri

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openUri -- xmlwriter_open_uri — Create new xmlwriter using source uri for output

Descripción

Estilo orientado a objetos

public XMLWriter::openUri ( string $uri ) : bool

Estilo por procedimientos

xmlwriter_open_uri ( string $uri ) : XMLWriter|false

Creates a new XMLWriter using uri for the output.

Parámetros

uri

The URI of the resource for the output.

Valores devueltos

Estilo orientado a objetos: Devuelve true en caso de éxito o false en caso de error.

Estilo por procedimientos: Returns a new XMLWriter instance for later use with the xmlwriter functions on success, o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | This function returns now an XMLWriter instance on success. Previouly, a recurso has been returned in this case.

Ejemplos

Ejemplo #1 Direct output of XML

It is possible to directly output XML by using the php://output stream wrapper.

<?php
$out =new XMLWriter();
$out->openURI('php://output');
?>

Notas

Nota:

On Windows, files opened with this function are locked until the writer is released.

Ver también

  • XMLWriter::openMemory() - Create new xmlwriter using memory for string output

User Contributed Notes

There are no user contributed notes for this page.


Returns current buffer

  • « XMLWriter::openUri
  • XMLWriter::setIndent »
  • PHP Manual
  • XMLWriter
  • Returns current buffer

XMLWriter::outputMemory

xmlwriter_output_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::outputMemory -- xmlwriter_output_memory — Returns current buffer

Descripción

Estilo orientado a objetos

public XMLWriter::outputMemory ( bool $flush = true ) : string

Estilo por procedimientos

xmlwriter_output_memory ( XMLWriter $writer , bool $flush = true ) : string

Returns the current buffer.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

flush

Whether to flush the output buffer or not. Default is true.

Valores devueltos

Returns the current buffer as a string.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::flush() - Flush current buffer

User Contributed Notes

There are no user contributed notes for this page.


Toggle indentation on/off

  • « XMLWriter::outputMemory
  • XMLWriter::setIndentString »
  • PHP Manual
  • XMLWriter
  • Toggle indentation on/off

XMLWriter::setIndent

xmlwriter_set_indent

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndent -- xmlwriter_set_indent — Toggle indentation on/off

Descripción

Estilo orientado a objetos

public XMLWriter::setIndent ( bool $enable ) : bool

Estilo por procedimientos

xmlwriter_set_indent ( XMLWriter $writer , bool $enable ) : bool

Toggles indentation on or off.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

enable

Whether indentation is enabled.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ejemplos

Ejemplo #1 XMLWriter::setIndent() and mixed Content

Enabling indentation is not suitable for mixed content, because the indent string is also inserted before inline elements.

<?php
$writer = new XMLWriter();
$writer->openMemory();
$writer->setIndent(2);
$writer->startDocument();
$writer->startElement('p');
$writer->text('before');
$writer->writeElement('a', 'element');
$writer->text('after');
$writer->endElement();
$writer->endDocument();
echo $writer->outputMemory();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<p>before <a>element</a>
after</p>

Notas

Nota:

The indent is reset when an xmlwriter is opened.

Ver también

  • XMLWriter::setIndentString() - Set string used for indenting

User Contributed Notes

There are no user contributed notes for this page.


Set string used for indenting

  • « XMLWriter::setIndent
  • XMLWriter::startAttribute »
  • PHP Manual
  • XMLWriter
  • Set string used for indenting

XMLWriter::setIndentString

xmlwriter_set_indent_string

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndentString -- xmlwriter_set_indent_string — Set string used for indenting

Descripción

Estilo orientado a objetos

public XMLWriter::setIndentString ( string $indentation ) : bool

Estilo por procedimientos

xmlwriter_set_indent_string ( XMLWriter $writer , string $indentation ) : bool

Sets the string which will be used to indent each element/attribute of the resulting xml.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

indentation

The indentation string.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Notas

Nota:

The indent is reset when an xmlwriter is opened.

Ver también

  • XMLWriter::setIndent() - Toggle indentation on/off

User Contributed Notes

There are no user contributed notes for this page.


Create start attribute

  • « XMLWriter::setIndentString
  • XMLWriter::startAttributeNs »
  • PHP Manual
  • XMLWriter
  • Create start attribute

XMLWriter::startAttribute

xmlwriter_start_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttribute -- xmlwriter_start_attribute — Create start attribute

Descripción

Estilo orientado a objetos

public XMLWriter::startAttribute ( string $name ) : bool

Estilo por procedimientos

xmlwriter_start_attribute ( XMLWriter $writer , string $name ) : bool

Starts an attribute.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

name

The attribute name.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ejemplos

Ejemplo #1 Basic XMLWriter::startAttribute() Usage

<?php
$writer = new XMLWriter;
$writer->openURI('php://output');
$writer->startDocument('1.0', 'UTF-8');?>
$writer->startElement('element');
$writer->startAttribute('attribute');
$writer->text('value');
$writer->endAttribute();
$writer->endElement();
$writer->endDocument();

El resultado del ejemplo sería algo similar a:

<?xml version="1.0" encoding="UTF-8"?>
<element attribute="value"/>

Ver también

  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


Create start namespaced attribute

  • « XMLWriter::startAttribute
  • XMLWriter::startCdata »
  • PHP Manual
  • XMLWriter
  • Create start namespaced attribute

XMLWriter::startAttributeNs

xmlwriter_start_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttributeNs -- xmlwriter_start_attribute_ns — Create start namespaced attribute

Descripción

Estilo orientado a objetos

public XMLWriter::startAttributeNs ( string|null $prefix , string $name , string|null $namespace ) : bool

Estilo por procedimientos

xmlwriter_start_attribute_ns ( XMLWriter $writer , string|null $prefix , string $name , string|null $namespace ) : bool

Starts a namespaced attribute.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

prefix

The namespace prefix.

name

The attribute name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.
8.0.0 | prefix is nullable now.

Ver también

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


Create start CDATA tag

  • « XMLWriter::startAttributeNs
  • XMLWriter::startComment »
  • PHP Manual
  • XMLWriter
  • Create start CDATA tag

XMLWriter::startCdata

xmlwriter_start_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startCdata -- xmlwriter_start_cdata — Create start CDATA tag

Descripción

Estilo orientado a objetos

public XMLWriter::startCdata ( ) : bool

Estilo por procedimientos

xmlwriter_start_cdata ( XMLWriter $writer ) : bool

Starts a CDATA.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::endCdata() - End current CDATA
  • XMLWriter::writeCdata() - Write full CDATA tag

User Contributed Notes

There are no user contributed notes for this page.


Create start comment

  • « XMLWriter::startCdata
  • XMLWriter::startDocument »
  • PHP Manual
  • XMLWriter
  • Create start comment

XMLWriter::startComment

xmlwriter_start_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::startComment -- xmlwriter_start_comment — Create start comment

Descripción

Estilo orientado a objetos

public XMLWriter::startComment ( ) : bool

Estilo por procedimientos

xmlwriter_start_comment ( XMLWriter $writer ) : bool

Starts a comment.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::endComment() - Create end comment
  • XMLWriter::writeComment() - Write full comment tag

User Contributed Notes

There are no user contributed notes for this page.


Create document tag

  • « XMLWriter::startComment
  • XMLWriter::startDtd »
  • PHP Manual
  • XMLWriter
  • Create document tag

XMLWriter::startDocument

xmlwriter_start_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDocument -- xmlwriter_start_document — Create document tag

Descripción

Estilo orientado a objetos

public XMLWriter::startDocument ( string|null $version = "1.0" , string|null $encoding = null , string|null $standalone = null ) : bool

Estilo por procedimientos

xmlwriter_start_document ( XMLWriter $writer , string|null $version = "1.0" , string|null $encoding = null , string|null $standalone = null ) : bool

Starts a document.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

version

The version number of the document as part of the XML declaration.

encoding

The encoding of the document as part of the XML declaration.

standalone

yes or no.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::endDocument() - End current document

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD tag

  • « XMLWriter::startDocument
  • XMLWriter::startDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Create start DTD tag

XMLWriter::startDtd

xmlwriter_start_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtd -- xmlwriter_start_dtd — Create start DTD tag

Descripción

Estilo orientado a objetos

public XMLWriter::startDtd ( string $qualifiedName , string|null $publicId = null , string|null $systemId = null ) : bool

Estilo por procedimientos

xmlwriter_start_dtd ( XMLWriter $writer , string $qualifiedName , string|null $publicId = null , string|null $systemId = null ) : bool

Starts a DTD.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::endDtd() - End current DTD
  • XMLWriter::writeDtd() - Write full DTD tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD AttList

  • « XMLWriter::startDtd
  • XMLWriter::startDtdElement »
  • PHP Manual
  • XMLWriter
  • Create start DTD AttList

XMLWriter::startDtdAttlist

xmlwriter_start_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdAttlist -- xmlwriter_start_dtd_attlist — Create start DTD AttList

Descripción

Estilo orientado a objetos

public XMLWriter::startDtdAttlist ( string $name ) : bool

Estilo por procedimientos

xmlwriter_start_dtd_attlist ( XMLWriter $writer , string $name ) : bool

Starts a DTD attribute list.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

name

The attribute list name.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::endDtdAttlist() - End current DTD AttList
  • XMLWriter::writeDtdAttlist() - Write full DTD AttList tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD element

  • « XMLWriter::startDtdAttlist
  • XMLWriter::startDtdEntity »
  • PHP Manual
  • XMLWriter
  • Create start DTD element

XMLWriter::startDtdElement

xmlwriter_start_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdElement -- xmlwriter_start_dtd_element — Create start DTD element

Descripción

Estilo orientado a objetos

public XMLWriter::startDtdElement ( string $qualifiedName ) : bool

Estilo por procedimientos

xmlwriter_start_dtd_element ( XMLWriter $writer , string $qualifiedName ) : bool

Starts a DTD element.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::endDtdElement() - End current DTD element
  • XMLWriter::writeDtdElement() - Write full DTD element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD Entity

  • « XMLWriter::startDtdElement
  • XMLWriter::startElement »
  • PHP Manual
  • XMLWriter
  • Create start DTD Entity

XMLWriter::startDtdEntity

xmlwriter_start_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdEntity -- xmlwriter_start_dtd_entity — Create start DTD Entity

Descripción

Estilo orientado a objetos

public XMLWriter::startDtdEntity ( string $name , bool $isParam ) : bool

Estilo por procedimientos

xmlwriter_start_dtd_entity ( XMLWriter $writer , string $name , bool $isParam ) : bool

Starts a DTD entity.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

name

The name of the entity.

isParam

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::endDtdEntity() - End current DTD Entity
  • XMLWriter::writeDtdEntity() - Write full DTD Entity tag

User Contributed Notes

There are no user contributed notes for this page.


Create start element tag

  • « XMLWriter::startDtdEntity
  • XMLWriter::startElementNs »
  • PHP Manual
  • XMLWriter
  • Create start element tag

XMLWriter::startElement

xmlwriter_start_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startElement -- xmlwriter_start_element — Create start element tag

Descripción

Estilo orientado a objetos

public XMLWriter::startElement ( string $name ) : bool

Estilo por procedimientos

xmlwriter_start_element ( XMLWriter $writer , string $name ) : bool

Starts an element.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

name

The element name.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start namespaced element tag

  • « XMLWriter::startElement
  • XMLWriter::startPi »
  • PHP Manual
  • XMLWriter
  • Create start namespaced element tag

XMLWriter::startElementNs

xmlwriter_start_element_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startElementNs -- xmlwriter_start_element_ns — Create start namespaced element tag

Descripción

Estilo orientado a objetos

public XMLWriter::startElementNs ( string|null $prefix , string $name , string|null $namespace ) : bool

Estilo por procedimientos

xmlwriter_start_element_ns ( XMLWriter $writer , string|null $prefix , string $name , string|null $namespace ) : bool

Starts a namespaced element.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The element name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNs() - Write full namespaced element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start PI tag

  • « XMLWriter::startElementNs
  • XMLWriter::text »
  • PHP Manual
  • XMLWriter
  • Create start PI tag

XMLWriter::startPi

xmlwriter_start_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startPi -- xmlwriter_start_pi — Create start PI tag

Descripción

Estilo orientado a objetos

public XMLWriter::startPi ( string $target ) : bool

Estilo por procedimientos

xmlwriter_start_pi ( XMLWriter $writer , string $target ) : bool

Starts a processing instruction tag.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

target

The target of the processing instruction.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::endPi() - End current PI
  • XMLWriter::writePi() - Writes a PI

User Contributed Notes

There are no user contributed notes for this page.


Write text

  • « XMLWriter::startPi
  • XMLWriter::writeAttribute »
  • PHP Manual
  • XMLWriter
  • Write text

XMLWriter::text

xmlwriter_text

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::text -- xmlwriter_text — Write text

Descripción

Estilo orientado a objetos

public XMLWriter::text ( string $content ) : bool

Estilo por procedimientos

xmlwriter_text ( XMLWriter $writer , string $content ) : bool

Writes a text.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

content

The contents of the text. The characters <, >, & and " are written as entity references (i.e. &lt;, &gt;, &amp; and &quot;, respectively). All other characters including ' are written literally. To write the special XML characters literally, or to write literal entity references, xmlwriter_write_raw() has to be used.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Write full attribute

  • « XMLWriter::text
  • XMLWriter::writeAttributeNs »
  • PHP Manual
  • XMLWriter
  • Write full attribute

XMLWriter::writeAttribute

xmlwriter_write_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttribute -- xmlwriter_write_attribute — Write full attribute

Descripción

Estilo orientado a objetos

public XMLWriter::writeAttribute ( string $name , string $value ) : bool

Estilo por procedimientos

xmlwriter_write_attribute ( XMLWriter $writer , string $name , string $value ) : bool

Writes a full attribute.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

name

The name of the attribute.

value

The value of the attribute.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ejemplos

Ejemplo #1 Intermixing Sub-elements and Attributes

If writing sub-elements and attributes is intermixed, any attempt to write attributes after the first sub-element will fail and return false.

<?php
$xml = new XMLWriter();
$xml->openMemory();

$xml->startElement('element');
$xml->writeAttribute('attr1', '0');
$xml->writeElement('subelem', '0');
var_dump($xml->writeAttribute('attr2', '0'));
$xml->endElement();

echo $xml->flush();
?>

El resultado del ejemplo sería:

bool(false)
<element attr1="0"><subelem>0</subelem></element>

Ver también

  • XMLWriter::writeAttributeNs() - Write full namespaced attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute

User Contributed Notes

There are no user contributed notes for this page.


Write full namespaced attribute

  • « XMLWriter::writeAttribute
  • XMLWriter::writeCdata »
  • PHP Manual
  • XMLWriter
  • Write full namespaced attribute

XMLWriter::writeAttributeNs

xmlwriter_write_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttributeNs -- xmlwriter_write_attribute_ns — Write full namespaced attribute

Descripción

Estilo orientado a objetos

public XMLWriter::writeAttributeNs ( string|null $prefix , string $name , string|null $namespace , string $value ) : bool

Estilo por procedimientos

xmlwriter_write_attribute_ns ( XMLWriter $writer , string|null $prefix , string $name , string|null $namespace , string $value ) : bool

Writes a full namespaced attribute.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The attribute name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

value

The attribute value.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute

User Contributed Notes

There are no user contributed notes for this page.


Write full CDATA tag

  • « XMLWriter::writeAttributeNs
  • XMLWriter::writeComment »
  • PHP Manual
  • XMLWriter
  • Write full CDATA tag

XMLWriter::writeCdata

xmlwriter_write_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeCdata -- xmlwriter_write_cdata — Write full CDATA tag

Descripción

Estilo orientado a objetos

public XMLWriter::writeCdata ( string $content ) : bool

Estilo por procedimientos

xmlwriter_write_cdata ( XMLWriter $writer , string $content ) : bool

Writes a full CDATA.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

content

The contents of the CDATA.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ejemplos

Ejemplo #1 Basic xmlwriter_write_cdata() Usage

<?php
// set up the document
$xml = new XmlWriter();
$xml->openMemory();
$xml->setIndent(true);
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('mydoc');
$xml->startElement('myele');

// CData output
$xml->startElement('mycdataelement');
$xml->writeCData("text for inclusion as CData");
$xml->endElement();

// end the document and output
$xml->endElement();
$xml->endElement();
echo $xml->outputMemory(true);
?>

El resultado del ejemplo sería:

<mydoc>
 <myele>
  <mycdataelement><![CDATA[text for inclusion as CData]?]></mycdataelement>
 </myele>
</mydoc>

Ver también

  • XMLWriter::startCdata() - Create start CDATA tag
  • XMLWriter::endCdata() - End current CDATA

User Contributed Notes

There are no user contributed notes for this page.


Write full comment tag

  • « XMLWriter::writeCdata
  • XMLWriter::writeDtd »
  • PHP Manual
  • XMLWriter
  • Write full comment tag

XMLWriter::writeComment

xmlwriter_write_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeComment -- xmlwriter_write_comment — Write full comment tag

Descripción

Estilo orientado a objetos

public XMLWriter::writeComment ( string $content ) : bool

Estilo por procedimientos

xmlwriter_write_comment ( XMLWriter $writer , string $content ) : bool

Writes a full comment.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

content

The contents of the comment.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::endComment() - Create end comment

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD tag

  • « XMLWriter::writeComment
  • XMLWriter::writeDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Write full DTD tag

XMLWriter::writeDtd

xmlwriter_write_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtd -- xmlwriter_write_dtd — Write full DTD tag

Descripción

Estilo orientado a objetos

public XMLWriter::writeDtd ( string $name , string|null $publicId = null , string|null $systemId = null , string|null $content = null ) : bool

Estilo por procedimientos

xmlwriter_write_dtd ( XMLWriter $writer , string $name , string|null $publicId = null , string|null $systemId = null , string|null $content = null ) : bool

Writes a full DTD.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

name

The DTD name.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

content

The content of the DTD.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startDtd() - Create start DTD tag
  • XMLWriter::endDtd() - End current DTD

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD AttList tag

  • « XMLWriter::writeDtd
  • XMLWriter::writeDtdElement »
  • PHP Manual
  • XMLWriter
  • Write full DTD AttList tag

XMLWriter::writeDtdAttlist

xmlwriter_write_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdAttlist -- xmlwriter_write_dtd_attlist — Write full DTD AttList tag

Descripción

Estilo orientado a objetos

public XMLWriter::writeDtdAttlist ( string $name , string $content ) : bool

Estilo por procedimientos

xmlwriter_write_dtd_attlist ( XMLWriter $writer , string $name , string $content ) : bool

Writes a DTD attribute list.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

name

The name of the DTD attribute list.

content

The content of the DTD attribute list.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startDtdAttlist() - Create start DTD AttList
  • XMLWriter::endDtdAttlist() - End current DTD AttList

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD element tag

  • « XMLWriter::writeDtdAttlist
  • XMLWriter::writeDtdEntity »
  • PHP Manual
  • XMLWriter
  • Write full DTD element tag

XMLWriter::writeDtdElement

xmlwriter_write_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdElement -- xmlwriter_write_dtd_element — Write full DTD element tag

Descripción

Estilo orientado a objetos

public XMLWriter::writeDtdElement ( string $name , string $content ) : bool

Estilo por procedimientos

xmlwriter_write_dtd_element ( XMLWriter $writer , string $name , string $content ) : bool

Writes a full DTD element.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

name

The name of the DTD element.

content

The content of the element.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startDtdElement() - Create start DTD element
  • XMLWriter::endDtdElement() - End current DTD element

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD Entity tag

  • « XMLWriter::writeDtdElement
  • XMLWriter::writeElement »
  • PHP Manual
  • XMLWriter
  • Write full DTD Entity tag

XMLWriter::writeDtdEntity

xmlwriter_write_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdEntity -- xmlwriter_write_dtd_entity — Write full DTD Entity tag

Descripción

Estilo orientado a objetos

public XMLWriter::writeDtdEntity ( string $name , string $content , bool $isParam = false , string|null $publicId = null , string|null $systemId = null , string|null $notationData = null ) : bool

Estilo por procedimientos

xmlwriter_write_dtd_entity ( XMLWriter $writer , string $name , string $content , bool $isParam = false , string|null $publicId = null , string|null $systemId = null , string|null $notationData = null ) : bool

Writes a full DTD entity.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

name

The name of the entity.

content

The content of the entity.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.
8.0.0 | publicId, systemId and notationData are nullable now.

Ver también

  • XMLWriter::startDtdEntity() - Create start DTD Entity
  • XMLWriter::endDtdEntity() - End current DTD Entity

User Contributed Notes

There are no user contributed notes for this page.


Write full element tag

  • « XMLWriter::writeDtdEntity
  • XMLWriter::writeElementNs »
  • PHP Manual
  • XMLWriter
  • Write full element tag

XMLWriter::writeElement

xmlwriter_write_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElement -- xmlwriter_write_element — Write full element tag

Descripción

Estilo orientado a objetos

public XMLWriter::writeElement ( string $name , string|null $content = null ) : bool

Estilo por procedimientos

xmlwriter_write_element ( XMLWriter $writer , string $name , string|null $content = null ) : bool

Writes a full element tag.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

name

The element name.

content

The element contents.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNs() - Write full namespaced element tag

User Contributed Notes

There are no user contributed notes for this page.


Write full namespaced element tag

  • « XMLWriter::writeElement
  • XMLWriter::writePi »
  • PHP Manual
  • XMLWriter
  • Write full namespaced element tag

XMLWriter::writeElementNs

xmlwriter_write_element_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElementNs -- xmlwriter_write_element_ns — Write full namespaced element tag

Descripción

Estilo orientado a objetos

public XMLWriter::writeElementNs ( string|null $prefix , string $name , string|null $namespace , string|null $content = null ) : bool

Estilo por procedimientos

xmlwriter_write_element_ns ( XMLWriter $writer , string|null $prefix , string $name , string|null $namespace , string|null $content = null ) : bool

Writes a full namespaced element tag.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The element name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

content

The element contents.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startElementNs() - Create start namespaced element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


Writes a PI

  • « XMLWriter::writeElementNs
  • XMLWriter::writeRaw »
  • PHP Manual
  • XMLWriter
  • Writes a PI

XMLWriter::writePi

xmlwriter_write_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writePi -- xmlwriter_write_pi — Writes a PI

Descripción

Estilo orientado a objetos

public XMLWriter::writePi ( string $target , string $content ) : bool

Estilo por procedimientos

xmlwriter_write_pi ( XMLWriter $writer , string $target , string $content ) : bool

Writes a processing instruction.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

target

The target of the processing instruction.

content

The content of the processing instruction.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::startPi() - Create start PI tag
  • XMLWriter::endPi() - End current PI

User Contributed Notes

There are no user contributed notes for this page.


Write a raw XML text

  • « XMLWriter::writePi
  • XSL »
  • PHP Manual
  • XMLWriter
  • Write a raw XML text

XMLWriter::writeRaw

xmlwriter_write_raw

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4)

XMLWriter::writeRaw -- xmlwriter_write_raw — Write a raw XML text

Descripción

Estilo orientado a objetos

public XMLWriter::writeRaw ( string $content ) : bool

Estilo por procedimientos

xmlwriter_write_raw ( XMLWriter $writer , string $content ) : bool

Writes a raw xml text.

Parámetros

xmlwriter

Sólo para llamadas por procedimientos. El resource XMLWriter que está siendo modificado. Este recurso proviene de una llamada a xmlwriter_open_uri() o xmlwriter_open_memory().

content

The text string to write.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | writer expects an XMLWriter instance now; previously, a resource was expected.

Ver también

  • XMLWriter::text() - Write text

User Contributed Notes

There are no user contributed notes for this page.


XSL

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
    • Configuración en tiempo de ejecución
    • Tipos de recursos
  • Constantes predefinidas
  • Ejemplos
    • Ficheros collection.xml y collection.xsl de ejemplo
    • Manejo de errores con las funciones de manejo de errores de libxml
  • XSLTProcessor — Clase XSLTProcessor
    • XSLTProcessor::__construct — Crea un nuevo objeto XSLTProcessor
    • XSLTProcessor::getParameter — Obtiene el valor de un parámetro
    • XSLTProcessor::getSecurityPrefs — Obtiene las preferencias de seguridad
    • XSLTProcessor::hasExsltSupport — Determina si PHP tiene soporte para EXSLT
    • XSLTProcessor::importStylesheet — Importa una hoja de estilos
    • XSLTProcessor::registerPHPFunctions — Activa la capacidad de usar funciones PHP como funciones XSLT
    • XSLTProcessor::removeParameter — Elimina un parámetro
    • XSLTProcessor::setParameter — Establece el valor para uno o varios parámetros
    • XSLTProcessor::setProfiling — Establece el fichero de salida para la información resultado del proceso
    • XSLTProcessor::setSecurityPrefs — Establece las preferencias de seguridad
    • XSLTProcessor::transformToDoc — Transforma en un DOMDocument
    • XSLTProcessor::transformToUri — Transformar a URI
    • XSLTProcessor::transformToXml — Transforma a 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));
?>


Introducción

La extensión XSL implementa el estándar XSL, realizando » transformaciones XSLT usando la » biblioteca libxslt

User Contributed Notes

There are no user contributed notes for this page.


Requerimientos

Esta extensión requiere la extensión libxml de PHP. Esto significa que también es necesario pasar la opción --enable-libxml, aunque esto se realiza implícitamente debido a que libxml está habilitada de forma predeterminada.

Esta extensión usa libxslt disponible en » http://xmlsoft.org/XSLT/. Se requiere una versión de libxslt 1.1.0 o superior.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

PHP 5 incluye la extensión XSL por defecto y puede ser activada añadiendo el argumento --with-xsl[=DIR] en la línea de configuración. DIR es el directorio de instalación de libxslt.

User Contributed Notes

There are no user contributed notes for this page.


Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles sólo cuando la extensión haya sido compilada con PHP, o bien sea cargada dinámicamente en ejecución.

XSL_CLONE_AUTO (integer)
XSL_CLONE_NEVER (integer)
XSL_CLONE_ALWAYS (integer)
LIBXSLT_VERSION (integer)
versión libxslt como 10117. Disponible a partir de PHP 5.1.2.
LIBXSLT_DOTTED_VERSION (string)
versión de libxslt como la 1.1.17. Disponible a partir de PHP 5.1.2.
LIBEXSLT_VERSION (integer)
versión de libexslt como la 813. Disponible a partir de PHP 5.1.2.
LIBEXSLT_DOTTED_VERSION (string)
versión de libexslt como la 1.1.17. Disponible a partir de PHP 5.1.2.
XSL_SECPREF_NONE (integer)
Desactivar todas las restricciones de seguridad.
XSL_SECPREF_READ_FILE (integer)
Deshabilita la lectura de archivos.
XSL_SECPREF_WRITE_FILE (integer)
Deshabilita la escritura de archivos.
XSL_SECPREF_CREATE_DIRECTORY (integer)
No permite crear directorios.
XSL_SECPREF_READ_NETWORK (integer)
No permite leer los archivos de la red.
XSL_SECPREF_WRITE_NETWORK (integer)
Deshabilita la escritura de archivos de red.
XSL_SECPREF_DEFAULT (integer)
Deshabilita todo acceso de escritura, es decir, una máscara de bits de XSL_SECPREF_WRITE_NETWORK | XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE.

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

Tabla de contenidos

  • Ficheros collection.xml y collection.xsl de ejemplo
  • Manejo de errores con las funciones de manejo de errores de libxml

User Contributed Notes

There are no user contributed notes for this page.


Ficheros collection.xml y collection.xsl de ejemplo

Muchos ejemplos en esta referencia requieren tanto un fichero XML como un XSL. Se usará collection.xml y collection.xsl que contienen el siguiente código:

Ejemplo #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>

Ejemplo #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.


Manejo de errores con las funciones de manejo de errores de libxml

libxml ofrece una serie de funciones para el manejo de errores, que pueden ser empleadas para capturar y tratar los errores en el procesamiento de XSLT.

Ejemplo #1 fruits.xml

Un archivo XML válido.

<fruits>
 <fruit>Apple</fruit>
 <fruit>Banana</fruit>
 <fruit>Cherry</fruit>
</fruits>

Ejemplo #2 fruits.xsl

Contiene una expresión selectiva no válida.

<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>

Ejemplo #3 Errores de compaginación e impresión

El siguiente ejemplo captura y muestra los errores de libxml que se producen al llamar a XSLTProcessor::importStyleSheet() on una hoja de estilo que contiene un error.

<?php

$xmldoc = new DOMDocument();
$xsldoc = new DOMDocument();
$xsl = new XSLTProcessor();

$xmldoc->loadXML('fruits.xml');
$xsldoc->loadXML('fruits.xsl');

libxml_use_internal_errors(true);
$result = $xsl->importStyleSheet($xsldoc);
if (!$result) {
    foreach (libxml_get_errors() as $error) {
        echo "Libxml error: {$error->message}\n";
    }
}
libxml_use_internal_errors(false);

if ($result) {
    echo $xsl->transformToXML($xmldoc);
}

?>

El resultado del ejemplo sería algo similar a:

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.


Clase XSLTProcessor

(PHP 5, PHP 7, PHP 8)

Introducción

Sinopsis de la Clase

XSLTProcessor {
/* Métodos */
getParameter ( string $namespaceURI , string $localName ) : string
public getSecurityPrefs ( ) : int
hasExsltSupport ( ) : bool
public importStylesheet ( object $stylesheet ) : bool
registerPHPFunctions ( mixed $restrict = ? ) : void
removeParameter ( string $namespaceURI , string $localName ) : bool
setParameter ( string $namespace , string $name , string $value ) : bool
setProfiling ( string $filename ) : bool
public setSecurityPrefs ( int $securityPrefs ) : int
transformToDoc ( DOMNode $doc ) : DOMDocument
transformToURI ( DOMDocument $doc , string $uri ) : int
transformToXml ( object $doc ) : string
}

Tabla de contenidos

  • XSLTProcessor::__construct — Crea un nuevo objeto XSLTProcessor
  • XSLTProcessor::getParameter — Obtiene el valor de un parámetro
  • XSLTProcessor::getSecurityPrefs — Obtiene las preferencias de seguridad
  • XSLTProcessor::hasExsltSupport — Determina si PHP tiene soporte para EXSLT
  • XSLTProcessor::importStylesheet — Importa una hoja de estilos
  • XSLTProcessor::registerPHPFunctions — Activa la capacidad de usar funciones PHP como funciones XSLT
  • XSLTProcessor::removeParameter — Elimina un parámetro
  • XSLTProcessor::setParameter — Establece el valor para uno o varios parámetros
  • XSLTProcessor::setProfiling — Establece el fichero de salida para la información resultado del proceso
  • XSLTProcessor::setSecurityPrefs — Establece las preferencias de seguridad
  • XSLTProcessor::transformToDoc — Transforma en un DOMDocument
  • XSLTProcessor::transformToUri — Transformar a URI
  • XSLTProcessor::transformToXml — Transforma a 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


Crea un nuevo objeto XSLTProcessor

  • « XSLTProcessor
  • XSLTProcessor::getParameter »
  • PHP Manual
  • XSLTProcessor
  • Crea un nuevo objeto XSLTProcessor

XSLTProcessor::__construct

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::__construct — Crea un nuevo objeto XSLTProcessor

Descripción

XSLTProcessor::__construct ( )

Crea un nuevo objeto XSLTProcessor.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Creando un 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.


Obtiene el valor de un parámetro

  • « XSLTProcessor::__construct
  • XSLTProcessor::getSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Obtiene el valor de un parámetro

XSLTProcessor::getParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::getParameter — Obtiene el valor de un parámetro

Descripción

XSLTProcessor::getParameter ( string $namespaceURI , string $localName ) : string

Obtiene un parámetro si ha sido previamente establecido por XSLTProcessor::setParameter().

Parámetros

namespaceURI

La URI del namespace del parámetro XSLT.

localName

El nombre local del parámetro XSLT.

Valores devueltos

El valor del parámetro (como un string), o false si no está definido.

Ver también

  • XSLTProcessor::setParameter() - Establece el valor para uno o varios parámetros
  • XSLTProcessor::removeParameter() - Elimina un parámetro

User Contributed Notes

There are no user contributed notes for this page.


Obtiene las preferencias de seguridad

  • « XSLTProcessor::getParameter
  • XSLTProcessor::hasExsltSupport »
  • PHP Manual
  • XSLTProcessor
  • Obtiene las preferencias de seguridad

XSLTProcessor::getSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::getSecurityPrefs — Obtiene las preferencias de seguridad

Descripción

public XSLTProcessor::getSecurityPrefs ( ) : int

Obtiene las preferencias de seguridad.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

A bitmask consisting of XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK.

User Contributed Notes

There are no user contributed notes for this page.


Determina si PHP tiene soporte para EXSLT

  • « XSLTProcessor::getSecurityPrefs
  • XSLTProcessor::importStylesheet »
  • PHP Manual
  • XSLTProcessor
  • Determina si PHP tiene soporte para EXSLT

XSLTProcessor::hasExsltSupport

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

XSLTProcessor::hasExsltSupport — Determina si PHP tiene soporte para EXSLT

Descripción

XSLTProcessor::hasExsltSupport ( ) : bool

Este método determina si PHP se compiló con la » librería EXSLT.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Comprobando si tiene EXSLT

<?php

$proc = new XSLTProcessor;
if (!$proc->hasExsltSupport()) {
    die('EXSLT no disponible');
}

// aquí las líneas de código con EXSLT..

?>

User Contributed Notes

There are no user contributed notes for this page.


Importa una hoja de estilos

  • « XSLTProcessor::hasExsltSupport
  • XSLTProcessor::registerPHPFunctions »
  • PHP Manual
  • XSLTProcessor
  • Importa una hoja de estilos

XSLTProcessor::importStylesheet

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::importStylesheet — Importa una hoja de estilos

Descripción

public XSLTProcessor::importStylesheet ( object $stylesheet ) : bool

Este método importa la hoja de estilos a XSLTProcessor para realizar transformaciones.

Parámetros

stylesheet

La hoja de estilos importada como objeto DOMDocument o SimpleXMLElement.

Valores devueltos

No devuelve ningún valor.

Historial de cambios

Versión | Descripción
5.2.8 | Acepta SimpleXMLElement de nuevo; no funcionaba desde PHP 5.2.6.

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!


Activa la capacidad de usar funciones PHP como funciones XSLT

  • « XSLTProcessor::importStylesheet
  • XSLTProcessor::removeParameter »
  • PHP Manual
  • XSLTProcessor
  • Activa la capacidad de usar funciones PHP como funciones XSLT

XSLTProcessor::registerPHPFunctions

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

XSLTProcessor::registerPHPFunctions — Activa la capacidad de usar funciones PHP como funciones XSLT

Descripción

XSLTProcessor::registerPHPFunctions ( mixed $restrict = ? ) : void

Este método activa la capacidad de usar funciones PHP como funciones XSLT dentro de las hojas de estilo XSL.

Parámetros

restrict

Usar este parámetro para acceder únicamente a ciertas funciones a ser llamadas desde XSLT.

Este parámetro puede ser tanto un string (nombre de la función) como un array de funciones.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Sencilla llamada a una función de PHP desde una hoja de estilos

<?php
$xml = <<<EOB
<allusers>
 <user>
  <uid>bob</uid>
 </user>
 <user>
  <uid>joe</uid>
 </user>
</allusers>
EOB;
$xsl = <<<EOB
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:php="http://php.net/xsl">
<xsl:output method="html" encoding="utf-8" indent="yes"/>
 <xsl:template match="allusers">
  <html><body>
    <h2>Users</h2>
    <table>
    <xsl:for-each select="user">
      <tr><td>
        <xsl:value-of
             select="php:function('ucfirst',string(uid))"/>
      </td></tr>
    </xsl:for-each>
    </table>
  </body></html>
 </xsl:template>
</xsl:stylesheet>
EOB;
$xmldoc = DOMDocument::loadXML($xml);
$xsldoc = DOMDocument::loadXML($xsl);

$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML($xmldoc);
?>

Historial de cambios

Versión | Descripción
5.1.0 | Se añadió el parámetro restrict.

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


Elimina un parámetro

  • « XSLTProcessor::registerPHPFunctions
  • XSLTProcessor::setParameter »
  • PHP Manual
  • XSLTProcessor
  • Elimina un parámetro

XSLTProcessor::removeParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::removeParameter — Elimina un parámetro

Descripción

XSLTProcessor::removeParameter ( string $namespaceURI , string $localName ) : bool

Elimina un parámetro, si ya existía. Esto hará que el procesador use el valor por defecto para el parámetro como está especificado en la hoja de estilos.

Parámetros

namespaceURI

La URI del namespace para el parámetro XSLT.

localName

Nombre local del parámetro XSLT.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XSLTProcessor::setParameter() - Establece el valor para uno o varios parámetros
  • XSLTProcessor::getParameter() - Obtiene el valor de un parámetro

User Contributed Notes

There are no user contributed notes for this page.


Establece el valor para uno o varios parámetros

  • « XSLTProcessor::removeParameter
  • XSLTProcessor::setProfiling »
  • PHP Manual
  • XSLTProcessor
  • Establece el valor para uno o varios parámetros

XSLTProcessor::setParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::setParameter — Establece el valor para uno o varios parámetros

Descripción

XSLTProcessor::setParameter ( string $namespace , string $name , string $value ) : bool
XSLTProcessor::setParameter ( string $namespace , array $options ) : bool

Establece el valor para uno o más parámetros a ser usado en las siguientes transformaciones con XSLTProcessor. Si el parámetro no existe en la hoja de estilos, será ignorado.

Parámetros

namespace

La URI para el namespace del parámetro XSLT.

name

Nombre local del parámetro XSLT.

value

Nuevo valor para el parámetro XSLT.

options

Un array de parejas nombre => valor. Esta sintaxis está disponible desde PHP 5.1.0.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Changing the owner before the transformation

<?php

$collections = array(
    'Marc Rutkowski' => 'marc',
    'Olivier Parmentier' => 'olivier'
);

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configuración del procesador
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // asociamos las reglas xsl

foreach ($collections as $name => $file) {
    // Cargamos el XML origen
    $xml = new DOMDocument;
    $xml->load('collection_' . $file . '.xml');

    $proc->setParameter('', 'owner', $name);
    $proc->transformToURI($xml, 'file:///tmp/' . $file . '.html');
}

?>

Ver también

  • XSLTProcessor::getParameter() - Obtiene el valor de un parámetro
  • XSLTProcessor::removeParameter() - Elimina un parámetro

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.


Establece el fichero de salida para la información resultado del proceso

  • « XSLTProcessor::setParameter
  • XSLTProcessor::setSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Establece el fichero de salida para la información resultado del proceso

XSLTProcessor::setProfiling

(PHP >= 5.3.0, PHP 7, PHP 8)

XSLTProcessor::setProfiling — Establece el fichero de salida para la información resultado del proceso

Descripción

XSLTProcessor::setProfiling ( string $filename ) : bool

Establece el nombre del fichero de salida para la información generada del propio procesado de la hoja de estilos.

Parámetros

filename

Ruta al fichero donde volcar la información.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo de salida de información

<?php
// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configuración del procesador
$proc = new XSLTProcessor;
$proc->setProfiling('profiling.txt');
$proc->importStyleSheet($xsl); // adjunta las reglas xsl

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);
?>

Este código generará la siguiente información en el fichero profiling.txt:

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.


Establece las preferencias de seguridad

  • « XSLTProcessor::setProfiling
  • XSLTProcessor::transformToDoc »
  • PHP Manual
  • XSLTProcessor
  • Establece las preferencias de seguridad

XSLTProcessor::setSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::setSecurityPrefs — Establece las preferencias de seguridad

Descripción

public XSLTProcessor::setSecurityPrefs ( int $securityPrefs ) : int

Establece las preferencias de seguridad.

Parámetros

securityPrefs

Las nuevas preferencias de seguridad. Las siguientes constantes pueden ser ORed: XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK. Alternativamente, XSL_SECPREF_NONE o se puede pasar XSL_SECPREF_DEFAULT.

Valores devueltos

Devuelve las antiguas preferencias de seguridad.

User Contributed Notes

There are no user contributed notes for this page.


Transforma en un DOMDocument

  • « XSLTProcessor::setSecurityPrefs
  • XSLTProcessor::transformToUri »
  • PHP Manual
  • XSLTProcessor
  • Transforma en un DOMDocument

XSLTProcessor::transformToDoc

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToDoc — Transforma en un DOMDocument

Descripción

XSLTProcessor::transformToDoc ( DOMNode $doc ) : DOMDocument

Transforma el nodo origen en un DOMDocument aplicando las hojas de estilo dadas por el método XSLTProcessor::importStylesheet().

Parámetros

doc

El nodo a transformar.

Valores devueltos

El DOMDocument resultante o false en caso de error.

Ejemplos

Ejemplo #1 Transformando en un DOMDocument

<?php

// Carga del fichero origen XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configuración del procesador
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // adjunta las reglas xsl

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

El resultado del ejemplo sería:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

Ver también

  • XSLTProcessor::transformToUri() - Transformar a URI
  • XSLTProcessor::transformToXml() - Transforma a 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.


Transformar a URI

  • « XSLTProcessor::transformToDoc
  • XSLTProcessor::transformToXml »
  • PHP Manual
  • XSLTProcessor
  • Transformar a URI

XSLTProcessor::transformToUri

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToUri — Transformar a URI

Descripción

XSLTProcessor::transformToURI ( DOMDocument $doc , string $uri ) : int

Transforma el nodo origen a una URI aplicando la hoja de estilos dada por el metodo XSLTProcessor::importStylesheet().

Parámetros

doc

El documento a transformar.

uri

Devuelve la ubicación URI para la transformación.

Valores devueltos

Retorna el número de bytes escritos o false en caso de error.

Ejemplos

Ejemplo #1 Transformando a un fichero HTML

<?php

// Carga el fichero XML origen
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configura el procesador
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // adjunta las reglas xsl

$proc->transformToURI($xml, 'file:///tmp/out.html');

?>

Ver también

  • XSLTProcessor::transformToDoc() - Transforma en un DOMDocument
  • XSLTProcessor::transformToXml() - Transforma a 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();
?>


Transforma a XML

  • « XSLTProcessor::transformToUri
  • Extensiones de GUI »
  • PHP Manual
  • XSLTProcessor
  • Transforma a XML

XSLTProcessor::transformToXml

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToXml — Transforma a XML

Descripción

XSLTProcessor::transformToXml ( object $doc ) : string

Transforma el nodo origen a un string aplicando la hoja de estilos dada por el método xsltprocessor::importStylesheet().

Parámetros

doc

El objeto DOMDocument o SimpleXMLElement para ser transformado.

Valores devueltos

Resultado de la transformación a string o false en caso de error.

Ejemplos

Ejemplo #1 Transformando a un string

<?php

// Carga el fichero XML origen
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configura el procesador
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // adjunta las reglas XSL

echo $proc->transformToXML($xml);

?>

El resultado del ejemplo sería:

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>

Ver también

  • XSLTProcessor::transformToDoc() - Transforma en un DOMDocument
  • XSLTProcessor::transformToUri() - Transformar a 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.


Extensiones de GUI

  • UI
    • Introducción
    • Instalación/Configuración
    • UI\Point — Represents a position (x,y)
    • UI\Size — Represents dimenstions (width, height)
    • UI\Window — Window
    • UI\Control — Control
    • UI\Menu — Menu
    • UI\MenuItem — Menu Item
    • UI\Area — Area
    • UI\Executor — Execution Scheduler
    • UI\Controls\Tab — Tab Control
    • UI\Controls\Check — Check Control
    • UI\Controls\Button — Button Control
    • UI\Controls\ColorButton — ColorButton Control
    • UI\Controls\Label — Label Control
    • UI\Controls\Entry — Entry Control
    • UI\Controls\MultilineEntry — MultilineEntry Control
    • UI\Controls\Spin — Spin Control
    • UI\Controls\Slider — Slider Control
    • UI\Controls\Progress — Progress Control
    • UI\Controls\Separator — Control Separator
    • UI\Controls\Combo — Combo Control
    • UI\Controls\EditableCombo — EdiableCombo Control
    • UI\Controls\Radio — Radio Control
    • UI\Controls\Picker — Picker Control
    • UI\Controls\Form — Control Form (Arrangement)
    • UI\Controls\Grid — Control Grid (Arrangement)
    • UI\Controls\Group — Control Group (Arrangement)
    • UI\Controls\Box — Control Box (Arrangement)
    • UI\Draw\Pen — Draw Pen
    • UI\Draw\Path — Draw Path
    • UI\Draw\Matrix — Draw Matrix
    • UI\Draw\Color — Color Representation
    • UI\Draw\Stroke — Draw Stroke
    • UI\Draw\Brush — Brushes
    • UI\Draw\Brush\Gradient — Gradient Brushes
    • UI\Draw\Brush\LinearGradient — Linear Gradient
    • UI\Draw\Brush\RadialGradient — Radial Gradient
    • UI\Draw\Text\Layout — Represents Text Layout
    • UI\Draw\Text\Font — Represents a Font
    • UI\Draw\Text\Font\Descriptor — Font Descriptor
    • UI Funciones
    • 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

  • Introducción
  • Instalación/Configuración
    • Requerimientos
    • Instalación
  • UI\Point — Represents a position (x,y)
    • UI\Point::at — Tamaño de coerción
    • UI\Point::__construct — Construye un nuevo punto
    • UI\Point::getX — Recupera X
    • UI\Point::getY — Recupera Y
    • UI\Point::setX — Establece X
    • UI\Point::setY — Establece Y
  • UI\Size — Represents dimenstions (width, height)
    • UI\Size::__construct — Construye un nuevo tamaño
    • UI\Size::getHeight — Recupera la altura
    • UI\Size::getWidth — Recupera el ancho
    • UI\Size::of — Punto de coerción
    • UI\Size::setHeight — Establece la altura
    • UI\Size::setWidth — Establece el ancho
  • UI\Window — Window
    • UI\Window::add — Añade un control
    • UI\Window::__construct — Construye una nueva ventana
    • UI\Window::error — Mostrar cuadro de error
    • UI\Window::getSize — Obtiene el tamaño de la ventana
    • UI\Window::getTitle — Obtiene el título
    • UI\Window::hasBorders — Detección del Borde
    • UI\Window::hasMargin — Detección de Margen
    • UI\Window::isFullScreen — Detección de pantalla completa
    • UI\Window::msg — Mostrar Cuadro de Mensajes
    • UI\Window::onClosing — Cierre de la devolución de llamada
    • UI\Window::open — Abrir Diálogo
    • UI\Window::save — Guarda Diálogo
    • UI\Window::setBorders — Uso de Bordes
    • UI\Window::setFullScreen — Uso de la pantalla completa
    • UI\Window::setMargin — Uso del Margen
    • UI\Window::setSize — Establece Tamaño
    • UI\Window::setTitle — Título de la Vetana
  • 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 — Añade elemento de menú
    • UI\Menu::appendAbout — Añade elemento de menú Acerca de
    • UI\Menu::appendCheck — Añade un elemento de menú comprobable
    • UI\Menu::appendPreferences — Añade elemento de menú de preferencias
    • UI\Menu::appendQuit — Añade elemento de menú salir
    • UI\Menu::appendSeparator — Añade separador de elementos del menú
    • UI\Menu::__construct — Construye un nuevo menú
  • UI\MenuItem — Menu Item
    • UI\MenuItem::disable — Desactiva elemento del menú
    • UI\MenuItem::enable — Activa elemento de menú
    • UI\MenuItem::isChecked — Detecta Marcado
    • UI\MenuItem::onClick — Llamada de retorno On Click
    • UI\MenuItem::setChecked — Establece marcado
  • 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 — Llena una ruta
    • UI\Draw\Pen::restore — Restaura
    • UI\Draw\Pen::save — Guarda
    • UI\Draw\Pen::stroke — Traza una ruta
    • UI\Draw\Pen::transform — Transformación de la matriz
    • UI\Draw\Pen::write — Dibuja el texto en el punto
  • UI\Draw\Path — Draw Path
    • UI\Draw\Path::addRectangle — Dibuja un rectángulo
    • UI\Draw\Path::arcTo — Dibuja un arco
    • UI\Draw\Path::bezierTo — Draw Bezier Curve
    • UI\Draw\Path::closeFigure — Cerrar Figura
    • UI\Draw\Path::__construct — Construye una nueva ruta
    • UI\Draw\Path::end — Finalizar Ruta
    • UI\Draw\Path::lineTo — Dibuja una línea
    • UI\Draw\Path::newFigure — Dibuja figura
    • UI\Draw\Path::newFigureWithArc — Dibuja figura con arco
  • UI\Draw\Matrix — Draw Matrix
    • UI\Draw\Matrix::invert — Invertir matriz
    • UI\Draw\Matrix::isInvertible — Detección de invertido
    • UI\Draw\Matrix::multiply — Multiplica la matriz
    • UI\Draw\Matrix::rotate — Rota la matriz
    • UI\Draw\Matrix::scale — Escala la Matriz
    • UI\Draw\Matrix::skew — Inclina la Matriz
    • UI\Draw\Matrix::translate — Traduce la matriz
  • UI\Draw\Color — Color Representation
    • UI\Draw\Color::__construct — Construye un nuevo color
    • UI\Draw\Color::getChannel — Manipulación de color
    • UI\Draw\Color::setChannel — Manipulación de color
  • UI\Draw\Stroke — Draw Stroke
    • UI\Draw\Stroke::__construct — Construye un nuevo trazo
    • UI\Draw\Stroke::getCap — Get Line Cap
    • UI\Draw\Stroke::getJoin — Obtiene la unión de línea
    • UI\Draw\Stroke::getMiterLimit — Obtiene el límite de inglete
    • UI\Draw\Stroke::getThickness — Obtiene el grosor
    • UI\Draw\Stroke::setCap — Set Line Cap
    • UI\Draw\Stroke::setJoin — Establece la línea de unión
    • UI\Draw\Stroke::setMiterLimit — Establece el límite de ingletes
    • UI\Draw\Stroke::setThickness — Establece el grosor
  • 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 — Construir un nuevo diseño de texto
    • UI\Draw\Text\Layout::setColor — Establece el color
    • UI\Draw\Text\Layout::setWidth — Establece el ancho
  • UI\Draw\Text\Font — Represents a Font
    • UI\Draw\Text\Font::__construct — Construye una nueva fuente
    • UI\Draw\Text\Font::getAscent — Métricas de la fuente
    • UI\Draw\Text\Font::getDescent — Métricas de la fuente
    • UI\Draw\Text\Font::getLeading — Métricas de la fuente
    • UI\Draw\Text\Font::getUnderlinePosition — Métricas de la fuente
    • UI\Draw\Text\Font::getUnderlineThickness — Métricas de la fuente
  • 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 Funciones
    • UI\Draw\Text\Font\fontFamilies — Recuperar las familias de fuentes
    • UI\quit — Quit UI Loop
    • UI\run — Enter UI Loop
  • UI\Draw\Text\Font\Weight — Font Weight Settings
  • UI\Draw\Text\Font\Italic — Italic Font Settings
  • UI\Draw\Text\Font\Stretch — Font Stretch Settings
  • UI\Draw\Line\Cap — Line Cap Settings
  • UI\Draw\Line\Join — Line Join Settings
  • UI\Key — Key Identifiers
  • UI\Exception\InvalidArgumentException — InvalidArgumentException
  • UI\Exception\RuntimeException — RuntimeException

User Contributed Notes

There are no user contributed notes for this page.


Introducción

This extension wraps libui to provide an OO API for the cross platform development of native look-and-feel user interfaces .

User Contributed Notes

There are no user contributed notes for this page.


Instalación/Configuración

Tabla de contenidos

  • Requerimientos
  • Instalación

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


Requerimientos

Installation requires the libui library, and PHP 7 or newer.

This extension requires the » libui library version 0.1.0 or higher to be installed. See the libui documentation for a list of prerequisites.

User Contributed Notes

There are no user contributed notes for this page.


Instalación

Esta extensión » PECL no se distribuye con PHP.

Se puede encontrar información para la instalación de esta extensión PECL en el capítulo del manual titulado Instalación de extensiones PECL. Se puede encontrar información adicional, tal como nuevos lanzamientos, descargas, ficheros fuente, información de mantenimiento, y un CHANGELOG, aquí: » https://pecl.php.net/package/ui.

Los binarios de Windows (ficheros DLL) para esta extensión de PECL están disponibles en el sitio web de PECL.

User Contributed Notes

There are no user contributed notes for this page.


Represents a position (x,y)

(UI 0.9.9)

Introducción

Points are used throughout UI to represent co-ordinates on a screen, control, or area.

Sinopsis de la Clase

final UI\Point {
/* Propiedades */
public $x ;
public $y ;
/* Constructor */
public __construct ( float $x , float $y )
/* Métodos */
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 )
}

Propiedades

x

Holds the X co-ordinate, can be read/written directly

y

Holds the Y co-ordinate, can be read/written directly

Tabla de contenidos

  • UI\Point::at — Tamaño de coerción
  • UI\Point::__construct — Construye un nuevo punto
  • UI\Point::getX — Recupera X
  • UI\Point::getY — Recupera Y
  • UI\Point::setX — Establece X
  • UI\Point::setY — Establece Y

User Contributed Notes

There are no user contributed notes for this page.


Tamaño de coerción

  • « UI\Point
  • UI\Point::__construct »
  • PHP Manual
  • UI\Point
  • Tamaño de coerción

UI\Point::at

(UI 1.0.2)

UI\Point::at — Tamaño de coerción

Descripción

public static UI\Point::at ( float $point ) : UI\Point
public static UI\Point::at ( UI\Size $size ) : UI\Point

Devolverá un objeto de punto UI donde x y y son iguales a los suministrados, ya sea en forma flotante o de tamaño UI.

Parámetros

point

El valor de x y y

size

El tamaño a convertir

Valores devueltos

El punto resultante

User Contributed Notes

There are no user contributed notes for this page.


Construye un nuevo punto

  • « UI\Point::at
  • UI\Point::getX »
  • PHP Manual
  • UI\Point
  • Construye un nuevo punto

UI\Point::__construct

(UI 0.9.9)

UI\Point::__construct — Construye un nuevo punto

Descripción

public UI\Point::__construct ( float $x , float $y )

Construye un nuevo punto usando nuevas coordenadas

Parámetros

x

La nueva coordenada X

y

La nueva coordenada Y

User Contributed Notes

There are no user contributed notes for this page.


Recupera X

  • « UI\Point::__construct
  • UI\Point::getY »
  • PHP Manual
  • UI\Point
  • Recupera X

UI\Point::getX

(UI 0.9.9)

UI\Point::getX — Recupera X

Descripción

public UI\Point::getX ( ) : float

Recupera la coordenada X

Parámetros

Esta función no tiene parámetros.

Valores devueltos

La coordenada X actual

User Contributed Notes

There are no user contributed notes for this page.


Recupera Y

  • « UI\Point::getX
  • UI\Point::setX »
  • PHP Manual
  • UI\Point
  • Recupera Y

UI\Point::getY

(UI 0.9.9)

UI\Point::getY — Recupera Y

Descripción

public UI\Point::getY ( ) : float

Recupera la coordenada Y

Parámetros

Esta función no tiene parámetros.

Valores devueltos

La coordenada Y actual

User Contributed Notes

There are no user contributed notes for this page.


Establece X

  • « UI\Point::getY
  • UI\Point::setY »
  • PHP Manual
  • UI\Point
  • Establece X

UI\Point::setX

(UI 0.9.9)

UI\Point::setX — Establece X

Descripción

public UI\Point::setX ( float $point )

Establece la coordenada X

Parámetros

point

La nueva coordenada X

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Establece Y

  • « UI\Point::setX
  • UI\Size »
  • PHP Manual
  • UI\Point
  • Establece Y

UI\Point::setY

(UI 0.9.9)

UI\Point::setY — Establece Y

Descripción

public UI\Point::setY ( float $point )

Establece la coordenada Y

Parámetros

point

La nueva coordenada Y

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Represents dimenstions (width, height)

(UI 0.9.9)

Introducción

Sizes are used throughout UI to represent the size of a screen, control, or area.

Sinopsis de la Clase

final UI\Size {
/* Propiedades */
public $width ;
public $height ;
/* Constructor */
public __construct ( float $width , float $height )
/* Métodos */
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 )
}

Propiedades

width

Holds the width, can be read/written directly

height

Holds the height, can be read/written directly

Tabla de contenidos

  • UI\Size::__construct — Construye un nuevo tamaño
  • UI\Size::getHeight — Recupera la altura
  • UI\Size::getWidth — Recupera el ancho
  • UI\Size::of — Punto de coerción
  • UI\Size::setHeight — Establece la altura
  • UI\Size::setWidth — Establece el ancho

User Contributed Notes

There are no user contributed notes for this page.


Construye un nuevo tamaño

  • « UI\Size
  • UI\Size::getHeight »
  • PHP Manual
  • UI\Size
  • Construye un nuevo tamaño

UI\Size::__construct

(UI 0.9.9)

UI\Size::__construct — Construye un nuevo tamaño

Descripción

public UI\Size::__construct ( float $width , float $height )

Construye un nuevo tamaño usando un nuevo ancho y alto

Parámetros

width

El nuevo ancho

height

El nuevo alto

User Contributed Notes

There are no user contributed notes for this page.


Recupera la altura

  • « UI\Size::__construct
  • UI\Size::getWidth »
  • PHP Manual
  • UI\Size
  • Recupera la altura

UI\Size::getHeight

(UI 0.9.9)

UI\Size::getHeight — Recupera la altura

Descripción

public UI\Size::getHeight ( ) : float

Recupera la altura

Parámetros

Esta función no tiene parámetros.

Valores devueltos

La altura actual

User Contributed Notes

There are no user contributed notes for this page.


Recupera el ancho

  • « UI\Size::getHeight
  • UI\Size::of »
  • PHP Manual
  • UI\Size
  • Recupera el ancho

UI\Size::getWidth

(UI 0.9.9)

UI\Size::getWidth — Recupera el ancho

Descripción

public UI\Size::getWidth ( ) : float

Recupera el ancho

Parámetros

Esta función no tiene parámetros.

Valores devueltos

El ancho actual

User Contributed Notes

There are no user contributed notes for this page.


Punto de coerción

  • « UI\Size::getWidth
  • UI\Size::setHeight »
  • PHP Manual
  • UI\Size
  • Punto de coerción

UI\Size::of

(UI 1.0.2)

UI\Size::of — Punto de coerción

Descripción

public static UI\Size::of ( float $size ) : UI\Size
public static UI\Size::of ( UI\Point $point ) : UI\Size

Devolverá un objeto de tamaño UI en el que el ancho y la altura son iguales a los suministrados, ya sea en forma flotante o en forma de UI.

Parámetros

size

El valor de la anchura y la altura

point

El punto a convertir

Valores devueltos

El tamaño resultante

User Contributed Notes

There are no user contributed notes for this page.


Establece la altura

  • « UI\Size::of
  • UI\Size::setWidth »
  • PHP Manual
  • UI\Size
  • Establece la altura

UI\Size::setHeight

(UI 0.9.9)

UI\Size::setHeight — Establece la altura

Descripción

public UI\Size::setHeight ( float $size )

Establece una nueva altura

Parámetros

size

La nueva altura

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Establece el ancho

  • « UI\Size::setHeight
  • UI\Window »
  • PHP Manual
  • UI\Size
  • Establece el ancho

UI\Size::setWidth

(UI 0.9.9)

UI\Size::setWidth — Establece el ancho

Descripción

public UI\Size::setWidth ( float $size )

Establece un nuevo ancho

Parámetros

size

El nuevo ancho

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Window

(UI 0.9.9)

Introducción

Represents a UI Window

Sinopsis de la Clase

UI\Window extends UI\Control {
/* Propiedades */
protected $controls ;
/* Constructor */
public __construct ( string $title , Size $size , bool $menu = false )
/* Métodos */
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étodos heredados */
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 ( )
}

Propiedades

controls

Contains controls, should not be manipulated directly

Tabla de contenidos

  • UI\Window::add — Añade un control
  • UI\Window::__construct — Construye una nueva ventana
  • UI\Window::error — Mostrar cuadro de error
  • UI\Window::getSize — Obtiene el tamaño de la ventana
  • UI\Window::getTitle — Obtiene el título
  • UI\Window::hasBorders — Detección del Borde
  • UI\Window::hasMargin — Detección de Margen
  • UI\Window::isFullScreen — Detección de pantalla completa
  • UI\Window::msg — Mostrar Cuadro de Mensajes
  • UI\Window::onClosing — Cierre de la devolución de llamada
  • UI\Window::open — Abrir Diálogo
  • UI\Window::save — Guarda Diálogo
  • UI\Window::setBorders — Uso de Bordes
  • UI\Window::setFullScreen — Uso de la pantalla completa
  • UI\Window::setMargin — Uso del Margen
  • UI\Window::setSize — Establece Tamaño
  • UI\Window::setTitle — Título de la Vetana

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();

?>


Añade un control

  • « UI\Window
  • UI\Window::__construct »
  • PHP Manual
  • UI\Window
  • Añade un control

UI\Window::add

(UI 0.9.9)

UI\Window::add — Añade un control

Descripción

public UI\Window::add ( UI\Control $control )

Añadirá un control a esta ventana

Parámetros

control

El control a añadir

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Construye una nueva ventana

  • « UI\Window::add
  • UI\Window::error »
  • PHP Manual
  • UI\Window
  • Construye una nueva ventana

UI\Window::__construct

(UI 0.9.9)

UI\Window::__construct — Construye una nueva ventana

Descripción

public UI\Window::__construct ( string $title , Size $size , bool $menu = false )

Construirá una nueva ventana

Parámetros

title

El título de la Ventana

size

El tamaño de la Ventana

menu

Interruptor del menú

User Contributed Notes

There are no user contributed notes for this page.


Mostrar cuadro de error

  • « UI\Window::__construct
  • UI\Window::getSize »
  • PHP Manual
  • UI\Window
  • Mostrar cuadro de error

UI\Window::error

(UI 0.9.9)

UI\Window::error — Mostrar cuadro de error

Descripción

public UI\Window::error ( string $title , string $msg )

Mostrará un cuadro de error

Parámetros

title

El título del cuadro de error

msg

El mensaje para el cuadro de error

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el tamaño de la ventana

  • « UI\Window::error
  • UI\Window::getTitle »
  • PHP Manual
  • UI\Window
  • Obtiene el tamaño de la ventana

UI\Window::getSize

(UI 0.9.9)

UI\Window::getSize — Obtiene el tamaño de la ventana

Descripción

public UI\Window::getSize ( ) : UI\Size

Devolverá el tamaño de esta ventana

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el título

  • « UI\Window::getSize
  • UI\Window::hasBorders »
  • PHP Manual
  • UI\Window
  • Obtiene el título

UI\Window::getTitle

(UI 0.9.9)

UI\Window::getTitle — Obtiene el título

Descripción

public UI\Window::getTitle ( ) : string

Recuperará el título de esta Ventana

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Detección del Borde

  • « UI\Window::getTitle
  • UI\Window::hasMargin »
  • PHP Manual
  • UI\Window
  • Detección del Borde

UI\Window::hasBorders

(UI 0.9.9)

UI\Window::hasBorders — Detección del Borde

Descripción

public UI\Window::hasBorders ( ) : bool

Detectará si se usan bordes en esta ventana

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Detección de Margen

  • « UI\Window::hasBorders
  • UI\Window::isFullScreen »
  • PHP Manual
  • UI\Window
  • Detección de Margen

UI\Window::hasMargin

(UI 0.9.9)

UI\Window::hasMargin — Detección de Margen

Descripción

public UI\Window::hasMargin ( ) : bool

Detectará si se usan márgenes en esta ventana

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Detección de pantalla completa

  • « UI\Window::hasMargin
  • UI\Window::msg »
  • PHP Manual
  • UI\Window
  • Detección de pantalla completa

UI\Window::isFullScreen

(UI 0.9.9)

UI\Window::isFullScreen — Detección de pantalla completa

Descripción

public UI\Window::isFullScreen ( ) : bool

Detectará si esta ventana se utiliza toda la pantalla

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Mostrar Cuadro de Mensajes

  • « UI\Window::isFullScreen
  • UI\Window::onClosing »
  • PHP Manual
  • UI\Window
  • Mostrar Cuadro de Mensajes

UI\Window::msg

(UI 0.9.9)

UI\Window::msg — Mostrar Cuadro de Mensajes

Descripción

public UI\Window::msg ( string $title , string $msg )

Mostrará un cuadro de mensajes

Parámetros

title

El título del cuadro de mensajes

msg

El mensaje

User Contributed Notes

There are no user contributed notes for this page.


Cierre de la devolución de llamada

  • « UI\Window::msg
  • UI\Window::open »
  • PHP Manual
  • UI\Window
  • Cierre de la devolución de llamada

UI\Window::onClosing

(UI 0.9.9)

UI\Window::onClosing — Cierre de la devolución de llamada

Descripción

protected UI\Window::onClosing ( ) : int

Debería destruir con agilidad esta ventana

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Abrir Diálogo

  • « UI\Window::onClosing
  • UI\Window::save »
  • PHP Manual
  • UI\Window
  • Abrir Diálogo

UI\Window::open

(UI 0.9.9)

UI\Window::open — Abrir Diálogo

Descripción

public UI\Window::open ( ) : string

Mostrará un diálogo de archivo abierto

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve el nombre del archivo seleccionado para su apertura

User Contributed Notes

There are no user contributed notes for this page.


Guarda Diálogo

  • « UI\Window::open
  • UI\Window::setBorders »
  • PHP Manual
  • UI\Window
  • Guarda Diálogo

UI\Window::save

(UI 0.9.9)

UI\Window::save — Guarda Diálogo

Descripción

public UI\Window::save ( ) : string

Mostrará un diálogo a guardar

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Devuelve el nombre del archivo seleccionado para ser guardado

User Contributed Notes

There are no user contributed notes for this page.


Uso de Bordes

  • « UI\Window::save
  • UI\Window::setFullScreen »
  • PHP Manual
  • UI\Window
  • Uso de Bordes

UI\Window::setBorders

(UI 0.9.9)

UI\Window::setBorders — Uso de Bordes

Descripción

public UI\Window::setBorders ( bool $borders )

Habilitará o deshabilitará el uso de los bordes en esta ventana

Parámetros

borders

User Contributed Notes

There are no user contributed notes for this page.


Uso de la pantalla completa

  • « UI\Window::setBorders
  • UI\Window::setMargin »
  • PHP Manual
  • UI\Window
  • Uso de la pantalla completa

UI\Window::setFullScreen

(UI 0.9.9)

UI\Window::setFullScreen — Uso de la pantalla completa

Descripción

public UI\Window::setFullScreen ( bool $full )

Activará o desactivará el uso de la pantalla completa para esta ventana

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

full

User Contributed Notes

There are no user contributed notes for this page.


Uso del Margen

  • « UI\Window::setFullScreen
  • UI\Window::setSize »
  • PHP Manual
  • UI\Window
  • Uso del Margen

UI\Window::setMargin

(UI 0.9.9)

UI\Window::setMargin — Uso del Margen

Descripción

public UI\Window::setMargin ( bool $margin )

Habilitará o deshabilitará el uso de los márgenes para esta Ventana

Parámetros

margin

User Contributed Notes

There are no user contributed notes for this page.


Establece Tamaño

  • « UI\Window::setMargin
  • UI\Window::setTitle »
  • PHP Manual
  • UI\Window
  • Establece Tamaño

UI\Window::setSize

(UI 0.9.9)

UI\Window::setSize — Establece Tamaño

Descripción

public UI\Window::setSize ( UI\Size $size )

Establecerá el tamaño de esta ventana

Parámetros

size

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Título de la Vetana

  • « UI\Window::setSize
  • UI\Control »
  • PHP Manual
  • UI\Window
  • Título de la Vetana

UI\Window::setTitle

(UI 0.9.9)

UI\Window::setTitle — Título de la Vetana

Descripción

public UI\Window::setTitle ( string $title )

Pondrá el título de esta ventana

Parámetros

title

El nuevo título

User Contributed Notes

There are no user contributed notes for this page.


Control

(UI 0.9.9)

Introducción

This is the closed base class for all UI Controls.

Sinopsis de la Clase

final UI\Control {
/* Métodos */
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 ( )
}

Tabla de contenidos

  • 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

Descripción

public UI\Control::destroy ( )

Shall destroy this Control

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Control::disable ( )

Shall disable this Control

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Control::enable ( )

Shall enable this Control

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Control::getParent ( ) : UI\Control

Shall return the parent Control

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Control::getTopLevel ( ) : int

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Control::hide ( )

Shall hide this Control

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Control::isEnabled ( ) : bool

Shall detect if this Control is enabled

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Control::isVisible ( ) : bool

Shall detect if this Control is visible

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Control::setParent ( UI\Control $parent )

Shall set the parent Control of this Control

Parámetros

parent

The parent Control

Valores devueltos

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

Descripción

public UI\Control::show ( )

Shall show this Control

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Menu

(UI 0.9.9)

Introducción

Menus must be constructed before the first Window, and can be shown on any Window

Sinopsis de la Clase

UI\Menu {
/* Constructor */
public __construct ( string $name )
/* Métodos */
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 ( )
}

Tabla de contenidos

  • UI\Menu::append — Añade elemento de menú
  • UI\Menu::appendAbout — Añade elemento de menú Acerca de
  • UI\Menu::appendCheck — Añade un elemento de menú comprobable
  • UI\Menu::appendPreferences — Añade elemento de menú de preferencias
  • UI\Menu::appendQuit — Añade elemento de menú salir
  • UI\Menu::appendSeparator — Añade separador de elementos del menú
  • UI\Menu::__construct — Construye un nuevo menú

User Contributed Notes

There are no user contributed notes for this page.


Añade elemento de menú

  • « UI\Menu
  • UI\Menu::appendAbout »
  • PHP Manual
  • UI\Menu
  • Añade elemento de menú

UI\Menu::append

(UI 0.9.9)

UI\Menu::append — Añade elemento de menú

Descripción

public UI\Menu::append ( string $name , string $type = UI\MenuItem::class ) : UI\MenuItem

Añadirá un nuevo elemento del menú

Parámetros

name

El nombre (texto) del nuevo elemento

type

El tipo para el nuevo elemento

Valores devueltos

Un objeto construido del tipo dado

User Contributed Notes

There are no user contributed notes for this page.


Añade elemento de menú Acerca de

  • « UI\Menu::append
  • UI\Menu::appendCheck »
  • PHP Manual
  • UI\Menu
  • Añade elemento de menú Acerca de

UI\Menu::appendAbout

(UI 0.9.9)

UI\Menu::appendAbout — Añade elemento de menú Acerca de

Descripción

public UI\Menu::appendAbout ( string $type = UI\MenuItem::class ) : UI\MenuItem

Se añadirá un elemento del menú Acerca de

Parámetros

type

El tipo para el nuevo elemento

Valores devueltos

Un elemento del menú Acerca de construido del tipo dado

User Contributed Notes

There are no user contributed notes for this page.


Añade un elemento de menú comprobable

  • « UI\Menu::appendAbout
  • UI\Menu::appendPreferences »
  • PHP Manual
  • UI\Menu
  • Añade un elemento de menú comprobable

UI\Menu::appendCheck

(UI 0.9.9)

UI\Menu::appendCheck — Añade un elemento de menú comprobable

Descripción

public UI\Menu::appendCheck ( string $name , string $type = UI\MenuItem::class ) : UI\MenuItem

Se añadirá un elemento del menú comprobable

Parámetros

name

El nombre (texto) del nuevo elemento

type

El tipo para el nuevo elemento

Valores devueltos

Un elemento de menú construido y comprobable del tipo dado

User Contributed Notes

There are no user contributed notes for this page.


Añade elemento de menú de preferencias

  • « UI\Menu::appendCheck
  • UI\Menu::appendQuit »
  • PHP Manual
  • UI\Menu
  • Añade elemento de menú de preferencias

UI\Menu::appendPreferences

(UI 0.9.9)

UI\Menu::appendPreferences — Añade elemento de menú de preferencias

Descripción

public UI\Menu::appendPreferences ( string $type = UI\MenuItem::class ) : UI\MenuItem

Se añadirá un elemento del menú de Preferencias

Parámetros

type

El tipo para el nuevo elemento

Valores devueltos

Un elemento de menú de Preferencias construido del tipo dado

User Contributed Notes

There are no user contributed notes for this page.


Añade elemento de menú salir

  • « UI\Menu::appendPreferences
  • UI\Menu::appendSeparator »
  • PHP Manual
  • UI\Menu
  • Añade elemento de menú salir

UI\Menu::appendQuit

(UI 0.9.9)

UI\Menu::appendQuit — Añade elemento de menú salir

Descripción

public UI\Menu::appendQuit ( string $type = UI\MenuItem::class ) : UI\MenuItem

Se añadirá un elemento del menú de salida

Parámetros

type

El tipo para el nuevo elemento

Valores devueltos

Un elemento del menú de salida construido del tipo dado

User Contributed Notes

There are no user contributed notes for this page.


Añade separador de elementos del menú

  • « UI\Menu::appendQuit
  • UI\Menu::__construct »
  • PHP Manual
  • UI\Menu
  • Añade separador de elementos del menú

UI\Menu::appendSeparator

(UI 0.9.9)

UI\Menu::appendSeparator — Añade separador de elementos del menú

Descripción

public UI\Menu::appendSeparator ( )

Se añadirá un separador

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Construye un nuevo menú

  • « UI\Menu::appendSeparator
  • UI\MenuItem »
  • PHP Manual
  • UI\Menu
  • Construye un nuevo menú

UI\Menu::__construct

(UI 0.9.9)

UI\Menu::__construct — Construye un nuevo menú

Descripción

public UI\Menu::__construct ( string $name )

Construirá un nuevo menú

Parámetros

name

El nombre (texto) del menú

User Contributed Notes

There are no user contributed notes for this page.


Menu Item

(UI 0.9.9)

Introducción

Menu Items should only be created by the Menu

Sinopsis de la Clase

UI\MenuItem {
/* Métodos */
public disable ( )
public enable ( )
public isChecked ( ) : bool
protected onClick ( )
public setChecked ( bool $checked )
}

Tabla de contenidos

  • UI\MenuItem::disable — Desactiva elemento del menú
  • UI\MenuItem::enable — Activa elemento de menú
  • UI\MenuItem::isChecked — Detecta Marcado
  • UI\MenuItem::onClick — Llamada de retorno On Click
  • UI\MenuItem::setChecked — Establece marcado

User Contributed Notes

There are no user contributed notes for this page.


Desactiva elemento del menú

  • « UI\MenuItem
  • UI\MenuItem::enable »
  • PHP Manual
  • UI\MenuItem
  • Desactiva elemento del menú

UI\MenuItem::disable

(UI 0.9.9)

UI\MenuItem::disable — Desactiva elemento del menú

Descripción

public UI\MenuItem::disable ( )

Desactivará este elemento del menú

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Activa elemento de menú

  • « UI\MenuItem::disable
  • UI\MenuItem::isChecked »
  • PHP Manual
  • UI\MenuItem
  • Activa elemento de menú

UI\MenuItem::enable

(UI 0.9.9)

UI\MenuItem::enable — Activa elemento de menú

Descripción

public UI\MenuItem::enable ( )

Activará este elemento del menú

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Detecta Marcado

  • « UI\MenuItem::enable
  • UI\MenuItem::onClick »
  • PHP Manual
  • UI\MenuItem
  • Detecta Marcado

UI\MenuItem::isChecked

(UI 0.9.9)

UI\MenuItem::isChecked — Detecta Marcado

Descripción

public UI\MenuItem::isChecked ( ) : bool

Detecta si este elemento del menú está marcado

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Llamada de retorno On Click

  • « UI\MenuItem::isChecked
  • UI\MenuItem::setChecked »
  • PHP Manual
  • UI\MenuItem
  • Llamada de retorno On Click

UI\MenuItem::onClick

(UI 0.9.9)

UI\MenuItem::onClick — Llamada de retorno On Click

Descripción

protected UI\MenuItem::onClick ( )

Se ejecutará cuando se haga clic en este elemento del menú

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Establece marcado

  • « UI\MenuItem::onClick
  • UI\Area »
  • PHP Manual
  • UI\MenuItem
  • Establece marcado

UI\MenuItem::setChecked

(UI 0.9.9)

UI\MenuItem::setChecked — Establece marcado

Descripción

public UI\MenuItem::setChecked ( bool $checked )

Establecerá el estado marcado de este elemento del menú

Parámetros

checked

El nuevo estado

User Contributed Notes

There are no user contributed notes for this page.


Area

(UI 0.9.9)

Introducción

An Area represents a canvas which can be used to draw, and respond to mouse and key events.

Sinopsis de la Clase

UI\Area extends UI\Control {
/* Constants */
const int Ctrl ;
const int Alt ;
const int Shift ;
const int Super ;
const int Down ;
const int Up ;
/* Métodos */
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étodos heredados */
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 predefinidas

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

Tabla de contenidos

  • 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

Descripción

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

Parámetros

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

Descripción

protected UI\Area::onKey ( string $key , int $ext , int $flags )

Shall be executed on key events

Parámetros

key

The key pressed

ext

The extended key pressed

flags

Event modifiers

Valores devueltos

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

Descripción

protected UI\Area::onMouse ( UI\Point $areaPoint , UI\Size $areaSize , int $flags )

Shall be executed on mouse events

Parámetros

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

Descripción

public UI\Area::redraw ( )

Requests that this Area is redrawn

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Area::scrollTo ( UI\Point $point , UI\Size $size )

Scroll this Area

Parámetros

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

Descripción

public UI\Area::setSize ( UI\Size $size )

Sets the size of this Area

Parámetros

size

The new size

User Contributed Notes

There are no user contributed notes for this page.


Execution Scheduler

(UI 2.0.0)

Introducción

This facility schedules repetitive execution of a callback, useful for animations and other such activities.

Sinopsis de la Clase

abstract UI\Executor {
/* Constructor */
public __construct ( )
public __construct ( int $microseconds )
public __construct ( int $seconds , int $microseconds )
/* Métodos */
public kill ( ) : void
abstract protected onExecute ( ) : void
public setInterval ( int $microseconds ) : bool
public setInterval ( int $seconds , int $microseconds ) : bool
}

Tabla de contenidos

  • 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

Descripción

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

Parámetros

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

Descripción

public UI\Executor::kill ( ) : void

Shall stop an executor, the executor cannot be restarted

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

abstract protected UI\Executor::onExecute ( ) : void

Shall be repetitively queued for execution in the main thread

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

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

Parámetros

seconds

microseconds

Valores devueltos

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Tab Control

(UI 0.9.9)

Introducción

A Tab can contain many pages of Controls, each with a title, each selectable by the user.

Sinopsis de la Clase

UI\Controls\Tab extends UI\Control {
/* Propiedades */
protected $controls ;
/* Métodos */
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étodos heredados */
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 ( )
}

Propiedades

controls

Contains controls, should not be manipulated directly

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Tab::append ( string $name , UI\Control $control ) : int

Append a new page to this Tab

Parámetros

name

The name for the new page

control

The control for the new page

Valores devueltos

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

Descripción

public UI\Controls\Tab::delete ( int $index ) : bool

Shall remove the selected page from this Tab

Parámetros

index

The index of the page to remove

Valores devueltos

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

Descripción

public UI\Controls\Tab::hasMargin ( int $page ) : bool

Shall detect if the given page has a margin.

Parámetros

page

The index of the page

Valores devueltos

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

Descripción

public UI\Controls\Tab::insertAt ( string $name , int $page , UI\Control $control )

Shall insert a new page into this Tab

Parámetros

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

Descripción

public UI\Controls\Tab::pages ( ) : int

Shall return the number of pages in this Tab

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Controls\Tab::setMargin ( int $page , bool $margin )

Shall enable or disable margins on the selected page

Parámetros

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)

Introducción

A Check is a labelled checkable box

Sinopsis de la Clase

UI\Controls\Check extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* Métodos */
public getText ( ) : string
public isChecked ( ) : bool
protected onToggle ( )
public setChecked ( bool $checked )
public setText ( string $text )
/* Métodos heredados */
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 ( )
}

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Check::__construct ( string $text )

Shall construct a new Check

Parámetros

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

Descripción

public UI\Controls\Check::getText ( ) : string

Shall return the text (label) for this Check

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Controls\Check::isChecked ( ) : bool

Shall detect the status of this Check

Parámetros

Esta función no tiene parámetros.

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

Descripción

protected UI\Controls\Check::onToggle ( )

Shall be executed when the status of this Check is changed

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Check::setChecked ( bool $checked )

Shall change the status of this Check

Parámetros

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

Descripción

public UI\Controls\Check::setText ( string $text )

Shall set the text (label) for this Check

Parámetros

text

The new text (label)

User Contributed Notes

There are no user contributed notes for this page.


Button Control

(UI 0.9.9)

Introducción

Represents a labelled clickable button

Sinopsis de la Clase

UI\Controls\Button extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* Métodos */
public getText ( ) : string
protected onClick ( )
public setText ( string $text )
/* Métodos heredados */
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 ( )
}

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Button::__construct ( string $text )

Shall construct a new Button

Parámetros

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

Descripción

public UI\Controls\Button::getText ( ) : string

Shall retrieve the text (label) for this Button

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

protected UI\Controls\Button::onClick ( )

Shall be executed when this Button is clicked

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Button::setText ( string $text )

Shall set the text (label) for this Button

Parámetros

text

The new text (label)

User Contributed Notes

There are no user contributed notes for this page.


ColorButton Control

(UI 0.9.9)

Introducción

A Color Button is a button which displays a color picker when clicked

Sinopsis de la Clase

UI\Controls\ColorButton extends UI\Control {
/* Métodos */
public getColor ( ) : UI\Color
protected onChange ( )
public setColor ( UI\Draw\Color $color )
public setColor ( int $color )
/* Métodos heredados */
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 ( )
}

Tabla de contenidos

  • 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

Descripción

public UI\Controls\ColorButton::getColor ( ) : UI\Color

Shall retrieve the currently selected Color

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

protected UI\Controls\ColorButton::onChange ( )

Shall be executed when the selected Color is changed

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\ColorButton::setColor ( UI\Draw\Color $color )
public UI\Controls\ColorButton::setColor ( int $color )

Shall set the currently selected Color

Parámetros

color

The new color

User Contributed Notes

There are no user contributed notes for this page.


Label Control

(UI 0.9.9)

Introducción

A Label is a single line of text, meant to identify, for the user, some element of the interface.

Sinopsis de la Clase

UI\Controls\Label extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* Métodos */
public getText ( ) : string
public setText ( string $text )
/* Métodos heredados */
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 ( )
}

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Label::__construct ( string $text )

Shall construct a new Label

Parámetros

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

Descripción

public UI\Controls\Label::getText ( ) : string

Shall return the current text for this Label

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Controls\Label::setText ( string $text )

Shall set the text for this Label

Parámetros

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Entry Control

(UI 0.9.9)

Introducción

An Entry is a text entry control, suitable for entering plain text, passwords, or search terms.

Sinopsis de la Clase

UI\Controls\Entry extends UI\Control {
/* Constants */
const int Normal ;
const int Password ;
const int Search ;
/* Constructor */
public __construct ( int $type = UI\Controls\Entry::Normal )
/* Métodos */
public getText ( ) : string
public isReadOnly ( ) : bool
protected onChange ( )
public setReadOnly ( bool $readOnly )
public setText ( string $text )
/* Métodos heredados */
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 predefinidas

UI\Controls\Entry::Normal

A normal single line entry

UI\Controls\Entry::Password

A password entry

UI\Controls\Entry::Search

A search entry

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Entry::__construct ( int $type = UI\Controls\Entry::Normal )

Construct a new entry of the given type

Parámetros

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

Descripción

public UI\Controls\Entry::getText ( ) : string

Shall return the current text from this Entry

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Controls\Entry::isReadOnly ( ) : bool

Shall detect if this Entry is read only

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

protected UI\Controls\Entry::onChange ( )

Shall be executed when the text in this Entry changes

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Entry::setReadOnly ( bool $readOnly )

Shall enable or disable read only for this Entry

Parámetros

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

Descripción

public UI\Controls\Entry::setText ( string $text )

Shall set the text for this Entry

Parámetros

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


MultilineEntry Control

(UI 0.9.9)

Introducción

A Multiline Entry is a text entry control able to hold multiple lines of text, with or without wrapping.

Sinopsis de la Clase

UI\Controls\MultilineEntry extends UI\Control {
/* Constants */
const int Wrap ;
const int NoWrap ;
/* Constructor */
public __construct ( int $type = ? )
/* Métodos */
public append ( string $text )
public getText ( ) : string
public isReadOnly ( ) : bool
protected onChange ( )
public setReadOnly ( bool $readOnly )
public setText ( string $text )
/* Métodos heredados */
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 predefinidas

UI\Controls\MultilineEntry::Wrap

Allow lines to wrap

UI\Controls\MultilineEntry::NoWrap

Do not allow lines to wrap

Tabla de contenidos

  • 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

Descripción

public UI\Controls\MultilineEntry::append ( string $text )

Shall append the given text to the text in this Multiline Entry

Parámetros

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

Descripción

public UI\Controls\MultilineEntry::__construct ( int $type = ? )

Shall construct a new Multiline Entry of the given type

Parámetros

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

Descripción

public UI\Controls\MultilineEntry::getText ( ) : string

Shall return the text in this Multiline Entry

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\MultilineEntry::isReadOnly ( ) : bool

Shall detect if this Multiline Entry is read only

Parámetros

Esta función no tiene parámetros.

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

Descripción

protected UI\Controls\MultilineEntry::onChange ( )

Shall be executed when the text in this Multiline Entry is changed

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\MultilineEntry::setReadOnly ( bool $readOnly )

Shall enable or disable read only on this Multiline Entry

Parámetros

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

Descripción

public UI\Controls\MultilineEntry::setText ( string $text )

Shall set the text in this Multiline Entry

Parámetros

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Spin Control

(UI 0.9.9)

Introducción

A Spin box is a text box with an up-down control which changes the integer value in the box, within a defined range

Sinopsis de la Clase

UI\Controls\Spin extends UI\Control {
/* Constructor */
public __construct ( int $min , int $max )
/* Métodos */
public getValue ( ) : int
protected onChange ( )
public setValue ( int $value )
/* Métodos heredados */
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 ( )
}

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Spin::__construct ( int $min , int $max )

Constructs a new Spin with the given range

Parámetros

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

Descripción

public UI\Controls\Spin::getValue ( ) : int

Get the value in this Spin

Parámetros

Esta función no tiene parámetros.

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

Descripción

protected UI\Controls\Spin::onChange ( )

Shall be executed when the value in this Spin changes

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Spin::setValue ( int $value )

Set the value in this Spin

Parámetros

value

The new value

User Contributed Notes

There are no user contributed notes for this page.


Slider Control

(UI 0.9.9)

Introducción

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.

Sinopsis de la Clase

UI\Controls\Slider extends UI\Control {
/* Constructor */
public __construct ( int $min , int $max )
/* Métodos */
public getValue ( ) : int
protected onChange ( )
public setValue ( int $value )
/* Métodos heredados */
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 ( )
}

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Slider::__construct ( int $min , int $max )

Construct a new Slider with the given range

Parámetros

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

Descripción

public UI\Controls\Slider::getValue ( ) : int

Get the value from this Slider

Parámetros

Esta función no tiene parámetros.

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

Descripción

protected UI\Controls\Slider::onChange ( )

Shall be executed when the value of this Slider changes

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Slider::setValue ( int $value )

Shall set the value for this Slider

Parámetros

value

The new value

User Contributed Notes

There are no user contributed notes for this page.


Progress Control

(UI 0.9.9)

Introducción

A Progress control is a familiar Progress bar: It represents progress as a percentage, with a possible range of 0 to 100 (inclusive).

Sinopsis de la Clase

UI\Controls\Progress extends UI\Control {
/* Métodos */
public getValue ( ) : int
public setValue ( int $value )
/* Métodos heredados */
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 ( )
}

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Progress::getValue ( ) : int

Shall retrieve the current value of this Progress bar

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Progress::setValue ( int $value )

Shall set the value for this Progress bar

Parámetros

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)

Introducción

A Separator represents a control separator, it has no other function.

Sinopsis de la Clase

UI\Controls\Separator extends UI\Control {
/* Constants */
const int Horizontal ;
const int Vertical ;
/* Constructor */
public __construct ( int $type = UI\Controls\Separator::Horizontal )
/* Métodos heredados */
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 predefinidas

UI\Controls\Separator::Horizontal

A Horizontal Separator

UI\Controls\Separator::Vertical

A Vertical Separator

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Separator::__construct ( int $type = UI\Controls\Separator::Horizontal )

Shall construct a new Separator of the given type

Parámetros

type

Separator::Horizonal or Separator::Vertical

User Contributed Notes

There are no user contributed notes for this page.


Combo Control

(UI 0.9.9)

Introducción

A Combo control represents a list of options, like the familiar select HTML element.

Sinopsis de la Clase

UI\Controls\Combo extends UI\Control {
/* Métodos */
public append ( string $text )
public getSelected ( ) : int
protected onSelected ( )
public setSelected ( int $index )
/* Métodos heredados */
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 ( )
}

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Combo::append ( string $text )

Append an option to this Combo

Parámetros

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

Descripción

public UI\Controls\Combo::getSelected ( ) : int

Shall retrieve the index of the option selected in this Combo

Parámetros

Esta función no tiene parámetros.

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

Descripción

protected UI\Controls\Combo::onSelected ( )

Shall be executed when an option is selected in this Combo

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Combo::setSelected ( int $index )

Shall set the currently selected option in this Combo

Parámetros

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)

Introducción

An Editable Combo is a Combo which allows the user to enter custom options

Sinopsis de la Clase

UI\Controls\EditableCombo extends UI\Control {
/* Métodos */
public append ( string $text )
public getText ( ) : string
protected onChange ( )
public setText ( string $text )
/* Métodos heredados */
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 ( )
}

Tabla de contenidos

  • 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

Descripción

public UI\Controls\EditableCombo::append ( string $text )

Shall append a new option to this Editable Combo

Parámetros

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

Descripción

public UI\Controls\EditableCombo::getText ( ) : string

Get the value of the currently selected option in this Editable Combo

Parámetros

Esta función no tiene parámetros.

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

Descripción

protected UI\Controls\EditableCombo::onChange ( )

Shall be executed when the value of this Editable Combobox changes

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\EditableCombo::setText ( string $text )

Shall set the text of the currently selected option in this Editable Combo

Parámetros

text

The new text

User Contributed Notes

There are no user contributed notes for this page.


Radio Control

(UI 0.9.9)

Introducción

A Radio is similar to the radio input type familiar from HTML

Sinopsis de la Clase

UI\Controls\Radio extends UI\Control {
/* Métodos */
public append ( string $text )
public getSelected ( ) : int
protected onSelected ( )
public setSelected ( int $index )
/* Métodos heredados */
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 ( )
}

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Radio::append ( string $text )

Shall append a new option to this Radio

Parámetros

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

Descripción

public UI\Controls\Radio::getSelected ( ) : int

Shall retrieve the index of the currently selected option in this Radio

Parámetros

Esta función no tiene parámetros.

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

Descripción

protected UI\Controls\Radio::onSelected ( )

Shall be executed when the option selected in this Radio changes

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Radio::setSelected ( int $index )

Shall set the currently selected option in this Radio

Parámetros

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)

Introducción

A Picker represents a button which when clicked presents a native Date/Time/DateTime Picker interface to the user.

Sinopsis de la Clase

UI\Controls\Picker extends UI\Control {
/* Constants */
const int Date ;
const int Time ;
const int DateTime ;
/* Constructor */
public __construct ( int $type = UI\Controls\Picker::Date )
/* Métodos heredados */
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 predefinidas

UI\Controls\Picker::Date

A Date Picker

UI\Controls\Picker::Time

A Time Picker

UI\Controls\Picker::DateTime

A Date and Time Picker

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Picker::__construct ( int $type = UI\Controls\Picker::Date )

Construct a new Picker of the given type

Parámetros

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)

Introducción

A Form is a control which allows the arrangement of other controls into a familiar layout (the form).

Sinopsis de la Clase

UI\Controls\Form extends UI\Control {
/* Propiedades */
protected $controls ;
/* Métodos */
public append ( string $label , UI\Control $control , bool $stretchy = false ) : int
public delete ( int $index ) : bool
public isPadded ( ) : bool
public setPadded ( bool $padded )
/* Métodos heredados */
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 ( )
}

Propiedades

controls

Contains controls, should not be manipulated directly

Tabla de contenidos

  • 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

Descripción

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

Parámetros

label

The text for the label

control

A control

stretchy

Should be set true to stretch the control

Valores devueltos

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

Descripción

public UI\Controls\Form::delete ( int $index ) : bool

Shall delete the control at the given index in this Form

Parámetros

index

The index of the control to remove

Valores devueltos

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

Descripción

public UI\Controls\Form::isPadded ( ) : bool

Shall detect if padding is enabled on this Form

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Form::setPadded ( bool $padded )

Shall enable or disable padding on this Form

Parámetros

padded

User Contributed Notes

There are no user contributed notes for this page.


Control Grid (Arrangement)

(UI 0.9.9)

Introducción

A Grid is a control which is allows the arrangement of children into a grid

Sinopsis de la Clase

UI\Controls\Grid extends UI\Control {
/* Constants */
const int Fill ;
const int Start ;
const int Center ;
const int End ;
const int Leading ;
const int Top ;
const int Trailing ;
const int Bottom ;
/* Propiedades */
protected $controls ;
/* Métodos */
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étodos heredados */
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 predefinidas

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

Propiedades

controls

Contains controls, should not be manipulated directly

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Grid::append ( UI\Control $control , int $left , int $top , int $xspan , int $yspan , bool $hexpand , int $halign , bool $vexpand , int $valign )

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

control

The Control to append

left

top

xspan

yspan

hexpand

halign

vexpand

valign

Valores devueltos

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

Descripción

public UI\Controls\Grid::isPadded ( ) : bool

Shall detect if padding is enabled on this Grid

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Grid::setPadded ( bool $padding )

Shall enable or disable padding for this Grid

Parámetros

padding

User Contributed Notes

There are no user contributed notes for this page.


Control Group (Arrangement)

(UI 0.9.9)

Introducción

A Group is a titled container for child controls

Sinopsis de la Clase

UI\Controls\Group extends UI\Control {
/* Propiedades */
protected $controls ;
/* Constructor */
public __construct ( string $title )
/* Métodos */
public append ( UI\Control $control )
public getTitle ( ) : string
public hasMargin ( ) : bool
public setMargin ( bool $margin )
public setTitle ( string $title )
/* Métodos heredados */
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 ( )
}

Propiedades

controls

Contains controls, should not be manipulated directly

Tabla de contenidos

  • 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 hay información de versión disponible, podría estar únicamente en Git)

UI\Controls\Group::append — Append Control

Descripción

public UI\Controls\Group::append ( UI\Control $control )

Shall append a control to this Group

Parámetros

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

Descripción

public UI\Controls\Group::__construct ( string $title )

Shall construct a new Group with the given title

Parámetros

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

Descripción

public UI\Controls\Group::getTitle ( ) : string

Shall return the current title for this Group

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Controls\Group::hasMargin ( ) : bool

Shall detect if this Group has a margin

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Group::setMargin ( bool $margin )

Shall enable or disable margins for this Group

Parámetros

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

Descripción

public UI\Controls\Group::setTitle ( string $title )

Shall set the title for this Group

Parámetros

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)

Introducción

A Box allows the arrangement of other controls

Sinopsis de la Clase

UI\Controls\Box extends UI\Control {
/* Constants */
const int Vertical ;
const int Horizontal ;
/* Propiedades */
protected $controls ;
/* Constructor */
public __construct ( int $orientation = UI\Controls\Box::Horizontal )
/* Métodos */
public append ( Control $control , bool $stretchy = false ) : int
public delete ( int $index ) : bool
public getOrientation ( ) : int
public isPadded ( ) : bool
public setPadded ( bool $padded )
/* Métodos heredados */
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 ( )
}

Propiedades

controls

Contains controls, should not be manipulated directly

Constantes predefinidas

UI\Controls\Box::Vertical

UI\Controls\Box::Horizontal

Tabla de contenidos

  • 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

Descripción

public UI\Controls\Box::append ( Control $control , bool $stretchy = false ) : int

Shall append the given control to this Box

Parámetros

control

The control to append

stretchy

Set true to stretch the control

Valores devueltos

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

Descripción

public UI\Controls\Box::__construct ( int $orientation = UI\Controls\Box::Horizontal )

Shall construct a new box

Parámetros

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

Descripción

public UI\Controls\Box::delete ( int $index ) : bool

Shall delete the control at the given index from this Box

Parámetros

index

The index of the control to delete

Valores devueltos

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

Descripción

public UI\Controls\Box::getOrientation ( ) : int

Shall retrieve the orientation of this Box

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Box::isPadded ( ) : bool

Shall detect if padding is enabled on this Box

Parámetros

Esta función no tiene parámetros.

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

Descripción

public UI\Controls\Box::setPadded ( bool $padded )

Shall enable or disable padding on this Box

Parámetros

padded

User Contributed Notes

There are no user contributed notes for this page.


Draw Pen

(UI 0.9.9)

Introducción

The Pen is passed to the Area Draw event handler, it is used for clipping, filling, stroking, and writing to Draw Paths.

Sinopsis de la Clase

final UI\Draw\Pen {
/* Métodos */
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 )
}

Tabla de contenidos

  • UI\Draw\Pen::clip — Clip a Path
  • UI\Draw\Pen::fill — Llena una ruta
  • UI\Draw\Pen::restore — Restaura
  • UI\Draw\Pen::save — Guarda
  • UI\Draw\Pen::stroke — Traza una ruta
  • UI\Draw\Pen::transform — Transformación de la matriz
  • UI\Draw\Pen::write — Dibuja el texto en el punto

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

Descripción

public UI\Draw\Pen::clip ( UI\Draw\Path $path )

Shall clip the given Path

Parámetros

path

The path to clip

User Contributed Notes

There are no user contributed notes for this page.


Llena una ruta

  • « UI\Draw\Pen::clip
  • UI\Draw\Pen::restore »
  • PHP Manual
  • UI\Draw\Pen
  • Llena una ruta

UI\Draw\Pen::fill

(UI 0.9.9)

UI\Draw\Pen::fill — Llena una ruta

Descripción

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 )

Llenará la ruta dada

Parámetros

path

La ruta a llenar

with

El color o el pincel para rellenar

User Contributed Notes

There are no user contributed notes for this page.


Restaura

  • « UI\Draw\Pen::fill
  • UI\Draw\Pen::save »
  • PHP Manual
  • UI\Draw\Pen
  • Restaura

UI\Draw\Pen::restore

(UI 0.9.9)

UI\Draw\Pen::restore — Restaura

Descripción

public UI\Draw\Pen::restore ( )

Restaurará un bolígrafo previamente guardado

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Guarda

  • « UI\Draw\Pen::restore
  • UI\Draw\Pen::stroke »
  • PHP Manual
  • UI\Draw\Pen
  • Guarda

UI\Draw\Pen::save

(UI 0.9.9)

UI\Draw\Pen::save — Guarda

Descripción

public UI\Draw\Pen::save ( )

Guardará el bolígrafo

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Traza una ruta

  • « UI\Draw\Pen::save
  • UI\Draw\Pen::transform »
  • PHP Manual
  • UI\Draw\Pen
  • Traza una ruta

UI\Draw\Pen::stroke

(UI 0.9.9)

UI\Draw\Pen::stroke — Traza una ruta

Descripción

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 )

Trazará la ruta dada

Parámetros

path

La ruta del trazo

with

El color o el pincel con el que trazar

stroke

La configuración del trazo

User Contributed Notes

There are no user contributed notes for this page.


Transformación de la matriz

  • « UI\Draw\Pen::stroke
  • UI\Draw\Pen::write »
  • PHP Manual
  • UI\Draw\Pen
  • Transformación de la matriz

UI\Draw\Pen::transform

(UI 0.9.9)

UI\Draw\Pen::transform — Transformación de la matriz

Descripción

public UI\Draw\Pen::transform ( UI\Draw\Matrix $matrix )

Realizará la transformación de la matriz

Parámetros

matrix

La matriz a usar

User Contributed Notes

There are no user contributed notes for this page.


Dibuja el texto en el punto

  • « UI\Draw\Pen::transform
  • UI\Draw\Path »
  • PHP Manual
  • UI\Draw\Pen
  • Dibuja el texto en el punto

UI\Draw\Pen::write

(UI 0.9.9)

UI\Draw\Pen::write — Dibuja el texto en el punto

Descripción

public UI\Draw\Pen::write ( UI\Point $point , UI\Draw\Text\Layout $layout )

Dibujará la disposición del texto en el punto dado

Parámetros

point

El punto a realizar el dibujo

layout

La disposición del texto a dibujar

User Contributed Notes

There are no user contributed notes for this page.


Draw Path

(UI 0.9.9)

Introducción

A Draw Path guides a Draw Pen, telling the Pen where to draw on an Area.

Sinopsis de la Clase

UI\Draw\Path {
/* Constants */
const int Winding ;
const int Alternate ;
/* Constructor */
public __construct ( int $mode = UI\Draw\Path::Winding )
/* Métodos */
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 predefinidas

UI\Draw\Path::Winding

This is the default draw path mode

UI\Draw\Path::Alternate

This is the alternate draw path mode

Tabla de contenidos

  • UI\Draw\Path::addRectangle — Dibuja un rectángulo
  • UI\Draw\Path::arcTo — Dibuja un arco
  • UI\Draw\Path::bezierTo — Draw Bezier Curve
  • UI\Draw\Path::closeFigure — Cerrar Figura
  • UI\Draw\Path::__construct — Construye una nueva ruta
  • UI\Draw\Path::end — Finalizar Ruta
  • UI\Draw\Path::lineTo — Dibuja una línea
  • UI\Draw\Path::newFigure — Dibuja figura
  • UI\Draw\Path::newFigureWithArc — Dibuja figura con arco

User Contributed Notes

There are no user contributed notes for this page.


Dibuja un rectángulo

  • « UI\Draw\Path
  • UI\Draw\Path::arcTo »
  • PHP Manual
  • UI\Draw\Path
  • Dibuja un rectángulo

UI\Draw\Path::addRectangle

(UI 0.9.9)

UI\Draw\Path::addRectangle — Dibuja un rectángulo

Descripción

public UI\Draw\Path::addRectangle ( UI\Point $point , UI\Size $size )

Trazará la ruta de un rectángulo del tamaño dado, en el punto dado

Parámetros

point

El punto de partida de la forma

size

El tamaño del rectángulo

User Contributed Notes

There are no user contributed notes for this page.


Dibuja un arco

  • « UI\Draw\Path::addRectangle
  • UI\Draw\Path::bezierTo »
  • PHP Manual
  • UI\Draw\Path
  • Dibuja un arco

UI\Draw\Path::arcTo

(UI 0.9.9)

UI\Draw\Path::arcTo — Dibuja un arco

Descripción

public UI\Draw\Path::arcTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Trazará la ruta para un arco

Parámetros

point

El punto de partida del mapeo

radius

El radio del arco

angle

El ángulo del arco

sweep

El alcance del arco

negative

Valores devueltos

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

Descripción

public UI\Draw\Path::bezierTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Shall draw a bezier curve

Parámetros

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.


Cerrar Figura

  • « UI\Draw\Path::bezierTo
  • UI\Draw\Path::__construct »
  • PHP Manual
  • UI\Draw\Path
  • Cerrar Figura

UI\Draw\Path::closeFigure

(UI 0.9.9)

UI\Draw\Path::closeFigure — Cerrar Figura

Descripción

public UI\Draw\Path::closeFigure ( )

Cerrará la figura actual

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Construye una nueva ruta

  • « UI\Draw\Path::closeFigure
  • UI\Draw\Path::end »
  • PHP Manual
  • UI\Draw\Path
  • Construye una nueva ruta

UI\Draw\Path::__construct

(UI 0.9.9)

UI\Draw\Path::__construct — Construye una nueva ruta

Descripción

public UI\Draw\Path::__construct ( int $mode = UI\Draw\Path::Winding )

Construirá una nueva ruta en el modo dado

Parámetros

mode

Path::Winding o Path::Alternate

User Contributed Notes

There are no user contributed notes for this page.


Finalizar Ruta

  • « UI\Draw\Path::__construct
  • UI\Draw\Path::lineTo »
  • PHP Manual
  • UI\Draw\Path
  • Finalizar Ruta

UI\Draw\Path::end

(UI 0.9.9)

UI\Draw\Path::end — Finalizar Ruta

Descripción

public UI\Draw\Path::end ( )

Finalizará esta ruta

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Dibuja una línea

  • « UI\Draw\Path::end
  • UI\Draw\Path::newFigure »
  • PHP Manual
  • UI\Draw\Path
  • Dibuja una línea

UI\Draw\Path::lineTo

(UI 0.9.9)

UI\Draw\Path::lineTo — Dibuja una línea

Descripción

public UI\Draw\Path::lineTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Trazará la ruta para una línea

Parámetros

point

El punto de partida del mapeo

radius

angle

sweep

negative

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Dibuja figura

  • « UI\Draw\Path::lineTo
  • UI\Draw\Path::newFigureWithArc »
  • PHP Manual
  • UI\Draw\Path
  • Dibuja figura

UI\Draw\Path::newFigure

(UI 0.9.9)

UI\Draw\Path::newFigure — Dibuja figura

Descripción

public UI\Draw\Path::newFigure ( UI\Point $point )

Trazará una nueva figura en el punto dado

Parámetros

point

El punto de partida del mapeo

User Contributed Notes

There are no user contributed notes for this page.


Dibuja figura con arco

  • « UI\Draw\Path::newFigure
  • UI\Draw\Matrix »
  • PHP Manual
  • UI\Draw\Path
  • Dibuja figura con arco

UI\Draw\Path::newFigureWithArc

(UI 0.9.9)

UI\Draw\Path::newFigureWithArc — Dibuja figura con arco

Descripción

public UI\Draw\Path::newFigureWithArc ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Parámetros

point

radius

angle

sweep

negative

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Draw Matrix

(UI 0.9.9)

Introducción

Sinopsis de la Clase

UI\Draw\Matrix {
/* Métodos */
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 )
}

Tabla de contenidos

  • UI\Draw\Matrix::invert — Invertir matriz
  • UI\Draw\Matrix::isInvertible — Detección de invertido
  • UI\Draw\Matrix::multiply — Multiplica la matriz
  • UI\Draw\Matrix::rotate — Rota la matriz
  • UI\Draw\Matrix::scale — Escala la Matriz
  • UI\Draw\Matrix::skew — Inclina la Matriz
  • UI\Draw\Matrix::translate — Traduce la matriz

User Contributed Notes

There are no user contributed notes for this page.


Invertir matriz

  • « UI\Draw\Matrix
  • UI\Draw\Matrix::isInvertible »
  • PHP Manual
  • UI\Draw\Matrix
  • Invertir matriz

UI\Draw\Matrix::invert

(UI 0.9.9)

UI\Draw\Matrix::invert — Invertir matriz

Descripción

public UI\Draw\Matrix::invert ( )

Invertirá esta matriz

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Detección de invertido

  • « UI\Draw\Matrix::invert
  • UI\Draw\Matrix::multiply »
  • PHP Manual
  • UI\Draw\Matrix
  • Detección de invertido

UI\Draw\Matrix::isInvertible

(UI 0.9.9)

UI\Draw\Matrix::isInvertible — Detección de invertido

Descripción

public UI\Draw\Matrix::isInvertible ( ) : bool

Detectará si esta Matriz puede ser invertida

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Multiplica la matriz

  • « UI\Draw\Matrix::isInvertible
  • UI\Draw\Matrix::rotate »
  • PHP Manual
  • UI\Draw\Matrix
  • Multiplica la matriz

UI\Draw\Matrix::multiply

(UI 0.9.9)

UI\Draw\Matrix::multiply — Multiplica la matriz

Descripción

public UI\Draw\Matrix::multiply ( UI\Draw\Matrix $matrix ) : UI\Draw\Matrix

Multiplicará esta matriz con la matriz dada

Parámetros

Esta función no tiene parámetros.

Valores devueltos

La nueva matriz

User Contributed Notes

There are no user contributed notes for this page.


Rota la matriz

  • « UI\Draw\Matrix::multiply
  • UI\Draw\Matrix::scale »
  • PHP Manual
  • UI\Draw\Matrix
  • Rota la matriz

UI\Draw\Matrix::rotate

(UI 0.9.9)

UI\Draw\Matrix::rotate — Rota la matriz

Descripción

public UI\Draw\Matrix::rotate ( UI\Point $point , float $amount )

Rotar esta Matriz

Parámetros

point

amount

User Contributed Notes

There are no user contributed notes for this page.


Escala la Matriz

  • « UI\Draw\Matrix::rotate
  • UI\Draw\Matrix::skew »
  • PHP Manual
  • UI\Draw\Matrix
  • Escala la Matriz

UI\Draw\Matrix::scale

(UI 0.9.9)

UI\Draw\Matrix::scale — Escala la Matriz

Descripción

public UI\Draw\Matrix::scale ( UI\Point $center , UI\Point $point )

Escalará esta Matriz

Parámetros

center

point

User Contributed Notes

There are no user contributed notes for this page.


Inclina la Matriz

  • « UI\Draw\Matrix::scale
  • UI\Draw\Matrix::translate »
  • PHP Manual
  • UI\Draw\Matrix
  • Inclina la Matriz

UI\Draw\Matrix::skew

(UI 0.9.9)

UI\Draw\Matrix::skew — Inclina la Matriz

Descripción

public UI\Draw\Matrix::skew ( UI\Point $point , UI\Point $amount )

Inclinará esta Matriz

Parámetros

point

amount

User Contributed Notes

There are no user contributed notes for this page.


Traduce la matriz

  • « UI\Draw\Matrix::skew
  • UI\Draw\Color »
  • PHP Manual
  • UI\Draw\Matrix
  • Traduce la matriz

UI\Draw\Matrix::translate

(UI 0.9.9)

UI\Draw\Matrix::translate — Traduce la matriz

Descripción

public UI\Draw\Matrix::translate ( UI\Point $point )

Traducirá esta Matriz

Parámetros

point

User Contributed Notes

There are no user contributed notes for this page.


Color Representation

(UI 0.9.9)

Introducción

Represents RGBA colours, individual channels are accessible via public properties.

Sinopsis de la Clase

UI\Draw\Color {
/* Constants */
const int Red ;
const int Green ;
const int Blue ;
const int Alpha ;
/* Propiedades */
public $r ;
public $g ;
public $b ;
public $a ;
/* Constructor */
public __construct ( UI\Draw\Color $color = ? )
public __construct ( int $color = ? )
/* Métodos */
public getChannel ( int $channel ) : float
public setChannel ( int $channel , float $value ) : void
}

Propiedades

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 predefinidas

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

Tabla de contenidos

  • UI\Draw\Color::__construct — Construye un nuevo color
  • UI\Draw\Color::getChannel — Manipulación de color
  • UI\Draw\Color::setChannel — Manipulación de color

User Contributed Notes

There are no user contributed notes for this page.


Construye un nuevo color

  • « UI\Draw\Color
  • UI\Draw\Color::getChannel »
  • PHP Manual
  • UI\Draw\Color
  • Construye un nuevo color

UI\Draw\Color::__construct

(UI 0.9.9)

UI\Draw\Color::__construct — Construye un nuevo color

Descripción

public UI\Draw\Color::__construct ( UI\Draw\Color $color = ? )
public UI\Draw\Color::__construct ( int $color = ? )

Construirá un nuevo color

Parámetros

color

Puede ser UI\Draw\Color o RRGGBBAA

User Contributed Notes

There are no user contributed notes for this page.


Manipulación de color

  • « UI\Draw\Color::__construct
  • UI\Draw\Color::setChannel »
  • PHP Manual
  • UI\Draw\Color
  • Manipulación de color

UI\Draw\Color::getChannel

(UI 0.9.9)

UI\Draw\Color::getChannel — Manipulación de color

Descripción

public UI\Draw\Color::getChannel ( int $channel ) : float

Recuperará el valor de un canal

Parámetros

channel

La identidad del canal constante

Valores devueltos

El valor actual del canal solicitado

User Contributed Notes

There are no user contributed notes for this page.


Manipulación de color

  • « UI\Draw\Color::getChannel
  • UI\Draw\Stroke »
  • PHP Manual
  • UI\Draw\Color
  • Manipulación de color

UI\Draw\Color::setChannel

(UI 0.9.9)

UI\Draw\Color::setChannel — Manipulación de color

Descripción

public UI\Draw\Color::setChannel ( int $channel , float $value ) : void

Pondrá el canal seleccionado en el valor dado

Parámetros

channel

La identidad del canal constante

value

El nuevo valor para el canal seleccionado

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Draw Stroke

(UI 0.9.9)

Introducción

Holds the configuration for the Pen to perform a stroke

Sinopsis de la Clase

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étodos */
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 )
}

Tabla de contenidos

  • UI\Draw\Stroke::__construct — Construye un nuevo trazo
  • UI\Draw\Stroke::getCap — Get Line Cap
  • UI\Draw\Stroke::getJoin — Obtiene la unión de línea
  • UI\Draw\Stroke::getMiterLimit — Obtiene el límite de inglete
  • UI\Draw\Stroke::getThickness — Obtiene el grosor
  • UI\Draw\Stroke::setCap — Set Line Cap
  • UI\Draw\Stroke::setJoin — Establece la línea de unión
  • UI\Draw\Stroke::setMiterLimit — Establece el límite de ingletes
  • UI\Draw\Stroke::setThickness — Establece el grosor

User Contributed Notes

There are no user contributed notes for this page.


Construye un nuevo trazo

  • « UI\Draw\Stroke
  • UI\Draw\Stroke::getCap »
  • PHP Manual
  • UI\Draw\Stroke
  • Construye un nuevo trazo

UI\Draw\Stroke::__construct

(UI 0.9.9)

UI\Draw\Stroke::__construct — Construye un nuevo trazo

Descripción

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 )

Construirá un nuevo trazo

Parámetros

cap

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, o UI\Draw\Line\Cap::Square

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, o UI\Draw\Line\Join::Bevel

thickness

El grosor del trazo

miterLimit

Límite de inglete (el valor por defecto es válido para todas las plataformas)

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

Descripción

public UI\Draw\Stroke::getCap ( ) : int

Shall retrieve the line cap setting of this Stroke

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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.


Obtiene la unión de línea

  • « UI\Draw\Stroke::getCap
  • UI\Draw\Stroke::getMiterLimit »
  • PHP Manual
  • UI\Draw\Stroke
  • Obtiene la unión de línea

UI\Draw\Stroke::getJoin

(UI 0.9.9)

UI\Draw\Stroke::getJoin — Obtiene la unión de línea

Descripción

public UI\Draw\Stroke::getJoin ( ) : int

Recuperaremos el ajuste de la línea de unión de este trazo

Parámetros

Esta función no tiene parámetros.

Valores devueltos

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, o UI\Draw\Line\Join::Bevel

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el límite de inglete

  • « UI\Draw\Stroke::getJoin
  • UI\Draw\Stroke::getThickness »
  • PHP Manual
  • UI\Draw\Stroke
  • Obtiene el límite de inglete

UI\Draw\Stroke::getMiterLimit

(UI 0.9.9)

UI\Draw\Stroke::getMiterLimit — Obtiene el límite de inglete

Descripción

public UI\Draw\Stroke::getMiterLimit ( ) : float

Recuperará el límite de ingletes de este trazo

Parámetros

Esta función no tiene parámetros.

Valores devueltos

El actual límite de ingletes

User Contributed Notes

There are no user contributed notes for this page.


Obtiene el grosor

  • « UI\Draw\Stroke::getMiterLimit
  • UI\Draw\Stroke::setCap »
  • PHP Manual
  • UI\Draw\Stroke
  • Obtiene el grosor

UI\Draw\Stroke::getThickness

(UI 0.9.9)

UI\Draw\Stroke::getThickness — Obtiene el grosor

Descripción

public UI\Draw\Stroke::getThickness ( ) : float

Recuperará el grosor de este trazo

Parámetros

Esta función no tiene parámetros.

Valores devueltos

El grosor actual

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

Descripción

public UI\Draw\Stroke::setCap ( int $cap )

Shall set the line cap setting for this Stroke

Parámetros

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.


Establece la línea de unión

  • « UI\Draw\Stroke::setCap
  • UI\Draw\Stroke::setMiterLimit »
  • PHP Manual
  • UI\Draw\Stroke
  • Establece la línea de unión

UI\Draw\Stroke::setJoin

(UI 0.9.9)

UI\Draw\Stroke::setJoin — Establece la línea de unión

Descripción

public UI\Draw\Stroke::setJoin ( int $join )

Establecerá la línea de unión para este trazo

Parámetros

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, o UI\Draw\Line\Join::Bevel

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Establece el límite de ingletes

  • « UI\Draw\Stroke::setJoin
  • UI\Draw\Stroke::setThickness »
  • PHP Manual
  • UI\Draw\Stroke
  • Establece el límite de ingletes

UI\Draw\Stroke::setMiterLimit

(UI 0.9.9)

UI\Draw\Stroke::setMiterLimit — Establece el límite de ingletes

Descripción

public UI\Draw\Stroke::setMiterLimit ( float $limit )

Establece el límite de ingletes para este trazo

Parámetros

limit

El nuevo límite

User Contributed Notes

There are no user contributed notes for this page.


Establece el grosor

  • « UI\Draw\Stroke::setMiterLimit
  • UI\Draw\Brush »
  • PHP Manual
  • UI\Draw\Stroke
  • Establece el grosor

UI\Draw\Stroke::setThickness

(UI 0.9.9)

UI\Draw\Stroke::setThickness — Establece el grosor

Descripción

public UI\Draw\Stroke::setThickness ( float $thickness )

Establecerá el grosor de este trazo

Parámetros

thickness

El nuevo grosor

User Contributed Notes

There are no user contributed notes for this page.


Brushes

(UI 0.9.9)

Introducción

Represents a solid color brush

Sinopsis de la Clase

UI\Draw\Brush {
/* Constructor */
public __construct ( UI\Draw\Color $color )
public __construct ( int $color )
/* Métodos */
public getColor ( ) : UI\Draw\Color
public setColor ( UI\Draw\Color $color ) : void
public setColor ( int $color ) : void
}

Tabla de contenidos

  • 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

Descripción

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

Parámetros

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

Descripción

public UI\Draw\Brush::getColor ( ) : UI\Draw\Color

Shall return a UI\Draw\Color for this brush

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

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

Parámetros

color

Can be a UI\Draw\Color or RRGGBBAA

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Gradient Brushes

(UI 2.0.0)

Introducción

Abstract for gradient brushes

Sinopsis de la Clase

abstract UI\Draw\Brush\Gradient extends UI\Draw\Brush {
/* Métodos */
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étodos heredados */
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
}

Tabla de contenidos

  • 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

Descripción

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

Parámetros

position

The position for the new stop

color

The color for the new stop, may be UI\Draw\Color or RRGGBBAA

Valores devueltos

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

Descripción

public UI\Draw\Brush\Gradient::delStop ( int $index ) : int

Advertencia

Esta función no está documentada actualmente, solamente se encuentra disponible la lista de parámetros.

Parámetros

index

Valores devueltos

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

Descripción

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

Parámetros

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

Valores devueltos

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Linear Gradient

(UI 2.0.0)

Introducción

Sinopsis de la Clase

UI\Draw\Brush\LinearGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct ( UI\Point $start , UI\Point $end )
/* Métodos heredados */
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
}

Tabla de contenidos

  • 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

Descripción

public UI\Draw\Brush\LinearGradient::__construct ( UI\Point $start , UI\Point $end )

Shall construct a new linear gradient

Parámetros

start

end

User Contributed Notes

There are no user contributed notes for this page.


Radial Gradient

(UI 2.0.0)

Introducción

Sinopsis de la Clase

UI\Draw\Brush\RadialGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct ( UI\Point $start , UI\Point $outer , float $radius )
/* Métodos heredados */
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
}

Tabla de contenidos

  • 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

Descripción

public UI\Draw\Brush\RadialGradient::__construct ( UI\Point $start , UI\Point $outer , float $radius )

Shall construct a new radial gradient

Parámetros

start

outer

radius

User Contributed Notes

There are no user contributed notes for this page.


Represents Text Layout

(UI 0.9.9)

Introducción

A Text Layout represents the layout of text which will be drawn by the Pen

Sinopsis de la Clase

UI\Draw\Text\Layout {
/* Constructor */
public __construct ( string $text , UI\Draw\Text\Font $font , float $width )
/* Métodos */
public setColor ( UI\Draw\Color $color , int $start = 0 , int $end = ? )
public setColor ( int $color , int $start = 0 , int $end = ? )
public setWidth ( float $width )
}

Tabla de contenidos

  • UI\Draw\Text\Layout::__construct — Construir un nuevo diseño de texto
  • UI\Draw\Text\Layout::setColor — Establece el color
  • UI\Draw\Text\Layout::setWidth — Establece el ancho

User Contributed Notes

There are no user contributed notes for this page.


Construir un nuevo diseño de texto

  • « UI\Draw\Text\Layout
  • UI\Draw\Text\Layout::setColor »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Construir un nuevo diseño de texto

UI\Draw\Text\Layout::__construct

(UI 0.9.9)

UI\Draw\Text\Layout::__construct — Construir un nuevo diseño de texto

Descripción

public UI\Draw\Text\Layout::__construct ( string $text , UI\Draw\Text\Font $font , float $width )

Construirá un nuevo diseño de texto

Parámetros

text

El texto para el diseño

font

El tipo de letra a utilizar para escribir

width

El ancho del diseño

User Contributed Notes

There are no user contributed notes for this page.


Establece el color

  • « UI\Draw\Text\Layout::__construct
  • UI\Draw\Text\Layout::setWidth »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Establece el color

UI\Draw\Text\Layout::setColor

(UI 0.9.9)

UI\Draw\Text\Layout::setColor — Establece el color

Descripción

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 = ? )

Establecerá el color para todo o un rango del texto en el diseño

Parámetros

color

El color a usar

start

El carácter inicial

end

El carácter final, por defecto el final del string

User Contributed Notes

There are no user contributed notes for this page.


Establece el ancho

  • « UI\Draw\Text\Layout::setColor
  • UI\Draw\Text\Font »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Establece el ancho

UI\Draw\Text\Layout::setWidth

(UI 0.9.9)

UI\Draw\Text\Layout::setWidth — Establece el ancho

Descripción

public UI\Draw\Text\Layout::setWidth ( float $width )

Establecerá el ancho del diseño del texto

Parámetros

width

El nuevo ancho

User Contributed Notes

There are no user contributed notes for this page.


Represents a Font

(UI 0.9.9)

Introducción

Loads a described font

Sinopsis de la Clase

UI\Draw\Text\Font {
/* Constructor */
public __construct ( UI\Draw\Text\Font\Descriptor $descriptor )
/* Métodos */
public getAscent ( ) : float
public getDescent ( ) : float
public getLeading ( ) : float
public getUnderlinePosition ( ) : float
public getUnderlineThickness ( ) : float
}

Tabla de contenidos

  • UI\Draw\Text\Font::__construct — Construye una nueva fuente
  • UI\Draw\Text\Font::getAscent — Métricas de la fuente
  • UI\Draw\Text\Font::getDescent — Métricas de la fuente
  • UI\Draw\Text\Font::getLeading — Métricas de la fuente
  • UI\Draw\Text\Font::getUnderlinePosition — Métricas de la fuente
  • UI\Draw\Text\Font::getUnderlineThickness — Métricas de la fuente

User Contributed Notes

There are no user contributed notes for this page.


Construye una nueva fuente

  • « UI\Draw\Text\Font
  • UI\Draw\Text\Font::getAscent »
  • PHP Manual
  • UI\Draw\Text\Font
  • Construye una nueva fuente

UI\Draw\Text\Font::__construct

(UI 0.9.9)

UI\Draw\Text\Font::__construct — Construye una nueva fuente

Descripción

public UI\Draw\Text\Font::__construct ( UI\Draw\Text\Font\Descriptor $descriptor )

Construirá una nueva fuente usando el descriptor dado

Parámetros

descriptor

El descriptor de la fuente

User Contributed Notes

There are no user contributed notes for this page.


Métricas de la fuente

  • « UI\Draw\Text\Font::__construct
  • UI\Draw\Text\Font::getDescent »
  • PHP Manual
  • UI\Draw\Text\Font
  • Métricas de la fuente

UI\Draw\Text\Font::getAscent

(UI 1.0.3)

UI\Draw\Text\Font::getAscent — Métricas de la fuente

Descripción

public UI\Draw\Text\Font::getAscent ( ) : float

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Métricas de la fuente

  • « UI\Draw\Text\Font::getAscent
  • UI\Draw\Text\Font::getLeading »
  • PHP Manual
  • UI\Draw\Text\Font
  • Métricas de la fuente

UI\Draw\Text\Font::getDescent

(UI 1.0.3)

UI\Draw\Text\Font::getDescent — Métricas de la fuente

Descripción

public UI\Draw\Text\Font::getDescent ( ) : float

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Métricas de la fuente

  • « UI\Draw\Text\Font::getDescent
  • UI\Draw\Text\Font::getUnderlinePosition »
  • PHP Manual
  • UI\Draw\Text\Font
  • Métricas de la fuente

UI\Draw\Text\Font::getLeading

(UI 1.0.3)

UI\Draw\Text\Font::getLeading — Métricas de la fuente

Descripción

public UI\Draw\Text\Font::getLeading ( ) : float

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Métricas de la fuente

  • « UI\Draw\Text\Font::getLeading
  • UI\Draw\Text\Font::getUnderlineThickness »
  • PHP Manual
  • UI\Draw\Text\Font
  • Métricas de la fuente

UI\Draw\Text\Font::getUnderlinePosition

(UI 1.0.3)

UI\Draw\Text\Font::getUnderlinePosition — Métricas de la fuente

Descripción

public UI\Draw\Text\Font::getUnderlinePosition ( ) : float

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Métricas de la fuente

  • « UI\Draw\Text\Font::getUnderlinePosition
  • UI\Draw\Text\Font\Descriptor »
  • PHP Manual
  • UI\Draw\Text\Font
  • Métricas de la fuente

UI\Draw\Text\Font::getUnderlineThickness

(UI 1.0.3)

UI\Draw\Text\Font::getUnderlineThickness — Métricas de la fuente

Descripción

public UI\Draw\Text\Font::getUnderlineThickness ( ) : float

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Font Descriptor

(UI 0.9.9)

Introducción

Describes a font

Sinopsis de la Clase

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étodos */
public getFamily ( ) : string
public getItalic ( ) : int
public getSize ( ) : float
public getStretch ( ) : int
public getWeight ( ) : int
}

Tabla de contenidos

  • 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

Descripción

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

Parámetros

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

Descripción

public UI\Draw\Text\Font\Descriptor::getFamily ( ) : string

Shall return the requested font family

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Draw\Text\Font\Descriptor::getItalic ( ) : int

Shall return constant setting

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Draw\Text\Font\Descriptor::getSize ( ) : float

Shall return the requested size

Parámetros

Esta función no tiene parámetros.

Valores devueltos

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

Descripción

public UI\Draw\Text\Font\Descriptor::getStretch ( ) : int

Shall return requested stretch

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Weight Detection

  • « UI\Draw\Text\Font\Descriptor::getStretch
  • UI Funciones »
  • 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

Descripción

public UI\Draw\Text\Font\Descriptor::getWeight ( ) : int

Shall return requested weight

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


UI Funciones

Tabla de contenidos

  • UI\Draw\Text\Font\fontFamilies — Recuperar las familias de fuentes
  • UI\quit — Quit UI Loop
  • UI\run — Enter UI Loop

User Contributed Notes

There are no user contributed notes for this page.


Recuperar las familias de fuentes

  • « UI Funciones
  • UI\quit »
  • PHP Manual
  • UI Funciones
  • Recuperar las familias de fuentes

UI\Draw\Text\Font\fontFamilies

(UI 0.9.9)

UI\Draw\Text\Font\fontFamilies — Recuperar las familias de fuentes

Descripción

UI\Draw\Text\Font\fontFamilies ( ) : array

Devuelve un array con las familas de fuentes válidas para el sistema actual

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Quit UI Loop

  • « UI\Draw\Text\Font\fontFamilies
  • UI\run »
  • PHP Manual
  • UI Funciones
  • Quit UI Loop

UI\quit

(UI 2.0.0)

UI\quit — Quit UI Loop

Descripción

UI\quit ( ) : void

Shall cause the main loop to be exited

Parámetros

Esta función no tiene parámetros.

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Enter UI Loop

  • « UI\quit
  • UI\Draw\Text\Font\Weight »
  • PHP Manual
  • UI Funciones
  • Enter UI Loop

UI\run

(UI 2.0.0)

UI\run — Enter UI Loop

Descripción

UI\run ( int $flags = ? ) : void

Shall cause PHP to enter into the main loop, by default control will not be returned to the caller

Parámetros

flags

Set UI\Loop to return control, and UI\Wait to return control after waiting

Valores devueltos

User Contributed Notes

There are no user contributed notes for this page.


Font Weight Settings

(UI 0.9.9)

Introducción

Sinopsis de la Clase

final UI\Draw\Text\Font\Weight {
/* Constants */
const int Thin ;
const int UltraLight ;
const int Light ;
const int Book ;
const int Normal ;
const int Medium ;
const int SemiBold ;
const int Bold ;
const int UltraBold ;
const int Heavy ;
const int UltraHeavy ;
}

User Contributed Notes

There are no user contributed notes for this page.


Italic Font Settings

(UI 0.9.9)

Introducción

Sinopsis de la Clase

final UI\Draw\Text\Font\Italic {
/* Constants */
const int Normal = 0 ;
const int Oblique = 1 ;
const int Italic = 2 ;
}

User Contributed Notes

There are no user contributed notes for this page.


Font Stretch Settings

(UI 0.9.9)

Introducción

Sinopsis de la Clase

final UI\Draw\Text\Font\Stretch {
/* Constants */
const int UltraCondensed = 0 ;
const int ExtraCondensed = 1 ;
const int Condensed = 2 ;
const int SemiCondensed = 3 ;
const int Normal = 4 ;
const int SemiExpanded = 5 ;
const int Expanded = 6 ;
const int ExtraExpanded = 7 ;
const int UltraExpanded = 8 ;
}

User Contributed Notes

There are no user contributed notes for this page.


Line Cap Settings

(UI 0.9.9)

Introducción

Sinopsis de la Clase

final UI\Draw\Line\Cap {
/* Constants */
const int Flat ;
const int Round ;
const int Square ;
}

User Contributed Notes

There are no user contributed notes for this page.


Line Join Settings

(UI 0.9.9)

Introducción

Sinopsis de la Clase

final UI\Draw\Line\Join {
/* Constants */
const int Miter ;
const int Round ;
const int Bevel ;
}

User Contributed Notes

There are no user contributed notes for this page.


Key Identifiers

(UI 1.0.0)

Introducción

Sinopsis de la Clase

final UI\Key {
/* Constants */
const int Escape ;
const int Insert ;
const int Delete ;
const int Home ;
const int End ;
const int PageUp ;
const int PageDown ;
const int Up ;
const int Down ;
const int Left ;
const int Right ;
const int F1 ;
const int F2 ;
const int F3 ;
const int F4 ;
const int F5 ;
const int F6 ;
const int F7 ;
const int F8 ;
const int F9 ;
const int F10 ;
const int F11 ;
const int F12 ;
const int N0 ;
const int N1 ;
const int N2 ;
const int N3 ;
const int N4 ;
const int N5 ;
const int N6 ;
const int N7 ;
const int N8 ;
const int N9 ;
const int NDot ;
const int NEnter ;
const int NAdd ;
const int NSubtract ;
const int NMultiply ;
const int NDivide ;
}

User Contributed Notes

There are no user contributed notes for this page.


InvalidArgumentException

(UI 1.0.3)

Introducción

Sinopsis de la Clase

UI\Exception\InvalidArgumentException extends InvalidArgumentException implements Throwable {
/* Propiedades heredadas */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Métodos heredados */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

User Contributed Notes

There are no user contributed notes for this page.


RuntimeException

(UI 1.0.3)

Introducción

Sinopsis de la Clase

UI\Exception\RuntimeException extends RuntimeException implements Throwable {
/* Propiedades heredadas */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Métodos heredados */
final public Exception::getMessage ( ) : string
final public Exception::getPrevious ( ) : Throwable
final public Exception::getCode ( ) : mixed
final public Exception::getFile ( ) : string
final public Exception::getLine ( ) : int
final public Exception::getTrace ( ) : array
final public Exception::getTraceAsString ( ) : string
public Exception::__toString ( ) : string
final private Exception::__clone ( ) : void
}

User Contributed Notes

There are no user contributed notes for this page.


FAQ: Preguntas frequentes

  • Información general
  • Listas de correos
  • Consiguiendo PHP
  • Problemas con bases de datos
  • Instalación
  • Problemas de Compilación
  • Utilizar PHP
  • Hash de Contraseñas — Hash de contraseñas seguro
  • PHP y HTML
  • PHP y COM
  • Preguntas Varias

User Contributed Notes

There are no user contributed notes for this page.


Información general

Esta sección contiene las preguntas más generales sobre PHP: Qué es y qué hace.

  1. ¿Qué es PHP?
  2. ¿Qué significa PHP?
  3. ¿Cuál es la relación entre las versiones?
  4. ¿Puedo usar varias versiones de PHP al mismo tiempo?
  5. ¡Creo que he encontrado un error! ¿A quién debo informar?
¿Qué es PHP?

Según el prefacio del manual:

PHP es un lenguaje de «scripting» que puede ser embebido en HTML. Gran parte de su sintaxis se toma prestada de C, Java y Perl con un par de características específicas propias de PHP. El objetivo del lenguaje es permitir a los desarrolladores web escribir con rapidez páginas generadas dinámicamente.

¿Qué significa PHP?

PHP significa PHP: Hypertext Preprocessor. Esto confunde a mucha gente porque la primera palabra del acrónimo es el acrónimo mismo. Este tipo de acrónimo se denomina 'acrónimo recursivo'. Para más información, los curiosos pueden visitar » El Diccionario de Informática On-Line Gratuito ó la » entrada de acrónimo recursivo en Wikipedia (ambos en inglés).

¿Cuál es la relación entre las versiones?

PHP/FI 2.0 es una versión de PHP antigua y sin soporte. PHP 3 es el sucesor de PHP/FI 2.0 y es mucho mejor. PHP 7 es la generación actual de PHP, la cual emplea el Motor Zend 3 que, entre otras cosas, ofrece muchas características adicionales de POO.

¿Puedo usar varias versiones de PHP al mismo tiempo?

Sí. Vea el fichero INSTALL que se incluye en la distribución del código fuente de PHP.

¡Creo que he encontrado un error! ¿A quién debo informar?

Debería ir a la Base de datos de errores de PHP y asegurarse de que no se trate de un error ya descubierto. Si no lo encuentra en la Base de datos, use el formulario de notificación para informar del error. Es importante que utilice la Base de datos de errores en vez de solamente enviar un correo electrónico a una de las listas de correo, ya que así al error se le asignará un número de seguimiento, pudiendo volver luego y comprobar el estado de dicho error. La Base de datos de errores de PHP se encuentra en » https://bugs.php.net/.

User Contributed Notes

There are no user contributed notes for this page.


Listas de correos

Esta sección contiene preguntas acerca de cómo ponerse en contacto con la comunidad de PHP. La mejor forma es a través de las listas de correos.

  1. ¿Existen listas de correos de PHP?
  2. ¿Existen otras comunidades?
  3. ¿Puedo crear mi propia lista de correos de PHP?
  4. ¡Ayuda! ¡Aparentemente no puedo iniciar/cancelar suscripciones en una de las listas de correos!
  5. ¿Existe un archivo de las listas de correos en alguna parte?
  6. ¿Qué puedo preguntar en la lista de correos?
  7. ¿Qué información debo incluir cuando envío mensajes a las listas de correos?
¿Existen listas de correos de PHP?

¡Por supuesto! Hay listas de correos para diferentes asuntos. Las listas de correos más comunes de la comunidad se pueden encontrar en nuestra página de » Listas de correos.

La lista de correos más general es php-general. Para suscribirse, envíe un correo electrónico en blanco a » php-general-subscribe@lists.php.net. Para anular su suscripción, envíe un correo electrónico en blanco a » php-general-unsubscribe@lists.php.net.

También puede iniciar y cancelar suscripciones usando la interfaz web de nuestra página » Listas de correos. También se incluyen instrucciones para darse de baja al final de cada mensaje de las listas de correos.

¿Existen otras comunidades?

Hay un sinnúmero de comunidades de PHP alrededor del mundo, y tenemos vínculos con algunos de estos recursos (asi como información sobre cómo averiguar más) en nuestra página de » Soporte.

¿Puedo crear mi propia lista de correos de PHP?

¡Absolutamente! De hecho, no sólo lo permitimos libremente, lo apoyamos! Ayudando a otros compartiendo su conocimiento y experiencia sobre PHP ayuda a fomentar el crecimiento y desarrollo de la comunidad mundial de PHP y del lenguaje en sí.

¡Ayuda! ¡Aparentemente no puedo iniciar/cancelar suscripciones en una de las listas de correos!

Si tiene problemas con la suscripción o la baja de una suscripción en una lista de correos, puede ser porque el software de la lista de correos no entiende la correcta dirección de e-mail a utilizar. Si su dirección es joeblow@example.com, y está intentando suscribirse a php-general, puede enviar su solicitud de suscripción a php-general-subscribe-joeblow=example.com@lists.php.net, o su solicitud de baja a php-general-unsubscribe-joeblow=example.com@lists.php.net. Use direcciones similares para otras listas de correos.

La causa más común por la que la gente tiene problemas a la hora de darse de baja de nuestras listas de correos se debe al reenvío de correos. Por ejemplo, si su e-mail es danbrown@example.com, pero se suscribió a la lista de correos con el redireccionador php-lists@example.com y reenvía eso a danbrown@example.com, intentar dar de baja a danbrown@example.com no funcionará, ya que esa dirección no existe en nuestros sistemas. En cambio, necesitará dar de baja la dirección de la que haya sido enviado el correo de suscripción - en este caso, php-lists@example.com.

¿Existe un archivo de las listas de correos en alguna parte?

Si, encontrará vínculos a algunos sitios que mantienen archivos en la sección » Listas de correos. También encontrará decenas de Sitios que archivan y/o sindican el contenido de nuestra lista de correos usando su Motor de Búsqueda de Internet favorito y buscando "archivos de la lista de correos de php".

Todos los artículos de las listas de correos son también archivados como noticias. Puede acceder al servidor de noticias en » news://news.php.net/ con un cliente de este servicio. También existe una interfaz web experimental para el servidor de noticias en » http://news.php.net/

¿Qué puedo preguntar en la lista de correos?

Dado que PHP está creciendo más y más cada día, el tráfico en la lista de correos php-general se ha incrementado, yendo de 75 a 200 o más mensajes por día. Debido a esto, es del interés de todos que sólo use la lista como último recurso, una vez haya probado todos los demás caminos.

Antes de enviar su consulta a la lista por favor eche un vistazo a esta FAQ y al manual para ver si puede encontrar ayuda en tales sitios. Si no encuentra nada, pruebe con los archivos de las listas de correos (vea más arriba). Si tiene problemas con la instalación o configuración de PHP, por favor lea en su totalidad la documentación incluida y los documentos README. Si todavía no puede encontrar información alguna que le ayude, es más que bienvenido para usar la lista de correos apropiada.

Para asegurarse de que reciba las mejores respuestas (y recudir la probabilidad de frustrar a sus compañeros), por favor tenga en cuenta enviar la pregunta a la lista correspondiente. Por ejemplo, si está teniendo dificultades instalando PHP, debería enviar su consulta a la lista de correos php-install. Una advertencia: algunas listas tienen nombres similares y usos totalmente diferentes; una consulta respecto scripts PHP en Windows debería ser dirigida a la lista de usuarios de PHP en Windows, no a la lista del Funcionamiento Interno de Windows.

Antes de consultar, puede que sea de su interés leer el artículo » Cómo formular preguntas inteligentemente, ya que es una buena idea para todos.

¿Qué información debo incluir cuando envío mensajes a las listas de correos?

Mensajes como "¡No logro que PHP funcione! ¡Ayúdenme! ¿Qué está mal?" son absolutamente inútiles para todos. Si está sufriendo dificultades con la ejecución y configuración de PHP debe incluir el sistema operativo que está usando, la versión de PHP que está tratando de utilizar, de qué forma adquirió el software (pre-compilada, Git, RPM, etc.), qué ha hecho hasta el momento, y el mensaje de error exacto o el resultado actual.

Esto se aplica también para cualquier otro problema: debe incluir una explicación de qué ha hecho, qué está tratando de hacer, y algún mensaje de error encontrado en el proceso. Si tiene problemas con su código fuente, debería incluir la parte del código que no funciona, indicando en que línea se encuentra el error mediante un comentario apropiadamente situado. ¡No incluya más código del necesario! Eso hace al mensaje difícil de leer, y mayoría puede simplemente ignorarlo por esta razón. Si no está seguro de cuánta información debería ser incluida, envie lo que crea de relevancia significativa a su problema actual, y preparese para dar más datos sobre su solicitud.

Otro punto importante a tener en mente es hacer un resumen de su problema en el asunto del mensaje. Un asunto como "AYUUDAAAA!!!" o "¿Cuál es el problema aquí?" será ignorado por la mayoría de los lectores.

Y por último, es recomendable que lea el artículo » Cómo formular preguntas inteligentemente, debido a que será de gran ayuda para todos, especialmente para Ud. mismo.

User Contributed Notes

There are no user contributed notes for this page.


Consiguiendo PHP

Esta sección contiene detalles sobre las ubicaciones de descarga de PHP, y asuntos específicos a diferentes sistemas operativos.

  1. ¿Donde puedo conseguir PHP?
  2. ¿Hay versiones binarias pre-compiladas disponibles?
  3. ¿Donde consigo las bibliotecas requeridas para compilar algunas de las extensiones opcionales de PHP?
  4. ¿Cómo hago para que esas bibliotecas funcionen?
  5. He conseguido la última versión del código fuente de PHP desde el repositorio Git en mi máquina Windows, ¿Qué necesito para su compilación?
  6. ¿Dónde consigo el Archivo de Capacidades del Explorador?
  7. ¿Que significa thread safety cuando se descarga PHP?
¿Donde puedo conseguir PHP?

Se puede descargar PHP desde cualquier miembro de la red de Sitios de PHP. Estos se pueden encontrar en » https://www.php.net/. También puede utilizar Git anónimo para conseguir la última versión del código fuente. Para mayor información, visite » https://www.php.net/git.php.

¿Hay versiones binarias pre-compiladas disponibles?

Nosotros solo distribuímos binarios pre-compilados para sistemas Windows, debido a que no tenemos la capacidad de compilar PHP para cada plataforma popular Linux/Unix con todas las combinaciones de extensiones. También tenga en cuenta que muchas distribuciones Linux actualmente vienen con PHP integrado. Los binarios para Windows pueden ser descargados desde nuestra página de » Descargas. Para binarios de Linux, por favor visite el sitio de su distribución.

¿Donde consigo las bibliotecas requeridas para compilar algunas de las extensiones opcionales de PHP?

Nota: Aquellas marcadas con * no son seguras a nivel de hilos; no se recomienda su uso en entornos multihilo.

  • » LDAP (Unix).
  • » LDAP (Unix/Win) : Directorio de Mozilla (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 localmente.
  • » FreeType (libttf):.
  • » ZLib (Unix/Win32).
  • » expat XML parser (Unix/Win32).
  • » PDFLib.
  • » mcrypt.
  • » mhash.
  • » t1lib.
  • » dmalloc.
  • » aspell.
  • » readline.

¿Cómo hago para que esas bibliotecas funcionen?

Necesitará seguir las instrucciones provistas en la biblioteca. Algunas de estas bibliotecas son detectadas automáticamente cuando ejecuta el script 'configure' de PHP (tal como la biblioteca GD), y otras tendran que ser habilitadas usando opciones '--with-EXTENSION' con 'configure'. Ejecute 'configure --help' para una lista de estas opciones.

He conseguido la última versión del código fuente de PHP desde el repositorio Git en mi máquina Windows, ¿Qué necesito para su compilación?

Véase al wiki de PHP para las últimas instrucciones: » Instrucciones de construcción paso a paso

¿Dónde consigo el Archivo de Capacidades del Explorador?

Se puede encontrar el archivo browscap.ini en » http://browscap.org/.

¿Que significa thread safety cuando se descarga PHP?

Thread Safety significa que el binario puede funcionar en un servidor multi-hilo como por ejemplo bajo Apache 2 para windows.Thread Safety funciona creando una copia local de almacenamiento para cada hilo, de manera que los datos no colisionarán con otros hilos.

Entonces ¿que necesito? Si se elige ejecutar PHP como binario CGI, entonces no se necesita thread safety, por que el binario es invocado en cada petición. Para servidores multi-hilo, como IIS5 y IIS6 se debe utilizar la versión threaded de PHP.

User Contributed Notes

There are no user contributed notes for this page.


Problemas con bases de datos

Esta sección contiene preguntas comunes sobre la relación entre PHP y bases de datos. Sí, PHP puede acceder a prácticamente cualquier base de datos disponible hoy en día.

  1. He escuchado que es posible acceder a Microsoft SQL Server desde PHP. ¿Cómo?
  2. ¿Puedo acceder a bases de datos Microsoft Access?
  3. ¿Por qué el uso de la extensión MySQL (ext/mysql), que he utilizado durante más de 10 años, está desaconsejado? ¿Está obsoleta? ¿Qué utilizo en su lugar? ¿Cómo puedo migrar?
  4. ¿Porqué recibo un error que luce algo así: "Warning: 0 is not a MySQL result index in <archivo> on line <x>" o "Warning: Supplied argument is not a valid MySQL result resource in <archivo> on line <x>"?
He escuchado que es posible acceder a Microsoft SQL Server desde PHP. ¿Cómo?

En máquinas Unix se puede usar PDO_ODBC o la API ODBC Unificada.

En máquinas Windows se puede usar PDO_SQLSRV o SQLSRV.

Consulte también la respuesta de la siguiente pregunta.

¿Puedo acceder a bases de datos Microsoft Access?

Si. Usted ya dispone de todas las herramientas necesarias si está corriendo enteramente bajo Windows 9x/Me, o NT/2000, en donde es posible utilizar ODBC y los controladores ODBC para bases de datos Microsoft Access.

Si está corriendo PHP en una máquina Unix y desea comunicarse con MS Access en Windows, necesitará controladores ODBC para Unix. » OpenLink Software tiene controladores ODBC basados en Unix que tienen esa capacidad.

Otra alternativa consiste en usar un servidor SQL que tenga controladores ODBC Windows y usarlo para almacenar los datos, a los cuales puede acceder desde Microsoft Access (usando ODBC) y PHP (usando los controladores incorporados), o usar un formato de archivo intermedio que Access y PHP entiendan, como archivos planos o bases de datos dBase. Sobre este punto, Tim Hayes de OpenLink Software escribe:

Usar otra base de datos como intermediario no es una buena idea, cuando es posible usar ODBC desde PHP directamente a su base de datos, es decir, con los controladores de OpenLink. Si realmente necesita usar un formato de archivo intermedio, OpenLink ha lanzado ahora Virtuoso (un motor de bases de datos virtual) para NT, Linux y otras plataformas Unix. Por favor visite nuestro » sitio web para una descarga gratuita.

Una opción que ha sido probada con éxito es usar MySQL y sus controladores MyODBC en Windows y sincronizar las bases de datos. Steve Lawrence escribe:

  • Instale MySQL en su plataforma de acuerdo a las instrucciones de MySQL. La última versión disponible se encuentra en » http://www.mysql.com/. No se requiere ninguna configuración especial, exceptuando al momento de configurar una base de datos, y al configurar la cuenta de usuario, debe poner % en el campo de host, o el nombre del host del equipo Windows desde el que desea acceder a MySQL. Anote su nombre de servidor, nombre de usuario y contraseña.
  • Descargue el controlador MyODBC para Windows desde el sitio de MySQL. Instálelo en su equipo Windows. Es posible probar su operación con las utilidades incluidas con este programa.
  • Cree un usuario o dsn de sistema en su administrador de ODBC, ubicado en el panel de control. Cree un nombre dsn, ingrese su nombre de host, nombre de usuario, contraseña, puerto, etc. para su base de datos MySQL configurada en el paso 1.
  • Instale Access usando la instalación completa, esto asegura que tenga las elementos adicionales apropiados... por lo menos requerirá el soporte ODBC y el gestor de tablas enlazadas.
  • ¡Ahora la parte divertida! Cree una nueva base de datos Access. En la ventana de tabla use el clic derecho y seleccione Enlazar Tablas, o bajo la opción del menú de archivo, seleccione Obtener Datos Externos y luego Enlazar Tablas. Cuando el cuadro de navegación de archivos aparezca, seleccione archivos de tipo: ODBC. Seleccione dsn de Sistema y el nombre de su dsn creado en el paso 3. Seleccione la tabla a enlazar, presione Aceptar, y ¡listo! ¡Ahora es posible abrir la tabla y agregar/eliminar/editar datos en su servidor MySQL! También es posible construir consultas, importar/exportar tablas a MySQL, construir formularios y reportes, etc.

Consejos y Trucos:

  • Es posible construir sus tablas en Access y exportarlas a MySQL, y luego enlazarlas de vuelta. Esto facilita la rápida creación de tablas.
  • Cuando se crean tablas en Access, es necesario tener una clave primaria definida para tener acceso de escritura a la tabla en Access. Asegúrese de crear una clave primaria en MySQL antes de enlazar en Access.
  • Si modifica una tabla en MySQL, es necesario re-enlazarla en Access. Diríjase a Herramientas>Adiciones>Gestor de Tablas Enlazadas, vaya a su DSN ODBC, y seleccione la tabla a re-enlazar desde allí. También es posible transladar su fuente dsn allí, simplemente active el cuadro de verificación "siempre preguntar por una ubicación nueva" antes de presionar Aceptar.

¿Por qué el uso de la extensión MySQL (ext/mysql), que he utilizado durante más de 10 años, está desaconsejado? ¿Está obsoleta? ¿Qué utilizo en su lugar? ¿Cómo puedo migrar?

Existen tres extensiones de MySQL, como está descrito en la sección Elegir una API de MySQL. No se debe usar la API antigua, está obsoletea a partir de PHP 5.5.0 y ha sido movida a PECL a paritr de PHP 7.0.0. Se recomienda encarecidamente escribir todo el código nuevo con mysqli o PDO_MySQL.

La migración de los scripts no está disponible por el momento, aunque la API mysqli API contiene tanto una API procedimental como una API POO, siendo la versión procedimental similar a ext/mysql.

No es posible mezclar extensiones. Así, por ejemplo, pasar una conexión mysqli a PDO_MySQL o ext/mysql no funcionará.

¿Porqué recibo un error que luce algo así: "Warning: 0 is not a MySQL result index in <archivo> on line <x>" o "Warning: Supplied argument is not a valid MySQL result resource in <archivo> on line <x>"?

Está intentando usar un identificador de resultado que es 0. El 0 indica que su consulta falló por alguna razón. Necesita verificar errores después de enviar una consulta y antes de que intente usar el identificador de resultado devuelto. La manera apropiada de hacerlo es con un código similar al siguiente:

<?php

$resultado = mysql_query("SELECT * FROM tablas_priv");
if (!$resultado) {
    echo mysql_error();
    exit;
}
?>
o
<?php

$resultado = mysql_query("SELECT * FROM tablas_priv")
    or die("Consulta fallida: " . mysql_error());
?>

User Contributed Notes

doug at unlikelysource dot com 31-Mar-2017 08:53
To enable SQL Server access from ubuntu 16.04:

* Run these commands:
```
sudo curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > mssql-release.list
sudo mv mssql-release.list /etc/apt/sources.list.d
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install msodbcsql unixodbc-dev
sudo apt-get install php7.1-dev
sudo apt-get install autoconf
sudo pecl install pdo_sqlsrv-4.1.6.1
```

*  Confirm ODBC driver installation:
```
odbcinst -q -d -n "ODBC Driver 13 for SQL Server"
```

* Update the php.ini file: run` php --ini` to find the path to your php.ini file
* Add this line to /path/to/php.ini
```
extension=pdo_sqlsrv.so
```
* Run `php -i` to confirm SQLSRV support was added
* NOTE: extensions (on my computer) were installed here:
`/usr/local/lib/php/extensions/no-debug-non-zts-20160303/`

* Test user access directly on the Windows server running MSSQL:
```
sqlcmd -S ip_address -U username -P password -d database -q "select * from table_name"
```
* On the Windows server: open port 1433 in your firewall

* Install the FreeTds utils to test the connection:
```
sudo apt-get install freetds-bin
tsql -H mssql.host.ip.address -U username -P password -D database -p 1433
```

* Formulate the correct DSN (Data Source Name):
    See: http://php.net/manual/en/ref.pdo-sqlsrv.connection.php

* Sample PHP Code:
```
<?php
// Database params
$tcp  = '192.168.3.126';
$port = 1433;
$user = "test";
$password = "Password123";
$database = "test";

// Open connection
try {
    // Database connect -- use one of the two statements below
    $dsn =  'sqlsrv:Server=tcp:' . $tcp . ',' . $port . ';Database=' . $database;
    $dbh = new PDO( $dsn, $user, $password, array());
    // SQL prepare
    $sql = "SELECT * FROM prospects";
    $sth = $dbh->prepare($sql);
    // Execute
    $sth->execute();
    // Fetch results
    $row = $sth->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        $output = '<pre>';
        $output .= implode("\t", array_keys($row)) . PHP_EOL;
        $output .= implode("\t", $row) . PHP_EOL;
        while ($row = $sth->fetch(PDO::FETCH_NUM)) {
            $output .= implode("\t", $row) . PHP_EOL;
        }
    }
} catch (PDOException $e) {
    $output .= $e->getMessage();
}
$output .= '</pre>';
echo $output;
```
knb at gfz-potsdam dot de 11-Oct-2004 02:53
This is a crucial piece of information for SYBASE users:

If you are using the free, but old, 11.x client libs from sybase,
 then compile with option  "--with-sybase-ct=$SYBASE"
substitute $SYBASE with the appropriate directory name.

option --with-sybase (without ct) can somehow be used to talk to old MS-SQL servers, but only with the 11.x client libs.

If you are using free, or have legally obtained, 12.x client libs from sybase, then compile with option  "--with-sybase-ct=$SYBASE/$SYBASE_OCS"
substitute $SYBASE/$SYBASE_OCS with the appropriate directory name.


Instalación

Esta sección contiene preguntas comunes sobre la forma de instalar PHP. Este está disponible para casi cualquier SO y casi cualquier servidor web.

Para instalar PHP, siga las instrucciones de Instalación y configuración.

  1. ¿Por qué no debe utilizarse Apache2 con un MPM con hilos en un entorno de producción?
  2. Unix/Windows: ¿Donde debería ubicarse mi fichero php.ini?
  3. Unix: He instalado PHP, pero con cada documento que cargo, obtengo el mensaje 'Document Contains No Data'. ¿Qué está pasando?
  4. Unix: He instalado PHP usando paquetes RPM, pero Apache no procesa los las páginas de PHP. ¿Qué está pasando?
  5. Unix: Le he aplicado a Apache el parche de extensiones de FrontPage, y de pronto PHP dejó de funcionar. ¿Acaso PHP es incompatible con las extensiones de FrontPage para Apache?
  6. Unix/Windows: He inslatado PHP, pero cuando intento acceder a ficheros de script de PHP a través de mi navegador obtengo la pantalla en blanco.
  7. Unix/Windows: He instalado PHP, pero cuando intento acceder a un fichero de script de PHP a través de mi navegador, obtengo un error 500 del servidor.
  8. Algunos sistemas operativos: He instalado PHP sin errores, pero cuando intento iniciar Apache, obtengo errores de Símbolos no definidos: [mybox:user /src/php5] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress
  9. Windows: He instalado PHP, pero cuando intento acceder a un fichero de script de PHP a través de mi navegador, obtengo el error: cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
  10. Windows: He seguido todas las instrucciones, pero todavía no puedo hacer que PHP e IIS funcionen juntos.
  11. Cuando ejecuto PHP como CGI con IIS, PWS, OmniHTTPD o Xitami, obtengo el siguiente error: Security Alert! PHP CGI cannot be accessed directly..
  12. ¿Cómo sé si mi php.ini se ha encontrado y se está leyendo? Parece como si no lo fuera, ya que los cambios que realizo no se implementan.
  13. ¿Cómo agrego mi directorio de PHP a PATH en Windows?
  14. ¿Cómo hago que el fichero php.ini esté disponible para PHP en Windows?
  15. ¿Es posible usar la negociación de contenidos de Apache (opción MultiViews) con PHP?
  16. ¿PHP se limita a procesar únicamente métodos de peticiones GET y POST?
¿Por qué no debe utilizarse Apache2 con un MPM con hilos en un entorno de producción?

PHP es el «pegamento» utilizado para desarrollar buenas aplicaciones web uniendo docenas de bibliotecas de terceros y haciéndolas que parezcan una entidad coherente a través de una interfaz de lenguaje intuitiva y fácil de aprender. La flexibilidad y la potencia de PHP residen en la estabilidad y robustez de la plataforma subyacente. Requiere la combinación de un SO, de un servidor web y de bibliotecas de terceros, todos correctamente funcionando. Cuando cualquiera de ellos deja de funcionar, PHP necesita identificar los problemas y corregirlos rápidamente. Cuando el marco de trabajo subyacente se hace más complejo al no tener hilos de ejecución completamente independientes, segementos de memoria completamente independientes y un fuerte entorno de pruebas por cada petición a cubrir, se introducirán más debilidades en el sistema de PHP.

Si desea utilizar un MPM con hilos, considere una configuración de FastCGI donde PHP se ejecute en su propio espacio de memoria.

Unix/Windows: ¿Donde debería ubicarse mi fichero php.ini?

Por defecto, en Unix debería estar en /usr/local/lib, lo que es <install-path>/lib. Para cambiar esta ruta durante la compilación se ha de usar la bandera --with-config-file-path. Se debería establecer a algo como por ejemplo:

--with-config-file-path=/etc
Luego se debería copiar el fichero php.ini-development de la distribución a /etc/php.ini y editarlo para realizar cualquier cambio necesario.

--with-config-file-scan-dir=PATH

En Windows, la ruta predeterminada para el fichero php.ini es el directorio Windows. Si se utiliza el servidor web Apache, php.ini se busca primero en el directorio de instalación de Apache, p. ej. en C:\Archivos de programa\Apache Group\Apache. De esta forma se pueden tener distintos ficheros php.ini para diferentes versiones de Apache en la misma máquina.

Véase también el capítulo sobre el fichero de configuración.

Unix: He instalado PHP, pero con cada documento que cargo, obtengo el mensaje 'Document Contains No Data'. ¿Qué está pasando?

Esto probablemente signifique que PHP esté teniendo algún tipo de problema y esté realizando un volcado de memoria. Revise el registro de errores del servidor para ver si este es el caso, y después intente reproducir el problema con una pequeña prueba. Si sabe cómo usar 'gdb', le será de gran ayuda al poder proporcionar la traza de la pila con el informe de errores para que los desarrolladores puedan precisar el origen del problema. Si está utilizando PHP como un módulo de Apache, intente algo así:

  • Detener los procesos httpd

  • gdb httpd

  • Detener los procesos httpd

  • > run -X -f /ruta/al/httpd.conf

  • Luego obtenga el URL que causa el problema con su explorador

  • > run -X -f /ruta/al/httpd.conf

  • Si resulta en un volcado de memoria, gdb debería informárselo al instante

  • escriba: bt

  • Debería incluir la traza en su informe de errores, el cual debe ser enviado a » https://bugs.php.net/

Si su script utiliza las funciones de expresiones regulares (preg_match() y similares), debería asegurarse de que PHP y Apache se compilaron con los mismos paquetes de expresiones regulares. Esto debería ocurrir automáticamente con PHP y Apache 1.3.x

Unix: He instalado PHP usando paquetes RPM, pero Apache no procesa los las páginas de PHP. ¿Qué está pasando?

Asumiendo que instaló tanto Apache como PHP desde paquetes RPM, necesita descomentar o agregar algunas o todas de las siguientes líneas en su fichero 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
Y agregar:
AddType application/x-httpd-php .php
a las propiedades globales, o a las propiedades del VirtualDomain que desee que tenga añadido el soporte para PHP.

Unix: Le he aplicado a Apache el parche de extensiones de FrontPage, y de pronto PHP dejó de funcionar. ¿Acaso PHP es incompatible con las extensiones de FrontPage para Apache?

No, PHP funciona bien con las extensiones de FrontPage. El problema radica en que dicho parche modifica varias estructuras de Apache de las que depende PHP. La recompilación de PHP (con 'make clean ; make') tras la aplicación del parche debería resolver el problema.

Unix/Windows: He inslatado PHP, pero cuando intento acceder a ficheros de script de PHP a través de mi navegador obtengo la pantalla en blanco.

Ejecute 'ver código fuente' en el navegador web y probablemente encontrará que puede ver el código fuente de su script de PHP. Esto significa que el servidor web no envió el script a PHP para interpretarlo. Algo está mal en la configuración del servidor: vuelva a comprobarla con respecto a las instrucciones de instalación de PHP.

Unix/Windows: He instalado PHP, pero cuando intento acceder a un fichero de script de PHP a través de mi navegador, obtengo un error 500 del servidor.

Algo falló cuando el servidor intentó ejecutar PHP. Para obtener un mensaje de error detallado desde la línea de comandos, vaya al directorio que tiene el ejecutable de PHP (php.exe en Windows) y ejecute php -i. Si PHP tiene problemas al ejecutarse, el correspondiente error será mostrado en pantalla proporcionando una pista sobre lo que debe hacer a continuación. Si obtiene una pantalla completa de código HTML (la salida de la función phpinfo()) es porque PHP está funcionando, y su problema puede estar relacionado con la configuración del servidor, la cual debería de volver a revisar.

Algunos sistemas operativos: He instalado PHP sin errores, pero cuando intento iniciar Apache, obtengo errores de Símbolos no definidos:
[mybox:user /src/php5] root# apachectl configtest
      apachectl: /usr/local/apache/bin/httpd Undefined symbols:
      _compress
      _uncompress

Esto, en realidad, no tiene nada que ver con PHP, sino con las bibliotecas cliente de MySQL. Algunas necesitan --with-zlib, otras no. Esto también se trata en las Preguntas frecuentes de MySQL.

Windows: He instalado PHP, pero cuando intento acceder a un fichero de script de PHP a través de mi navegador, obtengo el error:
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

Este mensaje de error significa que PHP no pudo imprimir nada. Para obtener un mensaje de error detallado desde la línea de comandos, vaya al directorio que contiene el ejecutable de PHP (php.exe en Windows) y ejecute php -i. Si PHP tiene problemas al ejecutarse, el correspondiente error será mostrado en pantalla proporcionando una pista sobre lo que debe hacer a continuación. Si obtiene una pantalla completa de código HTML (la salida de la función phpinfo()) es porque PHP está funcionando.

Una vez que PHP esté funcionando desde la línea de comandos, intente acceder nuevamente al script a través de su navegador. Si continúa fallando, podría ser por una de las siguientes razones:

  • Los permisos de fichero en el script de PHP, php.exe, php5ts.dll, php.ini o cualquier extensión de PHP que esté intentando cargar, son tales que el usuario de internet anónimo ISUR_<machinename> no puede acceder a ellos.
  • El fichero de script no existe (o quizá no se ubique en donde usted cree que está en relación a su directorio raíz web). Observe que para IIS se puede manejar este error señalando la casilla 'comprobar si el fichero existe' al configurar la correspondencia de scripts en el Administrador de Servicios de Internet. Si un fichero de script no existe, el servidor devolverá un error HTTP 404 en su lugar. IIS también brinda el beneficio adicional de encargarse de cualquier autenticación requerida de forma automática basándose en lospermisos NTLanMan de su fichero de script.
Windows: He seguido todas las instrucciones, pero todavía no puedo hacer que PHP e IIS funcionen juntos.

Asegúrese de que todo usuario que necesite ejecutar un script de PHP tenga los permisos para ejecutar php.exe. IIS utiliza un usuario anónimo que se añade en el momento de su instalación. Este usuario necesita permisos para php.exe. Además, cualquier usuario autenticado necesitará permisos para poder ejecutar php.exe. Asimismo, es necesario indicarle a IIS4 que PHP es un motor de script. Le podría interesar leer también estas preguntas frecuentes.

Cuando ejecuto PHP como CGI con IIS, PWS, OmniHTTPD o Xitami, obtengo el siguiente error: Security Alert! PHP CGI cannot be accessed directly..

La directiva cgi.force_redirect debe establecerse a 0. Por defecto es 1, por lo que debe asegurarse de que no esté comentada (con un ;). Como todas las directivas, se configura en php.ini

Debido a que su valor predeterminado es 1, es crítico asegurarse al 100% de estar leyendo el fichero php.ini correcto. Lea estas preguntas frecuentes para más detalles.

¿Cómo sé si mi php.ini se ha encontrado y se está leyendo? Parece como si no lo fuera, ya que los cambios que realizo no se implementan.

Para asegurarse de que PHP está leyendo su php.ini, realice una llamada a phpinfo(). Cerca de la parte superior, habrá una lista llamada Configuration File (php.ini). Allí figurará dónde está buscando PHP el php.ini y si está siendo leído o no. Si existe solo un directorio en PATH, entonces PHP no está leyéndolo, por lo que debería colocar su php.ini en tal directorio. Si php.ini está incluido dentro de PATH, es que se está leyendo.

Si php.ini está siendo leído y PHP se está ejecutando como un módulo, deberá reiniciar su servidor web tras aplicar los cambios a php.ini

Véase también php_ini_loaded_file().

¿Cómo agrego mi directorio de PHP a PATH en Windows?

En Windows 7, XP, Vista, 2008, 2012 y siguientes:

  • Vaya a Panel de Control y abra el icono Sistema (Inicio ? Panel de control)

  • Vaya a la pestaña Avanzado

  • Haga clic en el botón 'Variables de Entorno'

  • Revise la parte de 'Variables de Sistema'

  • Encuentre la entrada Path (seguramente tendrá que desplazarse para encontrarla)

  • Haga doble clic en la entrada Path

  • Ingrese su directorio de PHP al final de todo, con un ';' antes (p.ej., ;C:\php)

  • Presione OK

En Windows 98/Me necesita editar el fichero autoexec.bat:

  • Abra el Bloc de Notas (Inicio ? Ejecutar y escriba notepad)

  • Abra el fichero C:\autoexec.bat

  • Localice la línea con PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;..... y agregue: ;C:\php al final de la misma

  • Guarde el fichero y reinicie la máquina

Nota: Asegúrese de reiniciar tras seguir los pasos anteriores para garantizar que se apliquen los cambios a PATH.

El manual de PHP solía promover el copiado de ficheros dentro del directorio de sistema de Windows. Esto es porque este directorio (C:\Windows, C:\WINNT, etc.) está por defecto en el PATH del sistema. La copia de ficheros dentro del directorio de sistema de Windows hace tiempo que ya no se utiliza ya que puede causar problemas.

¿Cómo hago que el fichero php.ini esté disponible para PHP en Windows?

Hay varias formas de hacerlo. Si está usando Apache, lea las instrucciones específicas de instalación (Apache 1, Apache 2), o de lo contrario, debe configurar la variable de entorno PHPRC:

En Windows:

  • Vaya a Panel de Control y abra el icono Sistema (Inicio ? Configuración ? Panel de Control ? Sistema, o directamente Inicio ? Panel de Control ? Sistema)

  • Vaya a la pestaña Avanzado

  • Haga clic en el botón 'Variables de Entorno'

  • Revise el panel de 'Variables de Sistema'

  • Haga clic en 'Nuevo' e ingrese 'PHPRC' como nombre de variable, y el directorio donde se encuentra php.ini como el valor de la variable (p.ej., C:\php)

  • Presione OK y reinicie la máquina

En Windows 98/Me necesita editar el fichero autoexec.bat:

  • Abra el Bloc de Notas (Inicio ? Ejecutar y escriba notepad)

  • Abra el fichero C:\autoexec.bat

  • Agregue una nueva línea al final del fichero: set PHPRC=C:\php (reemplace C:\php con el directorio donde se encuentre php.ini). Por favor, observe que la ruta no puede contener espacios. Por ejemplo, si instaló PHP en C:\Archivos de programa\PHP, debería ingresar C:\ARCHIV~1\PHP en su lugar.

  • Guarde el fichero y reinicie la máquina

¿Es posible usar la negociación de contenidos de Apache (opción MultiViews) con PHP?

Si los enlaces a ficheros de PHP incluyen la extensión, todo funciona perfectamente. Estas preguntas frecuentes son solo para aquellos casos en los que los enlaces a ficheros de PHP no incluyen la extensión y se desea utilizar la negociación de contenidos para elegir ficheros de PHP sin extensión desde un URL. En este caso, reemplace la línea AddType application/x-httpd-php .php con:

AddHandler php5-script php
AddType text/html php
Esta solución no funciona para Apache 1 ya que el módulo de PHP no capta php-script.

¿PHP se limita a procesar únicamente métodos de peticiones GET y POST?

No. Es posible manejar cualquier método de peticiones, por, ej., CONNECT. El estado de respuesta apropiado puede ser enviado con header(). Si solo se van a manejar los métodos GET y POST, esto se puede lograr con la siguiente configuración de Apache:

<LimitExcept GET POST>
Deny from all
</LimitExcept>

User Contributed Notes

ssaxena at nriol dot com 12-Mar-2010 02:28
Here are my struggle to get PHP 5.2.12 working on Windows XP SP3, IIS 5.1 (Please note Win XP SP3 has issue of FastCGI)

1. Dowloaded installer and installed in C:\Program Files\PHP as ISAPI module

---->Did not work

Added php5isapi.dll in ISAPI Filter and added the extension .php in Home Dir->Configuration
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

(And the Google was pointing to the Fast CGI issue; Don't know why microsoft has MS-FAST ! )
Uninstalled the PHP and cleaned up the folders, PATH environment variable & PHPRC, the IIS settings and registry entries and shut down(restart is different from shut down) the system to make it very clean

2. Reinstalled the PHP in C:\PHP as ISAPI and did the same as above in IIS
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

Uninstalled and cleaned up same as above and took a breath to make sure what I am doing wrong.
Shutdown the system.

3. Unzipped the php-5.2.12-Win32.zip and did the same as above (this time manually PATH variable and security permission for the PHP folder and following settings)

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:\Inetpub\wwwroot"
extension_dir = "C:\PHP\ext"
cgi.force_redirect = 0

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system.

4. Downloaded Microsoft Web Platform Installer 2.0 and select the PHP+Fast CGI+Windows Cache for PHP extension and Web Deployment Tools
restarted the system to take effect the settings

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system

5. Took the prev version of PHP php-5.2.4-Win32.zip unzip the folder and did the following changes:

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:\Inetpub\wwwroot"
extension_dir = "C:\PHP\ext"
cgi.force_redirect = 0

set the security permission as IIS_machinename with full access to the C:\PHP folder

------->IT GOT WOKRING

Hope people would be aware of php-5.2.12 and would love the php-5.2.4
john dot calder at manukau dot ac dot nz 03-May-2008 10:19
WINDOWS 2003 and IIS.  BIG LESSON FOR ME was "don't mess with the optional components".
I had lots of trouble until I tried installing without asking for extras and then it was very smooth.
I have found no need to set up paths.
I have found no need to configure IIS.
I have found no need to change security on the PHP folder.

What works for me with Windows/IIS:

1.  You need to be logged-on as "administrator"

2.  Run  "php-5.2.6-win32-installer.msi"
Your ONLY action during this wizard is to select "IIS ISAPI" as the webserver.  Do NOT CHANGE anything else!  I am guessing that the optional extras apply only to Apache because after enabling them I see Apache-related error messages.

3.  Setup a test virtual directory as you would for an ASP or ASP.NET web app.  eg "phptest"
Then use notepad to create a test page eg "test.php"
<?php
phpinfo();
?>

4.  In Internet Explorer, test with eg this address
http://localhost/phptest/test.php

IF this does not give you a beautiful page of details THEN start reading other advice on this page - especially helpful for me was the faq advice to test run "php.exe -i" from the command prompt.
charleslynch at xybersoftware dot com 17-Apr-2008 07:30
One final note to the message below if you are getting the message about not having rights to execute...You need to use IIS right click on the website and choose 'Properties/Home Directory' then on the 'Execute Permissions' combo box you need to choose 'Scripts only'...Click ok...another dialog may appear asking which directories to apply the action too...choose any directories that you intend on using php in and click ok...It should work now...
joerg at fenin dot de 02-Nov-2007 02:35
To limit HTTP Request Methods on the Apache server running PHP you should use mod_rewrite or mod_security instead of LimitExcept, to give you more control over the handling of such http errors.  Can go in .htaccess file or httpd.conf

# mod_rewrite
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|POST)$
  RewriteRule .* - [F,L]
</IfModule>

# mod_security
<IfModule mod_security.c>
  SecFilterSelective REQUEST_METHOD "!^(GET|HEAD|POST)$" "deny,log,status:403"
</IfModule>

You can use the php request method scanner at askapache to see exactly how your server deals with various request methods, and check that your server is configured properly..

http://www.askapache.com/online-tools/request-method-scanner/
scott at chaisson dot net 19-Sep-2007 09:18
Windows 2000 Server and IIS (SP4 and all patches):

After many frustrating hours of trying to figure out the install (again), It took a while, but here are a couple tips:

PHP working with IIS uses c:\winnt\php.ini

It doesn't matter what you set the path to, nor what you set the PHPRC environment variable to. After you get PHP running correctly in the installation folder (using php -i) copy the php.ini file into the c:\winnt folder.

Here's what worked for me:

- Add PHP path to System environment variable

- Add php5activescript.dll from http://snaps.php.net/ to the PHP folder, then Register it: "regsvr32 php5activescript.dll"

Set extension_dir and doc_root directives in PHP.INI:
  extension_dir = C:\WWW\PHP\ext
  doc_root = C:\WWW\Site
  cgi.force_redirect = 0

(the last cgi.force_redirect isn't required, but I like to set it anyway)

Copy the .INI file into WINNT folder

In IIS Manager, right-click "Default Web Site", Click "Home Directory",
  Click "Configuration", "Add" the ISAPI application:
    Executable: <your php install>\php5isapi.dll
    Extension: .php
    Limit to: GET,HEAD,POST
    Check: "Script Engine"
    Uncheck: "Check that file exists"

Finally: Set up an ISAPI filter:
  Click the "ISAPI Filters" tab,
  Filter Name: PHP
  Executable: <your php install>\php5isapi.dll

Notes: You don't have to set any of your folders as "Script source" folders. .PHP files aren't scripts, merely text files that require processing before being shipped off to the browser, which is what the ISAPI filter does.

Finally, working again.

Chase
christianfelix at laszlo dot com 16-Jul-2007 03:39
For Windows XP users

Just add php.ini to windows/system 32 and also save a copy in the setup folder e.g. c:/php/php.ini, c:/php5/php.ini,

You have to follow the suggestions, add to path, uncomment extensions and voila!!
Meiki67 skipthis at geemail 07-Jun-2007 04:41
Had a hard day to MSI install 5.2.3 on WinXP with MySQL. I use a drive substitution (subst drive: path - in my case subst d: c:\drive_d) and installed PHP in D:\PHP - which in reality is C:\DRIVE_D\PHP.  To make a long story short - only after (1) changing all substituted D:\ back to C:\DRIVE_D and (2) resolving all DOS short names to Win long names PHP started to work. The first one is clear - the substitution works only for the active console user - not for services or IUSR. For the second one I have no explanation, since DOS short names should work systemwide - maybe Win handles them correctly but PHP not ?

BTW <?php phpinfo(); ?> was of tremendeous help

Meiki
Curtis 18-May-2007 07:39
I have some additional troubleshooting tips for 53.7, which deals with getting a blank screen on your browser when running a PHP script.

In addition to server misconfiguration, it may also be that PHP isn't configured to output errors to the browser, which is the case if you or your host uses a more secure php.ini. If this is the case, you need to find out where errors are being logged to find out if any errors are preventing normal output from being delivered to the client.

If you have access to php.ini, check the 'display_errors' directive, which is, by default, located under the 'error_reporting' directive. It's helpful to have 'display_errors' on during debugging phases, but best to have it off in production environments.

Related functions: http://php.net/ini_set | http://php.net/error_reporting | http://php.net/error_log
knutw at sparhell dot no 06-Nov-2006 09:15
I recntly upgraded from PHP 5.1 to 5.2 on my Windows Server 2003 using IIS6. I selected CGI as before. My PHP folder is as always C:\Program Files\PHP. I also edited my brand new php.ini, enabling all my old extensions and recommended settings for IIS. I like not to keep my old config into a new version.

After upgrade, I just got blank pages in my browser, and the response status was 404 Not found.

I checked my installation twice, using this FAQ, but got no way.

Then I went to IIS Manager, Web Service Extensions. The php Service Extension was Allowed as it should. I deleted the Service Extension and added it. The old extension used short file names containing tilde (PROGRA~) character, but I don'æt know if that gas anything to do with the problem. Anyway, after allowing my" new" Service Extension, pointing to php-cgi.exe as before, mye web sites suddenly worked. So will revommend anyone with thos problem to delete and add the Servcie Extension. It didn't help re-allowing it, restarting IIS or the complete server.
13-Sep-2006 07:03
After setting the PHPRC environment variable, none of my PHP files would hit the preprocessor. The browser was just serving out PHP source code right there in the "view source."

The manual was telling me to set this var to "c:\php," but nothing was working. It's almost as if IIS/Win2000 wasn't reading my php.ini at all.

After I set that variable to "c:\php\php.ini," all of a sudden I was getting honest to goodness PHP pages working.
emzeperx at emzeper dot hu 01-Jan-2006 12:36
You do not have to restart the whole system make effect of changing the PATH env var. For me (sbs2003) worked automatically.
on older systems you can use

set $Path=%path%;c:\php

command to extend immediately the path var.
JUSTANOTHERUSER 14-Aug-2005 11:23
<LimitExcept GET POST>
Deny from all
</LimitExcept>

Does not work with Apache2+ & PHP5 . Apache Refuses to start
per dot fikse at ipj dot no 12-Jul-2005 01:22
Installing PHP 4 or 5 on Windows Server 2003 x64 results in http error 505. This is not a PHP bug. It is due to running a 32-bit ISAPI DLL under the 64-bit version of IIS 6, as documented here: http://support.microsoft.com/?id=895976

Solution: Flip the Metabase flag for Enable32bitAppOnWin64 as described in http://support.microsoft.com/?id=894435 ,
like this: CSCRIPT ADSUTIL.VBS SET W3SVC/AppPools/Enable32bitAppOnWin64 1

(Alternatively with full path: cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1)
barry dot fagin at usafa dot af dot mil 04-Jan-2005 09:22
Fixing 404 (file not found) errors with PHP 5.0.3 and IIS 6.0

IIS 6.0 is installed with security settings that don't permit dynamic content.  This means that even if all the hints in the FAQ are paid attention to (.ini modified correctly, security and permissions correct for IUSR_xxx user, etc), you still get 404 errors for all php files.

To fix this:  IIS Manager -> expand local computer -> Web Services Extensions -> Add web service or extension -> .php, browse to c:\php\php-cgi.exe or wherever you had the php executable installed. That plus setting the doc_root in the .ini file solved the problem.

--BF
jeff_graham at datacenterservices dot net 01-Feb-2004 01:51
As stated within the note "jimo at mail dot azhsv dot com
29-Nov-2003 04:33
PHP 4 and IIS 6.0 (Windows Server 2003)," I found the same steps were requiered for installation of PhP 5 beta 3 on my Windows 2003 server (Standard Edition)
nigel dot salt at hotmail dot com 13-Dec-2003 05:00
Finally got IIS 5 and PHP 5 to talk.

What worked for me was:

1) Set
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\
W3SVC\Parameters\Script Map]
".php"="your path to php\\php.exe"

2) ensure there is not a php.ini in the windows system folder and that there is one wherever you've put PHP

3) edit php.ini and set cgi force redirect to 0 and cgi.rfc2616_headers = 1

4) Put the PHP scripts in their own folder underneath the inetpub root

5) Open the IIS console, right click your new php folder
In the Directory tab
 set application name to the name of the folder
 set executable and script as permission
 set application protection to low
Click configuration and check that .php is mapped to wherever you put
PHP

Restart IIS

Try a very simple PHP page and it should work

Nigel
jimo at mail dot azhsv dot com 29-Nov-2003 07:33
PHP 4 and IIS 6.0 (Windows Server 2003)

Had difficulty getting PHP 4.3.3 to work with Win2003 Ent Server for use with SquirrelMail.  Problem found and believed solved.  Appears to be something New with IIS 6.0 (More security by Micro$oft)  Was getting 404 error and php was not being run as a cgi even though it was in extensions and IIS user had rights to execute it. (php from command line operated correctly)

If you are installing on Windows Server 2003 (only have Enterprise Edition ? Not sure if this applies to standard edition), and you have done the normal procedures for inclusion of PHP scripts (either ISAPI or CGI) in IIS, you will still get a 404 error when attempting to execute those scripts even though IIS has rights and the extension points to the correct file.  To alleviate this problem, perform the following:

1.    Open a command prompt window
2.    Change to C:\windows\system32
3.    Execute the command:  cscript  iisext.vbs /AddFile c:\php\php.exe 1 php 0 php
4.    Execute the command:  cscript iisext.vbs /EnFile c:\php\php.exe
5.    To check for correct execution of the above,
6.    Execute the command:  cscript IisExt.vbs /ListFile ? the php extension should be listed

If you try just step 4 without step 3 you get an error that the file is not in the list (and won?t be there till you do step 3 above)

After this, IIS seems to like the php extension and work normally.

For additional reference, see the below 3 Micro$oft KB Articles:
HOWTO: Enable and Disable ISAPI Extensions and CGI Applications in IIS 6.0 (MS KB Article 328360)

HOWTO List Web Server Extensions and Extension Files in IIS 6.0 (MS KB Article 328505)

HOWTO Add and Remove Web Service Extension Files in IIS 6.0 (MS KB Article 328419)
peter dot mosinskisNOSPAM at csuci dot edu 06-Mar-2003 12:36
Running Win2K AS + IIS5.0 + PHP 4.3.1, I ran into a nasty problem that I mistakenly thought had to do with something in the php.ini configuration. When I would try to submit a form using the HTTP method GET it would work, but I would get a "404 Page Not Found" error using the POST method.

All my permissions were set correctly, the php.ini was configured correctly. It had to do with URLScan being installed on IIS (see below)

Page 404 File Not Found Error When Using POST method in PHP (and Perl, and otherwise)
-------------------------------------------

This is related to the Microsoft URLScan utility. If you have this problem, the IIS administrator has probably run the IIS Lockdown tool as well as configured URLScan to reject this type of HTTP method when sent in a URL. These tools are meant to enhance web server security.

URLScan configuration files can be found in the \WINNT\system32\inetsrv\urlscan folder on the web server. Specifically, the file to modify is urlscan.ini.

The changes to make are as follows:
1. Make sure UseAllowVerbs=1 under [options]
2. Under the [AllowVerbs] section, list your allowed HTTP methods to include:
    GET
    POST

For more information on the IIS Lockdown tool and URLScan, visit http://technet.microsoft.com
monroe at peoplego dot com 17-May-2002 10:32
INSTALLATION ON OPENBSD 3.1 VIA PORTS COLLECTION
Would have succeed but no mysql support.
I commented out the FLAVORS+= dbase filepro mysql mysql_bundled postgresql iodbc in the /usr/ports/www/php4/Makefile and in the configure options added
--with-mysql=/usr/local   and it worked.

Good Luck


Problemas de Compilación

Esta sección reune la mayoría de errores que ocurren al momento de compilar.

  1. Tengo la última versión de PHP usando el servicio anónimo Git, pero no hay un script de configuración.
  2. Tengo problemas configurando PHP para que trabaje con Apache. Dice que no puede encontrar el httpd.h, pero esta justo donde digo que esta!
  3. Mientras se configura PHP (./configure), se devuelve un error similar al siguiente: checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up
  4. Cuando intento iniciar Apache, obtengo el siguiente mensaje: fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found
  5. Cuando ejecuto la configuración, dice que no puede encontrar los archivos o librerías para GD, gdbm, o algún otro paquete!
  6. Cuando se esta compilando el archivo language-parser.tab.c, da errores así yytname undeclared.
  7. Cuando ejecuto make, parece que se ejecuta bien, pero luego falla cuando intenta enlazar la aplicación final quejandose de que faltan algunos archivos.
  8. Cuando se enlaza PHP, se queja del número de referencias indefenidas.
  9. No puedo encontrar la manera de compilar PHP con Apache 1.3.
  10. He seguido todos los pasos para instalar la versión del módulo de Apache en Unix, y cuando mis scripts de PHP aparecen se me pregunta por guardar el archivo.
  11. Dice que use: --activate-module=src/modules/php4/libphp4.a, pero ese archivo no existe, asi que lo cambie a --activate-module=src/modules/php4/libmodphp4.a y no funciona!? que esta pasando?
  12. Cuando intento compilar Apache con PHP como un módulo estatico usando --activate-module=src/modules/php4/libphp4.a me dice que mi compilador no es compatible con ANSI.
  13. Cuando intento compilar PHP usando --with-apxs obtengo mensajes de error extraños.
  14. Durante el make, obtengo errores sobre microtime, y muchas cosas de RUSAGE_.
  15. Cuando compilo PHP con MySQL, la configuración se ejecuta bien, pero durante el make obtengo un error similar al siguiente: 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é esta mal?
  16. Si deseo actualizar mi PHP. ¿Donde puedo encontrar la línea ./configure que fue usada para compilar mi instalación actual de PHP?
  17. Cuando compilo PHP con la librería GD, también da errores raros de compilación o segfaults en la ejecución.
  18. Cuando compilo PHP parece que recibo errores al azar, como si se colgara. Estoy usando Solaris si eso importa.
Tengo la última versión de PHP usando el servicio anónimo Git, pero no hay un script de configuración.

Se tiene que tener el paquete autoconf de GNU instalado y así se podrá generar el script de configuración desde configure.in. Solo se ejecuta ./buildconf en el directorio de nivel superior después de obtener los fuentes desde el servidor Git. (También, a menos que se ejecute configure con la opción --enable-maintainer-mode, el script de configuración no se recompilará automaticamente cuando el archivo configure.in es actualizado, así que debe de asegurarse que se hace manualmente cuando se note que configure.in haya cambiado. Un sintoma de esto es encontrar cosas como @VARIABLE@ en el archivo Makefile después de configurar o ejecutar config.status).

Tengo problemas configurando PHP para que trabaje con Apache. Dice que no puede encontrar el httpd.h, pero esta justo donde digo que esta!

Se necesita decirle al script configure/setup de apache la ubicación del nivel superior del árbol origen. Esto significa que se debe especificar --with-apache=/path/to/apache y no --with-apache=/path/to/apache/src.

Mientras se configura PHP (./configure), se devuelve un error similar al siguiente:

checking lex output file root... ./configure: lex: command not found
configure: error: cannot find output from lex; giving up

Se debe asegurar de leer cuidadosamente las instrucciones installation y notar que se necesita flex y bison instalados para compilar PHP. Dependiendo de la configuración, se necesitará instalar bison y flex desde el paquete de origen, como un RPM

Cuando intento iniciar Apache, obtengo el siguiente mensaje:

fatal: relocation error: file /path/to/libphp4.so:
symbol ap_block_alarms: referenced symbol not found

Este error usualmente se da cuando un programa del núcleo de Apache se compila como una librería DS0 para uso compartido. Se debe reconfigurar apache, asegurándose de usar al menos una de los siguientes flags:

--enable-shared=max --enable-rule=SHARED_CORE

Para mas información, leer el archivo de nivel superior de Apache INSTALL o las páginas del manual de Apache » DSO manual.

Cuando ejecuto la configuración, dice que no puede encontrar los archivos o librerías para GD, gdbm, o algún otro paquete!

Se puede configurar el script para que busque los archivos de encabezados y librerías en ubicaciones no estándar para especificar flags adicionales para ser pasados al preprocesador y compilador C, como:

    CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
Si se esta usando una variante de csh como login shell (por qué?), debería de ser:
    env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

Cuando se esta compilando el archivo language-parser.tab.c, da errores así yytname undeclared.

Se debe actualizar la versión de Bison. Se puede encontrar la ultima versión en » http://www.gnu.org/software/bison/bison.html.

Cuando ejecuto make, parece que se ejecuta bien, pero luego falla cuando intenta enlazar la aplicación final quejandose de que faltan algunos archivos.

Algunas versiones antiguas de make no colocan correctamente las versiones compiladas de archivos y funciones de directorio en el mismo directorio. Se debe intentar ejecutar las funciones cp *.o y entonces re-ejecutar make para ver si eso ayuda. Si no lo hace, realmente se debería actualizar a la versión más reciente de GNU Make.

Cuando se enlaza PHP, se queja del número de referencias indefenidas.

Hay que mirar la linea del enlace y asegurarse de que todas las librerías apropiadas han sido incluidas al final. Las mas comunes que podrían estar perdidas son las '-ldl' y librerías requeridas como soporte por cualquier base de datos que se haya incluido.

Algunas personas han reportado que han tenido que adicionar '-ldl' inmediatamente seguido por libphp4.a cuando enlazan con Apache.

No puedo encontrar la manera de compilar PHP con Apache 1.3.

Esto es muy fácil actualmente. Siga cuidadosamente estos pasos:

  • Obtener la ultima distribución de Apache 1.3 desde » http://httpd.apache.org/download.cgi.
  • Descomprimir el archivo en alguna parte, por ejemplo /usr/local/src/apache-1.3.
  • Compilar PHP para la primera ejecución ./configure --with-apache=/<path>/apache-1.3 (sustituir <path> por la ruta actual del directorio de apache-1.3).
  • Escribir make seguido por make install para compilar PHP y copiar los archivos necesarios al árbol de la distribución de Apache.
  • Cambiar los directorios en el directorio /<path>/apache-1.3/src y editar el archivo de Configuration. Adicionar al archivo: AddModule modules/php4/libphp4.a.
  • Escribir: ./configure seguido por make.
  • Se debería tener ahora un httpd binario con PHP habilitado!

Nota:Se puede usar también el nuevo script ./configure. Ver las instrucciones en el archivo README.configure el cual es parte de la distribución de Apache. También se puede hechar una mirada al archivo INSTALL en la distribución de PHP.

He seguido todos los pasos para instalar la versión del módulo de Apache en Unix, y cuando mis scripts de PHP aparecen se me pregunta por guardar el archivo.

Esto significa que el módulo de PHP no esta siendo invocado por alguna razón. Hay tres cosas que chequear antes de pedir ayuda:

  • Asegurarse que el binario del httpd que se esta ejecutando es el nuevo binario httpd que se acaba de hacer. Para ver esto, se debe intentar ejecutar: /path/to/binary/httpd -l Si no se ve mod_php4.c listado, entonces no se esta ejecutando el binario correcto. Hay que encontrarlo e instalar el binario correcto.
  • Asegurarse de que es agregado el Mime Type correcto en uno de los archivos de Apache .conf. Debería de ser: AddType application/x-httpd-php .php También asegurarse que esta línea AddType no esta oculta dentro de un bloque de <Virtualhost> o uno de <Directory> el cual podría evitar que se aplique en el lugar donde se prueba el script.
  • Por último, el lugar por defecto de los archivos de configuración de Apache cambio entre Apache 1.2 y Apache 1.3. Se debería chequear que el archivo de configuración al cual se le agrega la línea AddType esta siendo leído actualmente. Se puede poner un error de sintaxis obvio dentro del archivo httpd.conf o algún otro cambio que pueda decir si el archivo esta siendo leído de forma correcta.

Dice que use: --activate-module=src/modules/php4/libphp4.a, pero ese archivo no existe, asi que lo cambie a --activate-module=src/modules/php4/libmodphp4.a y no funciona!? que esta pasando?

Hay que tener en cuenta que el archivo libphp4.a no se supone que exista. El proceso de apache sera creado!.

Cuando intento compilar Apache con PHP como un módulo estatico usando --activate-module=src/modules/php4/libphp4.a me dice que mi compilador no es compatible con ANSI.

Este es un mensaje de error equivocado de Apache que ha sido corregido en las versiones mas recientes.

Cuando intento compilar PHP usando --with-apxs obtengo mensajes de error extraños.

Hay 3 cosas que chequear aqui. Primero, por alguna razón cuando Apache compila el script de Perl apxs, algunas veces termina compilandose sin el compilador apropiado y sin los flags correspondientes. Hay que encontrar el script apxs (intentar con el comando which apxs), algunas veces se encuentra en /usr/local/apache/bin/apxs o /usr/sbin/apxs. Abrirlo y revisar las líneas similares a estas:

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 esto es lo que se ve, se ha encontrado el problema. Podrían contener espacios u otros valores incorrectos, como 'q()'. Hay que cambiar esas linas para que digan:
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
El segundo problema posible podría ser un caso único en Red Hat 6.1 y 6.2. El script apxs de Red Hat esta malo. Hay que ver esta línea:
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
Si se ve como la línea anterior, hay que cambiarla por:
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
Por último, si se reconfigura/reinstala Apache, hay que agregar un make clean al proceso después de ./configure y antes de make.

Durante el make, obtengo errores sobre microtime, y muchas cosas de RUSAGE_.

Durante la parte de la instalación de make, si se encuentran problemas que se vean similares a esto:

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

Significa que el sistema esta mal. Se necesita corregir los archivos /usr/include instalando el paquete glibc-devel que coincida con tu glibc. Esto no tiene nada que ver con PHP. Para comprobar esto, hay que hacer esta simple prueba:

$ cat >test.c <<X
#include <sys/resource.h>
X
$ gcc -E test.c >/dev/null
Si esto produce errores, se sabrá que los archivos incluidos están mal.

Cuando compilo PHP con MySQL, la configuración se ejecuta bien, pero durante el make obtengo un error similar al siguiente: 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é esta mal?

Primero, es importante darse cuenta que esto es un Warning y no un error fatal. Debido a que esto es la última salida vista durante el make, podría verse como un error fatal pero no lo es. Por supuesto, si se ha puesto el compilador a que pare en los Warnings, lo hará. También hay que tener en mente que el soporte por MySQL es habilitado por defecto.

Nota:

Como en PHP 4.3.2, se verá el siguiente texto después de que se complete la compilación (make):

Build complete.
(Es seguro hacer caso omiso de las advertencias sobre tempnam y tmpnam).

Si deseo actualizar mi PHP. ¿Donde puedo encontrar la línea ./configure que fue usada para compilar mi instalación actual de PHP?

Si se mira el archivo config.nice, en el árbol origen de la instalación actual de PHP o, si esto no esta disponible, simplemente se debe ejecutar un script con

<?php phpinfo(); ?>
Al inicio de la salida se mostrará la línea ./configure que fue usada para compilar la instalación de PHP.

Cuando compilo PHP con la librería GD, también da errores raros de compilación o segfaults en la ejecución.

Hay que asegurar que la librería GD y PHP estan enlazados contra las mismas librerías dependientes (ej: libpng).

Cuando compilo PHP parece que recibo errores al azar, como si se colgara. Estoy usando Solaris si eso importa.

Usando utilidades no-GNU mientras se compila PHP podría causar problemas. Hay que asegurarse de usar herramientas GNU para estar seguros que la compilación de PHP funcionará. Por ejemplo, en Solaris, usando el SunOS BSD-compatible o versiones de Solaris de sed no funcionará, pero usando las versiones GNU o Sun POSIX (xpg4) de sed hará que funcione. Enlaces: » GNU sed, » GNU flex, y » GNU bison.

User Contributed Notes

synnus at gmail dot com 25-Jun-2017 10:10
j'ai réalisé pour vous une machine virtuel pour compiler php 7
il suffira d'utiliser mon logiciel pour télécharger l'image disque virtuel
qui fonctionne sous virtualbox ; cette image contient une version gratuite
légale de windows 10 proposé par Microsoft lui même Réarmable .
tout le nécessaire pour compiler php 7 sera sur le bureau.

Le dossier Release pour récupérer les fichiers compiler
le lancer de compilation avec les commandes
Buildconf
Configure
nmake ...

voir la documentation https://wiki.php.net/internals/windows/stepbystepbuild
tout est déjà pré configuré vous vous trouvez à la section "Compile"
partie "4.Run : "

pour télécharger l'image c'est ici
https://github.com/Darksynx/Compiling-php7-to-a-virtual-machine

=========

I realized for you a virtual machine to compile php 7
It will suffice to use my software to download the virtual disk image
Which runs under virtualbox; This image contains a free version
Legal of Windows 10 proposed by Microsoft itself Resettable.
All necessary to compile php 7 will be on the desktop.

The Release folder to recover the compile files
The compilation run with commands
buildconf
Sets
Nmake ...

See the documentation https://wiki.php.net/internals/windows/stepbystepbuild
Everything is already preconfigured you are in the section "Compile"
Party "4.Run:"

To download the image here
https://github.com/Darksynx/Compiling-php7-to-a-virtual-machine
Fabio 22-Feb-2012 01:47
When building PHP 5.3.x for Apache 2.4.x you may get an error in the apxs query for the MPM_NAME.
This is because the apxs included in Apache 2.4.x doesn't recognize that query anymore.

To resolve this issue one should modify the PHP configure file to use the right MPM module used by Apache.

To know the used MPM you can execute this command: apachectl -t -D DUMP_MODULES | grep mpm

Then, edit the PHP configure file, search for the APXS_MPM variable and force its value to prefork, event or worker according to the value returned by the previous command.

Hope it helps.
-
Fabio
terry at mackintoshweb dot com 19-Sep-2009 08:43
The configure script of PHP 5.3.0 has some test lines that use expr with the option --, my expr (version 2.0) does not except --.  This causes a run of error messages from the shell like:

./configure: line 2xxx: test: =: unary operator expected
expr: syntax error

I used buildconf --force to see if it would fix this.
While it resulted in a quit different file, it still had the lines of code with expr -- in it.
05-May-2007 06:48
@ anca-phpdoc at anca dot tv:

You can use ./configure --with-libxml-dir=/path_to_xml2-config
anca-phpdoc at anca dot tv 08-Dec-2005 07:48
For the configure newbies among us:

If you update or reinstall any of the libraries used to compile in a different directory than they started out, you will need to make sure that you update the config.cache file (or re-generate it) so that configure will not look in the wrong place for the information.

On Mac OS X, for example, I updated my libxml using Fink.  Fink placed the files in the /sw directory.  However, php was still looking for important libxml files (such as xml2-config) in the old directory (/usr/bin/xml2-config).   After updating config.cache with the new value of the xml2-config path, I was able to compile correctly.


Utilizar PHP

Esta sección reúne varios errores comunes a los que se puede enfrentar mientras se escriben scripts de PHP.

  1. No puedo recordar el orden de los parámetros de las funciones de PHP, ¿son aleatorios?
  2. Me gustaría escribir un script genérico en PHP que pueda manejar datos provenientes de cualquier formulario. ¿Cómo puedo saber qué variables del método POST están disponibles?
  3. Necesito convertir todas las comillas simples (') en barras invertidas seguidas de comillas simples (\'). ¿Cómo puedo hacer esto con expresiones regulares? También me gustaría convertir " en \" y \ en \\.
  4. Cuando hago lo siguiente, la salida se muestra en el orden equivocado: <?php function mi_función($argumento) { echo $argumento + 10; } $variable = 10; echo "mi_función($variable) = " . mi_función($variable); ?> ¿Qué está pasando?
  5. ¡Eh!, ¿qué les pasa a mis nuevas líneas? <pre> <?php echo "Esto debería ser la primer línea."; ?> <?php echo "Esto debería mostrarse después de la línea anterior."; ?> </pre>
  6. Recibo el mensaje 'Warning: Cannot send session cookie - headers already sent...' o 'Cannot add header information - headers already sent...'.
  7. Necesito acceder directamente a información de las cabeceras de una petición. ¿Cómo puedo hacerlo?
  8. Cuando intento usar la autenticación con IIS obtengo el mensaje 'No Input file specified'.
  9. Windows: No puedo acceder a ficheros compartidos en otra computadora usando IIS
  10. ¿Cómo se supone que mezclo XML y PHP? ¡A este no le gustan mis etiquetas <?xml!
  11. ¿Dónde puedo encontrar un listado completo de las variables disponibles de PHP?
  12. ¿Cómo puedo generar ficheros PDF sin usar bibliotecas no gratuitas o comerciales como PDFLib? Me gustaría algo que sea gratis y no requiera bibliotecas de PDF externas.
  13. Estoy intentando acceder a una de las variables estándar de CGI (como $DOCUMENT_ROOT o $HTTP_REFERER) en una función definida por el usuario, y parece que no puede encontrarla. ¿Qué está mal?
  14. Algunas directivas de PHP pueden también tomar una abreviatura de valores de bytes, en lugar de solo valores de bytes integer. ¿Cuáles son todas las opciones de abreviaturas de bytes disponibles?
  15. Windows: Mis conexiones caducan al utilizar localhost, mientras que "127.0.0.1" funciona.
No puedo recordar el orden de los parámetros de las funciones de PHP, ¿son aleatorios?

PHP es un pegamento que une cientos de bibliotecas externas y esto, a veces, lo complica. Por eso, una simple regla de oro es la siguiente:

Los parámetros de las funciones de Array están ordenados como "aguja, pajar", mientras que sucede lo contrario con las funciones de String, esto es, "pajar, aguja".

Me gustaría escribir un script genérico en PHP que pueda manejar datos provenientes de cualquier formulario. ¿Cómo puedo saber qué variables del método POST están disponibles?

PHP ofrece muchas variables predefinidas, como la variable superglobal $_POST. Se puede recorrer la variable $_POST, ya que es un array asociativo con todos los valores provenientes de POST. Por ejemplo, vamos a recorrerla simplemente con foreach, comprobar los valores vacíos, empty(), y mostrarlos todos.

<?php
$vacío = $post = array();
foreach ($_POST as $nombre_variable => $nombre_valor) {
    if (empty($nombre_valor)) {
        $vacío[$nombre_variable] = $nombre_valor;
    } else {
        $post[$nombre_variable] = $nombre_valor;
    }
}

print "<pre>";
if (empty($vacío)) {
    print "Ninguno de los valores de POST esta vacío, se envió:\n";
    var_dump($post);
} else {
    print "Tenemos " . count($vacío) . " valores vacíos\n";
    print "Registrados:\n"; var_dump($post);
    print "Vacíos:\n";  var_dump($vacío);
    exit;
}
?>

Necesito convertir todas las comillas simples (') en barras invertidas seguidas de comillas simples (\'). ¿Cómo puedo hacer esto con expresiones regulares? También me gustaría convertir " en \" y \ en \\.

Asumiendo que esto es para una base de datos, utilice el mecanismo de escape que viene con esta. Por ejemplo, emplee la función mysql_real_escape_string() con MYSQL y pg_escape_string() con PostgreSQL. Existen también las funciones genéricas addslashes() y stripslashes(), las cuales son más comunes en código PHP antiguo.

Nota: Sobre de la directiva: magic_quotes_gpc

La directiva de PHP magic_quotes_gpc tiene por defecto el valor on. Básicamente ejecuta addslashes() en los datos obtenidos por GET, POST, y COOKIE. Se puede usar stripslashes() para quitarlos.

Cuando hago lo siguiente, la salida se muestra en el orden equivocado:
<?php
function mi_función($argumento)
{
    echo $argumento + 10;
}
$variable = 10;
echo "mi_función($variable) = " . mi_función($variable);
?>
¿Qué está pasando?

Para poder usar los resultados de funciones en una expresión (como la concatenación con otras cadenas del ejemplo anterior), es necesario devolver el valor con return; no utilzar echo.

¡Eh!, ¿qué les pasa a mis nuevas líneas?
<pre>
<?php echo "Esto debería ser la primer línea."; ?>
<?php echo "Esto debería mostrarse después de la línea anterior."; ?>
</pre>

En PHP, la terminación de un bloque de código se realiza bien con "?>" o con "?>\n" (donde \n significa una nueva línea). Con el ejemplo anterior, las sentencias de 'echo' estarán en una línea debido a que PHP omite las nuevas líneas después del final de un bloque. Esto significa que es necesario agregar una nueva línea extra después de cada bloque de código PHP para poder imprimir una nueva línea.

¿Por qué PHP hace esto? Porque cuando se formatea HTML normal, esto hace la vida más fácil ya que normalmente no se desea esa nueva línea, pero se tendrían que crear líneas extremadamente largas o, de lo contrario, hacer el código fuente de la pagina ilegible para obtener tal efecto.

Recibo el mensaje 'Warning: Cannot send session cookie - headers already sent...' o 'Cannot add header information - headers already sent...'.

Las funciones header(), setcookie(), y las funciones de sesión necesitan agregar cabeceras al flujo de salida, pero las cabeceras solo pueden enviarse antes de cualquier otro contenido. No puede haber ninguna salida antes de usar esas funciones, salidas como HTML. La función headers_sent() comprobará si un script ya ha enviado las cabeceras. Véase también las funciones de control de salida.

Necesito acceder directamente a información de las cabeceras de una petición. ¿Cómo puedo hacerlo?

La función getallheaders() lo hará si se está ejecutando PHP como un módulo de Apache. El siguiente trozo de código mostrará todas las cabeceras de la petición:

<?php
$cabeceras = getallheaders();
foreach ($cabeceras as $nombre => $contenido) {
    echo "headers[$nombre] = $contenido<br />\n";
}
?>

Véae también
apache_lookup_uri(),
apache_response_headers(), y
fsockopen()

Cuando intento usar la autenticación con IIS obtengo el mensaje 'No Input file specified'.

El modelo de seguridad de IIS es el culpable en este caso. Es un problema común a todos los programas CGI que se ejecutan bajo IIS. Una solución es crear un fichero de HTML plano (no analizado por PHP) como la página de entrada en un directorio autenticado. Se debe utilizar entonces una etiqueta META para redirigir a la página de PHP, o tener un enlace a dicha página. PHP reconocerá así la autenticación correctamente. Con el módulo ISAPI, esto no es un problema. Esto no debería afectar a otros servidores web NT. Para más información, véase: » http://support.microsoft.com/kb/q160422/ y la sección del manual sobre Autenticación HTTP .

Windows: No puedo acceder a ficheros compartidos en otra computadora usando IIS

Ha de cambiar Ir a los Servicios de Información de Internet. Localice su fichero PHP y vaya a sus propiedades. Luego vaya a la pestaña Seguridad de Archivos, Editar -< Acceso anónimo y control de autenticación.

Se puede corregir el problema ya sea desmarcando Acceso anónimo y dejando Autenticación integrada de Windows marcado, o marcando Acceso anónimo y editando el usuario, que ya no tendría que tener derecho de acceso.

¿Cómo se supone que mezclo XML y PHP? ¡A este no le gustan mis etiquetas <?xml!

Con el fin de integrar directamente <?xml en código de PHP, se han de desactivar las etiquetas abreviadas estableciendo la directiva de PHP short_open_tags a 0. Esta directiva no se puede establecer con ini_set(). Independientemente de que short_open_tags esté activada o no, se puede hacer algo como: <?php echo '<?xml'; ?>. El valor predeterminado de esta directiva es On.

¿Dónde puedo encontrar un listado completo de las variables disponibles de PHP?

Lea la página del manual sobre variables predefinidas, que incluye un listado parcial de variables predefinidas disponibles para su script. Se pude ver un listado completo de las variables disponibles (y mucha mas información) llamando a la función phpinfo(). Asegúrese de leer la sección del manual sobre variables desde fuentes externas a PHP, la cual describe escenarios comunes para variables externas, como desde un formulario HTML, una cookie, y un URL.

Nota: register_globals: Observación importante

Desde PHP 4.2.0, el valor por defecto de la directiva register_globals es off. La comunidad de PHP desaconseja el uso de esta directiva y sugiere el uso de otras formas como superglobals.

¿Cómo puedo generar ficheros PDF sin usar bibliotecas no gratuitas o comerciales como PDFLib? Me gustaría algo que sea gratis y no requiera bibliotecas de PDF externas.

Hay algunas alternativas escritas en PHP como » FPDF y » TCPDF.

Estoy intentando acceder a una de las variables estándar de CGI (como $DOCUMENT_ROOT o $HTTP_REFERER) en una función definida por el usuario, y parece que no puede encontrarla. ¿Qué está mal?

Utilice $_SERVER['DOCUMENT_ROOT'] y $_SERVER['HTTP_REFERER'] en su lugar.

Algunas directivas de PHP pueden también tomar una abreviatura de valores de bytes, en lugar de solo valores de bytes integer. ¿Cuáles son todas las opciones de abreviaturas de bytes disponibles?

Las opciones disponibles son K (para Kilobytes), M (para Megabytes) y G (para Gigabytes; disponible desde PHP 5.1.0). Ninguna considera las mayúsculas/minúsculas. Cualquier otra cosa asume bytes. 1M es igual a un Megabyte o 1048576 bytes. 1K es igual a un Kilobyte o 1024 bytes. Estas notaciones abreviadas pueden utlizarse en php.ini y en la función ini_set(). Observe que el valor numérico se moldea a integer; por ejemplo, 0.5M es interpretado como 0.

Nota: kilobyte contra kibibyte

La notación de PHP describe que un kilobyte equivale a 1024 bytes, mientras que el estándar IEC considera que debe ser un kibibyte. Resumiendo: k y K = 1024 bytes.

Windows: Mis conexiones caducan al utilizar localhost, mientras que "127.0.0.1" funciona.

Antes de PHP 5.3.4, existía un error en el código de resolución de red dentro de PHP que ocasionaba que localhost fallase en todas las situaciones relacionadas con flujos si IPv6 estaba habilitado. Para solucionar este problema se puede usar tanto "127.0.0.1" como deshabilitar la resolución de IPv6 en el fichero hosts.

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.


Hash de contraseñas seguro

Esta sección explica las razones que justifican el uso de funciones hash para proteger las contraseñas. También se explica cómo hacerlo de un modo efectivo.

  1. ¿Por qué debo usar hash en las contraseñas de los usuarios de mi aplicación?
  2. ¿Por qué las funciones hash más comunes como md5 y sha1 no son adecuadas para las contraseñas?
  3. ¿Qué hash debo aplicar a mis contraseñas, si las funciones hash más comunes no son adecuadas?
  4. ¿Qué es una sal (salt)?
  5. ¿Cómo almaceno mis sales?
¿Por qué debo usar hash en las contraseñas de los usuarios de mi aplicación?

El hash de contraseñas es una de las consideraciones de seguridad más elementales que se deben llevar a la práctica al diseñar una aplicación que acepte contraseñas de los usuarios. Sin hashing, cualquier contraseña que se almacene en la base de datos de la aplicación podrá ser robada si la base de datos se ve comprometida, con lo que inmediatamente no sólo estaría comprometida la aplicación, sino también las cuentas de otros servicios de nuestros usuarios, siempre y cuando no utilicen contraseñas distintas.

Si aplicamos un algoritmo hash a las contraseñas antes de almacenarlas en la base de datos, dificultamos al atacante el determinar la contraseña original, pese a que en un futuro podrá comparar el hash resultante con la contraseña original.

Sin embargo, es importante tener en cuenta que el hecho de aplicar hash a las contraseñas sólo protege de que se vean comprometidas las contraseñas almacenadas, pero no las protege necesariamente de ser interceptadas por un código malicioso inyectado en la propia aplicación.

¿Por qué las funciones hash más comunes como md5() y sha1() no son adecuadas para las contraseñas?

Los algoritmos hash como MD5, SHA1 o SHA256 están diseñados para ser muy rápidos y eficientes. Con las técnicas y equipos modernos, es algo trivial extraer por fuerza bruta la salida de estos algoritmos, para determinar los datos de entrada originales.

Dada la velocidad con que los ordenadores actuales pueden "invertir" estos algoritmos hash, muchos profesionales de la seguridad recomiendan encarecidamente no utilizarlas como funciones hash para contraseñas.

¿Qué hash debo aplicar a mis contraseñas, si las funciones hash más comunes no son adecuadas?

Al aplicar un algoritmo hash, los dos factores más importantes son el coste computacional y la sal. Cuanto más cueste aplicar un algoritmo hash, más costará analizar su salida por fuerza bruta.

PHP 5.5 proporciona una API de hash de contraseñas nativa que maneja cuidadosamente el empleo de hash y la verificación de contraseñas de una manera segura. También hay una » biblioteca de compatibilidad de PHP pura disponible para PHP 5.3.7 y posterior.

Otra opción es la función crypt(), la cual tiene soporte para varios algoritmos hash en PHP 5.3 y posterior. Al emplear esta función, se garantiza que el algoritmo que se seleccione esté disponible, debido a que PHP contiene implementaciones nativas de cada algoritomo soportado, en caso de que el sistema no tenga soporte para uno o más de estos algoritmos.

El algoritmo recomendado para el empleo de contraseñas con hash es Blowfish, que es también el predeterminado de la API de hash de contraseñas, que, aunque es significativamente más caro computacionalmente que MD5 o SHA1, sigue siendo escalable.

Observar que si se emplea crypt() para verificar una contraseña, será necesario tomar precauciones para evitar ataques de temporización utilizando una comparación de string de tiempo constantes. Ni los operadores == y === de PHP ni strcmp() llevan a cabo una comparación de string de tiempo constante. Debido a que password_verify() hará esto de forma automática, se recomienda el empleo de la API de hash de contraseñas nativa siempre que sea posible.

¿Qué es una sal (salt)?

Una sal criptográfica es un dato que se utiliza durante el proceso de hash para eliminar la posibilidad de que el resultado pueda buscarse a partir de una lista de pares precalculados de hash y sus entradas originales, conocidas como tablas rainbow.

Es decir, una sal es un pequeño dato añadido que hace que los hash sean significantemente más difíciles de crackear. Existe un gran número de servicios online que ofrecen grandes listas de códigos hash precalculados, junto con sus datos de entrada originales. El uso de una sal hace muy difícil o imposible encontrar el hash resultante en cualquiera de estas listas.

password_hash() creará una sal aleatoria si no se proporciona una, siendo esta generalmente la estrategia más sencilla y segura.

¿Cómo almaceno mis sales?

Al utilizar password_hash() o crypt(), el valor devuelto incluye la sal como parte del hash generado. Este valor debería almacenarse tal cual en la base de datos, ya que incluye información sobre la función hash que se empleó y así proporcionarla directamente a password_verify() o crypt() al verificar contraseñas.

El siguiente diagrama muestra el formato de un valor devuelto por crypt() o password_hash(). Como se puede observar, son autocontenidos, con toda la información del algoritmo y la sal requerida para futuras verificaciones de contraseñas.

Los componentes del valor devuelto por password_hash y crypt: en orden, el algoritmo elegido, las opciones del algoritmo, la sal utilizada, y la contraseña con hash.

User Contributed Notes

swardx at gmail dot com 29-Jun-2016 09:36
A great read..

https://nakedsecurity.sophos.com/2013/11/20/serious-security-how-to-store-your-users-passwords-safely/

Serious Security: How to store your users’ passwords safely

In summary, here is our minimum recommendation for safe storage of your users’ passwords:

    Use a strong random number generator to create a salt of 16 bytes or longer.
    Feed the salt and the password into the PBKDF2 algorithm.
    Use HMAC-SHA-256 as the core hash inside PBKDF2.
    Perform 20,000 iterations or more. (June 2016.)
    Take 32 bytes (256 bits) of output from PBKDF2 as the final password hash.
    Store the iteration count, the salt and the final hash in your password database.
    Increase your iteration count regularly to keep up with faster cracking tools.

Whatever you do, don’t try to knit your own password storage algorithm.
alf dot henrik at ascdevel dot com 12-Mar-2014 07:58
I feel like I should comment some of the clams being posted as replies here.

For starters, speed IS an issue with MD5 in particular and also SHA1. I've written my own MD5 bruteforce application just for the fun of it, and using only my CPU I can easily check a hash against about 200mill. hash per second. The main reason for this speed is that you for most attempts can bypass 19 out of 64 steps in the algorithm. For longer input (> 16 characters) it won't apply, but I'm sure there's some ways around it.

If you search online you'll see people claiming to be able to check against billions of hashes per second using GPUs. I wouldn't be surprised if it's possible to reach 100 billion per second on a single computer alone these days, and it's only going to get worse. It would require a watt monster with 4 dual high-end GPUs or something, but still possible.

Here's why 100 billion per second is an issue:
Assume most passwords contain a selection of 96 characters. A password with 8 characters would then have 96^8 = 7,21389578984e+15 combinations.
With 100 billion per second it would then take 7,21389578984e+15 / 3600 = ~20 hours to figure out what it actually says. Keep in mind that you'll need to add the numbers for 1-7 characters as well. 20 hours is not a lot if you want to target a single user.

So on essence:
There's a reason why newer hash algorithms are specifically designed not to be easily implemented on GPUs.

Oh, and I can see there's someone mentioning MD5 and rainbow tables. If you read the numbers here, I hope you realize how incredibly stupid and useless rainbow tables have become in terms of MD5. Unless the input to MD5 is really huge, you're just not going to be able to compete with GPUs here. By the time a storage media is able to produce far beyond 3TB/s, the CPUs and GPUs will have reached much higher speeds.

As for SHA1, my belief is that it's about a third slower than MD5. I can't verify this myself, but it seems to be the case judging the numbers presented for MD5 and SHA1. The issue with speeds is basically very much the same here as well.

The moral here:
Please do as told. Don't every use MD5 and SHA1 for hasing passwords ever again. We all know passwords aren't going to be that long for most people, and that's a major disadvantage. Adding long salts will help for sure, but unless you want to add some hundred bytes of salt, there's going to be fast bruteforce applications out there ready to reverse engineer your passwords or your users' passwords.
fluffy at beesbuzz dot biz 11-Jun-2012 11:33
The security issue with simple hashing (md5 et al) isn't really the speed, so much as the fact that it's idempotent; two different people with the same password will have the same hash, and so if one person's hash is brute-forced, the other one will as well.  This facilitates rainbow attacks.  Simply slowing the hash down isn't a very useful tactic for improving security.  It doesn't matter how slow and cumbersome your hash algorithm is - as soon as someone has a weak password that's in a dictionary, EVERYONE with that weak password is vulnerable.

Also, hash algorithms such as md5 are for the purpose of generating a digest and checking if two things are probably the same as each other; they are not intended to be impossible to generate a collision for.  Even if an underlying password itself requires a lot of brute forcing to determine, that doesn't mean it will be impossible to find some other bit pattern that generates the same hash in a trivial amount of time.

As such: please, please, PLEASE only use salted hashes for password storage.  There is no reason to implement your own salted hash mechanism, either, as crypt() already does an excellent job of this.


PHP y HTML

PHP y HTML interactúan mucho: PHP puede generar HTML, y HTML puede pasar información a PHP. Antes de leer esta sección, es importante que aprenda cómo obtener variables desde fuentes externas. La página del manual sobre este tema incluye muchos ejemplos también.

  1. ¿Qué codificación/decodificación es necesaria al pasar un valor a través de un formulario/URL?
  2. Estoy intentando usar una etiqueta <input type="image">, pero las variables $foo.x y $foo.y no están disponibles. $_GET['foo.x'] tampoco existe. ¿Dónde están?
  3. ¿Cómo creo arrays en un <form> de HTML?
  4. ¿Cómo obtengo todos los resultados de una etiqueta de selección múltiple en HTML?
  5. ¿Cómo puedo pasar una variable de Javascript a PHP?
¿Qué codificación/decodificación es necesaria al pasar un valor a través de un formulario/URL?

Existen varios escenarios en los que la codificación es importante. Asumiendo que se tiene un valor $datos de tipo string, el cual contiene la cadena que desea pasar sin codificar, existen los escenarios relevantes:

  • Interpretación de HTML. Para especificar una cadena aleatoria, es necesario incluirla entre comillas dobles, y aplicar htmlspecialchars() sobre el valor completo.

  • URL: Un URL consta de varias partes. Si los datos han de ser interpretados como un elemento, es necesario codificarlo con urlencode().

Ejemplo #1 Un elemento oculto de un formulario HTML

<?php
    echo '<input type="hidden" value="' . htmlspecialchars($datos) . '" />'."\n";
?>

Nota: No es correcto aplicar urlencode() sobre $datos, ya que es responsabilidad de los navegadores codificar los datos. Todos los navegadores populares lo realizan correctamente. Observe que esto ocurrirá independientemente del método (es decir, GET o POST). Aunque solo se observará esto en el caso de una petición GET, ya que las peticiones POST normalmente están ocultas.

Ejemplo #2 Datos a editar por el usuario

<?php
    echo "<textarea name='misdatos'>\n";
    echo htmlspecialchars($datos)."\n";
    echo "</textarea>";
?>

Nota: Los datos son mostrados en el navegador como se esperaba, ya que el navegador interpretará los símbolos HTML escapados. Durante el envío, ya sea mediante GET o POST, los datos serán codificados por el navegador para su transferencia, y serán decodificados directamente por PHP. Por lo tanto, no será necesario realizar ninguna codificación/decodificación, todo es manejado automáticamente.

Ejemplo #3 En un URL

<?php
    echo '<a href="' . htmlspecialchars("/siguientepagina.php?etapa=23&datos=" .
        urlencode($datos)) . '">'."\n";
?>

Nota: De hecho, se está imitando una petición GET de HTML, por lo que no es necesario aplicar urlencode() manualmente a los datos.

Nota: Es necesario usar htmlspecialchars() sobre el URL completo, ya que el URL se da como un valor de un atributo HTML. En este caso, el navegador primero reemplazará los caracteres HTML especiales por los caracteres correctos del valor, y luego pasará el URL. PHP entenderá el URL correctamente, ya que ya se utilizó urlencode() sobre los datos. Se observará que el caracter & en el URL es reemplazado por &amp;. Aunque la mayoría de navegadores entenderán el carácter si se olvida esto, no siempre es posible que ocurra. Así que, incluso si un URL no es dinámico, es necesario usar htmlspecialchars() sobre el URL.

Estoy intentando usar una etiqueta <input type="image">, pero las variables $foo.x y $foo.y no están disponibles. $_GET['foo.x'] tampoco existe. ¿Dónde están?

Cuando se envía un formulario, es posible usar una imagen en lugar del botón de envío estándar con una etiqueta como esta:

<input type="image" src="imagen.gif" name="foo" />
Cuando un usuario pulsa sobre la imagen, el formulario al que pertenece será transmitido al servidor con dos variables adicionales: foo.x y foo.y.

Dado que foo.x y foo.y habrían representado nombres de variable inválidos en PHP, éstas son convertidas automáticamente a foo_x y foo_y. Es decir, los puntos son reemplazados con caracteres de subrayado. Por lo tanto, es posible acceder a estas variables como cualquier otra descrita en la sección sobre la recuperación de variables desde fuentes externas. Por ejemplo, $_GET['foo_x'].

Nota:

Los espacios en nombres de variables de petición son convertidos a caracteres de subrayado.

¿Cómo creo arrays en un <form> de HTML?

Para hacer que el resultado de <form> sea enviado como un array a un script de PHP, se deben nombrar los elementos <input>, <select> o <textarea> de esta forma:

<input name="MiArray[]" />
<input name="MiArray[]" />
<input name="MiArray[]" />
<input name="MiArray[]" />
Observe los corchetes después del nombre de la variable; ellos son los que la convierten en un array. Es posible agrupar los elementos en diferentes arrays asignando el mismo nombre a elementos diferentes:
<input name="MiArray[]" />
<input name="MiArray[]" />
<input name="MiOtroArray[]" />
<input name="MiOtroArray[]" />
Esto produce dos array, MiArray y MiOtroArray, que son enviados al script PHP. También es posible asignar claves específicas a los arrays:
<input name="OtroArray[]" />
<input name="OtroArray[]" />
<input name="OtroArray[email]" />
<input name="OtroArray[telefono]" />
El array OtroArray ahora tendrá las claves 0, 1, email y telefono.

Nota:

La especificación de claves de arrays es opcional en HTML. Si no se especifican las claves, el array será rellenado en el orden en que aparecen los elementos en el formulario. Nuestro primer ejemplo contendrá las claves 0, 1, 2 y 3.

Véase también Funciones de arrays y Variables desde fuentes externas.

¿Cómo obtengo todos los resultados de una etiqueta de selección múltiple en HTML?

La etiqueta de selección múltiple en una construcción HTML permite a los usuarios elegir varios elementos de una lista. Estos elementos son pasados entonces al gestor de la acción del formulario. El problema es que todos son pasados con el mismo nombre de control. Es decir,

<select name="var" multiple="yes">
Cada opción elegida llegará al gestor de la acción como:
      var=opcion1
      var=opcion2
      var=opcion3
Cada opción sobrescribirá el contenido de la variable $var anterior. La solución es usar la característica "array desde un elemento de formulario" de PHP. Debería usarse la siguiente forma:
<select name="var[]" multiple="yes">
Esto le indica a PHP que debe tratar $var como un array y que cada asignación de un valor a var[] añade un elemento al array. El primer elemento se convierte en $var[0], el siguiente en $var[1], etc. La función count() puede usarse para determinar cuántas opciones fueron seleccionadas, y la función sort() puede usarse para ordenar el array de opciones si fuera necesario.

Observe que si se está usando JavaScript, los caracteres [] en el nombre del elemento podrían causar problemas al intentar referirse al elemento por su nombre. Use el ID numérico del elemento del formulario en su lugar, o encierre el nombre de la variable entre comillas simples y úselo como índice del array de elementos, por ejemplo:

      variable = document.forms[0].elements['var[]'];

¿Cómo puedo pasar una variable de Javascript a PHP?

Ya que Javascript es una tecnología (usualmente) del lado del cliente, y PHP es (usualmente) una tecnología del lado del servidor, y dado que HTTP es un protocolo "sin estados", los dos lenguajes no pueden compartir variables directamente.

Sin embargo, es posible pasar variables entre los dos. Una forma de hacerlo es generar código Javascript con PHP, y hacer que el navegador se refresque a sí mismo, volviendo a pasar variables específicas al script de PHP. El ejemplo de abajo muestra precisamente cómo hacer esto; permite que el código de PHP capture el alto y el ancho de la pantalla, algo que normalmente sólo es posible en el lado del cliente.

Ejemplo #4 Generación de Javascript con PHP

<?php
if (isset($_GET['ancho']) AND isset($_GET['alto'])) {
  // imprimir las variables de geometría
  echo "El ancho de la pantalla es: ". $_GET['ancho'] ."<br />\n";
  echo "El alto de la pantalla es: ". $_GET['alto'] ."<br />\n";
} else {
  // pasar las variables de geometría
  // (preservar la cadena de consulta original
  //   -- las variables post deberán ser manejadas de otra forma)

  echo "<script language='javascript'>\n";
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&ancho=\" + screen.width + \"&alto=\" + screen.height;\n";
  echo "</script>\n";
  exit();
}
?>

User Contributed Notes

murphy 28-Jan-2020 08:58
The scenario:

1. There is a php script which (possibly complemented by a direct written HTML code) consrtucts a HTML page via its echo command, based on whatever algoritmus eventually based on supplementary data from server files or databases.

2. This php script leads to data being saved into string variable(s), which (possibly) can contain arbitrary characters, including control codes (newline, tab...), HTML special characters (&,<...) and non-ASCII (international) characters.

3. These non-ASCII characters are UTF-8 encoded, as well as the HTML page (I do highly recommend) *)

4. The values of these PHP string variables have to be transferred into javascript variables for further processing by javascript (or exposing these values in HTML directly)

The problem:

it is not safe to PHP-echo such variables into HTML (javascript) directly, because some of characters possily contained in them cause malfunction of the HTML. These strings need some encoding/escaping in order to become strings of non-conflicting characters

The solution

There may be a big lot of ways of this encoding. The following one seems to me the easiest one:
The PHP variable with unpredictable value can originate from some file, as an example (or from user input as well):

$variable=file_get_content(...)

1. Convert all bytes of that string into hex values and prepend all hex-digit-pairs with %

$variable_e=preg_replace("/(..)/","%$1",bin2hex($variable))

The new variable is now guarantied to contain only %1234567890abcdefABCDEF chracters (e.g. %61%63%0a...) and can safely be directly echoed into HTML:

var variable="<?php echo $variable_e;?>" //that's NOT all folks

But now the value is still encoded. To get the original value of the variable, it has te be decoded: *)

var variable=decodeURIComponent("<?php echo $variable_e;?>")

The value of the variable is now the same as the original value.

*) I have no idea about non-UTF-8 encoded pages/data, espetially how the decodeURIComponent works in such a case, because i have no reason to use other encodings and handle them as highly deprecatad.

WARNING: this approach is not (generally) safe against code injection. I highly recommend some further check (parsing) of the value depending on the particular case.

P.S. For very large amount of data, I would recomment to save them into file on the PHP side (file_put_content) and read them by javascript via HTTP Request.

I use this approach as it needs one line of code on server as well as client side. I do agree with arguement that not all chaeacters have to be encoded.

Do not enjoy my possibly stupid solution, if you have a better idea

murphy
starbugfourtytwo at gmail dot com 29-May-2019 11:04
Why use such a complicated example for js to php? why not do this..so we can understand:

javascript:

const variable = "A"

php:

do whatever it takes to get A from javascript
smileytechguy at smileytechguy dot com 02-Feb-2018 04:55
The (at least that I've found) best way to pass data from PHP to JS is json_encode.  Doing so will convert arrays, strings, numbers, etc. as best as possible.

<?php
$myInt = 7;
// a bunch of special characters to demonstrate proper encoding
$myString = <<<EOF
" ' ; &\ $
EOF;
$myArr = [1, "str", 2];
$myAssocArr = ["foo" => "bar"];
?>

<script>
var myInt = <?= json_encode($myInt) ?>;
var myString = <?= json_encode($myString) ?>;
var myArr = <?= json_encode($myArr) ?>;
var myAssocArr = <?= json_encode($myAssocArr) ?>;
</script>

This will render the following JS code, which correctly stores the variables:
<script>
var myInt = 7;
var myString = "\" ' ; &\\ $";
var myArr = [1,"str",2];
var myAssocArr = {"foo":"bar"};
</script>

Do note that there are no "s or anything like that around the json_encode output; json_encode handles that for you.
Jay 01-Apr-2014 09:25
If you have a really large form, be sure to check your max_input_vars setting.  Your array[] will get truncated if it exceeds this.  http://www.php.net/manual/en/info.configuration.php#ini.max-input-vars
jetboy 30-Dec-2005 07:06
While previous notes stating that square brackets in the name attribute are valid in HTML 4 are correct, according to this:

http://www.w3.org/TR/xhtml1/#C_8

the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.

Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document.


PHP y COM

PHP puede ser usado para acceder a objetos COM y DCOM en plataformas Win32.

  1. He compilado un DLL para calcular algo. ¿Hay alguna forma de ejecutar ese DLL bajo PHP?
  2. ¿Qué quiere decir 'Unsupported variant type: xxxx (0xxxxx)'?
  3. ¿Es posible manipular objetos visuales en PHP?
  4. ¿Puedo almacenar un objeto COM en una sesión?
  5. ¿Cómo puedo atrapar errores de COM?
  6. ¿Puedo generar archivos DLL desde scripts PHP como puedo en Perl?
  7. ¿Qué quiere decir 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}'?
  8. ¿Cómo puedo ejecutar un objeto COM desde un servidor remoto?
  9. Recibo 'DCOM is disabled in C:\ruta...\nombre_script.php on line 6', ¿qué puedo hacer?
  10. ¿Es posible leer/manipular un objeto ActiveX en una página con PHP?
  11. ¿Es posible obtener una instancia en ejecución de un componente?
  12. ¿Hay una forma de manejar un evento enviado desde un objeto COM?
  13. Estoy teniendo problemas al intentar invocar un método de un objeto COM el cual expone más de una interfaz. ¿Qué puedo hacer?
  14. Así que PHP funciona con COM, ¿qué hay de COM+?
  15. Si PHP puede manipular objetos COM, ¿podemos imaginar el uso de MTS para manejar recursos de componentes, en conjunto con PHP?
He compilado un DLL para calcular algo. ¿Hay alguna forma de ejecutar ese DLL bajo PHP?

Si se trata de un DLL simple no hay forma aun de ejecutarlo desde PHP. Si el archivo DLL contiene un servidor COM es posible que pueda acceder a él si implementa la interfaz IDispatch.

¿Qué quiere decir 'Unsupported variant type: xxxx (0xxxxx)'?

Existen docenas de tipos VARIANT y combinaciones de ellos. La mayoría de ellos son soportados pero algunos aun deben ser implementados. Las matrices no están completamente soportadas. Solo las matrices unidimensionales de índice pueden ser pasadas entre PHP y COM. Si encuentra otros tipos que no sean soportados, por favor repórtelos como un bug (si aun no han sido reportados) y ofrezca tanta información como tenga disponible.

¿Es posible manipular objetos visuales en PHP?

En general es posible, pero ya que PHP es usado frecuentemente como un lenguaje de scripting web, corre en el contexto de servidores web, por lo que objetos visuales nunca aparecerán en el escritorio de los servidores. Si usa PHP para una aplicación de scripting, p.ej. en conjunto con PHP-GTK, no hay limitaciones al acceder y manipular objetos visuales a través de COM.

¿Puedo almacenar un objeto COM en una sesión?

No, no puede. Las instancias COM son tratadas como recursos y por lo tanto sólo están disponibles en el contexto de un script único.

¿Cómo puedo atrapar errores de COM?

La extensión COM lanza excepciones com_exception, las cuales puede atrapar y luego inspeccionar el miembro code para determinar el siguiente paso.

¿Puedo generar archivos DLL desde scripts PHP como puedo en Perl?

No, desafortunadamente no existe una herramienta de ese tipo disponible para PHP.

¿Qué quiere decir 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}'?

Este error puede tener varias razones:

  • el valor CLSID es incorrecto
  • el archivo DLL solicitado no existe
  • el componente solicitado no implementa la interfaz IDispatch

¿Cómo puedo ejecutar un objeto COM desde un servidor remoto?

Exactamente como ejecuta objetos locales. Tan solo debe pasar la IP de la máquina remota como segundo parámetro al constructor COM.

Asegúrese de que ha definido com.allow_dcom =true en su php.ini.

Recibo 'DCOM is disabled in C:\ruta...\nombre_script.php on line 6', ¿qué puedo hacer?

Edite su archivo php.ini y defina com.allow_dcom =true.

¿Es posible leer/manipular un objeto ActiveX en una página con PHP?

Esto no tiene nada que ver con PHP. Los objetos ActiveX son cargados en el lado del cliente si son solicitados por el documento HTML. No hay relación con el script PHP y por lo tanto no hay una interacción directa posible con el lado del servidor.

¿Es posible obtener una instancia en ejecución de un componente?

Esto es posible con la ayuda de monikers. Si desea obtener múltiples referencias a la misma instancia de word, puede crear esa instancia como se muestra:

<?php
$word = new COM("C:\docs\word.doc");
?>

Esto creará una nueva instancia si no hay una instancia en ejecución disponible, o devolverá un gestor a la instancia en ejecución, si existe.

¿Hay una forma de manejar un evento enviado desde un objeto COM?

Puede definir el receptor de un evento y asociarlo usando com_event_sink(). Es posible usar com_print_typeinfo() para que PHP genere un esqueleto para la clase receptora del evento.

Estoy teniendo problemas al intentar invocar un método de un objeto COM el cual expone más de una interfaz. ¿Qué puedo hacer?

La respuesta es tan simple como poco satisfactoria. No estamos seguros pero parece que no es posible hacer nada. Si alguien tiene información específica al respecto, por favor » infórmenos :)

Así que PHP funciona con COM, ¿qué hay de COM+?

COM+ extiende COM mediante un marco para administrar componentes a través de MTS y MSMQ pero no hay nada especial que PHP deba soportar para usar tales componentes.

Si PHP puede manipular objetos COM, ¿podemos imaginar el uso de MTS para manejar recursos de componentes, en conjunto con PHP?

PHP por sí mismo no maneja transacciones aun. Por lo tanto si un error ocurre no se inicia un proceso rollback. Si usa componentes que soporten transacciones tendrá que implementar la gestión de transacciones usted mismo.

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.


Preguntas Varias

Puede que existan algunas preguntas que no podemos colocar en otras categorías. Este es el lugar en donde puede encontrarlas.

  1. ¿Cómo puedo manipular los manuales comprimidos mediante bz2 en Windows?
¿Cómo puedo manipular los manuales comprimidos mediante bz2 en Windows?

Si no cuenta con una herramienta de archivación que pueda manejar archivos bz2, » descargue la herramienta de línea de comandos de RedHat (por favor refiérase a la inforamción presentada más adelante).

Si no desea usar una herramienta de línea de comandos, puede probar herramientas gratuitas como » Stuffit Expander, » UltimateZip, » 7-Zip, o » Quick Zip. Si dispone de herramientas como » WinRAR o » Power Archiver, puede descomprimir fácilmente archivos bz2 con ellas. Si usa Total Commander (anteriormente Windows Commander), un módulo adicional para ese programa se encuentra disponible de forma gratuita desde el sitio de » Total Commander.

La herramienta bzip2 de línea de comandos por Redhat:

Los usuarios de Win2k Sp2 deben obtener la versión más reciente, 1.0.2, todos los demás usuarios de Windows deben obtener la versión 1.00. Después de la descarga, renombre el ejecutable a bzip2.exe. Para mayor conveniencia, colóquelo en un directorio que sea parte de sus rutas predeterminadas, p.ej. C:\Windows, en donde C representa la unidad en donde se encuentra su instalación de Windows.

Nota: lang representa su lenguaje, y x el formato deseado, p.ej: pdf. Para descomprimir el archivo php_manual_lang.x.bz2 siga las siguientes instrucciones:

  • abra una ventana con el intérprete de comandos
  • cambie de directorio hacia la carpeta en donde almacenó el archivo php_manual_lang.x.bz2 descargado
  • invoque bzip2 -d php_manual_lang.x.bz2, extrayendo de este modo php_manual_lang.x en la misma carpeta

En caso de que haya descargado el archivo php_manual_lang.tar.bz2 con varios archivos html en su interior, el procedimiento es el mismo. La única diferencia es que recibe un archivo php_manual_lang.tar. Se conoce que el formato tar es tratado por la mayoría de archivadores en Windows, como por ejemplo » WinZip.

User Contributed Notes

doerr at apkk dot de 28-Dec-2010 05:41
If you only needed register_globals for get/post variables, the effictive solution for 5.3 is:
  import_request_variables("GPC", "");

But if the skripts relied on session_register() you'll have to do more:
- Replace all variables that appeared after session_register with _SESSION equivalents - so $myvar becomes $_SESSION['myvar']
- Take care if your variables appeared inside strings - 'Hello $user !' works, but 'Hello $_SESSION['user'] !' not - so you have to concatenate the string: 'Hello '.$_SESSION['user'] .' !'
- Session variables in function declarations (for whatever purpose) will not work - keeping the old (local) names will work in most cases.
- Finally, replace the session_register(..) line with session_start()
markus 18-Jun-2005 03:34
Considering the comment below. I think there's a way to avoid that "problem":

<?php
//
// $starttime is an example of a variable that we might need to define,
// even before, running the "register_globals OFF" emulator below.
//
list($msec, $sec) = explode(' ', microtime());
$starttime = ((float)$msec + (float)$sec);

//
// If register_globals is ON, ensure no unexpected globals are defined.
// ie. We'll try to emulate a register_globals OFF environment.
//
if( (bool)@ini_get('register_globals') )
{
    $superglobals = array($_ENV, $_GET, $_POST, $_COOKIE, $_FILES, $_SERVER);
    if( isset($_SESSION) )
    {
        array_unshift($superglobals, $_SESSION);
    }
    $knownglobals = array(
        //
        // Known PHP Reserved globals and superglobals:
        //
        '_ENV',        'HTTP_ENV_VARS',
        '_GET',        'HTTP_GET_VARS',
        '_POST',    'HTTP_POST_VARS',
        '_COOKIE',    'HTTP_COOKIE_VARS',
        '_FILES',    'HTTP_FILES_VARS',
        '_SERVER',    'HTTP_SERVER_VARS',
        '_SESSION',    'HTTP_SESSION_VARS',
        '_REQUEST',

        //
        // Global variables used by this code snippet:
        //
        'superglobals',
        'knownglobals',
        'superglobal',
        'global',
        'void',

        //
        // Known global variables defined before this code snippet is reached.
        //
        'starttime',
    );
    foreach( $superglobals as $superglobal )
    {
        foreach( $superglobal as $global => $void )
        {
            if( !in_array($global, $knownglobals) )
            {
                unset($GLOBALS[$global]);
            }
        }
    }
}
?>

Note the stuff related to the $_SESSION array depends on whether the PHP session has been started or not. You might want to call session_start() before this point (or set session.auto_start ON).

HTH+ :)
php at REMOVEMEkennel17 dot co dot uk 12-Apr-2005 08:22
Regarding simulating register_globals = off, note that it is impossible to adequately prevent $_SESSION variables from being globalised, as the array (and thus the globals) are created on a call to session_start().  You would therefore have to 'undo' this when you start a session as using it at the start of your script will have no effect.

To avoid potential problems, use a prefix that is unique for all session variables (e.g. 'SESS_'), and only access them via the $_SESSION array.  The prefix ensures that you don't have a naming clash (and therefore a security risk) with any non-session globals.


Apéndices

  • Historia de PHP y Proyectos Relacionados
    • Historia de PHP
    • Historia de los proyectos relacionados con PHP
    • Libros sobre PHP
    • Publicaciones sobre PHP
  • Migración de PHP 7.4.x a PHP 8.0.x
    • Nuevas características
    • Cambios incompatibles hacia atrás
    • Características obsoletas
    • Other Changes
  • Migración de PHP 7.3.x a PHP 7.4.x
    • New Features
    • Nuevas clases e interfaces
    • Nuevas funciones
    • Nuevas constantes globales
    • Backward Incompatible Changes
    • Características obsoletas
    • Extensiones eliminadas
    • Other Changes
    • Windows Support
  • Migración de PHP 7.2.x a PHP 7.3.x
    • Nuevas características
    • Nuevas funciones
    • Nuevas constantes globales
    • Cambios incompatibles con el pasado
    • Características obsoletas
    • Other Changes
    • Soporte de Windows
  • Migración de PHP 7.1.x a PHP 7.2.x
    • New features
    • Nuevas funciones
    • Nuevas constantes globales
    • Cambios incompatibles hacia atrás
    • Características obsoletas en PHP 7.2.x
    • Otros cambios
  • Migración de PHP 7.0.x a PHP 7.1.x
    • Nuevas características
    • Nuevas funciones
    • Nuevas constantes globales
    • Cambios retroincompatibles
    • Características obsoletas en PHP 7.1.x
    • Changed functions
    • Otros cambios
    • Soporte para Windows
  • Migración de PHP 5.6.x a PHP 7.0.x
    • Cambios retroincompatibles
    • Nuevas características
    • Características obsoletas en PHP 7.0.x
    • Funciones cambiadas
    • Nuevas funciones
    • Nuevas clases e interfaces
    • Nuevas constantes globales
    • Cambios en los Módulos SAPI
    • Extensiones y SAPI eliminadas
    • Otros cambios
  • Migración de PHP 5.5.x a PHP 5.6.x
    • Cambios retroincompatibles
    • Características nuevas
    • Características obsoletas en PHP 5.6.x
    • Cambios en funciones
    • Nuevas funciones
    • Cambios de OpenSSL en PHP 5.6.x
    • Otros cambios en extensiones
    • Nuevas constantes globales
  • Depuración en PHP
    • Sobre la depuración en PHP
  • Opciones de configuración
    • Listado de opciones de configuración del núcleo
  • Directivas de php.ini
    • Listado de directivas de php.ini
    • Lista de secciones de php.ini
    • Descripción de las directivas del núcleo de php.ini
  • Categorización de Extensiones
    • Alfabética
    • Incorporación
    • Estado
  • Listado de funciones alias
  • Lista de palabras reservadas
    • Lista de palabras reservadas
    • Clases predefinidas
    • Constantes predefinidas
    • Listado de otras palabras reservadas
  • Lista de Tipos de Recurso
  • Lista de filtros disponibles
    • Filtros de String
    • Filtros de conversión
    • Filtros de compresión
    • Filtros de encriptación
  • Lista de Transportes de Sockets Soportados
    • Dominio de Internet: TCP, UDP, SSL, y TLS
    • Dominio Unix: Unix y UDG
  • Tablas de comparación de tipos de PHP
  • Lista de componentes léxicos del analizador
  • Guía de entorno de usuario para nombres
    • Global Namespace
    • Reglas
    • Tips
  • Acerca del manual
    • Formatos
    • Acerca de los comentarios de usuarios
    • Como interpretar la definición de una función (prototipo)
    • Versiones de PHP documentadas en este manual
    • Cómo encontrar más información sobre PHP
    • Cómo ayudar a mejorar la documentación
    • Cómo generamos los formatos
    • Traducciones
  • Creative Commons Attribution 3.0
  • Listado de índices
    • Listado de Funciones y Métodos
    • Listado de ejemplos
  • Registro de cambios

User Contributed Notes

There are no user contributed notes for this page.


Historia de PHP y Proyectos Relacionados

Tabla de contenidos

  • Historia de PHP
  • Historia de los proyectos relacionados con PHP
  • Libros sobre PHP
  • Publicaciones sobre PHP

PHP ha recorrido un largo camino desde su nacimiento a mediados de los 90. Desde sus humildes comienzos hasta ser uno de los más importantes lenguajes de programación web, la evolución de PHP es un cuento de hadas para "geeks". Pero ojo, un crecimiento explosivo como tal no era una tarea fácil. Aquellos de ustedes que estén interesados en ver brevemente cómo PHP creció hasta convertirse en lo que es hoy, lean. Si le gustaría tocar una pieza de la historia de Internet, puede encontrar versiones antiguas de PHP en el » Museo de PHP.

User Contributed Notes

tarlepp 21-Jul-2017 12:01
It seems like PHP7 is missing here totally, also some comment about why skip PHP6 version would be nice.


Historia de PHP

PHP Tools, FI, Equipo de Construcción, y PHP/FI

PHP tal y como se conoce hoy en día es en realidad el sucesor de un producto llamado PHP/FI. Creado en 1994 por Rasmus Lerdorf, la primera encarnación de PHP era un conjunto simple de ficheros binarios Common Gateway Interface (CGI) escritos en el lenguaje de programación C. Originalmente utilizado para rastrear visitas de su currículum online, llamó al conjunto de scripts "Personal Home Page Tools", más frecuentemente referenciado como "PHP Tools". Con el paso del tiempo se quiso más funcionalidad, y Rasmus reescribió PHP Tools, produciendo una implementación más grande y rica. Este nuevo modelo fue capaz de interaccionar con bases de datos, y mucho más, proporcionando un entorno de trabajo sobre cuyos usuarios podían desarrollar aplicaciones web dinámicas sencillas tales como libros de visitas. En junio de 1995, Rasmus » publicó el código fuente de PHP Tools, lo que permitió a los desarrolladores usarlo como considerasen apropiado. Esto también permitió -y animó- a los usuarios a proporcionar soluciones a los errores del código, y generalmente a mejorarlo.

En septiembre de ese mismo año, Rasmus amplió PHP y -por un corto periodo de tiempo- abandonó el nombre de PHP. Ahora, refiriéndose a las herramientas como FI (abreviatura de "Forms Interpreter"), la nueva implementación incluía algunas de las funciones básicas de PHP tal y como la conocemos hoy. Tenía variables como las de Perl, interpretación automática de variables de formulario y sintaxis incrustada HTML. La sintaxis por sí misma era similar a la de Perl, aunque mucho más limitada, simple y algo inconsistente. De hecho, para embeber el código en un fichero HTML, los desarrolladores tenían que usar comentarios de HTML. Aunque este método no era completamente bien recibido, FI continuó gozando de expansión y aceptación como una herramienta CGI --- pero todavía no completamente como lenguaje. Sin embargo, esto comenzó a cambiar al mes siguiente; en octubre de 1995 Rasmus publicó una versión nueva del código. Recordando el nombre PHP, ahora era llamado (resumidamente) "Personal Home Page Construction Kit," y fue la primera versión que presumía de ser, en aquel momento, considerada como una interfaz de scripts avanzada. El lenguaje fue deliberadamente diseñado para asemejarse a C en estructura, haciéndolo una adopción sencilla para desarrolladores familiarizados con C, Perl, y lenguajes similares. Habiendo sido así bastante limitado a sistemas UNIX y compatibles con POSIX, el potencial para una implementación de Windows NT estaba siendo explorada.

El código fue completamente rehecho de nuevo, y en abril de 1996, combinando los nombres de versiones anteriores, Rasmus introdujo PHP/FI. Esta implementación de segunda generación comenzó realmente a desarrollar PHP desde un conjunto de herramientas dentro de un lenguaje de programación de derecho propio. Incluía soporte interno para DBM, mSQL, y bases de datos Postgres95, cookies, soporte para funciones definidas por el usuario, y mucho más. Ese mes de junio, PHP/FI brindó una versión 2.0. Sin embargo, un interesante hecho sobre esto, es que sólo había una única versión completa de PHP 2.0. Cuando finalmente pasó de la versión beta en noviembre de 1997, el motor de análisis subyacente ya estaba siendo reescrito por completo.

Aunque vivió una corta vida de desarrollo, continuó gozando de un crecimiento de popularidad en el aún joven mundo del desarrollo. En 1997 y 1998, PHP/FI tenía un culto de varios miles de usuarios en todo el mundo. Una encuesta de Netcraft en mayo de 1998 indicó que cerca de 60,000 dominios reportaron que tenían cabeceras que contenían "PHP", indicando en efecto que el servidor host lo tenía instalado. Este número se correspondía con aproximadamente el 1% de todos los dominios de Internet del momento. A pesar de estas impresionantes cifras, la maduración de PHP/FI estaba condenada por limitaciones; mientras habían varios contribuidores menores, aún era desarrollado principalmente por un individuo.

Ejemplo #1 Ejemplo de Código PHP/FI

<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  Hey, ¡está usando Netscape!<p>
<!--endif-->

<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
  Lo siento, esta entrada no existe<p>
<!--endif exit-->
  Bienvenido <!--$user-->!<p>
  Le quedan <!--$index:0--> créditos en su cuenta.<p>

<!--include /text/footer.html-->

PHP 3

PHP 3.0 fue la primera versión que más se parecía al PHP que existe hoy. Encontrando todavía PHP/FI 2.0 ineficiente y falto de las características que necesitaban para impulsar una aplicación de comercio electrónico que estaban desarrollando para un proyecto de universidad, Andi Gutmans y Zeev Suraski, de Tel Aviv, Israel, comenzaron otra nueva versión del analizador subyacente en 1997. Proponiendo Rasmus online, discutieron varios aspectos de la implementación actual y su redesarrollo de PHP. En un esfuerzon para mejorar el motor y comenzar a construir sobre la base de usuario de PHP/FI existente, Andi, Rasmus y Zeev decidieron colaborar en el desarrollo de un nuevo e independiente lenguaje de programación. Este lenguaje completamente nuevo fue publicado bajo un nuevo nombre, que eliminó la implicación del uso limitado personal que el nombre PHP/FI tenía. Fue renombrado simplemente como 'PHP', con el significado de un acrónimo recursivo - PHP: Hypertext Preprocessor.

Una de las mejores características de PHP 3.0 era su gran extensibilidad. Además de proveer a los usuarios finales de una interfaz madura para múltiplies bases de datos, protocolos, y APIs, la sencillez de ampliar el lenguaje mismo atrajo a docenas de desarrolladores que presentaron variedad de módulos. Podría decirse que esta fue la clave para el tremendo éxito de PHP 3.0. Otras características clave introducidas en PHP 3.0 incluían el soporte para programación orientada a objetos y una sintaxis de lenguaje mucho más potente y consistente.

En junio de 1998, con muchos nuevos desarrolladores de todo el mundo unidos al esfuerzon, PHP 3.0 fue anunciado por el nuevo Equipo de Desarrollo de PHP como el sucesor oficial de PHP/FI 2.0. El desarrollo activo de PHP/FI 2.0, que estaba casi parado desde noviembre del año anterior, fue oficialmente finalizado. Después de aproximadamente nueve meses de pruebas públicas, cuando el anuncio de la versión oficial de PHP 3.0 vino, ya estaba instalado en más de 70,000 dominios de todo el mundo, y ya no estaba limitado a sistemas operativos compatibles con POSIX. Una relativamente pequeña parte de de los dominios que tenían instalado PHP estaban albergados en servidores que ejecutaban Windows 95, 98, y NT, y Macintosh. En este punto, PHP 3.0 estaba instalado en aproximadamente el 10% de los servidores web de Internet.

PHP 4

En el invierno de 1998, poco después del lanzamiento oficial de PHP 3.0, Andi Gutmans y Zeev Suraski comenzaron a trabajar en una nueva versión del núcleo de PHP. Los objetivos de diseño fueron mejorar la ejecución de aplicaciones complejas y mejorar la modularidad del código base de PHP. Estas aplicaciones se hicieron posibles por las nuevas características de PHP 3.0 y el apoyo de una gran variedad de bases de datos y APIs de terceros, pero PHP 3.0 no estaba diseñado para un mantenimiento tan complejo de aplicaciones eficientemente.

El nuevo motor, apodado 'Motor Zend' (proviene de sus nombres de pila, Zeev y Andi), alcanzó estos objetivos de diseño satisfactoriamente, y se introdujo por primera vez a mediados de 1999. PHP 4.0, basado en este motor, y asociado con un gran rango de nuevas características adicionales, fue oficialmente publicado en Mayo del 2000, casi dos años después que su predecesor. Además de la mejora de rendimiento de esta versión, PHP 4.0 incluía otras características clave como el soporte para la mayoría de los servidores Web, sesiones HTTP, buffers de salida, formas más seguras de controlar las entradas de usuario y muchas nuevas construcciones de lenguaje.

PHP 5

PHP 5 fué lanzado en Julio del 2004 después de un largo desarrollo y varios pre-releases. Está básicamente impulsado por su núcleo, Zend Engine 2.0 que contiene un nuevo modelo de objectos y docenas de nuevas opciones.

El equipo de desarrollo de PHP incluye docenas de desarrolladores, así como docenas de otras personas trabajando en proyectos relacionados y de soporte para PHP, como PEAR, PECL, y documentación, y una infraestructura en red subyacente de más de cien servidores web individuales en seis de los siete continentes del mundo. Aunque es solo una estimación basada en estadísticas de años ateriores, es seguro suponer que PHP ahora está instalado en diez o quizá cien millones de dominios en todo el mundo.

User Contributed Notes

There are no user contributed notes for this page.


Historia de los proyectos relacionados con PHP

PEAR

» PEAR, la extensión de PHP y repositorio de aplicaciones (originalmente, extensión de PHP y repositorio add-on) es la base de clases para PHP y en un futuro seguramente será la forma de distribuir extensiones PHP entre desarrolladores.

PEAR nació de las discusiones mantenidas en el PHP Developers' Meeting (PDM) transcurrido en Enero de 2000 en Tel Aviv. Fue creado por Stig S. Bakken, y lo dedicó a su primogénita, Malin Bakken.

Hasta principios de 2000, PEAR fue creciendo hasta ser un gran y significativo proyecto con un gran número de programadores trabajando en la implementación común, funcionalidad reutilizable para el beneficio de toda la comunidad PHP. PEAR hoy incluye una gran variedad de clases de infraestructura para acceso a bases de datos, caché de contenido, cálculos matemáticos, comercio electrónico y mucho más.

Más información sobre PEAR se puede encontrar en » el manual.

Garantía de calidad de PHP

La » Iniciativa para la Garantía de Calidad de PHP se configuró en el verano de 2000 en respuesta a los que criticaban que las versiones de PHP se liberaban sin que fueran comprobadas suficientemente para entornos de producción. El equipo ahora consiste en un grupo central de desarrolladores con un buen entendimiento del código base de PHP. Estos desarrolladores están mucho tiempo localizando y solucionando problemas con PHP. Además, hay muchos miembros de otros equipos que testean y prueban estas soluciones usando una gran variedad de plataformas.

PHP-GTK

» PHP-GTK es la solución PHP para escribir las aplicaciones GUI del lado del cliente. Andrei Zmievski nos recuerda la planificación y la creación del proceso de PHP-GTK:

Programar GUI siempre ha estado entre mis intereses, y he encontrado que Gtk+ es una herramienta muy buena, salvo que programar con ella en C es algo tedioso. Tras presenciar las implementaciones de PyGtk y GTK-Perl, decidí ver si PHP se podría hacer con la interfaz Gtk+, incluso mínimamente. En Agosto de 2000 empecé a tener más tiempo libre, con lo que comencé a experimentar. Mi principal guía fue la implementación PyGtk con características completas bastante buenas y con un buen interfaz orientado a objetos. James Henstridge, el autor de PyGtk, proveyó mucha ayuda adicional durante esos estados iniciales.

Escribir las interfaces de todas las funciones Gtk+ estaba fuera de cuestión, por lo que mantuve la idea de generador de código, similar a cómo PyGtk lo hizo. El generador de código es un programa PHP que lee un conjunto de ficheros .defs que contienen las clases Gtk+, constantes e información de métodos y genera código C que interactúa PHP con ellos. Lo que no se puede generar automáticamente puede escribirse a mano en ficheros .overrides.

Trabajar en el generador de código y la infraestructura llevó algo de tiempo, porque pude dedicar poco tiempo a PHP-GTK durante el otoño de 2000. Después mostré PHP-GTK a Frank Kromann, que se interesó y empezó a ayudarme con el trabajo del generador de código y con la implementación para Win32. Cuando escribimos el primer programa Hola Mundo y funcionó, fue extremadamente excitante. Llevó un par de meses más llevar el proyecto a una condición presentable y la versión inicial se liberó el 1 de Marzo de 2001. La historia rápidamente llegó a SlashDot.

Dándome cuenta que PHP-GTK podría extenderse, configuré listas de correo separadas y repositorios CVS para ello, así como el sitio web gtk.php.net con la ayuda de Colin Viebrock. La documentación también tenía que hacerse y James Moore se únio al proyecto para ayudar en esto.

Desde su lanzamiento PHP-GTK fue ganando popularidad. Tenemos nuestro propio equipo de documentación, el manual sigue mejorando, la gente ha comenzado a escribir extensiones para PHP-GTK, y con ello más y mejores aplicaciones.

User Contributed Notes

There are no user contributed notes for this page.


Libros sobre PHP

Según crecía PHP, empezó a ser reconocido como una popular plataforma de desarrollo web. Una de las más interesantes formas de ver esta tendencia fué observando los libros de PHP que han ido publicando a lo largo de los años.

Por lo que nosotros sabemos, el primer libro dedicado a PHP fue 'PHP - tvorba interaktivních internetových aplikací' (PHP - Creando aplicaciones interactivas en internet) - un libro checo publicado en 1999, cuyo autor fue Jirka Koseksiendo. Al mes siguiente le siguió un libro alemán cuyos autores fueron Egon Schmid, Christian Cartus y Richard Blume. El primer libro en Inglés sobre PHP se publicó poco después, y fue 'Core PHP Programming' de Leon Atkinson. Los dos libros cubrían PHP 3.0.

Mientras estos libros fueron los primeros de su tipo - fueron seguidos por un gran número de libros de una multitud de autores y editores. ¡Existen más 400 libros en inglés, 100 libros en alemán, y más de 50 libros en francés o español! Además, se pueden encontrar libros sobre PHP en la mayoría de las demás lenguas, incluyendo coreano, japonés y hebreo.

Evidentemente, este gran número de libros, escritos por diferentes autores, publicados por muchos editores, y su disponibilidad en tantas lenguas - son un fuerte testimonio del éxito mundial de PHP.

User Contributed Notes

There are no user contributed notes for this page.


Publicaciones sobre PHP

Por lo que sabemos, el primer artículo sobre PHP en una revista impresa se publicó en la version checa de Computerworld en la primavera de 1998, y cubría PHP 3.0. Como con los libros, fue el primero en una serie de muchos artículos publicados sobre PHP en varias revistas importantes.

Artículos sobre PHP han aparecido en Dr. Dobbs, Linux Enterprise, Linux Magazine y muchas otras. Artículos sobre migración de aplicaciones basadas en PHP bajo Windows ¡han aparecido incluso en el MSDN de Microsoft!

User Contributed Notes

There are no user contributed notes for this page.


Migración de PHP 7.4.x a PHP 8.0.x

Tabla de contenidos

  • Nuevas características
  • Cambios incompatibles hacia atrás
  • Características obsoletas
  • Other Changes

Esta nueva versión mayor trae consigo una serie de nuevas características y algunas incompatibilidades que debe ser probado antes de cambiar las versiones de PHP en los entornos de producción.

Véanse también las guías de migración para versiones 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.


Nuevas características

PHP Core

Argumentos nombrados

Se ha añadido soporte para losArgumentos nombrados.

Atributos

Se ha añadido soporte para los Atributos.

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.

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.


Cambios incompatibles hacia atrás

PHP Core

String to Number Comparison

Non-strict comparisons between numbers and non-numeric strings now work by casting the number to string and comparing the strings. Comparisons between numbers and numeric strings continue to work as before. Notably, this means that 0 == "not-a-number" is considered false now.

Comparison | Before | After
0 == "0" | true | true
0 == "0.0" | true | true
0 == "foo" | true | false
0 == "" | true | false
42 == " 42" | true | true
42 == "42foo" | true | false

Other incompatible Changes

  • match is now a reserved keyword.

  • Assertion failures now throw by default. If the old behavior is desired, assert.exception=0 can be set in the INI settings.

  • Methods with the same name as the class are no longer interpreted as constructors. The __construct() method should be used instead.

  • The ability to call non-static methods statically has been removed. Thus is_callable() will fail when checking for a non-static method with a classname (must check with an object instance).

  • The (real) and (unset) casts have been removed.

  • The track_errors ini directive has been removed. This means that php_errormsg is no longer available. The error_get_last() function may be used instead.

  • The ability to define case-insensitive constants has been removed. The third argument to define() may no longer be true.

  • The ability to specify an autoloader using an __autoload() function has been removed. spl_autoload_register() should be used instead.

  • The errcontext argument will no longer be passed to custom error handlers set with set_error_handler().

  • create_function() has been removed. Anonymous functions may be used instead.

  • each() has been removed. foreach or ArrayIterator should be used instead.

  • The ability to unbind this from closures that were created from a method, using Closure::fromCallable() or ReflectionMethod::getClosure(), has been removed.

  • The ability to unbind this from proper closures that contain uses of this has also been removed.

  • The ability to use array_key_exists() with objects has been removed. isset() or property_exists() may be used instead.

  • The behavior of array_key_exists() regarding the type of the key parameter has been made consistent with isset() and normal array access. All key types now use the usual coercions and array/object keys throw a TypeError.

  • Any array that has a number n as its first numeric key will use n+1 for its next implicit key, even if n is negative.

  • The default error_reporting level is now E_ALL. Previously it excluded E_NOTICE and E_DEPRECATED.

  • display_startup_errors is now enabled by default.

  • Using parent inside a class that has no parent will now result in a fatal compile-time error.

  • The @ operator will no longer silence fatal errors (E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR, E_PARSE). Error handlers that expect error_reporting to be 0 when @ is used, should be adjusted to use a mask check instead:

    <?php
    // Replace
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
        if (    error_reporting() == 0) {
            return;     // Silenced
            }
            // ...
    }

    // With
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
        if (!(    error_reporting() & $err_no)) {
            return;     // Silenced
            }
            // ...
    }
    ?>

    Additionally, care should be taken that error messages are not displayed in production environments, which can result in information leaks. Please ensure that display_errors=Off is used in conjunction with error logging.

  • #[ is no longer interpreted as the start of a comment, as this syntax is now used for attributes.

  • Inheritance errors due to incompatible method signatures (LSP violations) will now always generate a fatal error. Previously a warning was generated in some cases.

  • The precedence of the concatenation operator has changed relative to bitshifts and addition as well as subtraction.

    <?php
    echo "Sum: " . $a + $b;
    // was previously interpreted as:
    echo ("Sum: " . $a) + $b;
    // is now interpreted as:
    echo "Sum:" . ($a + $b);
    ?>

  • Arguments with a default value that resolves to null at runtime will no longer implicitly mark the argument type as nullable. Either an explicit nullable type, or an explicit null default value has to be used instead.

    <?php
    // Replace
    function test(int $arg = CONST_RESOLVING_TO_NULL) {}
    // With
    function test(?int $arg = CONST_RESOLVING_TO_NULL) {}
    // Or
    function test(int $arg = null) {}
    ?>

  • A number of warnings have been converted into Error exceptions:

    • Attempting to write to a property of a non-object. Previously this implicitly created an stdClass object for null, false and empty strings.
    • Attempting to append an element to an array for which the PHP_INT_MAX key is already used.
    • Attempting to use an invalid type (array or object) as an array key or string offset.
    • Attempting to write to an array index of a scalar value.
    • Attempting to unpack a non-array/Traversable.
    • Attempting to access unqualified constants which are undefined. Previously, unqualified constant accesses resulted in a warning and were interpreted as strings.

    A number of notices have been converted into warnings:

    • Attempting to read an undefined variable.
    • Attempting to read an undefined property.
    • Attempting to read an undefined array key.
    • Attempting to read a property of a non-object.
    • Attempting to access an array index of a non-array.
    • Attempting to convert an array to string.
    • Attempting to use a resource as an array key.
    • Attempting to use null, a boolean, or a float as a string offset.
    • Attempting to read an out-of-bounds string offset.
    • Attempting to assign an empty string to a string offset.

  • Attempting to assign multiple bytes to a string offset will now emit a warning.

  • Unexpected characters in source files (such as NUL bytes outside of strings) will now result in a ParseError exception instead of a compile warning.

  • Uncaught exceptions now go through "clean shutdown", which means that destructors will be called after an uncaught exception.

  • The compile time fatal error "Only variables can be passed by reference" has been delayed until runtime, and converted into an "Argument cannot be passed by reference" Error exception.

  • Some "Only variables should be passed by reference" notices have been converted to "Argument cannot be passed by reference" exception.

  • The generated name for anonymous classes has changed. It will now include the name of the first parent or interface:

    <?php
    new class extends ParentClass {};
    // -> ParentClass@anonymous
    new class implements FirstInterface, SecondInterface {};
    // -> FirstInterface@anonymous
    new class {};
    // -> class@anonymous
    ?>

    The name shown above is still followed by a NUL byte and a unique suffix.

  • Non-absolute trait method references in trait alias adaptations are now required to be unambiguous:

    <?php
    class X {
        use     T1, T2 {
                func as otherFunc;
        }
        function     func() {}
    }
    ?>

    If both T1::func() and T2::func() exist, this code was previously silently accepted, and func was assumed to refer to T1::func. Now it will generate a fatal error instead, and either T1::func or T2::func needs to be written explicitly.

  • The signature of abstract methods defined in traits is now checked against the implementing class method:

    <?php
    trait MyTrait {
        abstract private function     neededByTrait(): string;
    }

    class     MyClass {
        use     MyTrait;

            // Error, because of return type mismatch.
            private function neededByTrait(): int { return 42; }
    }
    ?>

  • Disabled functions are now treated exactly like non-existent functions. Calling a disabled function will report it as unknown, and redefining a disabled function is now possible.

  • data:// stream wrappers are no longer writable, which matches the documented behavior.

  • The arithmetic and bitwise operators +, -, *, /, **, %, <<, >>, &, |, ^, ~, ++, -- will now consistently throw a TypeError when one of the operands is an array, recurso or non-overloaded object. The only exception to this is the array + array merge operation, which remains supported.

  • Float to string casting will now always behave locale-independently.

    <?php
    setlocale    (LC_ALL, "de_DE");
    $f = 3.14;
    echo     $f, "\n";
    // Previously: 3,14
    // Now:        3.14
    ?>

    See printf(), number_format() and NumberFormatter() for ways to customize number formatting.

  • Support for deprecated curly braces for offset access has been removed.

    <?php
    // Instead of:
    $array{0};
    $array{"key"};
    // Write:
    $array[0];
    $array["key"];
    ?>

  • Applying the final modifier on a private method will now produce a warning unless that method is the constructor.

  • If an object constructor exit()s, the object destructor will no longer be called. This matches the behavior when the constructor throws.

  • Namespaced names can no longer contain whitespace: While Foo\Bar will be recognized as a namespaced name, Foo \ Bar will not. Conversely, reserved keywords are now permitted as namespace segments, which may also change the interpretation of code: new\x is now the same as constant('new\x'), not new \x().

  • Nested ternaries now require explicit parentheses.

  • debug_backtrace() and Exception::getTrace() will no longer provide references to arguments. It will not be possible to change function arguments through the backtrace.

  • Numeric string handling has been altered to be more intuitive and less error-prone. Trailing whitespace is now allowed in numeric strings for consistency with how leading whitespace is treated. This mostly affects:

    • The is_numeric() function
    • String-to-string comparisons
    • Type declarations
    • Increment and decrement operations

    The concept of a "leading-numeric string" has been mostly dropped; the cases where this remains exist in order to ease migration. Strings which emitted an E_NOTICE "A non well-formed numeric value encountered" will now emit an E_WARNING "A non-numeric value encountered" and all strings which emitted an E_WARNING "A non-numeric value encountered" will now throw a TypeError. This mostly affects:

    • Arithmetic operations
    • Bitwise operations

    This E_WARNING to TypeError change also affects the E_WARNING "Illegal string offset 'string'" for illegal string offsets. The behavior of explicit casts to int/float from strings has not been changed.

  • Magic Methods will now have their arguments and return types checked if they have them declared. The signatures should match the following list:

    • __call(string $name, array $arguments): mixed
    • __callStatic(string $name, array $arguments): mixed
    • __clone(): void
    • __debugInfo(): ?array
    • __get(string $name): mixed
    • __invoke(mixed $arguments): mixed
    • __isset(string $name): bool
    • __serialize(): array
    • __set(string $name, mixed $value): void
    • __set_state(array $properties): object
    • __sleep(): array
    • __unserialize(array $data): void
    • __unset(string $name): void
    • __wakeup(): void

  • call_user_func_array() array keys will now be interpreted as parameter names, instead of being silently ignored.

  • Declaring a function called assert() inside a namespace is no longer allowed, and issues E_COMPILE_ERROR. The assert() function is subject to special handling by the engine, which may lead to inconsistent behavior when defining a namespaced function with the same name.

Resource to Object Migration

Several recursos have been migrated to objects. Return value checks using is_resource() should be replaced with checks for false.

  • curl_init() will now return a CurlHandle object rather than a recurso. The curl_close() function no longer has an effect, instead the CurlHandle instance is automatically destroyed if it is no longer referenced.

  • curl_multi_init() will now return a CurlMultiHandle object rather than a recurso. The curl_multi_close() function no longer has an effect, instead the CurlMultiHandle instance is automatically destroyed if it is no longer referenced.

  • curl_share_init() will now return a CurlShareHandle object rather than a recurso. The curl_share_close() function no longer has an effect, instead the CurlShareHandle instance is automatically destroyed if it is no longer referenced.

  • enchant_broker_init() will now return an EnchantBroker object rather than a recurso.

  • enchant_broker_request_dict() and enchant_broker_request_pwl_dict() will now return an EnchantDictionary object rather than a recurso.

  • The GD extension now uses GdImage objects as the underlying data structure for images, rather than recursos. The imagedestroy() function no longer has an effect; instead the GdImage instance is automatically destroyed if it is no longer referenced.

  • openssl_x509_read() and openssl_csr_sign() will now return an OpenSSLCertificate object rather than a recurso. The openssl_x509_free() function is deprecated and no longer has an effect, instead the OpenSSLCertificate instance is automatically destroyed if it is no longer referenced.

  • openssl_csr_new() will now return an OpenSSLCertificateSigningRequest object rather than a recurso.

  • openssl_pkey_new() will now return an OpenSSLAsymmetricKey object rather than a recurso. The openssl_pkey_free() function is deprecated and no longer has an effect, instead the OpenSSLAsymmetricKey instance is automatically destroyed if it is no longer referenced.

  • shmop_open() will now return a Shmop object rather than a recurso. The shmop_close() function no longer has an effect, and is deprecated; instead the Shmop instance is automatically destroyed if it is no longer referenced.

  • socket_create(), socket_create_listen(), socket_accept(), socket_import_stream(), socket_addrinfo_connect(), socket_addrinfo_bind(), and socket_wsaprotocol_info_import() will now return a Socket object rather than a recurso. socket_addrinfo_lookup() will now return an array of AddressInfo objects rather than recursos.

  • msg_get_queue() will now return an SysvMessageQueue object rather than a recurso.

  • sem_get() will now return an SysvSemaphore object rather than a recurso.

  • shm_attach() will now return an SysvSharedMemory object rather than a recurso.

  • xml_parser_create() and xml_parser_create_ns() will now return an XMLParser object rather than a recurso. The xml_parser_free() function no longer has an effect, instead the XMLParser instance is automatically destroyed if it is no longer referenced.

  • The XMLWriter functions now accept and return, respectively, XMLWriter objects instead of recursos.

  • inflate_init() will now return an InflateContext object rather than a recurso.

  • deflate_init() will now return a DeflateContext object rather than a recurso.

COM and .Net (Windows)

The ability to import case-insensitive constants from type libraries has been removed. The second argument to com_load_typelib() may no longer be false; com.autoregister_casesensitive may no longer be disabled; case-insensitive markers in com.typelib_file are ignored.

CURL

CURLOPT_POSTFIELDS no longer accepts objects as arrays. To interpret an object as an array, perform an explicit (array) cast. The same applies to other options accepting arrays as well.

Date and Time

mktime() and gmmktime() now require at least one argument. time() can be used to get the current timestamp.

DOM

Unimplemented classes from the DOM extension that had no behavior and contained test data have been removed. These classes have also been removed in the latest version of the DOM standard:

  • DOMNameList
  • DomImplementationList
  • DOMConfiguration
  • DomError
  • DomErrorHandler
  • DOMImplementationSource
  • DOMLocator
  • DOMUserDataHandler
  • DOMTypeInfo

Enchant

  • enchant_broker_list_dicts(), enchant_broker_describe() and enchant_dict_suggest() will now return an empty array instead of null.

Exif

read_exif_data() has been removed; exif_read_data() should be used instead.

Filter

  • The FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED flags for the FILTER_VALIDATE_URL filter have been removed. The scheme and host are (and have been) always required.

  • The INPUT_REQUEST and INPUT_SESSION source for filter_input() etc. have been removed. These were never implemented and their use always generated a warning.

GD

  • The deprecated functions image2wbmp() has been removed.

  • The deprecated functions png2wbmp() and jpeg2wbmp() have been removed.

  • The default mode parameter of imagecropauto() no longer accepts -1. IMG_CROP_DEFAULT should be used instead.

  • On Windows, php_gd2.dll has been renamed to php_gd.dll.

GMP

gmp_random() has been removed. One of gmp_random_range() or gmp_random_bits() should be used instead.

Iconv

iconv implementations which do not properly set errno in case of errors are no longer supported.

IMAP

  • The unused default_host argument of imap_headerinfo() has been removed.

  • The imap_header() function which is an alias of imap_headerinfo() has been removed.

Internationalization Functions

  • The deprecated constant INTL_IDNA_VARIANT_2003 has been removed.

  • The deprecated Normalizer::NONE constant has been removed.

LDAP

  • The deprecated functions ldap_sort(),
ldap_control_paged_result() and
ldap_control_paged_result_response() have been removed.

  • The interface of ldap_set_rebind_proc() has changed; the callback parameter does not accept empty strings anymore; null should be used instead.

MBString

  • The mbstring.func_overload directive has been removed. The related MB_OVERLOAD_MAIL, MB_OVERLOAD_STRING, and MB_OVERLOAD_REGEX constants have also been removed. Finally, the "func_overload" and "func_overload_list" entries in mb_get_info() have been removed.

  • mb_parse_str() can no longer be used without specifying a result array.

  • A number of deprecated mbregex aliases have been removed. See the following list for which functions should be used instead:

    • mbregex_encoding() ? mb_regex_encoding()
    • mbereg() ? mb_ereg()
    • mberegi() ? mb_eregi()
    • mbereg_replace() ? mb_ereg_replace()
    • mberegi_replace() ? mb_eregi_replace()
    • mbsplit() ? mb_split()
    • mbereg_match() ? mb_ereg_match()
    • mbereg_search() ? mb_ereg_search()
    • mbereg_search_pos() ? mb_ereg_search_pos()
    • mbereg_search_regs() ? mb_ereg_search_regs()
    • mbereg_search_init() ? mb_ereg_search_init()
    • mbereg_search_getregs() ? mb_ereg_search_getregs()
    • mbereg_search_getpos() ? mb_ereg_search_getpos()
    • mbereg_search_setpos() ? mb_ereg_search_setpos()

  • The e modifier for mb_ereg_replace() has been removed. mb_ereg_replace_callback() should be used instead.

  • A non-string pattern argument to mb_ereg_replace() will now be interpreted as a string instead of an ASCII codepoint. The previous behavior may be restored with an explicit call to chr().

  • The needle argument for mb_strpos(),
mb_strrpos(), mb_stripos(),
mb_strripos(), mb_strstr(),
mb_stristr(), mb_strrchr() and
mb_strrichr() can now be empty.

  • The is_hex parameter, which was not used internally, has been removed from mb_decode_numericentity().

  • The legacy behavior of passing the encoding as the third argument instead of an offset for the mb_strrpos() function has been removed; an explicit 0 offset with the encoding should be provided as the fourth argument instead.

  • The ISO_8859-* character encoding aliases have been replaced by ISO8859-* aliases for better interoperability with the iconv extension. The mbregex ISO 8859 aliases with underscores (ISO_8859_* and ISO8859_*) have also been removed.

  • mb_ereg() and mb_eregi() will now return boolean true on a successful match. Previously they returned integer 1 if matches was not passed, or max(1, strlen($matches[0])) if matches was passed.

OCI8

  • The OCI-Lob class is now called OCILob, and the OCI-Collection class is now called OCICollection for name compliance enforced by PHP 8 arginfo type annotation tooling.

  • Several alias functions have been marked as deprecated.

  • oci_internal_debug() and its alias ociinternaldebug() have been removed.

ODBC

  • odbc_connect() no longer reuses connections.

  • The unused flags parameter of odbc_exec() has been removed.

OpenSSL

  • openssl_seal() and openssl_open() now require method to be passed, as the previous default of "RC4" is considered insecure.

Regular Expressions (Perl-Compatible)

When passing invalid escape sequences they are no longer interpreted as literals. This behavior previously required the X modifier – which is now ignored.

PHP Data Objects

  • The default error handling mode has been changed from "silent" to "exceptions". See Errors and error handling for details.

  • The signatures of some PDO methods have changed:

    • PDO::query(string $query, ?int $fetchMode = null, mixed ...$fetchModeArgs)
    • PDOStatement::setFetchMode(int $mode, mixed ...$args)

PDO ODBC

The php.ini directive pdo_odbc.db2_instance_name has been removed.

PDO MySQL

PDO::inTransaction() now reports the actual transaction state of the connection, rather than an approximation maintained by PDO. If a query that is subject to "implicit commit" is executed, PDO::inTransaction() will subsequently return false, as a transaction is no longer active.

PostgreSQL

  • The deprecated pg_connect() syntax using multiple parameters instead of a connection string is no longer supported.

  • The deprecated pg_lo_import() and pg_lo_export() signature that passes the connection as the last argument is no longer supported. The connection should be passed as first argument instead.

  • pg_fetch_all() will now return an empty array instead of false for result sets with zero rows.

Phar

Metadata associated with a phar will no longer be automatically unserialized, to fix potential security vulnerabilities due to object instantiation, autoloading, etc.

Reflection

  • The method signatures

    • ReflectionClass::newInstance($args)
    • ReflectionFunction::invoke($args)
    • ReflectionMethod::invoke($object, $args)

    have been changed to:

    • ReflectionClass::newInstance(...$args)
    • ReflectionFunction::invoke(...$args)
    • ReflectionMethod::invoke($object, ...$args)

    Code that must be compatible with both PHP 7 and PHP 8 can use the following signatures to be compatible with both versions:

    • ReflectionClass::newInstance($arg = null, ...$args)
    • ReflectionFunction::invoke($arg = null, ...$args)
    • ReflectionMethod::invoke($object, $arg = null, ...$args)

  • The ReflectionType::__toString() method will now return a complete debug representation of the type, and is no longer deprecated. In particular the result will include a nullability indicator for nullable types. The format of the return value is not stable and may change between PHP versions.

  • Reflection export() methods have been removed. Instead reflection objects can be cast to string.

  • ReflectionMethod::isConstructor() and
ReflectionMethod::isDestructor() now also return true for
__construct() and
__destruct() methods of interfaces.
Previously, this would only be true for methods of classes and traits.

  • ReflectionType::isBuiltin() method has been moved to ReflectionNamedType. ReflectionUnionType does not have it.

Sockets

  • The deprecated AI_IDN_ALLOW_UNASSIGNED and AI_IDN_USE_STD3_ASCII_RULES flags for socket_addrinfo_lookup() have been removed.

Standard PHP Library (SPL)

  • SplFileObject::fgetss() has been removed.

  • SplFileObject::seek() now always seeks to the beginning of the line. Previously, positions =1 sought to the beginning of the next line.

  • SplHeap::compare() now specifies a method signature. Inheriting classes implementing this method will now have to use a compatible method signature.

  • SplDoublyLinkedList::push(), SplDoublyLinkedList::unshift() and SplQueue::enqueue() now return void instead of true.

  • spl_autoload_register() will now always throw a TypeError on invalid arguments, therefore the second argument do_throw is ignored and a notice will be emitted if it is set to false.

  • SplFixedArray is now an IteratorAggregate and not an Iterator. SplFixedArray::rewind(), SplFixedArray::current(), SplFixedArray::key(), SplFixedArray::next(), and SplFixedArray::valid() have been removed. In their place, SplFixedArray::getIterator() has been added. Any code which uses explicit iteration over SplFixedArray must now obtain an Iterator through SplFixedArray::getIterator(). This means that SplFixedArray is now safe to use in nested loops.

Standard Library

  • assert() will no longer evaluate string arguments, instead they will be treated like any other argument. assert($a == $b) should be used instead of assert('$a == $b'). The assert.quiet_eval ini directive and the ASSERT_QUIET_EVAL constant have also been removed, as they would no longer have any effect.

  • parse_str() can no longer be used without specifying a result array.

  • The string.strip_tags filter has been removed.

  • The needle argument of strpos(), strrpos(), stripos(), strripos(), strstr(), strchr(), strrchr(), and stristr() will now always be interpreted as a string. Previously non-string needles were interpreted as an ASCII code point. An explicit call to chr() can be used to restore the previous behavior.

  • The needle argument for strpos(),
strrpos(), stripos(), strripos(),
strstr(), stristr() and strrchr() can
now be empty.

  • The length argument for substr(), substr_count(), substr_compare(), and iconv_substr() can now be null. null values will behave as if no length argument was provided and will therefore return the remainder of the string instead of an empty string.

  • The length argument for array_splice() can now be null. null values will behave identically to omitting the argument, thus removing everything from the offset to the end of the array.

  • The args argument of vsprintf(), vfprintf(), and vprintf() must now be an array. Previously any type was accepted.

  • The 'salt' option of password_hash() is no longer supported. If the 'salt' option is used a warning is generated, the provided salt is ignored, and a generated salt is used instead.

  • The quotemeta() function will now return an empty string if an empty string was passed. Previously false was returned.

  • The following functions have been removed:

    • hebrevc()
    • convert_cyr_string()
    • money_format()
    • ezmlm_hash()
    • restore_include_path()
    • get_magic_quotes_gpc()
    • get_magic_quotes_runtime()
    • fgetss()

  • FILTER_SANITIZE_MAGIC_QUOTES has been removed.

  • Calling implode() with parameters in a reverse order ($pieces, $glue) is no longer supported.

  • parse_url() will now distinguish absent and empty queries and fragments:

    • http://example.com/foo ? query = null, fragment = null
    • http://example.com/foo? ? query = "", fragment = null
    • http://example.com/foo# ? query = null, fragment = ""
    • http://example.com/foo?# ? query = "", fragment = ""
    Previously all cases resulted in query and fragment being null.

  • var_dump() and debug_zval_dump() will now print floating-point numbers using serialize_precision rather than precision. In a default configuration, this means that floating-point numbers are now printed with full accuracy by these debugging functions.

  • If the array returned by __sleep() contains non-existing properties, these are now silently ignored. Previously, such properties would have been serialized as if they had the value null.

  • The default locale on startup is now always "C". No locales are inherited from the environment by default. Previously, LC_ALL was set to "C", while LC_CTYPE was inherited from the environment. However, some functions did not respect the inherited locale without an explicit setlocale() call. An explicit setlocale() call is now always required if a locale component should be changed from the default.

  • The deprecated DES fallback in crypt() has been removed. If an unknown salt format is passed to crypt(), the function will fail with *0 instead of falling back to a weak DES hash now.

  • Specifying out of range rounds for SHA256/SHA512 crypt() will now fail with *0 instead of clamping to the closest limit. This matches glibc behavior.

  • The result of sorting functions may have changed, if the array contains elements that compare as equal.

  • Any functions accepting callbacks that are not explicitly specified to accept parameters by reference will now warn if a callback with reference parameters is used. Examples include array_filter() and array_reduce(). This was already the case for most, but not all, functions previously.

  • The HTTP stream wrapper as used by functions like file_get_contents() now advertises HTTP/1.1 rather than HTTP/1.0 by default. This does not change the behavior of the client, but may cause servers to respond differently. To retain the old behavior, set the 'protocol_version' stream context option, e.g.

    <?php
    $ctx     = stream_context_create(['http' => ['protocol_version' => '1.0']]);
    echo     file_get_contents('http://example.org', false, $ctx);
    ?>

  • Calling crypt() without an explicit salt is no longer supported. If you would like to produce a strong hash with an auto-generated salt, use password_hash() instead.

  • substr(), mb_substr(), iconv_substr() and grapheme_substr() now consistently clamp out-of-bounds offsets to the string boundary. Previously, false was returned instead of the empty string in some cases.

  • On Windows, the program execution functions (proc_open(), exec(), popen() etc.) using the shell, now consistently execute %comspec% /s /c "$commandline", which has the same effect as executing $commandline (without additional quotes).

Sysvsem

  • The auto_release parameter of sem_get() was changed to accept bool values rather than int.

Tidy

  • The use_include_path parameter, which was not used internally, has been removed from tidy_repair_string().

  • tidy::repairString() and tidy::repairFile() became static methods.

Tokenizer

  • T_COMMENT tokens will no longer include a trailing newline. The newline will instead be part of a following T_WHITESPACE token. It should be noted that T_COMMENT is not always followed by whitespace, it may also be followed by T_CLOSE_TAG or end-of-file.

  • Namespaced names are now represented using the T_NAME_QUALIFIED (Foo\Bar), T_NAME_FULLY_QUALIFIED (\Foo\Bar) and T_NAME_RELATIVE (namespace\Foo\Bar) tokens. T_NS_SEPARATOR is only used for standalone namespace separators, and only syntactially valid in conjunction with group use declarations.

XMLReader

XMLReader::open() and XMLReader::xml() are now static methods. They can still be called as instance methods, but inheriting classes need to declare them as static if they override these methods.

XML-RPC

The XML-RPC extension has been moved to PECL and is no longer part of the PHP distribution.

Zip

ZipArchive::OPSYS_Z_CPM has been removed (this name was a typo). Use ZipArchive::OPSYS_CPM instead.

Zlib

  • gzgetss() has been removed.

  • zlib.output_compression is no longer automatically disabled for Content-Type: image/*.

Windows PHP Test Packs

The test runner has been renamed from run-test.php to run-tests.php, to match its name in php-src.

User Contributed Notes

There are no user contributed notes for this page.


Características obsoletas

Núcleo PHP

  • If a parameter with a default value is followed by a required parameter, the default value has no effect. This is deprecated as of PHP 8.0.0 and can generally be resolved by dropping the default value, without a change in functionality:

    <?php
    function test($a = [], $b) {} // Before
    function test($a, $b) {}      // After
    ?>

    One exception to this rule are parameters of the form Type $param = null, where the null default makes the type implicitly nullable. This usage remains allowed, but it is recommended to use an explicit nullable type instead:

    <?php
    function test(A $a = null, $b) {} // Still allowed
    function test(?A $a, $b) {}       // Recommended
    ?>

  • Calling get_defined_functions() with exclude_disabled explicitly set to false is deprecated and no longer has an effect. get_defined_functions() will never include disabled functions.

Enchant

  • enchant_broker_set_dict_path() and enchant_broker_get_dict_path() are deprecated, because that functionality is neither available in libenchant < 1.5 nor in libenchant-2.

  • enchant_dict_add_to_personal() is deprecated; use enchant_dict_add() instead.

  • enchant_dict_is_in_session() is deprecated; use enchant_dict_is_added() instead.

  • enchant_broker_free() and enchant_broker_free_dict() are deprecated; unset the object instead.

  • The ENCHANT_MYSPELL and ENCHANT_ISPELL constants are deprecated.

LibXML

libxml_disable_entity_loader() has been deprecated. As libxml 2.9.0 is now required, external entity loading is guaranteed to be disabled by default, and this function is no longer needed to protect against XXE attacks.

PGSQL / PDO PGSQL

  • The constant PGSQL_LIBPQ_VERSION_STR now has the same value as PGSQL_LIBPQ_VERSION, and thus is deprecated.

  • Function aliases in the pgsql extension have been deprecated. See the following list for which functions should be used instead:

    • pg_errormessage() ? pg_last_error()
    • pg_numrows() ? pg_num_rows()
    • pg_numfields() ? pg_num_fields()
    • pg_cmdtuples() ? pg_affected_rows()
    • pg_fieldname() ? pg_field_name()
    • pg_fieldsize() ? pg_field_size()
    • pg_fieldtype() ? pg_field_type()
    • pg_fieldnum() ? pg_field_num()
    • pg_result() ? pg_fetch_result()
    • pg_fieldprtlen() ? pg_field_prtlen()
    • pg_fieldisnull() ? pg_field_is_null()
    • pg_freeresult() ? pg_free_result()
    • pg_getlastoid() ? pg_last_oid()
    • pg_locreate() ? pg_lo_create()
    • pg_lounlink() ? pg_lo_unlink()
    • pg_loopen() ? pg_lo_open()
    • pg_loclose() ? pg_lo_close()
    • pg_loread() ? pg_lo_read()
    • pg_lowrite() ? pg_lo_write()
    • pg_loreadall() ? pg_lo_read_all()
    • pg_loimport() ? pg_lo_import()
    • pg_loexport() ? pg_lo_export()
    • pg_setclientencoding() ? pg_set_client_encoding()
    • pg_clientencoding() -> pg_client_encoding()

Standard Library

  • Sort comparison functions that return true or false will now throw a deprecation warning, and should be replaced with an implementation that returns an integer less than, equal to, or greater than zero.

    <?php
    // Replace
    usort($array, fn($a, $b) => $a > $b);
    // With
    usort($array, fn($a, $b) => $a <=> $b);
    ?>

Zip

  • Using an empty file as ZipArchive is deprecated. Libzip 1.6.0 does not accept empty files as valid zip archives any longer. The existing workaround will be removed in the next version.

  • The procedural API of Zip is deprecated. Use ZipArchive instead. Iteration over all entries can be accomplished using ZipArchive::statIndex() and a for loop:

    <?php
    // iterate using the procedural API
    assert(is_resource($zip));
    while (    $entry = zip_read($zip)) {
        echo     zip_entry_name($entry);
    }

    // iterate using the object-oriented API
    assert($zip instanceof ZipArchive);
    for (    $i = 0; $entry = $zip->statIndex($i); $i++) {
        echo     $entry['name'];
    }
    ?>

Reflection

  • ReflectionFunction::isDisabled() is deprecated, as it is no longer possible to create a ReflectionFunction for a disabled function. This method now always returns false.

  • ReflectionParameter::getClass(),
ReflectionParameter::isArray(), and
ReflectionParameter::isCallable() are deprecated.
ReflectionParameter::getType() and the
ReflectionType APIs should be used instead.

User Contributed Notes

There are no user contributed notes for this page.


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

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

There are no user contributed notes for this page.


Migración de PHP 7.3.x a PHP 7.4.x

Tabla de contenidos

  • New Features
  • Nuevas clases e interfaces
  • Nuevas funciones
  • Nuevas constantes globales
  • Backward Incompatible Changes
  • Características obsoletas
  • Extensiones eliminadas
  • Other Changes
  • Windows Support

Esta nueva versión menor trae consigo una serie de nuevas características y algunas incompatibilidades que debe ser probado antes de cambiar las versiones de PHP en los entornos de producción.

Véanse también las guías de migración para versiones de PHP 7.0.x, 7.1.x, 7.2.x y 7.3.x.

User Contributed Notes

There are no user contributed notes for this page.


New Features

PHP Core

Typed properties

Class properties now support type declarations.

<?php
class User {
    public int $id;
    public string $name;
}
?>
The above example will enforce that $user->id can only be assigned int values and $user->name can only be assigned string values.

Arrow functions

Arrow functions provide a shorthand syntax for defining functions with implicit by-value scope binding.

<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
// $nums = array(10, 20, 30, 40);
?>

Limited return type covariance and argument type contravariance

The following code will now work:

<?php
class A {}
class B extends A {}

class Producer {
    public function method(): A {}
}
class ChildProducer extends Producer {
    public function method(): B {}
}
?>
Full variance support is only available if autoloading is used. Inside a single file only non-cyclic type references are possible, because all classes need to be available before they are referenced.

Null coalescing assignment operator

<?php
$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}
?>

Unpacking inside arrays

<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
?>

Numeric literal separator

Numeric literals can contain underscores between digits.

<?php
6.674_083e-11; // float
299_792_458;   // decimal
0xCAFE_F00D;   // hexadecimal
0b0101_1111;   // binary
?>

Weak references

Weak references allow the programmer to retain a reference to an object that does not prevent the object from being destroyed.

Allow exceptions from __toString()

Throwing exceptions from __toString() is now permitted. Previously this resulted in a fatal error. Existing recoverable fatal errors in string conversions have been converted to Error exceptions.

CURL

CURLFile now supports stream wrappers in addition to plain file names, if the extension has been built against libcurl >= 7.56.0.

Filter

The FILTER_VALIDATE_FLOAT filter now supports the min_range and max_range options, with the same semantics as FILTER_VALIDATE_INT.

FFI

FFI is a new extension, which provides a simple way to call native functions, access native variables, and create/access data structures defined in C libraries.

GD

Added the IMG_FILTER_SCATTER image filter to apply a scatter filter to images.

Hash

Added crc32c hash using Castagnoli's polynomial. This CRC32 variant is used by storage systems, such as iSCSI, SCTP, Btrfs and ext4.

Multibyte String

Added the mb_str_split() function, which provides the same functionality as str_split(), but operating on code points rather than bytes.

OPcache

Support for preloading code has been added.

Regular Expressions (Perl-Compatible)

The preg_replace_callback() and preg_replace_callback_array() functions now accept an additional flags argument, with support for the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags. This influences the format of the matches array passed to to the callback function.

PDO

The username and password can now be specified as part of the PDO DSN for the mysql, mssql, sybase, dblib, firebird and oci drivers. Previously this was only supported by the pgsql driver. If a username/password is specified both in the constructor and the DSN, the constructor takes precedence.

It is now possible to escape question marks in SQL queries to avoid them being interpreted as parameter placeholders. Writing ?? allows sending a single question mark to the database and e.g. use the PostgreSQL JSON key exists (?) operator.

PDO_OCI

PDOStatement::getColumnMeta() is now available.

PDO_SQLite

PDOStatement::getAttribute(PDO::SQLITE_ATTR_READONLY_STATEMENT) allows checking whether the statement is read-only, i.e. if it doesn't modify the database.

PDO::setAttribute(PDO::SQLITE_ATTR_EXTENDED_RESULT_CODES, true) enables the use of SQLite3 extended result codes in PDO::errorInfo() and PDOStatement::errorInfo().

SQLite3

Added SQLite3::lastExtendedErrorCode() to fetch the last extended result code.

Added SQLite3::enableExtendedResultCodes($enable = true), which will make SQLite3::lastErrorCode() return extended result codes.

Standard

strip_tags() with array of tag names

strip_tags() now also accepts an array of allowed tags: instead of strip_tags($str, '<a><p>') you can now write strip_tags($str, ['a', 'p']).

Custom object serialization

A new mechanism for custom object serialization has been added, which uses two new magic methods: __serialize and __unserialize.

<?php
// Returns array containing all the necessary state of the object.
public function __serialize(): array;

// Restores the object state from the given data array.
public function __unserialize(array $data): void;
?>
The new serialization mechanism supersedes the Serializable interface, which will be deprecated in the future.

Array merge functions without arguments

array_merge() and array_merge_recursive() may now be called without any arguments, in which case they will return an empty array. This is useful in conjunction with the spread operator, e.g. array_merge(...$arrays).

proc_open() function

proc_open() now accepts an array instead of a string for the command. In this case the process will be opened directly (without going through a shell) and PHP will take care of any necessary argument escaping.

<?php
proc_open(['php', '-r', 'echo "Hello World\n";'], $descriptors, $pipes);
?>

proc_open() now supports redirect and null descriptors.

<?php
// Like 2>&1 on the shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['redirect', 1]], $pipes);
// Like 2>/dev/null or 2>nul on the shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['null']], $pipes);
?>

argon2i(d) without libargon

password_hash() now has the argon2i and argon2id implementations from the sodium extension when PHP is built without libargon.

User Contributed Notes

wow-apps.pro 26-Feb-2020 08:42
<?php

// How to get property type? For example for testing:

class Foo
{
    private int $num;
    private bool $isPositive;
    private $notes;
}

$reflection = new \ReflectionClass(Foo::class);
$classProperties = $reflection->getProperties(\ReflectionProperty::IS_PRIVATE);
foreach ($classProperties as $classProperty) {
    var_dump((string) $classProperty->getType());
}

/**
 * Result:
 * "int"
 * "bool"
 * ""
 */
Rain 27-Jan-2020 08:44
It should be noted that typed properties internally are never initialized to a default null. Unless of course you initialize them to null yourself. That's why you will always going to encounter this error if you try to access them before initialization.

**Typed property foo::$bar must not be accessed before initialization**

<?php
class User
{
    public $id;
    public string $name; // Typed property (Uninitialized)
    public ?string $age = null; //  Typed property (Initialized)
}

$user = new User;
var_dump(is_null($user->id)); // bool(true)
var_dump(is_null($user->name)); // PHP Fatal error: Typed property User::$name must not be accessed before initialization
var_dump(is_null($user->age));// bool(true)
?>

Another thing worth noting is that it's not possible to initialize a property of type object to anything other than null.  Since the evaluation of properties happens at compile-time and object instantiation happens at runtime. One last thing, callable type is not supported due to its context-dependent behavior.


Nuevas clases e interfaces

Reflection

  • ReflectionReference

User Contributed Notes

There are no user contributed notes for this page.


Nuevas funciones

Núcleo PHP

  • get_mangled_object_vars()
  • password_algos()
  • sapi_windows_set_ctrl_handler()

GD

  • imagecreatefromtga()

OpenSSL

  • openssl_x509_verify()

Process Control

  • pcntl_unshare()

SQLite3

  • SQLite3::backup()
  • SQLite3Stmt::getSQL()

User Contributed Notes

shaman_master at list dot ru 17-Jun-2020 11:42
Also added mb_str_split()  — given a multibyte string, return an array of its characters


Nuevas constantes globales

Núcleo PHP

  • PHP_WINDOWS_EVENT_CTRL_C
  • PHP_WINDOWS_EVENT_CTRL_BREAK

Multibyte String

  • MB_ONIGURUMA_VERSION

Sockets

Añadidas las siguientes opciones de sockets específicas de FreeBSD:

  • SO_LABEL
  • SO_PEERLABEL
  • SO_LISTENQLIMIT
  • SO_LISTENQLEN
  • SO_USER_COOKIE

Tidy

  • TIDY_TAG_ARTICLE
  • TIDY_TAG_ASIDE
  • TIDY_TAG_AUDIO
  • TIDY_TAG_BDI
  • TIDY_TAG_CANVAS
  • TIDY_TAG_COMMAND
  • TIDY_TAG_DATALIST
  • TIDY_TAG_DETAILS
  • TIDY_TAG_DIALOG
  • TIDY_TAG_FIGCAPTION
  • TIDY_TAG_FIGURE
  • TIDY_TAG_FOOTER
  • TIDY_TAG_HEADER
  • TIDY_TAG_HGROUP
  • TIDY_TAG_MAIN
  • TIDY_TAG_MARK
  • TIDY_TAG_MENUITEM
  • TIDY_TAG_METER
  • TIDY_TAG_NAV
  • TIDY_TAG_OUTPUT
  • TIDY_TAG_PROGRESS
  • TIDY_TAG_SECTION
  • TIDY_TAG_SOURCE
  • TIDY_TAG_SUMMARY
  • TIDY_TAG_TEMPLATE
  • TIDY_TAG_TIME
  • TIDY_TAG_TRACK
  • TIDY_TAG_VIDEO

User Contributed Notes

There are no user contributed notes for this page.


Backward Incompatible Changes

PHP Core

Array-style access of non-arrays

Trying to use values of type null, bool, int, float or resource as an array (such as $null["key"]) will now generate a notice.

get_declared_classes() function

The get_declared_classes() function no longer returns anonymous classes that have not been instantiated yet.

fn keyword

fn is now a reserved keyword. In particular, it can no longer be used as a function or class name. It can still be used as a method or class constant name.

<?php tag at end of file

<?php at the end of the file (without trailing newline) will now be interpreted as an opening PHP tag. Previously it was interpreted either as a short opening tag followed by literal php and resulted in a syntax error (with short_open_tag=1) or was interpreted as a literal <?php string (with short_open_tag=0).

Stream wrappers

When using include/require on a stream, streamWrapper::stream_set_option() will be invoked with the STREAM_OPTION_READ_BUFFER option. Custom stream wrapper implementations may need to implement the streamWrapper::stream_set_option() method to avoid a warning (always returning false is a sufficient implementation).

Serialization

The o serialization format has been removed. As it is never produced by PHP, this may only break unserialization of manually crafted strings.

Password algorithm constants

Password hashing algorithm identifiers are now nullable strings rather than integers.

  • PASSWORD_DEFAULT was int 1; now is null
  • PASSWORD_BCRYPT was int 1; now is string '2y'
  • PASSWORD_ARGON2I was int 2; now is string 'argon2i'
  • PASSWORD_ARGON2ID was int 3; now is string 'argon2id'

Applications correctly using the constants PASSWORD_DEFAULT, PASSWORD_BCRYPT, PASSWORD_ARGON2I, and PASSWORD_ARGON2ID will continue to function correctly.

htmlentities() function

htmlentities() will now raise a notice (instead of a strict standards warning) if it is used with an encoding for which only basic entity substitution is supported, in which case it is equivalent to htmlspecialchars().

fread() and fwrite() function

fread() and fwrite() will now return false if the operation failed. Previously an empty string or 0 was returned. EAGAIN/EWOULDBLOCK are not considered failures.

These functions now also raise a notice on failure, such as when trying to write to a read-only file resource.

BCMath Arbitrary Precision Mathematics

BCMath functions will now warn if a non well-formed number is passed, such as "32foo". The argument will be interpreted as zero, as before.

CURL

Attempting to serialize a CURLFile class will now generate an exception. Previously the exception was only thrown on unserialization.

Using CURLPIPE_HTTP1 is deprecated, and is no longer supported as of cURL 7.62.0.

The $version parameter of curl_version() is deprecated. If any value not equal to the default CURLVERSION_NOW is passed, a warning is raised and the parameter is ignored.

Date and Time

Calling var_dump() or similar on a DateTime or DateTimeImmutable instance will no longer leave behind accessible properties on the object.

Comparison of DateInterval objects (using ==, <, and so on) will now generate a warning and always return false. Previously all DateInterval objects were considered equal, unless they had properties.

Intl

The default parameter value of idn_to_ascii() and idn_to_utf8() is now INTL_IDNA_VARIANT_UTS46 instead of the deprecated INTL_IDNA_VARIANT_2003.

MySQLi

The embedded server functionality has been removed. It was broken since at least PHP 7.0.

The undocumented mysqli::$stat property has been removed in favor of mysqli::stat().

OpenSSL

The openssl_random_pseudo_bytes() function will now throw an exception in error situations, similar to random_bytes(). In particular, an Error is thrown if the number of requested bytes is less than or equal to zero, and an Exception is thrown if sufficient randomness cannot be gathered. The $crypto_strong output argument is guaranteed to always be true if the function does not throw, so explicitly checking it is not necessary.

Regular Expressions (Perl-Compatible)

When PREG_UNMATCHED_AS_NULL mode is used, trailing unmatched capturing groups will now also be set to null (or [null, -1] if offset capture is enabled). This means that the size of the $matches will always be the same.

PHP Data Objects

Attempting to serialize a PDO or PDOStatement instance will now generate an Exception rather than a PDOException, consistent with other internal classes which do not support serialization.

Reflection

Reflection objects will now generate an exception if an attempt is made to serialize them. Serialization for reflection objects was never supported and resulted in corrupted reflection objects. It has been explicitly prohibited now.

Standard PHP Library (SPL)

Calling get_object_vars() on an ArrayObject instance will now always return the properties of the ArrayObject itself (or a subclass). Previously it returned the values of the wrapped array/object unless the ArrayObject::STD_PROP_LIST flag was specified.

Other affected operations are:

  • ReflectionObject::getProperties()
  • reset(), current(), etc. Use Iterator methods instead.
  • Potentially others working on object properties as a list, e.g. array_walk().

(array) casts are not affected. They will continue to return either the wrapped array, or the ArrayObject properties, depending on whether the ArrayObject::STD_PROP_LIST flag is used.

SplPriorityQueue::setExtractFlags() will throw an exception if zero is passed. Previously this would generate a recoverable fatal error on the next extraction operation.

ArrayObject, ArrayIterator, SplDoublyLinkedList and SplObjectStorage now support the __serialize() and __unserialize() mechanism in addition to the Serializable interface. This means that serialization payloads created on older PHP versions can still be unserialized, but new payloads created by PHP 7.4 will not be understood by older versions.

Tokenizer

token_get_all() will now emit a T_BAD_CHARACTER token for unexpected characters instead of leaving behind holes in the token stream.

Incoming Cookies

As of PHP 7.4.11, the names of incoming cookies are no longer url-decoded for security reasons.

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


Características obsoletas

Núcleo PHP

Operadores ternarios anidados sin paréntesis explícitos

Las operaciones ternarias anidadas deben utilizar explícitamente paréntesis para dictar el orden de las operaciones. Anteriormente, cuando se usaba sin paréntesis, la asociatividad izquierda no resultaría en el comportamiento esperado en la mayoría de los casos.

<?php
1 ? 2 : 3 ? 4 : 5;   // obsoleto
(1 ? 2 : 3) ? 4 : 5; // ok
1 ? 2 : (3 ? 4 : 5); // ok
?>

Acceso al desplazamiento de Array y string usando llaves

La sintaxis de acceso de desplazamiento en array y string con llaves es obsoleto. Use $var[$idx] en vez de $var{$idx}.

La llamada (real) y la función is_real()

La llamada (real) es obsoleta, use (float) en su lugar.

La función is_real() es también obsoleta, use is_float() en su lugar.

Desencadenando $this cuando $this es usado

Desencadenando $this de un cierre no estático que use $this es obsoleto.

palabra clave parent sin clase de padre

Usar parent dentro de una clase sin un padre es obsoleto, y lanzará un error de compilación en el futuro. Actualmente sólo se generará un error si/cuando el padre es accedido en tiempo de ejecución.

Opción INI allow_url_include

La directiva ini allow_url_include es obsoleta. Habilitar esta generará un aviso de depreciación en el arranque.

Caracteres inválidos en las funciones de conversión de base

Pasar caracteres inválidos a base_convert(), bindec(), octdec() y hexdec() generará ahora un aviso de depreciación. El resultado se seguirá calculando como si los caracteres inválidos no existieran. Liderando y siguiendo el espacio blanco, así como prefijos de tipo 0x (dependiendo de la base) siguen estando permitidos.

Usar array_key_exists() en objetos

Usar array_key_exists() en objetos es obsoleto. En lugar de eso, debe usar isset() o property_exists().

Funciones de comillas mágicas

Las funciones get_magic_quotes_gpc() y get_magic_quotes_runtime() son obsoletas. Estas siempre devolverán false.

función hebrevc()

La función hebrevc() es obsoleta. Esta puede ser reemplazada con nl2br(hebrev($str)) o, preferiblemente, el uso del soporte RTL de Unicode.

función convert_cyr_string()

La función convert_cyr_string() es obsoleta.
Esta puede ser reemplazada con mb_convert_string(),
iconv() o UConverter.

función money_format()

La función money_format() es obsoleta. Esta puede ser reemplazada con la funcionalidad intl NumberFormatter.

función ezmlm_hash()

La función ezmlm_hash() es obsoleta.

función restore_include_path()

La función restore_include_path() es obsoleta. Esta puede ser reemplazada con ini_restore('include_path').

Implode con el orden de los parámetros históricos

Pasar parámetros a implode() en orden inverso es obsoleto, use implode($glue, $parts) en vez de implode($parts, $glue).

COM

La importación de bibliotecas de tipos con registro constante que no distingue entre mayúsculas y y minúsculas es obsoleto.

Filter

FILTER_SANITIZE_MAGIC_QUOTES es obsoleto, use FILTER_SANITIZE_ADD_SLASHES en su lugar.

Multibyte String

Pasar un patrón sin string a mb_ereg_replace() es obsoleto. Actualmente, los patrones sin string se interpretan como puntos de código ASCII. En PHP 8, el patrón será interpretado como un string en su lugar.

Pasar la codificación como tercer parámetro a mb_strrpos() es obsoleto. En su lugar, pasar un offset de 0, y codificar como cuarto parámetro.

Protocolo ligero de acceso a directorios

ldap_control_paged_result_response() y ldap_control_paged_result() son obsoletas. Los controles de paginación pueden ser enviados junto con ldap_search() en su lugar.

Reflection

Llamar a ReflectionType::__toString() ahora generará un aviso de depreciación. Este método ha sido desaprobado en favor de ReflectionNamedType::getName() en la documentación desde PHP 7.1, pero no lanzó un aviso de depreciación por razones técnicas.

Los métodos export() en todas las clases Reflection están obsoletos. Contruir un objeto Reflection y convertir este a string en su lugar:

<?php
// ReflectionClass::export(Foo::class, false) is:
echo new ReflectionClass(Foo::class), "\n";

// $str = ReflectionClass::export(Foo::class, true) is:
$str = (string) new ReflectionClass(Foo::class);
?>

Socket

Las flags AI_IDN_ALLOW_UNASSIGNED y AI_IDN_USE_STD3_ASCII_RULES para socket_addrinfo_lookup() sob obsoletas, debido a una depreciación ascendente en el 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


Extensiones eliminadas

Estas extensiones han sido trasladadas a PECL y ya no forman parte de la distribución de PHP. Las versiones del paquete PECL de estas extensiones se crearán según a demanda de los usuarios.

  • Firebird/Interbase - el acceso a una base de datos basada en InterBase y/o Firebird sigue siendo con el driver PDO Firebird.
  • Recode
  • WDDX

User Contributed Notes

There are no user contributed notes for this page.


Other Changes

Performance Improvements

PHP Core

A specialized VM opcode for the array_key_exists() function has been added, which improves performance of this function if it can be statically resolved. In namespaced code, this may require writing \array_key_exists() or explicitly importing the function.

Regular Expressions (Perl-Compatible)

When preg_match() in UTF-8 mode ("u" modifier) is repeatedly called on the same string (but possibly different offsets), it will only be checked for UTF-8 validity once.

Changes to INI File Handling

zend.exception_ignore_args is a new INI directive for including or excluding arguments from stack traces generated from exceptions.

opcache.preload_user is a new INI directive for specifying the user account under which preloading code is execute if it would otherwise be run as root (which is not allowed for security reasons).

Migration to pkg-config

A number of extensions have been migrated to exclusively use pkg-config for the detection of library dependencies. Generally, this means that instead of using --with-foo-dir=DIR or similar only --with-foo is used. Custom library paths can be specified either by adding additional directories to PKG_CONFIG_PATH or by explicitly specifying compilation options through FOO_CFLAGS and FOO_LIBS.

The following extensions and SAPIs are affected:

  • CURL:
    • --with-curl no longer accepts a directory.
  • Enchant:
    • --with-enchant no longer accepts a directory.
  • FPM:
    • --with-fpm-systemd now uses only pkg-config for libsystem checks. The libsystemd minimum required version is 209.
  • GD:
    • --with-gd becomes --enable-gd (whether to enable the extension at all) and --with-external-gd (to opt into using an external libgd, rather than the bundled one).
    • --with-png-dir has been removed. libpng is required.
    • --with-zlib-dir has been removed. zlib is required.
    • --with-freetype-dir becomes --with-freetype
    • --with-jpeg-dir becomes --with-jpeg
    • --with-webp-dir becomes --with-webp
    • --with-xpm-dir becomes --with-xpm
  • IMAP:
    • --with-kerberos-systemd no longer accepts a directory.
  • Intl:
    • --with-icu-dir has been removed. If --enable-intl is passed, then libicu is always required.
  • LDAP:
    • --with-ldap-sasl no longer accepts a directory.
  • Libxml:
    • --with-libxml-dir has been removed.
    • --enable-libxml becomes --with-libxml.
    • --with-libexpat-dir has been renamed to --with-expat and no longer accepts a directory.
  • Litespeed:
    • --with-litespeed becomes --enable-litespeed.
  • Mbstring:
    • --with-onig has been removed. Unless --disable-mbregex has been passed, libonig is required.
  • ODBC:
    • --with-iodbc no longer accepts a directory.
    • --with-unixODBC without a directory now uses pkg-config (preferred). Directory is still accepted for old versions without libodbc.pc.
  • OpenSSL:
    • --with-openssl no longer accepts a directory.
  • PCRE:
    • --with-pcre-regex has been removed. Instead --with-external-pcre is provided to opt into using an external PCRE library, rather than the bundled one.
  • PDO_SQLite:
    • --with-pdo-sqlite no longer accepts a directory.
  • Readline:
    • --with-libedit no longer accepts a directory.
  • Sodium:
    • --with-sodium no longer accepts a directory.
  • SQLite3:
    • --with-sqlite3 no longer accepts a directory.
  • XSL:
    • --with-xsl no longer accepts a directory.
  • Zip:
    • --with-libzip has been removed.
    • --enable-zip becomes --with-zip.

CSV escaping

fputcsv(),
fgetcsv(),
SplFileObject::fputcsv(),
SplFileObject::fgetcsv(), and
SplFileObject::setCsvControl()
now accept an empty string as $escape argument,
which disables the proprietary PHP escaping mechanism.

The behavior of str_getcsv() has been adjusted accordingly (formerly, an empty string was identical to using the default).

SplFileObject::getCsvControl() now may also return an empty string for the third array element, accordingly.

Data Filtering

The filter extension no longer exposes --with-pcre-dir for Unix builds and can now reliably be built as shared when using ./configure

GD

The behavior of imagecropauto() in the bundled libgd has been synced with that of system libgd:

  • IMG_CROP_DEFAULT is no longer falling back to IMG_CROP_SIDES
  • Threshold-cropping now uses the algorithm of system libgd

The default $mode parameter of imagecropauto() has been changed to IMG_CROP_DEFAULT; passing -1 is now deprecated.

imagescale() now supports aspect ratio preserving scaling to a fixed height by passing -1 as $new_width.

HASH Message Digest Framework

The hash extension cannot be disabled anymore and is always an integral part of any PHP build, similar to the date extension.

Intl

The intl extension now requires at least ICU 50.1.

ResourceBundle now implements Countable.

Lightweight Directory Access Protocol

Support for nsldap and umich_ldap has been removed.

Libxml

All libxml-based extensions now require libxml 2.7.6 or newer.

Multibyte String

The oniguruma library is no longer bundled with PHP, instead libonig needs to be available on the system. Alternatively --disable-mbregex can be used to disable the mbregex component.

OPcache

The --disable-opcache-file and --enable-opcache-file configure options have been removed in favor of the opcache.file_cache INI directive.

Password Hashing

The password_hash() and functions now accept nullable string and int for $algo argument.

PEAR

Installation of PEAR (including PECL) is no longer enabled by default. It can be explicitly enabled using --with-pear. This option is deprecated and may be removed in the future.

Reflection

The numeric values of the modifier constants (IS_ABSTRACT, IS_DEPRECATED, IS_EXPLICIT_ABSTRACT, IS_FINAL, IS_IMPLICIT_ABSTRACT, IS_PRIVATE, IS_PROTECTED, IS_PUBLIC, and IS_STATIC) on the ReflectionClass, ReflectionFunction, ReflectionMethod, ReflectionObject, and ReflectionProperty classes have changed.

SimpleXML

SimpleXMLElement now implements Countable.

SQLite3

The bundled libsqlite has been removed. To build the SQLite3 extension a system libsqlite3 = 3.7.4 is now required. To build the PDO_SQLite extension a system libsqlite3 = 3.5.0 is now required.

Serialization and unserialization of SQLite3, SQLite3Stmt and SQLite3Result is now explicitly forbidden. Formerly, serialization of instances of these classes was possible, but unserialization yielded unusable objects.

The @param notation can now also be used to denote SQL query parameters.

Zip

The bundled libzip library has been removed. A system libzip >= 0.11 is now necessary to build the zip extension.

User Contributed Notes

santi at mola dot io 31-Jul-2020 07:54
Note for internals/extensions:

Many opcode values changed between PHP 7.3 and 7.4, so most documentation resources are outdated in that regard. You can look the definitions at Zend/zend_vm_opcodes.h in php-src. For example, ZEND_ECHO changes from 40 to 136.

While opcode changes happen in a lot of PHP versions, the change in 7.4 is quite significant.
ohcc at 163 dot com 09-Jun-2020 04:56
As of PHP 7.4, an exception thrown within the user-defined shutdown function can be caught by the user-defined exception handler.

<?php
    set_error_handler(
        function($level, $error, $file, $line){
            if(0 === error_reporting()){
                return false;
            }
            throw new ErrorException($error, -1, $level, $file, $line);
        },
        E_ALL
    );

    register_shutdown_function(function(){
        $error = error_get_last();
        if($error){
            throw new ErrorException($error['message'], -1, $error['type'], $error['file'], $error['line']);
        }
    });

    set_exception_handler(function($exception){
        // ... more code ...
    });

    require 'NotExists.php';
Florent H (Sowapps) 16-Feb-2020 07:37
This version brings an important changes with the directive zend.exception_ignore_args set to On by default.
In all stack traces, the args key is now missing.
All php frameworks have to handle this to report errors & exceptions.


Windows Support

configure flags

configure ahora considera a los conjuntos adicionales como CFLAGS y LDFLAGS variables de entorno.

Manejo de CTRL

CTRL+C y CTRL+BREAK en la consola pueden ser capturados mediante la configuración de una función de manejo con sapi_windows_set_ctrl_handler().

proc_open() en Windows se puede pasar una opción "create_process_group". Se requiere si el proceso del hijo se supone que maneja eventos CTRL.

OPcache

OPcache ahora soporta un número arbitrario de cachés separados por usuario a través de la directiva INI opcache.cache_id. Todos los procesos con el mismo ID de caché y el usuario comparten una instancia OPcache.

stat

La implementación de la estadística se ha refactorizado.

  • Un número inode An inode number se entregado y se basa en el índice de archivos NTFS.
  • El número del dispositivo se basa ahora en el número de serie del volumen.

Obsérvese que ambos valores se derivan del sistema y se proporcionan tal cual en los sistemas de 64 bits. En sistemas de 32 bits, estos valores podrían desbordar el entero de 32 bits en PHP, así que son falsos.

libsqlite3

libsqlite3 ya no está compilada estáticamente en php_sqlite3.dll y php_pdo_sqlite.dll, pero más bien disponible como libsqlite3.dll. Consulte las instrucciones de instalación para SQLite3 y PDO_SQLITE, respectivamente.

User Contributed Notes

There are no user contributed notes for this page.


Migración de PHP 7.2.x a PHP 7.3.x

Tabla de contenidos

  • Nuevas características
  • Nuevas funciones
  • Nuevas constantes globales
  • Cambios incompatibles con el pasado
  • Características obsoletas
  • Other Changes
  • Soporte de Windows

Esta nueva versión menor trae consigo una serie de nuevas características y unas pocas incompatibilidades que se deben probar antes de cambiar las versiones de PHP en entornos de producción.

Véanse también las guías de migración para versiones de PHP 7.0.x, 7.1.x y 7.2.x.

User Contributed Notes

jrg dot guzz at gmail dot com 10-Jun-2020 09:00
Como parte del aumento de la seguridad, se recomienda mantener actualizada su versión de PHP. Aquí hemos proporcionado los pasos para actualizar la versión actual de PHP 7.2 a 7.3 en las versiones de Ubuntu 14/16/18 /19/20 sin eliminar la anterior. Para que podamos volver a las versiones anteriores si hay algo incompatible con la nueva después de cambiar.
    1. Inicie sesión en el servidor a través de SSH como root.
       * Sino sabes no importa usa el comando sudo (como yo)
    2. Verifique su versión actual de PHP.
       $ php -v
PHP 7.2.36

    3. Para instalar PHP 7.3, primero debemos agregar el repositorio:
       (Mucho ojo  aquí,(PRECAUCIÓN) ...Si te encuentras en la versión Ubuntu  19 / 20 no es necesario agregar repositorios , los trae por default.Puedes consultar con este comando los repositorios:

 $sudo apt-cache policy | grep http | awk '{print $2 $3}' | sort -u

 Sino se encuentran app/php o app/apache2 usa este comando:

$sudo add-apt-repository ppa: ondrej / php

    4. Luego ejecute una actualización:
$sudo apt-get update

    5. Después de completar la actualización, necesitamos instalar PHP 7.3.
$ sudo apt install php7.3

    6.  Luego instale los paquetes PHP requeridos según su instalación actual:
$sudo apt install php7.3-common php7.3-cli php7.3-bz2 php7.3-curl php7.3-gd php7.3-intl php7.3-json php7.3-readline php7.3-xml php7. 3-zip php7.3-fpm php7.3-bcmath php7.3-mbstring

      Se suman nuevos comandos para la version 7.3 de Php.En el orden que se escriben para no dañar los modulos.

Detener el Servidor Apache
$sudo systemctl stop apache2

Desactivar el Modulo Php 7.2
 $sudo a2dismod php7.2

Activas Modulo Proxy fcgi
$sudo a2enmod proxy_fcgi setenvif

Activar Modulo fpm
$sudo a2enmod php7.3-fpm

Activar Modulo de Php 7.3
$sudo a2enmod php7.3

    7. Luego reinicie Apache:
$sudo systemctl start apache2

    8. Por último comprobamos el Status del Sercidor Apache2, apagar y  prender un par de veces el servidor.(Todo correcto):

 $sudo systenctl status apache2

    9. La nueva versión de PHP debería estar activa ahora. Puede verificarlo desde la línea de comando:

$php -v
PHP 7.3.28


Nuevas características

PHP Core

Sintaxis Heredoc y Nowdoc más flexible

Ya no es necesario que el marcador de cierre de los string de documento vaya seguido de un punto y coma o línea nueva. Además, el marcador de cierre puede ser sangrado, en en cuyo caso la indentación se quitará de todas las líneas del string de documento.

La Desestructuración de Arrays soporta las Asignaciones de Referencia

La desestructuración de arrays ahora soporta asignaciones de referencia utilizando la sintaxis [&$a, [$b, &$c]] = $d. Lo mismo se soporta también para list().

Operador Instanceof acepta literales

instanceof ahora permite los literales como el primer operando, en en cuyo caso el resultado es siempre false.

Excepción del error de compilación en lugar de algunos errores de compilación

Una nueva excepción CompileError ha sido añadida, de la cual hereda ParseError. Un pequeño número de errores de compilación lanzarán ahora CompileError en vez de generar un error fatal. Actualmente esto sólo afecta a los errores de compilación que pueden ser lanzados por token_get_all() en modo TOKEN_PARSE, pero más errores pueden ser convertidos en el futuro.

Se permite el uso de comas en las llamadas

Ahora se permiten las comas en las llamadas a funciones y métodos.

Soporte de Argon2id

El argumento de configuración--with-password-argon2[=dir] ahora proporciona soporte tanto para los hashes de Argon2i como de Argon2id en las fuynciones password_hash(), password_verify(), password_get_info(), y password_needs_rehash(). Las contraseñas pueden ser descifradas y verificadas usando la constante PASSWORD_ARGON2ID. El soporte tanto para Argon2i como para Argon2id en las funciones password_*() ahora requiere que PHP esté enlazado con la biblioteca de referencia libargon2 = 20161029.

FastCGI Process Manager

Se han añadido nuevas opciones para personalizar el registro de FPM:

log_limit
Esta opción global puede utilizarse para establecer el límite de registro para la línea que permite registrar mensajes de más de 1024 caracteres sin envoltura. También arregla varios problemas de envoltura.
log_buffering
Esta opción global permite un registro experimental sin buffer extra.
decorate_workers_output
Esta opción de pool permite deshabilitar la decoración de salida para la salida de los trabajadores cuando se habilita catch_workers_output.

Funciones matemáticas de BC

bcscale() ahora también puede ser usado como getter para recuperar la escala actual en uso.

Protocolo ligero de acceso a directorios

El soporte completo para los controles de LDAP se ha añadido a las funciones de consulta LDAP y

  • Un parámetro $serverctrls para enviar controles al
servidor en ldap_add(),
ldap_mod_replace(), ldap_mod_add(),
ldap_mod_del(), ldap_rename(),
ldap_compare(), ldap_delete(),
ldap_modify_batch(),
ldap_search(), ldap_list() y
ldap_read() ha sido añadido.
  • El parámetro de salida $serverctrls para obtener los controles del servidor en ldap_parse_result() ha sido añadido.
  • Soporte para LDAP_OPT_SERVER_CONTROLS y LDAP_OPT_CLIENT_CONTROLS en ldap_get_option() y ldap_set_option() ha sido arreglado.

Funciones de string multibyte

Soporte completo de mapeo y plegado de casos

Se ha añadido soporte al mapeo completo y el plegado de casos. A diferencia del mapeo simple, el mapeo completo de los casos puede cambiar la longitud del string. Por ejemplo:

<?php
mb_strtoupper("Straße");
// Produces STRAßE en PHP 7.2
// Produces STRASSE en PHP 7.3
?>
Los diferentes modos de mapeo y plegado están disponibles a través de mb_convert_case():
  • MB_CASE_LOWER (usado por mb_strtolower())
  • MB_CASE_UPPER (usado por mb_strtoupper())
  • MB_CASE_TITLE
  • MB_CASE_FOLD
  • MB_CASE_LOWER_SIMPLE
  • MB_CASE_UPPER_SIMPLE
  • MB_CASE_TITLE_SIMPLE
  • MB_CASE_FOLD_SIMPLE (utilizado en operaciones que no tienen en cuenta los casos)
Sólo se realiza un mapeo de casos completo incondicional y agnóstico del lenguaje.

Las operaciones de string insensible a los casos que utilizan el plegado de casos

Las operaciones de string insensible a las mayúsculas y minúsculas utilizan ahora el plegado de mayúsculas en lugar del mapeo de mayúsculas y minúsculas durante las comparaciones. Esto significa que más caracteres serán considerado (caso insensible) igual ahora.

MB_CASE_TITLE realiza la conversión de casos de título

mb_convert_case() con MB_CASE_TITLE ahora realiza una conversión de título-caso basado en Cased y CaseIgnorable propiedades derivadas de Unicode. En particular, esto también mejora el manejo de comillas y apóstrofes.

Soporte Unicode 11

La tabla de datos Multibyte String ha sido actualizado para Unicode 11.

Soporte de string largos

Las Funciones Multibyte String ahora soportan correctamente strings de más de 2GB.

Mejoras en el rendimiento

Funcionamiento de la extensión Multibyte String extension ha mejorado significativamente en todos los aspectos. Las mayores mejoras son en las funciones de conversión de casos.

Soporte de capturas nombradas

Las funciones mb_ereg_* ahora soportan capturas nombradas. Las funciones de coincidencia como mb_ereg() ahora retornarán capturas nombradas usando su número de grupo como su nombre, de forma similar a la PCRE:

<?php
mb_ereg('(?<word>\w+)', '?', $matches);
// => [0 => "?", 1 => "?", "word" => "?"];
?>
Adicionalmente, mb_ereg_replace() ahora soporta la notación \k<> y \k'' para referirse a las capturas nombradas en el string de reemplazo:
<?php
mb_ereg_replace('\s*(?<word>\w+)\s*', "_\k<word>_\k'word'_", ' foo ');
// => "_foo_foo_"
?>
\k<> y \k'' también puede utilizarse para referencias numeradas, que también funciona con números de grupo mayores de 9.

Readline

Soporte para las opciones completion_append_character y completion_suppress_append ha sido añadido para readline_info(). Estas opciones sólo están disponibles si PHP está vinculado con libreadline (más que con 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

?>


Nuevas funciones

Núcleo PHP

  • array_key_first()
  • array_key_last()
  • gc_status()
  • hrtime()
  • is_countable()
  • net_get_interfaces()

Gestor del proceso FastCGI

  • fpm_get_status()

Fecha y hora

  • DateTime::createFromImmutable()

Precisión múltiple de GNU

  • gmp_binomial()
  • gmp_kronecker()
  • gmp_lcm()
  • gmp_perfect_power()

Funciones de internacionalización

  • Normalizer::getRawDecomposition()
  • normalizer_get_raw_decomposition()
  • Spoofchecker::setRestrictionLevel()

Protocolo ligero de acceso a directorios

  • 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.


Nuevas constantes globales

Núcleo PHP

  • PASSWORD_ARGON2ID

Biblioteca URL del cliente

  • CURLAUTH_BEARER
  • CURLAUTH_GSSAPI
  • CURLE_WEIRD_SERVER_REPLY
  • CURLINFO_APPCONNECT_TIME_T
  • CURLINFO_CONNECT_TIME_T
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD_T
  • CURLINFO_CONTENT_LENGTH_UPLOAD_T
  • CURLINFO_FILETIME_T
  • CURLINFO_HTTP_VERSION
  • CURLINFO_NAMELOOKUP_TIME_T
  • CURLINFO_PRETRANSFER_TIME_T
  • CURLINFO_PROTOCOL
  • CURLINFO_PROXY_SSL_VERIFYRESULT
  • CURLINFO_REDIRECT_TIME_T
  • CURLINFO_SCHEME
  • CURLINFO_SIZE_DOWNLOAD_T
  • CURLINFO_SIZE_UPLOAD_T
  • CURLINFO_SPEED_DOWNLOAD_T
  • CURLINFO_SPEED_UPLOAD_T
  • CURLINFO_STARTTRANSFER_TIME_T
  • CURLINFO_TOTAL_TIME_T
  • CURL_LOCK_DATA_CONNECT
  • CURL_LOCK_DATA_PSL
  • CURL_MAX_READ_SIZE
  • CURLOPT_ABSTRACT_UNIX_SOCKET
  • CURLOPT_DISALLOW_USERNAME_IN_URL
  • CURLOPT_DNS_SHUFFLE_ADDRESSES
  • CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS
  • CURLOPT_HAPROXYPROTOCOL
  • CURLOPT_KEEP_SENDING_ON_ERROR
  • CURLOPT_PRE_PROXY
  • CURLOPT_PROXY_CAINFO
  • CURLOPT_PROXY_CAPATH
  • CURLOPT_PROXY_CRLFILE
  • CURLOPT_PROXY_KEYPASSWD
  • CURLOPT_PROXY_PINNEDPUBLICKEY
  • CURLOPT_PROXY_SSLCERT
  • CURLOPT_PROXY_SSLCERTTYPE
  • CURLOPT_PROXY_SSL_CIPHER_LIST
  • CURLOPT_PROXY_SSLKEY
  • CURLOPT_PROXY_SSLKEYTYPE
  • CURLOPT_PROXY_SSL_OPTIONS
  • CURLOPT_PROXY_SSL_VERIFYHOST
  • CURLOPT_PROXY_SSL_VERIFYPEER
  • CURLOPT_PROXY_SSLVERSION
  • CURLOPT_PROXY_TLS13_CIPHERS
  • CURLOPT_PROXY_TLSAUTH_PASSWORD
  • CURLOPT_PROXY_TLSAUTH_TYPE
  • CURLOPT_PROXY_TLSAUTH_USERNAME
  • CURLOPT_REQUEST_TARGET
  • CURLOPT_SOCKS5_AUTH
  • CURLOPT_SSH_COMPRESSION
  • CURLOPT_SUPPRESS_CONNECT_HEADERS
  • CURLOPT_TIMEVALUE_LARGE
  • CURLOPT_TLS13_CIPHERS
  • CURLPROXY_HTTPS
  • CURLSSH_AUTH_GSSAPI
  • CURL_SSLVERSION_MAX_DEFAULT
  • CURL_SSLVERSION_MAX_NONE
  • CURL_SSLVERSION_MAX_TLSv1_0
  • CURL_SSLVERSION_MAX_TLSv1_1
  • CURL_SSLVERSION_MAX_TLSv1_2
  • CURL_SSLVERSION_MAX_TLSv1_3
  • CURL_SSLVERSION_TLSv1_3
  • CURL_VERSION_ALTSVC (as of PHP 7.3.6)
  • CURL_VERSION_ASYNCHDNS
  • CURL_VERSION_BROTLI
  • CURL_VERSION_CONV
  • CURL_VERSION_CURLDEBUG (as of PHP 7.3.6)
  • CURL_VERSION_DEBUG
  • CURL_VERSION_GSSAPI
  • CURL_VERSION_GSSNEGOTIATE
  • CURL_VERSION_HTTPS_PROXY
  • CURL_VERSION_IDN
  • CURL_VERSION_LARGEFILE
  • CURL_VERSION_MULTI_SSL
  • CURL_VERSION_NTLM
  • CURL_VERSION_NTLM_WB
  • CURL_VERSION_PSL (as of PHP 7.3.6)
  • CURL_VERSION_SPNEGO
  • CURL_VERSION_SSPI
  • CURL_VERSION_TLSAUTH_SRP

Filtrado de datos

  • FILTER_SANITIZE_ADD_SLASHES

Notación de objetos en JavaScript

  • JSON_THROW_ON_ERROR

Protocolo ligero de acceso a directorios

  • 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

String Multibyte

  • 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.


Cambios incompatibles con el pasado

Núcleo PHP

Interpretación de la etiqueta final Heredoc/Nowdoc

Debido a la introducción de la sintaxis flexible heredoc/nowdoc, los documentos string que contienen la etiqueta final dentro de su cuerpo pueden causar errores de sintaxis o cambios de la interpretación. Por ejemplo en:

<?php
$str = <<<FOO
abcdefg
   FOO
FOO;
?>
la aparición de FOO con sangría, previamente no tenía ningún significado especial. Ahora se interpretará como el final de la cadena heredoc y el siguiente FOO; provocará un error de sintaxis. Este problema siempre se puede resolver eligiendo una etiqueta final que no aparezca dentro del contenido de la cadena.

Continuar problemas del modificador de adventencias

Declaraciones de continue dirigidas a switch las estructuras de flujo de control ahora generarán una advertencia. En php la declaración continue es equivalente atargeting switch is equivalent to break, mientras estas se comportan como continue 2 en otros lenguajes.

<?php
while ($foo) {
    switch ($bar) {
      case "baz":
         continue;
         // Warning: "continue" el modificador equivale a
         //          "break". ¿Te referías a usar "continue 2"?
   }
}
?>

Interpretación estricta de las claves Integer en String ArrayAccess

Acceos de array de tipo $obj["123"], donde $obj implementa ArrayAccess y "123" es un integer string literal ya no dará como resultado una conversión implícita a integer, p.e., $obj->offsetGet("123") se llamará en lugar de $obj->offsetGet(123). Esto coincide para el comportamiento existente para los no literales. El comportamiento de arrays no se ve afectado de ninguna manera, ellos continuan explícitamente convirtiendo claves de string integrales a enteros.

Propiedades estáticas ya no separadas por asignación de referencia

En PHP, las propiedades estáticas se comparten entre las clases heredadas, a menos que la propiedad estática se invalide explícitamente en una clase secundaria. Sin embargo, debido a un macanismo de implementación fue posible separar las propiedades estáticas asignando una referencia. Esta laguna ha sido arreglada.

<?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)
?>

Referencias devueltas por Array y accesos a la propiedad se desenvuelven inmediatamente

Referencias devueltas por array y accesos a la propiedad se desenvuelven ahora como parte del acceso. Esto significa que ya no es posible modificar la referencia entre el acceso y el uso del valor de acceso:

<?php
$arr = [1];
$ref =& $arr[0];
var_dump($arr[0] + ($arr[0] = 2));
// Previously: int(4), Now: int(3)
?>
Esto hace que el comportamientos de las referencias y no referencias sea consistente. Por favor note que la lectura y escritura de un valor dentro de una sola expresión permanece como un comportamiento indefinido y puede cambiar de nuevo en el futuro.

Argumento Unpacking de Traversables con claves no enteras ya no se permiten

Argumento unpacking dejó de funcionar con Traversables con las claves no enteras. El siguiente código funcionó en PHP 5.6-7.2 por accidente.

<?php
function foo(...$args) {
    var_dump($args);
}
function gen() {
    yield 1.23 => 123;
}
foo(...gen());
?>

Varios

La utilidad ext_skel ha sido completamente rediseñada con nuevas opciones y algunas opciones antiguas eliminadas. Ahora está escrito en PHP y no tiene dependencias externas.

Soporte para el BeOS ha sido retirado.

Excepciones lanzadas debido a la conversión automática de advertencias a excepciones en modo EH_THROW (e.j. algunas excepciones DateTime) ya no ocupan el estado error_get_last(). Como tal, ahora funcionan de la misma manera que las excepciones lanzadas manualmente.

TypeError ahora informa de tipos erróneos como int y bool en lugar de integer y boolean, respectivamente.

Variables no definidas pasadas a compact() será ahora reportado como un aviso.

getimagesize() y funciones relacionadas ahora reportan el tipo mime de las imágenes BMP como image/bmp en lugar de image/x-ms-bmp, ya que el primero ha sido registrado en la IANA (véase » RFC 7903).

stream_socket_get_name() devolverá ahora las direcciones IPv6 envueltas entre paréntesis. Por ejemplo "[::1]:1337" será devuelto en lugar de "::1:1337".

BCMath Matemáticas de Precisión Arbitraria

Todas las advertencias lanzadas por las funciones BCMath son ahora usadas por el manejo de errores de PHP. Anteriormente algunas advertencias han sido escritas directamente a stderr.

bcmul() y bcpow() ahora devuelven los números con la escala solicitada. Anteriormente, los números devueltos pueden haber omitido los ceros decimales.

IMAP, POP3 y NNTP

Los inicio de sesión rsh/ssh están desactivados por defecto. Use imap.enable_insecure_rsh si quiere habilitarlos. Tenga en cuenta que la biblioteca IMAP no filtra los nombres de los buzones antes de pasarlos al comando rsh/ssh, pasando así datos no confiables a esta función con rsh/ssh habilitado es inseguro.

Multibyte String

Debido al soporte añadido a las capturas nombradas, mb_ereg_*() los patrones que utilizan las capturas nombradas se comportarán de forma diferente. En particular las capturas nombradas formarán parte de las coincidencias y mb_ereg_replace() interpretará sintaxis adicional. Véase Capturas Nombradas para más información.

Extensión mejorada de MySQL

Las declaraciones preparadas ahora reportan correctamente los segundos fraccionarios para DATETIME, TIME y TIMESTAMP columnas con especificador de decimales (e.j. TIMESTAMP(6) cuando se usan microsegundos). Anteriormente, la parte de los segundos fraccionarios fue simplemente omitida de los valores devueltos.

Funciones MySQL (PDO_MYSQL)

Las declaraciones preparadas ahora reportan correctamente los segundos fraccionarios para DATETIME, TIME y TIMESTAMP columnas con especificador de decimales (e.j. TIMESTAMP(6) cuando se usa microsegundos). Anteriormente, la parte de los segundos fraccionarios fue simplemente omitida de los valores devueltos. Por favor tenga en cuenta que esto sólo afecta a la utilización de PDO_MYSQL con los preparados emulados apagados (e.j. usando la funcionalidad de la preparación nativa). Las declaraciones que utilizan conexiones que tienen PDO::ATTR_EMULATE_PREPARES=true (que es el valor por defecto) no se vieron afectados por el fallo arreglado y ya han obtenido los valores de segundos fraccionarios adecuados al motor.

Reflection

La exportación Reflection a string utiliza ahora int y bool en lugar de integer y boolean, respectivamente.

Biblioteca estándar de PHP (SPL)

Si un autocargador SPL lanza una excepción, los siguientes autocargadores no serán ejecutados. Anteriormente todos los autocargadores eran ejecutados y las excepciones estaban encadenadas.

SimpleXML

Las operaciones matemáticas con objetos SimpleXML tratarán ahora el texto como un integer o float, lo que sea más apropieado. Anteriormente los valores se trataban como integers incondicionalmente.

User Contributed Notes

gmoreno 13-Feb-2021 09:49
Chris, that is actually mentioned here: https://www.php.net/manual/en/migration73.other-changes.php#migration73.other-changes.pcre
chris at ocproducts dot com 01-May-2020 08:17
PCRE has been updated (https://wiki.php.net/rfc/pcre2-migration#backward_incompatible_changes).
The new PCRE version is stricter in some cases.


Características obsoletas

Núcleo PHP

Constantes insensibles a mayúsculas y minúsculas

La declaración de constantes insensibles a las mayúsculas y minúsculas ha quedado obsoleta. Pasando true como el tercer argumento a define() generará ahora una advertencia de deprecación. El uso de constantes insensibles a las mayúsculas y minúsculas con un caso que

Namespaced assert()

Declarando una función llamada assert() dentro de un espacio de nombres es obsoleto. La función assert() está sujeta a un manejo especial por parte del motor, lo que puede dar lugar a un comportamiento inconsistente al definir una función con el mismo nombre.

Buscando Strings en una aguja sin string

Pasar una aguja sin string a las funciones de búsqueda de string es obsoleto. En el futuro la aguja será interpretada como un string en lugar de un punto de código ASCII. Dependiendo del comportamiento deseado, debe lanzar la aguja explícitamente al string o realizar un llamado explícito a chr(). Las siguientes funciones se ven afectadas:

  • strpos()
  • strrpos()
  • stripos()
  • strripos()
  • strstr()
  • strchr()
  • strrchr()
  • stristr()

Strip-Tags Streaming

La función fgetss() y el filtro stream string.strip_tags son obsoletos. Esto también afecta al método SplFileObject::fgetss() y la función gzgetss().

Filtrado de datos

El uso explícito de las constantes FILTER_FLAG_SCHEME_REQUIRED y FILTER_FLAG_HOST_REQUIRED es ahora obsoleto; ambos están implícitos para FILTER_VALIDATE_URL de todos modos.

Procesamiento de imágenes y GD

image2wbmp() ha quedado obsoleta.

Funciones de internacionalización

El uso de la forma Normalizer::NONE lanza una advertencia de obsoleto, si PHP es enlazado con ICU = 56.

Multibyte String

El siguiente alias indocumentado mbereg_*() ha sido desaprobado. Use las correspondientes variantes mb_ereg_*() en su lugar.

  • 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()

Funciones ODBC y DB2 (PDO_ODBC)

La configuración ini pdo_odbc.db2_instance_name ha sido formalmente desaprobada. Está obsoleto en la documentación a partir de PHP 5.1.1.

User Contributed Notes

There are no user contributed notes for this page.


Other Changes

PHP Core

Set(raw)cookie accepts $option Argument

setcookie() and setrawcookie() now also support the following signature:

setcookie ( string $name , string $value = "" , array $options = [] ) : bool
where $options is an associative array which may have any of the keys "expires", "path", "domain", "secure", "httponly" and "samesite".

New Syslog ini Directives

The following ini Directives have been added to customize logging, if error_log is set to syslog:

syslog.facility
Specifies what type of program is logging the message.
syslog.filter
Specifies the filter type to filter the logged messages. There are three supported filter types - all, no-ctrl and ascii.
syslog.ident
Specifies the ident string which is prepended to every message.

Garbage Collection

The cyclic GC has been enhanced, which may result in considerable performance improvements.

Miscellaneous

var_export() now exports stdClass objects as an array cast to an object ((object) array( ... )), rather than using the nonexistent method stdClass::__setState().

debug_zval_dump() was changed to display recursive arrays and objects in the same way as var_dump(). Now, it doesn't display them twice.

array_push() and array_unshift() can now also be called with a single argument, which is particularly convenient wrt. the spread operator.

Interactive PHP Debugger

The unused constants PHPDBG_FILE, PHPDBG_METHOD, PHPDBG_LINENO and PHPDBG_FUNC have been removed.

FastCGI Process Manager

The getallheaders() function is now also available.

Client URL Library

libcurl = 7.15.5 is now required.

Data Filtering

FILTER_VALIDATE_FLOAT now also supports a thousand option, which defines the set of allowed thousand separator chars. The default ("',.") is fully backward compatible with former PHP versions.

FILTER_SANITIZE_ADD_SLASHES has been added as an alias of the magic_quotes filter (FILTER_SANITIZE_MAGIC_QUOTES). The magic_quotes filter is subject to removal in future versions of PHP.

FTP

The default transfer mode has been changed to binary.

Internationalization Functions

Normalizer::NONE is deprecated, when PHP is linked with ICU = 56.

Introduced Normalizer::FORM_KC_CF as Normalizer::normalize() argument for NFKC_Casefold normalization; available when linked with ICU = 56.

JavaScript Object Notation

A new flag has been added, JSON_THROW_ON_ERROR, which can be used with json_decode() or json_encode() and causes these functions to throw the new JsonException upon an error, instead of setting the global error state that is retrieved with json_last_error() and json_last_error_msg(). JSON_PARTIAL_OUTPUT_ON_ERROR takes precedence over JSON_THROW_ON_ERROR.

Multibyte String

The configuration option --with-libmbfl is no longer available.

ODBC (Unified)

Support for ODBCRouter and Birdstep including the birdstep.max_links ini directive has been removed.

OPcache

The opcache.inherited_hack ini directive has been removed. The value has already been ignored since PHP 5.3.0.

OpenSSL

The min_proto_version and max_proto_version ssl stream options as well as related constants for possible TLS protocol values have been added.

Regular Expressions (Perl-Compatible)

The PCRE extension has been upgraded to PCRE2, which may cause minor behavioral changes (for instance, character ranges in classes are now more strictly interpreted), and augments the existing regular expression syntax.

preg_quote() now also escapes the '#' character.

Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

The attribute PDO::DBLIB_ATTR_SKIP_EMPTY_ROWSETS to enable automatic skipping of empty rowsets has been added.

The PDO::DBLIB_ATTR_TDS_VERSION attribute which exposes the TDS version has been added.

DATETIME2 columns are now treated like DATETIME columns.

SQLite Functions (PDO_SQLITE)

SQLite3 databases can now be opened in read-only mode by setting the new PDO::SQLITE_ATTR_OPEN_FLAGS attribute to PDO::SQLITE_OPEN_READONLY.

Session Handling

session_set_cookie_params() now also supports the following signature:

session_set_cookie_params ( array $options ) : bool
where $options is an associative array which may have any of the keys "lifetime", "path", "domain", "secure", "httponly" and "samesite". Accordingly, the return value of session_get_cookie_params() now also has an element with the key "samesite". Furthermore, the new session.cookie_samesite ini option to set the default of the SameSite directive for cookies has been added. It defaults to "" (empty string), so no SameSite directive is set. Can be set to "Lax" or "Strict", which sets the respective SameSite directive.

Tidy

Building against » tidyp is now also supported transparently. Since tidyp offers no API to get the release date, tidy_get_release() and tidy::getRelease() return 'unknown' in this case.

XML Parser

The return value of the xml_set_external_entity_ref_handler() callback is no longer ignored if the extension has been built against libxml. Formerly, the return value has been ignored, and parsing did never stop.

Zip

Building against the bundled libzip is discouraged, but still possible by adding --without-libzip to the configuration.

Zlib Compression

The zlib/level context option for the compress.zlib wrapper to facilitate setting the desired compression level has been added.

User Contributed Notes

There are no user contributed notes for this page.


Soporte de Windows

Núcleo PHP

Más eliminación de archivos conforme con POSIX

Los descriptores de archivos son abiertos en modo compartido lectura/escritura/borrado por defecto. Esto mapea efectivamente la semántica de POSIX y permite eliminar los archivos con manejador en uso. No es 100% igual, algunas diferencias de plataforma todavía persisten. Después de la eliminación, la entrada del nombre del archivo es bloqueada, hasta que todos los manejadores abiertos estén cerrados.

User Contributed Notes

There are no user contributed notes for this page.


Migración de PHP 7.1.x a PHP 7.2.x

Tabla de contenidos

  • New features
  • Nuevas funciones
  • Nuevas constantes globales
  • Cambios incompatibles hacia atrás
  • Características obsoletas en PHP 7.2.x
  • Otros cambios

Esta versión menor viene con varias características nuevas y algunas incompatibilidades que deberían ser probadas antes de cambiar de versión de PHP en entornos de producción.

Véanse también las guías de migración para versiones de PHP 7.0.x y 7.1.x.

User Contributed Notes

There are no user contributed notes for this page.


New features

New object type

A new type, object, has been introduced that can be used for (contravariant) parameter typing and (covariant) return typing of any objects.

<?php

function test(object $obj) : object
{
    return new SplQueue();
}

test(new StdClass());

Extension loading by name

Shared extensions no longer require their file extension (.so for Unix or .dll for Windows) to be specified. This is enabled in the php.ini file, as well as in the dl() function.

Abstract method overriding

Abstract methods can now be overridden when an abstract class extends another abstract class.

<?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 is now a core extension

The modern Sodium cryptography library has now become a core extension in PHP.

For a complete function reference, see the Sodium chapter.

Password hashing with Argon2

Argon2 has been added to the password hashing API, where the following constants have been exposed:

  • PASSWORD_ARGON2I
  • PASSWORD_ARGON2_DEFAULT_MEMORY_COST
  • PASSWORD_ARGON2_DEFAULT_TIME_COST
  • PASSWORD_ARGON2_DEFAULT_THREADS

Extended string types for PDO

PDO's string type has been extended to support the national character type when emulating prepares. This has been done with the following constants:

  • PDO::PARAM_STR_NATL
  • PDO::PARAM_STR_CHAR
  • PDO::ATTR_DEFAULT_STR_PARAM

These constants are utilised by bitwise OR'ing them with PDO::PARAM_STR:

<?php

$db->quote('über', PDO::PARAM_STR | PDO::PARAM_STR_NATL);

Additional emulated prepares debugging information for PDO

The PDOStatement::debugDumpParams() method has been updated to include the SQL being sent to the DB, where the full, raw query (including the replaced placeholders with their bounded values) will be shown. This has been added to aid with debugging emulated prepares (and so it will only be available when emulated prepares are turned on).

Support for extended operations in LDAP

Support for EXOP has been added to the LDAP extension. This has been done by exposing the following functions and constants:

  • 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

Address Information additions to the Sockets extension

The sockets extension now has the ability to lookup address information, as well as connect to it, bind to it, and explain it. The following four functions have been added for this:

  • socket_addrinfo_lookup()
  • socket_addrinfo_connect()
  • socket_addrinfo_bind()
  • socket_addrinfo_explain()

Parameter type widening

Parameter types from overridden methods and from interface implementations may now be omitted. This is still in compliance with LSP, since parameters types are contravariant.

<?php

interface A
{
    public function Test(array $input);
}

class B implements A
{
    public function Test($input){} // type omitted for $input
}

Allow a trailing comma for grouped namespaces

A trailing comma can now be added to the group-use syntax introduced in PHP 7.0.

<?php

use Foo\Bar\{
    Foo,
    Bar,
    Baz,
};

proc_nice() support on Windows

The proc_nice() function is now supported on Windows.

pack() and unpack() endian support

The pack() and unpack() functions now support float and double in both little and big endian.

Enhancements to the EXIF extension

The EXIF extension has been updated to support a much larger range of formats. This means that their format specific tags are now properly translated when parsing images with the exif_read_data() function. The following new formats are now supported:

  • Samsung
  • DJI
  • Panasonic
  • Sony
  • Pentax
  • Minolta
  • Sigma/Foveon
  • AGFA
  • Kyocera
  • Ricoh
  • Epson

The EXIF functions exif_read_data() and exif_thumbnail() now support passing streams as their first argument.

New features in PCRE

  • The J modifier for setting PCRE_DUPNAMES has been added.

SQLite3 allows writing BLOBs

SQLite3::openBlob() now allows to open BLOB fields in write mode; formerly only read mode was supported.

Oracle OCI8 Transparent Application Failover Callbacks

Support for Oracle Database Transparent Application Failover (TAF) callbacks has been added. TAF allows PHP OCI8 applications to automatically reconnect to a preconfigured database when a connection is broken. The new TAF callback support allows PHP applications to monitor and control reconnection during failover.

Enhancements to the ZIP extension

Read and write support for encrypted archives has been added (requires libzip 1.2.0).

The ZipArchive class now implements the Countable interface.

The zip:// stream now accepts a 'password' context option.

User Contributed Notes

info at ensostudio dot ru 11-Sep-2020 07:28
Note: you cant change parameter type for abstract method defined in interface.
<?php
abstract class AbstractAssocArray imlements ArrayAccess
{
    abstract public function offsetSet($offset, $value): void;
    ...
}
abstract class AbstractAssocArray2 extends AbstractAssocArray
{
    abstract public function offsetSet(string $offset, $value): void;
}
class AssocArray extends AbstractAssocArray2
{
    public function offsetSet(string $offset, $value): void
    {
         $this->{$offset} = $value;
    }
}
?>
It's throw fatal error: Declaration of AbstractAssocArray::offsetSet(string $offset, $value): void must be compatible with AbstractAssocArrayAccess::offsetSet($offset, $value).


Nuevas funciones

Núcleo 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()

String Multibyte

  • 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.


Nuevas constantes globales

Núcleo de PHP

  • PHP_FLOAT_DIG
  • PHP_FLOAT_EPSILON
  • PHP_FLOAT_MIN
  • PHP_FLOAT_MAX
  • PHP_OS_FAMILY

Información de fichero

  • 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

'Hash' de contraseñas

  • 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.


Cambios incompatibles hacia atrás

Evitar que number_format() devuelva el cero negativo

Anteriormente, era posible que la función number_format() devolviera -0. Aunque esto es perfectamente válido de acuerdo con la especificación de punto flotante IEEE 754, esta peculiaridad no era deseable para mostrar los números formateados en una forma legible para los humanos.

<?php

var_dump(number_format(-0.01)); // now outputs string(1) "0" instead of string(2) "-0"

Convertir las claves numéricas de objetos y arrays

Las claves numéricas ahora se manejan mejor cuando se hacen arrays de objetos y objetos en arrays (ya sea de un modo explícito o por settype()).

Esto significa que las claves de números integer (o números integer en string) de los array que están siendo lanzados a los objetos son ahora accesibles:

<?php

// array to object
$arr = [0 => 1];
$obj = (object)$arr;
var_dump(
    $obj,
    $obj->{'0'}, // ahora accesible
    $obj->{0} // ahora accesible
);

El resultado del ejemplo sería:

object(stdClass)#1 (1) {
  ["0"]=>    // la clave string ahora, en lugar de la clave de los números integer
  int(1)
}
int(1)
int(1)

Y las claves de números enteros (o string de números enteros) de los objetos que están siendo lanzados a los array son ahora accesibles:

<?php

// object to array
$obj = new class {
    public function __construct()
    {
        $this->{0} = 1;
    }
};
$arr = (array)$obj;
var_dump(
    $arr,
    $arr[0], // ahora accesible
    $arr['0'] // ahora accesible
);

El resultado del ejemplo sería:

array(1) {
  [0]=>    // clave integer ahora, en lugar de la clave de string
  int(1)
}
int(1)
int(1)

No se permite pasar null a get_class()

Anteriormente, pasar null a la función get_class() daría a conocer el nombre de la clase adjunta. Este comportamiento ya ha sido eliminado, donde se emitirá un E_WARNING en su lugar. Para lograr el mismo comportamiento que antes, el argumento debe ser simplemente omitido.

Advertencia al contar los tipos no contables

Una advertencia E_WARNING se emitirá ahora cuando se intente contar (count()) tipos no contables (esto incluye la función alias sizeof()).

<?php

var_dump(
    count(null), // NULL si no es contable
    count(1), // integers no son contables
    count('abc'), // strings no son contables
    count(new stdclass), // objetos que no implementen la interfaz Countable no son contables
    count([1,2]) // arrays son contables
);

El resultado del ejemplo sería:

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)

Mover ext/hash de los recursos a los objetos

Como parte de la migración a largo plazo lejos de los recursos, la extensión Hash se ha actualizado para utilizar objetos en lugar de recursos. El cambio debería ser perfecto para los desarrolladores de PHP, excepto cuando is_resource() ha hecho comprobaciones (que necesitará ser actualizado a is_object() en su lugar).

Mejorar los valores por omisión de SSL/TLS

Se han hecho los siguientes cambios a los valores predeterminados:

  • tls:// ahora por omisión a TLSv1.0 o TLSv1.1 o TLSv1.2
  • ssl:// un alias de tls://
  • Las constantes STREAM_CRYPTO_METHOD_TLS_* por omisión a TLSv1.0 o TLSv1.1 + TLSv1.2, en lugar de sólo TLSv1.0

gettype() devolviendo valores en recursos cerrados

Anteriormente, usar gettype() en un recurso cerrado devolvería un string de "unknown type". Ahora, un string de "resource (closed)" es devuelto.

is_object() y __PHP_Incomplete_Class

Anteriormente, usar is_object() en la clase __PHP_Incomplete_Class devolvería false. Ahora, true será devuelto.

Promover el nivel de error de las constantes no definidas

Las referencias no cualificadas a constantes no definidas generarán ahora una advertencia E_WARNING (en vez de una E_NOTICE). En la próxima versión principal de PHP, generarán excepciones Error.

Soporte de Windows

Las versiones mínimas oficialmente soportadas de Windows son ahora Windows 7/Server 2008 R2.

Comprobación de los valores de propiedad predeterminados de los rasgos (traits)

Las comprobaciones de compatibilidad de los valores de propiedad de los rasgos por omisión ya no se realizarán.

object para los nombres de las clases

El nombre object fue previamente reservado en PHP 7.0. Esto ahora se ha reservado con fuerza, prohibiendo su uso como nombre de clase, rasgo o nombre de interfaz.

Soporte de NetWare

El soporte para NetWare ha sido eliminado.

array_unique() con SORT_STRING

Mientras que array_unique() con SORT_STRING antes copiaba el array y eliminaba los elementos no únicos (sin empaquetar el array después), ahora se construye un nuevo array añadiendo los elementos únicos. Esto puede dar lugar a diferentes índices numéricos.

Cambios con floats en la función bcmod()

La función bcmod() ya no trunca números fraccionarios a números enteros. Como tal, su comportamiento ahora sigue fmod(), en lugar del operador %. Por ejemplo bcmod('4', '3.5') ahora devuelve 0.5 en lugar de 1.

Funciones de hash y hash no criptográficas

Las funciones hash_hmac(), hash_hmac_file(), hash_pbkdf2(), y hash_init() (con HASH_HMAC) ya no aceptan los no criptográficos hashes.

Opciones de la función json_decode()

La opción de la función json_decode(), JSON_OBJECT_AS_ARRAY, es ahora usada si el segundo parámetro (asociativo) es null. Anteriormente, JSON_OBJECT_AS_ARRAY siempre fue ignorado.

Salida de rand() y mt_rand()

secuencias generadas por rand() y mt_rand() para una semilla específica puede diferir de PHP 7.1 en máquinas de 64 bits (debido a la fijación de un error de sesgo de módulo en la aplicación).

La eliminación de la configuración ini sql.safe_mode

La configuración ini sql.safe_mode ha sido eliminada.

Cambios a las funciones date_parse() y date_parse_from_format()

El elemento zone de el array devuelto por las funciones date_parse() y date_parse_from_format() ahora representan segundos en vez de minutos, y su signo está invertido. Por ejemplo -120 es ahora 7200.

User Contributed Notes

There are no user contributed notes for this page.


Características obsoletas en PHP 7.2.x

Cadenas sin entrecomillar

Las cadenas sin entrecomillar que sean constantes globales inexistentes se convierten en cadenas de ellas mismas. Este comportamiento solía emitir una E_NOTICE, pero a partir de ahora emitirá una E_WARNING. En la siguiente versión mayor de PHP, se lanzará una excepción Error en su lugar.

<?php

var_dump(INEXISTENTE);

/* Output:
Warning: Use of undefined constant INEXISTENTE - assumed 'INEXISTENTE' (this will throw an Error in a future version of PHP) in %s on line %d
string(11) "INEXISTENTE"
*/

png2wbmp() and jpeg2wbmp()

Las funciones png2wbmp() y jpeg2wbmp() de la extensión GD se han marcado como obsoletas y serán borradas en la siguiente versión mayor de PHP.

Variante INTL_IDNA_VARIANT_2003

La extensión Intl ha marcado como obsoleta la variante INTL_IDNA_VARIANT_2003, que es actualmente usada como el valor por defecto de idn_to_ascii() y idn_to_utf8(). PHP 7.4 cambiará estos valores por defecto a INTL_IDNA_VARIANT_UTS46, y en la siguiente versión mayor de PHP borrará la variante INTL_IDNA_VARIANT_2003.

__autoload() method

The __autoload() method has been deprecated because it is inferior to spl_autoload_register() (due to it not being able to chain autoloaders), and there is no interoperability between the two autoloading styles.

Directiva ini track_errors y variable $php_errormsg

Cuando la directiva ini track_errors está activada, una variable $php_errormsg es creada en el ámbito local cuando ocurre un error no fatal. Dado que el método preferido de obtener ese tipo de información de errores es usando error_get_last(), esta característica ha sido marcada como obsoleta.

Función create_function()

Debido a los problemas de seguridad de esta función (siendo una envoltura de eval()), esta antigua función ha sido marcada como obsoleta. La alternativa preferida es usar funciones anónimas.

Directiva ini mbstring.func_overload

Debido a los problemas de interoperabilidad de funciones basadas en cadenas usadas en entornos con esta directiva activada, ha sido marcada como obsoleta.

Forzado a (unset)

Forzar cualquier expresión a este tipo siempre resulta en null, por lo que este tipo de forzado superfluo ha sido marcado como obsoleto.

parse_str() sin segundo argumento

Sin un segundo argumento para parse_str(), los parámetros de una cadena de consulta son establecidos en el ámbito local. Debido a los problemas de seguridad de ello, el uso de parse_str() sin un segundo parámetro ha sido marcado como obsoleto. Esta función siempre debe ser usada con dos argumentos, ya que el segundo argumento provoca que la cadena de consulta sea interpretada a un array.

Función gmp_random()

Esta función genera un número aleatorio dentro de rango que es calculado por un método no expuesto y dependiente de la plataforma. Por ello, esta función ha sido ahora marcado como obsoleto. El método preferido de generar un número aleatorio usando la extensión GMP extension es usando gmp_random_bits() y gmp_random_range().

Función each()

Esta función es mucho más lenta iterando que un foreach normal, y causa problemas de implementación con algunos cambios del lenguaje. Ha sido por tanto marcada como obsoleta.

assert() con una cadena como argumento

Usar assert() con una cadena como argumento requería que la cadena fuera eval()uada. Debido al potencial para ejecución remota de código, el uso de assert() con una cadena como argumento ha sido marcado como obsoleto en favor del uso de expresiones booleanas.

Argumento $errcontext de manejadores de errores

El argumento $errcontext contiene todas las variables locales del ámbito donde ocurrió el error. Debido a su poco uso, y los problemas que causa con optimizaciones internas, ha sido marcado como obsoleto. En su lugar, se debe usar un depurador para obtener información sobre las variables del ámbito local del lugar del error.

Función read_exif_data()

El alias read_exif_data() ha sido marcado como obsoleto. La función exif_read_data() debe ser usada en su lugar.

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.


Otros cambios

El movimiento de utf8_encode() y utf8_decode()

Las funciones utf8_encode() y utf8_decode() se han movido ahora a la extensión estándar como funciones de string, mientras que antes la extensión XML era necesaria para que estuvieran disponibles.

Cambios a las funciones mail() y mb_sendmail()

El parámetro $additional_headers de mail() y mb_sendmail() ahora aceptan un array en vez de un string.

Soporte de LMDB

La extensión DBA ahora tiene soporte para LMDB.

Cambios en el sistema de compilación de PHP

  • Unix: Ahora se requiere Autoconf 2.64 o superior para compilar PHP.
  • Unix: el argumento de configuración --with-pdo-oci ya no necesita el número de versión del Cliente Instantáneo de Oracle.
  • Unix: el argumento de configuración --enable-gd-native-ttf ha sido eliminado. Esto no se usaba desde PHP 5.5.0.
  • Windows: el argumento de configuración --with-config-profile ha sido añadido. Esto puede ser usado para guardar configuraciones específicas, como el fichero mágico config.nice.bat.

Cambios a GD

  • imageantialias() está ahora también disponible si se compila con un sistema libgd.
  • imagegd() almacena las imágenes en color verdadero como imágenes en color verdadero. Anteriormente, eran convertidos en paleta.

Se movió MCrypt a PECL

La extensión MCrypt ha sido ahora movida fuera del núcleo a PECL. Dado que la libería mcrypt no ha recibido actualizaciones desde 2007, su uso es muy desaconsejado. En su lugar, o bien la extensión OpenSSL o Sodium pueden ser usadas.

session_module_name()

Pasar "user" la función session_module_name() ahora arroja un error de tipo E_RECOVERABLE_ERROR. Anteriormente, esto ha sido silenciosamente ignorado.

User Contributed Notes

There are no user contributed notes for this page.


Migración de PHP 7.0.x a PHP 7.1.x

Tabla de contenidos

  • Nuevas características
  • Nuevas funciones
  • Nuevas constantes globales
  • Cambios retroincompatibles
  • Características obsoletas en PHP 7.1.x
  • Changed functions
  • Otros cambios
  • Soporte para Windows

Esta nueva versión menor viene con varias características nuevas y unas pocas incompatibilidades que deberían ser probadas antes de cambiar de versión de PHP en entornos de producción.

Véanse también las guías de migración para versiones de PHP 7.0.x.

User Contributed Notes

There are no user contributed notes for this page.


Nuevas características

Tipos 'nullable'

Las declaraciones de tipos para parámetros y valores de retorno ahora se pueden marcar como «nullable» prefijando el nombre del tipo con un signo de cierre de interrogación. Esto significa que, así como el tipo especificado, se puede pasar null como un argumento, o ser devuelto como un valor, respectivamente.

<?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();

El resultado del ejemplo sería:

string(10) "elePHPant"
NULL
string(10) "elePHPant"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...

Funciones 'void'

Se ha introducido un tipo de retorno, void. Las funciones declaradas con 'void' como su tipo de retorno deben o bien omitir su sentencia 'return' totalmente, o utilizar una sentencia 'return' vacía. null no es un valor de retorno válido para una función 'void'.

<?php
function intercambiar(&$izquierdo, &$derecho) : void
{
    if ($izquierdo === $derecho) {
        return;
    }

    $tmp = $izquierdo;
    $izquierdo = $derecho;
    $derecho = $tmp;
}

$a = 1;
$b = 2;
var_dump(intercambiar($a, $b), $a, $b);

El resultado del ejemplo sería:

null
int(2)
int(1)

El uso del valor de retorno de una función 'void' simplemente se evalúa a null, sin emitir advertencias. Las razón de esto es porque las advertencias implicarían el uso de funciones genéricas de orden mayor.

Desestructuración de arrays simétricos

La sintaxis abreviada de array ([]) se puede usar ahora para desestructurar arrays para asignaciones (incluyendo dentro de foreach) como alternativa a la sintaxis list() existente, la cual aún se admite.

<?php
$datos = [
    [1, 'Tom'],
    [2, 'Fred'],
];

// Estilo de list()
list($id1, $nombre1) = $datos[0];

// Estilo de []
[$id1, $list] = $datos[0];

// Estilo de list()
foreach ($datos as list($id, $nombre)) {
    // aquí va la lógica con $id y $nombre
}

// Estilo de []
foreach ($datos as [$id, $nombre]) {
    // aquí va la lógica con $id y $nombre
}

Visibilidad de las constantes de clase

Se ha añadido soporte para especificar la visibilidad de constantes de clase.

<?php
class ConstDemo
{
    const PUBLIC_CONST_A = 1;
    public const PUBLIC_CONST_B = 2;
    protected const PROTECTED_CONST = 3;
    private const PRIVATE_CONST = 4;
}

El seudotipo iterable

Se ha introducido un nuevo seudotipo (similar a callable) llamado iterable. Se puede utilizar en parámetros y tipos de retorno, donde acepta tanto arrays u objetos que implementen la interfaz Traversable. Con respecto a la subtipificación, los tipos de parámetros de clases hijas podrían ampliar una declaración de la madre de array o Traversable a iterable. Con los tipos de retorno, las clases hijas podrían reducir un tipo de retorno de la madre de iterable a array o un objeto que implemente Traversable.

<?php
function iterator(iterable $iter)
{
    foreach ($iter as $val) {
        //
    }
}

Manejo de multicaptura de excepciones

Ahora se pueden especificar múltiples excepciones por bloque catch con el carácter tubería (|). Esto es útil para cuando diferentes excepciones de diferentes jerarquías de clases son manejadas como la misma.

<?php
try {
    // algo de código
} catch (FirstException | SecondException $e) {
    // manejar la primera y segunda excepción
}

Soporte para claves en list()

Ahora se pueden especificar claves en list(), o en su nueva sintaxis abreviada []. Esto habilita la desestructuración de arrays con claves no enteras o no secuenciales.

<?php
$datos = [
    ["id" => 1, "nombre" => 'Tom'],
    ["id" => 2, "nombre" => 'Fred'],
];

// Estilo de list()
list("id" => $id1, "nombre" => $nombre1) = $datos[0];

// Estilo de []
["id" => $id1, "nombre" => $nombre1] = $datos[0];

// Estilo de list()
foreach ($datos as list("id" => $id, "nombre" => $nombre)) {
    // aquí va la lógica con $id y $nombre
}

// Estilo de []
foreach ($datos as ["id" => $id, "nombre" => $nombre]) {
    // aquí va la lógica con $id y $nombre
}

Soporte para índices negativos de cadenas

Se ha añadido soporte para índices negativos de cadenas a las funciones de manipulación de cadenas que acepten índices, así como a la indexación de cadenas con [] o {}. En tales casos, un índice negativo se interpreta como un índice desde el final de la cadena.

<?php
var_dump("abcdef"[-2]);
var_dump(strpos("aabbcc", "b", -3));

El resultado del ejemplo sería:

string (1) "e"
int(3)

Los índices negativos de cadenas y arrays ahora tambíen se admiten en la sintaxis del paso de una variable dentro de cadenas.

<?php
$string = 'bar';
echo "The last character of '$string' is '$string[-1]'.\n";
?>

El resultado del ejemplo sería:

The last character of 'bar' is 'r'.

Soporte para AEAD en ext/openssl

Se ha añadido soporte para AEAD (modos GCM y CCM) ampliando las funciones openssl_encrypt() y openssl_decrypt() con parámetros adicionales.

Conversión de 'callables' Closure con Closure::fromCallable()

Se ha introducido un nuevo método estático a la clase Closure para poder convertir de forma sencilla callables a objetos 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');

El resultado del ejemplo sería:

string(10) "some value"

Manejo de señales asíncronas

Se ha introducido una nueva función llamada pcntl_async_signals() para habilitar el manejo de señales asíncronas sin el empleo de «ticks» (lo cual introduce mucha sobrecarga).

<?php
pcntl_async_signals(true); // turn on async signals

pcntl_signal(SIGHUP,  function($sig) {
    echo "SIGHUP\n";
});

posix_kill(posix_getpid(), SIGHUP);

El resultado del ejemplo sería:

SIGHUP

Soporte para 'push' del servidor HTTP/2 en ext/curl

Se ha añadido soporte para 'push' del servidor a la extensión CURL (requiere la versión 7.46 y superior). Esto se puede aprovechar a través de la función curl_multi_setopt() con la nueva constante CURLMOPT_PUSHFUNCTION. Las constantes CURL_PUSH_OK y CURL_PUSH_DENY también han sido añadidas, por lo que la ejecución de la retrollamada 'push' del servidor pueda ser aprobada o denegada.

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


Nuevas funciones

Núcleo 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.


Nuevas constantes globales

Constantes predefinidas del núcleo

  • PHP_FD_SETSIZE

CURL

  • CURLMOPT_PUSHFUNCTION
  • CURL_PUSH_OK
  • CURL_PUSH_DENY

Filtro de datos

  • FILTER_FLAG_EMAIL_UNICODE

Procesamiento de imágenes y 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.


Cambios retroincompatibles

Lanzamiento de una excepción al pasar muy pocos argumentos a una función

Anteriormente se emitía una advertencia al invocar funciones definidas por el usuario con muy pocos argumentos. Ahora, esta advertencia ha sido promovida a una excepción de tipo Error. Este cambio solamente se aplica a funciones definidas por el usuario, no a funciones internas. Por ejemplo:

<?php
function test($param){}
test();

El resultado del ejemplo sería algo similar a:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function test(), 0 passed in %s on line %d and exactly 1 expected in %s:%d

Prohibición de llamadas dinámicas a funciones de introspección de alcance

Se han prohibido las llamadas dinámicas a ciertas funciones (de la forma $func() o array_map('extract', ...), etc.). Estas funciones bien inspeccionan o modifican otro ámbito, presentando así un comportamiento ambiguo y poco fiable. Las funciones son las siguientes:

  • assert() - con una cadena como primer argumento
  • compact()
  • extract()
  • func_get_args()
  • func_get_arg()
  • func_num_args()
  • get_defined_vars()
  • mb_parse_str() - con un argumento
  • parse_str() - con un argumento
<?php
(function () {
    $func = 'func_num_args';
    $func();
})();

El resultado del ejemplo sería:

Warning: Cannot call func_num_args() dynamically in %s on line %d

Nombres de clases, interfaces o rasgos no válidos

Los siguientes nombres no se pueden usar como nombres de clases, interfaces o rasgos:

  • void
  • iterable

Las conversiones de cadenas numéricas ahora respetan la notación científica

Las operaciones y conversiones de enteros en cadenas de numéricas ahora respetan la notación científica. Esto también incluye la operación 'cast' a (int) y l as siguientes funciones: intval() (donde la base es 10), settype(), decbin(), decoct(), y dechex().

Correcciones al algoritmo mt_rand()

mt_rand() ahora utilizará predeterminadamente la versión corregida del algoritmo Mersenne Twister. Si se confiaba en la salida determinista de mt_srand(), la constante MT_RAND_PHP con la capacidad de preservar la implementación antigua (incorrecta) mediante un segundo parámetro opcional adicional a mt_srand().

rand() es un alias de mt_rand() y srand() de mt_srand()

rand() y srand() ahora son alias de mt_rand() y mt_srand(), respectivamente. Esto significa que la salida de las siguientes funciones ha cambiado: rand(), shuffle(), str_shuffle(), y array_rand().

Rechazar el caracter de control de borrado ASCII en identificadores

El caracter de control de borrado ASCII (0x7F) ya no se puede usar en identificadores que no estén entrecomillados.

error_log cambia con el valor syslog

Si el ajuste ini de error_log se establece a syslog, los niveles de error de PHP se corresponden con los niveles de error de syslog. Esto ofrece un mayor diferenciación en los registros de errores, al contrario que el enfoque anterior, donde todos los errores eran registrados con el nivel 'notice' solamente.

No invocar a destructores en objetos incompletos

Ahora, los destructores nunca son invocados en objetos que lanzan una excepción durante la ejecución de su constructor. En versiones anteriores, este comportamiento dependía de si al objeto se le hacía referencia fuera del constructor (p.ej., mediante el rastreo de una excepción).

Manejo de call_user_func() de argumentos de referencia

call_user_func() ahora generará siempre una advertencia al llamar a funciones que esperan referencias como argumentos. Anteriormente esto dependía de si la llamada era totalmente cualificada.

Además, call_user_func() y call_user_func_array() ya no abortarán la llamada a la función es este caso. La advertencia de "expected reference" (se esperaba una referencia) será emitida, aunque la llamada procederá como siempre.

El operador de índice vacío ya no se admite más para cadenas

La aplicación del operador de índice vacío a una cadena (p.ej. $str[] = $x) lanza un error fatal en lugar de convertirla a un array silenciosamente.

Directivas ini eliminadas

Las siguientes directivas ini han sido eliminadas:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

Cambio en la ordenación de arrays cuando los elementos son creados automáticamente durante asignaciones por referencia

El orden de los elementos de un array ha cambiado cuando estos elementos han sido creados automáticamente mediante una asignación por referencia. Por ejemplo:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Salida del ejemplo anterior en PHP 7.0:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Salida del ejemplo anterior en PHP 7.1:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Ordenación de elementos iguales

El algoritmo de ordenación interno se ha mejorado, lo que podría resultar en una ordenación diferente de los elementos que se comparan como iguales.

Nota:

No confíe en el orden de elementos que se comparan como iguales; podría cambiar en cualquier momento.

Mensaje de error para los errores E_RECOVERABLE

El mensaje de error para errores E_RECOVERABLE ha cambiado de "Catchable fatal error" a "Recoverable fatal error".

Parámetro $options de unserialize()

El elemento allowed_classes del parámetro $options de unserialize() ahora está estrictamente tipificado, es decir, si se da un valor distinto a un array o un boolean, unserialize() devuelve false y emite un E_WARNING.

DateTime constructor incorporates microseconds

DateTime y DateTimeImmutable ahora incorporan adecuadamente microsegundos al ser construidos desde el momento actual, ya sea explícitamente o con una cadena relativa(p.ej., "first day of next month"). Esto significa que la simple comparación de dos instancias recién creadas ahora probablemente devuelva false en lugar de true:

<?php
new DateTime() == new DateTime();
?>

Conversión de errores fatales a excepciones Error

En la extensión Date, los datos de serialización inválidos para las clases DateTime o DatePeriod, o el fallo de inicialización de una zona horaria desde datos serializados, ahora lanzarán una excepción Error desde los métodos __wakeup() o __set_state(), en lugar de resultar en un error fatal.

En la extensión DBA, las funciones que modifican datos (como dba_insert()) ahora lanzarán una excepción Error en lugar de emitir un error fatal capturable si la clave no contiene exactamente dos elementos.

En la extensión DOM, un esquema inválido o contextos de validación RelaxNG ahora lanzarán una excepción Error en lugar de resultar en un error fatal. De manera similar, el intento de registrar una clase nodo que no extienda la clase base apropiada, o el intento de leer una propiedad inválida o escribir en una propiedad de solo lectura, también lanzará una excepción Error.

En la extensión IMAP, las direcciones de correo electrónica mayores de 16385 bytes lanzarán una excepción Error en lugar de resultar en un error fatal.

En la extensión Intl, el fallo al invocar al constructor padre en una clase que extiende Collator antes de invocar a los métodos padres ahora lanzará una excepción Error en lugar de resultar en un error fatal recuperable. También, clonar un objeto Transliterator ahora lanzará una excepción Error en caso de fallo al clonar el transliterador interno en lugar de resultar en un error fatal.

En la extensión LDAP, proporcionar un tipo de modificación desconocido a ldap_batch_modify() ahora lanzará una excepción Error en lugar de resultar en un error fatal.

En la extensión bstring, las funciones mb_ereg() y mb_eregi() ahora lanzarán una excepción ParseError si se proporciona una expresión de PHP inválida y se emplea la opción 'e'.

En la extensión Mcrypt, las funciones mcrypt_encrypt() y mcrypt_decrypt() ahora lanzarán una excepción Error en lugar de resultar en un error fatal si mcrypt no puede ser inicializado.

En la extensión mysqli, el intento de leer una propiedad inválidad o escribir en una propiedad de solo lectura ahora lanzará una excepción Error en lugar de resultar en un error fatal.

En la extensión Reflection, el fallo al recuperar un objeto de reflexión o recuperar una propiedad de un objeto ahora lanzará una excepción Error en lugar de resultar en un error fatal.

En la extensión Session, los manejadores de sesiones propios que no devuelvan cadenas para los ID de sesción ahora lanzarán una excepción Error en lugar de resultar en un error fatal cuando una función sea invocada y deba generar un ID de sesión.

En la extensión SimpleXML, la creación de un atributo sin nombre o duplicado ahora lanzará una excepción Error en lugar de resultar en un error fatal.

En la extensión SPL, el intento de clonar un objeto SplDirectory ahora lanzará una excepción Error en lugar de resultar en un error fatal. De forma simiarl, invocar a ArrayIterator::append() cuando se recorre un objeto también lanzará una excepción Error.

En la extensión estándar, la función assert(), al proporcionarle un argumento de cadena a su primer parámetro, ahora lanzará una excepción ParseError en lugar de resultar en un error fatal capturable si el código de PHP no es válido. De forma similar, invocar a forward_static_call() fuera del ámbito de una clase ahora también lanzará una excepción Error.

En la extensión Tidy, la creación manual de un objeto tidyNode ahora lanzará una excepción Error en lugar de resultar en un error fatal.

En la extensión WDDX, una referencia circular al serializar ahora lanzará una excepción Error en lugar de resultar en un error fatal.

En la extensión XML-RPC, una referencia circular al serializar ahora lanzará una instancia de una excepción Error en lugar de resultar en un error fatal.

En la extensión Zip, el método ZipArchive::addGlob() ahora lanzará una excepción Error en lugar de resultar en un error fatal si el soporte para 'glob' no está disponible.

Las variables vinculadas léxicamente no pueden reutilizar nombres

Las variables vinculadas a un cierre mediante el constructor use no pueden utilizar el mismo nombre que cualquier superglobals, $this, o cualquier parámetro. Por ejemplo, todas estas definiciones de funciones resultarán en error fatal:

<?php
$f = function () use ($_SERVER) {};
$f = function () use ($this) {};
$f = function ($param) use ($param) {};

Cambio del tipo del parámetro de long2ip()

long2ip()() ahora espera un int en vez de un string.

Codificación y decodificación de JSON

El ajuste ini serialize_precision ahora controla la precisión de serialización al codificar 'doubles'.

La decodificación de una clave vacía ahora resulta en un nombre de propiedad vacío, en lugar de _empty_ como nombre de propiedad.

<?php
var_dump(json_decode(json_encode(['' => 1])));

El resultado del ejemplo sería algo similar a:

object(stdClass)#1 (1) {
  [""]=>
  int(1)
}

Al proporcionar la bandera JSON_UNESCAPED_UNICODE a json_encode(), las secuencias U+2028 y U+2029 ahora son escapadas.

Cambios en la semántica de los parámetros de mb_ereg() y mb_eregi()

El tercer parámetro de las funciones mb_ereg() y mb_eregi() (regs) ahora será establecido a un array vacío si no hubieron coincidencias. Anteriormente, el parametro era modificado.

Eliminación del soporte para el flujo sslv2

El flujo sslv2 se ha eliminado de OpenSSL.

User Contributed Notes

david at artefactual dot com 04-Apr-2019 05:29
Regarding the ArgumentCountError, PHP 7.1+ does still support user functions with a variable number of arguments, using the "func(...$args) {}" syntax, see: https://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
mikem at gmail dot com 21-Nov-2017 12:09
ArgumentCountError - this modification is the main reason to avoid this version on older projects.
kees at twekaers dot net 21-Mar-2017 11:49
The backwards incompatible change 'The empty index operator is not supported for strings anymore' has a lot more implications than just a fatal error on the following code

<?php
$a = "";
$a[] = "hello world";
var_dump($a);
?>

This will give a fatal error in 7.1 but will work as expected in 7.0 or below and give you: (no notice, no warning)

array(1) {
  [0]=>
  string(11) "hello world"
}

However, the following is also changed:

<?php
$a = "";
$a[0] = "hello world";
var_dump($a);
// 7.1: string(1) "h"
// pre-7.1: array(1) {  [0]=>  string(11) "hello world" }

$a = "";
$a[5] = "hello world";
var_dump($a);
// 7.1: string(6) "     h"
// pre-7.1: array(1) {  [0]=>  string(11) "hello world" }

?>
m dot r dot sopacua at gmail dot com 30-Dec-2016 03:49
"OMFG! Why was session.hash_function removed?!? Dude!"

https://wiki.php.net/rfc/session-id-without-hashing

There. Saved ya a search.
love at sickpeople dot se 24-Nov-2016 07:59
For anyone migrating from 5.x to 7.1:

About "Array ordering when elements are automatically created during by reference assignments has changed" on this page

(http://php.net/manual/en/migration71.incompatible.php#migration71.incompatible.array-order)

The behaviour of 7.1 is THE SAME as of PHP 5. It is only 7.0 that differs.

See https://3v4l.org/frbUc

<?php

$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);


Características obsoletas en PHP 7.1.x

ext/mcrypt

La extensión mcrypt fue declarada «abandonware» hace casi una década, y también era bastante compleja de utilizar. Por tanto, está obsoleta en favor de OpenSSL, y será eliminada del núcleo y puesta en PECL en PHP 7.2.

Opción 'eval' para mb_ereg_replace() y mb_eregi_replace()

El modificador de patrón e está obsoleto para las funciones mb_ereg_replace() y mb_eregi_replace().

User Contributed Notes

There are no user contributed notes for this page.


Changed functions

PHP Core

  • getopt() tiene un tercer parámetro opcional que expone el índice del siguiente elemento de la lista de vectores de argumentos a procesar. Esto se hace mediante un parámetro por referencia.
  • getenv() ya no requiere su parámetro. Si se omite, serán devueltas las variables de entorno actuales como un array asociativo.
  • get_headers() ahora tiene un parámetro adicional a habilitar para el pase de contextos de flujo personalizados.
  • output_reset_rewrite_vars() ya no reinica variables de reescritura de URL de sesión.
  • parse_url() es ahora más restrictivo y da soporte a RFC3986.
  • unpack() ahora acepta un tercer parámetro opcional para especificar el índice desde el ue iniciar el desempaquetamiento.

File System

  • file_get_contents() ahora acepta un índice de búsqueda negativo si el flujo es buscable.
  • tempnam() ahora emite un aviso al recurrir al directorio temp del sistema.

JSON

  • json_encode() ahora acepta una nueva opción, JSON_UNESCAPED_LINE_TERMINATORS, para inhabilitar el escape de los caracteres U+2028 y U+2029 al proporcionar JSON_UNESCAPED_UNICODE.

Multibyte String

  • mb_ereg() ahora rechaza secuencias de bytes ilegales.
  • mb_ereg_replace() ahora rechaza secuencias de bytes ilegales.

PDO

  • PDO::lastInsertId() ahora desencadenará un error para PostgreSQL cuando nextval no ha sido llamado para la sesión actual (la conexión de postgres).

PostgreSQL

  • pg_last_notice() ahora acepta un parámetro opcional para especificar una operación. Esto se puede hacer con una de las siguientes constantes nuevas: PGSQL_NOTICE_LAST, PGSQL_NOTICE_ALL, o PGSQL_NOTICE_CLEAR.
  • pg_fetch_all() ahora acepta un segundo parámetro opcional para especificar el tipo de resultado (similar al tercer parámetro de pg_fetch_array()).
  • pg_select() ahora acepta un cuarto parámetro opcional para especificar el tipo de resultado (similar al tercer parámetro de pg_fetch_array()).

User Contributed Notes

There are no user contributed notes for this page.


Otros cambios

Avisos y advertencias sobre aritmética con cadenas no inválidas

Se han introducido nuevos errores E_WARNING y E_NOTICE al forzar cadenas no válidas usando operadores que esperan número (+ - * / ** % << >> | & ^) o sus equivalentes de asignación. Se emite un E_NOTICE cuando la cadena comienza con un valor numérico pero contiene al final caracteres no numéricos, y se emite un E_WARNING cuando la cadena no contiene ningún valor numérico.

<?php
'1b' + 'algo';

El resultado del ejemplo sería:

Notice: A non well formed numeric value encountered in %s on line %d
Warning: A non-numeric value encountered in %s on line %d

Advertencia de desbordamiento de secuencia de escape octal

Anteriormente, las secuencias de escape de cadenas octales de tres octetos desbordaban silenciosamente. Ahora, siguen desbordando, pero se emite un E_WARNING.

<?php
var_dump("\500");

El resultado del ejemplo sería:

Warning: Octal escape sequence overflow \500 is greater than \377 in %s on line %d
string(1) "@"

Reparación de inconsistencias en $this

Pese a que $this está considerada un variable especial en PHP, carece de comprobaciones apropiadas para asegurarse de que no se usó como un nombre de variable o fue reasignada. Ahora, esto se ha rectificado para asegurarse de que $this no puede ser una variable definida por el usuario, reasignada a un valor diferente, o globalizada.

Generación de ID de sesión sin 'hash'

Los ID de sesión ya no utilzarán 'hash' en su generación. Este cambio provoca la eliminación de los cuatro siguientes ajustes ini:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

Y la adición de los dos siguientes ajustes ini:

  • session.sid_length - define la longitud del ID de sesión, siendo 32 caracteres la predeterminada por retrocompatibilidad
  • session.sid_bits_per_character - define el número de bits a almacenar por carácter (esto es, aumenta el rango de caracteres que se pueden utilizar en el ID de sesión), siendo 4 el predeterminado por retrocompatibilidad

Cambios en el manejo del fichero INI

precision

Si el valor se establece a -1, se usará el modo dtoa 0. El valor predeterminado aún es 14.

serialize_precision

Si el valor se establece a -1, se usará el modo dtoa 0. Ahora se usa el valor -1 como predeterminado.

gd.jpeg_ignore_warning

El valor predeterminado de este ajuste de php.ini ha cambiado a 1, por lo que las advertencias predeterminadas de libjpeg son ignoradas.

opcache.enable_cli

El valor predeterminado para este ajuste php.ini ha cambiado a 1 (habilitado) en PHP 7.1.2.

Generación de ID de sesión con un CSPRNG solamente

Los ID de sesión ahora solamente serán generados con un CSPRNG.

Mensajes TypeError más informativos cuando se permite null

Las excepciones TypeError para comprobaciones de tipo arg_info ahora proporcionan mensajes de error más informativos. Si el tipo de parámetro o el tipo devuelto acepta null (ya sea teniente un valor predeterminado de null o siendo un tipo «nullable»), el mensaje de error ahora mencionará esto con un mensaje "must be ... or null" o "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
?>


Soporte para Windows

readline

A la extensión readline se le da soporte a través de la » biblioteca WinEditLine. De esta manera, también se le da soporte al «shell» interactivo CLI (php.exe -a).

User Contributed Notes

There are no user contributed notes for this page.


Migración de PHP 5.6.x a PHP 7.0.x

Tabla de contenidos

  • Cambios retroincompatibles
  • Nuevas características
  • Características obsoletas en PHP 7.0.x
  • Funciones cambiadas
  • Nuevas funciones
  • Nuevas clases e interfaces
  • Nuevas constantes globales
  • Cambios en los Módulos SAPI
  • Extensiones y SAPI eliminadas
  • Otros cambios

Aunque PHP 7.0 es una nueva versión mayor, se ha realizado mucho esfuerzo para hacer la migración lo más sencilla posible. Esta versión se centra principalmente en la eliminación de la funcionalidad obsoleta de versiones anteriores y en la mejora de la consistencia del lenguaje.

Existen unas pocas incompatibilidades y nuevas características que deberían considerarse, debiendo así de probar el antes de cambiar de versión de PHP en entornos de producción.

User Contributed Notes

There are no user contributed notes for this page.


Cambios retroincompatibles

Cambios en el manejo de errores y excepciones

Muchos errores fatales y errores fatales recuperables han sido convertidos en excepciones en PHP 7. Estas excepciones de error heredan de la clase Error, la cual implementa en sí la interfaz Throwable, (la interfaz base que heredan todas las excepciones).

Esto significa que los manejadores de errores personalizados podrían no desencadenarse debido a que podrían lanzarse excepciones en su lugar (causando nuevos errores fatales para excepciones Error no capturadas).

Se puede encontrar una descripción más completa de cómo operan los errores en PHP 7 en la página de errores de PHP 7. Esta guía de migración simplemente enumerará los cambios que afectan a la retrocompatiblidad.

Ya no se garantiza que set_exception_handler() reciba objetos Exception

El código que implemente un manejador de excepciones registrado con set_exception_handler() empleando una declaración de tipo de Exception causará un error fatal cuando sea lance un objeto Error.

Si el manejador necesita funcionar tanto en PHP 5 como en PHP 7, se debería eliminar la declaración de tipo del manejador, mientras que el código que sea migrado para que funcione exclusivamente en PHP 7 puede simplemente reemplazar la declaración de tipo Exception con Throwable en su lugar.

<?php
// Código de la era de PHP 5 que no funcionará.
function handler(Exception $e) { ... }
set_exception_handler('handler');

// Compatible con PHP 5 y 7.
function handler($e) { ... }

// Solo PHP 7.
function handler(Throwable $e) { ... }
?>

Los constructores internos siempre lanzan excepciones en caso de fallo

Previamente, algunas clases internas devolvían null o un objeto inutilizable cuando el constructor fallaba. Ahora, todas las clases internas lanzan una Exception en tal caso, de la misma forma que las clases de usuario ya deben de hacerlo.

Los errores de análisis lanzan un objeto ParseError

Los errores de análisis ahora lanzan un objeto ParseError. El manejo de errores para eval() ahora debería incluir un bloque catch que permita manejar dicho error.

Cambios en la severidad de avisos E_STRICT

Todos los avisos de E_STRICT han sido reclasificados a otros niveles. Se mantiene la consntante E_STRICT, por lo que llamadas como error_reporting(E_ALL|E_STRICT) no ocasionarán ningún error.

Cambios en la severidad de avisos de E_STRICT
Situación | Nuevo nivel/comportamiento
Indexación mediante un recurso | E_NOTICE
Métodos estáticos abstractos | Aviso eliminado, no genera un error
'Redefinición' de un constructor | Aviso eliminado, no genera un error
Discordancia de la signatura durante la herencia | E_WARNING
Misma propiedad (compatible) en dos rasgos empleados | Aviso eliminado, no genera un error
Acceso a una propiedad estática de forma no estática | E_NOTICE
Solamente las variables deberían ser asignadas por referencia | E_NOTICE
Solamente las variables deberían ser pasadas por referencia | E_NOTICE
Llamada a métodos no estáticos de forma estática | E_DEPRECATED

Cambios en el manejo de variables

PHP 7 ahora emplea un árbol sintáctico abstracto al analizar ficheros. Esto ha permitido muchas mejoras en el lenguaje que antes eran imposibles debido a las limitaciones del analizador empleado en versiones previas de PHP, aunque ha resultado en la eliminación de unos pocos casos especiales por razones de consistencia, dando así lugar a roturas de retrocompatibilidad. Dichos casos están detallados a continuación.

Cambios en el manejo de variables, propiedades y métodos indirectos

El acceso indirecto a variables, propiedades y métodos ahora se evalúa estrictamente de izquierda a derecha, en contraste a la mezcla anterior de casos especiales. La tabla de abajo muestra los cambios en el orden de evaluación.

Antigua y nueva evaluación de expresiones indirectas
Expresión | Interpretación de PHP 5 | Interpretación de 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']()

El código que emplee el orden antiguo de evaluación de derecha a izquierda debe ser rescrito para utilizar explícitamente el orden de evaluación con llaves (véase la columna de en medio de arriba). Esto hará al código compatible con PHP 7.x y retrocompatible con PHP 5.x.

Cambios al manejo de list()

list() ya no asigna variables en orden inverso

list() ahora asigna valores a variables en el orden en el que estas se definen, en vez de en orden inverso. En general, esto solamente afecta al caso donde list() se emplea junto con el operador de array [], como se muestra a continuación:

<?php
list($a[], $a[], $a[]) = [1, 2, 3];
var_dump($a);
?>

Salida del ejemplo anterior en PHP 5:

array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}

Salida del ejemplo anterior en PHP 7:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

En general, se recomienda no depender del orden en el que ocurren las asignaciones de list(), ya que este es un detalle de implementación que podría cambiar en el futuro.

Se han eliminado las asignaciones vacías de list()

Las construcciones de list() ya no pueden estar vacías. Lo siguiente ya no es válido:

<?php
list() = $a;
list(,,) = $a;
list($x, list(), $y) = $a;
?>
list() no puede desempaquetar strings

list() ya no puede desempaquetar variables de tipo string. Debería usarse str_split() en su lugar.

Cambio en el ordenamiento de arrays cuando los elementos se crean automáticamente durante las asignaciones por referencia

El orden de los elementos de un array ha cambiado cuando dichos elementos han sido creados automáticamente haciendo referencia a ellos en una asignación por referencia. Por ejemplo:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Salida del ejemplo anterior en PHP 5:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Salida del ejemplo anterior en PHP 7:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

global solamente acepta variables simples

Ya no se pueden utilizar variables variables con la palabra reservada global. Se puede emplear la sintaxis de llaves para emular el comportamiento anterior si fuera necesario:

<?php
function f() {
    // Válido solamente en PHP 5.
    global $$foo->bar;

    // Válido en PHP 5 y 7.
    global ${$foo->bar};
}
?>

Como principio general, se desaconseja el uso de global con algo que no sea una simple variable.

Los paréntesis alrededor de argumentos de una función ya no afectan al comportamiento

En PHP 5, el uso de paréntesis redundantes alrededor de un argumento de una función podía silenciar advertencias del estándar estricto cuando el argumento de dicha función era pasado por referencia. Estas advertencias ahora se emiten siempre.

<?php
function obtenerArray() {
    return [1, 2, 3];
}

function arrayAlCuadrado(array &$a) {
    foreach ($a as &$v) {
        $v **= 2;
    }
}

// Genera una advertencia en PHP 7.
arrayAlCuadrado((obtenerArray()));
?>

El resultado del ejemplo sería:

Notice: Only variables should be passed by reference in /tmp/test.php on line 13

Cambios en foreach

Se han realizado cambios menores en el comportamiento de la estructura de control foreach, principalmente alrededor del manejo del puntero de arrays interno y la modificación del array en su recorrido.

foreach ya no cambia el puntero de arrays interno

Antes de PHP 7, el puntero de arrays interno era modificado mientras el array se recorría con foreach. Este ya no es el caso, como se muestra en el siguiente ejemplo:

<?php
$array = [0, 1, 2];
foreach ($array as &$val) {
    var_dump(current($array));
}
?>

Salida del ejemplo anterior en PHP 5:

int(1)
int(2)
bool(false)

Salida del ejemplo anterior en PHP 7:

int(0)
int(0)
int(0)

La iteración de foreach por valor opera sobre una copia del array

Al utilizar el modo predeterminado de iteración por valor, foreach ahora opera sobre una copia del array a recorrer en lugar del array en sí. Esto significa que los cambios realizados a un array durante una iteración no afectarán a los valores que se recorren.

Se ha mejorado el comportamiento de la iteración de foreach por referencia

Cuando se itera por referencia, foreach ahora realizará un trabajo mejor realizando un seguimiento de los cambios hechos en el array durante la iteración. Por ejemplo, al añadir valores a un array mientras se recorre dará como resultado también el recorrido de los valores añadidos:

<?php
$array = [0];
foreach ($array as &$val) {
    var_dump($val);
    $array[1] = 1;
}
?>

Salida del ejemplo anterior en PHP 5:

int(0)

Salida del ejemplo anterior en PHP 7:

int(0)
int(1)

Iteración de objetos no Traversables

Recorrer un objeto no Traversable ahora tendrá el mismo comportamiento que recorrer arrays por referencia. Esto resulta en que la mejora del comportamiento al modificar un array durante la iteración se aplique también cuando se añaden propiedades a o se eleminan de un objeto.

Cambios en el manejo del tipo integer

Literales de octal inválidos

Previamente, los literales de octal que contenían números inválidos eran truncados silenciosamente (0128 era tomado como 012). Ahora, un literal de octal inválido causará un error de análisis.

Desplazamientos negativos de bits

Los desplazamientos de bit mediante números negativos ahora lanzan un ArithmeticError:

<?php
var_dump(1 >> -1);
?>

Salida del ejemplo anterior en PHP 5:

int(0)

Salida del ejemplo anterior 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

Desplazamientos de bits fuera de rango

Los desplazamientos de bits (en cualquier dirección) fuera del ancho de bit de un integer siempre resultarán en 0. Anteriormente, el comportamiento de dichos desplazamientos dependía de la arquitectura.

Cambios en la División por Cero

Anteriormente, cuando se empleaba 0 como divisor de los operadores de división (/) o módulo (%), se emitía un error de tipo E_WARNING y se devolvía false. Ahora, el operador de división devuelve un valor de tipo float así como +INF, -INF, o NAN tal como se especifica en el IEEE 754. El error E_WARNING del operador de módulo ha sido eliminado, lanzando ahora una excepción DivisionByZeroError.

<?php
var_dump(3/0);
var_dump(0/0);
var_dump(0%0);
?>

Salida del ejemplo anterior 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)

Salida del ejemplo anterior 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

Cambios en el manejo del tipo string

Un string hexadecimal ya no se considera numérico

Los string que contienen números hexadecimales ya no se consideran numéricos. Por ejemplo:

<?php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));
?>

Salida del ejemplo anterior en PHP 5:

bool(true)
bool(true)
int(15)
string(2) "oo"

Salida del ejemplo anterior 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"

Se puede emplear filter_var() para comprobar si un string contiene un numero hexadecimal, y también para convertir un string de dicho tipo en un integer:

<?php
$str = "0xffff";
$int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
if (false === $int) {
    throw new Exception("¡Número entero inválido!");
}
var_dump($int); // int(65535)
?>

\u{ puede ocasionar errores

Debido a la incorporación de la nueva sintaxis de escape de puntos de código de Unicode, los string que contienen un literal \u{ seguido de una secuencia inválida causarán un error fatal. Para evitarlo, se debería escapar la barra inicial.

Funciones eliminadas

call_user_method() y call_user_method_array()

Estas funciones estaban obsoletas en PHP 4.1.0 en favor de call_user_func() y call_user_func_array(). Se podría también considerar el uso de funciones variables y/o el operador ....

Todas las funciones ereg*

Se han eliminado todas las funciones de ereg. Se recomienda PCRE como alternativa.

Alias de mcrypt

Se ha eliminado la función obsoleta mcrypt_generic_end() en favor de mcrypt_generic_deinit().

También se han eliminado las funciones obsoletas mcrypt_ecb(),
mcrypt_cbc(), mcrypt_cfb() y
mcrypt_ofb() en favor del
uso de mcrypt_decrypt() con la constante
MCRYPT_MODE_* apropiada.

Todas las funciones de ext/mysql

Se han eliminado todas las funciones de ext/mysql. Para más detalles sobre elegir una API de MySQL diferente, Véase Elegir una API de MySQL.

Todas las funciones ext/mssql

Se han eliminado todas las funciones de ext/mssql.

  • PDO_SQLSRV
  • PDO_ODBC
  • SQLSRV
  • ODBC Unidficada API

Alias de intl

Se han eliminado los alias obsoletos datefmt_set_timezone_id() y
IntlDateFormatter::setTimeZoneID()
en favor de datefmt_set_timezone() y
IntlDateFormatter::setTimeZone(), respectivamente.

set_magic_quotes_runtime()

Se ha eliminado set_magic_quotes_runtime(), junto con su alias magic_quotes_runtime(). Estaban obsoletos en PHP 5.3.0, y de hecho se quedaron sin funcionalidad con la eliminación de las comillas mágicas en PHP 5.4.0.

set_socket_blocking()

Se ha eliminado el alias obsoleto set_socket_blocking() en favor de stream_set_blocking().

dl() en PHP-FPM

dl() ya no se puede utilizar en PHP-FPM. Permanece funcional en CLI y en SAPI embebidas.

Funciones de Type1 de GD

Se ha eliminado el soporte para fuentes Type1 de PostScript de la extensión GD, resultado en la eliminación de las siguientes funciones:

  • imagepsbbox()
  • imagepsencodefont()
  • imagepsextendfont()
  • imagepsfreefont()
  • imagepsloadfont()
  • imagepsslantfont()
  • imagepstext()

Se recomienda utilizar fuentes TrueType y sus asociadas en su lugar.

Directivas INI eliminadas

Características eliminadas

Las siguientes directivas INI han sido eliminadas, así como sus características asociadas:

  • always_populate_raw_post_data
  • asp_tags

xsl.security_prefs

Ha sido eliminada la directiva xsl.security_prefs. En su lugar, debería llamarse al método XsltProcessor::setSecurityPrefs() para controlar las preferencias de seguridad en función de cada procesador.

Otros cambios retroincompatibles

No se pueden asignar nuevos objetos por referencia

El resultado de la sentencia new ya no se puede asignar a una variable por referencia:

<?php
class C {}
$c =& new C;
?>

Salida del ejemplo anterior en PHP 5:

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

Salida del ejemplo anterior en PHP 7:

Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3

Nombres de clase, interfaz y rasgo inválidos

Los siguientes nombres no se pueden emplear para nombrar a clases, interfaces o rasgos:

  • bool
  • int
  • float
  • string
  • null
  • true
  • false

Tampoco deberían utilizarse los siguientes nombres. Aunque no generan un error en PHP 7.0, están reservados para un uso futuro, por lo que deberían considerarse obsoletos.

  • resource
  • object
  • mixed
  • numeric

Eliminación de las etiquetas ASP y de script de PHP

Se ha eliminado el soporte para usar etiquetas ASP y de script para delimitar código de PHP. Las etiquetas afectadas son:

Etiquetas ASP y de script eliminadas
Etiqueta de apertura | Etiqueta de cierre
<% | %>
<%= | %>
<script language="php"> | </script>

Eliminación de llamadas desde contextos incompatibles

Ya obsoletas en PHP 5.6, las llamadas estáticas realizadas a un método no estático con un contexto incompatible resultarán ahora en la tenencia del método llamado de una variable $this indefinida y en la emisión de una advertencia de obsolescencia.

<?php
class A {
    public function prueba() { var_dump($this); }
}

// Nota: NO extiende a A
class B {
    public function llamadaAMétodoNoEstáticoDeA() { A::prueba(); }
}

(new B)->llamadaAMétodoNoEstáticoDeA();
?>

Salida del ejemplo anterior en PHP 5.6:

Deprecated: Non-static method A::prueba() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8
object(B)#1 (0) {
}

Salida del ejemplo anterior en PHP 7:

Deprecated: Non-static method A::prueba() 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 ahora es un operador asociativo derecho

El constructor yield ya no requiere paréntesis, ya que ha pasado a ser un operador asociativo derecho con precedencia entre print y =>. Esto puede resultar en un cambio de comportamiento:

<?php
echo yield -1;
// Anteriormente era interpretado como
echo (yield) - 1;
// Y ahora es intrepretado como
echo yield (-1);

yield $foo or die;
// Anteriormente era interpretado como
yield ($foo or die);
// Y ahora es intrepretado como
(yield $foo) or die;
?>

Los paréntesis se pueden emplear para desambiguar estos casos.

Las funciones no pueden tener varios parámetros con el mismo nombre

Ya no es posible definir dos o más parámetros de función con el mismo nombre. Por ejemplo, el siguiente método generará un error E_COMPILE_ERROR:

<?php
function foo($a, $b, $sin_usar, $sin_usar) {
    //
}
?>

Las funciones que inspeccionan argumentos informan del valor del parámetro actual

func_get_arg(), func_get_args(), debug_backtrace() y las excepciones de información de rastreo ya no informarán del valor original que fue pasado a un paramétro, en su lugar proporcionarán el valor actual (el cual podría haber sido modificado).

<?php
function foo($x) {
    $x++;
    var_dump(func_get_arg(0));
}
foo(1);?>

Salida del ejemplo anterior en PHP 5:

1

Salida del ejemplo anterior en PHP 7:

2

Las sentencias switch no pueden tener varios bloques default

Ya no es posible definir dos o más bloques default en una sentencia switch. Por ejemplo, la siguiente senetencia switch generará un error E_COMPILE_ERROR:

<?php
switch (1) {
    default:
    break;
    default:
    break;
}
?>

Eliminación de $HTTP_RAW_POST_DATA

$HTTP_RAW_POST_DATA ya no está disponible. Debería usarse el flujo php://input en su lugar.

Eliminación de los comentarios # en ficheros INI

Se ha eliminado el soporte para los comentarios prefijados con # en los ficheros INI. Se debe emplear en su lugar ; (punto y coma). Este cambio se aplica a php.ini, así como a ficheros manejados por parse_ini_file() y parse_ini_string().

JSON extension replaced with JSOND

Se ha reemplazado la extensión JSON por JSOND ocasionando tres roturas de RC (retocompatibilidad). La primera, un número no puede finalizar con un punto decimal (esto es, 34. debe cambiarse para que sea o 34.0 o 34). La segunda, al utilizar notación científica, el exponente e no debe seguir inmediatamente a un punto decimal (esto es, 3.e3 se debe cambiar para que sea o 3.0e3 o 3e3). Finalmente, una cadena vacía ya no se considera un JSON válido.

Fallo de funciones internas en un desbordamiento

Anteriormente, las funciones internas truncaban de forma silenciosa números producidos desde coacciones de tipo float a integer cuando el float era demasiado grande de representar como un integer. Ahora, se emitirá un E_WARNING y se devolverá null.

Reparaciones en los valores de devolución de gestores de sesión personalizados

Cualquier función declarada implementada por gestores de sesión personalizados que devuelvan o false o -1 serán errores fatales. Si desde estas funciones se devuelve cualquier valor distinto de un booleano, -1, o 0, fallarán y se emitirá un E_WARNING.

Sort order of equal elements

El algoritmo de ordenación interno ha sido mejorado, lo cual puede resultar en un orden diferente de elementos, que se comparan como iguales, que antes.

Nota:

No dependa del orden de los elementos que se comparan como iguales; podría cambiar en cualquier momento.

User Contributed Notes

ilya dot chase at yandex dot ru 30-Apr-2019 09:22
Take note that in preg_replace() function, flag '\e' was deleted in PHP 7.0.0. This function will return null always with this flag. Doc: https://www.php.net/manual/ru/function.preg-replace.php
tkondrashov at gmail dot com 02-Oct-2018 04:34
split() was also removed in 7.0, so be sure to check your old code for it as well as the functions listed in this doc
Ray.Paseur sometimes uses Gmail 23-Mar-2017 03:51
In the section captioned "Changes to the handling of indirect variables, properties, and methods" there are parentheses used in the table directly beneath "PHP 7 interpretation."

The parentheses are intended to show the evaluation order, but they are not part of the syntax, and should not be used in the variable definition or reference.  This juxtaposition confused one of my colleagues; hopefully this note will save someone else some time.

Examples of the correct curly-brace syntax is further down the page, in the section captioned "global only accepts simple variables."
viktor dot csiky at nospam dot nospam dot eu 21-Jul-2016 11:16
It is stated:

"foreach by-value operates on a copy of the array

When used in the default by-value mode, foreach will now operate on a copy of the array being iterated rather than the array itself. This means that changes to the array made during iteration will not affect the values that are iterated."

Please note that this is not exactly true. New foreach operates on a copy of the array, by-value or by-reference. It seems that in the latter case, the array copy is simply moved over (to) the original array before it is presumably destroyed.

As a consequence of this, you may not "dereference" an array containing values - e.g. for use with ReflectionMethod::invokeArgs() or the good ole' call_user_func().
Consider the snippet below:

<?php
function deref(Array $inputArray)
{
        $retVal = [];

        foreach ($inputArray as &$inputValue)
        {
            $retVal[] = $inputValue;
        }

        return $retVal;
}
?>

As of PHP 7.0, this *will no longer work*. You will get the usual suspect:

PHP Warning:  Parameter n to whatever() expected to be a reference, value given in baz.php on line x

You need to convert it to explicitly reference the original array:
<?php
function deref(Array $inputArray)
{
        $retVal = [];

        foreach ($inputArray as $inputKey => $inputValue)
        {
            $retVal[$inputKey] = &$inputArray[$inputKey];
        }

        return $retVal;
}
?>

PLEASE NOTE that this might have the unforeseen consequence of your code not working anymore in php versions less than 5.3 (that is, 5.2 and below).
maba at mb-systemhaus dot net 12-May-2016 09:52
NOTE:
the new variable handling in PHP 7 also has side effects on the COM .NET extension. Numeric variants (in the Windows application space) now must be quoted when passed over from PHP. This is the case when the receiving application expects a variable of type variant.

Here is an example:

<?php
  $word = new COM('Word.Application');

  // now load a document, ...

  // the following works in PHP 5 but will throw an exception in PHP 7
  $word->ActiveDocument->PrintOut(false, false, 0, $outfile);

  // the following works in PHP 7 as well, please note the quotes around the '0'
  $word->ActiveDocument->PrintOut(false, false, '0', $outfile);
?>
Frank 11-Apr-2016 03:40
[Editor's Note: that change is listed in the "Changed functions" section.]

The substr function has also been changed in a backward incompatible way.

<?php
substr("test",4);  # false in PHP 5,  "" in PHP 7
?>

In fact, this is the only thing we had to change in a number of places for our code base to run on PHP 7. It's definitely an improvement though, as the old behavior tended to cause bugs in border cases.
mossy2100 19-Dec-2015 05:29
Although $x/0 is technically not infinity in a purely mathematical sense, when you understand why the IEEE float includes a value for infinity, and returns infinity in this case, it makes sense that PHP would agree with this.

The reason is that programmers don't usually divide by 0 on purpose. A value of 0 as a divisor usually occurs due to underflow, i.e. a value which is too small to be represented as a float. So, for example, if you have values like:
$x = 1;
$y = 1e-15 * 1e-15;
$z = $x/$y;
Because $y will have underflowed to 0, the division operation will throw the division by zero warning, and $z will be set to INF. In a better computer, however, $y would not have the value 0 (it would be 1e-30) and $z would not have the value INF (it would be 1e30).

In other words, 0 is not only representative of an actual 0, but also a very small number which float cannot represent correctly (underflow), and INF does not only represent infinity, but also a very big number which float cannot represent correctly (overflow). We do the best we can within the limitations of floating point values, which are really just good approximations of the actual numbers being represented.

What does bother me is that division by zero is handled in two different ways depending on the operator. I would have preferred the new DivisionByZeroError exception to be thrown in all cases, for consistency and to enforce good programming practices.
tuxedobob 11-Dec-2015 09:23
As a programmer, I don't care whether 3/0 is INF or NaN. Both answers are (probably) equally useless, and tell me that something somewhere else is screwed up.
opitz dot alexander at googlemail dot com 04-Dec-2015 04:14
About the division by zero, please see discussion to IEEEE 754
For example: http://stackoverflow.com/questions/14682005/why-does-division-by-zero-in-ieee754-standard-results-in-infinite-value
me at fquff dot io 04-Dec-2015 06:45
[Editor's note: fixed limit on user request]

As a mathematician, 3/0 == +INF IS JUST WRONG. You can't just assume 3/0 == lim_{x->0+} 3/x, which is +INF indeed, because division IS NOT A CONTINUOUS FUNCTION in x == 0.

Also, 3/0 == +INF ("positive" infinity) while -3/0 == -INF ("negative" infinity) requires the assumption that 0 is a positive number, which is just as illogical as it looks like.

The fact that a warning is emitted is good, but it should definitely equals to NaN. ±INF is just illogical (and arithmetically wrong).

Except for this "detail", looks an amazing update, can't wait to test it even further!

Cheers,
P.


Nuevas características

Declaraciones de tipo escalar

Las declaraciones de tipo escalar son de dos tipos: coercitivo (por defecto) y estricto. Ahora se pueden forzar los siguientes tipos para parámetros (tanto coercitiva como estrictamente): cadenas de caracteres (string), números enteros (int), números decimales (float), y booleanos (bool). Estos se añaden a los tipos introducidos en PHP 5: nombres de clases, interfaces, arrays y callables.

<?php
// Modo coercitivo
function sumaDeEnteros(int ...$enteros)
{
    return array_sum($enteros);
}

var_dump(sumaDeEnteros(2, '3', 4.1));

El resultado del ejemplo sería:

int(9)

Para habilitar el modo estricto se debe colocar una simple directiva declare al inicio del fichero. Esto siginfica que la rigurosidad de la tipificación de escalares se configura en función de cada fichero. Esta directiva no solamente afecta a las declaraciones de tipo de parámetros, sino también al tipo de devolución de una función (véanse las declaraciones de tipo de devolución), a funciones internas de PHP, y a funciones de extensiones cargadas.

Se puede encontrar la documentación completa y ejemplos de las declaraciones de tipo escalar en la referencia de declaraciones de tipo.

Declaraciones de tipo de devolución

PHP 7 añade soporte para declaraciones de tipo de devolución. Similarmente a las declaraciones de tipo de argumento, las declaraciones de tipo de devolución especifican el tipo del valor que será devuelto por una función. Están disponibles los mismos tipos tanto para las declaraciones de tipo de devolución como para las declaraciones de tipo de argumento.

<?php

function sumarArrays(array ...$arrays): array
{
    return array_map(function(array $array): int {
        return array_sum($array);
    }, $arrays);
}

print_r(sumarArrays([1,2,3], [4,5,6], [7,8,9]));

El resultado del ejemplo sería:

Array
(
    [0] => 6
    [1] => 15
    [2] => 24
)

Se puede encontrar la documentación completa y ejemplos de las declaraciones de tipo de devolución en la referencia de las declaraciones de tipo de devolución.

Operador de fusión de null

El operador de fusión de null (??) se ha añadido como aliciente sintáctico para el caso común de la necesidad de utilizar un operador ternario junto con isset(). Devuelve su primer operando si existe y no es null; de lo contrario devuelve su segundo operando.

<?php
// Obntener el valor de $_GET['usuario'] y devolver 'nadie'
// si no existe.
$nombre_usuario = $_GET['usuario'] ?? 'nadie';
// Esto equivale a:
$nombre_usuario = isset($_GET['usuario']) ? $_GET['usuario'] : 'nadie';

// La fusión se puede encadenar: esto devolverá el primer
// valor definido de $_GET['usuario'], $_POST['usuario'],
// y 'nadie'.
$nombre_usuario = $_GET['usuario'] ?? $_POST['usuario'] ?? 'nadie';
?>

El operador nave espacial

El operador nave espacial se emplea para comparar dos expresiones. Devuelve -1, 0 o 1 cuando $a es respectivamente menor, igual, o mayor que $b. Las comparaciones se realizan según las reglas de comparación de tipos usuales de PHP.

<?php
// Números enteros
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Numeros decimales
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Cadenas de caracteres
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>

Arrays constantes con define()

Ahora se pueden definir constantes de array con define(). En PHP 5.6, solamente se podían definir con const.

<?php
define('ANIMALES', [
    'perro',
    'gato',
    'pájaro'
]);

echo ANIMALES[1]; // imprime "gato"
?>

Clases anónimas

Se ha añadido soporte para clases anónimas mediante new clase. Estas se pueden utilizar en lugar de definiciones de clases completas para objetos desechables:

<?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());
?>

El resultado del ejemplo sería:

object(class@anonymous)#2 (0) {
}

La documentación completa se puede encontrar en la referencia de clases anónimas.

Sintaxis de escape de puntos de códigos de Unicode

Esta sintaxis toma un punto de código de Unicode en forma hexadecimal, e imprime ese punto de código en UTF-8 a un string con entrecomillado doble o a un heredoc. Se acepta cualquier punto de código válido, siendo los ceros iniciales opcionales.

echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";

El resultado del ejemplo sería:

ª
ª (lo mismo que antes pero con ceros iniciales opcinales)
?

Closure::call()

Closure::call() es una manera más eficiente y abreviada de vincular temporalmente un ámbito de objeto a un cierre e invocarlo.

<?php
class A {private $x = 1;}

// Código anterior a PHP 7
$getX = function() {return $this->x;};
$getXCB = $getX->bindTo(new A, 'A'); // cierre intermedio
echo $getXCB();

// Código de PHP 7+
$getX = function() {return $this->x;};
echo $getX->call(new A);

El resultado del ejemplo sería:

1
1

Filtros para unserialize()

Esta característica busca el proporcionar una mejor seguridad al deserializar objetos en datos no fiables. Previene de posibles inyecciones de código al capacitar al desarrollador a crear listas blancas de clases que deden ser deserializadas.

<?php

// convertir todos los objetos a un objeto __PHP_Incomplete_Class
$data = unserialize($foo, ["allowed_classes" => false]);

// convertir todos los objetos a un objeto __PHP_Incomplete_Class excepto a los de MiClase y MiClase2
$data = unserialize($foo, ["allowed_classes" => ["MiClase", "MiClase2"]]);

// comportamiento predeterminado (lo mismo que omitir el segundo argumento) que acepta todas las clases
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar

La nueva clase IntlChar busca exponer funcionalidad adicional de ICU. La clase en sí define varios métodos estáticos y constantes que se pueden emplear para manipular caracteres Unicode.

<?php

printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));

El resultado del ejemplo sería:

10ffff
COMMERCIAL AT
bool(true)

Para utilizar esta clase debe estar instalada la extensión Intl.

Previsiones

Las previsiones son una mejora retrocompatible con la antigua función assert(). Con ellas se pueden realizar afirmaciones sin coste en código de producción, proporcionando la capacidad de lanzar excepciones personalizadas cuando la afirmación falla.

Mientras que la API antigua se siguie manteniendo por compatibilidad, assert() ahora es un constructor de lenguaje, permitiendo que el primer parámetro sea una expresión en lugar de solamente un string a evaluar o un valor de tipo boolean a probar.

<?php
ini_set('assert.exception', 1);

class ErrorPersonalizado extends AssertionError {}

assert(false, new ErrorPersonalizado('Un mensaje de error'));
?>

El resultado del ejemplo sería:

Fatal error: Uncaught ErrorPersonalizado: Un mensaje de error

Se pueden encontrar los detalles completos de esta característica, incluyendo cómo configurarla tanto en entornos de desarrollo como de producción, en la sección de previsiones de la referencia de assert().

Declaraciones de use en grupo

Las clases, funciones y constantes que se importen desde el mismo namespace ahora pueden ser agrupadas en una única sentencia use.

<?php
// Código anterior a PHP 7
use un\espacioDeNombres\ClaseA;
use un\espacioDeNombres\ClaseB;
use un\espacioDeNombres\ClaseC as C;

use function un\espacioDeNombres\fn_a;
use function un\espacioDeNombres\fn_b;
use function un\espacioDeNombres\fn_c;

use const un\espacioDeNombres\ConstA;
use const un\espacioDeNombres\ConstB;
use const un\espacioDeNombres\ConstC;

// código de PHP 7+
use un\espacioDeNombres\{ClaseA, ClaseB, ClaseC as C};
use function un\espacioDeNombres\{fn_a, fn_b, fn_c};
use const un\espacioDeNombres\{ConstA, ConstB, ConstC};
?>

Expresiones 'return' en generadores

Esta característica se basa en la funcionalidad de los generadores introducida en PHP 5.5. Habilita a la sentencia return para utilizarla dentro de un generador para que pueda devolver una expresión final (la devolución por referencia no está permitida). Este valor se puede obtener empleando el nuevo método Generator::getReturn(), el cual solamente se puede utilizar una vez que el generador ha finalizado de producir valores.

<?php

$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})();

foreach ($gen as $val) {
    echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

El resultado del ejemplo sería:

1
2
3

La capacidad de devolver explícitamente un valor final desde un generador (quizá desde una forma de computación de corutina) es útil debido a que puede ser específicamente manejado por el código del cliente que ejecuta el generador. Esto es mucho más simple que forzar al código del cliente a comprobar primero si el valor final se ha generado y luego, si es asi, manejar dicho valor específicamente.

Delegación de generadores

Los generadores ahora pueden delegar a otro generador, objeto Traversable o array de forma automática, sin la necesidad de escribir «clichés» en el generador más externo con la construcción yield from.

<?php
function gen()
{
    yield 1;
    yield 2;
    yield from gen2();
}

function gen2()
{
    yield 3;
    yield 4;
}

foreach (gen() as $val)
{
    echo $val, PHP_EOL;
}
?>

El resultado del ejemplo sería:

1
2
3
4

División entera con intdiv()

La nueva función intdiv() realiza una división entera de sus operandos y la devuelve.

<?php
var_dump(intdiv(10, 3));
?>

El resultado del ejemplo sería:

int(3)

Opciones de sesión

session_start() ahora acepta un array de opciones que sobrescriben las directivas de configuración de sesiones establecidas normalmente en php.ini.

Estas opciones también se han ampliado para admitir session.lazy_write, la cual está activada de forma predeterminada y causa que PHP solamente sobrescriba cualquier fichero de sesión si los datos de sesión han cambiado, y read_and_close, la cual es una opción que se puede pasar solo a session_start() para indicar que los datos de sesión deberían ser leídos y luego la sesión debería ser cerrada inmediatamente sin cambios.

Por ejemplo, para establecer session.cache_limiter a private e inmediatamente cerrar la sesión después de leerla:

<?php
session_start([
    'cache_limiter' => 'private',
    'read_and_close' => true,
]);
?>

preg_replace_callback_array()

Con la nueva función preg_replace_callback_array(), el código escrito es más claro al emplear la función preg_replace_callback(). Antes de PHP 7, las retrollamadas que necesitaban ser ejecutadas por cada expresión regular requerían que la función de retrollamda fuera contaminada con muchas ramificaciones.

Ahora, las retrollamadas se pueden registrar para cada expresión regular usando un array asociativo, donde la clave es una expresión regular y el valor es una retrollamada.

Funciones de CSPRNG

Se han añadido dos nuevas funciones para generar números enteros y cadenas de caractéres criptográficamente seguros de una forma multiplataforma: random_bytes() y random_int().

list() siempre desempaqueta objetos que implementen ArrayAccess

Anteriormente, no se garantizaba que list() operase correctamente con objetos que implementasen ArrayAccess. Esto ha sido arreglado.

Otras características

  • Se ha añadido el acceso a miembros de clase al clonar, p.ej. (clone $foo)->bar().

User Contributed Notes

Julian Sawicki 12-Sep-2020 02:30
Currying was possible in php 5.6. But in php 7.0 it is now possible to invoke a curryied function with a one liner.

<?php
// A curried function
function add($a) {
  return function($b) use ($a) {
    return $a + $b;
  };
}

// Invoking a curried function in PHP 7
$result = add(10)(15);
var_dump($result); // int 25

// Invoking a curried function in PHP 5.6
$add10 = add(10);
$result = $add10(15);
var_dump($result); // int 25
?>
Julian Sawicki 12-Sep-2020 01:52
In php 7.0 it's possible to curry functions in a way that's similar to JavaScript.

<?php

// A curried function
function add($a) {
  return function($b) use ($a) {
    return $a + $b;
  };
}

// Invoking curried function in PHP 7
$result = add(10)(15);

var_dump($result); // int 25

?>

Currying in this way is not possible in php 5.6.
nevercode at pm dot me 18-Aug-2020 09:03
It is worth nothing that the following code just works in PHP 7.4:

```
function nullOrDefault($x = null)
{
    $x ??= 3222;

    return $x;
}
```
Adrian Wiik 16-Jan-2020 01:52
A good rule of thumb for remembering what the spaceship operator expression returns is to replace the spaceship operator with a minus sign (-). If the result is negative, 0 or positive, the expression will return -1, 0 or 1 respectively.

Example:
<?php
echo 5 <=> 8; // 5 - 8 = -3, prints -1
echo 2 <=> 2; // 2 - 2 = 0, prints 0
echo 4 <=> 2; // 4 - 2 = 2, prints 1
ricasiano at gmail dot com 08-Jan-2020 12:53
Be careful on performing null coalesce on typecasted properties. Enclose them in parenthesis

<?php
$foo = new StdClass;
//(int) 23
$bar = $foo->bas ?? 23;
var_dump($bar);

$foo = new StdClass;
//(int) 23
$bar = (int) ($foo->bas ?? 23);
var_dump($bar);

$foo = new StdClass;
$bar = (int) $foo->bas ?? 23;
//Notice: Undefined property: stdClass::$bas
var_dump($bar);
TerryE 21-Jun-2017 09:13
$a = ''; // or 0 or false

$b = $a ?? 'a';
// $b is '' or 0 or false

$c = $a ?: 'a';
// $c is 'a'
PawelD 19-Jul-2016 09:23
<?php
class foo { static $bar = 'baz'; }
var_dump('foo'::$bar);
?>

if < php7.0

then we will receive a syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

but php7 returns string(3) "baz"

I think it's not documented anywhere


Características obsoletas en PHP 7.0.x

Constructores al estilo de PHP4

Los constructores al estilo de PHP4 (métodos que tienen el mismo nombre que la clase donde están definidos) están obsoletos y serán eliminados en el futuro. PHP 7 emitirá un error E_DEPRECATED si un constructor de PHP 4 es el único definido dentro de una clase. Las clases que implementen un método __construct() no se ven afectadas.

<?php
class foo {
    function foo() {
        echo 'Soy el constructor';
    }
}
?>

El resultado del ejemplo sería:

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

Llamadas estáticas a métodos no estáticos

Una llamada estática a un método que no esté declarado como static está obsoleta y podría ser eliminada en el futuro.

<?php
class foo {
    function bar() {
        echo '¡No soy estático!';
    }
}

foo::bar();
?>

El resultado del ejemplo sería:

Deprecated: Non-static method foo::bar() should not be called statically in - on line 8
¡No soy estático!

Opción 'salt' de password_hash()

La opción 'salt' de la función password_hash() está obsoleta para prevenir a los desarrolladores de generar sus propias sales (usualmente inseguras). La función en sí genera una sal criptográficamente segura cuando el desarrollador no proprorciona ninguna. Por tanto, no debería ser necesaria la generación de sales personalizadas.

Opción de contexto SSL capture_session_meta

La opción de contexto SSL capture_session_meta ha sido declarada obsoleta. Los metadatos de SSL ahora están disponibles a través de la función stream_get_meta_data().

Obsolescencias de LDAP

La siguiente función está obsoleta:

  • ldap_sort()

User Contributed Notes

There are no user contributed notes for this page.


Funciones cambiadas

Núcleo de PHP

  • debug_zval_dump() ahora imprime "int" en lugar de "long", y "float" en lugar de "double"
  • dirname() ahora toma opcionalmente un segundo parámetro, depth, para obtener el nombre del directorio de depth niveles hasta el directorio actual.
  • getrusage() ahora tiene soporte para Windows.
  • Las funciones mktime() y gmmktime() ya no aceptan el parámetro is_dst.
  • La función preg_replace() ya no admite "\e" (PREG_REPLACE_EVAL). Debería usarse en su lugar preg_replace_callback().
  • La función setlocale() ya no acepta que category sea un string. Se deberían utilizar en su lugar las constantes LC_*.
  • Las funciones exec(), system() y passthru() ahora poseen protección del byte NULL.
  • shmop_open() ahora devuelve un recurso en lugar de un entero, el cual ha de ser pasado a shmop_size(), shmop_write(), shmop_read(), shmop_close() y shmop_delete().
  • substr() y iconv_substr() ahora devuelven una cadena vacía si el número de caracteres de la cadena de entrada es el mismo que el del parámetro 'start'.
  • xml_set_object() ahora requiere que se destruya ('unset') $parser al finalizar para evitar fugas de memoria.

User Contributed Notes

There are no user contributed notes for this page.


Nuevas funciones

Closure

  • Closure::call()

CSPRNG

  • random_bytes()
  • random_int()

Manejo y registro de errores

  • error_clear_last()

Generator

  • Generator::getReturn()

Precisión múltiple de GNU

  • gmp_random_seed()

Math

  • intdiv()

PCRE

  • preg_replace_callback_array()

Opciones/Info de PHP

  • gc_mem_caches()
  • get_resources()

POSIX

  • posix_setrlimit()

Reflection

  • ReflectionParameter::getType()
  • ReflectionParameter::hasType()
  • ReflectionFunctionAbstract::getReturnType()
  • ReflectionFunctionAbstract::hasReturnType()

Zip

  • ZipArchive::setCompressionIndex()
  • ZipArchive::setCompressionName()

Compresión Zlib

  • inflate_add()
  • deflate_add()
  • inflate_init()
  • deflate_init()

User Contributed Notes

There are no user contributed notes for this page.


Nuevas clases e interfaces

Intl

  • IntlChar

Reflection

  • ReflectionGenerator
  • ReflectionType

Manejo de sesiónes

  • SessionUpdateTimestampHandlerInterface

Jerarquía de excepciones

  • Throwable
  • Error
  • TypeError
  • ParseError
  • AssertionError
  • ArithmeticError
  • DivisionByZeroError

User Contributed Notes

There are no user contributed notes for this page.


Nuevas constantes globales

Constantes predefinidas principales

  • PHP_INT_MIN

GD

  • IMG_WEBP (a 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.


Cambios en los Módulos SAPI

FPM

Los puertos de listen no cualificados ahora escuchan tanto en IPv4 como en IPv6

En PHP 5, una directiva listen con un único número de puerto escucha en todas las interfaces, pero solamente en IPv4. PHP 7 ahora acepta peticiones realizadas mediante IPv4 y IPv6.

Esto no afecta a las directivas que incluyen direcciones IP específicas; estas continúan escuchando solamente a dichas direcciones y protocolos.

User Contributed Notes

There are no user contributed notes for this page.


Extensiones y SAPI eliminadas

Extensiones eliminadas

  • ereg
  • mssql
  • mysql
  • sybase_ct

SAPI eliminadas

  • 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.


Otros cambios

Relajación en las restricciones de palabras reservadas

Ahora están permitidas las palabras reservadas globalmente como nombres de propiedades, de constantes y de métodos dentro de clases, interfaces y rasgos. Esto reduce la superficie de roturas de retrocompatibilidad cuando se introducen nuevas palabras reservadas, y evita las restricciones de nombres en las API.

Esto es particularmente útil al crear DSL internas con interfaces fluidas:

<?php
// 'new', 'private', y 'for' no se podían utilzar antes
Proyecto::new('Nombre del proyecto')->private()->for('propósito')->with('nombre de usuario');
?>

La única limitación es que la palabra reservada class no se puede usar aún como nombre de constante, de lo contrario entraría en conflicto con la sintaxis de resolución del nombre de la clase (NombreClase::class).

Eliminación de la advertencia de date.timezone

Anteriormente, se emitía una advertencia si el ajuste INI date.timezone no estaba establecido antes de utilizar cualquier función basada en fecha u hora. Ahora, esta advertencia ha sido eliminada (siendo aún UTC el valor predeterminado de date.timezone).

User Contributed Notes

There are no user contributed notes for this page.


Migración de PHP 5.5.x a PHP 5.6.x

Tabla de contenidos

  • Cambios retroincompatibles
  • Características nuevas
  • Características obsoletas en PHP 5.6.x
  • Cambios en funciones
  • Nuevas funciones
  • Cambios de OpenSSL en PHP 5.6.x
  • Otros cambios en extensiones
  • Nuevas constantes globales

La mayoria de las mejoras de PHP 5.6.x no tienen impacto en el código existente. Hay varias incompatibilidades y nuevas características que deberían ser consideradas, ya que el código debería probarse antes de cambiar de versión de PHP en ambientes de producción.

User Contributed Notes

There are no user contributed notes for this page.


Cambios retroincompatibles

Aunque la mayoría del código existente de PHP 5 debería funcionar sin cambios, se ha de tomar nota de algunos cambios retroincompatibles:

Las claves de un array no serán sobrescritas al definir un array como propiedad de una clase mediante un literal de array

Anteriormente, los array declarados como propiedades de clase que mezclaban claves explícita e implícitamente podían tener elementos de array sobrescritos de manera silenciosa si una clave explícita era la misma que una clave implícita secuencial. Por ejemplo:

<?php
class C {
    const UNO = 1;
    public $array = [
        self::UNO => 'foo',
        'bar',
        'quux',
    ];
}

var_dump((new C)->array);
?>

Salida del ejemplo anterior en PHP 5.5:

array(2) {
  [0]=>
  string(3) "bar"
  [1]=>
  string(4) "quux"
}

Salida del ejemplo anterior en PHP 5.6:

array(3) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(4) "quux"
}

Rigurosidad de json_decode()

json_decode() ahora siempre rechaza las variantes que no estén en minúsculas de los literales true, false y null de JSON, según la especificación de JSON, y establece json_last_error() en consecuencia. Anteriormente, json_decode() aceptaba entradas que consistían únicamente en uno de estos valores en mayúsculas o mezclando también minúsculas.

Este cambio solamente afectará a los casos donde hubiera sido pasado JSON no válido a json_decode(): una entrada JSON válida no se verá afectada y continuará siendo interpretada normalmente.

Las envolturas de flujos ahora verifican de manera predeterminada los certificados del par y los nombres de host al usar SSL/TLS

Todos los flujos encriptados de clientes ahora habilitan la verificación del par por omisión. De manera predeterminada se usará el paquete de CA predeterminado de OpenSSL para verificar el certificado del par. En la mayoría de los casos no será necesario realizar ningún cambio para comunicarse con servidores que posean certificados SSL válidos, ya que los distribuidores generalmente configuran OpenSSL para que emplee paquetes de CA bien conocidos.

El paquete de CA podría ser sobrescrito globalmente estableciendo la opción de configuración openssl.cafile u openssl.capath, o en función de cada petición, usando las opciones de contexto cafile o capath.

Aunque no se recomienda en general, es posible deshabilitar la verificación del certificado del par para una petición estableciendo la opción de contexto verify_peer a false, y para deshabilitar la validación del nombre del par estableciendo a false la opción de contexto verify_peer_name.

Los recursos GMP ahora son objetos

Los recursos GMP ahora son objetos. La API funcional implementada en la extensión GMP no ha cambiado, por lo que el código debería ejecutarse sin modificaciones, a menos que se revise en busca de un recurso explícitamente empleando is_resource() o similar.

Las funciones de Mcrypt ahora requieren claves e IV válidos

mcrypt_encrypt(), mcrypt_decrypt(), mcrypt_cbc(), mcrypt_cfb(), mcrypt_ecb(), mcrypt_generic() y mcrypt_ofb() ya no aceptan claves o IV con tamaños incorrectos, por lo que los modos de cifrado de bloques que requieran algún IV fallarán si no se proporciona uno.

Subidas de ficheros de cURL

Las subidas empleando la sintaxis @file ahora requieren que CURLOPT_SAFE_UPLOAD sea establecido a false. Debería utilizarse CURLFile en su lugar.

User Contributed Notes

Roger 22-Jun-2017 10:15
Another breaking change involves opening the special "php://input" stream for decompression. In PHP 5.5, the following code would allow PHP to decode a gzip'd request input stream:

<?php
// Open the input stream for requests with Content-Encoding: gzip.
$input = gzopen('php://input','r');
// This has the same effect as fopen('compress.zlib://php://input','r').

// Get the decompressed request body.
var_dump(stream_get_contents($input));
?>

However in PHP 5.6 this does not work. Instead PHP gives the following warning: gzopen(): cannot represent a stream of type Input as a File Descriptor.

It is unclear whether this is a bug or intentional, backward-incompatible change.


Características nuevas

Expresiones constantes

Ahora es posible proporcionar una expresión escalar que involucre literales numéricos y de string y/o constantes en contextos donde PHP anteriormente demandaba un valor estático, tal como una constante, una declaración de una propiedad o argumentos de funciones predeterminados.

<?php
const UNO = 1;
const DOS = UNO * 2;

class C {
    const TRES = DOS + 1;
    const UN_TERCIO = UNO / self::TRES;
    const SENTENCE = 'El valor de TRES es '.self::TRES;

    public function f($a = UNO + self::TRES) {
        return $a;
    }
}

echo (new C)->f()."\n";
echo C::SENTENCE;
?>

El resultado del ejemplo sería:

4
El valor de TRES es 3

Ahora también es posible definir un array constante utilizando la palabra reservada const:

<?php
const ARR = ['a', 'b'];

echo ARR[0];
?>

El resultado del ejemplo sería:

a

Funciones variádicas mediante ...

Las funciones variádicas ahora se pueden implementar usando el operador ..., en lugar de depender de func_get_args().

<?php
function f($requerido, $opcional = null, ...$parámetros) {
    // $parámetros es un array que contiene los argumentos restantes.
    printf('$requerido: %d; $opcional: %d; número de parámetros: %d'."\n",
           $requerido, $opcional, count($parámetros));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);
?>

El resultado del ejemplo sería:

$requerido: 1; $opcional: 0; número de parámetros: 0
$requerido: 1; $opcional: 2; número de parámetros: 0
$requerido: 1; $opcional: 2; número de parámetros: 1
$requerido: 1; $opcional: 2; número de parámetros: 2
$requerido: 1; $opcional: 2; número de parámetros: 3

Desempaquetar argumentos mediante ...

Los array y los objetos Traversable se pueden desempaquetar a listas de argumentos al invocar a funciones empleando el operador .... A esto también se le conoce como el operador 'splat' en otros lenguajes como Ruby.

<?php
function sumar($a, $b, $c) {
    return $a + $b + $c;
}

$operadores = [2, 3];
echo sumar(1, ...$operadores);
?>

El resultado del ejemplo sería:

6

Exponenciación mediante **

Se a añadido un operador asociativo derecho, **, para realizar la exponenciación, junto con un operador de asignación abreviado, **=.

<?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);
?>

El resultado del ejemplo sería:

2 ** 3 ==      8
2 ** 3 ** 2 == 512
a ==           8

use function y use const

El operador use se ha ampliado para admitir funciones de importación y constantes además de clases. Esto se lleva a cabo mediante los contructores use function y use const, respectivamente.

<?php
namespace Espacio\De\Nombres {
    const FOO = 42;
    function f() { echo __FUNCTION__."\n"; }
}

namespace {
    use const Espacio\De\Nombres\FOO;
    use function Espacio\De\Nombres\f;

    echo FOO."\n";
    f();
}
?>

El resultado del ejemplo sería:

42
Espacio\De\Nombres\f

phpdbg

PHP ahora incluye un depurador interactivo llamado phpdbg, implementado como un módulo de SAPI. Para más información, visite la » documentación de phpdbg.

Codificación de caracteres predeterminada

default_charset ahora se emplea como conjunto de caracteres predeterminado para las funciones htmlentities(), html_entity_decode() y htmlspecialchars(). Observe que si los ajustes de codificación iconv y mbstring (ahora obsoletos) están establecidos, tomarán precedencia sobre default_charset para las funciones de iconv y mbstring, respectivamente.

El valor predeterminado para este ajuste es UTF-8.

php://input es reutilizable

php://input ahora podría se reabierto y leído tantas veces como sea necesario. Este trabajo también ha resultado en una mayor reducción de la cantidad de memoria necesaria para tratar con datos POST.

Subidas de ficheros grandes

Ahora se admiten subidas de ficheros de más de 2 gigabytes.

GMP soporta la sobrecarga de operadores

Los objetos GMP ahora soportan la sobrecarga de operadores y la conversión a tipos escalares. Esto permite código más expresivo empleando 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;
}
?>

El resultado del ejemplo sería:

59
59
59

hash_equals() para comparar string con seguridad contra ataques de temporización

Se ha añadido la función hash_equals() para comparar dos string en tiempo constante. Esto debería emplearse para mitigar los ataques de temporización; por ejemplo, al probar los hash de contraseñas de crypt() (asumiendo que no se puede usar password_hash() y password_verify(), que no son susceptibles a ataques de temporización).

<?php
$previsto   = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correcto   = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrecto = crypt('1234',  '$2a$07$usesomesillystringforsalt$');

var_dump(hash_equals($previsto, $correcto));
var_dump(hash_equals($previsto, $incorrecto));
?>

El resultado del ejemplo sería:

bool(true)
bool(false)

__debugInfo()

El método mágico __debugInfo() se ha añadido para permitir a los objetos cambiar las propiedades y los valores que se muestran cuando el objeto se imprime al utilizar 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));
?>

El resultado del ejemplo sería:

object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}

Algoritmo de hash gost-crypto

Se ha añadido el algoritmo de hash gost-crypto. Implementa la función de hash GOST usando las tablas S-box de CryptoPro, como se especifica en la » RFC 4357, sección 11.2.

Mejoras en SSL/TLS

Se han realizado un amplio rango de mejoras al soporte para SSL/TLS en PHP 5.6. Estas incluyen la habilitación de la verificación del par por omisión, el soporte para la comparación de huellas digitales de certificados, la mitigación de ataques de renegociación TLS, y muchas opciones de contexto SSL nuevas para permitir un mayor control de grano fino en ajustes de protocolos y verificaciones al emplear flujos encriptados.

Estos cambios están descritos con más detalle en la sección Cambios de OpenSSL en PHP 5.6.x de esta guía de migración.

Soporte para pgsql asíncrono

La extensión pgsql ahora admite conexiones y consultas asíncronas, habilitando así un comportamiento de no bloqueo al interactuar con bases de datos de PostgreSQL. Las conexiones asíncronas podrían esteblecerse mediante la constante PGSQL_CONNECT_ASYNC, y se podrían emplear las nuevas funciones pg_connect_poll(), pg_socket(), pg_consume_input() y pg_flush() para manejar conexiones y consultas asíncronas.

User Contributed Notes

stocki dot r at gmail dot com 25-Feb-2021 02:24
You can create a self-documented, named argument workaround in PHP 5.6-7 with ... operator:

<?php
htmlspecialchars($string, ...array_values([
    'flags'         => ENT_COMPAT | ENT_HTML401,
    'encoding'      => 'UTF-8',
    'double_encode' => false,
]))
?>
BernieV 04-Dec-2019 12:31
The splat operator (...) is documented everywhere with no space after it.
But it seems to work just as well with whitespace between ... and what follows.
My IDE line-wrapped, introducing white-space, immediately after the ...
ciachn 06-Sep-2014 07:20
Having 2 ** 3 ** 2 = 512 is actually that is the exact correct behavior for a right-associative operator just as specified in the "**" documentation.
Anonymous 15-Jul-2014 12:58
Remember, that

    ($a ** $b) ** $c === $a ** ($b * $c)

Thats why exponent operator** is RIGHT associative.
ashnazg at php dot net 21-Apr-2014 03:07
Note the order of operations in that exponentiation operator, as it was opposite of what my first expectation was:

<?php
// what I had expected,
// evaluating left to right,
// since no parens were used to guide the order of operations
2 ** 3 ** 2 == 64; // (2 ** 3) ** 2 = 8 ** 2 = 64

// the given example,
// which appears to evaluate right to left
2 ** 3 ** 2 == 512; // 2 ** (3 ** 2) = 2 ** 9 = 512
?>
gmblar+php at gmail dot com 31-Jan-2014 02:36
<?php

function array_zip(...$arrays) {
    return array_merge(...array_map(NULL, ...$arrays));
}

$a = array(1, 4, 7);
$b = array(2, 5, 8);
$c = array(3, 6, 9);

var_dump(implode(', ', array_zip($a, $b, $c)));

// Output
string(25) "1, 2, 3, 4, 5, 6, 7, 8, 9"
tr0y 25-Jan-2014 07:02
It is also possible ( in 5.6.0alpha ) to typehint the ...-operator

function foo (stdclass ... $inbound) {
   var_dump($inbound);
}

// ok:
foo( (object)['foo' => 'bar'], (object)['bar' => 'foo'] );

// fails:
foo( 1, 2, 3, 4 );


Características obsoletas en PHP 5.6.x

Llamadas desde un contexto incompatible

Los métodos llamados desde un contexto incompatible ahora están obsoletos, generando errores E_DEPRECATED en lugar de E_STRICT cuando son invocados. El soporte para dichas llamadas será eliminado en una futura versión de PHP.

Un ejemplo de tales llamadas es:

<?php
class A {
    function f() { echo get_class($this); }
}

class B {
    function f() { A::f(); }
}

(new B)->f();
?>

El resultado del ejemplo sería:

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 y always_populate_raw_post_data

always_populate_raw_post_data ahora generará un error E_DEPRECATED cuando se rellene $HTTP_RAW_POST_DATA. El código nuevo debería utilizar php://input en lugar de $HTTP_RAW_POST_DATA, el cual será eliminado en una futura versión. Se puede activar este nuevo comportamiento (en el cual $HTTP_RAW_POST_DATA nunca está definido y por tanto no se generará un error E_DEPRECATED) estableciendo always_populate_raw_post_data a -1.

Ajustes de codificación de iconv y mbstring

Las opciones de configuración de iconv y mbstring relacionadas con la codificación están obsoletas en favor de default_charset. Las opciones obsoletas son:

  • 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.


Cambios en funciones

Núcleo de PHP

  • crypt() ahora emitirá un error E_NOTICE si se omite el parámetro salt.
  • substr_compare() ahora aceptará 0 para su parámetro length.
  • unserialize() ahora fallará si se proporcionan datos serializados que hayan sido manipulados para intentar instanciar un objeto sin llamar a su constructor.

cURL

  • Las subidas empleando la sintaxis @file ahora únicamente están soportadas si la opción CURLOPT_SAFE_UPLOAD está establecida a false. Debería utilizarse en su lugar CURLFile.

Mcrypt

  • El valor predeterminado del parámetro source de mcrypt_create_iv() ahora es MCRYPT_DEV_URANDOM en vez de MCRYPT_DEV_RANDOM.

OpenSSL

  • stream_socket_enable_crypto() ahora permite que el parámetro crypto_type sea opcional si el contexto SSL del flujo incluye la nueva opción crypto_type.

PostgreSQL

  • pg_insert(), pg_select(), pg_update() y pg_delete() ya no son experimentales.
  • pg_send_execute(),
pg_send_prepare(), pg_send_query()
y pg_send_query_params() ya no bloquearán hasta
que termine la escritura de la consulta si el flujo de socket subyacente para
la conexión a la base de datos está establecido al modo de no bloqueo.

Reflection

  • ReflectionClass::newInstanceWithoutConstructor() ahora permite que se instancien clases internas no finales.

XMLReader

  • XMLReader::getAttributeNs() y XMLReader::getAttributeNo() ahora devuelven null si no se pudo encontrar el atributo, al igual que XMLReader::getAttribute().

User Contributed Notes

There are no user contributed notes for this page.


Nuevas funciones

Fecha y Hora

  • 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.


Cambios de OpenSSL en PHP 5.6.x

Las envolturas de flujos ahora verifican los certificados del par y los nombres de host por omisión al utilizar SSL/TLS

Todos los flujos encriptados de clientes ahora habilitan la verificación del par por omisión. De manera predeterminada se usará el paquete de CA predeterminado de OpenSSL para verificar el certificado del par. En la mayoría de los casos no será necesario realizar ningún cambio para comunicarse con servidores que posean certificados SSL válidos, ya que los distribuidores generalmente configuran OpenSSL para que emplee paquetes de CA bien conocidos.

El paquete de CA podría ser sobrescrito globalmente estableciendo la opción de configuración openssl.cafile u openssl.capath, o en función de cada petición, usando las opciones de contexto cafile o capath.

Aunque no se recomienda en general, es posible deshabilitar la verificación del certificado del par para una petición estableciendo la opción de contexto verify_peer a false, y para deshabilitar la validación del nombre del par estableciendo a false la opción de contexto verify_peer_name.

Huellas digitales de certificados

Se ha añadido soporte para extraer y verificar huellas digitales de certificados. Se ha añadido openssl_x509_fingerprint() para extraer una huella digital de un certificado X.509, y se han añadido dos opciones de contexto de flujo SSL: capture_peer_cert para capturar el certificado X.509 del par, y peer_fingerprint para confirmar que el certificado del par debería coincidir con la huella digital dada.

Cifradores predeterminados actualizados

Los cifradores predeterminados empleados por PHP han sido actualizados a una lista más segura basada en las » recomendaciones de cifradores de Mozilla, con dos exclusiones adicionales: cifradores Diffie-Hellman anónimos, y RC4.

Se puede acceder a la lista mediante la nueva constante OPENSSL_DEFAULT_STREAM_CIPHERS, y se puede sobrescribir (como en versiones anteriores de PHP) estableciendo la opción de contexto ciphers.

Compresión deshabilitada de forma predeterminada

La compresión SSL/TLS ha sido deshabilitada de forma predeterminada para mitigar el ataque CRIME. PHP 5.4.13 añadió la opción de contexto disable_compression para poder deshabilitar la compresión: ahora está establecida a true (es decir, la compresión está deshabilitada) de forma predeterminada.

Permitir que los servidores prefieran su orden de cifradores

Se ha añadido la opción de contexto honor_cipher_order de SSL para que los servidores de flujos encriptados mitiguen las vulnerabilidades BEAST prefiriendo los cifradores del servidor a los del cliente.

Acceder al cifrador y protocolo negociados

Ahora se puede acceder al protocolo y cifrador que eran negociados para un flujo encriptado mediante stream_get_meta_data() o stream_context_get_options() cuando la opción de contexto capture_session_meta de SSL está establecida a 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);
?>

El resultado del ejemplo sería:

array(4) {
  ["protocol"]=>
  string(5) "TLSv1"
  ["cipher_name"]=>
  string(20) "ECDHE-RSA-AES128-SHA"
  ["cipher_bits"]=>
  int(128)
  ["cipher_version"]=>
  string(11) "TLSv1/SSLv3"
}

Nuevas opciones para secreto hacia adelante perfecto en servidores de flujos encriptados

Los flujos de clientes encriptados ya admiten secreto hacia adelante perfecto (PFS por sus siglas en inglés), ya que está generalmente controlado por el servidor. Los flujos encriptados de servidores de PHP emplean certificados capaces del secreto hacia adelante perfecto no necesitan tomar ninguna acción adicional para habilitar PFS; sin embargo, se han añadido varias opciones de contexto de SSL para permitir un mayor control sobre PFS y tratar con cualquier problema de compatibilidad que pudiera surgir.

ecdh_curve

Esta opción permite la selección de una curva específica a emplear con cifradores ECDH. Si no se especifca, se empleará prime256v1.

dh_param

Una ruta a un fichero que contiene parámetros para el intercambio de claves Diffie-Hellman, tal como el creado por el siguiente comando:

openssl dhparam -out /path/to/my/certs/dh-2048.pem 2048
single_dh_use

Si se establece a true, se creará un nuevo par de claves cuando se emplean parámetros Diffie-Hellman, mejorando así el secreto hacia adelante.

single_ecdh_use

Si se establece a true, se generará siempre un nuevo par de claves cuando se negocian cifradores ECDH. Esto mejora el secreto hacia adelante.

Selección de la versión de SSL/TLS

Ahora es posible seleccionar versiones específicas de SSL y TLS mediante la opción de contexto crypto_method de SSL o estableciendo un transporte esepecífico al crear una envoltura de flujos (por ejemplo, llamando a stream_socket_client() o stream_socket_server()).

La opción de contexto crypto_method de SSL acepta una máscara de bit que enumere los protocolos que están permitidos, como lo hace crypto_type de stream_socket_enable_crypto().

Versiones de protocolo seleccionadas y opciones correspondientes
Protocolo/s | Indicador del cliente | Indicador del servidor | Transporte
Cualquier versión de TLS o SSL | STREAM_CRYPTO_METHOD_ANY_CLIENT | STREAM_CRYPTO_METHOD_ANY_SERVER | ssl://
Cualquier versión de 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

// Requerir TLS 1.0 o superior al emplear file_get_contents():
$ctx = stream_context_create([
    'ssl' => [
        'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
    ],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Requerir TLS 1.1 o 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);

// Conectar usando el transoporte de socket de flujo tlsv1.2:// .
$sock = stream_socket_client('tlsv1.2://google.com:443/');

?>

Se ha añadido openssl_get_cert_locations()

Se ha añadido la función openssl_get_cert_locations(): devuelve las ubicaciones predeterminadas en las cuales PHP buscará paquetes de CA.

<?php
var_dump(openssl_get_cert_locations());
?>

El resultado del ejemplo sería:

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) ""
}

Soporte para SPKI

Se ha añadido soporte para generar, extraer y verificar claves públicas firmadas y retos (SPKAC por sus siglas en inglés). Se han añadido openssl_spki_new(), openssl_spki_verify(), openssl_spki_export_challenge(), y openssl_spki_export() para crear, verificar y exportar claves públicas PEM y retos asociados de SPKAC generadas desde un elemento KeyGen de HTML5.

openssl_spki_new

Genera una nueva SPKAC usando una clave privada, un string con un reto y un algoritmo de hash.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
?>

El resultado del ejemplo sería:

SPKAC=MIIBXjCByDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3L0IfUijj7+A8CPC8EmhcdNoe5fUAog7OrBdhn7EkxFButUp40P7+LiYiygYG1TmoI/a5EgsLU3s9twEz3hmgY9mYIqb/rb+SF8qlD/K6KVyUORC7Wlz1Df4L8O3DuRGzx6/+3jIW6cPBpfgH1sVuYS1vDBsP/gMMIxwTsKJ4P0CAwEAARYkYjViMzYxMTktNjY5YS00ZDljLWEyYzctMGZjNGFhMjVlMmE2MA0GCSqGSIb3DQEBAwUAA4GBAF7hu0ifzmjonhAak2FhhBRsKFDzXdKIkrWxVNe8e0bZzMrWOxFM/rqBgeH3/gtOUDRS5Fnzyq425UsTYbjfiKzxGeCYCQJb1KJ2V5Ij/mIJHZr53WYEXHQTNMGR8RPm7IxwVXVSHIgAfXsXZ9IXNbFbcaLRiSTr9/N4U+MXUWL7
openssl_spki_verify

Verifica la SPKAC provista.

<?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

Exporta retos asociados desde la SPKAC provista.

<?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;
?>

El resultado del ejemplo sería:

challenge string
openssl_spki_export

Exporta la clave pública RSA con formato PEM desde la SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
echo openssl_spki_export($spkac);
?>

El resultado del ejemplo sería:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcvQh9SKOPv4DwI8LwSaFx02h7
l9QCiDs6sF2GfsSTEUG61SnjQ/v4uJiLKBgbVOagj9rkSCwtTez23ATPeGaBj2Zg
ipv+tv5IXyqUP8ropXJQ5ELtbXPUN/gvw7cO5EbPHr/7eMhbpw8Gl+AfWxW5hLW8
MGw/+AwwjHBOwong/QIDAQAB
-----END PUBLIC KEY-----

User Contributed Notes

Victor 27-Oct-2015 09:36
To get back to the "old behavior" with self-signed ("snakeoil") certificates to possibly incorrect name, you need to set both options.

<?php
            $streamContext = stream_context_create([
                'ssl' => [
                    'verify_peer'      => false,
                    'verify_peer_name' => false
                ]
            ]);
            $contents = file_get_contents('https://url', false, $streamContext);
?>


Otros cambios en extensiones

cURL

Se han eliminado varias constantes marcadas como obsoletas en la biblioteca cURL:

  • CURLOPT_CLOSEPOLICY
  • CURLCLOSEPOLICY_CALLBACK
  • CURLCLOSEPOLICY_LEAST_RECENTLY_USED
  • CURLCLOSEPOLICY_LEAST_TRAFFIC
  • CURLCLOSEPOLICY_OLDEST
  • CURLCLOSEPOLICY_SLOWEST

OCI8

  • Se ha añadido soporte para conjuntos de resultados implícitos para Oracle Database 12c mediante la nueva función oci_get_implicit_resultset().
  • El empleo de oci_execute($s, OCI_NO_AUTO_COMMIT) para una SELECT ya no inicia innecesariamente un ROLLBACK interno durante el cierre de la conexión.
  • Se han añadido las sondas DTrace controladas por la opción de configuración --enable-dtrace.
  • oci_internal_debug() ahora es una instrucción no-op.
  • Ha cambiado el formato de salida de phpinfo() para OCI8.

Zip

Se ha añadido una opción de configuración, --with-libzip, para emplear un sistema de instalación de libzip. Se requiere la versión 0.11 de libzip, y se recomienda la 0.11.2 o posterior.

MySQLi

Se ha añadido una nueva opción, mysqli.rollback_on_cached_plink, para revertir conexiones que han sido puestas de nuevo en la provisión de conexiones persistentes.

User Contributed Notes

There are no user contributed notes for this page.


Nuevas constantes globales

GD

  • IMG_WEBP (a partir de 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.


Depuración en PHP

Tabla de contenidos

  • Sobre la depuración en PHP

User Contributed Notes

Anonymous 06-Aug-2020 08:51
I often rely on a Slack channel open that is solely dedicated to debug output in whatever project I'm working on. Then I use a PHP function called debug($obj) that takes $obj and uses the Slack API to post a message with that value to that channel. It's helped me immensely and hopefully it would help others too.
shananpk95 at gmail dot com 12-Mar-2020 04:51
I am using two ways to debug code

one is print the data and die the function in specific point.

     print_r($data);die;

second one is writing log file in specific point in code.

function write_log($log_msg)
{
    $log_filename = "logs";
    if (!file_exists($log_filename))
    {
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/debug.log';
  file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);

}

write_log("Writing Log");
$a = array(
        array('id' => '1','date' => '09-04-2018','length' => '10'),
        array('id' => '2','date' => '09-04-2018','length' => '20'),
        array('id' => '1','date' => '10-04-2018','length' => '11')
    );
write_log(print_r($a,1));
Fonstw 26-Feb-2020 08:54
For me, just outputting variables only works when I know a method should be broken.

I use Xdebug in PHP Storm (available on other IDE's and editors as well)
It allows me to use line breaks and fully inspect anything that's set and how their values are changed and allows me to call single method even at (paused) runtime to see what behaviour the method really gives at any given point, which gives me a much better insight on how my code works and how to get it to work like it should.

I wholeheartedly recomend anyone to try a fuller-fledged debugger like that!
metron19 at yandex dot ru 31-Jul-2019 12:56
A good example of data output to the console via <script> tags, I myself used this first, but he broke the captcha job, because <script> tags were inserted into the base64 code of the captcha picture. Then I began to display logs in the headers with such a function (it may help someone else, in a similar situation):

<?php

function header_log($data){
  $bt = debug_backtrace();
  $caller = array_shift($bt);
  $line = $caller['line'];
  $file = array_pop(explode('/', $caller['file']));
  header('log_'.$file.'_'.$caller['line'].': '.json_encode($data));
}

?>

Usage:
$myvar = array(1,2,3);
header_log( $myvar ); // in headers we see: log_filename_rownumber: [1,2,3]
tekintian at gmail dot com 24-Mar-2019 12:07
<?php
/**
 * ??????
 * @FileName: test_helper.php
 * @Author: TekinTian
 * @QQ: 3316872019
 * @Email: tekintian@gmail.com
 * @Supported: http://dev.yunnan.ws/
 * @Date:   2017-01-23 11:45:26
 * @Last Modified 2019-03-04
 */

if (!function_exists('dd')) {
    /**
     * ??????
     * @param  [type] $arr [description]
     * @return [type]      [description]
     */
    function dd($arr) {
        if (is_array($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";
        } else if (is_object($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";

        } else {
            echo $arr;
        }
        die;
    }
}

if (!function_exists('pp')) {
    /**
     * ?????
     * @param  [type] $arr [description]
     * @return [type]      [description]
     */
    function pp($arr) {
        if (is_array($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";
        } else if (is_object($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";

        } else {
            echo $arr;
        }
        die;
    }
}

if (!function_exists('pr')) {
    /**
     * ?????
     */
    function pr($arr) {
        if (is_array($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";
        } else if (is_object($arr)) {
            echo "<pre>";
            print_r($arr);
            echo "</pre>";

        } else {
            echo $arr;
        }
    }
}

if (!function_exists('vd')) {
    /**
     * ??????
     * @param  [type] $arr [description]
     * @return [type]      [description]
     */
    function vd($arr) {
        echo "<pre>";
        var_dump($arr);
        echo "</pre>";
        die;
    }
}

if (!function_exists('vv')) {
    function vv($arr) {
        echo "<pre>";
        var_dump($arr);
        echo "</pre>";
    }
}

if (!function_exists('console_log')) {
    /**
     * console.log???????
     * @param  [type] $data [?????????? ???????????]
     * @return [type]       [description]
     */
    function console_log($data) {
        if (is_array($data) || is_object($data)) {
            echo ("<script>console.log('" . json_encode($data) . "');</script>");
        } else {
            echo ("<script>console.log('" . $data . "');</script>");
        }
    }
}

/**
 * ??????????,????????
 *
 * @param     mixed   $var       ????????
 * @param     bool    $echo      ??????
 * @param     string  $label     ??????,???,???"???:"????
 * @param     bool    $strict    ??????
 * @return    string
 */
if (!function_exists('dump')) {
    function dump($var, $echo = true, $label = null, $strict = true) {
        $label = ($label === null) ? '' : rtrim($label) . ' ';
        if (!$strict) {
            if (ini_get('html_errors')) {
                $output = print_r($var, true);
                $output = "<pre>" . $label . htmlspecialchars($output, ENT_QUOTES) . "</pre>";
            } else {
                $output = $label . " : " . print_r($var, true);
            }
        } else {
            ob_start();
            var_dump($var);
            $output = ob_get_clean();
            if (!extension_loaded('xdebug')) {
                $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            }
        }
        if ($echo) {
            echo ($output);
            return null;
        } else {
            return $output;
        }

    }
}
rajendra at skydevelopers dot net 29-Sep-2018 11:06
I also use a method to print complete data from www.skydevelopers.net company:

function dd($data) {
    echo '<pre>';
    print_r($data);
    exit;
}

well this is also very beneficial
eric at derewonko dot com 14-Jan-2018 09:08
None of the given examples here do fit my needs.
When I debug, I want to see clearly what's going on and where is the debug data. Also it has to accommodate with the current styles and not fall behind or get mixed with other text etc.
This snippet will give you real debug notices in a flashy table:
- complete backtrace of calls on the left with line numbers
- arguments content on the right, with the variable name and coloring per variable type

<?php
function wtf(){
  error_reporting(E_ALL);
  $args = func_get_args();
  $backtrace = debug_backtrace();
  $file = file($backtrace[0]['file']);
  $src  = $file[$backtrace[0]['line']-1];  // select debug($varname) line where it has been called
  $pat  = '#(.*)'.__FUNCTION__.' *?\( *?\$(.*) *?\)(.*)#i';  // search pattern for wtf(parameter)
  $arguments  = trim(preg_replace($pat, '$2', $src));  // extract arguments pattern
  $args_arr = array_map('trim', explode(',', $arguments));

  print '<style>
  div.debug {visible; clear: both; display: table; width: 100%; font-family: Courier,monospace; border: medium solid red; background-color: yellow; border-spacing: 5px; z-index: 999;}
  div.debug > div {display: unset; margin: 5px; border-spacing: 5px; padding: 5px;}
  div.debug .cell {display: inline-flex; padding: 5px; white-space: pre-wrap;}
  div.debug .left-cell {float: left; background-color: Violet;}
  div.debug .array {color: RebeccaPurple; background-color: Violet;}
  div.debug .object pre {color: DodgerBlue; background-color: PowderBlue;}
  div.debug .variable pre {color: RebeccaPurple; background-color: LightGoldenRodYellow;}
  div.debug pre {white-space: pre-wrap;}
  </style>'.PHP_EOL;
  print '<div class="debug">'.PHP_EOL;
  foreach ($args as $key => $arg) {
    print '<div><div class="left-cell cell"><b>';
    array_walk(debug_backtrace(),create_function('$a,$b','print "{$a[\'function\']}()(".basename($a[\'file\']).":{$a[\'line\']})<br> ";'));
    print '</b></div>'.PHP_EOL;
    if (is_array($arg)) {
      print '<div class="cell array"><b>'.$args_arr[$key].' = </b>';
      print_r(htmlspecialchars(print_r($arg)), ENT_COMPAT, 'UTF-8');
      print '</div>'.PHP_EOL;
    } elseif (is_object($arg)) {
      print '<div class="cell object"><pre><b>'.$args_arr[$key].' = </b>';
      print_r(htmlspecialchars(print_r(var_dump($arg))), ENT_COMPAT, 'UTF-8');
      print '</pre></div>'.PHP_EOL;
    } else {
      print '<div class="cell variable"><pre><b>'.$args_arr[$key].' = </b>&gt;';
      print_r(htmlspecialchars($arg, ENT_COMPAT, 'UTF-8').'&lt;');
      print '</pre></div>'.PHP_EOL;
    }
    print '</div>'.PHP_EOL;
  }
  print '</div>'.PHP_EOL;
}
?>

Usage: wtf($arg1, $arg2,..);
That's it!
Bladimir 28-Sep-2017 02:24
Following example above using variable-lenght arguments to support similar Web API's console.log implementation

<?php
function console_log( ...$messages ){
  $msgs = '';
  foreach ($messages as $msg) {
    $msgs .= json_encode($msg);
  }

  echo '<script>';
  echo 'console.log('. json_encode($msgs) .')';
  echo '</script>';
}

?>
Anonymous 19-Apr-2017 08:17
I would like to add http://phpdebugbar.com/ which is also a handy tool for debugging/profiling data. and you could use it whenever framework you are using. :-)
netyou 27-Sep-2015 07:29
I find it very useful to print out to the browsers console instead of just var_dumping:

function console_log( $data ){
  echo '<script>';
  echo 'console.log('. json_encode( $data ) .')';
  echo '</script>';
}

Usage:
$myvar = array(1,2,3);
console_log( $myvar ); // [1,2,3]
skatebiker at gmail dot com 05-Dec-2014 01:24
p_r() is a function for logging variable values.

In this example the function p_r() does only log when the URL parameter d=<nonzero> is set. Reset it by d=0.
When  the parameter is a valid filename (relative to the script's path) it will be logged to that file rather than to the browser.

[code]
@session_start();
// debug
if (isset($_GET['d']))
{
  $_SESSION['d'] = $_GET['d'];
}

if (@$_SESSION['d']) {

function p_r($exp)
{
  $res = "";
  $trace = debug_backtrace();
  $level = 0;
  $e = error_reporting(E_ALL&~E_NOTICE);
  $file = strrpos($trace[$level]['file'], "/");
  $file = substr($trace[$level]['file'],$file+1);
  $line = date("H:i:s"). " " . $file . ' ' . $trace[$level]['line'] . ' ' . $trace[$level+1]['function'] . "()";
  $e = error_reporting($e);
  if (!is_string($exp)) $exp = var_export($exp,1);
  if (substr($_SESSION["d"],-4)==".log") {
    file_put_contents ($_SESSION["d"],$line . ": ". $exp . "\n",  FILE_APPEND);
  } else {
    $res = $line . "\n<pre>".htmlentities($exp). "</pre>\n";
    echo $res;
  }
  return $res;
}

    // refresh to prevent timeout
  $a = $_SESSION['d'];
  $_SESSION['d'] = $a;
  error_reporting (E_ALL);

} else {
  function  p_r() {}
}  // end if debug

[/code]
online _ use _ only == hotmail.com 15-Mar-2006 03:41
I still find that printing out variable values at problem points in the code is one of the easiest ways for me to debug.  If you're interested in knowing the full contents of an object/array/scalar, then use

var_dump($var).


Sobre la depuración en PHP

PHP 5.6 viene con el depurador interactivo phpdbg. Las versiones de PHP anteriores a la 5.6 no cuentan con una herramienta de depuración interna, sin embargo. Aún así, se puede utilizar uno de los depuradores externos. El » IDE Zend incluye un depurador y existen también algunas extensiones de depuración gratuitas como DBG en » http://www.php-debugger.com/dbg/, el » Depurador Avanzado de PHP (APD, por sus siglas en Inglés) o » Xdebug.

User Contributed Notes

Marco 17-Feb-2020 06:10
Kint is an awesome debugger.
To quote the author ... Its var_dump BUT ON STEROIDS !
pegasus.is.a.geek[at]gmail 24-May-2019 07:51
NOTE: ADP hasn't been maintained since 2004


Opciones de configuración

Tabla de contenidos

  • Listado de opciones de configuración del núcleo

User Contributed Notes

squeeNoSpam at NoSpamAddress dot com 14-Aug-2002 12:06
[Editor's note: The reason why some general options for the "configure" scripts are not documented is that said script is part of the GNU autoconf tools, and as such its general options are documented elsewhere, e.g.: http://www.gnu.org/manual/autoconf/index.html and http://www.airs.com/ian/configure/. Some are also documented in the INSTALL file that comes with the source distribution.]

The --prefix=PREFIX configure option isn't mentioned here. It apparently defaults to /usr/local, and sets the position of the php includes and libs. (in PREFIX/include/php and PREFIX/lib/php)


Listado de opciones de configuración del núcleo

A continuación se muestra una lista de parte de las opciones de configuración usadas por el script configure de PHP cuando se compila en entornos como UNIX. La mayoría de las opciones de configuración se enumeran en su ubicación correspondiente de las páginas de referencia de cada extensión, no aquí. Para una lista actualizada y completa de las opciones de configuración, ejecute ./configure --help en el directorio origen de PHP después de ejecutar autoconf (véase también el capítulo de Instalación). Podría ser interesante también consultar la documentación de » GNU configure para mayor información en otras opciones de configure como --prefix=PREFIJO.

Nota:

Estas opciones se utilizan únicamente durante la compilación. Si desea alterar la configuración en tiempo de ejecución de PHP, por favor vea el capítulo sobre Configuración en tiempo de ejecución.

  • Misceláneo
  • Comportamiento de PHP
  • Servidor

Opciones de configuración en PHP

Otras opciones

--enable-debug

Compilar con símbolos de depuración.

--with-layout=TYPE

Establece la forma de presentar los ficheros instalados. El tipo es PHP (predeterminado) o GNU.

--with-pear=DIR

Instalar PEAR en DIR (valor predeterminado PREFIJO/lib/php).

--without-pear

No instalar PEAR.

--enable-sigchild

Habilitar el propio manejador SIGCHLD de PHP.

--disable-rpath

Deshabilitar el paso de rutas adicionales de búsqueda de bibliotecas en tiempo de ejecución.

--enable-libgcc

Habilitar explícitamente el enlazado con libgcc.

--enable-php-streams

Incluir flujos de PHP experimentales. ¡No se use a menos que este probando el código!.

--with-zlib-dir[=DIR]

Definir la localización del directorio de instalación de zlib.

--with-tsrm-pthreads

Usar hilos de POSIX (predeterminado).

--enable-shared[=PKGS]

Construir bibliotecas compartidas [predeterminado=yes].

--enable-static[=PKGS]

Construir bibliotecas estáticas [predeterminado=yes].

--enable-fast-install[=PKGS]

Optimizar para una instalación rápida [predeterminado=yes].

--with-gnu-ld

Asumir que el compilador de C usa ld de GNU [predeterminado=no].

--disable-libtool-lock

Evitar bloqueos (podría romper construcciones en paralelo).

--with-pic

Intentar usar solo objetos PIC/no PIC [predeterminado=use both].

--enable-memory-limit

Compilar con soporte de límite de memoria. (No disponible desde PHP 5.2.1: siempre está habilitado).

--disable-url-fopen-wrapper

Deshabilitar la envoltura de fopen que considera URL que permita el acceso a ficheros mediante HTTP o FTP. (No disponible desde PHP 5.2.5)

--enable-versioning

Exportar solo los símbolos requeridos. Véase INSTALL para más información.

Opciones de PHP

--enable-maintainer-mode

Habilita las reglas y dependencias de Make, que no son útiles (y en ocasiones son confusas) para el usuario habitual.

--with-config-file-path=PATH

Establece la ruta a seguir para php.ini, el valor por defecto es /PREFIX/lib.

--enable-safe-mode

Habilita safe mode por defecto.

Advertencia

Esta característica ha sido declarada OBSOLETA desde PHP 5.3.0 y ELIMINADA a partir de PHP 5.4.0.

--with-exec-dir[=DIR]

Solo permite ejecutables en DIR cuando safe mode está por defecto a /usr/local/php/bin.

Advertencia

Esta característica ha sido declarada OBSOLETA desde PHP 5.3.0 y ELIMINADA a partir de PHP 5.4.0.

--enable-magic-quotes

Habilita magic quotes por defecto.

Advertencia

Esta característica ha sido declarada OBSOLETA desde PHP 5.3.0 y ELIMINADA a partir de PHP 5.4.0.

--disable-short-tags

Deshabilita la forma corta de la etiqueta de inicio php <? por defecto.

--enable-zend-multibyte

Habilita código multibyte en el analizador y el escáner de lenguaje PHP para ser ejecutado. Cuando PHP se compila con esta opción, también habilita la directiva encoding en el constructor declare.

Advertencia

Esta característica ha sido declarada OBSOLETA desde PHP 5.3.0 y ELIMINADA a partir de PHP 5.4.0.

--with-libdir

Especifica el directorio en el que están las librerías para compilar PHP en un sistema Unix. Para sistemas de 64 bits, es necesario especificar este argumento para poder usar el directorio lib64: --with-libdir=lib64.

Opciones SAPI

La siguiente lista contiene los SAPI&s disponibles ( Server Application Programming Interface) para PHP.

--with-aolserver=DIR

Especifica la ruta donde está AOLserver.

--with-apxs[=FILE]

Crea un módulo compartido de Apache. FILE es la ruta opcional de la herramienta Apache apxs, por defecto a apxs. Asegúrese de especificar la versión de apxs que está instalada en su sistema y NO la que está en los fuentes de Apache.

--with-apache[=DIR]

Crea un módulo estático de Apache. DIR es el directorio de Apache, por defecto es /usr/local/apache.

--with-mod_charset

Habilita la tranferencia de tablas para mod_charset (Apache en Ruso).

--with-apxs2[=FILE]

Crea un módulo compartido de Apache 2.0. FILE es la ruta opcional a la herramienta apxs, por defecto a apxs.

--with-caudium=DIR

Crea PHP como un módulo Pike para ser usado con Caudium. DIR es el directorio del servidor Caudium, con el valor por defecto /usr/local/caudium/server.

--disable-cli

Deshabilita la versión CLI de PHP (esto fuerza--without-pear). Para mayor información, vea la sección acerca de Usando PHP desde la línea de comando.

--enable-phpdbg

Habilitar el soporte para el módulo SAPI de depuración interactiva phpdbg en PHP 5.6.x o superior.

--enable-embed[=TYPE]

Habilita la creación de la librería SAPI. TYPE es shared o static, el valor por defecto es shared.

--with-isapi=DIR

Crea PHP como un módulo ISAPI para ser usado con Zeus.

--with-nsapi=DIR

Especifica la ruta para el servidor web instalado Netscape/iPlanet/SunONE.

--with-phttpd=DIR

No hay información disponible.

--with-pi3web=DIR

Crea PHP como un módulo para ser usado con Pi3Web.

--with-roxen=DIR

Crea PHP como un módulo Pike. DIR es el directorio base de Roxen, normalmente /usr/local/roxen/server.

--enable-roxen-zts

Crea el modulo Roxen usando Zend Thread Safety..

--with-servlet[=DIR]

Incluye soporte para servlet. DIR es el directorio base de instalación de JSDK. Este SAPI requiere que la extensión de java sea creada como un dl compartido.

--with-thttpd=SRCDIR

Crea PHP como un modulo thttpd.

--with-tux=MODULEDIR

Crea PHP como un módulo TUX (solo Linux).

--with-webjames=SRCDIR

Crea PHP como un módulo WebJames (solo RISC OS).

--disable-cgi

Desabilita la versión CGI de la construcción de PHP.

Desde PHP 5.3.0 este argumento habilita FastCGI mientras que anteriormente se tenía que activar usando --enable-fastcgi.

--enable-force-cgi-redirect

Habilita el chequeo de seguridad para redirecciones internas del servidor. Debe usar esta opción si esta ejecutando la versión CGI con Apache.

Desde PHP 5.3.0 este argumento está habilitado por defecto y ya no existe. Para deshabilitarlo se debe definir la directiva ini cgi.force_redirect a 0.

--enable-discard-path

Si esta opción está habilitada, el binario CGI de PHP puede, de manera segura, ser puesto fuera de la trayectoria web y los usuarios no podrán evitar la seguridad de .htaccess.

Desde PHP 5.3.0 este argumento está deshabilitado por defecto y ya no existe. Para activar esta opción la directiva ini cgi.discard_path debe estar definida como 1.

--enable-fastcgi

Si esta opción está activada, el modulo CGI será construido también con soporte para FastCGI.

Desde PHP 5.3.0 este argumento ya no existe y debe ser habilitado usando --enable-cgi en su lugar.

--disable-path-info-check

Si esta opción esta deshabilitada, las rutas, tales como /info.php/test?a=b fallarán. Para mas información vea el » Manual de Apache.

A partir de PHP 5.3.0 este argumento está activado por defecto y ya no existe. Para desactivar esta característica la directiva ini cgi.fix_pathinfo debe establecerse a 0.

User Contributed Notes

atesin () gmail ! com 04-Feb-2021 08:55
i'll answer myself (FINALLY!)

current "configure options" can be viewed with "php-config" shell script, aside with other compile time options too =D!!! ...

in some distributions it comes with the "php-devel" package... but until in this online manual "php-config" is mentioned in pecl extensions documentation (i couldn't find on pecl site), idk if that "php-devel" has something to do with this

... however i noticed they are literal strings inside the script, i hope the script itself were built together with php compilation o_O

in the previous page "configure options" (link shown above ^), there is an editor note with additional info about it
atesin () gmail ! com 04-Feb-2021 02:38
please somebody tell me how to display configure options used in php actual binary

it was shown in phpinfo() some years before, it was very useful, specially with 'phpize' recompilation and to enable some pecl/pear module :/

please tell me also which ctriteria had php guys used to suddenly decided to hide (or obfuscate) this info :/

thanks in advance


Directivas de php.ini

Tabla de contenidos

  • Listado de directivas de php.ini
  • Lista de secciones de php.ini
  • Descripción de las directivas del núcleo de php.ini

User Contributed Notes

There are no user contributed notes for this page.


Listado de directivas de php.ini

Este listado incluye las directivas de php.ini que se pueden establecer para la configuración de PHP.

La columna "Cambiable" muestra los modos que determinan cuándo y dónde una directiva puede ser establecida. Véase la sección Valores de modo cambiable para sus definiciones.

Opciones de configuración
Nombre | Por defecto | Cambiable | Historial de cambios
allow_url_fopen | "1" | PHP_INI_SYSTEM |
allow_url_include | "0" | PHP_INI_SYSTEM | Obsoleta desde desde PHP 5.2.0.
arg_separator.input | "&" | PHP_INI_PERDIR |
arg_separator.output | "&" | PHP_INI_ALL |
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.exception | "0" | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
auto_append_file | NULL | PHP_INI_PERDIR |
auto_detect_line_endings | "0" | PHP_INI_ALL |
auto_globals_jit | "1" | PHP_INI_PERDIR | Disponible desde PHP 5.0.0.
auto_prepend_file | NULL | PHP_INI_PERDIR |
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 |
default_charset | "UTF-8" | PHP_INI_ALL | Predeterminado a "UTF-8".
default_mimetype | "text/html" | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
disable_classes | "" | php.ini only |
disable_functions | "" | php.ini only |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL | Disponible desde PHP 4.0.3.
docref_ext | "" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
doc_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM | Esta característica obsoleta será eliminada con certeza en el futuro.
enable_post_data_reading | On | PHP_INI_PERDIR |
engine | "1" | PHP_INI_ALL |
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
error_prepend_string | NULL | PHP_INI_ALL |
error_reporting | NULL | PHP_INI_ALL |
exit_on_timeout | "" | PHP_INI_ALL | Disponible desde PHP 5.3.0
expose_php | "1" | php.ini only |
extension | NULL | php.ini only |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM |
fastcgi.logging | "1" | PHP_INI_SYSTEM |
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM | Disponible desde PHP 4.2.0.
fbsql.autocommit | "1" | PHP_INI_SYSTEM | Disponible desde PHP 4.0.6.
fbsql.batchSize | "1000" | PHP_INI_SYSTEM |
fbsql.batchsize | "1000" | PHP_INI_ALL |
fbsql.default_database | "" | PHP_INI_SYSTEM |
fbsql.default_database_password | "" | PHP_INI_SYSTEM |
fbsql.default_host | NULL | PHP_INI_SYSTEM |
fbsql.default_password | "" | PHP_INI_SYSTEM |
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM |
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM |
fbsql.max_connections | "128" | PHP_INI_SYSTEM |
fbsql.max_links | "128" | PHP_INI_SYSTEM |
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM |
fbsql.max_results | "128" | PHP_INI_SYSTEM |
fbsql.show_timestamp_decimals | "0" | PHP_INI_SYSTEM | Disponible desde PHP 5.1.5.
file_uploads | "1" | PHP_INI_SYSTEM |
from | "" | PHP_INI_ALL |
hard_timeout | "2" | PHP_INI_SYSTEM | Available since 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 |
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_all_pconnect | "0" | PHP_INI_SYSTEM | Disponible desde ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Disponible desde ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Disponible desde ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Disponible desde ibm_db2 1.0.2.
ibm_db2.i5_ignore_userid | "0" | PHP_INI_SYSTEM | Disponible desde ibm_db2 1.8.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 |
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Disponible desde ingres 1.0.0
ingres.array_index_start | "1" | PHP_INI_ALL | Disponible desde ingres 1.4.0
ingres.auto | "1" | PHP_INI_ALL | Disponible desde ingres 2.0.0.
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Disponible desde ingres 1.2.0.
ingres.cursor_mode | "0" | PHP_INI_ALL | Disponible desde ingres 1.1.0.
ingres.default_database | NULL | PHP_INI_ALL | Disponible desde ingres 1.0.0
ingres.default_password | NULL | PHP_INI_ALL | Disponible desde ingres 1.0.0
ingres.default_user | NULL | PHP_INI_ALL | Disponible desde ingres 1.0.0
ingres.describe | 1 | PHP_INI_ALL | Disponible desde ingres 2.1.0
ingres.fetch_buffer_size | 100 | PHP_INI_ALL | Disponible desde ingres 2.1.0
ingres.max_links | "-1" | PHP_INI_SYSTEM | Disponible desde ingres 1.0.0
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Disponible desde ingres 1.0.0
ingres.reuse_connection | "1" | PHP_INI_ALL | Disponible desde ingres 2.0.0
ingres.scrollable | "1" | PHP_INI_ALL | Disponible desde ingres 2.0.0.
ingres.trace | "0" | PHP_INI_ALL | Disponible desde ingres 2.0.0.
ingres.trace_connect | "0" | PHP_INI_ALL | Disponible desde ingres 1.2.1.
ingres.utf8 | "1" | PHP_INI_ALL | Disponible desde ingres 2.0.0.
last_modified | "0" | PHP_INI_ALL |
intl.default_locale | "" | PHP_INI_ALL |
intl.error_level | "0" | PHP_INI_ALL |
intl.use_exceptions | "0" | PHP_INI_ALL |
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Disponible desde ingres 1.0.0
ingres.array_index_start | "1" | PHP_INI_ALL | Disponible desde ingres 1.4.0
ingres.auto | "1" | PHP_INI_ALL | Disponible desde ingres 2.0.0.
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Disponible desde ingres 1.2.0.
ingres.cursor_mode | "0" | PHP_INI_ALL | Disponible desde ingres 1.1.0.
ingres.default_database | NULL | PHP_INI_ALL | Disponible desde ingres 1.0.0
ingres.default_password | NULL | PHP_INI_ALL | Disponible desde ingres 1.0.0
ingres.default_user | NULL | PHP_INI_ALL | Disponible desde ingres 1.0.0
ingres.describe | 1 | PHP_INI_ALL | Disponible desde ingres 2.1.0
ingres.fetch_buffer_size | 100 | PHP_INI_ALL | Disponible desde ingres 2.1.0
ingres.max_links | "-1" | PHP_INI_SYSTEM | Disponible desde ingres 1.0.0
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Disponible desde ingres 1.0.0
ingres.reuse_connection | "1" | PHP_INI_ALL | Disponible desde ingres 2.0.0
ingres.scrollable | "1" | PHP_INI_ALL | Disponible desde ingres 2.0.0.
ingres.trace | "0" | PHP_INI_ALL | Disponible desde ingres 2.0.0.
ingres.trace_connect | "0" | PHP_INI_ALL | Disponible desde ingres 1.2.1.
ingres.utf8 | "1" | PHP_INI_ALL | Disponible desde ingres 2.0.0.
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL |
mail.add_x_header | "0" | PHP_INI_PERDIR |
mail.force_extra_parameters | NULL | php.ini only |
mail.log | "" | PHP_INI_PERDIR |
max_execution_time | "30" | PHP_INI_ALL |
max_input_nesting_level | "64" | PHP_INI_PERDIR |
max_input_vars | 1000 | PHP_INI_PERDIR | Disponible desde PHP 5.3.9.
max_input_time | "-1" | PHP_INI_PERDIR |
memory_limit | "128M" | PHP_INI_ALL |
mongo.allow_empty_keys | 0 | PHP_INI_ALL |
mongo.allow_persistent | 1 | PHP_INI_ALL | Eliminado en 1.2.0
mongo.chunk_size | 262144 | PHP_INI_ALL |
mongo.cmd | "$" | PHP_INI_ALL |
mongo.default_host | "localhost" | PHP_INI_ALL |
mongo.default_port | 27017 | PHP_INI_ALL |
mongo.is_master_interval | 15 | PHP_INI_ALL | Añadido en 1.2.10, antes de 1.3.0 el valor predeterminado era 60.
mongo.long_as_object | o | PHP_INI_ALL |
mongo.native_long | 1 | PHP_INI_ALL | Antes de la versión 1.5.0, el valor predeterminado era 0.
mongo.ping_interval | 5 | PHP_INI_ALL | Añadido en 1.2.10
mongo.utf8 | 1 | PHP_INI_ALL |
mysql.allow_local_infile | "1" | PHP_INI_SYSTEM |
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL | Disponible desde PHP 4.3.0.
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL | Disponible desde PHP 4.0.1.
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.connect_timeout | "60" | PHP_INI_ALL | PHP_INI_SYSTEM en PHP <= 4.3.2. Disponible desde PHP 4.3.0.
mysqli.allow_local_infile | "1" | PHP_INI_SYSTEM | Disponible desde PHP 5.2.4.
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM | Disponible desde PHP 5.3.0.
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM | Disponible desde PHP 5.3.0.
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Disponible desde PHP 5.0.0.
mysqli.default_port | "3306" | PHP_INI_ALL | Disponible desde PHP 5.0.0.
mysqli.default_socket | NULL | PHP_INI_ALL | Disponible desde PHP 5.0.0.
mysqli.default_host | NULL | PHP_INI_ALL | Disponible desde PHP 5.0.0.
mysqli.default_user | NULL | PHP_INI_ALL | Disponible desde PHP 5.0.0.
mysqli.default_pw | NULL | PHP_INI_ALL | Disponible desde PHP 5.0.0.
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Disponible desde PHP 4.3.5.
mysqli.rollback_on_cached_plink | TRUE | PHP_INI_SYSTEM | Disponible desde PHP 5.6.0.
mysqlnd_memcache.enable | 1 | PHP_INI_SYSTEM | Disponible desde 1.0.0
mysqlnd_ms.enable | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.force_config_usage | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.ini_file | "" | PHP_INI_SYSTEM |
mysqlnd_ms.config_file | "" | PHP_INI_SYSTEM |
mysqlnd_ms.collect_statistics | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.multi_master | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.disable_rw_split | 0 | PHP_INI_SYSTEM |
mysqlnd_mux.enable | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.enable_qc | 1 | PHP_INI_SYSTEM |
mysqlnd_qc.ttl | 30 | PHP_INI_ALL |
mysqlnd_qc.cache_by_default | 0 | PHP_INI_ALL |
mysqlnd_qc.cache_no_table | 0 | PHP_INI_ALL |
mysqlnd_qc.use_request_time | 0 | PHP_INI_ALL |
mysqlnd_qc.time_statistics | 1 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics | 0 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics_log_file | /tmp/mysqlnd_qc.stats | PHP_INI_SYSTEM |
mysqlnd_qc.collect_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.query_trace_bt_depth | 3 | PHP_INI_SYSTEM |
mysqlnd_qc.collect_normalized_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.ignore_sql_comments | 1 | PHP_INI_ALL |
mysqlnd_qc.slam_defense | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.slam_defense_ttl | 30 | PHP_INI_SYSTEM |
mysqlnd_qc.std_data_copy | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.apc_prefix | qc_ | PHP_INI_ALL |
mysqlnd_qc.memc_server | 127.0.0.1 | PHP_INI_ALL |
mysqlnd_qc.memc_port | 11211 | PHP_INI_ALL |
mysqlnd_qc.sqlite_data_file | :memory: | PHP_INI_ALL |
mysqlnd_uh.enable | 1 | PHP_INI_SYSTEM |
mysqlnd_uh.report_wrong_types | 1 | PHP_INI_ALL |
opcache.enable | "1" | PHP_INI_ALL |
opcache.enable_cli | "0" | PHP_INI_SYSTEM | Entre PHP 7.1.2 y 7.1.6 inclusive, el valor predetermindao era "1"
opcache.memory_consumption | "128" | PHP_INI_SYSTEM | Antes de PHP 7.0.0 el valor predeterminado era "64"
opcache.interned_strings_buffer | "8" | PHP_INI_SYSTEM | Antes de PHP 7.0.0 el valor predeterminado era "4"
opcache.max_accelerated_files | "10000" | PHP_INI_SYSTEM | Antes de PHP 7.0.0 el valor predeterminado era "2000"
opcache.max_wasted_percentage | "5" | PHP_INI_SYSTEM |
opcache.use_cwd | "1" | PHP_INI_SYSTEM |
opcache.validate_timestamps | "1" | PHP_INI_ALL |
opcache.revalidate_freq | "2" | PHP_INI_ALL |
opcache.revalidate_path | "0" | PHP_INI_ALL |
opcache.save_comments | "1" | PHP_INI_SYSTEM |
opcache.load_comments | "1" | PHP_INI_ALL | Eliminado en PHP 7.0.0.
opcache.fast_shutdown | "0" | PHP_INI_SYSTEM | Eliminado en PHP 7.2.0.
opcache.enable_file_override | "0" | PHP_INI_SYSTEM |
opcache.optimization_level | "0x7FFFBFFF" | PHP_INI_SYSTEM | Cambiado desde 0xFFFFFFFF en PHP 5.6.18
opcache.inherited_hack | "1" | PHP_INI_SYSTEM | Eliminado 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 |
opcache.force_restart_timeout | "180" | PHP_INI_SYSTEM |
opcache.error_log | "" | PHP_INI_SYSTEM |
opcache.log_verbosity_level | "1" | PHP_INI_SYSTEM |
opcache.preferred_memory_model | "" | PHP_INI_SYSTEM |
opcache.protect_memory | "0" | PHP_INI_SYSTEM |
opcache.mmap_base | null | PHP_INI_SYSTEM |
opcache.restrict_api | "" | PHP_INI_SYSTEM |
opcache.file_update_protection | "2" | PHP_INI_ALL |
opcache.huge_code_pages | "0" | PHP_INI_SYSTEM |
opcache.lockfile_path | "/tmp" | PHP_INI_SYSTEM |
opcache.opt_debug_level | "0" | PHP_INI_SYSTEM |
opcache.file_cache | NULL | PHP_INI_SYSTEM | Disponible a partir de PHP 7.0.0
opcache.file_cache_only | "0" | PHP_INI_SYSTEM | Disponible a partir de PHP 7.0.0
opcache.file_cache_consistency_checks | "1" | PHP_INI_SYSTEM | Disponible a partir de PHP 7.0.0
opcache.file_cache_fallback | "1" | PHP_INI_SYSTEM | Solo Windows. Disponible a partir de PHP 7.0.0
opcache.validate_permission | "0" | PHP_INI_SYSTEM | Disponible a partir de PHP 7.0.14
opcache.validate_root | "0" | PHP_INI_SYSTEM | Disponible a partir de PHP 7.0.14
opcache.preload | "" | PHP_INI_SYSTEM | Disponible a partir de PHP 7.4.0
opcache.preload_user | "" | PHP_INI_SYSTEM | Disponible a partir de PHP 7.4.0
open_basedir | NULL | PHP_INI_ALL |
oracle.allow_persistent | "-1" | PHP_INI_ALL |
oracle.max_links | "-1" | PHP_INI_ALL |
oracle.max_persistent | "-1" | PHP_INI_ALL |
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR |
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 |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | "/usr/sbin/sendmail -t -i" | PHP_INI_SYSTEM |
serialize_precision | "-1" | PHP_INI_ALL | Hasta PHP 7.1.0, el valor predeterminado era 17.
short_open_tag | "1" | PHP_INI_PERDIR |
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL |
sql.safe_mode | "0" | PHP_INI_SYSTEM |
syslog.facility | "LOG_USER" | PHP_INI_SYSTEM | Disponible desde PHP 7.3.0.
syslog.filter | "no-ctrl" | PHP_INI_ALL | Disponible desde PHP 7.3.0.
syslog.ident | "php" | PHP_INI_SYSTEM | Disponible desde PHP 7.3.0.
sys_temp_dir | "" | PHP_INI_SYSTEM |
track_errors | "0" | PHP_INI_ALL | Obsoleta desde PHP 7.2.0.
unserialize_callback_func | NULL | PHP_INI_ALL | Disponible desde PHP 4.2.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 | Available as of uopz 5.0.2
uopz.exit | "0" | PHP_INI_SYSTEM | Available as of uopz 6.0.1
uopz.overloads | "1" | PHP_INI_SYSTEM | Available as of uopz 2.0.2. Removed as of uopz 5.0.0.
variables_order | "EGPCS" | PHP_INI_PERDIR |
vld.active | "0" | PHP_INI_SYSTEM |
vld.execute | "1" | PHP_INI_SYSTEM | Disponible desde vld 0.8.0.
vld.skip_append | "0" | PHP_INI_SYSTEM | Disponible desde vld 0.8.0.
vld.skip_prepend | "0" | PHP_INI_SYSTEM | Disponible desde vld 0.8.0.
windows.show_crt_warning | "0" | PHP_INI_ALL |
xbithack | "0" | PHP_INI_ALL |
xmlrpc_errors | "0" | PHP_INI_SYSTEM |
xmlrpc_error_number | "0" | PHP_INI_ALL |
yaz.keepalive | "120" | PHP_INI_ALL |
yaz.log_mask | NULL | PHP_INI_ALL | Disponible desde 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 | Solamente en php.ini |

User Contributed Notes

There are no user contributed notes for this page.


Lista de secciones de php.ini

Esta lista incluye las secciones de php.ini que se pueden establecer para configurar los ajustes de PHP según cada servidor o ruta. Estas secciones son opcionales.

Estas secciones no afectan directamente a PHP. Se utilizan para agrupar otras directivas de php.ini y hacerlas funcionar para un servidor o ruta determinados.

Estas secciones solo se utilizan en modo CGI/FastCGI y no pueden configurar directivas de extensión ni de zend_extension.

Secciones
Nombre | Cambiable | Historial de cambios
[HOST=] | PHP_INI_SYSTEM | Añadida en PHP 5.3.0.
[PATH=] | PHP_INI_SYSTEM | Añadida en PHP 5.3.0.

He aquí una breve explicación de las directivas de configuración.

[HOST=<host>]

Esta sección permite definir un conjunto de directivas de php.ini que afectarán solamente al servidor designado.

Ejemplo #1 Activar la notificación completa de errores por pantalla para el dominio dev.

[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On

[PATH=<path>]

Esta sección permite definir un conjunto de directivas de php.ini que tomarán efecto al ejecutar un script en la ruta designada.

Ejemplo #2 Añadir un script de seguridad para aréas protegidas

[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).


Descripción de las directivas del núcleo de php.ini

Esta lista incluye las directivas del núcleo de php.ini que se pueden establecer para la configuración de PHP. Las directivas manejadas por extensiones están enumeradas y detalladas en las respectivas páginas de la documentación de cada extensión. La información sobre las directivas de sesión, por ejemplo, se puede encontrar en la página de sesiones.

Nota:

Las opciones predeterminadas enumeradas aquí se usan cuando php.ini no está cargado; los valores para el php.ini de producción y desarrollo podrían variar.

Opciones del lenguaje

Opciones del lenguaje y configuración variada
Nombre | Por defecto | Cambiable | Historial de cambios
short_open_tag | "1" | PHP_INI_PERDIR |
asp_tags | "0" | PHP_INI_PERDIR | Eliminada in PHP 7.0.0.
precision | "14" | PHP_INI_ALL |
serialize_precision | "-1" | PHP_INI_ALL | Hasta PHP 5.3.5, el valor predeterminado era 100. Antes de PHP 7.1.0, el valor predeterminado era 17.
y2k_compliance | "1" | PHP_INI_ALL | Eliminado en PHP 5.4.0.
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | Eliminada en PHP 5.4.0.
disable_functions | "" | Sólo en PHP_INI_SYSTEM |
disable_classes | "" | Sólo en php.ini |
exit_on_timeout | "" | INI_ALL | Disponible desde PHP 5.3.0.
expose_php | "1" | Sólo en php.ini |
hard_timeout | "2" | PHP_INI_SYSTEM | Disponible desde PHP 7.1.0.
zend.exception_ignore_args | "0" | PHP_INI_ALL | Disponible desde PHP 7.4.0
zend.multibyte | "0" | PHP_INI_ALL | Disponible desde PHP 5.4.0
zend.script_encoding | NULL | PHP_INI_ALL | Disponible desde PHP 5.4.0
zend.detect-unicode | NULL | PHP_INI_ALL | Disponible desde PHP 5.4.0
zend.signal_check | "0" | PHP_INI_SYSTEM | Disponible desde PHP 5.4.0
zend.assertions | "1" | PHP_INI_ALL con restricciones | Disponible desde PHP 7.0.0.
detect_unicode | "1" | PHP_INI_ALL | Disponible desde PHP 5.1.0. Renombrada a zend.detect-unicode desde PHP 5.4.0.

He aquí una breve explicación de las directivas de configuración.

short_open_tag boolean

Indica a PHP si debería permitirse la forma abreviada de las etiquetas de apertura de PHP (<? ?>). Si se quiere utilizar PHP junto con XML, se puede desactivar esta opción para poder usar <?xml ?> en línea. Si no, puede imprimirse con PHP, por ejemplo: <?php echo '<?xml version="1.0"?>'; ?>. Además, si está desactivada, se debe usar siempre la forma no abreviada de la etiqueta de apertura de PHP (<?php ?>).

Nota:

Esta directiva también afecta a la abreviatura <?= en versiones anteriores a PHP 5.4.0, la cual es lo mismo que <? echo. El uso de esta abreviatura requería que short_open_tag estuviese activada. Desde PHP 5.4.0, <?= siempre está disponible.

asp_tags boolean
Activa el uso de las etiquetas estilo ASP (<% %>) además de las normales (<?php ?>). Esto incluye la abreviatura de variable-valor <%= $valor %>. Para más información, véase Salir de HTML.

Registro de cambios para asp_tags
Versión | Descripción
7.0.0 | Eliminada de PHP.

precision integer
El número de dígitos significativos que se muestran en números de punto flotante. -1 significa que se utilizará el algoritmo mejorado para redondear dichos números.
serialize_precision integer
El número de dígitos significativos almacenados durante la serialización de números de punto flotante. -1 significa que se utilizará el algoritmo mejorado para redondear dichos números.
y2k_compliance boolean
Asegura la compatibilidad con el año 2000 (causará problemas con navegadores no compatibles)
allow_call_time_pass_reference boolean

Sirve para avisar cuándo los argumentos son pasados por referencia al llamar a una función. El método recomendado para especificar los argumentos que deberían parsarse por referencia es en la declaración de la función. Se anima a probar y desactivar esta opción para asegurarse de que los scripts funcionen adecuadamente también en futuras versiones del lenguaje (si está característica está desactivada, se mostrará una advertencia cada vez que se utilice).

El paso de argumentos por referencia en el momento de llamar a una función quedó obsoleto por razones de limpieza en el código. Una función puede modificar sus argumentos de una manera no documentada si no declaró que dichos argumentos deberían ser pasados por referencia. Para evitar efectos secundarios, es mejor especificar qué argumentos son pasados por referencia solamente en la declaración de la función.

Véase también Explicación de las referencias.

Registro de cambios de allow_call_time_pass_reference
Versión | Descripción
5.4.0 | Eliminada de PHP.
5.3.0 | Emite un error de nivel E_DEPRECATED.
5.0.0 | Obsoleta, y genera un error de nivel E_COMPILE_WARNING.

expose_php boolean

Expone al mundo que PHP está instalado en el servidor, lo que incluye la versión de PHP en la cabecera HTTP (p.ej., X-Powered-By: PHP/5.3.7). Antes de PHP 5.5.0, los GUIDs del logotipo de PHP también eran expuestos, por lo que al añadirlos a la URL de un script de PHP, se mostraba el logotipo correspondiente (p.ej., » https://www.php.net/?=PHPE9568F34-D428-11d2-A769-00AA001ACF42). Esto también afectaba a la salida de phpinfo(), ya que cuando estaba desactivada, no se mostraban el logotipo de PHP y la información de los créditos.

Nota:

Desde PHP 5.5.0, estos GUIDs y la función php_logo_guid() han sido eliminados de PHP, y los GUIDs han sido reemplazados en su lugar con URIs de datos. Por lo tanto, ya no funciona el acceso al logotipo de PHP mediante la adición del GUID a la URL. Similarmente, desactivar expose_php no afectará a la visualización del logotipo de PHP en phpinfo().

Véase también php_logo_guid() y phpcredits().

disable_functions string

Esta directiva permite desactivar ciertas funciones por razones de seguridad. Requiere una lista con los nombres de las funciones delimitados por comas.

Solamente las funciones internas pueden ser desactivadas usando esta directiva. Las funciones definidas por el usuario no se ven afectadas.

Esta directiva debe ser establecida en el fichero php.ini. Por ejemplo, no puede establecerse en httpd.conf.

disable_classes string
Esta directiva permite desactivar ciertas clases por razones de seguridad. Requiere una lista con los nombres de las clases delimitados por comas. Esta directiva debe ser establecida en el fichero php.ini. Por ejemplo, no puede establecerse en httpd.conf.
zend.assertions integer
Cuando se establece a 1, se generará y se ejecutará código de afirmaciones (modo desarrollo). Si se establece a 0, el código de afirmaciones se generará aunque será saltado (no ejecutado) durante la ejecución. Cuando se establece a -1, el código de afirmaciones no se generará, haciendo que las afirmaciones tengan un coste de cero (modo producción).

Nota:

Si un proceso se inicia en modo de producción, zend.assertions no podrá ser cambiado durante la ejecución, ya que no se generó el código para las afirmaciones.

Si un proceso se inicia en modo desarrollo, zend.assertions no podrá ser establecido a -1 durante la ejecución.

hard_timeout int

zend.exception_ignore_args bool

Excluye argumentos del stack trace generados a partir de excepciones.

zend.multibyte bool

Permite analizar los ficheros fuentes con codificación multibyte. Se requiere habilitar zend.multibyte para utilizar codificaciones de caracteres como SJIS, BIG5, etc que contienen caracteres especiales en datos de cadenas multibyte. Las codificaciones compatibles con ISO-8859-1 como UTF-8, EUC, etc no requieren esta opción.

Enabling zend.multibyte requires the mbstring extension to be available.

zend.script_encoding string

Este valor será usado a menos que una directiva declare(encoding=...) aparezca al principio del script. Cuando se emplea una codificación incompatible con ISO-8859-1, se deben utilizar zend.multibyte y zend.script_encoding.

Los string literales se transliterarán de zend.script_enconding a mbstring.internal_encoding, como si mb_convert_encoding() hubiera sido llamada.

zend.detect_unicode boolean

Comprobar la marca BOM (Byte Order Mark) y verificar si el fichero contiene caracteres multibyte válidos. Esta detección se realiza antes de procesar __halt_compiler(). Disponible solamente en modo Zend Multibyte.

zend.signal_check boolean

Para verficar gestores de señales reemplazados en el apagado.

exit_on_timeout boolean

Esta es una directiva mod_php-only de Apache1 que fuerza a un subproceso de Apache a salir si expiró el tiempo de ejecución de PHP. Este tiempo de espera provoca una llamada interna a longjmp() en Apache1, que puede dejar algunas extensiones en un estado de incoherencia. Al terminar el proceso, será limpiado cualquier bloqueo pendiente o la memoria.

Límite de recursos

Límite de recursos
Nombre | Por defecto | Cambiable | Historial de cambios
memory_limit | "128M" | PHP_INI_ALL | "8M" antes de PHP 5.2.0, "16M" en PHP 5.2.0

He aquí una breve explicación de las directivas de configuración.

memory_limit integer

Establece el máximo de memoria en bytes que un script puede consumir. Ayuda a prevenir que scripts mal programados consuman toda la memoria disponible en el servidor. Observe que para no tener límite de memoria, se ha de establecer esta directiva a -1.

En versiones anteriores a PHP 5.2.1, esta directiva tenía que estar habilitada en tiempo de compilación usando --enable-memory-limit en la línea de configuración. Esta bandera en tiempo de compilación también se requería para definir las funciones memory_get_usage() y memory_get_peak_usage() en versiones anteriores a PHP 5.2.1.

Cuando se usa un integer, el valor del mismo es medido en bytes. También se puede usar la notación reducida, tal como se describe en esta FAQ.

Véase también: max_execution_time.

Ajuste del rendimiento

Ajuste del rendimiento
Nombre | Por defecto | Cambiable | Historial de cambios
realpath_cache_size | "16K" | PHP_INI_SYSTEM | Disponible desde PHP 5.1.0.
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Disponible desde PHP 5.1.0.

He aquí una breve explicación de las directivas de configuración.

realpath_cache_size integer

Determina el tamaño de la caché de realpath que va a ser usada por PHP. Este valor debe ser incrementado en sistemas donde PHP abra muchos ficheros, para reflejar la cantidad de operaciones realizadas con ficheros.

El tamaño representa el número total de bytes de los strings de rutas almacenadas, más el tamaño de los datos asociados con la entrada de la caché. Esto significa que para poder almacenar rutas mayores en la caché, el tamaño de esta debe ser mayor. Este valor no controla directamente el número de rutas distintas que pueden ser almacenadas en caché.

El tamaño requerido para los datos de entrada de la caché depende del sistema.

realpath_cache_ttl integer

Tiempo (en segundos) durante el cual almacenar en caché información de realpath para un determinado fichero o directorio. Para sistemas que raramente cambian ficheros, considere incrementar este valor.

Manejo de datos

Opciones de configuración de manejo de datos
Nombre | Por defecto | Cambiable | Historial de cambios
arg_separator.output | "&" | PHP_INI_ALL |
arg_separator.input | "&" | PHP_INI_PERDIR |
variables_order | "EGPCS" | PHP_INI_PERDIR | PHP_INI_ALL en PHP <= 5.0.5.
request_order | "" | PHP_INI_PERDIR | Disponible desde PHP 5.3.0
auto_globals_jit | "1" | PHP_INI_PERDIR |
register_argc_argv | "1" | PHP_INI_PERDIR |
register_long_arrays | "1" | PHP_INI_PERDIR | Obsoleta en PHP 5.3.0. Eliminada en PHP 5.4.0.
enable_post_data_reading | "1" | PHP_INI_PERDIR | Disponible desde PHP 5.4.0
post_max_size | "8M" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
auto_append_file | NULL | PHP_INI_PERDIR |
default_mimetype | "text/html" | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL | Se predetermina a "UTF-8" desde PHP >= 5.6.0, vacío para PHP < 5.6.0.
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | Eliminada en PHP 7.0.0.

He aquí una breve explicación de las directivas de configuración.

arg_separator.output string

El separador usado en PHP para distinguir argumentos en las URLs generadas.

arg_separator.input string

Lista de separadores empleados por PHP para convertir datos de URLs en variables.

Nota:

Cada carácter de esta directiva es considerado un separador.

variables_order string

Establece el orden de interpretación de variables EGPCS (Entorno, Get, Post, Cookie, y Servidor). Por ejemplo, si variables_order es "SP", PHP creará las superglobals $_SERVER y $_POST, pero no creará $_ENV, $_GET, y $_COOKIE. Si se establece a "", las variables superglobals no estarán disponibles.

Advertencia

En ambas SAPIs, CGI y FastCGI, $_SERVER también es rellenada con los valores de entorno; S siempre es equivalente a ES independientemente de la posición de E en esta directiva.

Nota:

El contenido y el orden de $_REQUEST también se ve afectado por esta directiva.

request_order string

Esta directiva describe el orden en que PHP registra las variables GET, POST y Cookie en el array _REQUEST. El registro se hace de izquierda a derecha; los nuevos valores reemplazan los valores más antiguos.

Si esta directiva no está definida, variables_order se usa para el contenido de $_REQUEST.

Observe que la distribución predeterminada de los ficheros php.ini no contienen 'C' para cookies, por motivos de seguridad.

auto_globals_jit boolean

Cuando está activada, las variables SERVER y EVN son creadas la primera vez que se necesitan ("Just In Time") en lugar de hacerlo cuando el script se inicia. Si estas variables no son usadas en un script, el tener esta directiva activada resultará en una mejora del rendimiento.

Advertencia

El uso de las variables SERVER y ENV se comprueba durante el tiempo de compilación, por lo que utilizarlas a través de, por ejemplo, variables variables no causará su inicialización.

register_argc_argv boolean
Indica a PHP si debe declarar las variables argv y argc (que pueden que contengan la información de GET). Véase también la línea de comandos.
register_long_arrays boolean
Indica a PHP si registrar o no las obsoletas variables predefinidas del tipo $HTTP_*_VARS. Cuando esté activada (predeterminado), las variables largas predefinidas de PHP, como $HTTP_GET_VARS, estarán definidas. Si no se utilizan, se recomienda desactivarlas por razones de rendimiento. En su lugar, use los arrays superglobales, como $_GET. Esta directiva empezó a estar disponible en PHP 5.0.0.
Advertencia

Esta característica ha sido declarada OBSOLETA desde PHP 5.3.0. Su uso está totalmente desaconsejado.

enable_post_data_reading boolean
Al deshabilitar esta opción hace que $_POST y $_FILES no sean rellenados. La única manera de leer datos de POST será a través de la envoltura de flujo php://input. Esto puede ser útil en peticiones de proxys o para procesar los datos de POST de una manera efeciente en cuestión de memoria.
post_max_size integer
Define el tamaño máximo de datos de POST permitidos. Esta opción también afecta a la subida de ficheros. Para subir ficheros grandes, este valor debe ser mayor que upload_max_filesize. Por norma general, memory_limit debe ser mayor que post_max_size. Cuando se usa un integer, el valor del mismo es medido en bytes. También se puede usar la notación reducida, tal como se describe en esta FAQ. Si el tamaño de los datos de POST es mayor que post_max_size, las superglobales $_POST y $_FILES estarán vacías. Esto se puede rastrear de varias maneras, por ejemplo, pasando la variable $_GET al script que procesa los datos, esto es, <form action="edit.php?procesado=1">, y luego comprobar si la variable $_GET['procesado'] existe.

Nota:

PHP acepta abreviaturas para valores de byte, incluyendo K (kilo), M (mega) y G (giga). PHP hará las conversión automaticamente si utiliza cualesquiera de estas abreviaturas. Tenga cuidado de no execeder el límite de los enteros con signo de 32 bits (si está usando veriones de 32 bits), puesto que hará que el script falle.

Registro de cambios para post_max_size
Versión | Descripción
5.3.4 | post_max_size = 0 no deshabilitará el límite cuando el tipo de contenido sea application/x-www-form-urlencoded o no esté registrado en PHP.
5.3.2 , 5.2.12 | Permitir un tamaño de post ilimitado estableciendo post_max_size a 0.

auto_prepend_file string

Especifica el nombre del fichero que será analizado automáticamente antes del fichero principal. El fichero es incluido como si fuera llamado con la función require, por lo que se usa include_path.

El valor especial none desactiva esta directiva.

auto_append_file string

Especifica el nombre del fichero que será analizado automaticamente después del fichero principal. El fichero es incluido como si fuera llamado con la función require, por que se utiliza include_path.

El valor especial none desactiva el esta directiva.

Nota: Si el script finaliza con exit(), está funcionalidad no será llevada a cabo.

default_mimetype string

Por defecto, PHP generará un tipo de medio empleando la cabecera Content-Type. Para deshabilitarlo, simplemente se ha de establecer a vacía.

El tipo de medio predeterminado interno de PHP está establecido a text/html.

default_charset string

A partir de PHP 5.6, "UTF-8" es el valor predeterminado empleándose su valor como la codificación de caracterse predeterminada para htmlentities(), html_entity_decode() y htmlspecialchars() si se omite el parámetro encoding. El valor de default_charset también se empleará para establecer el conjunto de caracteres predeterminado para las funciones de iconv si las opciones de configuración iconv.input_encoding, iconv.output_encoding y iconv.internal_encoding están desestablecidas, y para las funciones de mbstring si las opciones de configuración mbstring.http_input mbstring.http_output mbstring.internal_encoding están desestablecidas.

Todas las versiones de PHP utilizarán este valor como el conjunto de caracteres dentro de la cabecera Content-Type predeterminada enviada por PHP si la cabecera no ha sido sobrescrita por una llamada a header().

No se recomienda establecer default_charset a un valor vacío.

input_encoding string

Disponible desde PHP 5.6.0. Este ajuste se usa para módulos multibyte comos mbstring e iconv. El valor predeterminado es vacío.

output_encoding string

Disponible desde PHP 5.6.0. Este ajuste se usa para módulos multibyte comos mbstring e iconv. El valor predeterminado es vacío.

internal_encoding string

Disponible desde PHP 5.6.0. Este ajuste se usa para módulos multibyte comos mbstring e iconv. El valor predeterminado es vacío. Si está vacío, se usará default_charset.

always_populate_raw_post_data mixed
Advertencia

Esta característica fue declarada OBSOLETA en PHP 5.6.0 y ELILMINADA a partir de PHP 7.0.0.

Si se establece a true, PHP rellenará siempre $HTTP_RAW_POST_DATA que contiene los datos POST sin tratar. De lo contrario, la variable se rellena solamente cuando el tipo MIME de los datos es irreconocible.

El método preferido para acceder a los datos POST sin tratar es php://input, ya que $HTTP_RAW_POST_DATA está obsoleta a partir de PHP 5.6.0. Al establecer always_populate_raw_post_data a -1 se optará por el nuevo comportamiento que será implementado en una futura versión de, donde $HTTP_RAW_POST_DATA nunca está definida.

Independientemente del ajuste, $HTTP_RAW_POST_DATA no está disponible con enctype="multipart/form-data".

Véase también: magic_quotes_gpc, magic_quotes_runtime, y magic_quotes_sybase.

Rutas y directorios

Opciones de configuración de rutas y directorios
Nombre | Por defecto | Cambiable | Historial de cambios
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
open_basedir | NULL | PHP_INI_ALL | PHP_INI_SYSTEM en PHP < 5.3.0
doc_root | NULL | PHP_INI_SYSTEM |
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM |
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
extension | NULL | Solamente en php.ini |
zend_extension | NULL | Solamente en php.ini |
zend_extension_debug | NULL | Solamente en php.ini | Disponible antes de PHP 5.3.0.
zend_extension_debug_ts | NULL | Solamente en php.ini | Disponible antes de PHP 5.3.0.
zend_extension_ts | NULL | Solamente en php.ini | Disponible antes de PHP 5.3.0.
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM | Disponible desde PHP 5.2.0.
cgi.discard_path | "0" | PHP_INI_SYSTEM | Disponible desde PHP 5.3.0.
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM | PHP_INI_ALL antes de PHP 5.2.1.
cgi.force_redirect | "1" | PHP_INI_SYSTEM | PHP_INI_ALL antes de PHP 5.2.1.
cgi.nph | "0" | PHP_INI_SYSTEM | Disponible desde PHP 5.3.0.
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM | PHP_INI_ALL antes de PHP 5.2.1.
cgi.rfc2616_headers | "0" | PHP_INI_ALL |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM | PHP_INI_ALL antes de PHP 5.2.1.
fastcgi.logging | "1" | PHP_INI_SYSTEM | PHP_INI_ALL antes de PHP 5.2.1.

He aquí una breve explicación de las directivas de configuración.

include_path string

Especifica la lista de directorios donde las funciones require, include, fopen(), file(), readfile() y file_get_contents() buscarán ficheros. El formato es como la variable de entorno PATH del sistema: una lista de directorios separados por dos puntos en Unix o separados por punto y coma en Windows.

PHP considera cada entrada de la ruta de inclusión por separado cuando está buscando ficheros a incluir. Primero buscará en la primera ruta, y si no lo encuentra ahí, buscará en la siguiente, hasta que encuentre el fichero incluido, o devuelva una advertencia o un error. Se puede modificar o establecer una ruta de incluición propia en tiempo de ejecucción usando set_include_path().

Ejemplo #1 include_path en Unix

include_path=".:/php/includes"

Ejemplo #2 include_path en Windows

include_path=".;c:\php\includes"

El uso de . en la ruta de inclusión permite el uso de inclusiones relativas, ya que significa el directorio actual. Sin embargo, es más eficiente usar explícitamente include './fichero' que hacer que PHP compruebe siempre el directorio actual para cada inclusión.

Nota:

Las variables ENV también son accesibles en ficheros .ini. Por lo tanto, es posible hacer referencia al directorio raíz utilizando ${LOGIN} y ${USER}.

Las variables de entorno podrían variar entre APIs de servidores, ya que sus entornos pueden ser diferentes.

Ejemplo #3 include_path en Unix usando la variable de entorno ${USER}

include_path = ".:${USER}/pear/php"

open_basedir string

El límite de los ficheros a los que PHP puede acceder en el árbol de directorios especificado, incluyendo el fichero en sí. Esta directiva NO se ve afectada si el Modo Seguro está activado (On) o desactivado (Off).

Cuando un script intenta acceder al sistema de ficheros, por ejemplo, usando include, o fopen(), se comprueba la ubicación del fichero. Cuando el fichero está fuera del árbol de directorio especificado, PHP rechazará acceder a él. Todos los enlaces simbólicos se resuelven, por lo que no es posible evitar esta restricción con un enlace simbólico. Si el fichero no existe, el enlace simbólico no podría ser resuelto, por lo que el nombre de fichero se compara con (uno resuelto) open_basedir.

open_basedir puede afectar no sólo a las funciones del sistema de ficheros; por ejemplo, si MySQL está configurado para usar los controladores de mysqlnd, LOAD DATA INFILE se verá afectado por open_basedir. Mucha de la funcionalidad ampliada de PHP usa open_basedir de esta manera.

El valor especial . indica que el directorio de trabajo del script será usado como directorio base. Esto es, sin embargo, un poco peligroso, ya que el directorio de trabajo del script puede ser fácilmente cambiado con la función chdir().

En httpd.conf, se puede desactivar open_basedir (p.ej. para algunos servidores virtuales) de la misma manera que cualquier otra directiva de configuración con "php_admin_value open_basedir none".

Bajo Windows, los directorios se han de separar con punto y coma. En cualquier otro sistema, se ha de hacer con dos puntos. Como módulo de Apache, las rutas de open_basedir de los directorios superiores se heredan automáticamente.

La restricción especificada en open_basedir es un nombre de directorio desde PHP 5.2.16 y 5.3.4. Las versiones anteriores lo usaban como un prefijo. Esto quiere decir que "open_basedir = /dir/incl" también tiene acceso a "/dir/include" y "/dir/incls, si existen. Cuando se quiera restringir el acceso solamente a un directorio específico, se ha de finalizar con una barra. Por ejemplo: open_basedir = /dir/incl/

El valor predeterminado permite abrir cualquier fichero.

Nota:

A partir de PHP 5.3.0, open_basedir puede usarse en tiempo de ejecución. Esto significa que si open_basedir está establecido como /www/ en php.ini, un script puede reforzar la configuración a /www/tmp/ en tiempo de ejecución con ini_set(). Cuando se enumeran varios directorios, se puede usar la constante PATH_SEPARATOR como separador, independientemente del sistema operativo.

doc_root string

El "directorio raíz" de PHP en el servidor. Solamente usada si no está vacía. Si PHP no se compiló con FORCE_REDIRECT, debería establecerse doc_root si se está usando PHP como CGI bajo cualquier tipo de servidor (que no sea IIS). La alternativa es usar la configuación de cgi.force_redirect de más abajo.

user_ini.cache_ttl int

user_ini.filename string

user_dir string

El nombre base del directorio usado en un directorio principal de usuario para ficheros PHP, por ejemplo public_html .

extension_dir string

En qué directorio debería buscar PHP extensiones que se pueden cargar dinámicamente. Véase también: enable_dl, y dl().

extension string

Qué extensiones se cargarán dinámicamente cuando se inicie PHP.

zend_extension string

El nombre de la extensión Zend cargable dinámicamente (por ejemplo XDebug) cuando se inicie PHP.

zend_extension_debug string

Variante de zend_extension para extensiones compiladas con información de depuración antes de PHP 5.3.0.

zend_extension_debug_ts string

Variante de zend_extension para extensiones compiladas con información de depuración y subprocesamiento seguro antes de PHP 5.3.0.

zend_extension_ts string

Variante de zend_extension para extensiones compiladas con subprocesamiento seguro antes de PHP 5.3.0.

cgi.check_shebang_line boolean

Controla si PHP en modo CGI comprueba líneas que empiezan por #! (shebang) en el inicio del script que se está ejecutando. Esta línea podría ser necesaria si el script admite su ejecución tanto como un script independiente como mediante el modo CGI de PHP. El modo CGI de PHP omite esta línea e ignora su contenido si esta directiva si está activada.

cgi.discard_path boolean

Si está habilitado, el binario de CGI de PHP puede ser colocado sin riesgo fuera del árbol web, no siendo posible así eludir la seguridad de .htaccess.

cgi.fix_pathinfo boolean

Proporciona soporte real de PATH_INFO / PATH_TRANSLATED para CGI. El comportamiento anterior de PHP era establecer PATH_TRANSLATED a SCRIPT_FILENAME, por lo que no comprendía lo que era PATH_INFO. Para más información sobre PATH_INFO, véanse las especificaciones de CGI. Si se establece el valor de esta directiva a 1, el modo CGI de PHP corregirá sus rutas conforme a las especificaciones. Si se establece a cero, funcionará como anteriormente. Esta directiva está activada de forma predeterminada. Debería corregir sus scripts para que utilicen SCRIPT_FILENAME en lugar de PATH_TRANSLATED.

cgi.force_redirect boolean

cgi.force_redirect es necesario para proporcionar seguridad al ejecutar PHP como CGI bajo la mayoría de servidores web. Si no se define, PHP activa esta directiva de forma predeterminada. Puede desactivarla bajo su propia responsabilidad.

Nota:

Para usuarios de Windows: Al usar IIS, esta ocpción debe estar desactivada. Para OmniHTTPD o Xitami se aplica lo mismo.

cgi.nph boolean

Si cgi.nph está habilitado, forzará a que cgi siempre envíe Status: 200 en cada petidión.

cgi.redirect_status_env string

Si cgi.force_redirect está activada, y no se están usando servidores web Apache o Netscape (iPlanet), podría ser necesario establecer el nombre de una variable de entorno que PHP buscará para saber que se puede continuar con la ejecucción.

Nota:

Establecer esta variable podría causar problemas de seguridad, no la cambie a no ser que sepa lo que está haciendo.

cgi.rfc2616_headers int

Le indica a PHP qué tipo de encabezados usar cuando envía el código de respuesta HTTP. Si está establecida a 0, PHP envía una cabecera "Status:" » RFC 3875 la cual es admitida por Apache y otros servidores web. Cuando esta opción está establecida a 1, PHP enviará encabezados compatibles con la » RFC 2616.

Si esta opción está habiltada, y está ejecutándose PHP en un entorno CGI (p.ej. PHP-FPM) no se deberían usar las cabeceras de respuesta de estado HTTP estilo estándar RFC 2616, se debería usar en su lugar sus equivalentes RFC 3875, p.ej., en lugar de header("HTTP/1.0 404 Not found"); se debería usar header("Status: 404 Not Found");

Déjelo establecido a 0 a menos que sepa lo que está haciendo.

fastcgi.impersonate string

FastCGI bajo IIS (en SO basados en WINNT) admite la capacidad de imitar tokens de seguridad del cliente que llama. Esto permite a IIS definir el contexto de seguridad en el que la petición se ejecuta. mod_fastgci bajo Apache actualmente no admite esta característica (17/03/2002). Establézcalo a 1 si usa IIS. El valor predeterminado es cero.

fastcgi.logging boolean

Activa la identificación de la SAPI cuando se usa FastCGI. El valor predeterminado es habilitar la identificación.

Subida de ficheros

Opciones de configuración de subida de ficheros
Nombre | Por defecto | Cambiable | Historial de cambios
file_uploads | "1" | PHP_INI_SYSTEM | PHP_INI_ALL en PHP <= 4.2.3. Disponible desde PHP 4.0.3.
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
max_input_nesting_level | 64 | PHP_INI_PERDIR | Disponible desde PHP 5.3.9.
max_input_vars | 1000 | PHP_INI_PERDIR | Disponible desde PHP 5.3.9.
upload_max_filesize | "2M" | PHP_INI_PERDIR | PHP_INI_ALL en PHP <= 4.2.3.
max_file_uploads | 20 | PHP_INI_SYSTEM | Disponible desde PHP 5.2.12.

He aquí una breve explicación de las directivas de configuración.

file_uploads boolean

Si permitir o no la subida de ficheros mediante HTTP. Véanse también las directivas upload_max_filesize, upload_tmp_dir, y post_max_size.

upload_tmp_dir string

El directorio temporal usado para almacenar ficheros durante el proceso de subida. Es necesario tener permisos de escritura para el usuario que está ejecutando PHP. Si no está especificado, PHP usará el predeterminado del sistema.

Si el directorio especificado no tiene permisos de escritura, PHP recurrirá al directorio temporal predeterminado del sistema. Si la directiva open_basedir está activada, al directorio predeterminado del sistema se le ha de permitir la subida de ficheros para que funcione.

upload_max_filesize integer

El tamaño máximo de un fichero subido.

Cuando se usa un integer, el valor del mismo es medido en bytes. También se puede usar la notación reducida, tal como se describe en esta FAQ.
max_file_uploads integer

El número máximo de ficheros a subir permitidos de forma simultánea. A partir de PHP 5.3.4, los campos de subida de ficheros dejados en blanco en el momento del envío no cuentan en este límite.

Configuración de SQL en general

Opciones de configuración de SQL en general
Nombre | Por defecto | Cambiable | Historial de cambios
sql.safe_mode | "0" | PHP_INI_SYSTEM |

He aquí una breve explicación de las directivas de configuración.

sql.safe_mode boolean

Si está activado, las funciones de conexión a bases de datos que especifiquen valores predeterminados emplearán dichos valores en lugar cualquier argumento proporcionado por el usuario. Para los detalles de los valores predeterminados, veáse la documentación de las funciones de conexión relevantes.

Específico de Windows

Opciones de configuración específicas de Windows
Nombre | Por defecto | Cambiable | Historial de cambios
windows.show_crt_warning | "0" | PHP_INI_ALL | Disponibe desde PHP 5.4.0.

He aquí una breve explicación de las directivas de configuración.

windows_show_crt_warning boolean

Esta directiva muestra las advertencias CRT de Windows cuando está establecida. Estas advertencias eran mostradas de forma predeterminada hasta PHP 5.4.0.

User Contributed Notes

Simone Pellegatta 19-Jan-2021 12:08
Be careful while using auto_prepend_file.

When the custom exception handler, set by set_exception_handler(), handles an uncaught exception, it interrupts the execution of every script.

If the script with the unhandled exception has been automatically prepended or included by an automatically prepended script, however, the main script will continue running anyway.

This could cause several issues: when we think that throwing an exception would automatically interrupt the current application, a whole chunk of code is going to run anyway.
Anton Bannikov 22-Apr-2020 02:40
I had a problem with 'open_basedir =' string in php.ini. This string was writtren in VirtualHost Directory directive of Apache2 and successfully rewrote the same php.ini setting! It happened with VestaCP, but I think, it's a common way. Goog luck!
luisdev 03-Mar-2020 02:59
https://haydenjames.io/understanding-php-memory_limit/ explains the memory_limit setting nicely.
diamondeagle at webmail dot co dot za 15-Aug-2019 11:14
Note regarding the upload_tmp_dir setting and UNC Paths:

When using PHP on Windows OS and IIS FastCGI, if you need to use a UNC path to a folder on a network drive for the upload_tmp_dir setting then you must use three \ characters at the front of the UNC path.

Windows and PHP use the first slash as an escape character, so if you only use two slashes then it passes a UNC path with just one backslash. That is not valid for UNC paths and you many experience problems when uploading files, such as errors saying that "PHP is missing a temporary folder".

Correct:
upload_tmp_dir = "\\\path\to\your\folder"

Incorrect:
upload_tmp_dir = "\\path\to\your\folder"
alaa morad 09-Jan-2019 08:16
add enctype="multipart/form-data" to your <form> tag or it will not upload any file even if file_uploads=on
ex:
<form method="POST" action="upload. php" enctype="multipart/form-data">
// form contents
</form>
abc500x500 at gmail dot com 26-Aug-2017 08:10
Please illuminate this:
memory_limit=128mb meaning which?

1-per script only then if in a moment 1000 user request php script maximum only 128mb of server ram use6 by script.
2-per script + per user if in a moment 1000 user request a php script about 1000*128mb=128gb ram use by script.
Thanks
Adam 27-Jan-2017 02:51
Remember that `open_basedir` restriction does not affect exec functions. As long as you do not disable exec functions (see `disable_functions`, users will be able to use `exec("/bin/cat [...]")` to access sensitive world readable files.
fernandobasso dot br at gmail dot com 17-Oct-2016 08:06
This might help in case someone happens to maintain old applications with a charset other than utf-8.

According to the docs, you can override the default charset if you use `header()`.

Suppose php.ini sets the default_charset to "UTF-8", but you need a legacy charset, like ISO-8859-1.

Still,

<?php header('Content-Type: text/html; Charset=ISO-8859-1'); ?>

would not override the charset, just add it as well and the result
was a response header like (note the two charsets):

    Content-Type:"text/html; Charset=ISO-8859-1;CHARSET=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.
txyoji at yahoo dot com 21-Nov-2013 08:24
If you enable "open_basedir" option, it will disable the realpath_cache. This can be a significant performance hit.

https://bugs.php.net/bug.php?id=53263
michael dot buergi at gmx dot net 08-May-2013 06:18
the ini-setting "detect_unicode" is indeed "zend.detect_unicode" (according to the phpinfo of my 5.4.4)
iko at vision dot sk 01-May-2012 08:49
auto_globals_jit setting is also affecting $_REQUEST superglobal in 5.3 It is not explicitly stated in documentation.
kghbln 17-Nov-2011 03:09
Adding multiple directories to open_basedir:

open_basedir = "/var/www/htdocs/:/var/www/tmp/" adds both paths /var/www/htdocs/ and /var/www/tmp/. Do not forget the trailing slash, otherwise the last directory will be considered as a prefix (< 5.3.4).

On Windows you use ; as the seperator.
AntonioK 10-Mar-2011 05:29
Note that there is no way to disable eval() work by using disable_functions directive, because eval() is a language construct and not a function.

Many people advise to disable such potentially-insecure functions like system(), exec(), passthru(), eval() and so on in php.ini when not running in safe mode, but eval() would still work even it listed in disable_functions.
rlammers at linuxmail dot org 09-Jan-2011 04:23
This is a possible solution for a problem which seems to be a php-ini-problem but is not.

If a $_POST is used with large fields e.g. textarea's with more than 120kb characters php returns a blank screen, even if the max_post_size is 8M.

This problem may be caused by an apache-module SecFilter.

Adding the following lines to the .htaccess solves the problem.
SecFilterEngine Off
SecFilterScanPOST Off

I know this is not a php-issue, but i'm still posting it here since it looks like it is a php-problem and I did not find any sites or forums offering this solution.
amolitor at molitor-design dot com 10-Feb-2010 03:23
Amusingly, the include_path logically includes the current directory of the running file as the last entry all the time anyways, so part of the business about shoving "." into the include_path is spurious -- it's "there" on the end all the time, at least in the 5.2.12 source (see main/fopen_wrappers.c around line 503).

This one had me goin' for a while.
mrok at mrok dot com 22-Mar-2009 08:29
Note that on some Unix systems (i.e. PHP 5.1.6 on Centos 5.2) include_path in php.ini should NOT be quoted.

For example, instead of

 include_path='.:/usr/share/php'

use

 include_path=.:/usr/share/php

Using quotes does not cause any error message, but all of your require_once() directives will fail (indicating that file could not be opened) - unless full path to target file is provided.
leo at korfu dot cz 29-May-2006 03:45
"If the size of post data is greater than post_max_size..."

It seems that a more elegant way is comparison between post_max_size and $_SERVER['CONTENT_LENGTH']. Please note that the latter includes not only size of uploaded file plus post data but also multipart sequences. Leo
csg at DEL_THISdiatom dot de 02-Sep-2005 02:55
Starting with PHP 4.4.0 (at least PHP version 4.3.10 did have old, documented behaviour) interpretation of value of "session.save_path" did change in conjunction with "save_mode" and "open_basedir" enabled.

Documented ( http://de.php.net/manual/en/ref.session.php#ini.session.save-path ):
  Values of "session.save_path" should or may be  **without**  ending slash.
  For instance:
<?php
  // Valid only  *before* PHP 4.4.0:
  ini_set( "session.save_path", "/var/httpd/kunde/phptmp" );
?> will mean:
  The directory "/var/httpd/kunde/phptmp/" will be used to write data and therefore must be writable by the web server.

Starting with PHP 4.4.0 the server complains that "/var/httpd/kunde/" is not writable.
Solution: Add an ending slash in call of ini_set (or probably whereever you set "session.save_path"), e.g.:
<?php
  // Note the slash on ".....phptmp/":
  ini_set( "session.save_path", "/var/httpd/kunde/phptmp/" );
?>

Hope, that does help someone.


Categorización de Extensiones

Tabla de contenidos

  • Alfabética
  • Incorporación
  • Estado

Este apéndice categoriza más de 150 extensiones documentadas en el manual de PHP de acuerdo a varios criterios.

User Contributed Notes

There are no user contributed notes for this page.


Alfabética

  • Apache
  • APCu
  • Arrays
  • BC Math
  • Bzip2
  • Calendario
  • Classkit
  • Clases/Objetos
  • COM
  • CSPRNG
  • Ctype
  • CUBRID
  • cURL
  • Fecha/Hora
  • DBA
  • dBase
  • DB++
  • Direct IO
  • Directorios
  • DOM
  • Data Structures
  • Eio
  • Enchant
  • Manejo de errores
  • Ev
  • Event
  • Ejecución de programas
  • Exif
  • Expect
  • FANN
  • FANN
  • FrontBase
  • FDF
  • Fileinfo
  • filePro
  • Sistema de Ficheros
  • Filter
  • FastCGI Process Manager
  • FTP
  • Manejo de Funciones
  • Gearman
  • Gender
  • GeoIP
  • Gettext
  • Gmagick
  • GMP
  • GnuPG
  • Hash
  • HRTime
  • Firebird/InterBase
  • IBM DB2
  • iconv
  • GD
  • ImageMagick
  • IMAP
  • Opciones/Info de PHP
  • Ingres
  • Inotify
  • intl
  • JSON
  • LDAP
  • libxml
  • Lua
  • LZF
  • Mail
  • Mailparse
  • Math
  • Cadenas de caracteres multibyte
  • Mcrypt
  • Memcache
  • Memcached
  • Memtrack
  • Mhash
  • Misc.
  • Mongo
  • MongoDB\BSON
  • MongoDB\Controlador
  • mqseries
  • MySQL (Original)
  • MySQLi
  • Mysqlnd
  • mysqlnd_memcache
  • mysqlnd_ms
  • mysqlnd_mux
  • mysqlnd_qc
  • mysqlnd_uh
  • Ncurses
  • Network
  • OAuth
  • OCI8
  • OPcache
  • OpenAL
  • OpenSSL
  • Control de la salida
  • Paradox
  • Parle
  • Hash de contraseñas
  • PCNTL
  • PCRE
  • PDO
  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • Oracle (PDO)
  • ODBC y DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)
  • MS SQL Server (PDO)
  • PostgreSQL
  • Phar
  • POSIX
  • Proctitle
  • PS
  • Pspell
  • pthreads
  • Quickhash
  • Radius
  • Rar
  • Readline
  • Recode
  • Reflection
  • Expresiones Regulares de POSIX
  • RRD
  • ScoutAPM
  • Seaslog
  • Semaphore
  • Sesiones
  • Memoria compartida
  • SimpleXML
  • SNMP
  • SOAP
  • Sockets
  • Sodium
  • Solr
  • Sphinx
  • SPL
  • SQLite3
  • SQLSRV
  • ssdeep
  • SSH2
  • Estadísticas
  • Stomp
  • Flujos
  • Strings
  • SVM
  • SVN
  • Swoole
  • Sync
  • Taint
  • TCP
  • Tidy
  • Tokenizer
  • tokyo_tyrant
  • Trader
  • UI
  • ODBC
  • uopz
  • URLs
  • V8js
  • Manejo de variables
  • Varnish
  • WDDX
  • Weakref
  • win32service
  • WinCache
  • wkhtmltox
  • xattr
  • xdiff
  • Xhprof
  • Analizador XML
  • XMLDiff
  • XMLReader
  • XML-RPC
  • XMLWriter
  • XSL
  • Yaconf
  • Yaf
  • Yaml
  • Yar
  • YAZ
  • Zip
  • Zlib
  • Mensajería de 0MQ
  • ZooKeeper

User Contributed Notes

There are no user contributed notes for this page.


Incorporación

Extensiones del núcleo

No son extensiones realmente. Son parte del núcleo de PHP y no pueden omitirse en un binario de PHP con opciones de compilación.

  • Arrays

  • Clases/Objetos

  • CSPRNG

  • Fecha/Hora

  • Directorios

  • Manejo de errores

  • Ejecución de programas

  • Sistema de Ficheros

  • Filter

  • Manejo de Funciones

  • Hash

  • Opciones/Info de PHP

  • Mail

  • Math

  • Misc.

  • Network

  • Control de la salida

  • Hash de contraseñas

  • Phar

  • Reflection

  • Expresiones Regulares de POSIX

  • Sesiones

  • SPL

  • Flujos

  • Strings

  • Tokenizer

  • URLs

  • Manejo de variables

Bundled

Extensiones incorporadas en PHP.

  • Apache

  • BC Math

  • Calendario

  • COM

  • Ctype

  • DBA

  • Exif

  • Fileinfo

  • FTP

  • iconv

  • GD

  • intl

  • JSON

  • Cadenas de caracteres multibyte

  • OPcache

  • PCNTL

  • PCRE

  • PDO

  • POSIX

  • Semaphore

  • Memoria compartida

  • Sockets

  • SQLite3

  • XML-RPC

  • Zlib

Extensiones externas

Estas extensiones vienen con PHP, pero para poder compilarlas, se requieren bibliotecas externas.

  • Bzip2

  • cURL

  • dBase

  • DOM

  • Enchant

  • FrontBase

  • Gettext

  • GMP

  • Firebird/InterBase

  • IMAP

  • LDAP

  • libxml

  • Mcrypt

  • Mhash

  • MySQL (Original)

  • MySQLi

  • Mysqlnd

  • OCI8

  • OpenSSL

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • MySQL (PDO)

  • Oracle (PDO)

  • ODBC y DB2 (PDO)

  • PostgreSQL (PDO)

  • SQLite (PDO)

  • PostgreSQL

  • Pspell

  • Readline

  • Recode

  • SimpleXML

  • SNMP

  • SOAP

  • Sodium

  • Tidy

  • ODBC

  • WDDX

  • Analizador XML

  • XMLReader

  • XMLWriter

  • XSL

  • Zip

Extensiones PECL

Estas extensiones están disponibles desde » PECL. Seguramente requieren bibliotecas externas. Existen más extensiones PECL pero no están documentadas aún en el manual.

  • Classkit

  • CUBRID

  • DB++

  • Direct IO

  • Eio

  • Ev

  • Event

  • Expect

  • FDF

  • filePro

  • Gearman

  • Gender

  • GeoIP

  • Gmagick

  • GnuPG

  • IBM DB2

  • ImageMagick

  • Ingres

  • Inotify

  • Lua

  • LuaSandbox

  • LZF

  • Mailparse

  • Memcache

  • Memcached

  • Memtrack

  • Mongo

  • mqseries

  • mysqlnd_memcache

  • mysqlnd_ms

  • mysqlnd_mux

  • mysqlnd_qc

  • mysqlnd_uh

  • Ncurses

  • OAuth

  • OpenAL

  • Paradox

  • CUBRID (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MS SQL Server (PDO)

  • Proctitle

  • PS

  • pthreads

  • Quickhash

  • Radius

  • Rar

  • RRD

  • runkit

  • ScoutAPM

  • Seaslog

  • Solr

  • Sphinx

  • SQLSRV

  • ssdeep

  • SSH2

  • Estadísticas

  • Stomp

  • Swoole

  • SVM

  • SVN

  • Taint

  • TCP

  • tokyo_tyrant

  • Trader

  • V8js

  • Varnish

  • Weakref

  • win32service

  • WinCache

  • xattr

  • xdiff

  • Xhprof

  • Yaf

  • Yaml

  • YAZ

  • ZooKeeper

User Contributed Notes

There are no user contributed notes for this page.


Estado

Esta sección lista las extensiones que no son recomendables para su uso en producción - son demasiado "viejas" (obsoletas) o "nuevas" (experimentales).

Extensiones obsoletas

Estas extensiones han sido marcadas como obsoletas, por lo general han sido reemplazadas por otras extensiones.

  • Memtrack

Extensiones experimentales

El comportamiento de estas extensiones - incluyendo los nombres de sus funciones y cualquier otra cosa documentada sobre estas extensiones - puede cambiar sin previo aviso en una futura versión de PHP. Use estas extensiones bajo su propio riesgo.

  • DB++

  • Hash

  • ImageMagick

  • Ncurses

  • Paradox

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • Oracle (PDO)

  • PS

  • XML-RPC

User Contributed Notes

There are no user contributed notes for this page.


Listado de funciones alias

Hay unas cuantas funciones en PHP que puede llamar con más de un nombre. En algunos de los casos no hay ningún nombre preferido de entre los múltiples nombres, is_int() e is_integer() son un buen ejemplo. Sin embargo hay funciones que cambiaron de nombre a causa de una limpieza del API o alguna otra razón y los nombres antiguos solo se preservan como alias para mantener la compatibilidad con versiones anteriores. Suele ser mala idea usar este tipo de alias, ya que pueden quedar obsoletos o que cambien de nombre, y hacer imposible la portabilidad del script. Esta lista se facilita para ayudar a las personas que quieren actualizar su código antiguo a una nueva sintaxis.

Alias
Alias | Función maestra | Extensión
_ | gettext() | Gettext
chop | rtrim() | Sintaxis base
close | closedir() | Sintaxis base
com_get | com_propget() | COM
com_propset | com_propput() | COM
com_set | com_propput() | COM
die | exit() | Funciones misceláneas
diskfreespace | disk_free_space() | Sistema de ficheros
doubleval | floatval() | Sintaxis base
fbsql | fbsql_db_query() | FrontBase
fputs | fwrite() | Sintaxis base
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() | Sintaxis base
is_double | is_float() | Sintaxis base
is_integer | is_int() | Sintaxis base
is_long | is_int() | Sintaxis base
is_real | is_float() | Sintaxis base
is_writeable | is_writable() | Sintaxis base
join | implode() | Sintaxis base
key_exists | array_key_exists() | Sintaxis base
ldap_close | ldap_unbind() | LDAP
magic_quotes_runtime | set_magic_quotes_runtime() | Sintaxis base
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 | OCI-Collection::assignElem | OCI8
ocibindbyname | oci_bind_by_name() | OCI8
ocicancel | oci_cancel() | OCI8
ocicloselob | OCI-Lob::close | OCI8
ocicollappend | OCI-Collection::append | OCI8
ocicollassign | OCI-Collection::assign | OCI8
ocicollmax | OCI-Collection::max | OCI8
ocicollsize | OCI-Collection::size | OCI8
ocicolltrim | OCI-Collection::trim | OCI8
ocicolumnisnull | oci_field_is_null() | OCI8
ocicolumnname | oci_field_name() | OCI8
ocicolumnprecision | oci_field_precision() | OCI8
ocicolumnscale | oci_field_scale() | OCI8
ocicolumnsize | oci_field_size() | OCI8
ocicolumntype | oci_field_type() | OCI8
ocicolumntyperaw | oci_field_type_raw() | OCI8
ocicommit | oci_commit() | OCI8
ocidefinebyname | oci_define_by_name() | OCI8
ocierror | oci_error() | OCI8
ociexecute | oci_execute() | OCI8
ocifetch | oci_fetch() | OCI8
ocifetchinto | oci_fetch_array(), oci_fetch_row(), oci_fetch_assoc(), oci_fetch_object() | OCI8
ocifetchstatement | oci_fetch_all() | OCI8
ocifreecollection | OCI-Collection::free | OCI8
ocifreecursor | oci_free_statement() | OCI8
ocifreedesc | oci_free_descriptor() | OCI8
ocifreestatement | oci_free_statement() | OCI8
ocigetelem | OCI-Collection::getElem | OCI8
ociinternaldebug | oci_internal_debug() | OCI8
ociloadlob | OCI-Lob::load | OCI8
ocilogon | oci_connect() | OCI8
ocinewcollection | oci_new_collection() | OCI8
ocinewcursor | oci_new_cursor() | OCI8
ocinewdescriptor | oci_new_descriptor() | OCI8
ocinlogon | oci_new_connect() | OCI8
ocinumcols | oci_num_fields() | OCI8
ociparse | oci_parse() | OCI8
ocipasswordchange | oci_password_change() | OCI8
ociplogon | oci_pconnect() | OCI8
ociresult | oci_result() | OCI8
ocirollback | oci_rollback() | OCI8
ocisavelob | OCI-Lob::save | OCI8
ocisavelobfile | OCI-Lob::import | OCI8
ociserverversion | oci_server_version() | OCI8
ocisetprefetch | oci_set_prefetch() | OCI8
ocistatementtype | oci_statement_type() | OCI8
ociwritelobtofile | OCI-Lob::export | OCI8
ociwritetemporarylob | OCI-Lob::writeTemporary | OCI8
odbc_do | odbc_exec() | ODBC
odbc_field_precision | odbc_field_len() | ODBC
pg_clientencoding | pg_client_encoding() | PostgreSQL
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL
pos | current() | Sintaxis base
recode | recode_string() | Recode
show_source | highlight_file() | Sintaxis base
sizeof | count() | Sintaxis base
snmpwalkoid | snmprealwalk() | SNMP
strchr | strstr() | Sintaxis base
xptr_new_context | xpath_new_context() |

User Contributed Notes

There are no user contributed notes for this page.


Lista de palabras reservadas

Tabla de contenidos

  • Lista de palabras reservadas
  • Clases predefinidas
  • Constantes predefinidas
  • Listado de otras palabras reservadas

A continuación se muestra un listado de los identificadores predefinidos en PHP. Ninguno de estos identificadores se puede usar como identificador en scripts a menos que se indique los contrario. Estas listas incluyen tanto palabras reservadas como variables predefinidas, constantes y nombres de clases. Estas listas no son ni exhaustivas ni completas.

User Contributed Notes

There are no user contributed notes for this page.


Lista de palabras reservadas

Estas palabras tienen un significado especial en PHP. Algunas representan cosas que se parecen a funciones, otras se parecen a constantes, etc.; pero no lo son en realidad: son constructores del lenguaje. No se puede usar ninguna de las siguientes palabras como constantes, nombres de clases, nombres de funciones o métodos. Se pueden usar como nombres de variables, pero podría dar lugar a confusiones.

A partir de PHP 7.0.0, estas palabras reservadas están permitidas como nombres de propiedades, de constantes y de métodos de clases, interfaces y rasgos, excepto que class no puede utilizarse como nombre de constante.

Palabras reservadas de PHP
__halt_compiler() | abstract | and | array() | as
break | callable (a partir de PHP 5.4) | case | catch | class
clone | const | continue | declare | default
die() | do | echo | else | elseif
empty() | enddeclare | endfor | endforeach | endif
endswitch | endwhile | eval() | exit() | extends
final | finally (a partir de PHP 5.5) | fn (as of PHP 7.4) | for | foreach
function | global | goto (a partir de PHP 5.3) | if | implements
include | include_once | instanceof | insteadof (a partir de PHP 5.4) | interface
isset() | list() | match (a partir de PHP 8.0) | namespace (a partir de PHP 5.3) | new
or | print | private | protected | public
require | require_once | return | static | switch
throw | trait (a partir de PHP 5.4) | try | unset() | use
var | while | xor | yield (a partir de PHP 5.5) | yield from (a partir de PHP 7.0)
Constantes en tiempo de compilación
__CLASS__ | __DIR__ (a partir de PHP 5.3) | __FILE__ | __FUNCTION__ | __LINE__ | __METHOD__
__NAMESPACE__ (a partir de PHP 5.3) | __TRAIT__ (a partir de PHP 5.4) |  |  |  |

User Contributed Notes

Johnny D. 22-May-2020 06:37
const FORBIDDEN_TYPES = [
    'null',

    'bool',
    'false',
    'true',

    'int',
    'float',

    'string',
];
bla at taxistop dot be 19-Jul-2018 09:50
This list doesn't include 'self' and 'parent', which I take are indeed keywords.
Thomas Hansen 15-Aug-2016 10:08
Please note that reserved words are still not allowed to be used as namespace or as part of it:

<?php
namespace MyNameSpace\List;

class Test
{
}
?>

This will fail with a Parse error:  syntax error, unexpected 'List' (T_LIST), expecting identifier (T_STRING)
martindilling at gmail dot com 15-Apr-2013 10:20
RegEx to find all the keywords:

\b(
(a(bstract|nd|rray|s))|
(c(a(llable|se|tch)|l(ass|one)|on(st|tinue)))|
(d(e(clare|fault)|ie|o))|
(e(cho|lse(if)?|mpty|nd(declare|for(each)?|if|switch|while)|val|x(it|tends)))|
(f(inal|or(each)?|unction))|
(g(lobal|oto))|
(i(f|mplements|n(clude(_once)?|st(anceof|eadof)|terface)|sset))|
(n(amespace|ew))|
(p(r(i(nt|vate)|otected)|ublic))|
(re(quire(_once)?|turn))|
(s(tatic|witch))|
(t(hrow|r(ait|y)))|
(u(nset|se))|
(__halt_compiler|break|list|(x)?or|var|while)
)\b
Chris 04-Oct-2012 04:33
Here they are as arrays:

<?php
$keywords = array('__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor');

$predefined_constants = array('__CLASS__', '__DIR__', '__FILE__', '__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__', '__TRAIT__');
?>

Along with get_defined_functions() and get_defined_constants(), this can be useful for checking eval() statements.


Clases predefinidas

Esta sección enumera las clases predefinidas estándar. Varias extensiones definen otras clases, las cuales se describen en sus respectivas secciones.

Clases definidas estándar

Estas clases están definidas en el conjunto estándar de funciones que se incluyen en la compilación de PHP.

Directory
Creada por dir().
stdClass
Creada en la conversión al tipo object.
__PHP_Incomplete_Class
Posiblemente creada por unserialize().

Clases predefinidas a partir de PHP 5

Estas clases predefinidas adicionales se introdujeron en PHP 5.0.0.

Exception
ErrorException
Disponible desde PHP 5.1.0.
php_user_filter

Closure

La clase final predefinida Closure fue introducida en PHP 5.3.0. Se usa para representar funciones anónimas.

Para más información, véase la página de su clase.

Generator

La clase final predefinida Generator fue introducida en PHP 5.5.0. Se usa para representar generadores.

Para más información, véase la página de su clase.

Interfaces y clases predefinidas a partir de PHP 7

Estas interfaces y clases predefinidas adicionales se han introducido en PHP 7.0.0.

ArithmeticError
AssertionError
DivisionByZeroError
Error
Throwable
ParseError
TypeError

Clases especiales

Los siguientes identificadores no se pueden usar como nombres de clase, dado que tienen un propósito especial.

self
Clase actual.
static
Clase actual en tiempo de ejecución.
parent
Clase madre.

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 predefinidas

Constantes predefinidas del núcleo

Estas constantes están definidas por el núcleo de PHP. Este incluye PHP, el motor Zend, y los módulos SAPI.

PHP_VERSION (string)
La versión actual de PHP en notación "mayor.menor.edición[extra]".
PHP_MAJOR_VERSION (integer)
La versión "mayor" actual de PHP como valor integer (p.ej., int(5) en la versión "5.2.7-extra"). Disponible desde PHP 5.2.7.
PHP_MINOR_VERSION (integer)
La versión "menor" actual de PHP como valor integer (p.ej, int(2) en la versión "5.2.7-extra"). Disponible desde PHP 5.2.7.
PHP_RELEASE_VERSION (integer)
La versión de "publicación" (release) actual de PHP como valor integer (p.ej., int(7) en la versión "5.2.7-extra"). Disponible desde PHP 5.2.7.
PHP_VERSION_ID (integer)
La versión de PHP actual como valor integer, útil para comparar versiones (p.ej., int(50207) para la versión "5.2.7-extra"). Disponible desde PHP 5.2.7.
PHP_EXTRA_VERSION (string)
La versión "extra" actual de PHP, en forma de string (p.ej., '-extra' para la versión "5.2.7-extra"). Se usa a menudo por los distribuidores para indicar la versión de un paquete. Disponible desde PHP 5.2.7.
PHP_ZTS (integer)
Disponible desde PHP 5.2.7.
PHP_DEBUG (integer)
Disponible desde PHP 5.2.7.
PHP_MAXPATHLEN (integer)
La longitud máxima de los nombres de ficheros (incluyendo directorios) admitida por la compilación de PHP. Disponible desde PHP 5.3.0.
PHP_OS (string)
El sistema operativo para el que se construyó PHP.
PHP_OS_FAMILY (string)
La familia de sistemas operativos para la que se construyó PHP. Puede se 'Windows', 'BSD', 'OSX', 'Solaris', 'Linux' or 'Unknown'. Disponible desde PHP 7.2.0.
PHP_SAPI (string)
La API del servidor de la compilación de PHP. Ver también php_sapi_name().
PHP_EOL (string)
El símbolo 'Fin De Línea' correcto de la plataforma en uso. Disponible desde PHP 5.0.2
PHP_INT_MAX (integer)
El número entero más grande admitido en esta compilación de PHP. Normalmente int(2147483647). Disponible desde PHP 5.0.5
PHP_INT_MIN (integer)
El número entero más pequeño admitido en esta compilación de PHP. Normalmente int(-2147483648) en sistemas de 32 bits y int(-9223372036854775808) en sistemas de 64 bits. Disponible desde PHP 7.0.0. Usualmente, PHP_INT_MIN === ~PHP_INT_MAX.
PHP_INT_SIZE (integer)
El tamaño de un número entero en bytes en esta compilación de PHP. Disponible desde PHP 5.0.5
PHP_FLOAT_DIG (integer)
Número de dígitos decimales que se pueden redondear en un float y revertirlos si pédida de precisión. Disponible a partir de PHP 7.2.0.
PHP_FLOAT_EPSILON (float)
El menor número positivo representable x, tal que x + 1.0 != 1.0. Disponible a partir de PHP 7.2.0.
PHP_FLOAT_MIN (float)
El menor número de punto flotante representable. Disponible a partir de PHP 7.2.0.
PHP_FLOAT_MAX (float)
El mayor número de punto flotante representable. Disponible a partir de PHP 7.2.0.
DEFAULT_INCLUDE_PATH (string)
PEAR_INSTALL_DIR (string)
PEAR_EXTENSION_DIR (string)
PHP_EXTENSION_DIR (string)
PHP_PREFIX (string)
El valor de "--prefix" usado en la configuración.
PHP_BINDIR (string)
Especifica dónde se instalaron los binarios.
PHP_BINARY (string)
Especifica la ruta de los binarios de PHP durante la ejecución del script. Disponible desde PHP 5.4.
PHP_MANDIR (string)
Especifica dónde están instalados los manuales. Disponible desde PHP 5.3.7.
PHP_LIBDIR (string)
PHP_DATADIR (string)
PHP_SYSCONFDIR (string)
PHP_LOCALSTATEDIR (string)
PHP_CONFIG_FILE_PATH (string)
PHP_CONFIG_FILE_SCAN_DIR (string)
PHP_SHLIB_SUFFIX (string)
Sufijo de las bibliotecas compartidas de la plataforma de compilación, como "so" (mayoría de plataformas Unix) o "dll" (Windows).
PHP_FD_SETSIZE (string)
El número máximo de descriptores de ficheros para seleccionar llamadas al sistema. Disponble a partir de PHP 7.1.0.
E_ERROR (integer)
Constante de informe de error
E_WARNING (integer)
E_PARSE (integer)
E_NOTICE (integer)
E_CORE_ERROR (integer)
E_CORE_WARNING (integer)
E_COMPILE_ERROR (integer)
E_COMPILE_WARNING (integer)
E_USER_ERROR (integer)
E_USER_WARNING (integer)
E_USER_NOTICE (integer)
E_DEPRECATED (integer)
Disponible desde PHP 5.3.0
E_USER_DEPRECATED (integer)
Disponible desde PHP 5.3.0
E_ALL (integer)
E_STRICT (integer)
__COMPILER_HALT_OFFSET__ (integer)
Disponible desde PHP 5.1.0
true (boolean)
Ver también Booleanos.
false (boolean)
Ver también Booleanos.
null (null)
Ver también Null.

Ver también: Constantes mágicas.

Constantes predefinidas estándar

Todas las constantes de extensiones del núcleo están definidas en PHP de manera predeterminada.

User Contributed Notes

nabikaz at gmail dot com 10-Nov-2016 10:18
Don't use `PHP_EOL` for textarea of form to array, use it:

array_values(array_filter(explode("\n", str_replace("\r", '', $_POST['data']))))
Anonymous 27-Jan-2015 03:25
PHP_EOL can be used like that:

<?php

$data = 'some data'.PHP_EOL;
$fp = fopen('somefile', 'a');
fwrite($fp, $data);

?>

Which is the same of \r\n or \n depending on the OS.
You can put those lines in a while for example, and create a log file.
rdcapasso 08-Sep-2013 09:16
Volker's getOS() function needs to have the order of cases changed in the switch statement since "darwin" contains "win", which means that both "windows" and "darwin" will return self::OS_WIN. I've moved the 'dar' case above the 'win' case:

<?php
class System {

    const OS_UNKNOWN = 1;
    const OS_WIN = 2;
    const OS_LINUX = 3;
    const OS_OSX = 4;

    /**
     * @return int
     */
    static public function getOS() {
        switch (true) {
            case stristr(PHP_OS, 'DAR'): return self::OS_OSX;
            case stristr(PHP_OS, 'WIN'): return self::OS_WIN;
            case stristr(PHP_OS, 'LINUX'): return self::OS_LINUX;
            default : return self::OS_UNKNOWN;
        }
    }

}
?>


Listado de otras palabras reservadas

Las siguientes palabras no se pueden utilizar para dar nombre a una clase, interfaz o rasgo, y están también prohibidas emplearlas en espacios de nombres.

Palabras reservadas
int (a partir de PHP 7) | float (a partir de PHP 7) | bool (a partir de PHP 7) | string (a partir de PHP 7)
true (a partir de PHP 7) | false (a partir de PHP 7) | null (a partir de PHP 7) | void (a partir de PHP 7.1)
iterable (a partir de PHP 7.1) | object (a partir de PHP 7.2)

Las palabras de la siguiente lista han estado ligeramente reservadas. Aunque todavía se puden emplear como nombres de clases interfaces y rasgos, (así como en espacio de nombres), su uso está totalmente desaconsejado debido a que podrían ser utilizadas en versiones futuras de PHP.

Palabras ligeramente reservadas
resource (as of PHP 7) mixed (as of PHP 7) numeric (as of PHP 7)

User Contributed Notes

There are no user contributed notes for this page.


Lista de Tipos de Recurso

La siguiente es una lista de las funciones que crean, usan o destruyen recursos PHP. La función is_resource() se puede usar para determinar si una variable es un recurso, y get_resource_type() devolverá el tipo de recurso que es.

Tipos de recursos
Nombre del tipo de recurso | Creado por | Usado por | Destruido por | Definición
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Fichero bzip2
cubrid connection | 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() | Conexión a una base de datos de CUBRID
persistent cubrid connection | 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() | Conexión persistente a una base de datos de CUBRID
cubrid request | 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() | Solicitud de CUBRID
cubrid lob | cubrid_lob_get() | cubrid_lob_export() cubrid_lob_send() cubrid_lob_size() | cubrid_lob_close() | Nadie
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() | Nadie
curl | curl_copy_handle(), curl_init() | curl_copy_handle(), curl_errno(), curl_error(), curl_exec(), curl_getinfo(), curl_setopt() | curl_close() | Sesión de curl
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Enlace a una base de datos DBA
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | Nadie | Enlace persistente a una base de datos 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() | Enlace a una base de datos Dbase
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | dbx connection
dbx_result_object | dbx_query() | Nadie | Resultado dbx
xpath context
xpath object
fbsql link | fbsql_change_user(), fbsql_connect() | fbsql_autocommit(), fbsql_blob_size(), fbsql_clob_size(), fbsql_commit(), fbsql_change_user(), fbsql_create_blob(), fbsql_create_db(), fbsql_create_clob(), fbsql_data_seek(), fbsql_database_password(), fbsql_database(), fbsql_db_query(), fbsql_db_status(), fbsql_drop_db(), fbsql_errno(), fbsql_error(), fbsql_get_autostart_info(), fbsql_hostname(), fbsql_insert_id(), fbsql_list_dbs(), fbsql_password(), fbsql_read_blob(), fbsql_read_clob(), fbsql_rollback(), fbsql_select_db(), fbsql_set_password(), fbsql_set_transaction(), fbsql_start_db(), fbsql_stop_db(), fbsql_username() | fbsql_close() | Enlace a una base de datos fbsql
fbsql plink | fbsql_change_user(), fbsql_pconnect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | Nadie | Enlace persistente a una base de datos fbsql
fbsql result | fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() | fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() | fbsql_free_result() | Resultado de fbsql
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() | Fichero 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() | Flujo FTP
gd | imagecreate(), imagecreatefromgd(), imagecreatefromgd2(), imagecreatefromgd2part(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatefromxbm(), imagecreatefromxpm(), imagecreatetruecolor(), imagerotate() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagerotate(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness(), image2wbmp(), imagealphablending(), imageantialias(), imagecolorallocatealpha(), imagecolorclosesthwb(), imagecolordeallocate(), imagecolormatch(), imagefilter(), imagefttext(), imagegd(), imagegd2(), imageistruecolor(), imagelayereffect(), imagepalettecopy(), imagesavealpha(), imagesetstyle(), imagexbm() | imagedestroy() | Imagen GD
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | Nadie | Tipo de letra para GD
gd PS encoding
gd PS font | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | Tipo de letra PS para GD
GMP integer | gmp_init() | gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() | Nadie | Número GMP
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() | Enlace a un servidor IMAP, POP3
ingres | ingres_connect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | ingres_close() | Enlace a un base de datos ingresII
ingres persistent | ingres_pconnect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | Nadie | Enlace persistente a una base de datos ingresII
interbase blob
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Enlace a una base de datos Interbase
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | Nadie | Enlace persistente a una base de datos Interbase
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Consulta de Interbase
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Resultado de Interbase
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Transacción de Interbase
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | Conexión de ldap
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | Resultado de búsqueda de ldap
ldap result entry
SWFAction
SWFBitmap
SWFButton
SWFDisplayItem
SWFFill
SWFFont
SWFGradient
SWFMorph
SWFMovie
SWFShape
SWFSprite
SWFText
SWFTextField
mnogosearch agent
mnogosearch result
msql link | msql_connect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | msql_close() | Enlace a una base de datos mSQL
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | Nadie | Enlace persistente a mSQL
msql query | msql_db_query(), msql_list_dbs(), msql_list_fields(), msql_list_tables(), msql_query() | msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_field_seek(), msql_field_table(), msql_field_flags(), msql_field_len(), msql_field_name(), msql_field_type(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() | msql_free_result(), msql_free_result() | Resultado de mSQL
mssql link | mssql_connect() | mssql_query(), mssql_select_db() | mssql_close() | Enlace a una base de datos Microsoft SQL Server
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | Nadie | Enlace persistente a Microsoft SQL Server
mssql result | mssql_query() | mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() | mssql_free_result() | Rasultado de Microsoft SQL Server
mysql link | mysql_connect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Enlace a una base de datos MySQL
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | Nadie | Enlace persistente a una base de datos 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() | Resultado de MySQL
oci8 collection | oci_new_collection() | OCI-Collection::append(), OCI-Collection::assign(), OCI-Collection::assignElem(), OCI-Collection::getElem(), OCI-Collection::max(), OCI-Collection::size(), OCI-Collection::trim() | OCI-Collection::free() | Colección de Oracle
oci8 connection | 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() | Conexiión a base de datos de Oracle
oci8 lob | oci_new_descriptor() | OCI-Lob::append(), OCI-Lob::close(), OCI-Lob::eof(), OCI-Lob::erase(), OCI-Lob::export(), OCI-Lob::flush(), OCI-Lob::getBuffering(), OCI-Lob::import(), OCI-Lob::load(), OCI-Lob::read(), OCI-Lob::rewind(), OCI-Lob::save(), OCI-Lob::saveFile(), OCI-Lob::seek(), OCI-Lob::setBuffering(), OCI-Lob::size(), OCI-Lob::tell(), OCI-Lob::truncate(), OCI-Lob::write(), OCI-Lob::writeTemporary(), OCI-Lob::writeToFile(), oci_lob_copy(), oci_lob_is_equal() | OCI-Lob::free() | Objetos grandes de Oracle
oci8 statement | 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() | Cursor de 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() | Enlace a una base de datos ODBC
odbc link persistent | odbc_pconnect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | Nadie | Enlace persistente a una base de datos 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() | Resultado de ODBC
birdstep link
birdstep result
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | Clave OpenSSL
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Clave pública
pdf document | pdf_new() | pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_add_thumbnail(), pdf_arcn(), pdf_begin_pattern(), pdf_begin_template(), pdf_end_pattern(), pdf_end_template(), pdf_initgraphics(), pdf_makespotcolor(), pdf_set_info(), pdf_setcolor(), pdf_setmatrix(), pdf_open_memory_image() | pdf_close(), pdf_delete() | Documento PDF
pdf image | pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() | pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() | pdf_close_image() | Imagen en un fichero PDF
pdf object
pdf outline
pgsql large object | pg_lo_open() | pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() | pg_lo_close() | Objeto Grande de PostgreSQL
pgsql link | pg_connect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Enlace a una base de datos 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_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | Nadie | Enlace persistente a una base de datos PostgreSQL
pgsql result | pg_execute(), pg_query(), pg_query_params(), pg_get_result() | pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() | pg_free_result() | Resultado de PostgreSQL
pgsql string
printer
printer brush
printer font
printer pen
pspell | pspell_new(), pspell_new_config(), pspell_new_personal() | pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() | Nadie | Diccionario pspell
pspell config | pspell_config_create() | pspell_new_config() | Nadie | Configuración de pspell
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close() | Manejo de bloques de memoria compartida (a partir de PHP 7.0.0)
sockets file descriptor set | socket() | accept_connect(), bind(), connect(), listen(), read(), write() | close() | Socket
sockets i/o vector
stream | opendir() | readdir(), rewinddir() | closedir() | Gestor de directorio
stream | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | Gestor de fichero
stream | popen(), fsockopen(), pfsockopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Gestor de proceso
socket | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Gestor de socket
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Enlace a una base de datos Sybase usando la biblioteca DB
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | Nadie | Enlace persistente a una base de datos Sybase usando la biblioteca DB
sybase-db result | sybase_query(), sybase_unbuffered_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Resultado de Sybase usando la biblioteca DB
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Enlace a una base de datos Sybase usando la biblioteca CT
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | Nadie | Enlace persistente a una base de datos Sybase usando la biblioteca CT
sybase-ct result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Resultado de Sybase usando la biblioteca CT
sysvsem | sem_get() | sem_acquire() | sem_release() | Semáforo de System V
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | Memoria compartida de System V
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | Paquete 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() | Analizador sintáctico XML
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | Fichero comprimido gz
zlib.deflate | deflate_init() | deflate_add() | Ninguna() | contexto de desinflación incremental
zlib.inflate | inflate_init() | inflate_add() | Ninguna() | contexto de inflación incremental

User Contributed Notes

csaba at alum dot mit dot edu 06-Nov-2009 10:25
On my PHP 5.2 under Windows Vista, the resource type listed as interbase link is actually Firebird/InterBase link


Lista de filtros disponibles

Tabla de contenidos

  • Filtros de String
  • Filtros de conversión
  • Filtros de compresión
  • Filtros de encriptación

La siguiente es una lista de unos cuantos filtros de secuencia integrados que puede usar con stream_filter_append(). Su versión de PHP puede tener más filtros (o menos) que aquellos que aparecen aquí.

Vale la pena anotar una ligera asimetría entre stream_filter_append() y stream_filter_prepend(). Cada secuencia en PHP contiene un pequeño búfer de lectura en donde almacena los bloques de datos recibidos desde el sistema de archivos u otro recurso para procesar los datos de la forma más eficiente. Tan pronto como los datos son tomados del recurso y colocados en el búfer interno de la secuencia, éstos son procesados inmediatamente a través de cualquier filtro adjunto sin importar que la aplicación PHP esté lista para los datos o no. Si los datos están en el búfer de lectura cuando un filtro es añadido al final, los datos serán procesados inmediatamente a través del filtro haciendo parecer que el proceso fuera transparente. Sin embargo, si los datos están en el búfer de lectura cuando un filtro es adjuntado al comienzo, los datos NO serán procesados a través del filtro. En su lugar esperará a que el siguiente bloque de datos sea recuperado del recurso.

Para una lista de filtros instalados en su versión de PHP, use stream_get_filters().

User Contributed Notes

There are no user contributed notes for this page.


Filtros de String

Cada uno de estos filtros hace precisamente lo que su nombre implica y corresponden al comportamiento de una función de manejo de strings php incorporada. Para obtener más información sobre un filtro determinado, consulte la página del manual de la función correspondiente.

string.rot13

El uso de este filtro es equivalente a procesar todos los datos de la secuencia a través de la función str_rot13().

Ejemplo #1 string.rot13

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "Esto es una prueba.\n");
/* Salida:  Guvf vf n grfg.   */
?>

string.toupper

El uso de este filtro es equivalente a procesar todos los datos de la secuencia a través de la función strtoupper().

Ejemplo #2 string.toupper

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "Esto es una prueba.\n");
/* Salida:  ESTO ES UNA PRUEBA.   */
?>

string.tolower

El uso de este filtro es equivalente a procesar todos los datos de la secuencia a través de la función strtolower().

Ejemplo #3 string.tolower

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "Esto es una prueba.\n");
/* Salida:  esto es una prueba.   */
?>

string.strip_tags

El uso de este filtro es equivalente a procesar todos los datos de la secuencia a través de la función strip_tags(). Acepta parámetros en una de dos formas: Ya sea como un string que contiene una lista de etiquetas similares a el segundo parámetro de la función strip_tags(), o como un array de nombres de etiqueta.

Advertencia

Esta característica ha sido declarada OBSOLETA a partir de PHP 7.2.0. Su uso está totalmente desaconsejado.

Ejemplo #4 string.strip_tags

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, "<b><i><u>");
fwrite($fp, "<b>texto en negrita</b> ampliado a un <h1>título de nivel 1</h1>\n");
fclose($fp);
/* Imprime:  <b>texto en negrita</b> ampliado a un título de nivel 1   */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('b','i','u'));
fwrite($fp, "<b>texto en negrita</b> ampliado a un <h1>título de nivel 1</h1>\n");
fclose($fp);
/* Imprime:  <b>texto en negrita</b> ampliado a un título de nivel 1   */
?>

User Contributed Notes

There are no user contributed notes for this page.


Filtros de conversión

Como los filtros string.*, los filtros convert.* realiza acciones similares a sus nombres. Para obtener más información sobre un filtro determinado, consulte la página del manual de la función correspondiente.

convert.base64-encode y convert.base64-decode

El uso de estos filtros equivale a procesar todos los datos de la secuencia a través de las funciones base64_encode() y base64_decode() respectivamente. convert.base64-encode soporta parámetros dados como un array asociativo. Si el parámetro line-length se da, la salida de base64 se dividirá en trozos de line-length caracteres cada uno. Si el parámetro line-break-chars se da, cada porción será delimitada por los caracteres dados. Estos parámetros le dan el mismo efecto que el uso de base64_encode() con chunk_split().

Ejemplo #1 convert.base64-encode & convert.base64-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "Esto es una prueba.\n");
fclose($fp);
/* Outputs:  VGhpcyBpcyBhIHRlc3QuCg==  */

$param = array('line-length' => 8, 'line-break-chars' => "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "Esto es una prueba.\n");
fclose($fp);
/* Outputs:  VGhpcyBp
          :  cyBhIHRl
          :  c3QuCg==  */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Salida:  Esto es una prueba.  */
?>

convert.quoted-printable-encode y convert.quoted-printable-decode

El uso de la versión decodificada de este filtro equivale a procesar todo el flujo de datos a través de las funciones quoted_printable_decode(). No existe una función equivalente a convert.quoted-printable-encode. convert.quoted-printable-encode soporta parámetros dados como un array asociativo. Además de los parámetros soportados por convert.base64-encode, convert.quoted-printable-encode también soporta argumentos booleanos binary y force-encode-first. convert.base64-decode sólo soporta los parámetros line-break-chars como un tipo sugerido para quitar la carga útil codificada.

Ejemplo #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, "Esto es una prueba.\n");
/* Outputs:  =Esto es una prueba.=0A  */
?>

convert.iconv.*

Los filtros convert.iconv.* están disponibles, si el soporte iconv está habilitado, y su uso es equivalente a procesar todos los datos de la secuencia con iconv(). Estos filtros no soportan parámetros, sino que esperan que la entrada y codificaciones de salida que se darán como parte del nombre del filtro, es decir, ya sea como convert.iconv.<input-encoding>.<output-encoding> o convert.iconv.<input-encoding>/<output-encoding> (ambas notaciones son semánticamente equivalentes).

Ejemplo #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);
/* Salida: Esto es una prueba. */
?>

User Contributed Notes

There are no user contributed notes for this page.


Filtros de compresión

Mientras que los Envoltorios de compresión proporcionan una forma de crear ficheros gzip y bz2 compatibles con el sistema de archivos local, no proporcionan un medio para la compresión generalizada sobre los flujos de la red, ni proporcionan un medio para comenzar con un flujo no comprimido y la transición a uno comprimido. Para ello, se puede aplicar un filtro de compresión a cualquier recurso de flujo en cualquier momento.

Nota: Los filtros de compresión no generan cabeceras y avances utilizadas por las utilidades de línea de comando como gzip. Sólo comprimen y descomprimen las porciones de carga útil de los flujos de datos comprimidos.

zlib.deflate y zlib.inflate

zlib.deflate (compresión) y zlib.inflate (descompresión) son implementaciones de los métodos de compresión descritos en » RFC 1951. Los filtros deflate toma hasta tres parámetros pasados como un array asociativo. level describe la intensidad de compresión (1-9). Números más grandes producen, por lo general, resultados más pequeños, al costo de tiempo de procesamiento adicional. Dos niveles de compresión especiales existen también: 0 (para no-compresión), y -1 (el valor predeterminado de zlib -- actualmente 6). window es el registro en base-2 del tamaño de ventana del circuito cerrado de compresión. Valores más altos (de hasta 15 -- 32768 bytes) producen mejor compresión al costo de más memoria, mientras valores más bajos (alrededor de 9 -- 512 bytes) producen una compresión inferior en un espacio de memoria más pequeño. El tamaño de window es actualmente 15. memory es una escala que indica cuánta memoria debería ser reservada. Los valores válidos están en el rango de 1 (reserva mínima) a 9 (reserva máxima). Esta reserva de memoria afecta únicamente la repidez y no tiene impacto en el tamaño del resultado generado.

Nota: Debido a que el nivel de compresión es el parámetro más comúnmente usado, puede ser alternativamente proporcionado como un valor entero simple (en lugar de un elemento de array).

Los filtros de compresión zlib.* están disponibles con PHP desde la versión 5.1.0 si el soporte de zlib se encuentra habilitado. También están disponibles como una característica portada de vuelta en la versión 5.0.x, instalando el paquete » zlib_filter desde » PECL.

Ejemplo #1 zlib.deflate y zlib.inflate

<?php
$params = array('level' => 6, 'window' => 15, 'memory' => 9);

$texto_original = "Esto es una prueba.\nEsto es solo una prueba.\nEsta no es una cadena importante.\n";
echo "El texto original tiene " . strlen($texto_original) . " caracteres.\n";

$da = fopen('test.deflated', 'w');
stream_filter_append($da, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($da, $texto_original);
fclose($da);

echo "El archivo comprimido tiene " . filesize('test.deflated') . " bytes.\n";
echo "El texto original era:\n";
/* Use readfile y zlib.inflate para descomprimir al vuelo */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Genera la salida:

El texto original tiene 79 caracteres.
El archivo comprimido tiene 59 bytes.
El texto original era:
Esto es una prueba.
Esto es solo una prueba.
Esta no es una cadena importante.

 */
?>

Ejemplo #2 zlib.deflate simple

<?php
$texto_original = "Esto es una prueba.\nEsto es solo una prueba.\nEsta no es una cadena importante.\n";
echo "El texto original tiene " . strlen($texto_original) . " caracteres.\n";

$da = fopen('test.deflated', 'w');
/* Aqui "6" indica el nivel 6 de compresion */
stream_filter_append($da, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($da, $texto_original);
fclose($da);

echo "El archivo comprimido tiene " . filesize('test.deflated') . " bytes.\n";

/* Genera la salida:

El texto original tiene 79 caracteres.
El archivo comprimido tiene 53 bytes.

 */
?>

bzip2.compress y bzip2.decompress

bzip2.compress y bzip2.decompress funcionan de la misma forma que los filtros zlib descritos anteriormente. El filtro bzip2.compress acepta hasta dos parámetros dados como elementos de una matriz asociativa: blocks es un valor entero desde 1 hasta 9 que indica el número de bloques de 100kbytes de memoria a reservar para el espacio de trabajo. work es también un valor entero que va desde 0 a 250, e indica cuánto esfuerzo debe invertirse para expandir usando el método de compresión normal antes de caer en un método más lento pero más confiable. Modificar este parámetro afecta únicamente la rapidez de compresién. Ni el tamaño de la salida comprimida ni el uso de memoria se modifican por este valor. Un factor de trabajo de 0 le indica a la biblioteca bzip que debe usar el valor interno predeterminado. El filtro bzip2.decompress sólo acepta un parámetro, el cual puede ser pasado como un valor booleano ordinario, o como el elemento small de una matriz asociativa. small, cuando se define a un valor true, le indica a la biblioteca bzip de realice una descompresión con una cantidad de memoria mínima, al costo de la rapidez.

Las filtros de compresión bzip2.* se encuentran disponibles con PHP desde la versión 5.1.0 si el soporte de bz2 se encuentra habilitado. También se encuentran disponibles como una característica portada hacia atrás en la versión 5.0.x, instalando el paquete » bz2_filter desde » PECL.

Ejemplo #3 bzip2.compress y bzip2.decompress

<?php
$param = array('blocks' => 9, 'work' => 0);

echo "El archivo original tiene " . filesize('LICENSE') . " bytes.\n";

$da = fopen('LICENSE.compressed', 'w');
stream_filter_append($da, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($da, file_get_contents('LICENSE'));
fclose($da);

echo "El archivo comprimido tiene " . filesize('LICENSE.compressed') . " bytes.\n";

/* Genera la salida:

El archivo original tiene 3288 bytes.
El archivo comprimido tiene 1488 bytes.

 */
?>

User Contributed Notes

Anonymous 10-Feb-2021 06:37
To use the zlib.inflate filter with data originally written using gzcompress() or zlib.deflate, set the window option to 15 as outlined here: https://bugs.php.net/bug.php?id=68556

<?php
$fh = fopen(file_name, 'rb');
stream_filter_append($fh, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 15]);
$contents = stream_get_contents($fh);
fclose($fh);
bohwaz 08-Jul-2018 01:39
Please note that there is currently a bug in this feature. ftell(), fseek() and fstat() functions cannot be used. Writing to a stream after using this function will not change the stream position as it should.

See bug: https://bugs.php.net/bug.php?id=49874

Also the zlib filters don't work with php://temp, php://memory and php://input streams, nothing is outputted to those streams.
Anonymous 21-Aug-2015 06:12
To read a gzip encoded stream from http
<?php
$opts = [
    "http" => [
        "method" => "GET",
        "header" => [ "Accept-Encoding: gzip" ],
    ]
];
$ctx = stream_context_create($opts);
$f = fopen("http://php.net", "r", false, $ctx);
// check  stream_get_meta_data($f)["wrapper_data"] has "Content-Encoding: gzip"
stream_filter_append($f, "zlib.inflate", STREAM_FILTER_READ, ["window" => 30]);
echo stream_get_contents($f); // any stream processing
fclose($f);


Filtros de encriptación

Los filtros de cifrado son especialmente útiles para el cifrado de archivos y flujos.

mcrypt.* y mdecrypt.*

Advertencia

Esta característica ha sido declarada OBSOLETA a partir de PHP 7.0.1. Su uso está totalmente desaconsejado.

mcrypt.* y mdecrypt.* ofrecen encripción y desencripción simétrica usando libmcrypt. Ambos conjuntos de filtros soportan los mismos algoritmos disponibles a la extensión mcrypt en la forma de mcrypt.ciphername, en donde ciphername es el nombre del cifrado que debe ser pasado a mcrypt_module_open(). Los siguientes cinco parámetros se encuentran disponibles también:

parámetros del filtro mcrypt
Parámetro | ¿Requerido? | Por omisión | Valores de ejemplo
mode | Optional | cbc | cbc, cfb, ecb, nofb, ofb, stream
algorithms_dir | Optional | ini_get('mcrypt.algorithms_dir') | Ubicación de los módulos de los algoritmos
modes_dir | Optional | ini_get('mcrypt.modes_dir') | Ubicación de los módulos de los modos
iv | Required | N/A | Típicamente 8, 16, o 32 bytes de datos binarios. Depende del cifrado
key | Required | N/A | Típicamente 8, 16, o 32 bytes de datos binarios. Depende del cifrado

Ejemplo #1 Encriptar/Desencriptar con Blowfish

<?php
//$key que se supone que ha sido generado previamente
$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);

//desencriptar...
$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;
?>

Ejemplo #2 Encriptar el archivo usando AES-128 CBC con SHA256 HMAC en PHP 5.5+

<?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) );//marcador de posición, SHA256 HMAC irá aquí más tarde
         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 es un número del 1 al 16
         fwrite($fc, str_repeat(chr($padding), $padding) );//realizar el relleno de PKCS7
         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);//sobrescribir el marcador de posición
         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]);//asume el relleno del PKCS7
               $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.


Lista de Transportes de Sockets Soportados

Tabla de contenidos

  • Dominio de Internet: TCP, UDP, SSL, y TLS
  • Dominio Unix: Unix y UDG

La siguiente es una lista de los varios transportes de socket estilo URL que PHP tiene integrados para su uso con funciones de sockets basados en secuencias, tales como fsockopen(), y stream_socket_client(). Estos transportes no se aplican a la Extensión de Sockets.

Para una lista de transportes instalados con su versión de PHP use stream_get_transports().

User Contributed Notes

There are no user contributed notes for this page.


Dominio de Internet: TCP, UDP, SSL, y TLS

PHP 4, PHP 5. ssl:// y tls:// a partir de PHP 4.3.0, sslv2:// y sslv3:// a partir de PHP 5.0.2

Nota: Si no se especifica un transporte, se asumirá tcp://

  • 127.0.0.1
  • fe80::1
  • www.example.com
  • tcp://127.0.0.1
  • tcp://fe80::1
  • tcp://www.example.com
  • udp://www.example.com
  • ssl://www.example.com
  • sslv2://www.example.com
  • sslv3://www.example.com
  • tls://www.example.com

Los sockets del Dominio de Internet esperan un número de puerto junto con una dirección de destino. En el caso de fsockopen(), éste es especificado en un segundo parámetro y por lo tanto no tiene impacto sobre el formato de la URL de transporte. Sin embargo, en el caso de stream_socket_client() y funciones relacionadas, así como ocurre con URLs tradicionales, el número de puerto se especifica como un sufijo del URL de transporte delimitado con el signo dos puntos.

  • tcp://127.0.0.1:80
  • tcp://[fe80::1]:80
  • tcp://www.example.com:80

Nota: Direcciones IPv6 numéricas con números de puerto
En el segundo ejemplo anterior, mientras que los ejemplos IPv4 y con nombre de dominio fueron modificados solo ligeramente con la adición de sus dos puntos y número de puerto, la dirección IPv6 es rodeada por corchetes cuadrados: [fe80::1]. Esto es para poder distinguir entre los dos puntos usados en una dirección IPv6 y aquellos usados para delimitar el número de puerto.

Los transportes ssl:// y tls:// (disponibles únicamente cuando se compila el soporte para openssl con PHP) son extensiones del transporte tcp:// el cual incluye encripción SSL. A partir de PHP 4.3.0 el soporte OpenSSL debe ser compilado estáticamente con PHP, a partir de PHP 5.0.0 puede ser compilado como módulo o estáticamente.

ssl:// intentará negociar una conexión SSL V2 o SSL V3 dependiendo de las capacidades y preferencias del host remoto. sslv2:// y sslv3:// seleccionarán el protocolo SSL V2 o SSL V3 explícitamente.

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.


Dominio Unix: Unix y UDG

unix:// y udg:// (udg:// a partir de PHP 5).

  • unix:///tmp/misock
  • udg:///tmp/misock

unix:// provee acceso a una conexión secuencial de sockets en el dominio Unix. udg:// provee un transporte alternativo a un socket del dominio Unix, usando el protocolo de datagramas de usuario.

Los sockets de dominio Unix, a diferencia de los sockets del dominio de Internet, no esperan un número de puerto. En el caso de fsockopen(), el parámetro num_puerto debe ser definido como 0.

User Contributed Notes

Matthew Fortune 16-Feb-2007 03:03
It appears that fsockopen prior to php5 did not need the unix:// qualifier when opening a unix domain socket:

php4: fsockopen("/tmp/mysocket"......);

php5: fsockopen("unix:///tmp/mysocket"......);

This caught me out when upgrading.


Tablas de comparación de tipos de PHP

Las siguientes tablas demuestran el comportamiento de los tipos de PHP y los operadores de comparación, tanto para comparaciones flexibles como estrictas. Este suplemento está relacionado también con la sección del manual sobre manipulación de tipos. La inspiración proviene de varios comentarios de usuarios y del trabajo realizado en » BlueShoes.

Antes de usar estas tablas, es importante entender los tipos y sus significados. Por ejemplo, "42" es un string mientras que 42 es un integer. false es un boolean mientras "false" es un string.

Nota:

Los formularios HTML no pasan enteros, reales, o booleanos; solo pasan cadenas. Para saber si una cadena es numérica, se puede usar is_numeric().

Nota:

Hacer un simple if ($x) mientras que $x no esté definido, generará un error de nivel E_NOTICE. En lugar de esto, considere el uso de empty() o isset(), y/o inicialice sus variables.

Nota:

Algunas representaciones numéricas pueden resultar en un valor representado por la constante NAN. Cualquier comparación flexible o estricta de este valor con cualquier otro valor, incluyendo a sí mismo, excepto true, tendrá un resultado false, (esto es, NAN != NAN y NAN !== NAN). Algunos ejemplos de operaciones que producen NAN son sqrt(-1), asin(2), y acosh(0).

Comparaciones de $x con funciones PHP
Expresión | gettype() | empty() | is_null() | isset() | boolean : if($x)
$x = ""; | string | true | false | true | false
$x = null; | NULL | true | true | false | false
var $x; | NULL | true | true | false | false
$x no está definido | NULL | true | true | false | false
$x = array(); | array | true | false | true | false
$x = array('a', 'b'); | array | false | false | true | true
$x = false; | boolean | true | false | true | false
$x = true; | boolean | false | false | true | true
$x = 1; | integer | false | false | true | true
$x = 42; | integer | false | false | true | true
$x = 0; | integer | true | false | true | false
$x = -1; | integer | false | false | true | true
$x = "1"; | string | false | false | true | true
$x = "0"; | string | true | false | true | false
$x = "-1"; | string | false | false | true | true
$x = "php"; | string | false | false | true | true
$x = "true"; | string | false | false | true | true
$x = "false"; | string | false | false | true | true

Comparaciones flexibles con ==
 | true | false | 1 | 0 | -1 | "1" | "0" | "-1" | null | array() | "php" | ""
true | true | false | true | false | true | true | false | true | false | false | true | false
false | false | true | false | true | false | false | true | false | true | true | false | true
1 | true | false | true | false | false | true | false | false | false | false | false | false
0 | false | true | false | true | false | false | true | false | true | false | true | true
-1 | true | false | false | false | true | false | false | true | false | false | false | false
"1" | true | false | true | false | false | true | false | false | false | false | false | false
"0" | false | true | false | true | false | false | true | false | false | false | false | false
"-1" | true | false | false | false | true | false | false | true | false | false | false | false
null | false | true | false | true | false | false | false | false | true | true | false | true
array() | false | true | false | false | false | false | false | false | true | true | false | false
"php" | true | false | false | true | false | false | false | false | false | false | true | false
"" | false | true | false | true | false | false | false | false | true | false | false | true

Comparaciones estrictas con ===
 | true | false | 1 | 0 | -1 | "1" | "0" | "-1" | null | array() | "php" | ""
true | true | false | false | false | false | false | false | false | false | false | false | false
false | false | true | false | false | false | false | false | false | false | false | false | false
1 | false | false | true | false | false | false | false | false | false | false | false | false
0 | false | false | false | true | false | false | false | false | false | false | false | false
-1 | false | false | false | false | true | false | false | false | false | false | false | false
"1" | false | false | false | false | false | true | false | false | false | false | false | false
"0" | false | false | false | false | false | false | true | false | false | false | false | false
"-1" | false | false | false | false | false | false | false | true | false | false | false | false
null | false | false | false | false | false | false | false | false | true | false | false | false
array() | false | false | false | false | false | false | false | false | false | true | false | false
"php" | false | false | false | false | false | false | false | false | false | false | true | false
"" | false | false | false | false | false | false | false | false | false | false | false | true

User Contributed Notes

Anonymous 17-Nov-2020 02:24
I noticed that some "magic" also happens when comparing strings with leading zeros with only two equal signs:

<?php
var_dump('1' == '01');
var_dump('01' == '000001');
?>

Output:
bool(true)
bool(true)

If the string contains only numbers all leading zeroes seem to be ignored.
TrickyFoxy 02-Jan-2020 08:25
<?php
echo md5('240610708') == md5('QNKCDZO') ? "equal" : "not equal"; // prints equal!!!
php at ckls dot net 20-Aug-2018 02:50
regarding the editors note in php at richardneill dot org note:
[Editor's note: As of PHP 5.4.4 this is no longer true. Integral strings that overflow into floating point numbers will no longer be considered equal.]

While this is true, there is still the following behaviour:
<?php
$x = "1";
$y = "+1";
var_dump($x == $x);
?>
outputs "bool(true)".
So still be wary of string-comparison where both strings might be interpreted as numbers.
mark at theanti dot social 29-Mar-2018 08:59
There is also 0.0 which is not identical to 0.

  $x = 0.0;
  gettype($x); // double
  empty($x); // true
  is_null($x); //false
  isset($x); // true
  is_numeric($x); // true
  $x ? true : false; // false
  $x == 0; // true
  $x == "0"; // true
  $x == "0.0"; // true
  $x == false; // true
  $x == null; // true
  $x === 0; // false
  $x === false; // false
  $x === null; // false
  $x === "0"; // false
  $x === "0.0"; // false
alt dot jl-3gi8b7l at binich dot com 10-Mar-2018 03:41
Here's how PHP handles loose and strict comparisons of default parameters in functions:

Very unintuitive:

<?php
function f($x='surprise')
    {
    if ($x == 'surprise')
        return $x; // returns 0 !!
    }

echo f(0);
?>

Here some further tests:

<?php
function f($x='surprise')
    {
    if ($x == 'surprise')
        return 'A:'.$x;
    if ($x === 'surprise')
        return 'B:'.$x;
    return 'C:'.$x;
    }

echo "\n".f(0); // A:0 !!
echo "\n".f(0.0); // A:0 !!
echo "\n".f(NULL); // C: !!
echo "\n".f(FALSE); // C:
echo "\n".f(); // A:surprise
echo "\n".f(''); // C:
echo "\n".f((integer)0); // A:0
echo "\n".f((string)0); // C:0
echo "\n".f('0'); // C:0
echo "\n".f(0.1); // C:0.1
echo "\n".f(array()); // C:Array
echo "\n".f('surprise'); // A:surprise
?>
biziclop at vipmail dot hu 12-Aug-2017 08:57
Want to strictly compare integers that may or may not be converted to floats (via PHPExcel import/export, etc.)? You are out of luck:

var_dump(   (int)1 ===   (int)1 ); // bool(true)
var_dump( (float)1 === (float)1 ); // bool(true)
var_dump( (float)1 ===   (int)1 ); // bool(false)
var_dump(   (int)1 === (float)1 ); // bool(false)

This slightly complicated function might help you:

function equal_numbers( $a, $b ){
  if( $a === $b )  return true;
  if(   is_int( $a ) && is_float( $b ))  return (float)$a === $b && $a ===   (int)$b;
  if( is_float( $a ) &&   is_int( $b ))  return   (int)$a === $b && $a === (float)$b;
  return false;
}

Here are some tests:

test(100, 100.0 ); // int(100) float(100) bool(true)
test(  0,  -0   ); // int(0)   int(0)     bool(true)
test( -0,  -0.0 ); // int(0)   float(-0)  bool(true)
test(  0, 1/0   ); // int(0)   float(INF) bool(false)
test(  0, acos(2));// int(0)   float(NAN) bool(false)
test(       PHP_INT_MAX * 10, 0 );             //float(92233720368547758080) int(0) bool(false)
test((float)PHP_INT_MAX,     PHP_INT_MAX     );//float(9223372036854775808)  int(9223372036854775807) bool(false)
test((float)PHP_INT_MAX / 2, PHP_INT_MAX / 2 );//float(4611686018427387904)  float(4611686018427387904) bool(true)

function test( $a, $b ){
  var_dump( $a, $b, equal_numbers( $a, $b ));
}
engineer dot morozov at gmail dot com 07-Feb-2016 03:23
If you want to calculate how much more/less items by the criterion

Example:

in loop:
$counter += intval($item->isValid()) <=> 0.5;

if $counter >= 0 - valid items are more then invalid on $counter
if $counter  < 0 - valid items are less then invalid on $counter
trexx68 25-Apr-2015 05:11
If you want to view the truth tables colorized, just:

1. Save a local copy of this page as an .html file,
2. View the page source with any text editor.
3. Replace the opening <head> tag so it will include this:

<head>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

4. Replace the closing </body> tag with this:

  <script>
    $( "td:contains('FALSE')" ).css("color", "red");
    $( "td:contains('TRUE')" ).css("color", "green");
  </script>
</body>

5. Save the file, and view it on your browser.  Enjoy.
aravind dot a dot padmanabhan at gmail dot com 22-Apr-2015 02:31
please note that

$x = 0.0 ;
print empty($x); // returns 1 (true)

$x = "0.0";
print empty($x); // returns blank (false);
Anonymous 16-Oct-2014 06:19
The loose comparison chart is missing a few things.

array(1)==true returns true.

also:

(int)array(1) === 1 returns true

This is symmetric:

array(1) === (array)1 returns true

but the loose comparison

array(1)==1 still returns false.
blue dot hirano at gmail dot com 07-Sep-2014 02:29
The truth tables really ought to be colorized; they're very hard to read as they are right now (just big arrays of TRUE and FALSE).

Also, something to consider: clustering the values which compare similarly (like is done on qntm.org/equality) would make the table easier to read as well. (This can be done simply by hand by rearranging the order of headings to bring related values closer together).
Anonymous 21-Nov-2013 01:43
I'm running PHP 5.5.3.

This is a correction to one of the previous posts.

<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //false
?>

Output is:

true, false, false
crazy888s at hotmail dot com 14-Dec-2012 06:14
PHP's loose comparisons can be a huge convenience when used properly! It's extremely helpful to just remember the following are always FALSE:

null, false, "", 0, "0", array()

If your application never depends on a particular "empty/false/null/0/not set" value type, you won't have to worry about 99% of the other weird cases listed here. You won't need empty() or isset(). And ALL variable types will always work as expected for statements like:

if(boolean && !string){...}
if(array){...}
if(!null || int){...}

Consider the same when working with your database values.
php at richardneill dot org 12-Apr-2012 07:45
[Editor's note: As of PHP 5.4.4 this is no longer true. Integral strings that overflow into floating point numbers will no longer be considered equal.]

Be wary of string-comparison where both strings might be interpreted as numbers.  Eg:

$x="123456789012345678901234567890"; $y="123456789012345678900000000000";
echo  ($x==$y)?"equal":"not_equal";   #Prints equal !!

Both strings are getting converted to floats, then losing precision, then becoming equal :-(

Using "===" or making either of the strings non-numeric will prevent this.
[This is on a 32-bit machine, on a 64-bit, you will have to make the strings longer to see the effect]
Jouriy LYSENKO 17-Jun-2011 02:18
If $var not declared.

In php 5.2 :
<?php if($var) ?> - work

in php 5.3 :
<?php if($var) ?> - dont work and generate error E_NOTICE
php at benizi dot com 15-Feb-2010 10:31
It's interesting to note that 'empty()' and 'boolean : if($x)'
are paired as logical opposites, as are 'is_null()' and 'isset()'.
edgar at goodforall dot eu 15-Dec-2009 06:55
Some function to write out your own comparisson table in tsv format. Can be easily modified to add more testcases and/or binary functions. It will test all comparables against each other with all functions.

<?php
$funcs = array(
        /* Testing equality */
        'eq' => '==',
        'ne' => '!=',
        'gt' => '>',
        'lt' => '<',
        'ne2' => '<>',
        'lte' => '<=',
        'gte' => '>=',
        /* Testing identity */
        'id' => '===',
        'nid' => '!=='
);
class Test {
        protected $a;
        public $b;
        public function __construct($a,$b){
                $this->a = $a;
                $this->b = $b;
        }
        public function getab(){
                return $this->a.",". $this->b;
        }

}
$tst1 = new Test(1,2);
$tst2 = new Test(1,2);
$tst3 = new Test(2,2);
$tst4 = new Test(1,1);

$arr1 = array(1,2,3);
$arr2 = array(2,3,4);
$arr3 = array('a','b','c','d');
$arr4 = array('a','b','c');
$arr5 = array();

$comp1 = array(
        'ints' => array(-1,0,1,2),
        'floats' => array(-1.1,0.0,1.1,2.0),
        'string' => array('str', 'str1', '', '1'),
        'bools' => array(true, false),
        'null' => array(null),
        'objects' => array($tst1,$tst2,$tst3,$tst4),
        'arrays' => array($arr1, $arr2, $arr3, $arr4, $arr5)
);
$fbody = array();

foreach($funcs as $name => $op){
        $fbody[$name] = create_function('$a,$b', 'return $a ' . $op . ' $b;');
}

$table = array(array('function', 'comp1', 'comp2', 'f comp1 comp2', 'type'));
/* Do comparisons */
$comp2  = array();
foreach($comp1 as $type => $val){
        $comp2[$type] = $val;
}

foreach($comp1 as $key1 => $val1){
        foreach($comp2 as $key2 => $val2){
                addTableEntry($key1, $key2, $val1, $val2);
        }
}
$out = '';
foreach($table as $row){
        $out .= sprintf("%-20s\t%-20s\t%-20s\t%-20s\t%-20s\n", $row[0], $row[1], $row[2], $row[3], $row[4]);
}

print $out;
exit;

function addTableEntry($n1, $n2, $comp1, $comp2){
        global $table, $fbody;
        foreach($fbody as $fname => $func){
                        foreach($comp1 as $val1){
  foreach($comp2 as $val2){
                                        $val = $func($val1,$val2);
                                                $table[] = array($fname, gettype($val1) . ' => ' . sprintval($val1), gettype($val2) .' => ' . sprintval($val2), gettype($val) . ' => ' . sprintval($val), gettype($val1) . "-" . gettype($val2) . '-' . $fname);
                                        }
                        }
        }
}

function sprintval($val){
        if(is_object($val)){
                return 'object-' . $val->getab();
        }
        if(is_array($val)){
                return implode(',', $val);
        }
        if(is_bool($val)){
                if($val){
                        return 'true';
                }
                return 'false';
        }
        return strval($val);
}

?>
info at shaelf dot ru 06-Jan-2008 01:51
Compare object
<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //true
?>
frank 14-Aug-2007 03:06
A comparison table for <=,<,=>,> would be nice...
Following are TRUE (tested PHP4&5):
NULL <= -1
NULL <= 0
NULL <= 1
!(NULL >= -1)
NULL >= 0
!(NULL >= 1)
That was a surprise for me (and it is not like SQL, I would like to have the option to have SQL semantics with NULL...).
Jan 29-Dec-2005 11:23
Note that php comparison is not transitive:

"php" == 0 => true
0 == null => true
null == "php" => false
jerryschwartz at comfortable dot com 26-Jul-2005 01:04
In some languages, a boolean is promoted to an integer (with a value of 1 or -1, typically) if used in an expression with an integer. I found that PHP has it both ways:

If you add a boolean with a value of true to an integer with a value of 3, the result will be 4 (because the boolean is cast as an integer).

On the other hand, if you test a boolean with a value of true for equality with an integer with a value of three, the result will be true (because the integer is cast as a boolean).

Surprisingly, at first glance, if you use either < or > as the comparison operator the result is always false (again, because the integer as cast as a boolean, and true is neither greater nor less than true).
tom 17-Jun-2005 02:27
<?php
if (strlen($_POST['var']) > 0) {
    // form value is ok
}
?>

When working with HTML forms this a good way to:

(A) let "0" post values through like select or radio values that correspond to array keys or checkbox booleans that would return FALSE with empty(), and;
(B) screen out $x = "" values, that would return TRUE with isset()!

Because HTML forms post values as strings, this is a good way to test variables!

[[Editor Note: This will create a PHP Error of level E_NOTICE if the checked variable (in this case $_POST['var']) is undefined. It may be used after (in conjuection with) isset() to prevent this.]]
aidan at php dot net 24-Jan-2005 07:00
The way PHP handles comparisons when multiple types are concerned is quite confusing.

For example:
"php" == 0

This is true, because the string is casted interally to an integer. Any string (that does not start with a number), when casted to an integer, will be 0.


Lista de componentes léxicos del analizador

Algunas partes del lenguaje PHP son representadas internamente por tipos como T_SR. PHP produce identificadores como este a la hora de analizar errores, como "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10." ("Error de análisis: T_SR inesperado, se esperaba ',' o ';' en script.php en la línea 10.")

Se supone que uno debería saber lo qué significa T_SR. Para todo aquél que no lo sepa, se muestra una tabla con dichos identificadores, la sintaxis de PHP y referencias al apartado apropiado del manual.

Nota: Uso de las constantes T_*

Todos los componentes léxicos (o tokens) enumerados abajo también están definidos como constantes de PHP. Sus valores son automáticamente generados basándose en la infraestructura del analizador subyacente de PHP. Esto significa que el valor concreto de un componenete léxico puede cambiar entre dos versiones de PHP. Por ejemplo, la constante T_FILE es 365 en PHP 5.3, mientras que el mismo valor se refiere ahora a T_TRAIT en PHP 5.4, y el valor de T_FILE es 369. Esto sigifica que el código no debería nunca depender directamente de los valores originales de las constantes T_* tomadas de la versión X.Y.Z de PHP, para proporcionar cierta compatibildad entre múltiples versiones PHP. En su lugar, el código debería utilizar valores personalizados (usando números grandes como 10000) y una estrategia apropiada que funcione tanto con las versiones de PHP como con los valores de las constantes T_*.

Componente léxico
Elemento | Sintaxis | Referencia
T_ABSTRACT | abstract | Abstracción de clases (disponible desde PHP 5.0.0)
T_AND_EQUAL | &= | operadores de asignación
T_ARRAY | array() | array(), sintaxis de array
T_ARRAY_CAST | (array) | conversión de tipos
T_AS | as | foreach
T_BAD_CHARACTER |  | todo lo que haya por debajo de ASCII 32 excepto \t (0x09), \n (0x0a) y \r (0x0d)
T_BOOLEAN_AND | && | operadores lógios
T_BOOLEAN_OR | || | operadores lógicos
T_BOOL_CAST | (bool) o (boolean) | conversión de tipos
T_BREAK | break | break
T_CALLABLE | callable | callable
T_CASE | case | switch
T_CATCH | catch | Excepciones (disponible desde PHP 5.0.0)
T_CHARACTER |  | ya no se utiliza
T_CLASS | class | clases y objetos
T_CLASS_C | __CLASS__ | constantes mágicas
T_CLONE | clone | clases y objetos
T_CLOSE_TAG | ?> o %> | salir de HTML
T_COMMENT | // o #, y /* */ | comentarios
T_CONCAT_EQUAL | .= | operadores de asignación
T_CONST | const | constantes
T_CONSTANT_ENCAPSED_STRING | "foo" o 'bar' | sintaxis de string
T_CONTINUE | continue | continue
T_CURLY_OPEN | {$ | sintaxis compleja
T_DEC | -- | operadores de incremento/decremento
T_DECLARE | declare | declare
T_DEFAULT | default | switch
T_DIR | __DIR__ | constantes mágicas (disponible desde PHP 5.3.0)
T_DIV_EQUAL | /= | operadores de asignación
T_DNUMBER | 0.12, etc. | números de punto flotante
T_DOC_COMMENT | /** */ | comentarios tipo PHPDoc
T_DO | do | do..while
T_DOLLAR_OPEN_CURLY_BRACES | ${ | sintaxis compleja
T_DOUBLE_ARROW | => | sintaxis de array
T_DOUBLE_CAST | (real), (double) o (float) | conversión de tipos
T_DOUBLE_COLON | :: | véase T_PAAMAYIM_NEKUDOTAYIM más abajo
T_ECHO | echo | echo
T_ELLIPSIS | ... | argumentos de función (disponible desde PHP 5.6.0)
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE | " $a" | parte constante de un string con variables
T_ENDDECLARE | enddeclare | declare, sintaxis alternativa
T_ENDFOR | endfor | for, sintaxis alternativa
T_ENDFOREACH | endforeach | foreach, sintaxis alternativa
T_ENDIF | endif | if, sintaxis alternativa
T_ENDSWITCH | endswitch | switch, sintaxis alternativa
T_ENDWHILE | endwhile | while, sintaxis alternativa
T_END_HEREDOC |  | sintaxis de heredoc
T_EVAL | eval() | eval()
T_EXIT | exit o die | exit(), die()
T_EXTENDS | extends | extends, clases y objetos
T_FILE | __FILE__ | constantes mágicas
T_FINAL | final | Palabra clave Final
T_FINALLY | finally | Excepciones (disponible desde PHP 5.5.0)
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function o cfunction | funciones
T_FUNC_C | __FUNCTION__ | constantes mágicas
T_GLOBAL | global | ámbito de las variables
T_GOTO | goto | (disponible desde PHP 5.3.0)
T_HALT_COMPILER | __halt_compiler() | __halt_compiler (disponible desde PHP 5.1.0)
T_IF | if | if
T_IMPLEMENTS | implements | Interfaces de objetos
T_INC | ++ | operadores de incremento/decremento
T_INCLUDE | include() | include
T_INCLUDE_ONCE | include_once() | include_once
T_INLINE_HTML |  | texto fuera de PHP
T_INSTANCEOF | instanceof | operadores de tipo
T_INSTEADOF | insteadof | Rasgos (Traits) (disponible desde PHP 5.4.0)
T_INT_CAST | (int) o (integer) | conversión de tipos
T_INTERFACE | interface | Interfaces de objetos
T_ISSET | isset() | isset()
T_IS_EQUAL | == | operadores de comparación
T_IS_GREATER_OR_EQUAL | >= | operadores de comparación
T_IS_IDENTICAL | === | operadores de comparación
T_IS_NOT_EQUAL | != o <> | operadores de comparación
T_IS_NOT_IDENTICAL | !== | operadores de comparación
T_IS_SMALLER_OR_EQUAL | <= | operadores de comparación
T_SPACESHIP | <=> | operadores de comparación (disponible desde PHP 7.0.0)
T_LINE | __LINE__ | constantes mágicas
T_LIST | list() | list()
T_LNUMBER | 123, 012, 0x1ac, etc. | números enteros
T_LOGICAL_AND | and | operadores lógicos
T_LOGICAL_OR | or | operadores lógicos
T_LOGICAL_XOR | xor | operadores lógicos
T_METHOD_C | __METHOD__ | constantes mágicas
T_MINUS_EQUAL | -= | operadores de asignación
T_MOD_EQUAL | %= | operadores de asignación
T_MUL_EQUAL | *= | operadores de asignación
T_NAMESPACE | namespace | espacios de nombres (disponible desde PHP 5.3.0)
T_NS_C | __NAMESPACE__ | espacios de nombres (disponible desde PHP 5.3.0)
T_NS_SEPARATOR | \ | espacios de nombres (disponible desde PHP 5.3.0)
T_NEW | new | clases y objectos
T_NUM_STRING | "$a[0]" | array de índice numérico dentro de un string
T_OBJECT_CAST | (object) | conversión de tipos
T_OBJECT_OPERATOR | -> | clases y objetos
T_OPEN_TAG | <?php, <? o <% | salir de HTML
T_OPEN_TAG_WITH_ECHO | <?= o <%= | salir de HTML
T_OR_EQUAL | |= | operadores de asignación
T_PAAMAYIM_NEKUDOTAYIM | :: | ::. También se define como T_DOUBLE_COLON.
T_PLUS_EQUAL | += | operadores de asignación
T_POW | ** | operadores aritméticos (disponible desde PHP 5.6.0)
T_POW_EQUAL | **= | operadores de asignación (disponible desde PHP 5.6.0)
T_PRINT | print() | print
T_PRIVATE | private | clases y objetos
T_PUBLIC | public | clases y objetos
T_PROTECTED | protected | clases y objetos
T_REQUIRE | require() | require
T_REQUIRE_ONCE | require_once() | require_once
T_RETURN | return | valores de retorno
T_SL | << | operadores a nivel de bits
T_SL_EQUAL | <<= | operadores de asignación
T_SR | >> | operadores a nivel de bits
T_SR_EQUAL | >>= | operadores de asignación
T_START_HEREDOC | <<< | sintaxis de heredoc
T_STATIC | static | ámbito de las variables
T_STRING | parent, self, etc. | se comparan identificadores, p.ej. palabras clave como parent y self, nombres de funciones, nombres de clases y más. Véase también T_CONSTANT_ENCAPSED_STRING.
T_STRING_CAST | (string) | conversión de tipos
T_STRING_VARNAME | "${a | sintaxis compleja
T_SWITCH | switch | switch
T_THROW | throw | Excepciones
T_TRAIT | trait | Rasgos (Traits) (disponible desde PHP 5.4.0)
T_TRAIT_C | __TRAIT__ | __TRAIT__ (disponible desde PHP 5.4.0)
T_TRY | try | Excepciones
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | conversión de tipos
T_USE | use | espacios de nombres (disponible desde PHP 5.3.0; reservada desde PHP 4.0.0)
T_VAR | var | clases y objetos
T_VARIABLE | $foo | variables
T_WHILE | while | while, do..while
T_WHITESPACE | \t \r\n |
T_XOR_EQUAL | ^= | operadores de asignación
T_YIELD | yield | generadores (disponible desde PHP 5.5.0)

Véase también 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.


Guía de entorno de usuario para nombres

Tabla de contenidos

  • Global Namespace
  • Reglas
  • Tips

La siguiente es una guía para saber cómo elegir el mejor nombre para los identificadores del código del entorno del usuario PHP. Cuando se eligen nombres para cualquier código que crea símbolos en el global namespace, es importante tener en cuenta los siguientes lineamientos para evitar que en futuras versiones de PHP estos choquen con los símbolos elegidos.

User Contributed Notes

There are no user contributed notes for this page.


Global Namespace

Aquí hay una visión general de las construcciones de código que van al espacio de nombres global:

  • funciones

  • clases

  • interfaces

  • constantes (no constanstes de clase)

  • variables definidas fuera de funciones/métodos

User Contributed Notes

There are no user contributed notes for this page.


Reglas

La siguiente lista muestra un resumen de los derechos que se reserva el proyecto PHP para sí mismo, cuando elige los nombres para los nuevos identificadores internos. La guía definitiva son los » ESTÁNDARES DE CODIFICACION oficiales:

  • PHP es el propietario de el namespace de nivel superior, pero trata de encontrar una descripción decente de nombres y evitar así futuros choques.

  • Los nombres de función usan guion bajo entre palabras, mientras que los nombres de las clases usan las reglas camelCase o PascalCase.

  • PHP antepondrá a cualquier símbolo global de una extensión el nombre de de la extensión. (En el pasado, han habido numerosas excepciones a esta regla). Ejemplos:

    • curl_close()

    • mysql_query()

    • PREG_SPLIT_DELIM_CAPTURE

    • new DOMDocument()

    • strpos() (ejemplo de un error del pasado)

    • new SplFileObject()

  • Iteradores y Excepciones son como siempre, simplemente postfijados con "Iterator" y Exception." Ejemplos:

    • ArrayIterator

    • LogicException

  • PHP se reserva todos los simbolos que comienzan con __ como magicos. Es recomendado que no se creen simbolos que comiencen con __ en PHP a menos que se quiera usar una funcionalidad magica documentada. Ejemplos:

    • __get()

    • __autoload()

User Contributed Notes

There are no user contributed notes for this page.


Tips

Con el fin de escribir código que funcione en el futuro, se recomienda no colocar muchas variables, funciones o clases en el espacio de nombres global. Esto prevendrá de conflictos de nombres con código de terceros así como con posibles adiciones futuras al lenguaje.

Una manera común de evitar conflictos con nombres de funciones y clases es añadirlos a su propio espacio de nombres dedicado.

<?php

namespace MiProyecto;

function mi_función() {
    return true;
}

\MiProyecto\mi_función();

Esto todavía necesita que se mantenga la cuenta de los espacios de nombres ya utilizados, pero una vez que se decido el espacio de nombres que se va a usar se pueden añadir todas las funciones y clases e él sin tener que pensar más en conflictos.

Es una buena práctica limitar el número de variables añadidas al ámbito global para evitar conflictos de nombres con código de terceros.

Nota: Ámbito de variables

Debido a las reglas de ámbito de PHP, las variables definidas dentro de funciones y métodos no están en el ámbito global y, por tanto, no pueden crear conflictos con otras variables definidas en el ámbito global.

User Contributed Notes

There are no user contributed notes for this page.


Acerca del manual

Tabla de contenidos

  • Formatos
  • Acerca de los comentarios de usuarios
  • Como interpretar la definición de una función (prototipo)
  • Versiones de PHP documentadas en este manual
  • Cómo encontrar más información sobre PHP
  • Cómo ayudar a mejorar la documentación
  • Cómo generamos los formatos
  • Traducciones

User Contributed Notes

There are no user contributed notes for this page.


Formatos

El manual de PHP se encuentra disponible en diferentes formatos. Estos formatos se pueden dividir en dos grupos: formato accesible online y ficheros descargables.

Nota:

Algunas editoriales han publicado versiones impresas de este manual. No podemos recomendar ninguna de ellas, ya que suelen quedarse obsoletas rápidamente.

El manual puede ser leído online en » sitio web de PHP.net y en numerosos mirrors. Para un mejor funcionamiento, debería utilizar el mirror más cercano. La versión online del manual PHP tiene dos hojas de estilos CSS CSS, una para web y la otra para imprimir.

La ventaja del manual online sobre la mayoría de formatos offline es que contiene los comentarios/notas de usuarios y los » enlaces URL que pueden ser usados para llegar rápidamente hasta las partes deseadas del manual. Y obviamente, la desventaja es que se requiere estár online para ver este manual.

Existen varios formatos offline. El más apropiado para cada usuario depende del sistema operativo que use y de sus preferencias a la hora de leer. La información sobre como el manual es generado en tantos formatos diferentes se puede obtener en la sección de este apéndice titulada 'Cómo generamos los diferentes formatos' sección de su apéndice.

El formato más accesible desde diferentes plataformas es la versión HTML. Este manual se ofrece como un único fichero en HTML o como un paquete que contiene un fichero HTML por cada sección (colección de varios cientos de ficheros). Se proporcionan estas versiones de forma comprimida, por tanto, se require una utilidad para obtener los ficheros desde el archivo comprimido.

Para plataformas Windows, la versión Windows HTML Help Workshop mejora la versión del manual en HTML, al poder usar la aplicación Windows HTML Help Workshop. Esta versión proporciona: búsqueda completa de texto, índice completo y favoritos. Muchos entornos de desarrollo para PHP incorporan esta versión de la documentación para proporcionar un acceso fácil . También hay visores CHM disponibles para Linux. Dale un vistazo a » xCHM o » GnoCHM.

También está disponible la » versión extendida de CHM , la cual se actualiza menos frecuentemente, pero proporciona otras muchas opciones. Solamente funciona con Microsoft Windows debido a la tecnología utilizada para crear estas páginas de ayuda.

User Contributed Notes

There are no user contributed notes for this page.


Acerca de los comentarios de usuarios

Los comentarios de los usuarios juegan un papel muy importante en el desarrollo de este manual. Permitir a los lectores del manual contribuir con ejemplos y aclaraciones desde su navegador, hace que podamos mejorar el manual. Y mientras los comentarios no formen parte del manual, podrán ser consultados online y también en algunos de los soportes offline.

Nota:

Los comentarios de los usuarios no son moderados antes de ser publicados online, así que la calidad de lo escrito como los ejemplos o incluso la veracidad de lo expuesto en el comentario no podrá ser garantizada. (Tampoco hay ninguna garantía de la calidad o exactitud del texto del manual).

Nota:

Por propósito de la cobertura de la licencia, los comentarios contribuidos por los usuarios son considerados partes del manual PHP, y tienen el mismo tipo de licencia que la documentación (por el momento Creative Commons Attribution) Para más información vea la página Copyright del Manual

User Contributed Notes

There are no user contributed notes for this page.


Como interpretar la definición de una función (prototipo)

Cada función en el manual está documentada para obtener una referencia rápida. Si sabemos como leer e interpretar el manual será mucho más fácil aprender PHP. En lugar de confiar en ejemplos o copiar y pegar, todo el mundo debería saber como interpretar una definición de funciones (prototipos). Empecemos:

Nota: Prerrequisitos: Comprensión básica de los diferentes tipos

Aunque PHP es un lenguaje de programación relajado (en lo referente a los tipos de variables/valores), es importante entender, básicamente, estos diferentes tipos, ya que son importantes.

Las definiciones de funciones nos dicen que tipo de valores son valores de retorno. Usemos la definición de la función strlen() en nuestro primer ejemplo:

strlen

(PHP 4, PHP 5)
strlen -- Obtiene longitud de un string

Descripción
int strlen ( string $string )

Devuelve longitud de un string

Explicación de la definición de una función
Parte | Descripción
strlen | El nombre de la función.
(PHP 4, PHP 5) | strlen() está disponible en todas las versiones de PHP 4, PHP 5
int | Tipo de valor devuelto por esta función, en este caso un entero (ejemplo: la longitud de un string se mide en números).
( string $string ) | El primer (sólo para este caso) parámetro o argumento para esta función se llama string, y es de tipo string.

Podríamos escribir la definición de esta función de un modo genérico:

      tipo de retorno    nombre función    ( tipo de parámetro   nombre parámetro )

Muchas funciones tiene múltiples parametros, por ejemplo in_array(). Su prototipo sería:

      boleano in_array ( mixto $aguja, array $pajar [, boleano $estricto = FALSE])

¿Qué significa? in_array() devuelve un valor booleano, true si termina con éxito (Si la aguja fue encontrada en el pajar) o false en caso de error (si la aguja no fue encontrada en el pajar). El primer parámetro se llama aguja y puede ser de muchos tipos, así que lo llamamos "mixto". Este mixtoaguja (que es lo que estamos buscando) bien puede ser un valor escalar (string, integer, o float), o un array. El pajar (el array en el que buscamos) es el segundo parámetro. El tercero es un parámetro opcional y lo llamamos estricto. Todos los parámetros opcionales están entre [ paréntesis ]. El manual muestra que el parámetro estricto es por defecto booleano false. Vea la página del manual de cada función para informarse de cómo funcionan.

Además, el símbolo & (et) antepuesto a un parámetro de función permite que dicho parámetro sea pasado por referencia, como se muestra abajo:

       int preg_match ( string $pattern , string $subject [, array &$matches
      [, int $flags = 0 [, int $offset = 0 ]]] )

En este ejemplo se puede ver que el tercer parámetro opcional &$matches será pasado por referencia.

También hay funciones con información PHP mucho más compleja. Toma html_entity_decode() como ejemplo:

(PHP 4 >= 4.3.0, PHP 5)

Esto significa que esta función solo está disponible desde la versión PHP 4.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Versiones de PHP documentadas en este manual

Este manual contiene información sobre anteriores, actuales y futuras versiones de PHP. Cambios en el comportamiento están documentados como notas, changelogs y texto en las páginas del manual. La versión más antigua documentada es PHP 5.0.0.

Cuando existe documentación sobre la última versión (no lanzada) en desarrollo de PHP, será etiquetada como "disponible en Git" o "versión de desarrollo". Y si bien estos cambios se deben planificar, en casos raros pueden cambiar.

Todo el desarrollo se lleva a cabo en Git y puede ser corroborado como se describe en la página » acceso anónimo a Git.

Y para aclarar, el manual se referirá a lanzamientos generales, secundarios y específicos PHP. Tomemos PHP 5.3.1 como ejemplo, entonces el 5 hace referencia a la versión general, el 3 a la secundaria, y el 1 es el lanzamiento específico. Normalmente PHP sólo añade nuevas características a los lanzamientos generales y secundarios, y corrige bugs en los específicos. Sin embargo, Esta convención no siempre es cierta.

También tome en cuenta que el manual de PHP está escrito en presente, no en futuro, incluso para documentar características que todavía no están disponibles. La razón de esto es que el manual puede superar la prueba del tiempo, por lo que no requiere de tediosas actualizaciones gramáticas con cada lanzamiento.

Muchas veces el manual de PHP muestra "valores por defecto" para las directivas PHP. Estos valores están basados en cómo actúa PHP sin un archivo de configuración php.ini, y por tanto pueden diferir de los valores encontrados en los archivos php.ini-development y php.ini-production distribuidos. también hacen referencia a la última versión de PHP, aunque las entradas de changelog hacen mención de valores antiguos. Vea el Apéndice de directivas PHP para detalles con respecto a estos valores y sus cambios.

User Contributed Notes

There are no user contributed notes for this page.


Cómo encontrar más información sobre PHP

Este manual no pretende dar prácticas de programación en general. Si es su primera vez o es un principiante, seguramente encontrará difícil aprender como programar con PHP usando solamente este manual. Busque mejor un libro orientado a principiantes.

Hay un gran número de listas de correo activas para discutir cualquier aspecto relacionado con la programación con PHP. Si se queda bloqueado con un problema, puede usar estas listas para obtener ayuda. Para ver las opciones de soporte, incluidas listas de correo, ver » página de soporte de PHP.net.

User Contributed Notes

There are no user contributed notes for this page.


Cómo ayudar a mejorar la documentación

Hay tres formas en la que todo el mundo puede ayudar a mejorar esta documentación.

Si hay un error en el manual, en cualquier idioma, por favor infórmenos usando el sistema de informe de errores » https://bugs.php.net/. Clasifique el error como "Documentation Problem". Cualquier problema relacionado con la documentación, incluyendo manuales en diferentes formatos, deben ser enviados como bug.

Nota:

Por favor, no abusar del sistema de informes de errores mandando peticiones de ayuda. En su lugar, utilice las listas de correos y recursos mencionados anteriormente. » soporte de PHP.

Contribuyendo con comentarios, se pueden dar ejemplos, advertencias y aclaraciones para otros lectores. Pero por favor no utilice el sistema de informe de errores, utilice el sistema de comentarios. Para más información, vea la sección titulada 'Acerca de comentarios de los usuarios'.

También es posible enviar pull requests al » repositorio de documentación espejo en Github.

El manual de PHP es traducido a muchos otros idiomas. Si sabe inglés y otro idioma extranjero puede ayudar a mejorar el manual de PHP trabajando con el equipo de traducción. Para más información de como empezar una nueva traducción o ayudar con la traducción, por favor lea » http://doc.php.net/tutorial/.

El proyecto de la documentación de PHP también tiene un canal de IRC donde muchos de los autores se reúnen. Pase por #php.doc o irc.efnet.org y podremos discutir formas de mejorar la documentación de PHP.

User Contributed Notes

There are no user contributed notes for this page.


Cómo generamos los formatos

Este manual está escrito en XML usando » DocBook XML DTD, y » PhD (El render [D]ocBook basado en[PH]P ) para el mantenimiento y formato.

Usamos XML como base, para generar diferentes formatos, centralizando un solo código fuente para todos los diferentes formatos del manual. Utilizamos la herramienta » PhD para crear las páginas del manual online. También usamos » Microsoft HTML Help Workshop para generar el formato de ayuda Windows HTML y por supuesto usamos PHP para crear algunas conversiones adicionales y formateado.

El manual de PHP es generado en varios idiomas y formatos, ver » https://www.php.net/docs.php para más información. El código fuente XML puede ser descargado desde Git y visualizado en » https://github.com/php/doc-en".

User Contributed Notes

There are no user contributed notes for this page.


Traducciones

El manual de PHP no solamente está disponible en diferentes formatos, tambien se encuentra en diferentes idiomas. El manual es escrito primero en inglés y luego grupos de traductores de todo el mundo se encargan de mantener la traducción a su idioma sincronizada con la versión inglesa. Si la traducción de algún apartado del manual no ha sido realizada todavía por el equipo de traductores, este aparecerá en inglés hasta que sea traducido.

Las personas involucradas en las traducciones, utilizan el código fuente en XML disponible en » https://github.com/php/doc-en" y lo traducen a su idioma. No utilizan las versiones generadas (como HTML o texto plano) Es el sistema de generación de formatos el que se encarga de producirlos a partir de XML a formatos de lectura legibles por humanos.

Nota:

Si le interesa ayudar o participar en la traducción de la documentación a su idioma, póngase en contacto con el equipo de traducción/documentación apuntándose a la lista de correo phpdoc. Mande un mensaje vacio a » phpdoc-subscribe@lists.php.net. La dirección de la esta lista de correo es phpdoc@lists.php.net. Explique que está interesado en traducir el manual a un idioma y nos pondremos en contacto con usted. Le mandaremos información para que pueda empezar una nueva traducción o para que pase a formar parte del equipo de traducción de su idioma, si este ya existe.

Por el momento el idioma está disponible, parcialmente o no, en 10 idiomas.

Puede ser descargado desde: » 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.


Listado de índices

Tabla de contenidos

  • Listado de Funciones y Métodos
  • Listado de ejemplos

User Contributed Notes

There are no user contributed notes for this page.


Listado de Funciones y Métodos

Lista todas las funciones y métodos del manual

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 - Valor absoluto
    • acos - Arco coseno
    • acosh - Arco coseno hiperbólico
    • addcslashes - Escapa una cadena al estilo de C
    • addslashes - Escapa un string con barras invertidas
    • apache_child_terminate - Finaliza un proceso de Apache después de esta llamada
    • apache_getenv - Obtiene una variable del entorno subprocess_env de Apache
    • apache_get_modules - Obtiene una lista de los módulos cargados en el servidor Apache
    • apache_get_version - Obtiene la versión del servidor Apache
    • apache_lookup_uri - Realiza una petición parcial por la URI especificada y devuelve toda la información sobre ella
    • apache_note - Obtiene y establece las notas de petición de apache
    • apache_request_headers - Obtiene todas las cabeceras HTTP
    • apache_response_headers - Obtiene todas las cabeceras HTTP de respuesta
    • apache_setenv - Establece una variable subprocess_env de Apache
    • APCUIterator::current - Obtener el elemento actual
    • APCUIterator::getTotalCount - Obtiene el conteo total
    • APCUIterator::getTotalHits - Obtener resultados totales de la memoria caché
    • APCUIterator::getTotalSize - Obtiene el tamaño total del caché
    • APCUIterator::key - Obtiene la clave del iterador
    • APCUIterator::next - Mueve el puntero al siguiente elemento
    • APCUIterator::rewind - Rebobina el iterador
    • APCUIterator::valid - Comprueba si la posición actual es válida
    • APCUIterator::__construct - Construye un objeto iterador APCUIterator
    • apcu_add - Cache a new variable in the data store
    • apcu_cache_info - Recupera la información almacenada en la memoria APCu
    • apcu_cas - Actualiza un valor antiguo con un nuevo valor
    • apcu_clear_cache - Limpia el caché del APCu
    • apcu_dec - Disminuir un número almacenado
    • apcu_delete - Elimina una variable almacenada en caché
    • apcu_enabled - Si el APCu es utilizable en el entorno actual
    • apcu_entry - Atomically fetch or generate a cache entry
    • apcu_exists - Checks if entry exists
    • apcu_fetch - Fetch a stored variable from the cache
    • apcu_inc - Increase a stored number
    • apcu_key_info - Get detailed information about the cache key
    • apcu_sma_info - Retrieves APCu Shared Memory Allocation information
    • apcu_store - Cache a variable in the data store
    • AppendIterator::append - Añade un iterador
    • AppendIterator::current - Obtiene el valor actual
    • AppendIterator::getArrayIterator - Obtiene el getArrayIterator
    • AppendIterator::getInnerIterator - Obtiene el iterador interno
    • AppendIterator::getIteratorIndex - Obtiene un índice de iteradores
    • AppendIterator::key - Obtiene la clave actual
    • AppendIterator::next - Desplazarse al siguiente elemento
    • AppendIterator::rewind - Rebobina el iterador
    • AppendIterator::valid - Comprueba la validación del elemento actual
    • AppendIterator::__construct - Construye un AppendIterator
    • array - Crea un array
    • ArrayAccess::offsetExists - Comprobar si existe un índice
    • ArrayAccess::offsetGet - Offset para recuperar
    • ArrayAccess::offsetSet - Asignar un valor al índice esepecificado
    • ArrayAccess::offsetUnset - Destruye un offset
    • ArrayIterator::append - Añade un elemento
    • ArrayIterator::asort - Ordena array por sus valores
    • ArrayIterator::count - Cuenta elementos
    • ArrayIterator::current - Devuelve la entrada actual del array
    • ArrayIterator::getArrayCopy - Obtener copia de un array
    • ArrayIterator::getFlags - Obtener opciones
    • ArrayIterator::key - Devuelve la clave actual del array
    • ArrayIterator::ksort - Ordena un array por sus claves
    • ArrayIterator::natcasesort - Ordena un array de forma natural, sensible a mayúsculas
    • ArrayIterator::natsort - Ordena un array de forma natural
    • ArrayIterator::next - Desplaza a la siguiente entrada
    • ArrayIterator::offsetExists - Compruebar si el índice existe
    • ArrayIterator::offsetGet - Obtener el valor de un índice
    • ArrayIterator::offsetSet - Establece el valor para un índice
    • ArrayIterator::offsetUnset - Destruye el valor de un índice
    • ArrayIterator::rewind - Rebobinar array al inicio
    • ArrayIterator::seek - Buscar la posición
    • ArrayIterator::serialize - Serializar
    • ArrayIterator::setFlags - Definir opciones de comportamiento
    • ArrayIterator::uasort - Ordenado definido por el usuario
    • ArrayIterator::uksort - Ordenado definido por el usuario
    • ArrayIterator::unserialize - Deserializar
    • ArrayIterator::valid - Comprueba si un array contiene más entradas
    • ArrayIterator::__construct - Construye un ArrayIterator
    • ArrayObject::append - Añade un valor
    • ArrayObject::asort - Ordena las entradas por valor
    • ArrayObject::count - Obtener el número de propiedades públicas en la clase ArrayObject
    • ArrayObject::exchangeArray - Intercambia el array por otro
    • ArrayObject::getArrayCopy - Crea una copia de la clase ArrayObject
    • ArrayObject::getFlags - Obtiene las flags de comportamiento
    • ArrayObject::getIterator - Crear un nuevo iterador desde una instancia ArrayObject
    • ArrayObject::getIteratorClass - Obtiene el nombre de clase iterador para ArrayObject
    • ArrayObject::ksort - Ordena las entradas por clave
    • ArrayObject::natcasesort - Ordena un array usando un algoritmo orden natural
    • ArrayObject::natsort - Ordena entradas usando un algoritmo de orden natural
    • ArrayObject::offsetExists - Devuelve si el índice solicitado existe
    • ArrayObject::offsetGet - Devuelve el valor del índice especificado
    • ArrayObject::offsetSet - Establece el valor en el índice especificado
    • ArrayObject::offsetUnset - Destruye el valor para el índice especificado
    • ArrayObject::serialize - Serializar un ArrayObject
    • ArrayObject::setFlags - Establece las flags de comportamiento
    • ArrayObject::setIteratorClass - Establece el nombre de clase iterador para ArrayObject
    • ArrayObject::uasort - Ordena las entradas con una función de comparación definida por el usuario y mantiene asociación de claves
    • ArrayObject::uksort - Ordena las entradas por clave usando una función de comparación definida por el usuario
    • ArrayObject::unserialize - Deserializar el objeto ArrayObject
    • ArrayObject::__construct - Construir un nuevo objeto Array
    • array_change_key_case - Cambia a mayúsculas o minúsculas todas las claves en un array
    • array_chunk - Divide un array en fragmentos
    • array_column - Devuelve los valores de una sola columna del array de entrada
    • array_combine - Crea un nuevo array, usando una matriz para las claves y otra para sus valores
    • array_count_values - Cuenta todos los valores de un array
    • array_diff - Calcula la diferencia entre arrays
    • array_diff_assoc - Calcula la diferencia entre arrays con un chequeo adicional de índices
    • array_diff_key - Calcula la diferencia entre arrays empleando las claves para la comparación
    • array_diff_uassoc - Calcula la diferencia entre arrays con un chequeo adicional de índices que se realiza por una función de devolución de llamada suministrada por el usuario
    • array_diff_ukey - Calcula la diferencia entre arrays usando una función de devolución de llamada en las keys para comparación
    • array_fill - Llena un array con valores
    • array_fill_keys - Llena un array con valores, especificando las keys
    • array_filter - Filtra elementos de un array usando una función de devolución de llamada
    • array_flip - Intercambia todas las claves de un array con sus valores asociados
    • array_intersect - Calcula la intersección de arrays
    • array_intersect_assoc - Calcula la intersección de arrays con un chequeo adicional de índices
    • array_intersect_key - Calcula la intersección de arrays usando sus claves para la comparación
    • array_intersect_uassoc - Calcula la intersección de arrays con una comprobación adicional de índices, los cuales se comparan con una función de retrollamada
    • array_intersect_ukey - Calcula la intersección de arrays usando una función de devolución de llamada en las claves para la comparación
    • array_keys - Devuelve todas las claves de un array o un subconjunto de claves de un array
    • array_key_exists - Verifica si el índice o clave dada existe en el array
    • array_key_first - Obtiene la primera clave de un array
    • array_key_last - Obtiene la última clave de un array
    • array_map - Aplica la retrollamada a los elementos de los arrays dados
    • array_merge - Combina dos o más arrays
    • array_merge_recursive - Une dos o más arrays recursivamente
    • array_multisort - Ordena varios arrays, o arrays multidimensionales
    • array_pad - Rellena un array a la longitud especificada con un valor
    • array_pop - Extrae el último elemento del final del array
    • array_product - Calcula el producto de los valores de un array
    • array_push - Inserta uno o más elementos al final de un array
    • array_rand - Seleccionar una o más claves aleatorias de un array
    • array_reduce - Reduce iterativamente un array a un solo valor usando una función llamada de retorno
    • array_replace - Reemplaza los elementos del array original con elementos de array adicionales
    • array_replace_recursive - Reemplaza los elementos de los arrays pasados al primer array de forma recursiva
    • array_reverse - Devuelve un array con los elementos en orden inverso
    • array_search - Busca un valor determinado en un array y devuelve la primera clave correspondiente en caso de éxito
    • array_shift - Quita un elemento del principio del array
    • array_slice - Extraer una parte de un array
    • array_splice - Elimina una porción del array y la reemplaza con otra cosa
    • array_sum - Calcular la suma de los valores de un array
    • array_udiff - Computa la diferencia entre arrays, usando una llamada de retorno para la comparación de datos
    • array_udiff_assoc - Computa la diferencia entre arrays con una comprobación de indices adicional, compara la información mediante una función de llamada de retorno
    • array_udiff_uassoc - Computa la diferencia entre arrays con una verificación de índices adicional, compara la información y los índices mediante una función de llamada de retorno
    • array_uintersect - Computa una intersección de arrays, compara la información mediante una función de llamada de retorno
    • array_uintersect_assoc - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información mediante una función de retrollamada
    • array_uintersect_uassoc - Calcula la intersección de arrays con una comprobación de índices adicional, compara la información y los índices mediante funciones de retrollamada por separado
    • array_unique - Elimina valores duplicados de un array
    • array_unshift - Añadir al inicio de un array uno a más elementos
    • array_values - Devuelve todos los valores de un array
    • array_walk - Aplicar una función proporcionada por el usuario a cada miembro de un array
    • array_walk_recursive - Aplicar una función de usuario recursivamente a cada miembro de un array
    • arsort - Ordena un array en orden inverso y mantiene la asociación de índices
    • Aserción - Verifica si la aserción es false
    • asin - Arco seno
    • asinh - Arco seno hiperbólico
    • asort - Ordena un array y mantiene la asociación de índices
    • assert_options - Establecer/obtener valores de las directivas relacionadas con las aserciones
    • atan - Arco tangente
    • atan2 - Arco tangente de dos variables
    • atanh - Arco tangente hiperbólica
  • b
    • base64_decode - Decodifica datos codificados con MIME base64
    • base64_encode - Codifica datos con MIME base64
    • basename - Devuelve el último componente de nombre de una ruta
    • base_convert - Convertir un número entre bases arbitrarias
    • bcadd - Añade dos números de precisión arbitrária
    • bccomp - Compara dos números de precisión arbitraria
    • bcdiv - Divide dos números de precisión arbitraria
    • bcmod - Obtiene el módulo de un número de precisión arbitraria
    • bcmul - Multiplica dos números de precisión arbitraria
    • bcpow - Elevar un número de precisión arbitraria a otro
    • bcpowmod - Eleva un número de precisión arbitraria a otro, reducido por un módulo especificado
    • bcscale - Establece los parametros de scale por defecto para todas las funciones matemáticas de bc
    • bcsqrt - Obtiene la raiz cuadrada de un número de precisión arbitraria
    • bcsub - Resta un número de precisión arbitraria de otro
    • bin2hex - Convierte datos binarios en su representación hexadecimal
    • bindec - Binario a decimal
    • bindtextdomain - Establece la ruta del dominio
    • bind_textdomain_codeset - Especifica el juego de caracteres en que los mensajes del catálogo del dominio serán devueltos
    • boolval - Obtener el valor booleano de una variable
    • bson_decode - Decodifica un objecto BSON a un array PHP
    • bson_encode - Serializa una variable PHP a un string BSON
    • bzclose - Cierra un fichero bzip2
    • bzcompress - Comprime una cadena en datos codificados en bzip2
    • bzdecompress - Descomprime datos codificados con bzip2
    • bzerrno - Devuelve el número de erro de bzip2
    • bzerror - Devuelve el número de error y la cadena del error de bzip2 en un array
    • bzerrstr - Devuelve una cadena de error de bzip2
    • bzflush - Fuerza la escritura de todos los datos del búfer
    • bzopen - Abre un fichero comprimido con bzip2
    • bzread - Lectura segura de ficheros bzip2
    • bzwrite - Escribe en un fichero bzip2 de forma segura binariamente
  • c
    • CachingIterator::count - El número de elementos en el iterador
    • CachingIterator::current - Devuelve el elemento actual
    • CachingIterator::getCache - Recuperar el contenido de la caché
    • CachingIterator::getFlags - Obtener las banderas utilizadas
    • CachingIterator::getInnerIterator - Devuelve el iterador interno
    • CachingIterator::hasNext - Comprueba que el iterador interno tenga un elemento siguiente válido
    • CachingIterator::key - Devuelve la clave del elemento actual
    • CachingIterator::next - Desplaza el iterador adelante
    • CachingIterator::offsetExists - Comprobar existencia de un índice
    • CachingIterator::offsetGet - El propósito offsetGet
    • CachingIterator::offsetSet - El propósito offsetSet
    • CachingIterator::offsetUnset - El propósito offsetUnset
    • CachingIterator::rewind - Rebobina el iterador
    • CachingIterator::setFlags - El propósito de setFlags
    • CachingIterator::valid - Comprueba que el elemento actual sea válido
    • CachingIterator::__construct - Construir un nuevo objeto CachingIterator para el iterador
    • CachingIterator::__toString - Devolver la representación en formato cadena del elemento actual
    • CallbackFilterIterator::accept - Llama la llamada de retorno con el valor actual, la clave actual y el iterador interior como argumentos
    • CallbackFilterIterator::__construct - Crear un iterador filtrado desde otro iterador
    • call_user_func - Llamar a una llamada de retorno dada por el primer parámetro
    • call_user_func_array - Llamar a una llamada de retorno con un array de parámetros
    • cal_days_in_month - Devolver el número de días de un mes para un año y un calendario dados
    • cal_from_jd - Convierte de una Fecha Juliana a un calendario soportado
    • cal_info - Devuelve información sobre un calendario en particular
    • cal_to_jd - Convertir un calendario soportado a la Fecha Juliana
    • ceil - Redondear fracciones hacia arriba
    • chdir - Cambia de directorio
    • checkdate - Validar una fecha gregoriana
    • checkdnsrr - Comprueba registros DNS correspondientes a un nombre de host de Internet dado o dirección IP
    • chgrp - Cambia el grupo del archivo
    • chmod - Cambia el modo de un fichero
    • chop - Alias de rtrim
    • chown - Cambia el propietario del fichero
    • chr - Devuelve un caracter específico
    • chroot - Cambia el directorio raíz
    • chunk_split - Divide una cadena en trozos más pequeños
    • classkit_import - Importar nuevas definiciones de métodos de clase desde un archivo
    • classkit_method_add - Añade dinámicamente un nuevo método una clase dada
    • classkit_method_copy - Copia un método de una clase a otra
    • classkit_method_redefine - Cambia dinámicamente el código del método dado
    • classkit_method_remove - Elimina dinámicamente el método dado
    • classkit_method_rename - Cambia dinámicamente el nombre del método dado
    • class_alias - Crea un alias para una clase
    • class_exists - Verifica si la clase ha sido definida
    • class_implements - Devuelve las interfaces que son implementadas por la clase o interfaz dadas
    • class_parents - Devuelve las clases padre de la clase dada.
    • class_uses - Devolver los "traits" usados por la clase dada
    • clearstatcache - Limpia la caché de estado de un archivo
    • cli_get_process_title - Returns the current process title
    • cli_set_process_title - Sets the process title
    • closedir - Cierra un gestor de directorio
    • closelog - Cerrar conexión al log del sistema
    • Closure::bind - Duplicar un cierre con un objeto vinculado y ámbito de clase especificados
    • Closure::bindTo - Duplicar el cierre con un objeto vinculado y ámbito de clase nuevos
    • Closure::call - Vincula y llama al cierre
    • Closure::fromCallable - Convierte un 'callable' en un cierre
    • Closure::__construct - Constructor que anula la instanciación
    • Collator::asort - Ordenar un array manteniendo la relación de índices
    • Collator::compare - Comparar dos cadenas Unicode
    • Collator::create - Crear un cotejador
    • Collator::getAttribute - Obtener el valor de un atributo de cotejo
    • Collator::getErrorCode - Obtener el último código de error del cotejeador
    • Collator::getErrorMessage - Obtener el texto del último código de error del cotejador
    • Collator::getLocale - Obtener el nombre de la configuración regional del cotejador
    • Collator::getSortKey - Obtener la clave de ordenación de una cadena
    • Collator::getStrength - Obtener la fuerza de cotejo actual
    • Collator::setAttribute - Establecer el atributo de cotejo
    • Collator::setStrength - Establecer la fuerza (strength) de un cotejo
    • Collator::sort - Ordenar un array usando cotejador especificado
    • Collator::sortWithSortKeys - Ordenar un array usando el cotejador y las claves de ordenación especificados
    • Collator::__construct - Crear un objeto Collator
    • Collectable::isGarbage - Determinar si un objeto ha sido marcado como basura
    • Collectable::setGarbage - Marcar un objeto como basura
    • CommonMark\CQL::__construct - Constructor CQL
    • 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 - Manipulación AST
    • CommonMark\Node::insertAfter - Manipulación AST
    • CommonMark\Node::insertBefore - Manipulación AST
    • CommonMark\Node::prependChild - Manipulación AST
    • CommonMark\Node::replace - Manipulación AST
    • CommonMark\Node::unlink - Manipulación AST
    • CommonMark\Node\BulletList::__construct - Construcción BulletList
    • CommonMark\Node\CodeBlock::__construct - Constructor CodeBlock
    • CommonMark\Node\Heading::__construct - Constructor Heading
    • CommonMark\Node\Image::__construct - Constructor Image
    • CommonMark\Node\Link::__construct - Constructor Link
    • CommonMark\Node\OrderedList::__construct - Constructor OrderedList
    • CommonMark\Node\Text::__construct - Constructor Text
    • CommonMark\Parse - Parsing
    • CommonMark\Parser::finish - Parsing
    • CommonMark\Parser::parse - Parsing
    • CommonMark\Parser::__construct - Constructor Parser
    • CommonMark\Render - Rendering
    • CommonMark\Render\HTML - Rendering
    • CommonMark\Render\Latex - Rendering
    • CommonMark\Render\Man - Rendering
    • CommonMark\Render\XML - Rendering
    • compact - Crear un array que contiene variables y sus valores
    • 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 - Añadir Interface
    • Componere\Abstract\Definition::addMethod - Añadir método
    • Componere\Abstract\Definition::addTrait - Añadir rasgo
    • Componere\Abstract\Definition::getReflector - Reflection
    • Componere\cast - Moldeado
    • Componere\cast_by_ref - Moldeado
    • Componere\Definition::addConstant - Añade constante
    • Componere\Definition::addProperty - Añade propiedad
    • Componere\Definition::getClosure - Obtener Cierre
    • Componere\Definition::getClosures - Obtener Cierres
    • Componere\Definition::isRegistered - Detección del estado
    • Componere\Definition::register - Registro
    • Componere\Definition::__construct - Constructor Definition
    • Componere\Method::getReflector - Reflection
    • Componere\Method::setPrivate - Modificación de la accesibilidad
    • Componere\Method::setProtected - Modificación de la accesibilidad
    • Componere\Method::setStatic - Modificación de la accesibilidad
    • Componere\Method::__construct - Constructor Method
    • Componere\Patch::apply - Aplicación
    • Componere\Patch::derive - Derivación del parche
    • Componere\Patch::getClosure - Obtener Cierre
    • Componere\Patch::getClosures - Obtener Cierres
    • Componere\Patch::isApplied - Detección del estado
    • Componere\Patch::revert - Reversión
    • Componere\Patch::__construct - Constructor Patch
    • Componere\Value::hasDefault - Interacción de Value
    • Componere\Value::isPrivate - Detección de accesibilidad
    • Componere\Value::isProtected - Detección de accesibilidad
    • Componere\Value::isStatic - Detección de accesibilidad
    • Componere\Value::setPrivate - Modificación de la accesibilidad
    • Componere\Value::setProtected - Modificación de la accesibilidad
    • Componere\Value::setStatic - Modificación de la accesibilidad
    • Componere\Value::__construct - Constructor Value
    • com_create_guid - Generar un identificador único globalmente (GUID)
    • com_event_sink - Conectar eventos de un objeto COM a un objeto PHP
    • com_get_active_object - Devuelve un gestor a una instancia de un objeto COM ya en ejecución
    • com_load_typelib - Carga una biblioteca de tipos
    • com_message_pump - Procesar mensajes COM, durmiendo hata timeoutms milisegundos
    • com_print_typeinfo - Imprime una definición de clase de PHP para una interfaz despachable
    • Cond::broadcast - Broadcast a Condition
    • Cond::create - Create a Condition
    • Cond::destroy - Destroy a Condition
    • Cond::signal - Signal a Condition
    • Cond::wait - Wait for Condition
    • connection_aborted - Verifica si el cliente se desconectó
    • connection_status - Devuelve el campo de bits de status de conexión
    • constant - Devuelve el valor de una constante
    • Contexto parámetros - Listado de parámetros de contexto
    • convert_cyr_string - Convierte de un juego de caracteres cirílico a otro juego de caracteres cirílico
    • convert_uudecode - Descodifica una cadena codificada mediante uuencode
    • convert_uuencode - Codificar mediante uuencode una cadena
    • copy - Copia un fichero
    • cos - Coseno
    • cosh - Coseno hiperbólico
    • count - Cuenta todos los elementos de un array o algo de un objeto
    • Countable::count - Cuenta los elementos de un objeto
    • count_chars - Devuelve información sobre los caracteres usados en una cadena
    • crc32 - Calcula el polinomio crc32 de una cadena
    • create_function - Crear una función anónima (estilo lambda)
    • crypt - Hash de cadenas de un sólo sentido
    • ctype_alnum - Chequear posibles caracteres alfanuméricos
    • ctype_alpha - Chequear posibles caracteres alfabéticos
    • ctype_cntrl - Chequear posibles caracteres de control
    • ctype_digit - Chequear posibles caracteres numéricos
    • ctype_graph - Chequear posibles caracteres imprimibles, con excepción de los espacios
    • ctype_lower - Chequear posibles caracteres en minúscula
    • ctype_print - Chequear posibles caracteres imprimibles
    • ctype_punct - Chequear posibles caracteres imprimibles que no son ni espacios en blanco ni caracteres alfanuméricos
    • ctype_space - Chequear posibles caracteres de espacio en blanco
    • ctype_upper - Chequear posibles caracteres en mayúscula
    • ctype_xdigit - Chequear posibles caracteres que representen un dígito hexadecimal
    • cubrid_affected_rows - Devolver el número de filas afectadas por la última sentencia SQL
    • cubrid_bind - Vincular variables para una sentencia preparada como parámetros
    • cubrid_client_encoding - Devuelve el actual conjunto de caracteres de la conexión a CUBRID
    • cubrid_close - Cerrar la conexión de CUBRID
    • cubrid_close_prepare - Cerrar el gestor de solicitud
    • cubrid_close_request - Cerrar el gestor de solicitud
    • cubrid_column_names - Obtener los nombres de las columnas del resultado
    • cubrid_column_types - Obtener los tipos de columnas del resultado
    • cubrid_col_get - Obtener el contenido de la columna del tipo de colecctión usando OID
    • cubrid_col_size - Obtener el número de elementos de la columna del tipo de colección usando OID
    • cubrid_commit - Consigna una transacción
    • cubrid_connect - Abrir una conexión al servidor CUBRID
    • cubrid_connect_with_url - Establecer el entorno para la conexión al servidor de CUBRID
    • cubrid_current_oid - Obtener el OID de la posición del cursor actual
    • cubrid_data_seek - Mueve el puntero interno de la fila del resultado CUBRID
    • cubrid_db_name - Obtener el nombre de la base de datos desde los resultados de cubrid_list_dbs
    • cubrid_disconnect - Cerrar una conexión a una base de datos
    • cubrid_drop - Borrar una instancia usando OID
    • cubrid_errno - Devuelve el valor numérico del mensaje de error de la operación de CUBRID previa
    • cubrid_error - Se usa para obtener el mensaje de error
    • cubrid_error_code - Obtener el código de error de la llamada a una función más reciente
    • cubrid_error_code_facility - Obtener el código de error del dispositivo
    • cubrid_error_msg - Obtener el último mensaje de error de la llamada a la función más reciente
    • cubrid_execute - Ejecutar una sentencia SQL preparada
    • cubrid_fetch - Obtener la siguiente fila de un conjunto de resultados
    • cubrid_fetch_array - Extrae una fila como array asociativo, numérico o ambos
    • cubrid_fetch_assoc - Devuelve un array asociativo que se corresponde con la fila obtenida
    • cubrid_fetch_field - Devuelve un objeto con ciertas propiedades
    • cubrid_fetch_lengths - Devuelve una matriz con las longitudes de los valores de cada campo de la fila actual
    • cubrid_fetch_object - Devuelve un objeto con los nombres de las columnas
    • cubrid_fetch_row - Devuelve un array numérico con los valores de la fila actual
    • cubrid_field_flags - Devuelve una cadena con las banderas del índice del campo dado
    • cubrid_field_len - Devuelve la longitud máxima del campo especificado
    • cubrid_field_name - Devuelve el nombre del índice del campo especificado
    • cubrid_field_seek - Mueve el cursor del conjunto de resultados al índece del campo especificado
    • cubrid_field_table - Devuelve el nombre de la tabla del campo especificado
    • cubrid_field_type - Devuelve el tipo de columna que se corresponde con el índice del campo dado
    • cubrid_free_result - Liberar la memoria ocupada por los datos del resultado
    • cubrid_get - Obtener una columna usando OID
    • cubrid_get_autocommit - Devuelve el modo auto-commit de la conexión
    • cubrid_get_charset - Devolver el conjunto de caracteres de la conexión CUBRID actual
    • cubrid_get_class_name - Obtener el nombre de la clase usando OID
    • cubrid_get_client_info - Devolver la versión de la biblioteca cliente
    • cubrid_get_db_parameter - Devuelve los parámetros de la base de datos CUBRID
    • cubrid_get_query_timeout - Obtener el valor del tiempo de espera de consulta de la petición
    • cubrid_get_server_info - Devolver la versión del servidor CUBRID
    • cubrid_insert_id - Devuelve el ID generado por la última columna actualizada AUTO_INCREMENT
    • cubrid_is_instance - Comprobar si existe la instancia apuntada por OID
    • cubrid_list_dbs - Devuelve una matriz con la lista de todas las bases de datos Cubrid existentes
    • cubrid_load_from_glo - Leer información de una instancia GLO y guardarla en un fichero
    • cubrid_lob2_bind - Vincula un objeto LOB o un string como un objeto LOB a una sentencia preparada como parámetros
    • cubrid_lob2_close - Cierra un objeto LOB
    • cubrid_lob2_export - Exporta un objeto LOB a un fichero
    • cubrid_lob2_import - Importa datos BLOB/CLOB desde un fichero
    • cubrid_lob2_new - Crea un objeto LOB
    • cubrid_lob2_read - Lee desde datos BLOB/CLOB
    • cubrid_lob2_seek - Mover el cursor de un objeto LOB
    • cubrid_lob2_seek64 - Mover el cursor de un objeto LOB
    • cubrid_lob2_size - Obtiene el tamaño de un objeto LOB
    • cubrid_lob2_size64 - Obtiene el tamaño de un objeto LOB
    • cubrid_lob2_tell - Indica la posición del cursor de un objeto LOB
    • cubrid_lob2_tell64 - Indica la posición del cursor de un objeto LOB
    • cubrid_lob2_write - Escribe en un objeto LOB
    • cubrid_lob_close - Cerrar información BLOB/CLOB
    • cubrid_lob_export - Exportar datos BLOB/CLOB a un fichero
    • cubrid_lob_get - Obtener información BLOB/CLOB
    • cubrid_lob_send - Leer información BLOB/CLOB y enviarla directamente al navegador
    • cubrid_lob_size - Obtener el tamaño de datos BLOB/CLOB
    • cubrid_lock_read - Establecer un bloqueo de lectura sobre el OID dado
    • cubrid_lock_write - Establecer un bloqueo de escritura para el OID dado
    • cubrid_move_cursor - Mover el cursor en el resultado
    • cubrid_new_glo - Crear una instancia glo
    • cubrid_next_result - Obtiene el resultado de la siguiente consulta cuando se ejecutan multiples sentencias SQL
    • cubrid_num_cols - Devolver el número de columnas del conjunto de resultados
    • cubrid_num_fields - Devuelve el número de columnas del conjunto de resultados
    • cubrid_num_rows - Obtener el número de filas del conjunto de resultados
    • cubrid_pconnect - Abrir una conexión persistente a un servidor CUBRID
    • cubrid_pconnect_with_url - Abrir una conexión persistente al servidor CUBRID
    • cubrid_ping - Hacer ping en una conexión al servidor o reconectar si no hay conexión
    • cubrid_prepare - Preparar una sentencia SQL para su ejecución
    • cubrid_put - Actualizar un atributo usando OID
    • cubrid_query - Enviar una consulta CUBRID
    • cubrid_real_escape_string - Escapar caracteres especiales en una cadena para usarla en una sentencia SQL
    • cubrid_result - Devuelve el valor de un campo específico de una fila específica
    • cubrid_rollback - Retroceder una transacción
    • cubrid_save_to_glo - Guardar el fichero solicitado en una instancia GLO
    • cubrid_schema - Obtener la información del esquema solicitado
    • cubrid_send_glo - Leer información de un glo y enviarla a la salida estándar
    • cubrid_seq_drop - Borrar un elemento de una columna tipo secuencia usando OID
    • cubrid_seq_insert - Insertar un elemento en una columna tipo secuencia usando OID
    • cubrid_seq_put - Actualizar el valor del elemento de la columna de tipo secuencia usando OID
    • cubrid_set_add - Insertar un único elemento en la columna del tipo de conjunto usando OID
    • cubrid_set_autocommit - Establece el modo de confirmación automática de la conexión
    • cubrid_set_db_parameter - Configura los parámetros de la base de datos CUBRID
    • cubrid_set_drop - Borrar un elemento de la columna del tipo de conjunto usando OID
    • cubrid_set_query_timeout - Establecer el tiempo de espera de la ejecución de consultas
    • cubrid_unbuffered_query - Realiza una consulta sin traer los resultados a memoria
    • cubrid_version - Obtener la versión del módulo de PHP de CUBRID
    • CURLFile::getFilename - Recupera el nombre de un fichero
    • CURLFile::getMimeType - Recupera el tipo MIME
    • CURLFile::getPostFilename - Recupera el nombre de fichero para POST
    • CURLFile::setMimeType - Configura el tipo MIME
    • CURLFile::setPostFilename - Establecer el nombre de fichero para POST
    • CURLFile::__construct - Crear un objeto CURLFile
    • curl_close - Cierra una sesión cURL
    • curl_copy_handle - Copia el recurso cURL junto con todas sus preferencias
    • curl_errno - Devuelve el último número de error
    • curl_error - Devuelve una cadena que contiene el último error de la sesión actual
    • curl_escape - Función URL que codifica el string dado
    • curl_exec - Establece una sesión cURL
    • curl_getinfo - Obtener información sobre una transferencia específica
    • curl_init - Inicia sesión cURL
    • curl_multi_add_handle - Añade un recurso cURL a un grupo de recursos cURL
    • curl_multi_close - Cierra un grupo de recursos cURL
    • curl_multi_errno - Devuelve el último número de error de cURL múltiple
    • curl_multi_exec - Ejecuta las sub-conexiones del recurso cURL actual
    • curl_multi_getcontent - Devuelve el contenido del recurso cURL si CURLOPT_RETURNTRANSFER está activado
    • curl_multi_info_read - Obtiene información de las transferencias en curso
    • curl_multi_init - Devuelve un nuevo multi recurso cURL
    • curl_multi_remove_handle - Elimina un multi recurso de un conjunto de recursos cURL
    • curl_multi_select - Espera actividad en cualquier conexión en curl_multi
    • curl_multi_setopt - Configura una opción para el multi gestor cURL
    • curl_multi_strerror - Devuelve un string con la descripción del código de error
    • curl_pause - Pausa y reanuda una conexión
    • curl_reset - Reinicializa todas las opciones de un gestor de sesión libcurl
    • curl_setopt - Configura una opción para una transferencia cURL
    • curl_setopt_array - Configura múltiples opciones para una transferencia cURL
    • curl_share_close - Cierra un gestor cURL compartido
    • curl_share_errno - Devuelve el último número del error compartido cURL
    • curl_share_init - Inicializar un gestor cURL compartido
    • curl_share_setopt - Configura una opción para un manejador cURL compartido
    • curl_share_strerror - Devuelve string con la descripción del codigo de error dado
    • curl_strerror - Devuelve un string que describe el código de error dado
    • curl_unescape - Descodifica un string codificado de URL
    • curl_version - Obtiene la información de la versión de cURL
    • current - Devuelve el elemento actual en un array
  • d
    • data:// - Data (RFC 2397)
    • date - Dar formato a la fecha/hora local
    • DateInterval::createFromDateString - Establece un objeto DateInterval desde las partes relativas de una cadena
    • DateInterval::format - Formatea el intervalo
    • DateInterval::__construct - Crea un nuevo objeto DateInterval
    • DatePeriod::getDateInterval - Obtener el intervalo
    • DatePeriod::getEndDate - Obtener la fecha final
    • DatePeriod::getRecurrences - Gets the number of recurrences
    • DatePeriod::getStartDate - Obtener la fecha inicial
    • DatePeriod::__construct - Crea un nuevo objeto DatePeriod
    • DateTime::add - Añade una cantidad de días, meses, años, horas, minutos y segundos a un objeto DateTime
    • DateTime::createFromFormat - Analiza una cadena con un instante según un formato especificado
    • DateTime::createFromImmutable - Returns new DateTime object encapsulating the given DateTimeImmutable object
    • DateTime::createFromInterface - Returns new DateTime object encapsulating the given DateTimeInterface object
    • DateTime::diff - Devuelve la diferencia entre dos objetos DateTime
    • DateTime::format - Devuelve la fecha formateada según el formato dado
    • DateTime::getLastErrors - Devuelve las advertencias y los errores
    • DateTime::getOffset - Devuelve el índice de la zona horaria
    • DateTime::getTimestamp - Obtiene la marca de tiempo Unix
    • DateTime::getTimezone - Develve la zona horaria relativa al objeto DateTime dado
    • DateTime::modify - Altera la marca temporal
    • DateTime::setDate - Establece la fecha
    • DateTime::setISODate - Establece la fecha ISO
    • DateTime::setTime - Establece la hora
    • DateTime::setTimestamp - Establece la fecha y la hora basándose en una marca temporal de Unix
    • DateTime::setTimezone - Establece la zona horaria para el objeto DateTime
    • DateTime::sub - Sustrae una cantidad de días, meses, años, horas, minutos y segundos de un objeto DateTime
    • DateTime::__construct - Devuelve un nuevo objeto DateTime
    • DateTime::__set_state - El gestor __set_state
    • DateTime::__wakeup - El gestor __wakeup
    • DateTimeImmutable::add - Añade una cantidad de días, meses, años, horas, minutos y segundos
    • DateTimeImmutable::createFromFormat - Devuelve un nuevo objeto DateTimeImmutable formateado según el formato especificado
    • DateTimeImmutable::createFromInterface - Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object
    • DateTimeImmutable::createFromMutable - Devuelve un nuevo objeto DateTimeImmutable que encapsula el objeto DateTime dado
    • DateTimeImmutable::getLastErrors - Devuelve las advertencias y errores
    • DateTimeImmutable::modify - Crea un nuevo objeto con la marca de tiempo modificada
    • DateTimeImmutable::setDate - Establece la fecha
    • DateTimeImmutable::setISODate - Establece la fecha ISO
    • DateTimeImmutable::setTime - Establece la hora
    • DateTimeImmutable::setTimestamp - Establece la fecha y hora basadas en una marca de tiempo Unix
    • DateTimeImmutable::setTimezone - Establece la zona horaria
    • DateTimeImmutable::sub - Sustrae una cantidad de días, meses, años, horas, minutos y segundos
    • DateTimeImmutable::__construct - Devuelve un nuevo objeto DateTimeImmutable
    • DateTimeImmutable::__set_state - El gestor __set_state
    • DateTimeZone::getLocation - Devuelve la información de la ubicación para una zona horaria
    • DateTimeZone::getName - Devuelve el nombre de la zona horaria
    • DateTimeZone::getOffset - Devuelve el índice de la zona horaria de GMT
    • DateTimeZone::getTransitions - Devuelve todas las transiciones para una zona horaria
    • DateTimeZone::listAbbreviations - Devuelve una matriz asociativa que contiene el horario de verano (dst), el índice y el nombre de la zona horaria
    • DateTimeZone::listIdentifiers - Devuelve un array indexado numéricamente que contiene todos los identificadores de zonas horarias definidos
    • DateTimeZone::__construct - Crea un nuevo objeto DateTimeZone
    • date_add - Alias de DateTime::add
    • date_create - Alias de DateTime::__construct
    • date_create_from_format - Alias de DateTime::createFromFormat
    • date_create_immutable - Alias de DateTimeImmutable::__construct
    • date_create_immutable_from_format - Alias de DateTimeImmutable::createFromFormat
    • date_date_set - Alias de DateTime::setDate
    • date_default_timezone_get - Obtiene la zona horaria predeterminada usada por todas las funciones de fecha/hora en un script
    • date_default_timezone_set - Establece la zona horaria predeterminada usada por todas las funciones de fecha/hora en un script
    • date_diff - Alias de DateTime::diff
    • date_format - Alias de DateTime::format
    • date_get_last_errors - Alias de DateTime::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 - Devuelve un array asociativo con información detallada acerca de una fecha dada
    • date_parse_from_format - Obtiene información de una fecha dada formateada de acuerdo al formato especificado
    • date_sub - Alias de DateTime::sub
    • date_sunrise - Devuelve la hora de la salida del sol de un día y ubicación dados
    • date_sunset - Devuelve la hora de la puesta de sol de un día y ubicación dados
    • date_sun_info - Devuelve una matriz con información sobre la puesta/salida del sol y el comienzo/final del crepúsculo
    • 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 - Devuelve o establece el estado de AUTOCOMMIT en una conexión de bases de datos
    • db2_bind_param - Vincula una variable PHP a un parámetro de una sentencia SQL
    • db2_client_info - Devuelve un objeto cuyas propiedades describen cliente de una base de datos DB2
    • db2_close - Cierra una conexión a base de datos
    • db2_columns - Devuelve los campos de una tabla y sus metadatos asociados.
    • db2_column_privileges - Obtiene la lista de columnas y permisos asociados a una tabla
    • db2_commit - Confirmar una transacción
    • db2_connect - Devolver una conexión a la base de datos
    • db2_conn_error - Devolver una cadena que contenga el valor SQLSTATE devuelto por el último intento de conexión.
    • db2_conn_errormsg - Devolver el último mensaje de error de la conexión y su valor SQLCODE
    • db2_cursor_type - Determinar el tipo de cursor utilizado en una consulta
    • db2_escape_string - Escapar ciertos caracteres especiales
    • db2_exec - Ejecutar directamente una sentencia SQL
    • db2_execute - Ejecutar una sentencia SQL preparada
    • db2_fetch_array - Devolver un arreglo, indexado por la posición de las columnas, que represanta una fila de un bloque de resultados
    • db2_fetch_assoc - Devolver un arreglo, indexado por el nombre de las columnas, representando una fila del bloque de resultados
    • db2_fetch_both - Devolver un arreglo, indexado por el nombre y por la posición de la columna, representando una fila de un bloque de resultados
    • db2_fetch_object - Devolver un objeto con atributos que representan a las columnas de una fila extraida
    • db2_fetch_row - Establecer el apuntador de los resultados hacia la siguiente fila o a la fila solicitada
    • db2_field_display_size - Devolver el número máximo de bytes requeridos para mostrar una columna
    • db2_field_name - Devolver el nombre de la columna indicada del resultado
    • db2_field_num - Devolver la posición de la columna indicada en un resultado
    • db2_field_precision - Devolver la precisión de la columna indicada en el resultado
    • db2_field_scale - Devolver la escala de la columna indicada en el resultado
    • db2_field_type - Devolver el tipo de dato de la columna indicada en un resultado
    • db2_field_width - Devolver el tamaño del valor contenido en la columna indicada
    • db2_foreign_keys - Devolver un resultado que contenga las llaves foraneas de una tabla
    • db2_free_result - Liberar los recursos asociados con un resultado
    • db2_free_stmt - Liberar un recurso indicado
    • db2_get_option - Devolver el valor de la opción correpondiente a una conexión o sentencia
    • db2_last_insert_id - Devolver el ID autogenerado el la última sentencia INSERT ejecutada correctamente en la conexión
    • db2_lob_read - Obtener un segmento, de tamaño definido por el usuario, de un archivo LOB
    • db2_next_result - Solicitar el siguiente resultado de un procedimiento almacendo
    • db2_num_fields - Devolver el número de campos que contiene un resultado
    • db2_num_rows - Devolver el número de filas afectadas por una sentencia SQL
    • db2_pclose - Cerrar una conexión persistente a la base de datos
    • db2_pconnect - Devolver una conexión persistente a la base de datos
    • db2_prepare - Prepara un comando SQL para su ejecución
    • db2_primary_keys - Devolver un resultado con las llaves primarias de una tabla
    • db2_procedures - Devolver un resultado con los procedimientos almacenados registrados en la base de datos
    • db2_procedure_columns - Devolver un resultado con los parámetros de los procedimientos almacenados
    • db2_result - Devolver una columna específica del resultado
    • db2_rollback - Cancelar una transacción
    • db2_server_info - Returns an object with properties that describe the DB2 database server
    • db2_set_option - Set options for connection or statement resources
    • db2_special_columns - Returns a result set listing the unique row identifier columns for a table
    • db2_statistics - Returns a result set listing the index and statistics for a table
    • db2_stmt_error - Returns a string containing the SQLSTATE returned by an SQL statement
    • db2_stmt_errormsg - Returns a string containing the last SQL statement error message
    • db2_tables - Returns a result set listing the tables and associated metadata in a database
    • db2_table_privileges - Returns a result set listing the tables and associated privileges in a database
    • dbase_add_record - Añade un registro a una base de datos
    • dbase_close - Cierra una base de datos
    • dbase_create - Crea una base de datos
    • dbase_delete_record - Borra un registro de una base de datos
    • dbase_get_header_info - Obtiene la información de cabecera de una base de datos
    • dbase_get_record - Obtiene un registro de una base de datos como una matriz indexada
    • dbase_get_record_with_names - Obtiene un registro de una base de datos como una matriz asociativa
    • dbase_numfields - Obtiene el número de campos de una base de datos
    • dbase_numrecords - Obtener el número de registros de una base de datos
    • dbase_open - Abre una base de datos
    • dbase_pack - Empaquetar una base de datos
    • dbase_replace_record - Reemplaza un registro en una base de datos
    • dba_close - Cerrar una base de datos DBA
    • dba_delete - Elimina una entrada DBA especificada por clave
    • dba_exists - Verificar si la clave existe
    • dba_fetch - Recuperar datos especificados por clave
    • dba_firstkey - Recuperar la primera clave
    • dba_handlers - Listar todos los gestores disponibles
    • dba_insert - Insertar entrada
    • dba_key_split - Separa una clave en representación de cadena en representación de array
    • dba_list - Listar todos los archivos de base de datos abiertos
    • dba_nextkey - Recuperar la siguiente clave
    • dba_open - Abrir una base de datos
    • dba_optimize - Optimizar base de datos
    • dba_popen - Abrir una base de datos de forma persistente
    • dba_replace - Reemplazar o insertar una entrada
    • dba_sync - Sincronizar base de datos
    • dbplus_add - Añade una tupla a una relación
    • dbplus_aql - Realizar una consulta AQL
    • dbplus_chdir - Obtener/Estabecer el directorio virtual actual de la base de datos
    • dbplus_close - Cierra una relación
    • dbplus_curr - Get current tuple from relation
    • dbplus_errcode - Obtener la cadena de error de un código de error dado o del último error
    • dbplus_errno - Obtener el código de error de la última operación
    • dbplus_find - Establecer una restricción en una relación
    • dbplus_first - Obtener la primera tupla de una relación
    • dbplus_flush - Vuelca todos los cambios hechos en una relación
    • dbplus_freealllocks - Liberar todos los bloqueos mantenidos por este cliente
    • dbplus_freelock - Libera el bloqueo de escritura en una tupla
    • dbplus_freerlocks - Liberar todos los bloqueos de una relación dada
    • dbplus_getlock - Obtener un bloqueo de escritura en una tupla
    • dbplus_getunique - Obtener un único número de identificación para una relación
    • dbplus_info - Obtener información sobre una relación
    • dbplus_last - Obtener la última tupla de una relación
    • dbplus_lockrel - Solictar un bloqueo de escritura en una relación
    • dbplus_next - Obtener la siguiente tupla de una relación
    • dbplus_open - Abre un archivo de relación
    • dbplus_prev - Obtener la tupla previa de una relación
    • dbplus_rchperm - Cambiar los permisos de una relación
    • dbplus_rcreate - Crea una nueva relación de DB++
    • dbplus_rcrtexact - Crea una copia exacta pero vacía de una relación incluyendo los índices
    • dbplus_rcrtlike - Crea una copia vacía de una relación con los índeces predeterminados
    • dbplus_resolve - Resuelve la información del host de la relación
    • dbplus_restorepos - Restablece la posición
    • dbplus_rkeys - Especificar una nueva clave primaria para un relaición
    • dbplus_ropen - Abrir un archivo local de relación
    • dbplus_rquery - Realizar una consulta AQL local (en bruto)
    • dbplus_rrename - Renombrar una relación
    • dbplus_rsecindex - Crear un nuevo índice secundario para una relación
    • dbplus_runlink - Eliminar una relación del sistema de archivos
    • dbplus_rzap - Eliminar todas las tuplas de una relación
    • dbplus_savepos - Guardar la posición
    • dbplus_setindex - Establecer el índice
    • dbplus_setindexbynumber - Establecer el índice por número
    • dbplus_sql - Realiza una consulta SQL
    • dbplus_tcl - Ejecutar código TCL en el lado del servidor
    • dbplus_tremove - Eliminar una tupla y devolver la nueva tupla actual
    • dbplus_undo - Deshacer
    • dbplus_undoprepare - Preparara deshacer
    • dbplus_unlockrel - Liberar un bloqueo de escritura en una relación
    • dbplus_unselect - Eliminar una restricción de una relación
    • dbplus_update - Actualizar la tupla especificada en la relación
    • dbplus_xlockrel - Solicitar un bloqueo exclusivo de una relación
    • dbplus_xunlockrel - Liberar un bloqueo exclusivo en una relación
    • dcgettext - Sobrescribe el dominio de la búsqueda única del mensaje
    • dcngettext - Versión plural de dcgettext
    • debug_backtrace - Genera un rastreo
    • debug_print_backtrace - Muestra un rastreo
    • debug_zval_dump - Vuelca a la salida una cadena con la representación de un valor interno de zend
    • decbin - Decimal a binario
    • dechex - Decimal a hexadecimal
    • decoct - Decimal a octal
    • define - Define una constante con nombre
    • defined - Comprueba si existe una constante con nombre dada
    • deflate_add - Incrementally deflate data
    • deflate_init - Initialize an incremental deflate context
    • deg2rad - Convierte el número en grados a su equivalente en radianes
    • delete - Véase unlink o unset
    • dgettext - Sobrescribe el dominio actual
    • die - Equivalente a exit
    • dio_close - Cierra el descriptor de fichero fd
    • dio_fcntl - Lleva a cabo la función fcntl de la biblioteca C en el fichero fd
    • dio_open - Abre (crea si fuera necesario) un fichero a un nivel más bajo que el permitido por flujos de entrada y salida de las bibliotecas en C
    • dio_read - Leer bytes de un descriptor de fichero
    • dio_seek - Salta a una posición del descriptor de fichero desde donde proceda
    • dio_stat - Consulta información de estado del descriptor de fichero fd
    • dio_tcsetattr - Establece los atributos terminales y la tasa de baudios del puerto serie
    • dio_truncate - Trunca un descriptor de fichero fd a un determinado número de bytes
    • dio_write - Escribe datos en el descriptor de fichero con un truncado opcional
    • dir - Devuelve una instancia de la clase Directory
    • Directory::close - Cierra un gestor de directorio
    • Directory::read - Lee una entrada desde el controlador de directorio
    • Directory::rewind - Rebobina el manejador de directorio
    • DirectoryIterator::current - Devuelve el elemento actual del DirectoryIterator
    • DirectoryIterator::getATime - Obtener el último acceso del elemento actual DirectoryIterator
    • DirectoryIterator::getBasename - Obtener el nombre base del elemento actual DirectoryIterator
    • DirectoryIterator::getCTime - Obtiene el cambio de tiempo del inodo para el elemento actual DirectoryIterator
    • DirectoryIterator::getExtension - Obtiene la extensión de un fichero
    • DirectoryIterator::getFilename - Devuelve el nombre del fichero del elemento actual DirectoryIterator
    • DirectoryIterator::getGroup - Obtiene el grupo para el elemento actual DirectoryIterator
    • DirectoryIterator::getInode - Obtiene el inodo para el elemento actual DirectoryIterator
    • DirectoryIterator::getMTime - Obtiene la última modificación para el elemento actual DirectoryIterator
    • DirectoryIterator::getOwner - Obtiene el dueño del elemento actual DirectoryIterator
    • DirectoryIterator::getPath - Obtiene la ruta del elemento iterador actual sin nombre de fichero
    • DirectoryIterator::getPathname - Devuelve la ruta y nombre de fichero del elemento actual DirectoryIterator
    • DirectoryIterator::getPerms - Obtiene los permisos del elemento actual DirectoryIterator
    • DirectoryIterator::getSize - obtiene el tamaño de el elemento actual DirectoryIterator
    • DirectoryIterator::getType - Determina el tipo del elemento actual DirectoryIterator
    • DirectoryIterator::isDir - Determina si el elemento actual DirectoryIterator es un directorio
    • DirectoryIterator::isDot - Determina si el elemento actual DirectoryIterator es '.' o '..'
    • DirectoryIterator::isExecutable - Determina si el emento actual DirectoryIterator es ejecutable
    • DirectoryIterator::isFile - Determina si el elemento actual DirectoryIterator es un fichero
    • DirectoryIterator::isLink - Determina si el elemento actual DirectoryIterator es un enlace simbólico
    • DirectoryIterator::isReadable - Determina si el elemento actual DirectoryIterator puede ser leído
    • DirectoryIterator::isWritable - Determina si el elemento actual DirectoryIterator se puede escribir
    • DirectoryIterator::key - Devuelve la clave del elemento actual DirectoryIterator
    • DirectoryIterator::next - Avanza al siguiente elemento DirectoryIterator
    • DirectoryIterator::rewind - Robobina DirectoryIterator hasta volver al inicio
    • DirectoryIterator::seek - Mueve el apuntador interno del elemento DirectoryIterator
    • DirectoryIterator::valid - Comprueba si la actual posición de DirectoryIterator es un fichero válido
    • DirectoryIterator::__construct - Construye un iterador nuevo directorio de una ruta
    • DirectoryIterator::__toString - Obtiene el nombre del fichero como un string
    • dirname - Devuelve la ruta de un directorio padre
    • diskfreespace - Alias de disk_free_space
    • disk_free_space - Devuelve el espacio disponible de un sistema de archivos o partición de disco
    • disk_total_space - Devuelve el tamaño total de un sistema de archivos o partición de disco
    • dl - Carga una extensión de PHP durante la ejecución
    • dngettext - Versión plural de dgettext
    • dns_check_record - Alias de checkdnsrr
    • dns_get_mx - Alias de getmxrr
    • dns_get_record - Fetch DNS Resource Records associated with a hostname
    • DOMAttr::isId - Verifica si un atributo es un ID definido.
    • DOMAttr::__construct - Crea un nuevo objeto DOMAttr
    • DOMCdataSection::__construct - Construye un nuevo objeto DOMCdataSection
    • DOMCharacterData::appendData - Añade el string de caracteres al final de los datos de carácter del nodo.
    • DOMCharacterData::deleteData - Eliminar una serie de caracteres del nodo
    • DOMCharacterData::insertData - Inserta un string en la posición de 16-bit especificada
    • DOMCharacterData::replaceData - Reemplaza un substring dentro de un nodo DOMCharacterData
    • DOMCharacterData::substringData - Extrae una serie de datos del nodo
    • DOMComment::__construct - Crea un nuevo objeto DOMComment
    • DOMDocument::createAttribute - Crear nuevo attribute
    • DOMDocument::createAttributeNS - Crea un nuevo nodo atributo con un namespace asociado.
    • DOMDocument::createCDATASection - Crea un nuevo nodo cdata
    • DOMDocument::createComment - Crea un nuevo nodo de comentario
    • DOMDocument::createDocumentFragment - Crea un nuevo fragmento de documento
    • DOMDocument::createElement - Crea un nuevo nodo elemento
    • DOMDocument::createElementNS - Crea un nuevo nodo elemento con el nombre de espacio asociado
    • DOMDocument::createEntityReference - Create new entity reference node
    • DOMDocument::createProcessingInstruction - Crea un nuevo nodo PI
    • DOMDocument::createTextNode - Crea un nuevo nodo de texto
    • DOMDocument::getElementById - Busca un elemento con cierto id
    • DOMDocument::getElementsByTagName - Busca todos los elementos con el nombre de etiqueta local dado
    • DOMDocument::getElementsByTagNameNS - Busca todos los elementos con el nombre de etiqueta dado en el espacio de nombre especificado.
    • DOMDocument::importNode - Importa un nodo dentro del documento actual
    • DOMDocument::load - Cargar un documento XML de un archivo.
    • DOMDocument::loadHTML - Cargar HTML de una cadena
    • DOMDocument::loadHTMLFile - Cargar HTML desde un fichero
    • DOMDocument::loadXML - Cargar XML desde una cadena
    • DOMDocument::normalizeDocument - Normaliza el documento
    • DOMDocument::registerNodeClass - Registra una clase extendida usada para crear tipos de nodos base
    • DOMDocument::relaxNGValidate - Realiza una validación relaxNG del documento
    • DOMDocument::relaxNGValidateSource - Realiza una validación relaxNG del documento
    • DOMDocument::save - Copia el árbol XML interno a un archivo
    • DOMDocument::saveHTML - Copia el documento interno a una cadena usando el formato HTML
    • DOMDocument::saveHTMLFile - Copia el documento interno a un fichero usando el formato HTML
    • DOMDocument::saveXML - Copia el arbol XML interno a un string
    • DOMDocument::schemaValidate - Valida un documento basado en un esquema
    • DOMDocument::schemaValidateSource - Valida un documento basado en un esquema
    • DOMDocument::validate - Valida el documento basado en su DTD
    • DOMDocument::xinclude - Sustituye XIncludes en un objeto DOMDocument
    • DOMDocument::__construct - Crea un nuevo objeto DOMDocument
    • DOMDocumentFragment::appendXML - Añade información XML sin formato
    • DOMElement::getAttribute - Devuelve el valor de un atributo
    • DOMElement::getAttributeNode - Devuelve el nodo de un atributo
    • DOMElement::getAttributeNodeNS - Devuelve el nodo de un atributo
    • DOMElement::getAttributeNS - Devuelve el valor de un atributo
    • DOMElement::getElementsByTagName - Obtiene los elementos por nombre de etiqueta
    • DOMElement::getElementsByTagNameNS - Obtener los elementos por la URI del espacio de nombres y el nombre local
    • DOMElement::hasAttribute - Comprueba si existe un atributo
    • DOMElement::hasAttributeNS - Comprueba si un atributo existe
    • DOMElement::removeAttribute - Elimina un atributo
    • DOMElement::removeAttributeNode - Elimina un atributo
    • DOMElement::removeAttributeNS - Elimina un atributo
    • DOMElement::setAttribute - Añade un nuevo atributo
    • DOMElement::setAttributeNode - Añade un nuevo nodo de atributo al elemento
    • DOMElement::setAttributeNodeNS - Aña de un nuevo nodo de atributo al elemento
    • DOMElement::setAttributeNS - Añade un nuevo atributo
    • DOMElement::setIdAttribute - Declara el atributo especificado por su nombre como de tipo ID
    • DOMElement::setIdAttributeNode - Declara el atributo especificado por su nodo como de tipo ID
    • DOMElement::setIdAttributeNS - Declara el atributo especificado por su nombre local y su URI del espacio de nombres como de tipo ID
    • DOMElement::__construct - Crea un nuevo objeto DOMElement
    • DOMEntityReference::__construct - Crea un nuevo objeto DOMEntityReference
    • DOMImplementation::createDocument - Crea un objeto DOMDocument del tipo especificado con su elemento documento
    • DOMImplementation::createDocumentType - Crear un objeto DOMDocumentType vacío
    • DOMImplementation::hasFeature - Comprueba si la implementación de DOM implementa una característica específica
    • DOMImplementation::__construct - Crea un nuevo objeto DOMImplementation
    • DOMNamedNodeMap::count - Get number of nodes in the map
    • DOMNamedNodeMap::getNamedItem - Recupera un nodo especificado por su nombre
    • DOMNamedNodeMap::getNamedItemNS - Recupera un nodo especificado por el nombre local y la URI del espacio de nombres
    • DOMNamedNodeMap::item - Recupera un nodo especificado por su índice
    • DOMNode::appendChild - Añade un nuevo hijo al final de los hijos
    • DOMNode::C14N - Canonizar nodos a una cadena
    • DOMNode::C14NFile - Canonizar nodos a un fichero
    • DOMNode::cloneNode - Clona un nodo
    • DOMNode::getLineNo - Obtener el número de línea de un nodo
    • DOMNode::getNodePath - Obtener un XPath de un nodo
    • DOMNode::hasAttributes - Comprueba si un nodo tiene atributos
    • DOMNode::hasChildNodes - Comprueba si el nodo tiene hijos
    • DOMNode::insertBefore - Añade un nuevo hijo antes del nodo de referencia
    • DOMNode::isDefaultNamespace - Comprueba si la URI del espacio de nombres especificada es el espacio de nombres predeterminado
    • DOMNode::isSameNode - Indica si dos nodos son el mismo nodo
    • DOMNode::isSupported - Comprueba si una característica está soportada para la versión especificada
    • DOMNode::lookupNamespaceUri - Obtiene la URI del espacio de nombres del nodo basado en el prefijo
    • DOMNode::lookupPrefix - Obtiene el prefijo del espacio de nombres del nodo basándoes en la URI del espacio de nombres
    • DOMNode::normalize - Normaliza el nodo
    • DOMNode::removeChild - Elimina un hijo de la lista de hijos.
    • DOMNode::replaceChild - Reemplaza un hijo
    • DOMNodeList::count - Obtiene el número de nodos en la lista
    • DOMNodeList::item - Recupera un nodo especificado por un índice
    • DOMProcessingInstruction::__construct - Crea un nuevo objeto DOMProcessingInstruction
    • DOMText::isElementContentWhitespace - Devuelve si este nodo de texto contiene espacios en blanco en el contenido del elemento
    • DOMText::isWhitespaceInElementContent - Indica si este nodo de texto contiene espacios en blanco
    • DOMText::splitText - Rompe este nodo en dos nodos en el índice especificado
    • DOMText::__construct - Crea un nuevo objeto DOMText
    • DOMXPath::evaluate - Evalúa la expresión XPath dada y devuelve un resultado escrito si es posible
    • DOMXPath::query - Evalúa la expresión XPath dada
    • DOMXPath::registerNamespace - Registra el espacio de nombres con el objeto DOMXPath
    • DOMXPath::registerPhpFunctions - Registra funciones de PHP como funciones XPath
    • DOMXPath::__construct - Crea un nuevo objeto DOMXPath
    • dom_import_simplexml - Obtiene un objeto DOMElement desde un objeto SimpleXMLElement
    • doubleval - Alias de floatval
    • DSN de PDO_CUBRID - Conectar con bases de datos de CUBRID
    • DSN de PDO_IBM - Conectarse a bases de datos de IBM
    • DSN de PDO_INFORMIX - Conectarse a bases de datos de Informix
    • DSN de PDO_OCI - Conectar a bases de datos de Oracle
    • DSN de PDO_ODBC - Conectarse a bases de datos de ODBC o de DB2
    • DSN de PDO_SQLSRV - Conectar a bases de datos de MS SQL Server y de SQL Azure
    • Ds\Collection::clear - Removes all values
    • Ds\Collection::copy - Returns a shallow copy of the collection
    • Ds\Collection::isEmpty - Returns whether the collection is empty
    • Ds\Collection::toArray - Converts the collection to an array
    • Ds\Deque::allocate - Allocates enough memory for a required capacity
    • Ds\Deque::apply - Updates all values by applying a callback function to each value
    • Ds\Deque::capacity - Returns the current capacity
    • Ds\Deque::clear - Removes all values from the deque
    • Ds\Deque::contains - Determines if the deque contains given values
    • Ds\Deque::copy - Returns a shallow copy of the deque
    • Ds\Deque::count - Returns the number of values in the collection
    • Ds\Deque::filter - Creates a new deque using a callable to determine which values to include
    • Ds\Deque::find - Attempts to find a value's index
    • Ds\Deque::first - Returns the first value in the deque
    • Ds\Deque::get - Returns the value at a given index
    • Ds\Deque::insert - Inserts values at a given index
    • Ds\Deque::isEmpty - Returns whether the deque is empty
    • Ds\Deque::join - Joins all values together as a string
    • Ds\Deque::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Deque::last - Returns the last value
    • Ds\Deque::map - Returns the result of applying a callback to each value
    • Ds\Deque::merge - Returns the result of adding all given values to the deque
    • Ds\Deque::pop - Removes and returns the last value
    • Ds\Deque::push - Adds values to the end of the deque
    • Ds\Deque::reduce - Reduces the deque to a single value using a callback function
    • Ds\Deque::remove - Removes and returns a value by index
    • Ds\Deque::reverse - Reverses the deque in-place
    • Ds\Deque::reversed - Returns a reversed copy
    • Ds\Deque::rotate - Rotates the deque by a given number of rotations
    • Ds\Deque::set - Updates a value at a given index
    • Ds\Deque::shift - Removes and returns the first value
    • Ds\Deque::slice - Returns a sub-deque of a given range
    • Ds\Deque::sort - Sorts the deque in-place
    • Ds\Deque::sorted - Returns a sorted copy
    • Ds\Deque::sum - Returns the sum of all values in the deque
    • Ds\Deque::toArray - Converts the deque to an array
    • Ds\Deque::unshift - Adds values to the front of the deque
    • Ds\Deque::__construct - Creates a new instance
    • Ds\Hashable::equals - Determines whether an object is equal to the current instance
    • Ds\Hashable::hash - Returns a scalar value to be used as a hash value
    • Ds\Map::allocate - Allocates enough memory for a required capacity
    • Ds\Map::apply - Updates all values by applying a callback function to each value
    • Ds\Map::capacity - Returns the current capacity
    • Ds\Map::clear - Removes all values
    • Ds\Map::copy - Returns a shallow copy of the map
    • Ds\Map::count - Returns the number of values in the map
    • Ds\Map::diff - Creates a new map using keys that aren't in another map
    • Ds\Map::filter - Creates a new map using a callable to determine which pairs to include
    • Ds\Map::first - Returns the first pair in the map
    • Ds\Map::get - Returns the value for a given key
    • Ds\Map::hasKey - Determines whether the map contains a given key
    • Ds\Map::hasValue - Determines whether the map contains a given value
    • Ds\Map::intersect - Creates a new map by intersecting keys with another map
    • Ds\Map::isEmpty - Returns whether the map is empty
    • Ds\Map::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Map::keys - Returns a set of the map's keys
    • Ds\Map::ksort - Sorts the map in-place by key
    • Ds\Map::ksorted - Returns a copy, sorted by key
    • Ds\Map::last - Returns the last pair of the map
    • Ds\Map::map - Returns the result of applying a callback to each value
    • Ds\Map::merge - Returns the result of adding all given associations
    • Ds\Map::pairs - Returns a sequence containing all the pairs of the map
    • Ds\Map::put - Associates a key with a value
    • Ds\Map::putAll - Associates all key-value pairs of a traversable object or array
    • Ds\Map::reduce - Reduces the map to a single value using a callback function
    • Ds\Map::remove - Removes and returns a value by key
    • Ds\Map::reverse - Reverses the map in-place
    • Ds\Map::reversed - Returns a reversed copy
    • Ds\Map::skip - Returns the pair at a given positional index
    • Ds\Map::slice - Returns a subset of the map defined by a starting index and length
    • Ds\Map::sort - Sorts the map in-place by value
    • Ds\Map::sorted - Returns a copy, sorted by value
    • Ds\Map::sum - Returns the sum of all values in the map
    • Ds\Map::toArray - Converts the map to an array
    • Ds\Map::union - Creates a new map using values from the current instance and another map
    • Ds\Map::values - Returns a sequence of the map's values
    • Ds\Map::xor - Creates a new map using keys of either the current instance or of another map, but not of both
    • Ds\Map::__construct - Creates a new instance
    • Ds\Pair::clear - Removes all values
    • Ds\Pair::copy - Returns a shallow copy of the pair
    • Ds\Pair::isEmpty - Returns whether the pair is empty
    • Ds\Pair::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Pair::toArray - Converts the pair to an array
    • Ds\Pair::__construct - Creates a new instance
    • Ds\PriorityQueue::allocate - Allocates enough memory for a required capacity
    • Ds\PriorityQueue::capacity - Returns the current capacity
    • Ds\PriorityQueue::clear - Removes all values
    • Ds\PriorityQueue::copy - Returns a shallow copy of the queue
    • Ds\PriorityQueue::count - Returns the number of values in the queue
    • Ds\PriorityQueue::isEmpty - Returns whether the queue is empty
    • Ds\PriorityQueue::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\PriorityQueue::peek - Returns the value at the front of the queue
    • Ds\PriorityQueue::pop - Removes and returns the value with the highest priority
    • Ds\PriorityQueue::push - Pushes values into the queue
    • Ds\PriorityQueue::toArray - Converts the queue to an array
    • Ds\PriorityQueue::__construct - Creates a new instance
    • Ds\Queue::allocate - Allocates enough memory for a required capacity
    • Ds\Queue::capacity - Returns the current capacity
    • Ds\Queue::clear - Removes all values
    • Ds\Queue::copy - Returns a shallow copy of the queue
    • Ds\Queue::count - Returns the number of values in the queue
    • Ds\Queue::isEmpty - Returns whether the queue is empty
    • Ds\Queue::jsonSerialize - Regresa una representacion que puede ser convertida a 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 - Añade un elemento a la cola
    • Ds\Queue::toArray - Convierte la cola en un array
    • Ds\Queue::__construct - Creates a new instance
    • Ds\Sequence::allocate - Allocates enough memory for a required capacity
    • Ds\Sequence::apply - Updates all values by applying a callback function to each value
    • Ds\Sequence::capacity - Returns the current capacity
    • Ds\Sequence::contains - Determines if the sequence contains given values
    • Ds\Sequence::filter - Creates a new sequence using a callable to determine which values to include
    • Ds\Sequence::find - Attempts to find a value's index
    • Ds\Sequence::first - Returns the first value in the sequence
    • Ds\Sequence::get - Returns the value at a given index
    • Ds\Sequence::insert - Inserts values at a given index
    • Ds\Sequence::join - Joins all values together as a string
    • Ds\Sequence::last - Returns the last value
    • Ds\Sequence::map - Returns the result of applying a callback to each value
    • Ds\Sequence::merge - Returns the result of adding all given values to the sequence
    • Ds\Sequence::pop - Removes and returns the last value
    • Ds\Sequence::push - Adds values to the end of the sequence
    • Ds\Sequence::reduce - Reduces the sequence to a single value using a callback function
    • Ds\Sequence::remove - Removes and returns a value by index
    • Ds\Sequence::reverse - Reverses the sequence in-place
    • Ds\Sequence::reversed - Returns a reversed copy
    • Ds\Sequence::rotate - Rotates the sequence by a given number of rotations
    • Ds\Sequence::set - Updates a value at a given index
    • Ds\Sequence::shift - Removes and returns the first value
    • Ds\Sequence::slice - Returns a sub-sequence of a given range
    • Ds\Sequence::sort - Sorts the sequence in-place
    • Ds\Sequence::sorted - Returns a sorted copy
    • Ds\Sequence::sum - Returns the sum of all values in the sequence
    • Ds\Sequence::unshift - Adds values to the front of the sequence
    • Ds\Set::add - Adds values to the set
    • Ds\Set::allocate - Allocates enough memory for a required capacity
    • Ds\Set::capacity - Returns the current capacity
    • Ds\Set::clear - Removes all values
    • Ds\Set::contains - Determines if the set contains all values
    • Ds\Set::copy - Returns a shallow copy of the set
    • Ds\Set::count - Returns the number of values in the set
    • Ds\Set::diff - Creates a new set using values that aren't in another set
    • Ds\Set::filter - Creates a new set using a callable to determine which values to include
    • Ds\Set::first - Returns the first value in the set
    • Ds\Set::get - Returns the value at a given index
    • Ds\Set::intersect - Creates a new set by intersecting values with another set
    • Ds\Set::isEmpty - Returns whether the set is empty
    • Ds\Set::join - Joins all values together as a string
    • Ds\Set::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Set::last - Returns the last value in the set
    • Ds\Set::merge - Returns the result of adding all given values to the set
    • Ds\Set::reduce - Reduces the set to a single value using a callback function
    • Ds\Set::remove - Removes all given values from the set
    • Ds\Set::reverse - Reverses the set in-place
    • Ds\Set::reversed - Returns a reversed copy
    • Ds\Set::slice - Returns a sub-set of a given range
    • Ds\Set::sort - Sorts the set in-place
    • Ds\Set::sorted - Returns a sorted copy
    • Ds\Set::sum - Returns the sum of all values in the set
    • Ds\Set::toArray - Converts the set to an array
    • Ds\Set::union - Creates a new set using values from the current instance and another set
    • Ds\Set::xor - Creates a new set using values in either the current instance or in another set, but not in both
    • Ds\Set::__construct - Creates a new instance
    • Ds\Stack::allocate - Allocates enough memory for a required capacity
    • Ds\Stack::capacity - Returns the current capacity
    • Ds\Stack::clear - Removes all values
    • Ds\Stack::copy - Returns a shallow copy of the stack
    • Ds\Stack::count - Returns the number of values in the stack
    • Ds\Stack::isEmpty - Returns whether the stack is empty
    • Ds\Stack::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Stack::peek - Returns the value at the top of the stack
    • Ds\Stack::pop - Removes and returns the value at the top of the stack
    • Ds\Stack::push - Pushes values onto the stack
    • Ds\Stack::toArray - Converts the stack to an array
    • Ds\Stack::__construct - Creates a new instance
    • Ds\Vector::allocate - Allocates enough memory for a required capacity
    • Ds\Vector::apply - Updates all values by applying a callback function to each value
    • Ds\Vector::capacity - Returns the current capacity
    • Ds\Vector::clear - Removes all values
    • Ds\Vector::contains - Determines if the vector contains given values
    • Ds\Vector::copy - Returns a shallow copy of the vector
    • Ds\Vector::count - Returns the number of values in the collection
    • Ds\Vector::filter - Creates a new vector using a callable to determine which values to include
    • Ds\Vector::find - Attempts to find a value's index
    • Ds\Vector::first - Returns the first value in the vector
    • Ds\Vector::get - Returns the value at a given index
    • Ds\Vector::insert - Inserts values at a given index
    • Ds\Vector::isEmpty - Returns whether the vector is empty
    • Ds\Vector::join - Joins all values together as a string
    • Ds\Vector::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Vector::last - Returns the last value
    • Ds\Vector::map - Returns the result of applying a callback to each value
    • Ds\Vector::merge - Returns the result of adding all given values to the vector
    • Ds\Vector::pop - Removes and returns the last value
    • Ds\Vector::push - Adds values to the end of the vector
    • Ds\Vector::reduce - Reduces the vector to a single value using a callback function
    • Ds\Vector::remove - Removes and returns a value by index
    • Ds\Vector::reverse - Reverses the vector in-place
    • Ds\Vector::reversed - Returns a reversed copy
    • Ds\Vector::rotate - Rotates the vector by a given number of rotations
    • Ds\Vector::set - Updates a value at a given index
    • Ds\Vector::shift - Removes and returns the first value
    • Ds\Vector::slice - Returns a sub-vector of a given range
    • Ds\Vector::sort - Sorts the vector in-place
    • Ds\Vector::sorted - Returns a sorted copy
    • Ds\Vector::sum - Returns the sum of all values in the vector
    • Ds\Vector::toArray - Converts the vector to an array
    • Ds\Vector::unshift - Adds values to the front of the vector
    • Ds\Vector::__construct - Creates a new instance
  • e
    • each - Devolver el par clave/valor actual de un array y avanzar el cursor del array
    • easter_date - Obtener la fecha Unix para la medianoche de Pascua de un año dado
    • easter_days - Obtener el número de días despúes del 21 de marzo en el cuál cae Pascua para un año dado
    • echo - Muestra una o más cadenas
    • eio_busy - Incrementar artificialmente la carga. Podría ser útil en pruebas, evaluaciones comparativas
    • eio_cancel - Cancelar una petición
    • eio_chmod - Cambiar los permisos de fichero/directorio
    • eio_chown - Cambiar los permisos de un fichero/directorio
    • eio_close - Cerrar un fichero
    • eio_custom - Ejecutar una petición personalizada como cualquier otra llamada eio_*
    • eio_dup2 - Duplicar un descriptor de fichero
    • eio_event_loop - Monitorizar libeio hasta que todas las peticiones sean procesadas
    • eio_fallocate - Permitir al llamador manipular directamente el espacio de disco asignado a un fichero
    • eio_fchmod - Cambiar los permisos de un fichero
    • eio_fchown - Cambiar el propietario del fichero
    • eio_fdatasync - Sincronizar el estado de ficheros que están en memoria con un dispositivo de almacenamiento
    • eio_fstat - Obtener el estado de un fichero
    • eio_fstatvfs - Obtener las estadísticas del sistema de ficheros
    • eio_fsync - Sincronizar el estado de un fichero en memoria con un dispositivo de almacenamiento
    • eio_ftruncate - Truncar un fichero
    • eio_futime - Cambiar los momentos de último y acceso y modificación de un fichero
    • eio_get_event_stream - Obtiene un flujo que representa una variable usada en comnunicaciones internas con libeio
    • eio_get_last_error - Devuelve un string que describe el último error asociado con un recurso de petición
    • eio_grp - Crear un grupo de peticiones
    • eio_grp_add - Añadir una petición al grupo de peticiones
    • eio_grp_cancel - Cancelar un grupo de peticiones
    • eio_grp_limit - Establecer el límite de un grupo
    • eio_init - (Re-)inicializa Eio
    • eio_link - Crear un enlace duro par un fichero
    • eio_lstat - Obtener el estado de un fichero
    • eio_mkdir - Crear un directorio
    • eio_mknod - Crear un fichero especial u ordinario
    • eio_nop - No hace nada, sólo recorre el ciclo de peticiones entero
    • eio_npending - Devolver el número de peticiones, excepto las no manejadas
    • eio_nready - Devolver el número de peticiones aún no tratadas
    • eio_nreqs - Devuelve el número de peticiones a ser procesadas
    • eio_nthreads - Devuelve el número de hilos actualmente en uso
    • eio_open - Abrir un fichero
    • eio_poll - Puede ser llamada siempre que existan peticiones pendientes que necesitan ser finalizadas
    • eio_read - Leer de un descriptor de fichero en un índice dado
    • eio_readahead - Perform file readahead into page cache
    • eio_readdir - Leer un directorio al completo
    • eio_readlink - Leer el valor de un enlace simbólico
    • eio_realpath - Obtener el nombre de ruta absoluto canonizado
    • eio_rename - Cambiar el nombre o la ubicación de un fichero
    • eio_rmdir - Eliminar un directorio
    • eio_seek - Reposiciona el índice del fichero abierto asociado con el argumento fd al argumento offset según la directiva whence
    • eio_sendfile - Transferir información entre descriptores de ficheros
    • eio_set_max_idle - Establecer el número máximo de hilos parados
    • eio_set_max_parallel - Esteblecer el máximo de hilos paralelos
    • eio_set_max_poll_reqs - Establecer el máximo número de peticiones procesadas en una monitorización
    • eio_set_max_poll_time - Establecer el tiempo máximo de monitorización
    • eio_set_min_parallel - Esteblecer el número de hilos paralelos mínimo
    • eio_stat - Obtener el estado de un fichero
    • eio_statvfs - Obtener las estadísticas del sistema de ficheros
    • eio_symlink - Crear un enlace simbólico
    • eio_sync - Consignar el caché de buffer cache al disco
    • eio_syncfs - Realizar una llamada al sistema de syncfs de Linux si está disponible
    • eio_sync_file_range - Sincornizar un segmento de fichero con el disco
    • eio_truncate - Truncar un fichero
    • eio_unlink - Borrar un nombre y posiblemente el fichero al que se refiere
    • eio_utime - Cambiar los momentos de último y acceso y modificación de un fichero
    • eio_write - Escribir en un fichero
    • empty - Determina si una variable está vacía
    • EmptyIterator::current - El método current()
    • EmptyIterator::key - El método key()
    • EmptyIterator::next - El método next()
    • EmptyIterator::rewind - El método rewind()
    • EmptyIterator::valid - El método valid()
    • enchant_broker_describe - Enumera los proveedores de Enchant
    • enchant_broker_dict_exists - Si existe o no un diccionario. Usando una etiqueta no vacía
    • enchant_broker_free - Liberar el recurso de agente y sus diccionarios
    • enchant_broker_free_dict - Liberar un recurso de diccionario
    • enchant_broker_get_dict_path - Obtener la ruta del directorio para un 'backend' dado
    • enchant_broker_get_error - Devuelve el último error del agente
    • enchant_broker_init - Crear un nuevo objeto agente capaz de hacer peticiones
    • enchant_broker_list_dicts - Devuelve una lista de los diccionarios disponibles
    • enchant_broker_request_dict - Crear un diccionario usanto una etiqueta
    • enchant_broker_request_pwl_dict - Crea un diccionario usando un fichero PWL
    • enchant_broker_set_dict_path - Establecer la ruta del directorio para un 'backend' dado
    • enchant_broker_set_ordering - Declara una preferencia de diccionarios a usar para el lenguaje
    • enchant_dict_add - Add a word to personal word list
    • enchant_dict_add_to_personal - Añadir una palabra a una lista personal de palabras
    • enchant_dict_add_to_session - Añadir una palabra a esta sesión ortográfica
    • enchant_dict_check - Comprobar si una palabra está correctamente escrita o no
    • enchant_dict_describe - Describe un diccionario individual
    • enchant_dict_get_error - Devuelve el último error de la sesión ortográfica actual
    • enchant_dict_is_added - Whether or not 'word' exists in this spelling-session
    • enchant_dict_is_in_session - Si existe o no una palabra en esta sesión ortográfica
    • enchant_dict_quick_check - Verifica si la palabra está correctamente escrita y proporciona sugerencias
    • enchant_dict_store_replacement - Añadir una corrección a una palabra
    • enchant_dict_suggest - Devolverá una lista de valores si no se reúnen esas pre-condiciones
    • end - Establece el puntero interno de un array a su último elemento
    • ereg - Comparación de una expresión regular
    • eregi - Comparación de una expresión regular de forma insensible a mayúsculas-minúsculas
    • eregi_replace - Sustituye una expresión regular de forma insensible a mayúsculas-minúsculas
    • ereg_replace - Sustituye una expresión regular
    • Error::getCode - Obtener el código de error
    • Error::getFile - Obtener el fichero en el que ocurrío el error
    • Error::getLine - Obtener la línea en la que ocurrió el error
    • Error::getMessage - Obtener el mensaje de error
    • Error::getPrevious - Devuelve el objeto Throwable anterior
    • Error::getTrace - Obtener la traza de la pila
    • Error::getTraceAsString - Obtener la traza de la pila como un string
    • Error::__clone - Clonar el error
    • Error::__construct - Construir el objeto error
    • Error::__toString - Representación de string del error
    • ErrorException::getSeverity - Obtiene la severidad de la excepción
    • ErrorException::__construct - Constructor de la excepción
    • error_clear_last - Limpiar el error más reciente
    • error_get_last - Obtener el último error que ocurrió
    • error_log - Enviar un mensaje de error a las rutinas de manejo de errores definidas
    • error_reporting - Establece cuáles errores de PHP son notificados
    • escapeshellarg - Escapar una cadena a ser usada como argumento del intérprete de comandos
    • escapeshellcmd - Escapar meta-caracteres del intérprete de comandos
    • Ev::backend - Devuelve un entero que describe el back-end utilizado por libev
    • Ev::depth - Devuelve la profundidad de la recursividad
    • Ev::embeddableBackends - Returns the set of backends that are embeddable in other event loops
    • Ev::feedSignal - Feed a signal event info Ev
    • Ev::feedSignalEvent - Feed signal event into the default loop
    • Ev::iteration - Return the number of times the default event loop has polled for new events
    • Ev::now - Returns the time when the last iteration of the default event loop has started
    • Ev::nowUpdate - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress
    • Ev::recommendedBackends - Returns a bit mask of recommended backends for current platform
    • Ev::resume - Resume previously suspended default event loop
    • Ev::run - Begin checking for events and calling callbacks for the default loop
    • Ev::sleep - Block the process for the given number of seconds
    • Ev::stop - Stops the default event loop
    • Ev::supportedBackends - Returns the set of backends supported by current libev configuration
    • Ev::suspend - Suspend the default event loop
    • Ev::time - Returns the current time in fractional seconds since the epoch
    • Ev::verify - Performs internal consistency checks(for debugging)
    • eval - Evaluar una cadena como código de PHP
    • EvCheck::createStopped - Create instance of a stopped EvCheck watcher
    • EvCheck::__construct - Constructs the EvCheck watcher object
    • EvChild::createStopped - Create instance of a stopped EvCheck watcher
    • EvChild::set - Configures the watcher
    • EvChild::__construct - Constructs the EvChild watcher object
    • EvEmbed::createStopped - Create stopped EvEmbed watcher object
    • EvEmbed::set - Configures the watcher
    • EvEmbed::sweep - Realizar un único barrido sin bloqueos sobre el bucle embebido
    • EvEmbed::__construct - Constructs the EvEmbed object
    • Event::add - Makes event pending
    • Event::addSignal - Makes signal event pending
    • Event::addTimer - Makes timer event pending
    • Event::del - Makes event non-pending
    • Event::delSignal - Makes signal event non-pending
    • Event::delTimer - Makes timer event non-pending
    • Event::free - Make event non-pending and free resources allocated for this event
    • Event::getSupportedMethods - Returns array with of the names of the methods supported in this version of Libevent
    • Event::pending - Detects whether event is pending or scheduled
    • Event::set - Re-configures event
    • Event::setPriority - Set event priority
    • Event::setTimer - Re-configures timer event
    • Event::signal - Constructs signal event object
    • Event::timer - Constructs timer event object
    • Event::__construct - Constructs Event object
    • EventBase::dispatch - Despacha eventos pendientes
    • EventBase::exit - Detiene el envío de los eventos
    • EventBase::free - Free resources allocated for this event base
    • EventBase::getFeatures - Devuelve una máscara de bits de funcionalidades soportadas
    • EventBase::getMethod - Devuelve el método de evento utilizado
    • EventBase::getTimeOfDayCached - Devuelve el tiempo del evento base actual
    • EventBase::gotExit - Verifica si se ha indicado al bucle del evento de salir
    • EventBase::gotStop - Verifica si se ha indicado al bucle del evento de salir
    • EventBase::loop - Despacha eventos pendientes
    • EventBase::priorityInit - Define el número de prioridades por evento base
    • EventBase::reInit - Reinicializa el evento base (después de un 'fork')
    • EventBase::stop - Solicita a event_base que detenga la emisión de eventos
    • EventBase::__construct - Construye un objeto EventBase
    • EventBuffer::add - Añade datos al final de un buffer de eventos
    • EventBuffer::addBuffer - Mueve todos los datos de un buffer a la instancia actual de EventBuffer
    • EventBuffer::appendFrom - Mueve el número de bytes especificados desde un buffer fuente, al final del buffer actual
    • EventBuffer::copyout - Copia un número específico de bytes del principio del buffer
    • EventBuffer::drain - Elimina un número específico de bytes del principio del buffer sin copiarlo a ningún lugar
    • EventBuffer::enableLocking - Descripción
    • EventBuffer::expand - Reserva espacio en el buffer
    • EventBuffer::freeze - Evita que las llamadas puedan modificar un buffer de eventos
    • EventBuffer::lock - Bloquea un buffer
    • EventBuffer::prepend - Prepend data to the front of the buffer
    • EventBuffer::prependBuffer - Moves all data from source buffer to the front of current buffer
    • EventBuffer::pullup - Linearizes data within buffer and returns it's contents as a string
    • EventBuffer::read - Read data from an evbuffer and drain the bytes read
    • EventBuffer::readFrom - Read data from a file onto the end of the buffer
    • EventBuffer::readLine - Extracts a line from the front of the buffer
    • EventBuffer::search - Scans the buffer for an occurrence of a string
    • EventBuffer::searchEol - Scans the buffer for an occurrence of an end of line
    • EventBuffer::substr - Substracts a portion of the buffer data
    • EventBuffer::unfreeze - Re-enable calls that modify an event buffer
    • EventBuffer::unlock - Releases lock acquired by EventBuffer::lock
    • EventBuffer::write - Write contents of the buffer to a file or socket
    • EventBuffer::__construct - Construye el objeto EventBuffer
    • EventBufferEvent::close - Closes file descriptor associated with the current buffer event
    • EventBufferEvent::connect - Connect buffer event's file descriptor to given address or UNIX socket
    • EventBufferEvent::connectHost - Connects to a hostname with optionally asyncronous DNS resolving
    • EventBufferEvent::createPair - Creates two buffer events connected to each other
    • EventBufferEvent::disable - Disable events read, write, or both on a buffer event
    • EventBufferEvent::enable - Enable events read, write, or both on a buffer event
    • EventBufferEvent::free - Free a buffer event
    • EventBufferEvent::getDnsErrorString - Returns string describing the last failed DNS lookup attempt
    • EventBufferEvent::getEnabled - Returns bitmask of events currently enabled on the buffer event
    • EventBufferEvent::getInput - Returns underlying input buffer associated with current buffer event
    • EventBufferEvent::getOutput - Returns underlying output buffer associated with current buffer event
    • EventBufferEvent::read - Read buffer's data
    • EventBufferEvent::readBuffer - Drains the entire contents of the input buffer and places them into buf
    • EventBufferEvent::setCallbacks - Assigns read, write and event(status) callbacks
    • EventBufferEvent::setPriority - Assign a priority to a bufferevent
    • EventBufferEvent::setTimeouts - Set the read and write timeout for a buffer event
    • EventBufferEvent::setWatermark - Adjusts read and/or write watermarks
    • EventBufferEvent::sslError - Returns most recent OpenSSL error reported on the buffer event
    • EventBufferEvent::sslFilter - Crea un nuevo evento búfer SSL búfer para enviar sus datos a otro evento búfer
    • EventBufferEvent::sslGetCipherInfo - Returns a textual description of the cipher
    • EventBufferEvent::sslGetCipherName - Returns the current cipher name of the SSL connection
    • EventBufferEvent::sslGetCipherVersion - Returns version of cipher used by current SSL connection
    • EventBufferEvent::sslGetProtocol - Returns the name of the protocol used for current SSL connection
    • EventBufferEvent::sslRenegotiate - Tells a bufferevent to begin SSL renegotiation
    • EventBufferEvent::sslSocket - Creates a new SSL buffer event to send its data over an SSL on a socket
    • EventBufferEvent::write - Adds data to a buffer event's output buffer
    • EventBufferEvent::writeBuffer - Adds contents of the entire buffer to a buffer event's output buffer
    • EventBufferEvent::__construct - Constructs EventBufferEvent object
    • EventConfig::avoidMethod - Tells libevent to avoid specific event method
    • EventConfig::requireFeatures - Enters a required event method feature that the application demands
    • EventConfig::setMaxDispatchInterval - Prevents priority inversion
    • EventConfig::__construct - Constructs EventConfig object
    • EventDnsBase::addNameserverIp - Adds a nameserver to the DNS base
    • EventDnsBase::addSearch - Adds a domain to the list of search domains
    • EventDnsBase::clearSearch - Removes all current search suffixes
    • EventDnsBase::countNameservers - Gets the number of configured nameservers
    • EventDnsBase::loadHosts - Loads a hosts file (in the same format as /etc/hosts) from hosts file
    • EventDnsBase::parseResolvConf - Scans the resolv.conf-formatted file
    • EventDnsBase::setOption - Set the value of a configuration option
    • EventDnsBase::setSearchNdots - Set the 'ndots' parameter for searches
    • EventDnsBase::__construct - Constructs EventDnsBase object
    • EventHttp::accept - Makes an HTTP server accept connections on the specified socket stream or resource
    • EventHttp::addServerAlias - Adds a server alias to the HTTP server object
    • EventHttp::bind - Binds an HTTP server on the specified address and port
    • EventHttp::removeServerAlias - Removes server alias
    • EventHttp::setAllowedMethods - Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
    • EventHttp::setCallback - Sets a callback for specified URI
    • EventHttp::setDefaultCallback - Sets default callback to handle requests that are not caught by specific callbacks
    • EventHttp::setMaxBodySize - Sets maximum request body size
    • EventHttp::setMaxHeadersSize - Sets maximum HTTP header size
    • EventHttp::setTimeout - Sets the timeout for an HTTP request
    • EventHttp::__construct - Constructs EventHttp object(the HTTP server)
    • EventHttpConnection::getBase - Returns event base associated with the connection
    • EventHttpConnection::getPeer - Gets the remote address and port associated with the connection
    • EventHttpConnection::makeRequest - Makes an HTTP request over the specified connection
    • EventHttpConnection::setCloseCallback - Set callback for connection close
    • EventHttpConnection::setLocalAddress - Sets the IP address from which HTTP connections are made
    • EventHttpConnection::setLocalPort - Sets the local port from which connections are made
    • EventHttpConnection::setMaxBodySize - Sets maximum body size for the connection
    • EventHttpConnection::setMaxHeadersSize - Sets maximum header size
    • EventHttpConnection::setRetries - Sets the retry limit for the connection
    • EventHttpConnection::setTimeout - Sets the timeout for the connection
    • EventHttpConnection::__construct - Constructs EventHttpConnection object
    • EventHttpRequest::addHeader - Adds an HTTP header to the headers of the request
    • EventHttpRequest::cancel - Cancels a pending HTTP request
    • EventHttpRequest::clearHeaders - Removes all output headers from the header list of the request
    • EventHttpRequest::closeConnection - Closes associated HTTP connection
    • EventHttpRequest::findHeader - Finds the value belonging a header
    • EventHttpRequest::free - Frees the object and removes associated events
    • EventHttpRequest::getBufferEvent - Returns EventBufferEvent object
    • EventHttpRequest::getCommand - Returns the request command(method)
    • EventHttpRequest::getConnection - Returns EventHttpConnection object
    • EventHttpRequest::getHost - Returns the request host
    • EventHttpRequest::getInputBuffer - Returns the input buffer
    • EventHttpRequest::getInputHeaders - Returns associative array of the input headers
    • EventHttpRequest::getOutputBuffer - Returns the output buffer of the request
    • EventHttpRequest::getOutputHeaders - Returns associative array of the output headers
    • EventHttpRequest::getResponseCode - Returns the response code
    • EventHttpRequest::getUri - Returns the request URI
    • EventHttpRequest::removeHeader - Removes an HTTP header from the headers of the request
    • EventHttpRequest::sendError - Send an HTML error message to the client
    • EventHttpRequest::sendReply - Send an HTML reply to the client
    • EventHttpRequest::sendReplyChunk - Send another data chunk as part of an ongoing chunked reply
    • EventHttpRequest::sendReplyEnd - Complete a chunked reply, freeing the request as appropriate
    • EventHttpRequest::sendReplyStart - Initiate a chunked reply
    • EventHttpRequest::__construct - Constructs EventHttpRequest object
    • EventListener::disable - Disables an event connect listener object
    • EventListener::enable - Enables an event connect listener object
    • EventListener::getBase - Returns event base associated with the event listener
    • EventListener::getSocketName - Retreives the current address to which the listener's socket is bound
    • EventListener::setCallback - The setCallback purpose
    • EventListener::setErrorCallback - Set event listener's error callback
    • EventListener::__construct - Creates new connection listener associated with an event base
    • EventSslContext::__construct - Constructs an OpenSSL context for use with Event classes
    • EventUtil::getLastSocketErrno - Returns the most recent socket error number
    • EventUtil::getLastSocketError - Returns the most recent socket error
    • EventUtil::getSocketFd - Returns numeric file descriptor of a socket, or stream
    • EventUtil::getSocketName - Retreives the current address to which the socket is bound
    • EventUtil::setSocketOption - Sets socket options
    • EventUtil::sslRandPoll - Generates entropy by means of OpenSSL's RAND_poll()
    • EventUtil::__construct - The abstract constructor
    • EvFork::createStopped - Creates a stopped instance of EvFork watcher class
    • EvFork::__construct - Constructs the EvFork watcher object
    • EvIdle::createStopped - Creates instance of a stopped EvIdle watcher object
    • EvIdle::__construct - Constructs the EvIdle watcher object
    • EvIo::createStopped - Create stopped EvIo watcher object
    • EvIo::set - Configures the watcher
    • EvIo::__construct - Constructs EvIo watcher object
    • EvLoop::backend - Returns an integer describing the backend used by libev
    • EvLoop::check - Creates EvCheck object associated with the current event loop instance
    • EvLoop::child - Creates EvChild object associated with the current event loop
    • EvLoop::defaultLoop - Returns or creates the default event loop
    • EvLoop::embed - Creates an instance of EvEmbed watcher associated with the current EvLoop object
    • EvLoop::fork - Creates EvFork watcher object associated with the current event loop instance
    • EvLoop::idle - Creates EvIdle watcher object associated with the current event loop instance
    • EvLoop::invokePending - Invoke all pending watchers while resetting their pending state
    • EvLoop::io - Create EvIo watcher object associated with the current event loop instance
    • EvLoop::loopFork - Must be called after a fork
    • EvLoop::now - Returns the current "event loop time"
    • EvLoop::nowUpdate - Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress
    • EvLoop::periodic - Creates EvPeriodic watcher object associated with the current event loop instance
    • EvLoop::prepare - Creates EvPrepare watcher object associated with the current event loop instance
    • EvLoop::resume - Resume previously suspended default event loop
    • EvLoop::run - Begin checking for events and calling callbacks for the loop
    • EvLoop::signal - Creates EvSignal watcher object associated with the current event loop instance
    • EvLoop::stat - Creates EvStat watcher object associated with the current event loop instance
    • EvLoop::stop - Stops the event loop
    • EvLoop::suspend - Suspend the loop
    • EvLoop::timer - Creates EvTimer watcher object associated with the current event loop instance
    • EvLoop::verify - Performs internal consistency checks(for debugging)
    • EvLoop::__construct - Constructs the event loop object
    • EvPeriodic::again - Simply stops and restarts the periodic watcher again
    • EvPeriodic::at - Returns the absolute time that this watcher is supposed to trigger next
    • EvPeriodic::createStopped - Create a stopped EvPeriodic watcher
    • EvPeriodic::set - Configures the watcher
    • EvPeriodic::__construct - Constructs EvPeriodic watcher object
    • EvPrepare::createStopped - Crea una instancia detenida del watcher (testigo) EvPrepare
    • EvPrepare::__construct - Construye un objeto observador de EvPrepare
    • EvSignal::createStopped - Create stopped EvSignal watcher object
    • EvSignal::set - Configura el testigo
    • EvSignal::__construct - Construye el objeto observador EvSignal
    • EvStat::attr - Returns the values most recently detected by Ev
    • EvStat::createStopped - Create a stopped EvStat watcher object
    • EvStat::prev - Returns the previous set of values returned by EvStat::attr
    • EvStat::set - Configures the watcher
    • EvStat::stat - Initiates the stat call
    • EvStat::__construct - Constructs EvStat watcher object
    • EvTimer::again - Restarts the timer watcher
    • EvTimer::createStopped - Creates EvTimer stopped watcher object
    • EvTimer::set - Configures the watcher
    • EvTimer::__construct - Constructs an EvTimer watcher object
    • EvWatcher::clear - Clear watcher pending status
    • EvWatcher::feed - Feeds the given revents set into the event loop
    • EvWatcher::getLoop - Returns the loop responsible for the watcher
    • EvWatcher::invoke - Invokes the watcher callback with the given received events bit mask
    • EvWatcher::keepalive - Configures whether to keep the loop from returning
    • EvWatcher::setCallback - Sets new callback for the watcher
    • EvWatcher::start - Starts the watcher
    • EvWatcher::stop - Stops the watcher
    • EvWatcher::__construct - Abstract constructor of a watcher object
    • Exception::getCode - Obtiene el código de una excepción
    • Exception::getFile - Obtiene el fichero en el que se creó la excepción
    • Exception::getLine - Obtiene la línea en el que se creó la excepción
    • Exception::getMessage - Obtiene el mensaje de Excepción
    • Exception::getPrevious - Devuelve la excepción anterior
    • Exception::getTrace - Obtiene la traza de la pila
    • Exception::getTraceAsString - Obtiene la traza de la pila como una cadena de caracteres
    • Exception::__clone - Clona la excepción
    • Exception::__construct - Constructor de la excepción
    • Exception::__toString - Representación de la excepción en formato cadena
    • exec - Ejecutar un programa externo
    • exif_imagetype - Determinar el tipo de una imagen
    • exif_read_data - Lee las cabeceras EXIF desde un JPEG o un TIFF
    • exif_tagname - Obtener el nombre de la cabecera de un índice
    • exif_thumbnail - Recuperar la miniatura embebida de una imagen TIFF o JPEG
    • exit - Imprime un mensaje y termina el script actual
    • exp - Calcula la exponencial de e
    • expect:// - Flujos de Interacción de Procesos
    • expect_expectl - Espera a que la salida de un proceso coincida con un patrón, se supere un determinado periodo de tiempo, o se alcance un EOF
    • expect_popen - Ejecuta comandos por la shell Bourne, y abre el flujo PTY al proceso
    • explode - Divide un string en varios string
    • expm1 - Devuelve exp(numero)-1, calculado de tal forma que no pierde precisión incluso cuando el valor del numero se aproxima a cero.
    • extension_loaded - Encontrar si una extensión está cargada
    • extract - Importar variables a la tabla de símbolos actual desde un array
    • ezmlm_hash - Calcula el valor hash que necesita EZMLM
  • f
    • FANNConnection::getFromNeuron - Devuelve las posiciones de la neurona inicial
    • FANNConnection::getToNeuron - Devuelve las posiciones de la neurona terminal
    • FANNConnection::getWeight - Devuelve el peso de la conexión
    • FANNConnection::setWeight - Establece el peso de la conexión
    • FANNConnection::__construct - El constructor de la conexión
    • fann_cascadetrain_on_data - Entrena un conjunto de datos completo, por un período de tiempo utilizando el algoritmo de entrenamiento Cascade2
    • fann_cascadetrain_on_file - Entre un conjunto de datos completo desde un fichero, por un período de tiempo utilizando el algoritmo de entrenamiento Cascade2
    • fann_clear_scaling_params - Limpia los parámetros de escala
    • fann_copy - Crea una copia de una estructura fann
    • fann_create_from_file - Construye una red neuronal de retropropagación desde un fichero de configuración
    • fann_create_shortcut - Crea una red neuronal de retropropagación estándar que no está completamente conectada y que posee conexiones de atajo
    • fann_create_shortcut_array - Crea una red neuronal de retropropagación estándar que no está completamente conectada y que posee conexiones de atajo
    • fann_create_sparse - Crea una red neuronal de retropropagación estándar que no está conectada completamente
    • fann_create_sparse_array - Crea una red neuronal de retropropagación estándar que no está completamente conectada empleando un array con tamaños de capas
    • fann_create_standard - Crea una red neuronal de retropropagación estándar completamente conectada
    • fann_create_standard_array - Crea una red neuronal de retropropagación estándar completamente conectada empleando un array con tamaños de capas
    • fann_create_train - Crea una estructura de datos de entrenamiento vacía
    • fann_create_train_from_callback - Crea una estructura de datos de entrenamiento desde una función proporcionada por el usuario
    • fann_descale_input - Escalar datos en un vector de entrada después de obtenerlo de una RNA basada en parámetros previamente calculados
    • fann_descale_output - Escalar datos en un vector de entrada después de obtenerlo de una RNA basada en parámetros previamente calculados
    • fann_descale_train - Descalar datos de entrada y salida basados en parámetros previamente calculados
    • fann_destroy - Destruye la red por completo y libera adecuadamente toda la memoria asociada
    • fann_destroy_train - Destruye los datos de entrenamiento
    • fann_duplicate_train_data - Devuelve una copia exacta de uno datos de entrenamiento de fann
    • fann_get_activation_function - Devuelve la función de activación
    • fann_get_activation_steepness - Devuelve la pendiente de activación para el número de neurona y de capa proporcionados
    • fann_get_bias_array - Obtener el número de tendencias de cada capa de una red
    • fann_get_bit_fail - El número de bit fallidos
    • fann_get_bit_fail_limit - Devuelve el límite de fallo de bit empleado durante un entrenamiento
    • fann_get_cascade_activation_functions - Devuelve las funciones de activación en cascada
    • fann_get_cascade_activation_functions_count - Devuelve el número de funciones de activación en cascada
    • fann_get_cascade_activation_steepnesses - Devuelve las pendientes de activación en cascada
    • fann_get_cascade_activation_steepnesses_count - El número de pendientes de activación
    • fann_get_cascade_candidate_change_fraction - Devuelve la fracción de cambio de candidatas en cascada
    • fann_get_cascade_candidate_limit - Devuelve el límite de candidatas
    • fann_get_cascade_candidate_stagnation_epochs - Devuelve el número de épocas de estancamiento de candidatas en cascada
    • fann_get_cascade_max_cand_epochs - Devuelve el máximo de épocas de candidatas
    • fann_get_cascade_max_out_epochs - Devuelve el máximo de épocas de salida
    • fann_get_cascade_min_cand_epochs - Devuelve el mínimo de épocas de candidatas
    • fann_get_cascade_min_out_epochs - Devuelve el mínimo de épocas de salida
    • fann_get_cascade_num_candidates - Devuelve el número de candidatas empleadas durante un entrenamiento
    • fann_get_cascade_num_candidate_groups - Devuelve el número de grupos de candidatas
    • fann_get_cascade_output_change_fraction - Devuelve la fracción de cambio de salida en cascada
    • fann_get_cascade_output_stagnation_epochs - Devuelve el número de épocas de estancamiento de salida en cascada
    • fann_get_cascade_weight_multiplier - Devuelve el multiplicador de peso
    • fann_get_connection_array - Obtener las conexiones de la red
    • fann_get_connection_rate - Obtener el índice de conexión empleado al crear la red
    • fann_get_errno - Devuelve el número del último error
    • fann_get_errstr - Devuelve el string de último error
    • fann_get_layer_array - Obtener el número de neuronas de cada capa de la red
    • fann_get_learning_momentum - Devuelve el momento del aprendizaje
    • fann_get_learning_rate - Devuelve el índice de aprendizaje
    • fann_get_MSE - Lee el error cuadrático medio de la red
    • fann_get_network_type - Obtener el tipo de una red neuronal
    • fann_get_num_input - Obtener el número de neuronas de entrada
    • fann_get_num_layers - Obtener el número de capas de la red neuronal
    • fann_get_num_output - Obtener el número de neuronas de salida
    • fann_get_quickprop_decay - Devuelve la decadencia, que es un factor por el que los pesos deberían decrementar en cada iteración durante un entrenamiento quickprop
    • fann_get_quickprop_mu - Devuelve el factor mu
    • fann_get_rprop_decrease_factor - Devuelve el factor de disminución empleado durante un entrenamiento RPROP
    • fann_get_rprop_delta_max - Devuelve el tamaño de paso máximo
    • fann_get_rprop_delta_min - Devuelve el tamaño de paso mínimo
    • fann_get_rprop_delta_zero - Devuelve el tamaño de paso inicial
    • fann_get_rprop_increase_factor - Devuelve el factor de aumento empleado durante un entrenamiento RPROP
    • fann_get_sarprop_step_error_shift - Devuelve el desplazamiento del error de paso de sarprop
    • fann_get_sarprop_step_error_threshold_factor - Devuelve el factor de umbral del error de paso de sarprop
    • fann_get_sarprop_temperature - Devuelve la temperatura de sarprop
    • fann_get_sarprop_weight_decay_shift - Devuelve el desplazamiento de decadencia del peso de sarprop
    • fann_get_total_connections - Obtener el número total de conexiones de la red completa
    • fann_get_total_neurons - Obtener el número total de neuronas de la red completa
    • fann_get_training_algorithm - Devuelve el algoritmo de entrenamiento
    • fann_get_train_error_function - Devuelve la función de error empleada durante un entrenamiento
    • fann_get_train_stop_function - Devuelve la función de parada empleada durante el entrenamiento
    • fann_init_weights - Inicializar los pesos empleando el algoritmo de Widrow + Nguyen
    • fann_length_train_data - Devuelve el número de patrones de entrenamiento de los datos de entrenamiento
    • fann_merge_train_data - Funde los datos de entrenamiento
    • fann_num_input_train_data - Devuelve el número de entradas de cada patrón de entrenamiento de los datos de entrenamiento
    • fann_num_output_train_data - Devuelve el número de salidas de cada patrón de entrenamiento de los datos de entrenamiento
    • fann_print_error - Imprime el string de error
    • fann_randomize_weights - Dar a cada conexión un peso aleatorio entre min_weight y max_weight
    • fann_read_train_from_file - Lee un fichero que almacena datos de entrenamiento
    • fann_reset_errno - Reinicia el número del último error
    • fann_reset_errstr - Reinicia el string del último error
    • fann_reset_MSE - Reinicia el error cuadrático medio de la red
    • fann_run - Ejecutará la entrada a través de la red neuronal
    • fann_save - Guarda la red completa a un fichero de configuración
    • fann_save_train - Guarda la estructura de entrenamiento en un fichero
    • fann_scale_input - Escalar datos en un vector de entrada antes de alimentarlo a una RNA basada en parámetros previamente calculados
    • fann_scale_input_train_data - Escala las entradas de los datos de entrenamiento al rango especificado
    • fann_scale_output - Escalar datos en un vector de entrada antes de alimentarlo a una RNA basada en parámetros previamente calculados
    • fann_scale_output_train_data - Escala las salidas de los datos de entrenamiento al rango especificado
    • fann_scale_train - Escalar datos de entrada y salida basados en parámetros previamente calculados
    • fann_scale_train_data - Escala la entradas y salidas de los datos de entrenamiento al rango especificado
    • fann_set_activation_function - Establece la función de activación para la neurona y capa proporcionadas
    • fann_set_activation_function_hidden - Establece la función de activación para todas las capas ocultas
    • fann_set_activation_function_layer - Establece la función de activación para todas las neuronas de la capa proporcionada
    • fann_set_activation_function_output - Establece la función de activación para la capa de salida
    • fann_set_activation_steepness - Establece la pendiente de activación el número de neurona y capa proporcionados
    • fann_set_activation_steepness_hidden - Establece la pendiente de la activación para todas las neuronas de todas las capas ocultas
    • fann_set_activation_steepness_layer - Establece la pendiente de activación para todas las neuronas del número de capa proporcionada
    • fann_set_activation_steepness_output - Establece la pendiente de activación de la capa de salida
    • fann_set_bit_fail_limit - Establece el límite de fallo de bit empleado durante un entrenamiento
    • fann_set_callback - Establece la función de retrollamada a emplear durante el entrenamiento
    • fann_set_cascade_activation_functions - Establece el array de funciones de activación de candidatas en cascada
    • fann_set_cascade_activation_steepnesses - Establece el array de pendientes de activación de candidatas en cascada
    • fann_set_cascade_candidate_change_fraction - Establece la fracción de cambio de candidatas en cascada
    • fann_set_cascade_candidate_limit - Establece el límite de candidatas
    • fann_set_cascade_candidate_stagnation_epochs - Establece el número de épocas de estancamiento de candidatas en cascada
    • fann_set_cascade_max_cand_epochs - Establece el máximo de épocas de candidatas
    • fann_set_cascade_max_out_epochs - Establece el máximo de épocas de salida
    • fann_set_cascade_min_cand_epochs - Establece el mínimo de épocas de candidatas
    • fann_set_cascade_min_out_epochs - Establece el mínimo de épocas de salida
    • fann_set_cascade_num_candidate_groups - Establece el número de grupos de candidatas
    • fann_set_cascade_output_change_fraction - Establece la fracción de cambio de salida en cascada
    • fann_set_cascade_output_stagnation_epochs - Establece el número de épocas de estancamiento de salida en cascada
    • fann_set_cascade_weight_multiplier - Establece el multiplicador de peso
    • fann_set_error_log - Establece dónde registrar los errores
    • fann_set_input_scaling_params - Calcular los parámetros de escala de entrada para un uso futuro basados en datos de entrenamiento
    • fann_set_learning_momentum - Establece el momento del aprendizaje
    • fann_set_learning_rate - Establece el índice de aprendizaje
    • fann_set_output_scaling_params - Calcular los parámetros de escala de salida para un uso futuro basados en datos de entrenamiento
    • fann_set_quickprop_decay - Establece el factor de decadencia de quickprop
    • fann_set_quickprop_mu - Establece el factor mu de quickprop
    • fann_set_rprop_decrease_factor - Establece el factor de disminución empleado durante un entrenamiento RPROP
    • fann_set_rprop_delta_max - Establece el tamaño de paso máximo
    • fann_set_rprop_delta_min - Establece el tamaño de paso mínimo
    • fann_set_rprop_delta_zero - Establece el tamaño de paso inicial
    • fann_set_rprop_increase_factor - Establece el factor de aumento empleado durante un entrenamiento RPROP
    • fann_set_sarprop_step_error_shift - Establece el desplazamiento del error de paso de sarprop
    • fann_set_sarprop_step_error_threshold_factor - Establece el factor de umbral del error de paso de sarprop
    • fann_set_sarprop_temperature - Establece la temperatura de sarprop
    • fann_set_sarprop_weight_decay_shift - Establece el desplazamiento de decadencia del peso de sarprop
    • fann_set_scaling_params - Calcular los parámetros de escala de entrada y salida para un uso futuro basados en datos de entrenamiento
    • fann_set_training_algorithm - Establece el algoritmo de entrenamiento
    • fann_set_train_error_function - Establecer la función de error empleada durante un entrenamiento
    • fann_set_train_stop_function - Establece la función de parada empleada durante el entrenamiento
    • fann_set_weight - Establecer una conexión de la red
    • fann_set_weight_array - Establecer las conexiones de la red
    • fann_shuffle_train_data - Mezcla los datos de entrenamiento, aleatorizando el orden
    • fann_subset_train_data - Devuelve una copia de un subconjunto de los datos de entrenamiento
    • fann_test - Probar con un conjunto de entradas, y un conjunto de salidas deseadas
    • fann_test_data - Prueba un conjunto de datos de entrenamiento y calcula el ECM de dichos datos
    • fann_train - Entrenar una iteración con un conjunto de entradas y un conjunto de salidas deseadas
    • fann_train_epoch - Entrenar una época con un conjunto de datos de entrenamiento
    • fann_train_on_data - Entrena un conjunto de datos completo por un período de tiempo
    • fann_train_on_file - Entrena un conjunto de datos completo leído desde un fichero, por un período de tiempo
    • fastcgi_finish_request - Flushes all response data to the 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 - Cancel creating 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
    • fbsql_affected_rows - Obtiene el numero de filas afectadas en la anterior operación de FrontBase
    • fbsql_autocommit - Activa o desactiva el autocommit
    • fbsql_blob_size - Obtiene el tamaño de un BLOB
    • fbsql_change_user - Cambia el usuario logueado en la conexión activa
    • fbsql_clob_size - Obtiene el tamaño de un CLOB
    • fbsql_close - Cierra la conexión FrontBase
    • fbsql_commit - Ejecuta un commit de la transacción sobre la base de datos
    • fbsql_connect - Abre una conexión a un servidor FrontBase
    • fbsql_create_blob - Crea un BLOB
    • fbsql_create_clob - Crea un CLOB
    • fbsql_create_db - Crea una base de datos FrontBase
    • fbsql_database - Obtiene o especifica la base de datos usada por la conexión
    • fbsql_database_password - Asigna o recupera el password de una base de datos FrontBase
    • fbsql_data_seek - Mueve el puntero interno de resultado
    • fbsql_db_query - Ejecuta una consulta a FrontBase
    • fbsql_db_status - Obtiene el estado de una base de datos dada
    • fbsql_drop_db - Elimina (drop) una base de datos FrontBase
    • fbsql_errno - Devuelve el número de error de la última operación
    • fbsql_error - Devuelve el mensaje de error de la última operación
    • fbsql_fetch_array - Obtiene una fila de resultados como array asociativo, array numérico, o ambos
    • fbsql_fetch_assoc - Obtiene una fila de resultados como array asociativo
    • fbsql_fetch_field - Obtiene información de columnas de un resultado y la devuelve como objeto
    • fbsql_fetch_lengths - Obtiene la longitud de cada salida en un resultado
    • fbsql_fetch_object - Obtiene una fila de resultados como objeto
    • fbsql_fetch_row - Obtiene una fila de resultados como array enumerado
    • fbsql_field_flags - Obtiene los flags de un campo especificado en un resultado
    • fbsql_field_len - Devuleve la longitud de un campo especificado
    • fbsql_field_name - Obtiene el nombre de un campo especificado en un resultado
    • fbsql_field_seek - Mueve el puntero interno de resultado al campo con la posición especificada
    • fbsql_field_table - Obtiene el nombre de la tabla donde se encuentra el campo especificado
    • fbsql_field_type - Obtiene el tipo de campo especificado en un resultado
    • fbsql_free_result - Libera la memoria de resultados
    • fbsql_get_autostart_info - Descripción
    • fbsql_hostname - Obtiene o establece el nombre host de una conexión
    • fbsql_insert_id - Obtiene el valor id generado por la anterior operación INSERT
    • fbsql_list_dbs - Lista las bases de datos disponibles en un servidor FrontBase
    • fbsql_list_fields - Lista los campos de un resultado de FrontBase
    • fbsql_list_tables - Lista las tablas de una base de datos FrontBase
    • fbsql_next_result - Mover el puntero del resultado interno por el resultado de al lado
    • fbsql_num_fields - Obtener el número de campos del resultado
    • fbsql_num_rows - Obtener el número de filas del resultado
    • fbsql_password - Obtiene o asigna el password usado en una conexión
    • fbsql_pconnect - Abrir una conexión persistente a un servidor FrontBase
    • fbsql_query - Realiza una consulta FrontBase
    • fbsql_read_blob - Lee un BLOB de la base de datos
    • fbsql_read_clob - Lee un CLOB de la base de datos
    • fbsql_result - Obtiene los datos de resultado
    • fbsql_rollback - Retrocede una transacción a la base de datos
    • fbsql_rows_fetched - Obtiene el número de filas afectadas por la última consulta
    • fbsql_select_db - Selecciona una base de datos FrontBase
    • fbsql_set_characterset - Cambia el juego de caracteres de entrada/salida
    • fbsql_set_lob_mode - Asigna el modo de recuperación LOB para un set de resultados FrontBase
    • fbsql_set_password - Cambia la contraseña para el usuario especificado
    • fbsql_set_transaction - Asigna el bloqueo y aislamiento de la transacción
    • fbsql_start_db - Inicia una base de datos en un servidor local o remoto
    • fbsql_stop_db - Detiene una base de datos en un servidor local o remoto
    • fbsql_tablename - Alias de fbsql_table_name
    • fbsql_table_name - Obtiene el nombre de una tabla
    • fbsql_username - Obtiene o asigna el nombre de usuario de la conexión
    • fbsql_warnings - Activa o desactiva los warnings de FrontBase
    • fclose - Cierra un puntero a un archivo abierto
    • fdf_add_doc_javascript - Añadir código javascript al documento FDF
    • fdf_add_template - Añadir una plantilla al documento FDF
    • fdf_close - Cierra un documento FDF
    • fdf_create - Crear un nuevo documento FDF
    • fdf_enum_values - Invocar una función definida por el usuario por cada dato del documento
    • fdf_errno - Devuelve el código de error de la última operación sobre fdf
    • fdf_error - Consultar la descripción de un código de error FDF
    • fdf_get_ap - Consultar la publicación de un campo
    • fdf_get_attachment - Extraer un fichero subido por FDF
    • fdf_get_encoding - Consultar el valor de la clave /Encoding
    • fdf_get_file - Obtener el valor de la clave /F
    • fdf_get_flags - Consultar banderas de un campo
    • fdf_get_opt - Consultar un valor del array de opciones de un campo
    • fdf_get_status - Obtener el valor de la clave /STATUS
    • fdf_get_value - Obtener el valor de un campo
    • fdf_get_version - Consulta el número de versión de la API o de un fichero FDF
    • fdf_header - Establecer cabeceras de salida específicas de FDF
    • fdf_next_field_name - Obtener el siguiente nombre de campo
    • fdf_open - Abrir un documento FDF
    • fdf_open_string - Consulta un documento FDF a partir de un string
    • fdf_remove_item - Asignar contenedor para el formulario
    • fdf_save - Guardar un documento FDF
    • fdf_save_string - Devuelve el documento FDF en forma de string
    • fdf_set_ap - Establecer la apariencia de un campo
    • fdf_set_encoding - Asignar codificación de caracteres de FDF
    • fdf_set_file - Establecer el documento PDF en donde desplegar datos FDF
    • fdf_set_flags - Establecer banderas de un campo
    • fdf_set_javascript_action - Añadir una acción javascript a un campo
    • fdf_set_on_import_javascript - Añadir código javascript para ejecutar cuando Acrobat abra el FDF
    • fdf_set_opt - Establecer una opción sobre un campo
    • fdf_set_status - Establecer el valor de la clave /STATUS
    • fdf_set_submit_form_action - Asignar acción a un campo de formulario al enviarse
    • fdf_set_target_frame - Definir contenedor en el que mostrar el formulario
    • fdf_set_value - Establecer el valor de un campo
    • fdf_set_version - Asignar número de versión a un fichero FDF
    • fdiv - Divides two numbers, according to IEEE 754
    • feof - Comprueba si el puntero a un archivo está al final del archivo
    • FFI::addr - Creates an unmanaged pointer to C data
    • FFI::alignof - Gets the alignment
    • FFI::arrayType - Dynamically constructs a new C array type
    • FFI::cast - Performs a C type cast
    • FFI::cdef - Creates a new FFI object
    • FFI::free - Releases an unmanaged data structure
    • FFI::isNull - Checks whether a FFI\CData is a null pointer
    • FFI::load - Loads C declarations from a C header file
    • FFI::memcmp - Compares memory areas
    • FFI::memcpy - Copies one memory area to another
    • FFI::memset - Fills a memory area
    • FFI::new - Creates a C data structure
    • FFI::scope - Instantiates an FFI object with C declarations parsed during preloading
    • FFI::sizeof - Gets the size of C data or types
    • FFI::string - Creates a PHP string from a memory area
    • FFI::type - Creates an FFI\CType object from a C declaration
    • FFI::typeof - Gets the FFI\CType of FFI\CData
    • fflush - Vuelca la salida a un archivo
    • fgetc - Obtiene un carácter de un puntero a un archivo
    • fgetcsv - Obtiene una línea de un puntero a un fichero y la analiza en busca de campos CSV
    • fgets - Obtiene una línea desde el puntero a un fichero
    • fgetss - Obtiene un línea desde un puntero a un archivo y elimina las etiquetas HTML
    • file - Transfiere un fichero completo a un array
    • file:// - Acceso al sistema de ficheros local
    • fileatime - Obtiene el momento del último acceso a un archivo
    • filectime - Obtiene el momento del último cambio del i-nodo de un archivo
    • filegroup - Obtiene el grupo de un archivo
    • fileinode - Obtiene el i-nodo del archivo
    • filemtime - Obtiene el momento de la última modificación de un archivo
    • fileowner - Obtiene el propietario de un archivo
    • fileperms - Obtiene los permisos de un fichero
    • filepro - Lee y verifica el mapa del fichero
    • filepro_fieldcount - Encuentra cuantos campos hay en una base de datos filePro
    • filepro_fieldname - Obtiene el nombre de un campo
    • filepro_fieldtype - Obtiene el tipo de campo
    • filepro_fieldwidth - Obtiene el ancho de un campo
    • filepro_retrieve - Obtiene datos de una base de datos filePro
    • filepro_rowcount - Averigüa cuantas filas hay en una base de datos filePro
    • filesize - Obtiene el tamaño de un fichero
    • FilesystemIterator::current - El fichero actual
    • FilesystemIterator::getFlags - Obtiene el manejo de flags
    • FilesystemIterator::key - Recupera la clave del fichero actual
    • FilesystemIterator::next - Moverse al siguiente fichero
    • FilesystemIterator::rewind - Rebobina hasta volver al inicio
    • FilesystemIterator::setFlags - Establece las flags de manejo
    • FilesystemIterator::__construct - Construye un nuevo iterador filesystem
    • filetype - Obtiene el tipo de fichero
    • file_exists - Comprueba si existe un fichero o directorio
    • file_get_contents - Transmite un fichero completo a una cadena
    • file_put_contents - Escribir datos en un fichero
    • FilterIterator::accept - Comprueba si el elemento actual del iterador es aceptable
    • FilterIterator::current - Obtiene el valor del elemento actual
    • FilterIterator::getInnerIterator - Obtiene el iterador interno
    • FilterIterator::key - Obtiene la clave actual
    • FilterIterator::next - Mueve el iterador a la siguiente posición
    • FilterIterator::rewind - Rebobina el iterador
    • FilterIterator::valid - Comprueba si el elemento actual es válido
    • FilterIterator::__construct - Construye un filterIterator
    • filter_has_var - Comprueba si existe una variable de un tipo concreto existe
    • filter_id - Indica el ID del nombre de filtro que se indique
    • filter_input - Toma una variable externa concreta por su nombre y opcionalmente la filtra
    • filter_input_array - Obtiene variables externas y opcionalmente las filtra
    • filter_list - Devuelve una lista de todos los filtros soportados
    • filter_var - Filtra una variable con el filtro que se indique
    • filter_var_array - Retorna múltiple variables y opcionalmente las filtra
    • 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 - Cierra el recurso fileinfo
    • finfo_open - Crea un nuevo recurso fileinfo
    • floatval - Obtener el valor flotante de una variable
    • flock - Bloqueo de ficheros recomendado y portable
    • floor - Redondear fracciones hacia abajo
    • flush - Vaciar el búfer de salida del sistema
    • fmod - Devuelve el resto en punto flotante (módulo) de la división de los argumentos
    • fnmatch - Compara un nombre de fichero con un patrón
    • fopen - Abre un fichero o un URL
    • forward_static_call - Llamar a un método estático
    • forward_static_call_array - Llamar a un método estático y pasar los argumentos como matriz
    • fpassthru - Escribe toda la información restante de un puntero a un archivo
    • fprintf - Escribir una cadena con formato a una secuencia
    • fputcsv - Dar formato CSV a una línea y escribirla en un puntero a un fichero
    • fputs - Alias de fwrite
    • fread - Lectura de un fichero en modo binario seguro
    • frenchtojd - Convierte una fecha del Calendario Republicano Francés a una fecha Juliana
    • fscanf - Analiza la entrada desde un archivo de acuerdo a un formato
    • fseek - Busca sobre un puntero a un fichero
    • fsockopen - Abre una conexión vía sockets a Internet o a un dominio Unix
    • fstat - Obtiene información acerca de un archivo usando un puntero al archivo abierto
    • ftell - Devuelve la posición de lectura/escritura actual del puntero a un fichero
    • ftok - Convertir un nombre de ruta y un identificador de proyecto a una clave IPC de System V
    • ftp:// - Acceso a URLs por FTP(s)
    • ftp_alloc - Reserva espacio para que un archivo sea cargado
    • ftp_append - Append the contents of a file to another file on the FTP server
    • ftp_cdup - Vuelve al directorio padre
    • ftp_chdir - Cambia el directorio actual en un servidor FTP
    • ftp_chmod - Establecer permisos en un archivo via FTP
    • ftp_close - Cierra una conexión FTP
    • ftp_connect - Abre una conexión FTP
    • ftp_delete - Elimina un archivo en el servidor FTP
    • ftp_exec - Solicita la ejecución de un comando en el servidor FTP
    • ftp_fget - Descarga un archivo desde el servidor FTP y lo guarda en un archivo abierto
    • ftp_fput - Carga un archivo abierto en el servidor FTP
    • ftp_get - Descarga un archivo desde el servidor FTP
    • ftp_get_option - Recupera varios comportamientos de tiempo de ejecución de la secuencia FTP actual
    • ftp_login - Inicia sesión en una conexión FTP
    • ftp_mdtm - Devuelve el tiempo de la última modificación del archivo dado
    • ftp_mkdir - Crea un directorio
    • ftp_mlsd - Returns a list of files in the given directory
    • ftp_nb_continue - Continúa recuperando/enviando un archivo (modo no-bloqueo)
    • ftp_nb_fget - Recupera un archivo desde el servidor FTP y lo escribe en un archivo abierto (modo no-bloqueo)
    • ftp_nb_fput - Almacena un archivo desde un archivo abierto en el servidor FTP (modo no-bloqueo)
    • ftp_nb_get - Recupera un archivo desde el servidor FTP y lo escribe en un archivo local (modo no-bloqueo)
    • ftp_nb_put - Almacena un archivo en el servidor FTP (modo no-bloqueo)
    • ftp_nlist - Devuelve una lista de los archivos que se encuentran en el directorio especificado
    • ftp_pasv - Activa o desactiva el modo pasivo
    • ftp_put - Carga un archivo al servidor FTP
    • ftp_pwd - Devuelve el nombre del directorio actual
    • ftp_quit - Alias de ftp_close
    • ftp_raw - Envía un comando arbitrario a un servidor FTP
    • ftp_rawlist - Devuelve una lista detallada de archivos en el directorio especificado
    • ftp_rename - Renombra un archivo o un directorio en el servidor FTP
    • ftp_rmdir - Elimina un directorio
    • ftp_set_option - Establecer varias opciones FTP de tiempo de ejecución
    • ftp_site - Envía un comando SITE al servidor
    • ftp_size - Devuelve el tamaño del archivo dado
    • ftp_ssl_connect - Abre una conexión segura SSL-FTP
    • ftp_systype - Devuelve el identificador del tipo de sistema del servidor FTP remoto
    • ftruncate - Trunca un archivo a una longitud dada
    • function_exists - Devuelve true si la función dada ha sido definida
    • func_get_arg - Devuelve un elemento de una lista de argumentos
    • func_get_args - Devuelve un array que se compone de una lista de argumentos de función
    • func_num_args - Devuelve el número de argumentos pasados a la función
    • fwrite - Escritura de un archivo en modo binario seguro
  • g
    • gc_collect_cycles - Fuerza la recolección de los ciclos de basura existentes
    • gc_disable - Desactiva el recolector de referencia circular
    • gc_enable - Activa el colector de referencia circular
    • gc_enabled - Devuelve el estado del colector de referencia circular
    • gc_mem_caches - Reclaims memory used by the Zend Engine memory manager
    • gc_status - Gets information about the garbage collector
    • gd_info - Reunir información acerca de la biblioteca GD instalada actualmente
    • GearmanClient::addOptions - Añade opciones al cliente
    • GearmanClient::addServer - Añade un servidor de trabajos al cliente
    • GearmanClient::addServers - Añade una lista de servidores de trabajos al cliente
    • GearmanClient::addTask - Añade una tarea para ser ejecutada en paralelo
    • GearmanClient::addTaskBackground - Ejecuta una tarea en segundo plano para ser ejecutada en paralelo
    • GearmanClient::addTaskHigh - Añade una tarea de alta prioridad para ser ejecutada en paralelo
    • GearmanClient::addTaskHighBackground - Añade una tarea de alta prioridad ejecutada en segundo plano y en paralelo
    • GearmanClient::addTaskLow - Añade una tarea de baja prioridad para ejecutar en paralelo
    • GearmanClient::addTaskLowBackground - Añade una tarea de baja prioridad en segundo plano para ser ejecutada en paralelo
    • GearmanClient::addTaskStatus - Añade una tarea para obtener el estado
    • GearmanClient::clearCallbacks - Elimina todas las funciones de retorno de llamada
    • GearmanClient::clone - Crea una copia de un objeto GearmanClient
    • GearmanClient::context - Obtiene el contexto de la aplicación
    • GearmanClient::data - Retorna los datos de aplicación (obsoleto)
    • GearmanClient::do - Ejecuta una sola tarea y retorna el resultado [obsoleto]
    • GearmanClient::doBackground - Ejecuta una tarea en segundo plano
    • GearmanClient::doHigh - Ejecuta una tarea de prioridad alta
    • GearmanClient::doHighBackground - Ejecuta una tarea de alta prioridad en segundo plano
    • GearmanClient::doJobHandle - Obtiene el manejador de trabajo para la tarea en ejecución
    • GearmanClient::doLow - Ejecuta una tarea de baja prioridad
    • GearmanClient::doLowBackground - Ejecuta una tarea de prioridad baja en segundo plano
    • GearmanClient::doNormal - Ejecutar una única tarea y devolver un resultado
    • GearmanClient::doStatus - Obtiene el estado de la tarea en ejecución
    • GearmanClient::echo - Envía datos a todos los servidores de trabajo para ver si retornan [obsoleto]
    • GearmanClient::error - Retorna un string con el último error encontrado
    • GearmanClient::getErrno - Obtiene un valor errno
    • GearmanClient::jobStatus - Obtiene el estado de un trabajo en segundo plano
    • GearmanClient::ping - Envar datos a todos los servidores de trabajo para ver si los repiten
    • GearmanClient::removeOptions - Elimina opciones del cliente
    • GearmanClient::returnCode - Obtiene el último código de retorno de Gearman
    • GearmanClient::runTasks - Ejecuta una lista de tareas en paralelo
    • GearmanClient::setClientCallback - Función de llamada de retorno cuando hay un paquete de datos para una tarea (obsoleto)
    • GearmanClient::setCompleteCallback - Especifica una función a ser llamada cuando se complete una tarea
    • GearmanClient::setContext - Establece el contexto de la aplicación
    • GearmanClient::setCreatedCallback - Establece una llamada de retornopara cuando se encola una tarea
    • GearmanClient::setData - Establece los datos de aplicación (obsoleto)
    • GearmanClient::setDataCallback - Función de llamada de retorno para cuando hay un paquete de datos para la tarea
    • GearmanClient::setExceptionCallback - Establece una llamada de retorno para excepciones del trabajador
    • GearmanClient::setFailCallback - Establece una llamada de retorno para cuando falla un trabajo
    • GearmanClient::setOptions - Establece opciones del cliente
    • GearmanClient::setStatusCallback - Establece una llamada de retorno para obtener el estado de una tarea
    • GearmanClient::setTimeout - Establece el tiempo máximo de inactividad para actividad de entrada/salida en el socket
    • GearmanClient::setWarningCallback - Establece una llamada de retorno para los warnings del trabajador
    • GearmanClient::setWorkloadCallback - Establece una llamada de retorno para aceptar actualizaciones incrementales de datos
    • GearmanClient::timeout - Obtiene el tiempo máximo de inactividad de entrada/salida para el socket
    • GearmanClient::wait - Wait for I/O activity on all connections in a client
    • GearmanClient::__construct - Crea una instancia de GearmanClient
    • GearmanJob::complete - Envía el resultado y el estado completo (obsoleto)
    • GearmanJob::data - Envía datos para un trabajo en ejecución (obsoleto)
    • GearmanJob::exception - Envía una excepción para un trabajo en ejecución (obsoleto)
    • GearmanJob::fail - Envía el estado de fallo (obsoleto)
    • GearmanJob::functionName - Retorna el nombre de la función
    • GearmanJob::handle - Retorna el manejador para el trabajo
    • GearmanJob::returnCode - Obtiene el último código de retorno
    • GearmanJob::sendComplete - Envía el resultado y el estado completado
    • GearmanJob::sendData - Envía datos para un trabajo en ejecución
    • GearmanJob::sendException - Envía una excepción para un trabajo en ejecución
    • GearmanJob::sendFail - Envía el estado de fallo
    • GearmanJob::sendStatus - Envía el estado
    • GearmanJob::sendWarning - Envía una advertencia
    • GearmanJob::setReturn - Establece el valor de retorno
    • GearmanJob::status - Envía el estado (obsoleto)
    • GearmanJob::unique - Obtiene el identificador único
    • GearmanJob::warning - Envía un aviso (obsoleto)
    • GearmanJob::workload - Obtiene la carga de trabajo
    • GearmanJob::workloadSize - Obtiene el tamaño de la carga de trabajo
    • GearmanJob::__construct - Crea una instancia de GearmanJob
    • GearmanTask::create - Crea una tarea (obsoleto)
    • GearmanTask::data - Obtiene los datos retornados para una tarea
    • GearmanTask::dataSize - Obtiene el tamaño de la información retornada
    • GearmanTask::function - Obtiene el nombre de la función asociada (obsoleto)
    • GearmanTask::functionName - Retorna el nombre de la función asociada
    • GearmanTask::isKnown - Determina si la tarea es conocida
    • GearmanTask::isRunning - Comprueba si la tarea está siendo ejecutada
    • GearmanTask::jobHandle - Retorna el manejador del trabajo
    • GearmanTask::recvData - Guarda un trabajo o los datos resultantes de una tarea en un buffer
    • GearmanTask::returnCode - Retorna el último código de error
    • GearmanTask::sendData - Envía datos a una tarea (obsoleto)
    • GearmanTask::sendWorkload - Envía datos a una tarea
    • GearmanTask::taskDenominator - Obtiene el denominador del porcentaje de tarea completada
    • GearmanTask::taskNumerator - Retorna el numerador del tanto por ciento completado de la tarea, expresado como una fracción
    • GearmanTask::unique - Obtiene el identificador único de una tarea
    • GearmanTask::uuid - Obtiene el identificador único de una tarea (obsoleto)
    • GearmanTask::__construct - Crea una instancia de GearmanTask
    • GearmanWorker::addFunction - Registra y añade una función de retorno
    • GearmanWorker::addOptions - Añade opciones al trabajador
    • GearmanWorker::addServer - Añade un servidor de trabajo
    • GearmanWorker::addServers - Añade servidores de trabajo
    • GearmanWorker::clone - Crea una copia del trabajador
    • GearmanWorker::echo - Comprueba la respuesta de un servidor de trabajo
    • GearmanWorker::error - Retorna el último error que ha ocurrido
    • GearmanWorker::getErrno - Obtiene el código de error
    • GearmanWorker::options - Retorna las opciones del trabajador
    • GearmanWorker::register - Registra una función en el servidor de trabajo
    • GearmanWorker::removeOptions - Elimina las opciones del trabajador
    • GearmanWorker::returnCode - Obtiene el último código de retorno de Gearman
    • GearmanWorker::setId - Asigna un identificador al trabajador de tal forma que pueda ser rastreado cuando se solicite a gearmand la lista de los trabajadores disponibles
    • GearmanWorker::setOptions - Establece las opciones del trabajador
    • GearmanWorker::setTimeout - Establece un tiempo de espera máximo para actividad de entrada/salida del socket
    • GearmanWorker::timeout - Retorna el tiempo máximo de espera para actividad de entrada/salida del socket
    • GearmanWorker::unregister - Elimina el registro del nombre de una función en los servidores de trabajo
    • GearmanWorker::unregisterAll - Elimina el registro de todas los nombres de funciones en los servidores de trabajo
    • GearmanWorker::wait - Espera cualquier actividad de uno de los servidores de trabajo
    • GearmanWorker::work - Espera y realiza un trabajo
    • GearmanWorker::__construct - Crea una instancia GearmanWorker
    • Gender\Gender::connect - Conecta con un diccionario de nombres externo
    • Gender\Gender::country - Obtener la representación textual de un país
    • Gender\Gender::get - Obtener el género de un nombre
    • Gender\Gender::isNick - Comprueba si name0 es un alias de name1
    • Gender\Gender::similarNames - Obtener nombres similares
    • Gender\Gender::__construct - Construye un objeto Gender
    • Generator::current - Obtener el valor producido
    • Generator::getReturn - Obtener el valor devuelto de un generador
    • Generator::key - Obtener la clave generada
    • Generator::next - Continua la ejecución del generador
    • Generator::rewind - Rebobina el iterador
    • Generator::send - Enviar un valor al generador
    • Generator::throw - Lanzar una excepción dentro generador
    • Generator::valid - Verificar si el iterador ha sido cerrado
    • Generator::__wakeup - Serialize callback
    • geoip_asnum_by_name - Obtiene los Números de sistemas autónomos (ASN)
    • geoip_continent_code_by_name - Obtiene la abreviación de dos letras del continente
    • geoip_country_code3_by_name - Obtiene la abreviación de tres letras del país
    • geoip_country_code_by_name - Obtiene la abreviación de dos letras del país
    • geoip_country_name_by_name - Obtiene el nombre del país completo
    • geoip_database_info - Obtener información de la base de datos GeoIP
    • geoip_db_avail - Determina si la base de datos GeoIP está disponible
    • geoip_db_filename - Devuelve el nombre del fichero correspondiente a la base de datos de GeoIP
    • geoip_db_get_all_info - Devuelve información detallada sobre todos los tipos de bases de datos GeoIP
    • geoip_domain_by_name - Obtener el nombre de dominio de segundo nivel
    • geoip_id_by_name - Obtiene el tipo de conexión a Internet
    • geoip_isp_by_name - Obtiene el nombre del proveedor de servicios de Internet (ISP)
    • geoip_netspeedcell_by_name - Obtener la velocidad de la conexión a Internet
    • geoip_org_by_name - Consultar nombre de la organización
    • geoip_record_by_name - Devuelve información detallada de la Ciudad encontrada en la base de datos de GeoIP
    • geoip_region_by_name - Consultar el código de país y de región
    • geoip_region_name_by_code - Devuelve, a partir de una combinación de código de país y de región, el nombre de región
    • geoip_setup_custom_directory - Establecer un directorio personalizado para la base de datos de GeoIP
    • geoip_time_zone_by_country_and_region - Devuelve, a partir de una combinación de país y región, la zona horaria
    • getallheaders - Recupera todas las cabeceras de petición HTTP
    • getcwd - Obtiene el directorio actual en donde se esta trabajando
    • getdate - Obtener información de la fecha/hora
    • getenv - Obtiene el valor de una variable de entorno
    • gethostbyaddr - Obtener el nombre del host de Internet correspondiente a una dirección IP dada
    • gethostbyname - Obtener la dirección IPv4 que corresponde a un nombre de host de Internet dado
    • gethostbynamel - Obtener una lista de direcciones IPv4 que corresponde a un nombre de host de Internet dado
    • gethostname - Obtiene el nombre de host
    • getimagesize - Obtener el tamaño de una imagen
    • getimagesizefromstring - Obtener el tamaño de una imagen desde una cadena
    • getlastmod - Obtiene la hora de la última modificación de la página
    • getmxrr - Obtener los registros MX correspondientes a un nombre de host de Internet
    • getmygid - Obtener el GID del dueño del script PHP
    • getmyinode - Obtiene el inode del script actual
    • getmypid - Obtiene el ID del proceso PHP
    • getmyuid - Obtiene el UID del dueño del script PHP
    • getopt - Obtiene las opciones de la lista de argumentos de la línea de comandos
    • getprotobyname - Obtener el número de protocolo asociado con el nombre de protocolo
    • getprotobynumber - Obtiene el nombre de protocolo asociado con un número de protocolo
    • getrandmax - Mostrar el mayor valor aleatorio posible
    • getrusage - Obtiene el uso de los recursos actuales
    • getservbyname - Obtener el número de puerto asociado con un servicio y protocolo de Internet
    • getservbyport - Obtener el servicio de Internet que corresponde con el puerto y protocolo
    • gettext - Consultar un mensaje en el dominio actual
    • gettimeofday - Obtener la hora actual
    • gettype - Obtener el tipo de una variable
    • get_browser - Indica de lo que es capaz el navegador del usuario
    • get_called_class - El nombre de la clase enlazada estáticamente en tiempo de ejecución ("Late State Binding")
    • get_cfg_var - Obtiene el valor de una opción de configuración de PHP
    • get_class - Devuelve el nombre de la clase de un objeto
    • get_class_methods - Obtiene los nombres de los métodos de una clase
    • get_class_vars - Obtener las propiedades predeterminadas de una clase
    • get_current_user - Obtiene el nombre del propietario del script PHP actual
    • get_declared_classes - Devuelve una matriz con los nombres de las clases definidas
    • get_declared_interfaces - Devuelve un array con todas las interfaces declaradas
    • get_declared_traits - Devuelve un array de todos los traits declarados
    • get_defined_constants - Devuelve un array asociativo con los nombres de todas las constantes y sus valores
    • get_defined_functions - Devuelve un array de todas las funciones definidas
    • get_defined_vars - Devuelve una matriz con todas las variables definidas
    • get_extension_funcs - Devuelve una matriz con los nombres de funciones de un módulo
    • get_headers - Recupera todas las cabeceras enviadas por el servidor en respuesta a una petición HTTP
    • get_html_translation_table - Devuelve la tabla de traducción utilizada por htmlspecialchars y htmlentities
    • get_included_files - Devuelve un array con los nombres de los archivos incluidos o requeridos
    • get_include_path - Obtiene la opción de configuración include_path actual
    • get_loaded_extensions - Devuelve un array con los nombres de todos los módulos compilados y cargados
    • get_magic_quotes_gpc - Obtiene el valor actual de configuración de magic_quotes_gpc
    • get_magic_quotes_runtime - Obtiene el valor de configuración activo actual de magic_quotes_runtime
    • get_meta_tags - Extrae todo el contenido de atributos de etiquetas meta de un archivo y devuelve un array
    • get_object_vars - Obtiene las propiedades del objeto dado
    • get_parent_class - Recupera el nombre de la clase padre de un objeto o clase
    • get_required_files - Alias de get_included_files
    • get_resources - Returns active resources
    • get_resource_id - Returns an integer identifier for the given resource
    • get_resource_type - Devuelve el tipo de recurso
    • glob - Buscar coincidencias de nombres de ruta con un patrón
    • glob:// - Encuentra las rutas que coincidan con el patrón
    • GlobIterator::count - Obtiene el número de directorios y ficheros
    • GlobIterator::__construct - Construye un directorio usando glob
    • Gmagick::addimage - Añade una nueva imagen a la lista de imágenes del objeto Gmagick
    • Gmagick::addnoiseimage - Añade ruido aleatorio a la imagen
    • Gmagick::annotateimage - Anota una imagen con texto
    • Gmagick::blurimage - Añade un filtro de borrosidad a la imagen
    • Gmagick::borderimage - Rodea la imagen con un borde
    • Gmagick::charcoalimage - Simula un dibujo a carboncillo
    • Gmagick::chopimage - Elimina una región de una imagen y la recorta
    • Gmagick::clear - Limpia todos los recursos asociados con el objeto Gmagick
    • Gmagick::commentimage - Añade un comentario a una imagen
    • Gmagick::compositeimage - Compone una imagen en otra
    • Gmagick::cropimage - Extrae una región de la imagen
    • Gmagick::cropthumbnailimage - Crea una miniatura recortada
    • Gmagick::current - Devuelve la refencia al objeto Gmagick acutal
    • Gmagick::cyclecolormapimage - Desplaza un mapa de color de una imagen
    • Gmagick::deconstructimages - Devuelve ciertas diferencias de píxeles entre imágenes
    • Gmagick::despeckleimage - Reduce el ruido granular de una imagen
    • Gmagick::destroy - Destruye un objeto Gmagick
    • Gmagick::drawimage - Renderiza el objeto GmagickDraw en la imagen actual
    • Gmagick::edgeimage - Mejora los bordes dentro de una imagen
    • Gmagick::embossimage - Devuelve una imagen en escala de grises con un efecto tridimensional
    • Gmagick::enhanceimage - Mejora la calidad de una imagen con ruido
    • Gmagick::equalizeimage - Ecualiza el histograma de la imagen
    • Gmagick::flipimage - Crea una imagen espejo vertical
    • Gmagick::flopimage - Crea una imagen espejo horizontal
    • Gmagick::frameimage - Añade un borde tridimensional simulado
    • Gmagick::gammaimage - Corrección gamma de una imagen
    • Gmagick::getcopyright - Devuelve el copyright de la API GraphicsMagick como una cadena
    • Gmagick::getfilename - El nombre de archivo asociado a una secuencia de imágenes
    • Gmagick::getimagebackgroundcolor - Devuelve el color de fondo de la imagen
    • Gmagick::getimageblueprimary - Devuelve el punto primario azul de la cromaticidad
    • Gmagick::getimagebordercolor - Devuelve el color del borde de la imagen
    • Gmagick::getimagechanneldepth - Obtiene la profundidad de un canal de imagen en particular
    • Gmagick::getimagecolors - Devuelve el color del índice del mapa de color especificado
    • Gmagick::getimagecolorspace - Obtiene el espacio de colores de la imagen
    • Gmagick::getimagecompose - Devuelve el operador de composición asociado a la imagen
    • Gmagick::getimagedelay - Obetiene el retraso de la imagen
    • Gmagick::getimagedepth - Obtiene la profundidad de la imagen
    • Gmagick::getimagedispose - Obtiene el método de disposición de la imagen
    • Gmagick::getimageextrema - Obtiene los extremos de la imagen
    • Gmagick::getimagefilename - Devuelve el nombre de archivo de una imagen en particular de una secuencia
    • Gmagick::getimageformat - Devuelve el formato de una imagen en particular de una secuencia
    • Gmagick::getimagegamma - Obtiene el valor gamma de la imagen
    • Gmagick::getimagegreenprimary - Devuelve el punto primario verde de la cromaticidad
    • Gmagick::getimageheight - Devuelve el alto de la imagen
    • Gmagick::getimagehistogram - Obtiene el histograma de la imagen
    • Gmagick::getimageindex - Obtiene el índice de la imagen activa actual
    • Gmagick::getimageinterlacescheme - Obtiene la combinación de entrelazado de la imagen
    • Gmagick::getimageiterations - Obtiene las iteraciones de la imagen
    • Gmagick::getimagematte - Comprobar si la imagen tiene un canal mate
    • Gmagick::getimagemattecolor - Devuelve el color mate de la imagen
    • Gmagick::getimageprofile - Devuelve el perfil nominado de la imagen
    • Gmagick::getimageredprimary - Devuelve el punto primario rojo de la cromaticidad
    • Gmagick::getimagerenderingintent - Obtiene la propuesta de renderización de la imagen
    • Gmagick::getimageresolution - Obtiene la resolución X e Y de la imagen
    • Gmagick::getimagescene - Obtiene la escena de la imagen
    • Gmagick::getimagesignature - Genera un resumen de un mensaje SHA-256
    • Gmagick::getimagetype - Obtiene el tipo de imagen potencial.
    • Gmagick::getimageunits - Obtiene las unidades de resolución de la imagen
    • Gmagick::getimagewhitepoint - Devuelve el punto blanco de la cromaticidad
    • Gmagick::getimagewidth - Devuelve el ancho de la imagen
    • Gmagick::getpackagename - Devuelve el nombre del paquete de GraphicsMagick
    • Gmagick::getquantumdepth - Obtiene la profundidad de la cuantía de Gmagick como una cadena
    • Gmagick::getreleasedate - Devuelve la fecha de distribución de GraphicsMagick como una cadena
    • Gmagick::getsamplingfactors - Obtiene el factor de muestreo horizontal y vertical
    • Gmagick::getsize - Devuelve el tamaño asociado con el objeto Gmagick
    • Gmagick::getversion - Devuelve la versión de la API GraphicsMagick
    • Gmagick::hasnextimage - Comprueba si el objeto tiene más imágenes
    • Gmagick::haspreviousimage - Verifica si el objeto tiene una imagen previa
    • Gmagick::implodeimage - Crea una nueva imagen como una copia
    • Gmagick::labelimage - Añade una etiqueta a una imagen
    • Gmagick::levelimage - Ajusta los niveles de la imagen
    • Gmagick::magnifyimage - Escala una imagen x2 proporcionalmente
    • Gmagick::mapimage - Reemplaza los colores de una imagen con el color más cercano de una imagen de referencia
    • Gmagick::medianfilterimage - Aplica un filtro digital
    • Gmagick::minifyimage - Escala una imagen proporcionalmente a la mitad de su tamaño
    • Gmagick::modulateimage - Controla el brillo, la saturación y el tono
    • Gmagick::motionblurimage - Simula borrosidad en movimiento
    • Gmagick::newimage - Crea una nueva imagen
    • Gmagick::nextimage - Moverse a la siguiente imagen
    • Gmagick::normalizeimage - Mejora el contraste de una imagen a color
    • Gmagick::oilpaintimage - Simula una pintura al óleo
    • Gmagick::previousimage - Moverse a la imagen previa del objeto
    • Gmagick::profileimage - Añade o elimina un perfil de una imagen
    • Gmagick::quantizeimage - Analiza los colores dentro de una imagen de referencia
    • Gmagick::quantizeimages - Analiza los colores dentro de una secuencia de imágenes
    • Gmagick::queryfontmetrics - Devuelve una matriz que representa las métricas de la fuente
    • Gmagick::queryfonts - Devuelve las fuentes configuradas
    • Gmagick::queryformats - Devuelve los formatos admitidos por Gmagick
    • Gmagick::radialblurimage - Hace borrosa de forma radial una imagen
    • Gmagick::raiseimage - Crea un efecto de botón en 3D simulado
    • Gmagick::read - Lee una imagen desde un nombre de archivo
    • Gmagick::readimage - Lee una imagen desde un nombre de archivo
    • Gmagick::readimageblob - Lee una imagen desde una cadena binaria
    • Gmagick::readimagefile - Lee una imagen desde un descriptor de archivo abierto
    • Gmagick::reducenoiseimage - Suaviza los contornos de una imagen
    • Gmagick::removeimage - Elimina una imagen de la lista de imágenes
    • Gmagick::removeimageprofile - Elimina el perfil nombrado de la imagen y lo devuelve
    • Gmagick::resampleimage - Re-muestrea la imagen a la resolución deseada
    • Gmagick::resizeimage - Escala una imagen
    • Gmagick::rollimage - Compensa una imagen
    • Gmagick::rotateimage - Rota una imagen
    • Gmagick::scaleimage - Escala el tamaño de una imagen
    • Gmagick::separateimagechannel - Separa un canal de la imagen
    • Gmagick::setCompressionQuality - Establece la calidad de compresión predeterminada del objeto
    • Gmagick::setfilename - Establece el nombre de archivo antes de que se lea o escriba una imagen
    • Gmagick::setimagebackgroundcolor - Establece el color de fondo de la imagen
    • Gmagick::setimageblueprimary - Establece el punto primario azul de la cromaticidad de la imagen
    • Gmagick::setimagebordercolor - Establece el color de borde de la imagen
    • Gmagick::setimagechanneldepth - Establece la profundidad de una canal de imagen en particular
    • Gmagick::setimagecolorspace - Establece el espacio de color de una imagen
    • Gmagick::setimagecompose - Establece el operador de composción de una imagen
    • Gmagick::setimagedelay - Establece el retardo de una imagen
    • Gmagick::setimagedepth - Establece la profundidad de una imagen
    • Gmagick::setimagedispose - Establece el método de disposición de una imagen
    • Gmagick::setimagefilename - Establece el nombre de archivo de una imagen en particular en una secuencia
    • Gmagick::setimageformat - Establece el formato de una imagen en particular
    • Gmagick::setimagegamma - Establece el valor gamma de la imagen
    • Gmagick::setimagegreenprimary - Establece el punto primario verde de la cromaticidad de la imagen
    • Gmagick::setimageindex - Establece la posición del iterador en la lista de imágenes especificada con el parámetro index
    • Gmagick::setimageinterlacescheme - Establece la combinación de entrelazado de la imagen
    • Gmagick::setimageiterations - Establece las iteraciones de la imagen
    • Gmagick::setimageprofile - Añade un perfil nombrado al objeto Gmagick
    • Gmagick::setimageredprimary - Establece el punto primario rojo de la cromaticidad de la imagen
    • Gmagick::setimagerenderingintent - Establece el propósito de renderización de la imagen
    • Gmagick::setimageresolution - Establece la resolución de la imagen
    • Gmagick::setimagescene - Establece la escena de la imagen
    • Gmagick::setimagetype - Establece el tipo de imagen
    • Gmagick::setimageunits - Establece las unidades de resolución de la imagen
    • Gmagick::setimagewhitepoint - Establece el punto blanco de cromaticidad de la imagen
    • Gmagick::setsamplingfactors - Establece los factores de muestreo de la imagen
    • Gmagick::setsize - Establece el tamaño del objeto Gmagick
    • Gmagick::shearimage - Crea un paralelogramo
    • Gmagick::solarizeimage - Aplica un efecto de solarización a la imagen
    • Gmagick::spreadimage - Despalza aleatoriamente cada píxel en un bloque
    • Gmagick::stripimage - Elimina todos los perfiles y comentarios de una imagen
    • Gmagick::swirlimage - Arremolina los píxeles desde el centro de la imagen
    • Gmagick::thumbnailimage - Cambia el tamaño de una imagen
    • Gmagick::trimimage - Elimina los extremos de la imagen
    • Gmagick::write - Alias de Gmagick::writeimage
    • Gmagick::writeimage - Escribe una imagen al nombre de archivo especificado
    • Gmagick::__construct - El constructor Gmagick
    • GmagickDraw::annotate - Dibuja texto en la imagen
    • GmagickDraw::arc - Dibuja un arco
    • GmagickDraw::bezier - Dibuja una curva Bézier
    • GmagickDraw::ellipse - Dibuja una elipse en la imagen
    • GmagickDraw::getfillcolor - Devuelve el color de relleno
    • GmagickDraw::getfillopacity - Devuelve la opacidad usada cuando se dibuja
    • GmagickDraw::getfont - Devuelve el tipo de letra
    • GmagickDraw::getfontsize - Devuelve el tamaño de punto de la fuente
    • GmagickDraw::getfontstyle - Devuelve el estilo de fuente
    • GmagickDraw::getfontweight - Devuelve el peso de la fuente
    • GmagickDraw::getstrokecolor - Devuelve el color usado para contornear perfiles de objetos
    • GmagickDraw::getstrokeopacity - Devuelve la opacidad de los perfiles del objeto contorneado
    • GmagickDraw::getstrokewidth - Devuelve el ancho del contorno usado para dibular perfiles del objeto
    • GmagickDraw::gettextdecoration - Devuelve la decoración del texto
    • GmagickDraw::gettextencoding - Devuelve el conjunto de codificación usado para anotaciones de texto
    • GmagickDraw::line - Dibuja una línea en la imagen
    • GmagickDraw::point - Dibuja un punto
    • GmagickDraw::polygon - Dibuja un polígono
    • GmagickDraw::polyline - Dibuja una polilínea
    • GmagickDraw::rectangle - Dibuja un rectángulo
    • GmagickDraw::rotate - Aplica la rotación especificada al espacio de coordenadas actual
    • GmagickDraw::roundrectangle - Dibuja un rectángulo redondeado
    • GmagickDraw::scale - Ajusta el factor de escala
    • GmagickDraw::setfillcolor - Establece el color de relleno a usar cuando se dibujan objetos rellenos
    • GmagickDraw::setfillopacity - Establece la opacidad del relleno
    • GmagickDraw::setfont - Establece la fuente especificada completamente a usar cuando se anota texto
    • GmagickDraw::setfontsize - Establece el tamaño de punto de la fuente a usar cuando se anota texto
    • GmagickDraw::setfontstyle - Establece el estilo de fuente a usar cuando se anota texto
    • GmagickDraw::setfontweight - Establece el peso de la fuente
    • GmagickDraw::setstrokecolor - Establece el color usado para contornear los perfiles del objeto
    • GmagickDraw::setstrokeopacity - Especifica la opacidad del los perfiles del objeto contorneado
    • GmagickDraw::setstrokewidth - Establece el ancho del contorno usado para dibujar los perfiles del objeto.
    • GmagickDraw::settextdecoration - Especifica una decoración
    • GmagickDraw::settextencoding - Especifica el conjunto de codificación del texto
    • GmagickPixel::getcolor - Devuelve el color
    • GmagickPixel::getcolorcount - Devuelve la cuenta de color asociada a este color
    • GmagickPixel::getcolorvalue - Obtiene el valor normalizado del canal de color proporcionado
    • GmagickPixel::setcolor - Establece el color
    • GmagickPixel::setcolorvalue - Establece el valor normalizado de uno de los canales
    • GmagickPixel::__construct - El constructor GmagickPixel
    • gmdate - Formatea una fecha/hora GMT/UTC
    • gmmktime - Obtener la marca temporal de Unix para una fecha GMT
    • gmp_abs - Valor absoluto
    • gmp_add - Agrega números
    • gmp_and - AND a nivel de bit
    • gmp_binomial - Calculates binomial coefficient
    • gmp_clrbit - Limpia un bit
    • gmp_cmp - Compara los números
    • gmp_com - Calcula uno de los complementos
    • gmp_div - Alias de gmp_div_q
    • gmp_divexact - División exacta de números
    • gmp_div_q - Divide los números
    • gmp_div_qr - Divide los números y obtiene el cociente y resto
    • gmp_div_r - El resto de la división de los números
    • gmp_export - Exportar a un string binario
    • gmp_fact - Factorial
    • gmp_gcd - Calcula el máximo común divisor
    • gmp_gcdext - Calcula el máximo común divisor y multiplicadores
    • gmp_hamdist - Distancia Hamming
    • gmp_import - Importar de un string binario
    • gmp_init - Crea un número GMP
    • gmp_intval - Convertir un número GMP a entero
    • gmp_invert - Inverso del modulo
    • gmp_jacobi - Símbolo Jacobi
    • gmp_kronecker - Kronecker symbol
    • gmp_lcm - Calculate LCM
    • gmp_legendre - Símbolo Legendre
    • gmp_mod - Modulo de operación
    • gmp_mul - Multiplicación de números
    • gmp_neg - Número negativo
    • gmp_nextprime - Encuentra el siguiente número primo
    • gmp_or - Nivel de bit OR
    • gmp_perfect_power - Perfect power check
    • gmp_perfect_square - Comprueba el cuadrado perfecto
    • gmp_popcount - Cuenta la población
    • gmp_pow - Aumenta el número a la potencia
    • gmp_powm - Eleva un número a la potencia con modulo
    • gmp_prob_prime - Revisa si el número es "probablemente primo"
    • gmp_random - Numero al azar
    • gmp_random_bits - Un número aleatorio
    • gmp_random_range - Un número aleatorio
    • gmp_random_seed - Establece la semilla RNG
    • gmp_root - Tomar la parte entera de una raíz enésima
    • gmp_rootrem - Tomar la parte entera y el resto de una raíz enésima
    • gmp_scan0 - Escanear para 0
    • gmp_scan1 - Escanear para 1
    • gmp_setbit - Establece el bit
    • gmp_sign - El símbolo del número
    • gmp_sqrt - Calcula la raíz cuadrada
    • gmp_sqrtrem - Raíz cuadrada con resto
    • gmp_strval - Convierte un número GMP a cadena
    • gmp_sub - Resta los números
    • gmp_testbit - Prueba si un bit es establecido
    • gmp_xor - Nivel de bit XOR
    • gmstrftime - Formatear una fecha/hora GMT/UTC según la configuración local
    • gnupg_adddecryptkey - Añade una llave para desencriptar
    • gnupg_addencryptkey - Añade una llave para encriptar
    • gnupg_addsignkey - Añade una llave para firmar
    • gnupg_cleardecryptkeys - Elimina todas las llaves establecidas anteriormente para desencriptar
    • gnupg_clearencryptkeys - Elimina todas las llaves establecidas anteriormente paraencriptar
    • gnupg_clearsignkeys - Elimina todas las llaves establecidas anteriormente para firmar
    • gnupg_decrypt - Desencripta un texto dado
    • gnupg_decryptverify - Desencripta y verifica un texto dado
    • gnupg_encrypt - Encripta el texto dado
    • gnupg_encryptsign - Encripta y firma un texto dado
    • gnupg_export - Exporta una llave
    • gnupg_geterror - Retorna el texto de error si una función falla
    • gnupg_getprotocol - Retorna el protocolo activo actualmente para todas las operaciones
    • gnupg_import - Importa una llave
    • gnupg_init - Inicializa una conexión
    • gnupg_keyinfo - Retorna un array con información sobre todas las llaves que coinciden con un patrón dado
    • gnupg_setarmor - Activa o desactiva la salida blindada
    • gnupg_seterrormode - Fija el modo para error_reporting
    • gnupg_setsignmode - Fija el modo para firmar
    • gnupg_sign - Firma un texto dado
    • gnupg_verify - Verifica un texto firmado
    • grapheme_extract - Función para extraer una secuencia de un clúster de grafemas predeterminados desde un buffer de texto, que puede estar codificado en UTF-8
    • grapheme_stripos - Buscar la posición (en unidades de grafema) de la primera coincidencia de una cadena insensible a mayúsculas-minúsculas
    • grapheme_stristr - Devolver parte de la cadena "pajar" desde la primera coincidencia de la cadena "aguja" insensible a mayúsculas-minúsculas hasta el final de "pajar"
    • grapheme_strlen - Obtener la longitud de un string en unidades de grafema
    • grapheme_strpos - Buscar la posición (en unidades de grafema) de la primera ocurrencia de una cadena
    • grapheme_strripos - Buscar la posición (en unidades de grafema) de la última coincidencia de una cadena insensible a mayúsculas-minúsculas
    • grapheme_strrpos - Buscar la posición (en unidades de grafema) de la última coincidencia de una cadena
    • grapheme_strstr - Devolver parte de la cadena "pajar" desde la primera coincidencia de la cadena "aguja" hasta el final de "pajar"
    • grapheme_substr - Devolver parte de una cadena
    • gregoriantojd - Convierte una fecha Gregoriana en Fecha Juliana
    • gzclose - Cierra el apuntador de un archivo gz abierto
    • gzcompress - Comprime una cadena
    • gzdecode - Decodifica una cadena comprimida con gzip
    • gzdeflate - Comprime una cadena
    • gzencode - Crea una cadena comprimida con gzip
    • gzeof - Prueba de apuntador para EOF de archivo gz
    • gzfile - Lee un archivo gz completo en una matriz
    • gzgetc - Obtiene el caracter donde está el apuntador al archivo gz
    • gzgets - Obtiene la línea del apuntador al archivo
    • gzgetss - Obtiene la línea del apuntador al archivo gz y retira las etiquetas HTML
    • gzinflate - Descomprime una cadena comprimida
    • gzopen - Abre un archivo gz
    • gzpassthru - Muestra todos los datos restantes a partir del apuntador al achivo gz
    • gzputs - Alias de gzwrite
    • gzread - Lectura de archivo gz segura a nivel binario
    • gzrewind - Reinicia la posición del apuntador a un archivo gz
    • gzseek - Ubica el apuntador a un archivo gz
    • gztell - Indica la posición de lectura/escritura del apuntador al archivo gz
    • gzuncompress - Descomprime una cadena comprimida
    • gzwrite - Escritura en un archivo gz, segura a nivel binario
  • h
    • hash - Generar un valor hash (resumen de mensaje)
    • hash_algos - Devuelve una lista con los algoritmos de cifrado soportados
    • hash_copy - Copia un recurso de contexto de cifrado
    • hash_equals - Comparación de strings segura contra ataques de temporización
    • hash_file - Generar un valor hash usando el contenido de un fichero dado
    • hash_final - Finaliza un contexto incremental y devuelve el resultado cifrado
    • hash_hkdf - Generate a HKDF key derivation of a supplied key input
    • hash_hmac - Genera un valor cifrado mediante una clave especificada usando el método HMAC
    • hash_hmac_algos - Return a list of registered hashing algorithms suitable for hash_hmac
    • hash_hmac_file - Genera un valor cifrado mediante una clave especificada usando el método HMAC y el contenido de un fichero dado
    • hash_init - Iniciar un contexto de hashing incremental
    • hash_pbkdf2 - Genera una derivación de clave PBKDF2 de una contraseña proporcionada
    • hash_update - Pega más datos en un contexto incremental de cifrado activo
    • hash_update_file - Inyecta datos en un contexto de cifrado activo desde un fichero
    • hash_update_stream - Pega datos en un contexto de cifrado activo desde un flujo de datos abierto
    • header - Enviar encabezado sin formato HTTP
    • headers_list - Devuelve una lista de encabezados de respuesta enviados (o listos para enviar)
    • headers_sent - Comprueba si o donde han enviado cabeceras
    • header_register_callback - Llamar a una función de cabecera
    • header_remove - Elimina encabezados previamente establecidos
    • hebrev - Convierte texto hebreo lógico a texto visual
    • hebrevc - Convertir texto de hebreo lógico a texto visual con conversión de línea nueva
    • hex2bin - Decodifica una cadena binaria codificada hexadecimalmente
    • hexdec - Hexadecimal a decimal
    • highlight_file - Remarcado de la sintaxis de un fichero
    • highlight_string - Remarcado de sintaxis de una cadena
    • hrtime - Get the system's high resolution time
    • HRTime\PerformanceCounter::getFrequency - La frecuencia del cronómetro en pulsos por segundo
    • HRTime\PerformanceCounter::getTicks - Current ticks from the system
    • HRTime\PerformanceCounter::getTicksSince - Ticks elapsed since the given value
    • HRTime\StopWatch::getElapsedTicks - Get elapsed ticks for all intervals
    • HRTime\StopWatch::getElapsedTime - Obtener el tiempo transcurrido para todos los intervalos
    • HRTime\StopWatch::getLastElapsedTicks - Get elapsed ticks for the last interval
    • HRTime\StopWatch::getLastElapsedTime - Obtener el tiempo transcurrido para el último intervalo
    • HRTime\StopWatch::isRunning - Whether the measurement is running
    • HRTime\StopWatch::start - Start time measurement
    • HRTime\StopWatch::stop - Stop time measurement
    • htmlentities - Convierte todos los caracteres aplicables a entidades HTML
    • htmlspecialchars - Convierte caracteres especiales en entidades HTML
    • htmlspecialchars_decode - Convierte entidades HTML especiales de nuevo en caracteres
    • html_entity_decode - Convierte todas las entidades HTML a sus caracteres correspondientes
    • http:// - Acceso a URLS en HTTP(s)
    • http_build_query - Generar una cadena de consulta codificada estilo URL
    • http_response_code - Obtener u establecer el código de respuesta HTTP
    • hypot - Calcula la longitud de la hipotenusa de un triángulo de ángulo recto
  • i
    • ibase_add_user - Añade un usuario a una base de datos segura
    • ibase_affected_rows - Devuelve el número de columnas afectadas por la última consulta
    • ibase_backup - Inicia la tarea de copia de seguridad en el administrador de servicios y devuelve el control inmediatamente
    • ibase_blob_add - Añade datos a un nuevo blob
    • ibase_blob_cancel - Cancela la creación de un blob
    • ibase_blob_close - Cierra un blob
    • ibase_blob_create - Crea un nuevo blob al que añadir datos
    • ibase_blob_echo - Imprime el contenido de un blob
    • ibase_blob_get - Consulta un determinado número de bytes de un blob
    • ibase_blob_import - Crea un blob, copia un fichero en él, y lo cierra
    • ibase_blob_info - Devuelve el tamaño de un blob y otra información útil
    • ibase_blob_open - Abre un blob para su consulta
    • ibase_close - Cerrar una conexión con una base de datos InterBase
    • ibase_commit - Lleva a cabo una transacción
    • ibase_commit_ret - Lleva a cabo una transacción sin cerrarla
    • ibase_connect - Abrir una conexión a una base de datos
    • ibase_db_info - Consulta estadísticas de una base de datos
    • ibase_delete_user - Elimina un usuario de una base de datos segura
    • ibase_drop_db - Elimina una base de datos
    • ibase_errcode - Devuelve un código de error
    • ibase_errmsg - Devuelve un mensaje de error
    • ibase_execute - Ejecutar una consulta previamente preparada
    • ibase_fetch_assoc - Extra una fila en forma de array asociativo de una consulta
    • ibase_fetch_object - Consulta un objeto de una base de datos InterBase
    • ibase_fetch_row - Recuperar una fila desde una base de datos InterBase
    • ibase_field_info - Consulta información sobre un determinado campo
    • ibase_free_event_handler - Cancela un manejador de eventos ya registrado
    • ibase_free_query - Liberar la memoria reservada por una consulta preparada
    • ibase_free_result - Liberar un conjunto de resultados
    • ibase_gen_id - Incrementa el generador de nombres y devuelve su nuevo valor
    • ibase_maintain_db - Lleva a cabo una tarea de mantenimiento en el servidor de bases de datos
    • ibase_modify_user - Modifica un usuario en una base de datos segura
    • ibase_name_result - Asigna un nombre a un juego de resultados
    • ibase_num_fields - Consulta el número de campos de un resultado
    • ibase_num_params - Devuelve el número de parámetros de una sentencia preparada
    • ibase_param_info - Devuelve información sobre un parámetro de una sentencia preparada
    • ibase_pconnect - Abrir una conexión persistente con una base de datos InterBase
    • ibase_prepare - Preparar una consulta para su asociación con parámetros de sustitución y ejecución posterior
    • ibase_query - Ejecutar una consulta en una base de datos InterBase
    • ibase_restore - Inicia una tarea de restauración en el administrador de servicios y devuelve el control inmediatamente
    • ibase_rollback - Deshace una transacción
    • ibase_rollback_ret - Deshace una transacción sin cerrarla
    • ibase_server_info - Solicita información sobre un servidor de bases de datos
    • ibase_service_attach - Conecta al administrador de servicios
    • ibase_service_detach - Desconecta del administrador de servicios
    • ibase_set_event_handler - Registra una función manejadora de un determinado evento
    • ibase_trans - Comienza una transacción
    • ibase_wait_event - Espera a que la base de datos emita un determinado evento
    • iconv - Convierte un string a la codificación de caracteres indicada
    • iconv_get_encoding - Recupera variables de configuración interna de la extensión iconv
    • iconv_mime_decode - Decodifica un campo de la cabecera MIME
    • iconv_mime_decode_headers - Decodifica varios campos de cabeceras MIME en la misma llamada
    • iconv_mime_encode - Compone un campo de cabecera MIME
    • iconv_set_encoding - Establece las opciones para la conversión de codificación de caracteres
    • iconv_strlen - Retorna el número de caracteres de un string
    • iconv_strpos - Encuentra la posición de la primera aparición de una aguja en un pajar
    • iconv_strrpos - Busca la última aparición de un string
    • iconv_substr - Elimina parte del string
    • idate - Formatea una fecha/hora local como un entero
    • idn_to_ascii - Convierte un nombre de dominio a formato IDNA ASCII
    • idn_to_utf8 - Convierte un nombre de dominio de IDNA ASCII a Unicode
    • ignore_user_abort - Establecer si la desconexión de un cliente debería abortar la ejecución del script
    • image2wbmp - Exportar la imagen al navegador o a un fichero
    • imageaffine - Devuelve la imagen que contiene la imagen origen transformada afín, usando un área de recorte opcional
    • imageaffinematrixconcat - Concatena dos matrices (como al hacer muchas opciones de una vez)
    • imageaffinematrixget - Devuelve la imagen que contiene la imagen fuente transformada afín, usando un área de recorte opcional
    • imagealphablending - Establece el modo de mezcla para una imagen
    • imageantialias - Permitir o no el uso de funciones antialias
    • imagearc - Dibujar un arco
    • imagebmp - Output a BMP image to browser or file
    • imagechar - Dibujar un carácter horizontalmente
    • imagecharup - Dibujar un carácter verticalmente
    • imagecolorallocate - Asigna un color para una imagen
    • imagecolorallocatealpha - Asignar un color para una imagen
    • imagecolorat - Obtener el índice del color de un píxel
    • imagecolorclosest - Obtener el índice del color más próximo al color especificado
    • imagecolorclosestalpha - Obtener el índice del color más próximo al color + alpha especificado
    • imagecolorclosesthwb - Obtener el índice del color que tiene el tono, blancura y negrura
    • imagecolordeallocate - Desasignar un color de una imagen
    • imagecolorexact - Obtener el índice del color especificado
    • imagecolorexactalpha - Obtener el índice del color + alpha especificado
    • imagecolormatch - Hacer que los colores de la versión de la paleta de una imagen coincidan más estrechamente con la versión de color verdadero
    • imagecolorresolve - Obtener el índice del color especificado o su alternativa más próxima posible
    • imagecolorresolvealpha - Obtener el índice del color + alpha especificado o su alternativa más próxima posible
    • imagecolorset - Establecer el color para el índice de paleta especificada
    • imagecolorsforindex - Obtener los colores de un índice
    • imagecolorstotal - Averiguar el número de colores de la paleta de una imagen
    • imagecolortransparent - Definir un color como transparente
    • imageconvolution - Aplicar una matriz de convolución de 3x3, usando coeficiente e índice
    • imagecopy - Copiar parte de una imagen
    • imagecopymerge - Copiar y fusionar parte de una imagen
    • imagecopymergegray - Copiar y fusionar parte de una imagen con escala de grises
    • imagecopyresampled - Copia y cambia el tamaño de parte de una imagen redimensionándola
    • imagecopyresized - Copia y cambia el tamaño de parte de una imagen
    • imagecreate - Crea una nueva imagen basada en paleta
    • imagecreatefrombmp - Crea una nueva imagen a partir de un fichero o de una URL
    • imagecreatefromgd - Crear una imagen nueva desde un fichero GD o un URL
    • imagecreatefromgd2 - Crear una imagen nueva desde un fichero GD2 o un URL
    • imagecreatefromgd2part - Crear una nueva imagen desde una parte dada de un fichero GD2 o un URL
    • imagecreatefromgif - Crea una nueva imagen a partir de un fichero o de una URL
    • imagecreatefromjpeg - Crea una nueva imagen a partir de un fichero o de una URL
    • imagecreatefrompng - Crea una nueva imagen a partir de un fichero o de una URL
    • imagecreatefromstring - Crear una imagen nueva desde el flujo de imagen de la cadena
    • imagecreatefromwbmp - Crea una nueva imagen a partir de un fichero o de una URL
    • imagecreatefromwebp - Crea una nueva imagen a partir de un fichero o de una URL
    • imagecreatefromxbm - Crea una nueva imagen a partir de un fichero o de una URL
    • imagecreatefromxpm - Crea una nueva imagen a partir de un fichero o de una URL
    • imagecreatetruecolor - Crear una nueva imagen de color verdadero
    • imagecrop - Recorta una imagen usando las coordenadas, el tamaño, x, y, ancho y alto dados
    • imagecropauto - Recorta una imagen automáticamente usando uno de los modos disponibles
    • imagedashedline - Dibujar una línea discontinua
    • imagedestroy - Destruir una imagen
    • imageellipse - Dibujar una elipse
    • imagefill - Rellenar
    • imagefilledarc - Dibujar un arco parcial y rellenarlo
    • imagefilledellipse - Dibujar una elipse con relleno
    • imagefilledpolygon - Dibujar un polígono con relleno
    • imagefilledrectangle - Dibujar un rectángulo con relleno
    • imagefilltoborder - Rellenar con un color específico
    • imagefilter - Aplica un filtro a una imagen
    • imageflip - Flips an image using a given mode
    • imagefontheight - Obtener el alto de la fuente
    • imagefontwidth - Obtener el ancho de la fuente
    • imageftbbox - Devolver la caja circundante de un texto usando fuentes mediante FreeType 2
    • imagefttext - Escribir texto en la imagen usando fuentes mediante FreeType 2
    • imagegammacorrect - Aplicar una corrección gamma a la imagen GD
    • imagegd - Imprime una imagen GD2 a un navegador o archivo
    • imagegd2 - Imprime una imagen GD2 a un navegador o fichero
    • imagegetclip - Get the clipping rectangle
    • imagegetinterpolation - Get the interpolation method
    • imagegif - Exportar la imagen al navegador o a un fichero
    • imagegrabscreen - Capturar la pantalla completa
    • imagegrabwindow - Capturar una ventana
    • imageinterlace - Habilitar o deshabilitar en entrelazamiento
    • imageistruecolor - Averiguar si una imagen es de color verdadero
    • imagejpeg - Exportar la imagen al navegador o a un fichero
    • imagelayereffect - Establecer la bandera de mezcla alfa para usar los efectos de capa
    • imageline - Dibujar una línea
    • imageloadfont - Cargar una nueva fuente
    • imageopenpolygon - Draws an open polygon
    • imagepalettecopy - Copiar la paleta de una imagen a otra
    • imagepalettetotruecolor - Convierte una imagen basada en paleta a color verdadero
    • imagepng - Imprimir una imagen PNG al navegador o a un archivo
    • imagepolygon - Dibujar un polígono
    • imagerectangle - Dibuja un rectángulo
    • imageresolution - Get or set the resolution of the image
    • imagerotate - Rotar una imagen con un ángulo dado
    • imagesavealpha - Establecer la bandera para guardar la información completa del canal alfa (como oposición a la transparencia de un simple color) cuando se guardan imágenes PNG
    • imagescale - Redimensiona una imagen usando un nuevo ancho y alto
    • imagesetbrush - Establecer la imagen de pincel para el dibujo de líneas
    • imagesetclip - Set the clipping rectangle
    • imagesetinterpolation - Establecer el método de interpolación
    • imagesetpixel - Establecer un simple píxel
    • imagesetstyle - Establecer el estilo para el dibujo de líneas
    • imagesetthickness - Establecer el grosor para el dibujo de líneas
    • imagesettile - Establecer la imagen de tesela para rellenos
    • imagestring - Dibujar una cadena horizontalmente
    • imagestringup - Dibujar una cadena verticalmente
    • imagesx - Obtener el ancho de una imagen
    • imagesy - Obtener el alto de una imagen
    • imagetruecolortopalette - Convertir una imagen de color verdadero en una imagen de paleta
    • imagettfbbox - Devuelve la caja circundante de un texto usando fuentes TrueType
    • imagettftext - Escribir texto en la imagen usando fuentes TrueType
    • imagetypes - Devolver los tipos de imagen soportados por la versión actual de PHP
    • imagewbmp - Exportar la imagen al navegador o a un fichero
    • imagewebp - Imprimir una imagen WebP al navegador o fichero
    • imagexbm - Imprimir una imagen XBM en el navegador o en un fichero
    • image_type_to_extension - Obtiene la extensión de un tipo de imagen
    • image_type_to_mime_type - Obtiene el tipo Mime de un tipo de imagen devuelto por getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
    • Imagick::adaptiveBlurImage - Añade un filtro de borrosidad adaptativo a la imagen
    • Imagick::adaptiveResizeImage - Redimensiona una imagen adaptativamente con información dependiente de la triangulación
    • Imagick::adaptiveSharpenImage - Afila la imagen adaptativamente
    • Imagick::adaptiveThresholdImage - Selecciona un umbral para cada píxel basado en un rango de intensidad
    • Imagick::addImage - Añade una nueva imagen a la lista de imágenes del objeto Imagick
    • Imagick::addNoiseImage - Añade ruido aleatorio a la imagen
    • Imagick::affineTransformImage - Transforma una imagen
    • Imagick::animateImages - Anima una imagen o imágenes
    • Imagick::annotateImage - Anota una imagen con texto
    • Imagick::appendImages - Añade un conjunto de imágenes
    • Imagick::autoLevelImage - Description
    • Imagick::averageImages - Calcula la media de un conjunto de imágenes
    • Imagick::blackThresholdImage - Fuerza a todos los píxeles bajo un umbral a ser negros
    • Imagick::blueShiftImage - Description
    • Imagick::blurImage - Añade un filtro de borrosidad a la imagen
    • Imagick::borderImage - Rodea la imagen con un borde
    • Imagick::brightnessContrastImage - Description
    • Imagick::charcoalImage - Simula un dibujo a carboncillo
    • Imagick::chopImage - Borra una región de una imagen y la recorta
    • Imagick::clampImage - Description
    • Imagick::clear - Borra todos los recursos asociados con un objeto Imagick
    • Imagick::clipImage - Recorta a lo largo del primer trazado desde un perfil 8BIM
    • Imagick::clipImagePath - Description
    • Imagick::clipPathImage - Recorta a lo largo de trazados nominados desde un perfil 8BIM
    • Imagick::clone - Hace una copia exacta de un objeto Imagick
    • Imagick::clutImage - Reemplaza los colores de una imagen
    • Imagick::coalesceImages - Compone un conjunto de imágenes
    • Imagick::colorFloodfillImage - Cambia el valor del color de cualquier píxel que coincida con el objetivo
    • Imagick::colorizeImage - Mezcla el color de relleno con la imagen
    • Imagick::colorMatrixImage - Description
    • Imagick::combineImages - Combina una o más imágenes en una sóla imagen
    • Imagick::commentImage - Añade un comentario a la imagen
    • Imagick::compareImageChannels - Devuelve la diferencia entre una o más imágenes
    • Imagick::compareImageLayers - Devuelve la región circundante máxima entre imágenes
    • Imagick::compareImages - Compara una imagen con otra reconstruida
    • Imagick::compositeImage - Compone una imagen en otra
    • Imagick::contrastImage - Cambia el contraste de una imagen
    • Imagick::contrastStretchImage - Mejora el contraste de una imagen en color
    • Imagick::convolveImage - Aplica una semilla de convolución a medida a la imagen
    • Imagick::count - Get the number of images
    • Imagick::cropImage - Extrae una región de la imagen
    • Imagick::cropThumbnailImage - Crea una miniatura recortada
    • Imagick::current - Devuelve una referencia del objeto Imagick actual
    • Imagick::cycleColormapImage - Desplaza el mapa de colores de una imagen
    • Imagick::decipherImage - Descifra una imagen
    • Imagick::deconstructImages - Devuelve ciertas diferencias de píxeles entre imágenes
    • Imagick::deleteImageArtifact - Borra un artefacto de imagen
    • Imagick::deleteImageProperty - Description
    • Imagick::deskewImage - Elimina la torción de la imagen
    • Imagick::despeckleImage - Reduce el ruido granular de una imagen
    • Imagick::destroy - Destruye un objeto Imagick
    • Imagick::displayImage - Muestra una imagen
    • Imagick::displayImages - Muestra una imagen o una secuencia de imágenes
    • Imagick::distortImage - Deforma una imagen utilizando varios métodos de distorsión
    • Imagick::drawImage - Renderiza el objeto ImagickDraw a la imagen actual
    • Imagick::edgeImage - Mejora los bordes de la imagen
    • Imagick::embossImage - Devuelve una imagen en escala de grises con un efecto tridimensional
    • Imagick::encipherImage - Cifra una imagen
    • Imagick::enhanceImage - Mejora la calidad de una imagen con ruido
    • Imagick::equalizeImage - Ecualiza el histograma de la imagen
    • Imagick::evaluateImage - Aplica una expresión a una imagen
    • Imagick::exportImagePixels - Exporta píxeles de imagen en bruto
    • Imagick::extentImage - Establecer el tamaño de la imagen
    • Imagick::filter - Description
    • Imagick::flattenImages - Fusiona una secuencia de imágenes
    • Imagick::flipImage - Crea una imagen espejo vertical
    • Imagick::floodFillPaintImage - Cambia el valor del color de cualquier píxel que coincida con el objetivo
    • Imagick::flopImage - Crea una imagen espejo horizontal
    • Imagick::forwardFourierTransformImage - Description
    • Imagick::frameImage - Añade un borde tridimensional simulado
    • Imagick::functionImage - Aplica una función a la imagen
    • Imagick::fxImage - Evalúa una expresión por cada píxel de la imagen
    • Imagick::gammaImage - Corrección gamma de una imagen
    • Imagick::gaussianBlurImage - Hace borrosa una imagen
    • Imagick::getColorspace - Obtiene el espacio de color
    • Imagick::getCompression - Obtiene el tipo de compresión del objeto
    • Imagick::getCompressionQuality - Obtiene la calidad de compresión del objeto
    • Imagick::getCopyright - Devuelve el copyright de la API ImageMagick como una cadena
    • Imagick::getFilename - El nombre de archivo asociado a una secuencia de imágenes
    • Imagick::getFont - Obtiene la fuente
    • Imagick::getFormat - Devuelve el formato de un objeto Imagick
    • Imagick::getGravity - Obtiene la gravedad
    • Imagick::getHomeURL - Devuelve la URL de inicio de ImageMagick
    • Imagick::getImage - Devuelve un nuevo objeto Imagick
    • Imagick::getImageAlphaChannel - Obtiene el canal alfa de una imagen
    • Imagick::getImageArtifact - Obtener el artefacto de imagen
    • Imagick::getImageAttribute - Description
    • Imagick::getImageBackgroundColor - Devuelve el color de fondo de la imagen
    • Imagick::getImageBlob - Devuelve la secuencia de imágenes como un valor de tipo blob
    • Imagick::getImageBluePrimary - Devuelve el punto primario azul de la cromaticidad
    • Imagick::getImageBorderColor - Devuelve el color del borde de la imagen
    • Imagick::getImageChannelDepth - Obtiene la profundidad de un canal de imagen en particular
    • Imagick::getImageChannelDistortion - Compara los canales de imagen de una imagen con una imagen reconstruida
    • Imagick::getImageChannelDistortions - Obtiene las distorsiones del canal
    • Imagick::getImageChannelExtrema - Obtiene los extremos de uno o más canales de imagen
    • Imagick::getImageChannelKurtosis - Obtiene la curtosis y la asimetría estadística de un canal específico
    • Imagick::getImageChannelMean - Obtiene la media y la desviación estándar
    • Imagick::getImageChannelRange - Obtiene el rango del canal
    • Imagick::getImageChannelStatistics - Devuelve las estadísticas de cada canal de la imagen
    • Imagick::getImageClipMask - Obtiene la máscara de recorte de la imagen
    • Imagick::getImageColormapColor - Devuelve el color del índice del mapa de colores especficado
    • Imagick::getImageColors - Obtiene el número de colores únicos de la imagen
    • Imagick::getImageColorspace - Obtiene el espacio de color de la imagen
    • Imagick::getImageCompose - Devuelve el operador de composición asociado a la imagen
    • Imagick::getImageCompression - Obtiene el tipo de compresión de la imagen actual
    • Imagick::getImageCompressionQuality - Obtiene la calidad de compresión de la imagen actual
    • Imagick::getImageDelay - Obtiene el retraso de la imagen
    • Imagick::getImageDepth - Obtiene la profundidad de la imagen
    • Imagick::getImageDispose - Obtiene el método de disposición de la imagen
    • Imagick::getImageDistortion - Compara una imagen con una imagen reconstruida
    • Imagick::getImageExtrema - Obtiene los extremos de la imagen
    • Imagick::getImageFilename - Devuelve el nombre de archivo de una imagen en particular de una secuencia
    • Imagick::getImageFormat - Devuelve el formato de una imagen en particular de una secuencia
    • Imagick::getImageGamma - Obtiene el valor gamma de la imagen
    • Imagick::getImageGeometry - Obtiene el ancho y el alto como un array asociativo
    • Imagick::getImageGravity - Obtiene la gravedad de la imagen
    • Imagick::getImageGreenPrimary - Devuelve el punto primario verde de la cromaticidad
    • Imagick::getImageHeight - Devuelve el alto de la imagen
    • Imagick::getImageHistogram - Obtiene el histograma de la imagen
    • Imagick::getImageIndex - Obtiene el índice de la imagen activa actual
    • Imagick::getImageInterlaceScheme - Obtiene la combinación de entrelazado de la imagen
    • Imagick::getImageInterpolateMethod - Devuelve el método de interpolación
    • Imagick::getImageIterations - Obtiene las iteraciones de la imagen
    • Imagick::getImageLength - Devuelve la longitud de la imagen en bytes
    • Imagick::getImageMatte - Devuelve si la imagen tiene un canal mate
    • Imagick::getImageMatteColor - Devuelve el color mate de la imagen
    • Imagick::getImageMimeType - Description
    • Imagick::getImageOrientation - Obtiene la orientación de la imagen
    • Imagick::getImagePage - Devuelve la geometría de la página
    • Imagick::getImagePixelColor - Devuelve el color del píxel especificado
    • Imagick::getImageProfile - Devuelve el perfil nominado de la imagen
    • Imagick::getImageProfiles - Devuelve los perfiles de la imagen
    • Imagick::getImageProperties - Devuelve las propiedades de la imagen
    • Imagick::getImageProperty - Devuelve la propiedad nominada de la imagen
    • Imagick::getImageRedPrimary - Devuelve el punto primario rojo de la cromaticidad
    • Imagick::getImageRegion - Extrae una región de la imagen
    • Imagick::getImageRenderingIntent - Obtiene el propósito de renderización de la imagen
    • Imagick::getImageResolution - Obtiene la resolución X e Y de la imagen
    • Imagick::getImagesBlob - Devuelve todas las secuencias de imágenes como un blob
    • Imagick::getImageScene - Obtiene la escena de la imagen
    • Imagick::getImageSignature - Genera un resumen de un mensaje SHA-256
    • Imagick::getImageSize - Devuelve la longitud de la imagen en bytes
    • Imagick::getImageTicksPerSecond - Obtiene los pulsos por segundo de la imagen
    • Imagick::getImageTotalInkDensity - Obtiene la densidad de tinta total de la imagen
    • Imagick::getImageType - Obtiene el tipo de imagen potencial
    • Imagick::getImageUnits - Obtiene las unidades de resolución de la imagen
    • Imagick::getImageVirtualPixelMethod - Devuelve el método de píxel virtual
    • Imagick::getImageWhitePoint - Devuelve el punto blanco de la cromaticidad
    • Imagick::getImageWidth - Devuelve el ancho de la imagen
    • Imagick::getInterlaceScheme - Obtiene la combinación de entrelazado de un objeto
    • Imagick::getIteratorIndex - Obtiene el índice de la imagen activa actual
    • Imagick::getNumberImages - Devuelve el número de imágenes del objeto
    • Imagick::getOption - Devuelve un valor asociado con la clave especificada
    • Imagick::getPackageName - Devuelve el nombre del paquete de ImageMagick
    • Imagick::getPage - Devuelve la geometría de la página
    • Imagick::getPixelIterator - Devuelve un objeto MagickPixelIterator
    • Imagick::getPixelRegionIterator - Obtinene un objeto ImagickPixelIterator de una sección de imagen
    • Imagick::getPointSize - Obtiene el tamaño de punto
    • Imagick::getQuantum - Description
    • Imagick::getQuantumDepth - Obtiene la profundidad de la cuantía
    • Imagick::getQuantumRange - Devuelve el rango de cuantía de Imagick
    • Imagick::getRegistry - Description
    • Imagick::getReleaseDate - Devuelve la fecha de distribución de ImageMagick
    • Imagick::getResource - Devuelve el uso de memoria del recurso especificado
    • Imagick::getResourceLimit - Devuelve el límite del recurso especificado
    • Imagick::getSamplingFactors - Obtiene el factor de muestreo horizontal y vertical
    • Imagick::getSize - Devuelve el tamaño asociado con el objeto Imagick
    • Imagick::getSizeOffset - Devuelve el índice de tamaño
    • Imagick::getVersion - Devuelve la versión de la API ImageMagick
    • Imagick::haldClutImage - Reemplaza los colores de la imagen
    • Imagick::hasNextImage - Comprueba si el objeto tiene más imágenes
    • Imagick::hasPreviousImage - Verifica si el objeto tiene una imagen previa
    • Imagick::identifyFormat - Description
    • Imagick::identifyImage - Identifica una imagen y obtiene sus atributos
    • Imagick::implodeImage - Crea una nueva imagen como una copia
    • Imagick::importImagePixels - Importa los píxeles de una imagen
    • Imagick::inverseFourierTransformImage - Description
    • Imagick::labelImage - Añade una etiqueta a una imagen
    • Imagick::levelImage - Ajusta los niveles de la imagen
    • Imagick::linearStretchImage - Estrecha con saturación la intensidad de la imagen
    • Imagick::liquidRescaleImage - Anima una imagen o imágenes
    • Imagick::listRegistry - Description
    • Imagick::magnifyImage - Escala una imagen x2 proporcionalmente
    • Imagick::mapImage - Reemplaza los colores de una imagen con el color más cercano de una imagen de referencia
    • Imagick::matteFloodfillImage - Cambia el valor de transparencia de un color
    • Imagick::medianFilterImage - Aplica un filtro digital
    • Imagick::mergeImageLayers - Fusiona las capas de una imagen
    • Imagick::minifyImage - Escala una imagen proporcionalmente a la mitad de su tamaño
    • Imagick::modulateImage - Controla el brillo, la saturación y el tono
    • Imagick::montageImage - Crea una imagen compuesta
    • Imagick::morphImages - Metamorfosea un conjunto de imágenes
    • Imagick::morphology - Description
    • Imagick::mosaicImages - Forma un mosaico de imágenes
    • Imagick::motionBlurImage - Simula borrosidad en movimiento
    • Imagick::negateImage - Invierte los colores en la imagen de referencia
    • Imagick::newImage - Crea una nueva imagen
    • Imagick::newPseudoImage - Crea una nueva imagen
    • Imagick::nextImage - Se mueve a la siguiente imagen
    • Imagick::normalizeImage - Mejora el contraste de una imagen a color
    • Imagick::oilPaintImage - Simula una pintura al óleo
    • Imagick::opaquePaintImage - Cambia el color de cualquier píxel que coincida con el objetivo
    • Imagick::optimizeImageLayers - Elimina porciones repetidas de imágenes para optimizarlas
    • Imagick::orderedPosterizeImage - Realiza un entramado ordenado
    • Imagick::paintFloodfillImage - Cambia el valor del color de cualquier píxel que coincida con el objetivo
    • Imagick::paintOpaqueImage - Cambia cualquier píxel que coincida con el color
    • Imagick::paintTransparentImage - Cambia cualquier píxel que coincida con el color definido para el relleno
    • Imagick::pingImage - Trae los atributos básicos de una imagen
    • Imagick::pingImageBlob - Traer los atributos rápidamente
    • Imagick::pingImageFile - Obtener los atrbutos básicos de la imagen de una manera liviana
    • Imagick::polaroidImage - Simula una fotografía Polaroid
    • Imagick::posterizeImage - Reduce la imagen a un número limitado de niveles de color
    • Imagick::previewImages - Precisa rápidamente los parámetros apropiados para el procesamiento de la imagen
    • Imagick::previousImage - Se mueve a la imagen previa del objeto
    • Imagick::profileImage - Añade o elimina un perfil de una imagen
    • Imagick::quantizeImage - Analiza los colores dentro de una imagen de referencia
    • Imagick::quantizeImages - Analiza los colores dentro de una secuencia de imágenes
    • Imagick::queryFontMetrics - Devuelve una matriz que representa las métricas de la fuente
    • Imagick::queryFonts - Devuelve las fuentes configuradas
    • Imagick::queryFormats - Devuelve los formatos soportados por Imagick
    • Imagick::radialBlurImage - Hace borrosa de forma radial una imagen
    • Imagick::raiseImage - Crea un efecto de botón en 3D simulado
    • Imagick::randomThresholdImage - Crea una imagen de alto contraste y dos colores
    • Imagick::readImage - Lee una imagen desde un nombre de fichero
    • Imagick::readImageBlob - Lee una imagen desde un string binario
    • Imagick::readImageFile - Lee una imagen desde un gestor de fichero abierto
    • Imagick::readimages - Description
    • Imagick::recolorImage - Re-colorea una imagen
    • Imagick::reduceNoiseImage - Suaviza los contornos de una imagen
    • Imagick::remapImage - Re-mapea los colores de una imagen
    • Imagick::removeImage - Quita una imagen de la lista de imágenes
    • Imagick::removeImageProfile - Elimina el perfil nominado de la imagen y lo devuelve
    • Imagick::render - Renderiza todos los comandos de dibujo precedentes
    • Imagick::resampleImage - Remuestrea la imagen a la resolución deseada
    • Imagick::resetImagePage - Reinicia una página de imagen
    • Imagick::resizeImage - Escala una imagen
    • Imagick::rollImage - Compensa una imagen
    • Imagick::rotateImage - Rota una imagen
    • Imagick::rotationalBlurImage - Description
    • Imagick::roundCorners - Redondea las esquinas de una imagen
    • Imagick::sampleImage - Escala una imagen con un muestreo de píxeles
    • Imagick::scaleImage - Escala el tamaño de una imagen
    • Imagick::segmentImage - Segmenta una imagen
    • Imagick::selectiveBlurImage - Description
    • Imagick::separateImageChannel - Separa un canal de la imagen
    • Imagick::sepiaToneImage - Pone una imagen en tono sepia
    • Imagick::setBackgroundColor - Establece el color de fondo por omisión del objeto
    • Imagick::setColorspace - Establecer el espacio de color
    • Imagick::setCompression - Establece el tipo de compresión predeterminado del objeto
    • Imagick::setCompressionQuality - Establece la calidad de compresión predeterminda del objeto
    • Imagick::setFilename - Establece el nombre de archivo antes de que se lea o escriba una imagen
    • Imagick::setFirstIterator - Establece el iterador Imagick para la primera imagen
    • Imagick::setFont - Establece el tipo de letra
    • Imagick::setFormat - Establece el formato del objeto Imagick
    • Imagick::setGravity - Establece la gravedad
    • Imagick::setImage - Reemplaza una imagen en el objeto
    • Imagick::setImageAlphaChannel - Establece el canal alfa de la imagen
    • Imagick::setImageArtifact - Establecer un artefacto de imagen
    • Imagick::setImageAttribute - Description
    • Imagick::setImageBackgroundColor - Establece el color de fondo de la imagen
    • Imagick::setImageBias - Establece el sesgo de la imagen para cualquier método que convolucione una imagen
    • Imagick::setImageBiasQuantum - Description
    • Imagick::setImageBluePrimary - Establece el punto primario azul de la cromaticidad de la imagen
    • Imagick::setImageBorderColor - Establece el color de borde de la imagen
    • Imagick::setImageChannelDepth - Establece la profundidad de una canal de imagen en particular
    • Imagick::setImageClipMask - Establece la máscara de recorte de una imagen
    • Imagick::setImageColormapColor - Establece el color de un índice de mapa de color especificado
    • Imagick::setImageColorspace - Establece el espacio de color de una imagen
    • Imagick::setImageCompose - Establece el operador de composción de una imagen
    • Imagick::setImageCompression - Establece la compresión de una imagen
    • Imagick::setImageCompressionQuality - Establece la calidad de compresión de una imagen
    • Imagick::setImageDelay - Establece el retardo de una imagen
    • Imagick::setImageDepth - Establece la profundidad de una imagen
    • Imagick::setImageDispose - Establece el método de disposición de una imagen
    • Imagick::setImageExtent - Establece el tamaño de una imagen
    • Imagick::setImageFilename - Establece el nombre de archivo de una imagen en particular
    • Imagick::setImageFormat - Establece el formato de una imagen en particular
    • Imagick::setImageGamma - Establece el valor gamma de la imagen
    • Imagick::setImageGravity - Establece la gravedad de la imagen
    • Imagick::setImageGreenPrimary - Establece el punto primario verde de la cromaticidad de la imagen
    • Imagick::setImageIndex - Establece la posición del iterador
    • Imagick::setImageInterlaceScheme - Establece la compresión de la imagen
    • Imagick::setImageInterpolateMethod - Establece el método de interpolación de píxeles
    • Imagick::setImageIterations - Establece las iteraciones de una imagen
    • Imagick::setImageMatte - Establece el canal mate de la imagen
    • Imagick::setImageMatteColor - Establece el color mate de la imagen
    • Imagick::setImageOpacity - Establece el nivel de opacidad de la imagen
    • Imagick::setImageOrientation - Establece la orientación de la imagen
    • Imagick::setImagePage - Establece la geometría de la página de la imagen
    • Imagick::setImageProfile - Añade un perfil nominado al objeto Imagick
    • Imagick::setImageProperty - Establece una propiedad de la imagen
    • Imagick::setImageRedPrimary - Establece el punto primario rojo de la cromaticidad de la imagen
    • Imagick::setImageRenderingIntent - Establece el propósito de renderización de la imagen
    • Imagick::setImageResolution - Establece la resolución de la imagen
    • Imagick::setImageScene - Establece la escena de la imagen
    • Imagick::setImageTicksPerSecond - Establece los ticks por segundo de la imagen
    • Imagick::setImageType - Establece el tipo de imagen
    • Imagick::setImageUnits - Establece las unidades de resolución de la imagen
    • Imagick::setImageVirtualPixelMethod - Establece el método de píxel virtual de la imagen
    • Imagick::setImageWhitePoint - Establece el punto blanco de cromaticidad de la imagen
    • Imagick::setInterlaceScheme - Establece la compresión de la imagen
    • Imagick::setIteratorIndex - Establece la posición del iterador
    • Imagick::setLastIterator - Establece el iterador de Imagick a la última imagen
    • Imagick::setOption - Establece una opción
    • Imagick::setPage - Establece la geometría de página del objeto Imagick
    • Imagick::setPointSize - Establece el tamaño del punto
    • Imagick::setProgressMonitor - Description
    • Imagick::setRegistry - Description
    • Imagick::setResolution - Establece la resolución de la imagen
    • Imagick::setResourceLimit - Establece el límite de un recurso en particular en megabytes
    • Imagick::setSamplingFactors - Establece los factores de muestreo de la imagen
    • Imagick::setSize - Establece el tamaño del objeto Imagick
    • Imagick::setSizeOffset - Establece el tamaño y el índice del objeto Imagick
    • Imagick::setType - Establece el atributo tipo de imagen
    • Imagick::shadeImage - Crea un efecto en 3D
    • Imagick::shadowImage - Simula una sombra de imagen
    • Imagick::sharpenImage - Afila una imagen
    • Imagick::shaveImage - Recorta píxeles de los extremos de la imagen
    • Imagick::shearImage - Crea un paralelogramo
    • Imagick::sigmoidalContrastImage - Ajusta el contraste de una imagen
    • Imagick::sketchImage - Simula el bosquejo de un lapiz
    • Imagick::smushImages - Description
    • Imagick::solarizeImage - Aplica un efecto de solarización a la imagen
    • Imagick::sparseColorImage - Interpola colores
    • Imagick::spliceImage - Une un color sólido en la imagen
    • Imagick::spreadImage - Despalza aleatoriamente cada píxel en un bloque
    • Imagick::statisticImage - Description
    • Imagick::steganoImage - Oculta una marca de agua digital dentro de la imagen
    • Imagick::stereoImage - Compone dos imágenes
    • Imagick::stripImage - Elimina todos los perfiles y comentarios de una imagen
    • Imagick::subImageMatch - Description
    • Imagick::swirlImage - Arremolina los píxeles desde el centro de la imagen
    • Imagick::textureImage - Reviste repetidamente la textura de la imagen
    • Imagick::thresholdImage - Cambia el valor de píexeles individuales basdos en un umbral
    • Imagick::thumbnailImage - Cambia el tamaño de una imagen
    • Imagick::tintImage - Aplica un vector de color a cada píxel en la imagen
    • Imagick::transformImage - Método conveniente para establecer el tamaño del recorte y la geometría de la imagen
    • Imagick::transformImageColorspace - Transforma una imagen a un nuevo espacio de color
    • Imagick::transparentPaintImage - Pinta píxeles transparentes
    • Imagick::transposeImage - Crea una imagen espejo vertical
    • Imagick::transverseImage - Crea una imagen espejo horizontal
    • Imagick::trimImage - Elimina los extremos de la imagen
    • Imagick::uniqueImageColors - Desecha todos los colores de los píxeles excepto uno
    • Imagick::unsharpMaskImage - Afila una imagen
    • Imagick::valid - Comprueba si el elemento actual es válido
    • Imagick::vignetteImage - Añade un filtro de viñeta a la imagen
    • Imagick::waveImage - Aplica un filtro de onda a la imagen
    • Imagick::whiteThresholdImage - Fuerza a todos los píxeles por encima del umbral a ser blancos
    • Imagick::writeImage - Escribe una imagen al nombre de fichero especificado
    • Imagick::writeImageFile - Escribe una imagen a un gestor de archivo
    • Imagick::writeImages - Escribe una imagen o secuencia de imágenes
    • Imagick::writeImagesFile - Escribe fotogramas al gestor de archivo
    • Imagick::__construct - El constructor Imagick
    • Imagick::__toString - Devuelve la imagen como un string
    • ImagickDraw::affine - Ajusta la matriz de transformación afín actual
    • ImagickDraw::annotation - Dibuja texto en la imagen
    • ImagickDraw::arc - Dibuja un arco
    • ImagickDraw::bezier - Dibuja una curva de Bézier
    • ImagickDraw::circle - Dibuja un círculo
    • ImagickDraw::clear - Borra el objeto ImagickDraw
    • ImagickDraw::clone - Hace una copia exacta del objeto ImagickDraw especificado
    • ImagickDraw::color - Dibuja color en una imagen
    • ImagickDraw::comment - Añade un comentario
    • ImagickDraw::composite - Compone una imagen dentro de la imagen actual
    • ImagickDraw::destroy - Libera todos los recursos asociados
    • ImagickDraw::ellipse - Dibuja una elipse en la imagen
    • ImagickDraw::getClipPath - Obtiene el ID del trazado de recorte actual
    • ImagickDraw::getClipRule - Devuelve la regla de relleno de un polígono actual
    • ImagickDraw::getClipUnits - Devuelve la interpretación de unidades del trazado de recorte
    • ImagickDraw::getFillColor - Devuelve el color de relleno
    • ImagickDraw::getFillOpacity - Devuelve la opacidad usada cuando se dibuja
    • ImagickDraw::getFillRule - Devuelve la regla de relleno
    • ImagickDraw::getFont - Devuelve la fuente
    • ImagickDraw::getFontFamily - Devuelve la familia de la fuente
    • ImagickDraw::getFontSize - Devuelve el tamaño de punto de la fuente
    • ImagickDraw::getFontStretch - Description
    • ImagickDraw::getFontStyle - Devuelve el estilo de fuente
    • ImagickDraw::getFontWeight - Devuelve el peso de la fuente
    • ImagickDraw::getGravity - Devuelve la gravedad de emplazamiento del texto
    • ImagickDraw::getStrokeAntialias - Devuelve la configuración de antialias de contorno actual
    • ImagickDraw::getStrokeColor - Devuelve el color usado por los perfiles de objetos contorneados
    • ImagickDraw::getStrokeDashArray - Devuelve un array que representa el patrón de rayas y huecos usado por trazados contorneados
    • ImagickDraw::getStrokeDashOffset - Devuelve el índice dentro del patrón de discontinuidad para iniciar la discontinuidad
    • ImagickDraw::getStrokeLineCap - Devuelve la forma que se va a usar al final de los subtrazados abiertos cuando están contorneados
    • ImagickDraw::getStrokeLineJoin - Devuelve la forma que se va a usar en la esquinas de los trazados cuando están contorneados
    • ImagickDraw::getStrokeMiterLimit - Devuelve el límite del inglete del contorno
    • ImagickDraw::getStrokeOpacity - Devuelve la opacidad del perfil de objetos contorneados
    • ImagickDraw::getStrokeWidth - Devuelve al ancho del contorno usado para dibujar contornos de objetos
    • ImagickDraw::getTextAlignment - Devuelve la alineación del texto
    • ImagickDraw::getTextAntialias - Devuelve la configuración de antialias del texto actual
    • ImagickDraw::getTextDecoration - Devuelve la decoración del texto
    • ImagickDraw::getTextEncoding - Devuelve la codificación usada para anotaciones de texto
    • ImagickDraw::getTextInterlineSpacing - Description
    • ImagickDraw::getTextInterwordSpacing - Description
    • ImagickDraw::getTextKerning - Description
    • ImagickDraw::getTextUnderColor - Devuelve el color debajo del texto
    • ImagickDraw::getVectorGraphics - Devuelve una cadena que contiene gráficos vectoriales
    • ImagickDraw::line - Dibuja una línea
    • ImagickDraw::matte - Pinta sobre el canal de opacidad de la imagen
    • ImagickDraw::pathClose - Añade un elemento de trazado al trazado actual
    • ImagickDraw::pathCurveToAbsolute - Dibuja una curva cúbica de Bézier
    • ImagickDraw::pathCurveToQuadraticBezierAbsolute - Dibuja una curva Bézier cuadrática
    • ImagickDraw::pathCurveToQuadraticBezierRelative - Dibuja una curva Bézier cuadrática
    • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute - Dibuja una curva Bézier cuadrática
    • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative - Dibuja una curva Bézier cuadrática
    • ImagickDraw::pathCurveToRelative - Dibuja una curva cúbica de Bézier
    • ImagickDraw::pathCurveToSmoothAbsolute - Dibuja una curva cúbica de Bézier
    • ImagickDraw::pathCurveToSmoothRelative - Dibuja una curva cúbica de Bézier
    • ImagickDraw::pathEllipticArcAbsolute - Dibuja un arco elíptico
    • ImagickDraw::pathEllipticArcRelative - Dibuja un arco elíptico
    • ImagickDraw::pathFinish - Finaliza el trazado actual
    • ImagickDraw::pathLineToAbsolute - Dibuja un trazado de línea
    • ImagickDraw::pathLineToHorizontalAbsolute - Dibuja un trazado de línea horizontal
    • ImagickDraw::pathLineToHorizontalRelative - Dibuja una línea horizontal
    • ImagickDraw::pathLineToRelative - Dibuja un trazado de línea
    • ImagickDraw::pathLineToVerticalAbsolute - Dibuja un línea vertical
    • ImagickDraw::pathLineToVerticalRelative - Dibuja un trazado de línea vertical
    • ImagickDraw::pathMoveToAbsolute - Inicia un nuevo sub-trazado
    • ImagickDraw::pathMoveToRelative - Inicia un nuevo sub-trazado
    • ImagickDraw::pathStart - Declara el inicio de una lista de dibujo de trazados
    • ImagickDraw::point - Dibuja un punto
    • ImagickDraw::polygon - Dibuja un polígono
    • ImagickDraw::polyline - Dibuja una poli-línea
    • ImagickDraw::pop - Destruye el objeto ImagickDraw actual de la pila, y lo devuelve al objeto ImagickDraw previamente metido
    • ImagickDraw::popClipPath - Finaliza una definición de un trazado de recorte
    • ImagickDraw::popDefs - Finaliza una lista de definiciones
    • ImagickDraw::popPattern - Finaliza una definición de patrón
    • ImagickDraw::push - Clona el objeto ImagickDraw actual y lo mete en la pila
    • ImagickDraw::pushClipPath - Inicia la definición de un trazado de recorte
    • ImagickDraw::pushDefs - Indica que los siguientes comandos crean elementos con nombre para un procesamiento previo
    • ImagickDraw::pushPattern - Indica que los comandos subsiguientes hasta un comando ImagickDraw::opPattern() comprenden la definición de un patrón nominado
    • ImagickDraw::rectangle - Dibuja un rectángulo
    • ImagickDraw::render - Renderiza todos los comandos de dibujo precedentes en la imagen
    • ImagickDraw::resetVectorGraphics - Description
    • ImagickDraw::rotate - Aplica la rotación especificada al espacio de coordenadas actual
    • ImagickDraw::roundRectangle - Dibuja un rectángulo redondeado
    • ImagickDraw::scale - Ajusta el factor de escala
    • ImagickDraw::setClipPath - Asocia un trazado de recorte nominado con la imagen
    • ImagickDraw::setClipRule - Establece la regla de relleno de polígonos a usar por el trazado de recorte
    • ImagickDraw::setClipUnits - Establece la interpretación de las unidades de un trazado de recorte
    • ImagickDraw::setFillAlpha - Establece la opacidad a usar cuando se dibuja utilizando el color de relleno o la textura de relleno
    • ImagickDraw::setFillColor - Establece el color de relleno que se va a usar para dibujar objetos rellenos
    • ImagickDraw::setFillOpacity - Establece la opacidad para usarla cuando se dibuja utilizando el color de relleno o la textura de relleno
    • ImagickDraw::setFillPatternURL - Establece la URL a usar como un patrón de relleno para objetos rellenos
    • ImagickDraw::setFillRule - Establece la regla de relleno a usar mientras se dibujan polígonos
    • ImagickDraw::setFont - Establece la fuente especificada completamente para usarla cuando se escribe texto
    • ImagickDraw::setFontFamily - Establece la familia de fuentes para usarla cuando se escribe texto
    • ImagickDraw::setFontSize - Establece el tamaño de punto de la fuente para usarlo cuando se escribe texto
    • ImagickDraw::setFontStretch - Establece el estiramiento de la fuente para usarla cuando se escribe texto
    • ImagickDraw::setFontStyle - Establece el estilo de fuente para usarlo cuando se escribe texto
    • ImagickDraw::setFontWeight - Establece el peso de fuente
    • ImagickDraw::setGravity - Establece la gravedad de ubicación del texto
    • ImagickDraw::setResolution - Description
    • ImagickDraw::setStrokeAlpha - Especifica la opacidad de los perfiles de los objetos contorneados
    • ImagickDraw::setStrokeAntialias - Controla si los perfiles contorneados tiene antialias
    • ImagickDraw::setStrokeColor - Establece el color usado por los perfiles de objetos contorneados
    • ImagickDraw::setStrokeDashArray - Especifica el patrón de rayas y huecos usado por los trazados de contorno
    • ImagickDraw::setStrokeDashOffset - Especifica el índice dentro del patrón de discontinuidad para iniciar la discontinuidad
    • ImagickDraw::setStrokeLineCap - Especifica la forma que se va a usar al final de los subtrazados abiertos cuando están contorneados
    • ImagickDraw::setStrokeLineJoin - Especifica la forma que se va a usar en la esquinas de los trazados cuando están contorneados
    • ImagickDraw::setStrokeMiterLimit - Especifica el límite del inglete
    • ImagickDraw::setStrokeOpacity - Especifica la opacidad de los perfiles de los objetos contorneados
    • ImagickDraw::setStrokePatternURL - Establece el patrón usado para los perfiles de objetos contorneados
    • ImagickDraw::setStrokeWidth - Establece el ancho del contorno a usar para dibujar perfiles de objetos
    • ImagickDraw::setTextAlignment - Especifica una alineación de texto
    • ImagickDraw::setTextAntialias - Controla si el texto tiene antialias
    • ImagickDraw::setTextDecoration - Especifica una decoración
    • ImagickDraw::setTextEncoding - Especifica el conjunto de codificación del texto
    • ImagickDraw::setTextInterlineSpacing - Description
    • ImagickDraw::setTextInterwordSpacing - Description
    • ImagickDraw::setTextKerning - Description
    • ImagickDraw::setTextUnderColor - Especifica el color de un rectángulo de fondo
    • ImagickDraw::setVectorGraphics - Establece los gráficos vectoriales
    • ImagickDraw::setViewbox - Establece el tamaño de todos los lienzos
    • ImagickDraw::skewX - Tuerce el sistema de coordenadas actual en la dirección horizontal
    • ImagickDraw::skewY - Tuerce el sistema de coordenadas actual en la dirección vertical
    • ImagickDraw::translate - Aplica una traslación del sistema de coordenadas actual
    • ImagickDraw::__construct - El constructor ImagickDraw
    • ImagickKernel::addKernel - Description
    • ImagickKernel::addUnityKernel - Description
    • ImagickKernel::fromBuiltIn - Description
    • ImagickKernel::fromMatrix - Description
    • ImagickKernel::getMatrix - Description
    • ImagickKernel::scale - Description
    • ImagickKernel::separate - Description
    • ImagickPixel::clear - Borra los recursos asociados con este objeto
    • ImagickPixel::destroy - Desasigna los recursos asociados con este objeto
    • ImagickPixel::getColor - Devuelve el color
    • ImagickPixel::getColorAsString - Devuelve el color como string
    • ImagickPixel::getColorCount - Devuelve la cuenta de color asociada a este
    • ImagickPixel::getColorQuantum - Description
    • ImagickPixel::getColorValue - Obtiene el valor normalizado del canal de color proporcionado
    • ImagickPixel::getColorValueQuantum - Description
    • ImagickPixel::getHSL - Devuelve el color HSL normalizado del objeto ImagickPixel
    • ImagickPixel::getIndex - Description
    • ImagickPixel::isPixelSimilar - Comprobar la distancia entre este color y otro
    • ImagickPixel::isPixelSimilarQuantum - Description
    • ImagickPixel::isSimilar - Comprobar la distancia entre este color y otro
    • ImagickPixel::setColor - Establece el color
    • ImagickPixel::setColorCount - Description
    • ImagickPixel::setColorValue - Establece el valor normalizado de uno de los canales
    • ImagickPixel::setColorValueQuantum - Description
    • ImagickPixel::setHSL - Establece el color HSL normalizado
    • ImagickPixel::setIndex - Description
    • ImagickPixel::__construct - El constructor ImagickPixel
    • ImagickPixelIterator::clear - Borra los recursos asociados con un objeto PixelIterator
    • ImagickPixelIterator::destroy - Desasigna los recursos asociacdos con un objeto PixelIterator
    • ImagickPixelIterator::getCurrentIteratorRow - Devuelve la fila actual de objetos ImagickPixel
    • ImagickPixelIterator::getIteratorRow - Devuelve la fila actual del iterador de píxel
    • ImagickPixelIterator::getNextIteratorRow - Devuelve la fila siguiente del iterador de píxel
    • ImagickPixelIterator::getPreviousIteratorRow - Devuelve la fila previa
    • ImagickPixelIterator::newPixelIterator - Devuelve un nuevo iterador de píxel
    • ImagickPixelIterator::newPixelRegionIterator - Devuelve un nuevo iterador de píxel
    • ImagickPixelIterator::resetIterator - Reinicia el iterador de píxel
    • ImagickPixelIterator::setIteratorFirstRow - Establece el iterador de píxel a la primera fila de píxeles
    • ImagickPixelIterator::setIteratorLastRow - Establece el iterador de píxel a la última fila de píxeles
    • ImagickPixelIterator::setIteratorRow - Establecer la fila del iterador de píxel
    • ImagickPixelIterator::syncIterator - Sincornizar el iterador de píxel
    • ImagickPixelIterator::__construct - El constructor ImagickPixelIterator
    • imap_8bit - Convertir una cadena 8bit a una cadena quoted-printable
    • imap_alerts - Devuelve todos los mensajes de alerte de IMAP que han sucedido
    • imap_append - Añadir un mensaje de cadena a un buzón especificado
    • imap_base64 - Decodificar un texto cifrado con BASE64
    • imap_binary - Convertir una cadena 8bit a una cadena base64
    • imap_body - Leer el cuerpo del mensaje
    • imap_bodystruct - Leer la estructura de una sección del cuerpo especificado de un mensaje especificado
    • imap_check - Comprobar el buzón actual
    • imap_clearflag_full - Limpia las banderas de mensajes
    • imap_close - Cerrar una secuencia IMAP
    • imap_create - Alias de imap_createmailbox
    • imap_createmailbox - Crear un nuevo buzón de correo
    • imap_delete - Marcar un mensaje para su borrado del buzón actual
    • imap_deletemailbox - Elimina un buzón
    • imap_errors - Devuelve todos los errores de IMAP que han ocurrido
    • imap_expunge - Borra todos los mensajes marcados para eliminación
    • imap_fetchbody - Traer una sección en particular del cuerpo del mensaje
    • imap_fetchheader - Devolver la cabecera de un mensaje
    • imap_fetchmime - Obtener las cabeceras MIME para una sección en particular del mensaje
    • imap_fetchstructure - Leer la estructura de un mensaje en particular
    • imap_fetchtext - Alias de imap_body
    • imap_fetch_overview - Leer una visión general de la información de las cabeceras del mensaje dado
    • imap_gc - Limpia la caché de IMAP
    • imap_getacl - Obtiene el ACL para un buzón dado
    • imap_getmailboxes - Leer la lista de buzones, devolviendo información detallada de cada uno
    • imap_getsubscribed - Listar todos los buzones suscritos
    • imap_get_quota - Obtener la cuota de ajustes por usuario, y las estadísticas de uso por buzón
    • imap_get_quotaroot - Obtener la cuota de ajustes por usuario
    • imap_header - Alias de imap_headerinfo
    • imap_headerinfo - Leer la cabecera del mensaje
    • imap_headers - Devuelve las cabeceras de todos los mensajes de un buzón
    • imap_last_error - Obtiene el último error de IMAP que ocurrió durante esta petición de página
    • imap_list - Leer la lista de buzones
    • imap_listmailbox - Alias de imap_list
    • imap_listscan - Devuelve la lista de buzones que coinciden con el texto dado
    • imap_listsubscribed - Alias de imap_lsub
    • imap_lsub - Listar todos los buzones suscritos
    • imap_mail - Enviar un mensaje de correo electrónico
    • imap_mailboxmsginfo - Obtener información sobre el buzón actual
    • imap_mail_compose - Crear un mensaje MIME basado en las secciones sobre y cuerpo
    • imap_mail_copy - Copiar los mensajes especificados a un buzón
    • imap_mail_move - Mover los mensajes especificados a un buzón
    • imap_mime_header_decode - Decodificar los elementos de la cabecera MIME
    • imap_msgno - Obtiene el número de secuencia de mensaje para el UID dado
    • imap_mutf7_to_utf8 - Decode a modified UTF-7 string to UTF-8
    • imap_num_msg - Obtiene el número de mensajes del buzón actual
    • imap_num_recent - Obtiene el número de mensajes recientes en el buzón actual
    • imap_open - Abrir un flujo IMAP a un buzón
    • imap_ping - Comprobar si el flujo de IMAP está aún activo
    • imap_qprint - Convertir una cadena imprimible entrecomillada a una cadena de 8 bits
    • imap_rename - Alias de imap_renamemailbox
    • imap_renamemailbox - Renombrar un buzón antiguo a un buzón nuevo
    • imap_reopen - Reabrir un flujo IMAP hacia un nuevo buzón
    • imap_rfc822_parse_adrlist - Analiza una cadena de dirección
    • imap_rfc822_parse_headers - Analizar cabeceras de correo desde una cadena
    • imap_rfc822_write_address - Devuelve una dirección de correo correctamente formateada dados el buzón, host e información personal
    • imap_savebody - Guardar una sección del cuerpo específica en un fichero
    • imap_scan - Alias de imap_listscan
    • imap_scanmailbox - Alias de imap_listscan
    • imap_search - Esta función devuelve un array de mensajes que coinciden con el criterio de búsqueda dado
    • imap_setacl - Establece el ACL para el buzón dado
    • imap_setflag_full - Establece banderas en mensajes
    • imap_set_quota - Establece una cuota para un buzón dado
    • imap_sort - Obtiene y ordena mensajes
    • imap_status - Devuelve la información de estado de un buzón
    • imap_subscribe - Suscribirse a un buzón
    • imap_thread - Devuelve un árbol de mensajes hilados
    • imap_timeout - Establece o obtiene el tiempo de espera de imap
    • imap_uid - Esta función devuelve el UID del número de secuencia del mensaje dado
    • imap_undelete - Desmarcar el mensaje que está marcado para borrar
    • imap_unsubscribe - Cancelar la inscripción de un buzón
    • imap_utf7_decode - Decodifica una cadena codificada con UTF-7 modificado
    • imap_utf7_encode - Convierte una cadena ISO-8859-1 a un texto UTF-7 modifiicado
    • imap_utf8 - Convierte texto codificado MIME en UTF-8
    • imap_utf8_to_mutf7 - Encode a UTF-8 string to modified UTF-7
    • implode - Une elementos de un array en un string
    • inet_ntop - Convertir una dirección de internet empaquetada en una representación legible por humanos
    • inet_pton - Convertir una dirección IP legible por humanos a su representación in_addr empaquetada
    • InfiniteIterator::next - Mueve el iterador interno hacía adelante o se rebobina
    • InfiniteIterator::__construct - Construye 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
    • ingres_autocommit - Activa o desactiva la autoconsigna
    • ingres_autocommit_state - Comprueba si la conexión usa la autoconsigna
    • ingres_charset - Devuelve el conjunto de caracteres de la instalación
    • ingres_close - Cierra una conexión a una base de datos de Ingres
    • ingres_commit - Consigna una trasacción
    • ingres_connect - Abre una conexión a una base de datos de Ingres
    • ingres_cursor - Obtiene el nombre de un cursor de un recurso de resultados dado
    • ingres_errno - Obtiene el número del último error generado de Ingres
    • ingres_error - Obtener un mensaje de error coherente del último error generado
    • ingres_errsqlstate - Obtiene el código del último error SQLSTATE generado
    • ingres_escape_string - Escapa caracteres especiales para usuarlos en una consulta
    • ingres_execute - Ejecuta una consulta preparada
    • ingres_fetch_array - Obtiene una fila de resultados en un array
    • ingres_fetch_assoc - Obtienen una fila de resultados en un array asociativo
    • ingres_fetch_object - Obtiene una fila de resultados en un objeto
    • ingres_fetch_proc_return - Obtiene el valor de retorno de una llamada a un procedimiento
    • ingres_fetch_row - Obtiene una fila de resultados en un array enumerado
    • ingres_field_length - Obtiene la longitud de un campo
    • ingres_field_name - Obtiene el nombre de un campo de un resultado de una consulta
    • ingres_field_nullable - Comprueba si un campo puede contener valores null
    • ingres_field_precision - Obtiene la precisión de un campo
    • ingres_field_scale - Obtiene la escala de un campo
    • ingres_field_type - Obtiene el tipo de un campo de un resultado de una consulta
    • ingres_free_result - Libera los recursos asociados a un identificador de resultados
    • ingres_next_error - Obtiene el siguiente error de Ingres
    • ingres_num_fields - Obtiene el número de campos devueltos por la última consulta
    • ingres_num_rows - Obtener el número de filas afectadas o devueltas por una consulta
    • ingres_pconnect - Abre una conexión persistente a una base de datos de Ingres
    • ingres_prepare - Prepara una consulta para su ejecución posterior
    • ingres_query - Envía una consulta SQL a Ingres
    • ingres_result_seek - Establece la posición de una fila antes de obtener datos
    • ingres_rollback - Revierte una transacción
    • ingres_set_environment - Establece las características de entorno que controlan las opciones de salida
    • ingres_unbuffered_query - Envía una consulta SQL no almacenada en búfer a Ingres
    • ini_alter - Alias de ini_set
    • ini_get - Devuelve el valor de una directiva de configuración
    • ini_get_all - Obtiene todas las opciones de configuración
    • ini_restore - Restablece el valor de una opción de configuración
    • ini_set - Establece el valor de una directiva de configuración
    • inotify_add_watch - Añade un seguimiento a una instancia inotify inicializada
    • inotify_init - Inicializa una instancia inotify
    • inotify_queue_len - Devuelve un número superior a cero si hay eventos pendientes
    • inotify_read - Lee eventos de una instancia inotify
    • inotify_rm_watch - Elimina un seguimiento existente de una instancia inotify
    • intdiv - División entera
    • interface_exists - Comprueba si una interfaz ha sido definida
    • IntlBreakIterator::createCharacterInstance - Crear un iterador de ruptura para los límites de secuencias de caracters combinados
    • IntlBreakIterator::createCodePointInstance - Crear un iterador de ruptura para los límites de puntos de código
    • IntlBreakIterator::createLineInstance - Crear un iterador de ruptura para las lógicamente posibles saltos de línea
    • IntlBreakIterator::createSentenceInstance - Crear un iterador de ruptura para rupturas de sentencias
    • IntlBreakIterator::createTitleInstance - Crear un iterador de ruptura para rupturas de marcos de título
    • IntlBreakIterator::createWordInstance - Crear un iterador de ruptura para ruptura de palabras
    • IntlBreakIterator::current - Obtiene el índice de la posición actual
    • IntlBreakIterator::first - Coloca la posición al primer caracter en el texto
    • IntlBreakIterator::following - Avanza el iterador al primer límite siguiendo un offset específico
    • IntlBreakIterator::getErrorCode - Obtener el código del último error del objeto
    • IntlBreakIterator::getErrorMessage - Obtener el último mensaje de error del objeto
    • IntlBreakIterator::getLocale - Obtiene el locale asociado al objeto
    • IntlBreakIterator::getPartsIterator - Crear un iterador para fragmentos de navegación entre límites
    • IntlBreakIterator::getText - Obtiene el texto que está siendo escaneado
    • IntlBreakIterator::isBoundary - Indicar si un índice es un índice de límites
    • IntlBreakIterator::last - Establecer la posición del iterador al índice tras el último carácter
    • IntlBreakIterator::next - Avanzar el iterador al siguiente límite
    • IntlBreakIterator::preceding - Establecer la posición del iterador al primer límite antes de un índice
    • IntlBreakIterator::previous - Establecer la posición del iterador al límite inmediatamente anterior al actual
    • IntlBreakIterator::setText - Establecer el texto a escanear
    • IntlBreakIterator::__construct - Constructor privado para denegar la instanciación
    • IntlCalendar::add - Añadir una candidad (con signo) de tiempo al campo
    • IntlCalendar::after - Indica si el instante de este objeto es posterior al del proporcionado
    • IntlCalendar::before - Indica si el instante de este objeto es anterior al del proporcionado
    • IntlCalendar::clear - Limpiar uno o todos los campos
    • IntlCalendar::createInstance - Crear un nuevo IntlCalendar
    • IntlCalendar::equals - Comparar el instante de dos objetos IntlCalendar
    • IntlCalendar::fieldDifference - Calcular la diferencia entre el instante dado y el de este objeto
    • IntlCalendar::fromDateTime - Crear un IntlCalendar desde un objeto DateTime o tring
    • IntlCalendar::get - Obtiene el valor de un campo
    • IntlCalendar::getActualMaximum - El valor máximo de un campo, considerando el instante actual del objeto
    • IntlCalendar::getActualMinimum - El valor mínimo de un campo, considerando el instante actual del objeto
    • IntlCalendar::getAvailableLocales - Obtener un array con las zonas para las que existen datos
    • IntlCalendar::getDayOfWeekType - Inidcar si un día es un día de entresemana, del fin de semana o un día de transición entre ambos
    • IntlCalendar::getErrorCode - Obtener el código de error del objeto
    • IntlCalendar::getErrorMessage - Obtener el últime mensaje de error del objeto
    • IntlCalendar::getFirstDayOfWeek - Obtener el primer día de la semana de la región del calendario
    • IntlCalendar::getGreatestMinimum - Obtener el valor mínimo local más grande de un campo
    • IntlCalendar::getKeywordValuesForLocale - Obtener un conjunto de valores de palabras clave de zonas
    • IntlCalendar::getLeastMaximum - Obtener el máximo local más pequeño de un campo
    • IntlCalendar::getLocale - Obtener la configuración regional asociada al objeto
    • IntlCalendar::getMaximum - Obtener el valor máximo global de un campo
    • IntlCalendar::getMinimalDaysInFirstWeek - Obtener el número mínimo de días que puede tener la primera semana de un año o mes
    • IntlCalendar::getMinimum - Obtener el valor mínimo de un campo
    • IntlCalendar::getNow - Obtener el número que representa el instante actual
    • IntlCalendar::getRepeatedWallTimeOption - Obtener el comportamiento para tratar horas repetidas
    • IntlCalendar::getSkippedWallTimeOption - Obtener el comportamiento para tratar horas omitidas
    • IntlCalendar::getTime - Obtiene el tiempo representado por el objeto
    • IntlCalendar::getTimeZone - Obtener la zona horaria del objeto
    • IntlCalendar::getType - Obtener el tipo de calendario
    • IntlCalendar::getWeekendTransition - Obtener el instante del día en la que comienza o termina el fin de semana
    • IntlCalendar::inDaylightTime - Indicar si el instante del objeto está en el horario de verano
    • IntlCalendar::isEquivalentTo - Indicar si otro calendario es igual pero para un instante diferente
    • IntlCalendar::isLenient - Indicar si la interpretación de una fecha/hora está en modo tolerante
    • IntlCalendar::isSet - Determina si un campo está definido
    • IntlCalendar::isWeekend - Determina si una cierta fecha es fin de semana
    • IntlCalendar::roll - Añadir un valor a un campo si acarrear más campos significativos
    • IntlCalendar::set - Establecer un campo de instante o varios campos en común de una vez
    • IntlCalendar::setFirstDayOfWeek - Establecer el día en el que se estima que empieza la semana
    • IntlCalendar::setLenient - Establecer si la interpretación de la fecha/hora es tolerante
    • IntlCalendar::setMinimalDaysInFirstWeek - Establecer el número de días mínimo que puede tener la primera semana de un año o mes
    • IntlCalendar::setRepeatedWallTimeOption - Establecer el comportamiento para tratar horas repetidas en transiciones negativas de índices de zonas horarias
    • IntlCalendar::setSkippedWallTimeOption - Establecer el comportamiento para tratar horas omitidas en transiciones positivas de índices de zonas horarias
    • IntlCalendar::setTime - Establecer el momento del calendario en milisegundos desde la época
    • IntlCalendar::setTimeZone - Establecer la zona horaria usada por este calendario
    • IntlCalendar::toDateTime - Convertir un objeto IntlCalendar a un objeto DateTime
    • IntlCalendar::__construct - Constructor privado para no permitir la creación de instancias
    • IntlChar::charAge - Obtener la «edad» del punto de código
    • IntlChar::charDigitValue - Obtener el valor del dígito decimal de un carácter de dígito decimal
    • IntlChar::charDirection - Obtener el valor de la categoría bidireccional de un punto de código
    • IntlChar::charFromName - Buscar un carácter Unicode por su nombre y devolver su valor de punto de código
    • IntlChar::charMirror - Obtener el carácter de «imagen reflejada» de un punto de código
    • IntlChar::charName - Obtener el nombre de un carácter Unicode
    • IntlChar::charType - Obtener el valor de la categoría general de un punto de código
    • IntlChar::chr - Devolver el carácter Unicode mediante su valor de punto de código
    • IntlChar::digit - Obtener el valor del dígito decimal de un punto de código para una base dada
    • IntlChar::enumCharNames - Enumerar todos los caracteres de Unicode con asignación dentro de un rango
    • IntlChar::enumCharTypes - Enumerar todos los puntos de código con sus categorías generales de Unicode
    • IntlChar::foldCase - Realiza un «plegamiento» de un punto de código
    • IntlChar::forDigit - Obtener la representación de un carácter para un dígito y base dados
    • IntlChar::getBidiPairedBracket - Obtener la pareja del carácter parentético de un punto de código
    • IntlChar::getBlockCode - Obtener el bloque de asignación de Unicode que contiene a un punto de código
    • IntlChar::getCombiningClass - Obtener la clase de combinación de un punto de cógido
    • IntlChar::getFC_NFKC_Closure - Obtener la propiedad FC_NFKC_Closure de un punto de código
    • IntlChar::getIntPropertyMaxValue - Obtener el valor máximo de una propiedad de Unicode
    • IntlChar::getIntPropertyMinValue - Obtener el valor mínimo de una propiedad de Unicode
    • IntlChar::getIntPropertyValue - Obtener el valor de una propiedad de Unicode para un punto de código
    • IntlChar::getNumericValue - Obtener el valor numérico de un punto de código de Unicode
    • IntlChar::getPropertyEnum - Obtener el valor de la constante de una propiedad para un nombre de propiedad dado
    • IntlChar::getPropertyName - Obtener el nombre Unicode de una propiedad
    • IntlChar::getPropertyValueEnum - Obtener el valor de una propiedad para un nombre de valor dado
    • IntlChar::getPropertyValueName - Obtener el nombre Unicode para un valor de una propiedad
    • IntlChar::getUnicodeVersion - Obtener la versión de Unicode
    • IntlChar::hasBinaryProperty - Comprobar una propiedad de Unicode binaria para un punto de código
    • IntlChar::isalnum - Comporbar si un punto de código es un carácter alfanumérico
    • IntlChar::isalpha - Comprobar si un punto de código es un caracter de letra
    • IntlChar::isbase - Comprobar si un punto de código es un carácter base
    • IntlChar::isblank - Comprobar si un punto de código es un carácter «en blanco» o de «espacio horizontal»
    • IntlChar::iscntrl - Comprobar si un punto de código es un carácter de control
    • IntlChar::isdefined - Comprobar si un punto de código está definido
    • IntlChar::isdigit - Comprobar si un punto de código es un carácter de dígito
    • IntlChar::isgraph - Comprobar si un punto de código es un caráter gráfico
    • IntlChar::isIDIgnorable - Comprobar si un punto de código es un carácter ignorable
    • IntlChar::isIDPart - Comprobar si un punto de código es permisible en un identificador
    • IntlChar::isIDStart - Comprobar si un punto de código es permisible como el primer carácter de un identificador
    • IntlChar::isISOControl - Comprobar si un punto de código es un código de control de ISO
    • IntlChar::isJavaIDPart - Comprobar si un punto de código es permisible en un identificador de Java
    • IntlChar::isJavaIDStart - Comprobar si un punto de código es permisible como el primer carácter de un identificador de Java
    • IntlChar::isJavaSpaceChar - Comprobar si un punto de código es un carácter de espacio según Java
    • IntlChar::islower - Comprobar si un punto de código es una letra minúscula
    • IntlChar::isMirrored - Comprobar si un punto de código posee la propiedad Bidi_Mirrored
    • IntlChar::isprint - Comprobar si un punto de código es un carácter imprimible
    • IntlChar::ispunct - Comprobar si un punto de código es un carácter de puntuación
    • IntlChar::isspace - Comprobar si un punto de código es un carácter de espacio
    • IntlChar::istitle - Comprobar si un punto de código es una letra titular
    • IntlChar::isUAlphabetic - Comprobar si un punto de código tiene la propiedad de Unicode Alphabetic
    • IntlChar::isULowercase - Comprobar si un punto de código tiene la propiedad de Unicode Lowercase
    • IntlChar::isupper - Comprobar si un punto de código tiene la categoría general "Lu" (letra mayúscula)
    • IntlChar::isUUppercase - Comprobar si un punto de código tiene la propiedad de Unicode Uppercase
    • IntlChar::isUWhiteSpace - Comprobar si un punto de código tiene la propiedad de Unicode White_Space
    • IntlChar::isWhitespace - Comprobar si un punto de código es un carácter de espacio en blanco según ICU
    • IntlChar::isxdigit - Comprobar si el punto de código es un dígito hexadecimal
    • IntlChar::ord - Devolver el valor del punto de código de Unicode de un carácter
    • IntlChar::tolower - Convertir a minúsculas un carácter Unicode
    • IntlChar::totitle - Convertir un carácter Unicode a letra titular
    • IntlChar::toupper - Convertir a mayúsculas un carácter Unicode
    • IntlCodePointBreakIterator::getLastCodePoint - Obtener el último punto de código ignorado después de que el iterdor avance o retroceda
    • IntlDateFormatter::create - Crear un formateador de fechas
    • IntlDateFormatter::format - Formatear el valor fecha/hora como una cadena
    • IntlDateFormatter::formatObject - Formatea un objeto
    • IntlDateFormatter::getCalendar - Obtener el tipo de calendario usado por el objeto IntlDateFormatter
    • IntlDateFormatter::getCalendarObject - Obtener una copia del objeto calendario del formateador
    • IntlDateFormatter::getDateType - Obtener el tipo de fecha usada por un formateador de IntlDateFormatter
    • IntlDateFormatter::getErrorCode - Obtener el código del error de la última operación
    • IntlDateFormatter::getErrorMessage - Obtener el texto del error de la última operación
    • IntlDateFormatter::getLocale - Obtener la configuración regional usada por un formateador
    • IntlDateFormatter::getPattern - Obtener el patrón utilizado por un formateador de IntlDateFormatter
    • IntlDateFormatter::getTimeType - Obtener el tipo de hora usada por un formateador de IntlDateFormatter
    • IntlDateFormatter::getTimeZone - Obtener la zona horaria del formateador
    • IntlDateFormatter::getTimeZoneId - Obtener el ID de la zona horario usada por un formateador de IntlDateFormatter
    • IntlDateFormatter::isLenient - Obtener la tolerancia usada por un formateador de IntlDateFormatter
    • IntlDateFormatter::localtime - Convertir una cadena en un valor de marca de tiempo basado en un campo
    • IntlDateFormatter::parse - Convertir una cadena en un valor de marca de tiempo
    • IntlDateFormatter::setCalendar - Establecer el tipo de calendario usado por el formateador
    • IntlDateFormatter::setLenient - Establecer la tolerancia del analizador
    • IntlDateFormatter::setPattern - Establecer el patrón utilizado por el formateador de IntlDateFormatter
    • IntlDateFormatter::setTimeZone - Establece la zona horaria del formateador
    • IntlIterator::current - Obtiene el elemento actual
    • IntlIterator::key - Obtiene la clave actual
    • IntlIterator::next - Adelanta hasta el siguiente elemento
    • IntlIterator::rewind - Mueve el iterador al primer elemento
    • IntlIterator::valid - Comprueba si la posición actual es válida
    • IntlPartsIterator::getBreakIterator - Obtener un IntlBreakIterator respaldando este iterador de partes
    • IntlRuleBasedBreakIterator::getBinaryRules - Obtener la forma binaria de las reglas compiladas
    • IntlRuleBasedBreakIterator::getRules - Obtener el conjunto de reglas empleado para crear este objeto
    • IntlRuleBasedBreakIterator::getRuleStatus - Obtener el mayor valor de estado de las reglas de ruptura que determinaron la posición de ruptura actual
    • IntlRuleBasedBreakIterator::getRuleStatusVec - Obtener los valores de estado de las reglas de ruptura que determinaron la posición de ruptura acutal
    • IntlRuleBasedBreakIterator::__construct - Crear un iterador desde un conjunto de reglas
    • IntlTimeZone::countEquivalentIDs - Obtener el número de ID del grupo de equivalencias que incluye el ID dado
    • IntlTimeZone::createDefault - Crear una nueva copia de la zona horaria predeterminada para este host
    • IntlTimeZone::createEnumeration - Obtener una enumeración de ID de zonas horarias asociados al país o índice dado
    • IntlTimeZone::createTimeZone - Crear un objeto de zona horaria para el ID dado
    • IntlTimeZone::createTimeZoneIDEnumeration - Get an enumeration over system time zone IDs with the given filter conditions
    • IntlTimeZone::fromDateTimeZone - Crear un objeto de zona horaria desde DateTimeZone
    • IntlTimeZone::getCanonicalID - Obtener el ID canónico de la zona horaria del sistema o el ID normalizado de la zona horaria personalizada para el ID de zona horaria dado
    • IntlTimeZone::getDisplayName - Obtener un nombre de esta zona horaria apto para la presentación al usuario
    • IntlTimeZone::getDSTSavings - Obtener la cantidad de tiempo a añadir a la hora local estándar para obtener la hora local actual
    • IntlTimeZone::getEquivalentID - Obtener un ID del grupo de equivalencias que incluya el ID dado
    • IntlTimeZone::getErrorCode - Obtener el último código de error del objeto
    • IntlTimeZone::getErrorMessage - Obtener el último mensaje de error del objeto
    • IntlTimeZone::getGMT - Crear una zona horaria GMT (UTC)
    • IntlTimeZone::getID - Obtener el ID de la zona horaria
    • IntlTimeZone::getIDForWindowsID - Translate a Windows timezone into a system timezone
    • IntlTimeZone::getOffset - Obtener la zona horaria sin tratar y el índice GMT para el momento dado
    • IntlTimeZone::getRawOffset - Obtener el índice GMT sin tratar (antes de tomar en cuenta el horario de verano)
    • IntlTimeZone::getRegion - Get the region code associated with the given system time zone ID
    • IntlTimeZone::getTZDataVersion - Obtener la versión de los datos de zonas horarias actualmente usada por ICU
    • IntlTimeZone::getUnknown - Get the "unknown" time zone
    • IntlTimeZone::getWindowsID - Translate a system timezone into a Windows timezone
    • IntlTimeZone::hasSameRules - Comprobar si esta zona horaria tiene las mismas reglas e índices que otra
    • IntlTimeZone::toDateTimeZone - Convertir a un objeto DateTimeZone
    • IntlTimeZone::useDaylightTime - Comprobar si esta zona horaria utiliza el horario de verano
    • intl_error_name - Obtiene un nombre simbólico a partir de un código de error dado
    • intl_get_error_code - Obtiene el último código de error
    • intl_get_error_message - Obtener una descripción del último error
    • intl_is_failure - Comprueba si el código de error dado indica un fallo
    • intval - Obtiene el valor entero de una variable
    • in_array - Comprueba si un valor existe en un array
    • ip2long - Convierte una cadena que contiene una dirección con puntos del Protocolo de Internet (IPv4) en una dirección apropiada
    • iptcembed - Incluir información IPTC binaria en una imagen JPEG
    • iptcparse - Conviertir un bloque IPTC binario en simples etiquetas
    • isset - Determina si una variable está definida y no es null
    • is_a - Comprueba si un objeto es de una clase o tiene esta clase como una de sus madres
    • is_array - Comprueba si una variable es un array
    • is_bool - Comprueba si una variable es de tipo booleano
    • is_callable - Verificar que los contenidos de una variable puedan ser llamados como una función
    • is_countable - Verifica que el contenido de una variable es un valor contable
    • is_dir - Indica si el nombre de archivo es un directorio
    • is_double - Alias de is_float
    • is_executable - Indica si el nombre de archivo es ejecutable
    • is_file - Indica si el nombre de fichero es un fichero normal
    • is_finite - Encuentra si un valor es un número finito legal
    • is_float - Comprueba si el tipo de una variable es float
    • is_infinite - Encuentra si un valor es infinito
    • is_int - Comprueba si el tipo de una variable es integer
    • is_integer - Alias de is_int
    • is_iterable - Verifica que el contenido de una variable es un valor iterable
    • is_link - Indica si el nombre de archivo es un enlace simbólico
    • is_long - Alias de is_int
    • is_nan - Encuentra si un valor no es un número
    • is_null - Comprueba si una variable es null
    • is_numeric - Comprueba si una variable es un número o un string numérico
    • is_object - Comprueba si una variable es un objeto
    • is_readable - Indica si un fichero existe y es legible
    • is_real - Alias de is_float
    • is_resource - Comprueba si una variable es un recurso
    • is_scalar - Comprueba si una variable es escalar
    • is_soap_fault - Comprueba si una llamada SOAP ha fallado
    • is_string - Comprueba si una variable es de tipo string
    • is_subclass_of - Comprueba si el objeto tiene esta clase como uno de sus padres o si la implementa
    • is_tainted - Comprobar si un string está corrompido
    • is_uploaded_file - Indica si el archivo fue subido mediante HTTP POST
    • is_writable - Indica si un archivo existe y es escribible
    • is_writeable - Alias de is_writable
    • Iterator::current - Devuelve el elemento actual
    • Iterator::key - Devuelve la clave del elemento actual
    • Iterator::next - Avanza al siguiente elemento
    • Iterator::rewind - Rebobine la Iterator al primer elemento
    • Iterator::valid - Comprueba si la posición actual es válido
    • IteratorAggregate::getIterator - Recuperar un Iterator externo
    • IteratorIterator::current - Obtener el valor actual
    • IteratorIterator::getInnerIterator - Obtener el iterador interno
    • IteratorIterator::key - Obtener la clave del elemento actual
    • IteratorIterator::next - Avanzar al siguiente elemento
    • IteratorIterator::rewind - Rebobinar al primer elemento
    • IteratorIterator::valid - Comprobar si el iterador es válido
    • IteratorIterator::__construct - Crear un iterador de cualquier cosa que se pueda recorrer
    • iterator_apply - Llamar a una función para cada elemento de un iterador
    • iterator_count - Contar los elementos de un iterador
    • iterator_to_array - Copiar el iterador a un array
  • j
    • jddayofweek - Devuelve el día de la semana
    • jdmonthname - Devuelve el nombre de un mes
    • jdtofrench - Convierte una Fecha Juliana al Calendario Republicano Francés
    • jdtogregorian - Convierte una Fecha Juliana en una fecha Gregoriana
    • jdtojewish - Convierte una Fecha Juliana a una fecha del Calendario Judío
    • jdtojulian - Convierte una Fecha Juliana a una fecha del Calendario Juliano
    • jdtounix - Convierte una Fecha Juliana a una fecha Unix
    • jewishtojd - Convierte una fecha del Calendario Judío a una Fecha Juliana
    • join - Alias de implode
    • jpeg2wbmp - Convertir un archiov de imagen JPEG a un archivo de imagen WBMP
    • JsonSerializable::jsonSerialize - Especifica los datos que deberían serializarse para JSON
    • json_decode - Decodifica un string de JSON
    • json_encode - Retorna la representación JSON del valor dado
    • json_last_error - Devuelve el último error ocurrido
    • json_last_error_msg - Devuelve el string con el error de la última llamada a json_encode() o a json_decode()
    • juliantojd - Convierte una fecha del Calendario Juliano a una Fecha Juliana
  • k
    • key - Obtiene una clave de un array
    • key_exists - Alias de array_key_exists
    • krsort - Ordena un array por clave en orden inverso
    • ksort - Ordena un array por clave
  • l
    • lcfirst - Pasa a minúscula el primer caracter de un string
    • lcg_value - Generador lineal congruente combinado
    • lchgrp - Cambia el grupo de un enlace simbólico
    • lchown - Cambia el propietario de un enlace simbólico
    • ldap_8859_to_t61 - Traducir caracteres 8859 a caracteres t61
    • ldap_add - Agregar entradas al directorio de LDAP
    • ldap_add_ext - Add entries to LDAP directory
    • ldap_bind - Realiza la autenticación con un servidor LDAP
    • ldap_bind_ext - Bind to LDAP directory
    • ldap_close - Alias de ldap_unbind
    • ldap_compare - Comparar el valor del atributo encontrado en la entrada que se especificó con un DN
    • ldap_connect - Abre una conexión a un servidor LDAP
    • ldap_control_paged_result - Enviar el control de paginación LDAP
    • ldap_control_paged_result_response - Recuperar la cookie de paginación LDAP
    • ldap_count_entries - Contar el número de entradas en una búsqueda
    • ldap_delete - Eliminar una entrada de un directorio
    • ldap_delete_ext - Delete an entry from a directory
    • ldap_dn2ufn - Convertir un DN a un formato de nombramiento amigable al usuario
    • ldap_err2str - Convertir un número de error de LDAP a una cadena con un mensaje de error
    • ldap_errno - Devuelve el número de error LDAP del último comando LDAP
    • ldap_error - Devuelve el mensaje de error de LDAP del último comando LDAP
    • ldap_escape - Escapa una cadena de texto para su uso en un filtro LDAP o DN
    • ldap_exop - Performs an extended operation
    • ldap_exop_passwd - PASSWD extended operation helper
    • ldap_exop_refresh - Refresh extended operation helper
    • ldap_exop_whoami - WHOAMI extended operation helper
    • ldap_explode_dn - Divide un DN en sus partes componentes
    • ldap_first_attribute - Devolver el primer atributo
    • ldap_first_entry - Devolver el primer resultado de identificación
    • ldap_first_reference - Devolver la primera referencia
    • ldap_free_result - Liberar la memoria de resultado
    • ldap_get_attributes - Obtener atributos de una entrada de búsqueda de resultados
    • ldap_get_dn - Get the DN of a result entry
    • ldap_get_entries - Obtener todas las entradas de los resultados
    • ldap_get_option - Obtener el valor actual para la opción dada
    • ldap_get_values - Obtener todos los valores de una entrada de resultados
    • ldap_get_values_len - Obtener todos los valores binarios desde una entrada de resultados
    • ldap_list - Búsqueda de un solo nivel
    • ldap_modify - Modificar una entrada de LDAP
    • ldap_modify_batch - Batch and execute modifications on an LDAP entry
    • ldap_mod_add - Agregar valores de atributo a los atributos actuales
    • ldap_mod_add_ext - Add attribute values to current attributes
    • ldap_mod_del - Borrar valores de atributo de los atributos actuales
    • ldap_mod_del_ext - Delete attribute values from current attributes
    • ldap_mod_replace - Reemplazar valores de atributos con valores nuevos
    • ldap_mod_replace_ext - Replace attribute values with new ones
    • ldap_next_attribute - Obtener el siguiente atributo en un resultado
    • ldap_next_entry - Obtener el siguiente resultado de entrada
    • ldap_next_reference - Obtener la siguiente referencia
    • ldap_parse_exop - Parse result object from an LDAP extended operation
    • ldap_parse_reference - Extraer información de la entrada de referencia
    • ldap_parse_result - Extraer información del resultado
    • ldap_read - Leer una entrada
    • ldap_rename - Modificar el nombre de una entrada
    • ldap_rename_ext - Modify the name of an entry
    • ldap_sasl_bind - Unirse a un directorio LDAP utilizando SASL
    • ldap_search - Buscar el árbol LDAP
    • ldap_set_option - Establecer el valor de la opción proporcionada
    • ldap_set_rebind_proc - Establece una función de devolución de llamada para realizar revinculaciones en el rastreo referencial
    • ldap_sort - Clasificar entradas de resultados de LDAP en el lado del cliente
    • ldap_start_tls - Inciar TLS
    • ldap_t61_to_8859 - Traduce del conjunto de caracteres t61 al conjunto de caracteres 8859
    • ldap_unbind - Desenlazar de directorio LDAP
    • levenshtein - Cálculo de la distancia Levenshtein entre dos strings
    • libxml_clear_errors - Limpia el buffer de errores de libxml
    • libxml_disable_entity_loader - Deshabilita la capacidad de cargar entidades externas
    • libxml_get_errors - Recupera un array de errores
    • libxml_get_last_error - Recupera el último error de libxml
    • libxml_set_external_entity_loader - Cambia el cargador externo por defecto de entidades
    • libxml_set_streams_context - Configura el contexto de flujo para el próximo documento libxml cargado o escrito
    • libxml_use_internal_errors - Deshabilita errores libxml y permite al usuario extraer información de errores según sea necesario
    • LimitIterator::current - Obtiene el elemento actual
    • LimitIterator::getInnerIterator - Obtiene el iterador interno
    • LimitIterator::getPosition - Devuelve la posición actual
    • LimitIterator::key - Obtiene la clave actual
    • LimitIterator::next - Mueve el iterador a la siguiente posición
    • LimitIterator::rewind - Rebobina el iterador a un punto específicado
    • LimitIterator::seek - Mueve el apuntador interno a la posición dada
    • LimitIterator::valid - Comprobar si el elemento actual es válido
    • LimitIterator::__construct - Construye un LimitIterator
    • link - Crea un enlace duro
    • linkinfo - Obtiene información acerca de un enlace
    • list - Asignar variables como si fueran un array
    • Locale::acceptFromHttp - Intentar encontrar la mejor configuración regional basada en la cabecera "Accept-Language" de HTTP
    • Locale::canonicalize - Canonizar el string de configuración regional
    • Locale::composeLocale - Devolver un ID regional correctamente ordenado y delimitado
    • Locale::filterMatches - Comprobar si unfiltro de etiquetas de lenguaje coincide con una configuración regional
    • Locale::getAllVariants - Obtener las variantes de la configuración regional de entrada
    • Locale::getDefault - Obtener el valor de la configuración regional predeterminada del identificador global 'default_locale' de INTL
    • Locale::getDisplayLanguage - Devolver un nombre manifiesto debidamente localizado del lenguaje de la configuración regional de entrada
    • Locale::getDisplayName - Devolver un nombre manifiesto debidamente localizado de la configuración regional de entrada
    • Locale::getDisplayRegion - Devolver un nombre manifiesto debidamente localizado de la región de la configuración regional de entrada
    • Locale::getDisplayScript - Devolver un nombre manifiesto debidamente localizado de la escritura de la configuración regional de entrada
    • Locale::getDisplayVariant - Devolver un nombre manifiesto debidamente localizado de las variantes de la configuración regional de entrada
    • Locale::getKeywords - Obtener las palabras clave de la configuración regional de entrada
    • Locale::getPrimaryLanguage - Obtener el lenguaje principal de la configuración regional de entrada
    • Locale::getRegion - Obtener la región de la configuración local de entrada
    • Locale::getScript - Obtener la escritura de la configuración regional de entrada
    • Locale::lookup - Busca en la lista de etiquetas de lenguaje la mejor coincidencia para el lenguaje
    • Locale::parseLocale - Devolver un array de claves-valores de los elementos de las subetiquetas del ID regional
    • Locale::setDefault - Establecer la configuración regional predeterminada en tiempo de ejecución
    • localeconv - Obtener información sobre el formato numérico
    • localtime - Obtiene fecha y hora local
    • log - Logaritmo natural
    • log1p - Devuelve log(1 + numero), calculado de tal forma que no pierde precisión incluso cuando el valor del numero se aproxima a cero.
    • log10 - Logaritmo en base 10
    • log_cmd_delete - Función de retrollamada al borrar documentos
    • log_cmd_insert - Función de retrollamada al insertar documentos
    • log_cmd_update - Función de retrollamada al actualizar documentos
    • log_getmore - Función de retrollamada al obtener el próximo lote del cursor
    • log_killcursor - Función de retrollamada al ejecutar operaciones KILLCURSOR
    • log_reply - Función de retrollamada al leer una réplica de MongoDB
    • log_write_batch - Función de retrollamada al escribir lotes
    • long2ip - Convierte una dirección de red (IPv4) en una cadena de texto en formato con puntos estándar de internet
    • lstat - Da información acerca de un archivo o enlace simbólico
    • ltrim - Retira espacios en blanco (u otros caracteres) del inicio de un string
    • Lua::assign - Asigna una variable de PHP a Lua
    • Lua::call - Llama funciones de Lua
    • Lua::eval - Evalúa una cadena de texto como código Lua
    • Lua::getVersion - Obtiene la versión
    • Lua::include - Analiza un fichero script Lua
    • Lua::registerCallback - Registra una función PHP en Lua
    • Lua::__construct - Constructor de Lua
    • LuaClosure::__invoke - Invoke luaclosure
    • LuaSandbox::callFunction - Call a function in a Lua global variable
    • LuaSandbox::disableProfiler - Disable the profiler
    • LuaSandbox::enableProfiler - Enable the profiler.
    • LuaSandbox::getCPUUsage - Fetch the current CPU time usage of the Lua environment
    • LuaSandbox::getMemoryUsage - Fetch the current memory usage of the Lua environment
    • LuaSandbox::getPeakMemoryUsage - Fetch the peak memory usage of the Lua environment
    • LuaSandbox::getProfilerFunctionReport - Fetch profiler data
    • LuaSandbox::getVersionInfo - Return the versions of LuaSandbox and Lua
    • LuaSandbox::loadBinary - Load a precompiled binary chunk into the Lua environment
    • LuaSandbox::loadString - Load Lua code into the Lua environment
    • LuaSandbox::pauseUsageTimer - Pause the CPU usage timer
    • LuaSandbox::registerLibrary - Register a set of PHP functions as a Lua library
    • LuaSandbox::setCPULimit - Set the CPU time limit for the Lua environment
    • LuaSandbox::setMemoryLimit - Set the memory limit for the Lua environment
    • LuaSandbox::unpauseUsageTimer - Unpause the timer paused by LuaSandbox::pauseUsageTimer
    • LuaSandbox::wrapPhpFunction - Wrap a PHP callable in a LuaSandboxFunction
    • LuaSandboxFunction::call - Call a Lua function
    • LuaSandboxFunction::dump - Dump the function as a binary blob
    • LuaSandboxFunction::__construct - Unused
    • lzf_compress - Compresión LZF
    • lzf_decompress - Descompresión LZF
    • lzf_optimized_for - Determina para qué fue optimizada la extensión LZF
  • m
    • mail - Enviar correo
    • mailparse_determine_best_xfer_encoding - Obtiene la mejor forma de codificar
    • mailparse_msg_create - Crea un recurso de correo mime
    • mailparse_msg_extract_part - Extrae/decodifica una sección de mensaje
    • mailparse_msg_extract_part_file - Extrae/decodifica una sección de mensaje
    • mailparse_msg_extract_whole_part_file - Extrae una sección del mensaje incluyendo cabeceras sin descodificar la transferencia codificada
    • mailparse_msg_free - Libera un recurso MIME
    • mailparse_msg_get_part - Devuelve un gestor sobre una sección dada en un mensaje mime
    • mailparse_msg_get_part_data - Devuelve una matriz asociativa de información sobre el mensaje
    • mailparse_msg_get_structure - Devuelve una matriz de nombres de sección mime en el mensaje dado
    • mailparse_msg_parse - Procesar datos incrementalmente sobre un búfer
    • mailparse_msg_parse_file - Procesa un archivo
    • mailparse_rfc822_parse_addresses - Procesa direcciones compatibles con RFC 822
    • mailparse_stream_encode - Secuencia datos desde un apuntador de archivo, codifica y escribe a fp_destino
    • mailparse_uudecode_all - Procesa los datos desde un apuntador a archivo y extrae cada archivo embebido con codificación uu
    • main - Función main falsa
    • max - Encontrar el valor más alto
    • mb_check_encoding - Comprueba si el string es válido para a la codificación especificada
    • mb_chr - Get a specific character
    • mb_convert_case - Realiza una conversión a mayúsculas/minúsculas de un string
    • mb_convert_encoding - Convierte una codificación de caracteres
    • mb_convert_kana - Convierte un "kana" a otro ("zen-kaku", "han-kaku" y más)
    • mb_convert_variables - Convierte códigos de caracteres a variable/s
    • mb_decode_mimeheader - Decodifica un string en el campo de cabecera MIME
    • mb_decode_numericentity - Decodifica referencias a string numéricas de HTML en caracteres
    • mb_detect_encoding - Detecta la codificación de caracteres
    • mb_detect_order - Establece/obtiene el orden de detección de codificaciones de caracteres
    • mb_encode_mimeheader - Codifica un string para la cabecera MIME
    • mb_encode_numericentity - Convierte caracteres a referencias de string numéricas de HTML
    • mb_encoding_aliases - Obtiene los alias de un tipo de codificación conocido
    • mb_ereg - Comparación de expresiones regulares con soporte multibyte
    • mb_eregi - Comparación de expresiones regulares ignorando mayúsculas/minúsculas con soporte multibyte
    • mb_eregi_replace - Reemplaza una expresión regular con soporte multibyte ignorando mayúsculas/minúsculas
    • mb_ereg_match - Compararción de expresiones regulares para strings multibyte
    • mb_ereg_replace - Reemplaza una expresión regular con soporte multibyte
    • mb_ereg_replace_callback - Realiza una búsqueda y sustitución de una expresión regular con soporte multibyte usando una llamada de retorno
    • mb_ereg_search - Comparación de expresiones regulares multibyte para un string multibyte predefinido
    • mb_ereg_search_getpos - Devuelve la posición de inicio para la siguiente comparación de una expresión regular
    • mb_ereg_search_getregs - Recupera el resultado de la última comparación de expresión regular multibyte
    • mb_ereg_search_init - Configura el string y la expresión regular para una comparación de expresiones regulares multibyte
    • mb_ereg_search_pos - Devuelve la posición y la longitud de una parte coincidente de la expresión regular multibyte para un string multibyte predefinido
    • mb_ereg_search_regs - Devuelve la parte coincidente de una expresión regular multibyte
    • mb_ereg_search_setpos - Establece el punto de inicio de la siguiente comparación de una expresión regular
    • mb_get_info - Obtiene la configuración interna de mbstring
    • mb_http_input - Detecta la codificación de caracteres de entrada HTTP
    • mb_http_output - Establece/obtiene la codificación de caracteres de salida HTTP
    • mb_internal_encoding - Establece/obtiene la codificación de caracteres interna
    • mb_language - Establece/obtiene el idioma actual
    • mb_list_encodings - Devuelve un array con todos los tipos de codificaciones admitidas
    • mb_ord - Get code point of character
    • mb_output_handler - Función de llamada de retorno que convierte la codificación de caracteres en búfer de salida
    • mb_parse_str - Analiza datos GET/POST/COOKIE y establece varialbes globales
    • mb_preferred_mime_name - Obtener un string del conjunto de caracteres del MIME
    • mb_regex_encoding - Establecer/obtener la codificación de caracteres para expresiones regulares multibyte
    • mb_regex_set_options - Establece/obtiene las opciones predeterminadas para las funciones mbregex
    • mb_scrub - Description
    • mb_send_mail - Envía un correo codificado
    • mb_split - Divide cadenas de caracteres multibyte usando una expresión regular
    • mb_strcut - Obtener parte de un string
    • mb_strimwidth - Obtiene un string truncado con el ancho especificado
    • mb_stripos - Busca la posición de la primera ocurrencia de un string dentro de otro, insensible a mayúsculas/minúsculas
    • mb_stristr - Busca la primera ocurrencia de un string dentro de otro, insensible a mayúsculas/minúsculas
    • mb_strlen - Obtiene la longitud de una cadena de caracteres
    • mb_strpos - Busca la posición de la primera ocurrencia de un string en otro string
    • mb_strrchr - Busca la última ocurrencia de un carácter de un string dentro de otro
    • mb_strrichr - Busca la última ocurrencia de un carácter de un string dentro de otro, insensible a mayúsculas/minúsculas
    • mb_strripos - Busca la posicion de la última ocurrencia de un string dentro de otro string, insensible a mayúsculas/minúsculas
    • mb_strrpos - Busca la posicion de la última ocurrencia de un string en otro string
    • mb_strstr - Busca la primera ocurrencia de un string dentro de otro
    • mb_strtolower - Convierte una cadena de caracteres a minúsculas
    • mb_strtoupper - Convierte un string en mayúsculas
    • mb_strwidth - Devuelve el ancho de un string
    • mb_str_split - Given a multibyte string, return an array of its characters
    • mb_substitute_character - Establece/obtiene un carácter de sustitución
    • mb_substr - Obtiene parte de una cadena de caracteres
    • mb_substr_count - Cuenta el número de ocurrencias de un substring
    • mcrypt_cbc - Encripta/decripta datos en modo CBC
    • mcrypt_cfb - Encripta/decripta datos en modo CFB
    • mcrypt_create_iv - Crea un vector de inicialización (IV) desde una fuente aleatoria
    • mcrypt_decrypt - Desencripta texto cifrado con los parámetros dados
    • mcrypt_ecb - Obsoleto: Encripta/decripta datos en modo ECB
    • mcrypt_encrypt - Cifra texto plano con los parámetros dados
    • mcrypt_enc_get_algorithms_name - Devuelve el nombre del algoritmo abierto
    • mcrypt_enc_get_block_size - Devuelve el tamaño del bloque del algoritmo abierto
    • mcrypt_enc_get_iv_size - Devuelve el tamaño del IV del algoritmo abierto
    • mcrypt_enc_get_key_size - Devuelve el tamaño de clave máximo soportado por el modo abierto
    • mcrypt_enc_get_modes_name - Devuelve el nombre del modo abierto
    • mcrypt_enc_get_supported_key_sizes - Devuelve un array con los tamaños de clave soportados por el algoritmo abierto
    • mcrypt_enc_is_block_algorithm - Chequea si el algoritmo del modo abierto es un algoritmo por bloques
    • mcrypt_enc_is_block_algorithm_mode - Chequea si el cifrado del modo abierto trabaja sobre bloques
    • mcrypt_enc_is_block_mode - Chequea si el modo abierto retorna bloques
    • mcrypt_enc_self_test - Ejecuta una prueba automática sobre el módulo abierto
    • mcrypt_generic - Esta función encripta datos
    • mcrypt_generic_deinit - Esta función deinicializa un módulo de cifrado
    • mcrypt_generic_end - Esta función termina el cifrado
    • mcrypt_generic_init - Esta función inicializa todos los buffers requeridos para el cifrado
    • mcrypt_get_block_size - Toma el tamaño del bloque del cifrador especificado
    • mcrypt_get_cipher_name - Toma el nombre del cifrador especificado
    • mcrypt_get_iv_size - Devuelve el tamaño del IV perteneciente a una combinación cifrador/modo específica
    • mcrypt_get_key_size - Toma el tamaño de clave del cifrador especificado
    • mcrypt_list_algorithms - Obtiene un array con todos los cifradores soportados
    • mcrypt_list_modes - Obtiene un array con todos los modos soportados
    • mcrypt_module_close - Cierra el módulo mcrypt
    • mcrypt_module_get_algo_block_size - Devuelve el tamaño de bloque del algoritmo especificado
    • mcrypt_module_get_algo_key_size - Devuelve el tamaño de clave máximo soportado por el modo abierto
    • mcrypt_module_get_supported_key_sizes - Devuelve un array con los tamaños de clave soportados del algoritmo abierto
    • mcrypt_module_is_block_algorithm - Esta función chequea si el algoritmo especificado es un algoritmo por bloques
    • mcrypt_module_is_block_algorithm_mode - Devuelve si el módulo especificado es un algoritmo por bloques o no
    • mcrypt_module_is_block_mode - Devuelve si el modo especificado retorna bloques o no
    • mcrypt_module_open - Abre el módulo del algoritmo y el modo a ser utilizados
    • mcrypt_module_self_test - Esta función ejecuta una prueba automática sobre el módulo especificado
    • mcrypt_ofb - Encripta/desencripta datos en modo OFB
    • md5 - Calcula el 'hash' md5 de un string
    • md5_file - Calcula el resumen criptográfico md5 de un archivo dado
    • mdecrypt_generic - Desencripta datos
    • Memcache::add - Añadir un valor en el servidor
    • Memcache::addServer - Añadir servidor memcache al grupo de conexiones
    • Memcache::close - Cierra la conexión al servidor memcached
    • Memcache::connect - Abre una conexión al servidor memcached
    • Memcache::decrement - Decrementa numéricamente un valor
    • Memcache::delete - Elimina un valor del servidor
    • Memcache::flush - Limpia todos los valores existentes en el servidor
    • Memcache::get - Obtener valor del servidor
    • Memcache::getExtendedStats - Obtener estadísticas de todos los servidores en el grupo
    • Memcache::getServerStatus - Devuelve el estado del servidor
    • Memcache::getStats - Obtiene estadísticas del servidor
    • Memcache::getVersion - Devuelve la versión del servidor
    • Memcache::increment - Incrementa numéricamente un valor
    • Memcache::pconnect - Abre una conexión persistente a memcached
    • Memcache::replace - Reemplaza el valor de un valor existente
    • Memcache::set - Guarda datos en el servidor
    • Memcache::setCompressThreshold - Activa compresión automática de valores con datos largos
    • Memcache::setServerParams - Cambia parámetros del servidor y estado en tiempo de ejecucción
    • Memcached::add - Añade un ítem asociado a una nueva clave
    • Memcached::addByKey - Añade un ítem asociado a una nueva clave en un servidor específico
    • Memcached::addServer - Añade un servidor a la provisión de servidores
    • Memcached::addServers - Añadir varios servidores a la agrupación de servidores
    • Memcached::append - Añadir datos a un ítem existente
    • Memcached::appendByKey - Añadir datos a un ítem existente en un servidor específico
    • Memcached::cas - Comparar e intercambiar un ítem
    • Memcached::casByKey - Comparar e intercambiar un ítem en un servidor específico
    • Memcached::decrement - Decrementar un valor numérico de un ítem
    • Memcached::decrementByKey - Decrementar un valor numérico de un ítem almacenado en un servidor específico
    • Memcached::delete - Eliminar un ítem
    • Memcached::deleteByKey - Eliminar un ítem de un servidor específico
    • Memcached::deleteMulti - Eliminar varios ítems
    • Memcached::deleteMultiByKey - Eliminar varios ítems de un servidor específico
    • Memcached::fetch - Obtener el siguiente resultado
    • Memcached::fetchAll - Obtener todos los resultados restantes
    • Memcached::flush - Invalidar todos los ítems de la caché
    • Memcached::get - Obtener un ítem
    • Memcached::getAllKeys - Obtiene las claves almacenadas en todos los servidores
    • Memcached::getByKey - Obtiene un ítem de un servidor específico
    • Memcached::getDelayed - Obtener varios ítems
    • Memcached::getDelayedByKey - Solicitar varios ítems de un servidor específico
    • Memcached::getMulti - Obtener varios ítems
    • Memcached::getMultiByKey - Recuperar varios ítems de un servidor específico
    • Memcached::getOption - Obtener el valor de una opción de Memcached
    • Memcached::getResultCode - Devuelve el código resultante de la última operación
    • Memcached::getResultMessage - Devolver un mensaje que describe el resultado de la última operación
    • Memcached::getServerByKey - Hacer corresponder una clave con un servidor
    • Memcached::getServerList - Obtener la lista de servidores de la agrupación
    • Memcached::getStats - Obtener las estadísticas de la agrupación de servidores
    • Memcached::getVersion - Obtener la información de la versión de la agrupación de servidores
    • Memcached::increment - Incrementar un valor numérico de un ítem
    • Memcached::incrementByKey - Incrementar un valor numérico de un ítem, almacenado en un servidor específico
    • Memcached::isPersistent - Comprueba si se está utilizando una conexión persistente a memcache
    • Memcached::isPristine - Comprobar si la instancia se creó recientemente
    • Memcached::prepend - Anteponer datos a un ítem existente
    • Memcached::prependByKey - Anteponer datos a un ítem existente en un servidor específico
    • Memcached::quit - Cierra cualquier conexión abierta
    • Memcached::replace - Reemplaza un ítem asociado a una clave existente
    • Memcached::replaceByKey - Reemplazar un ítem bajo una clave existente en un servidor específico
    • Memcached::resetServerList - Limpia todos los servidores de la lista de servidores
    • Memcached::set - Guardar un ítem
    • Memcached::setByKey - Guardar un ítem en un servidor específico
    • Memcached::setMulti - Almacenar varios ítems
    • Memcached::setMultiByKey - Almacena varios ítems en un servidor específico
    • Memcached::setOption - Establecer una opción de Memcached
    • Memcached::setOptions - Establecer opciones de Memcached
    • Memcached::setSaslAuthData - Establecer las credenciales para la autenticación
    • Memcached::touch - Establecer una nueva expiración para un ítem
    • Memcached::touchByKey - Establecer una nueva expiración para un ítem de un servidor específico
    • Memcached::__construct - Crear una instancia de Memcached
    • memcache_debug - Activa/desactiva debug output
    • memory_get_peak_usage - Devuelve el máximo de memoria asignada por PHP
    • memory_get_usage - Devuelve la cantidad de memoria asignada a PHP
    • MessageFormatter::create - Construir un nuevo Formateador de Mensajes
    • MessageFormatter::format - Dar formato al mensaje
    • MessageFormatter::formatMessage - Formateo rápido de un mensaje
    • MessageFormatter::getErrorCode - Obtener el código de error de la última operación
    • MessageFormatter::getErrorMessage - Obtener el texto del error de la última operación
    • MessageFormatter::getLocale - Obtener la configuración regional desde la que se creó el formateador
    • MessageFormatter::getPattern - Obtener el patrón usado por el formateador
    • MessageFormatter::parse - Procesar la cadena de entrada según un patrón
    • MessageFormatter::parseMessage - Procesar rápidamente una cadena de entrada
    • MessageFormatter::setPattern - Establecer el patrón usado por el formateador
    • metaphone - Calcula la clave metaphone de un string
    • method_exists - Comprueba si existe un método de una clase
    • mhash - Calcula el hash
    • mhash_count - Toma el mayor ID de hash disponible
    • mhash_get_block_size - Toma el tamaño de bloque del algoritmo hash especificado
    • mhash_get_hash_name - Toma el nombre del algoritmo hash especificado
    • mhash_keygen_s2k - Genera una clave
    • microtime - Devuelve la fecha Unix actual con microsegundos
    • mime_content_type - Detecta el MIME Content-type para un fichero
    • min - Encontrar el valor más bajo
    • mkdir - Crea un directorio
    • mktime - Obtener la marca de tiempo Unix de una fecha
    • money_format - Da formato a un número como un string de moneda
    • Mongo::connectUtil - Conecta con un servidor de bases de datos
    • Mongo::getPoolSize - Obtener el tamaño de las agrupaciones de conexiones
    • Mongo::getSlave - Devuelve la dirección usada por las lecturas de slaveOkay
    • Mongo::getSlaveOkay - Obtiene el valor de slaveOkay de esta conexión
    • Mongo::poolDebug - Devuelve información sobre todas las agrupaciones de conexiones
    • Mongo::setPoolSize - Establecer el tamaño para futuras agrupaciones de conexiones
    • Mongo::setSlaveOkay - Cambia el valor de slaveOkay para esta conexión
    • Mongo::switchSlave - Elije un nuevo secundario para lecturas slaveOkay
    • Mongo::__construct - El propósito de __construct
    • MongoBinData::__construct - Crea un nuevo objeto de datos binarios
    • MongoBinData::__toString - Representación en forma de string de este objeto de datos binarios
    • MongoClient::close - Cierra esta conexión
    • MongoClient::connect - Conecta a un servidor de bases de datos
    • MongoClient::dropDB - Elimina una base de datos [obsoleto]
    • MongoClient::getConnections - Devuelve información sobre todas las conexiones abiertas
    • MongoClient::getHosts - Actualiza el estado de todos los hosts asociados
    • MongoClient::getReadPreference - Obtener la preferencia de lectura para esta conexión
    • MongoClient::getWriteConcern - Obteenr el asunto de escritura para esta conexión
    • MongoClient::killCursor - Elimina un cursor específico del servidor
    • MongoClient::listDBs - Enumera todas las bases de datos disponibles
    • MongoClient::selectCollection - Obtiene una colección de bases de datos
    • MongoClient::selectDB - Obtiene una base de datos
    • MongoClient::setReadPreference - Establece la preferencia de lectura para esta conexión
    • MongoClient::setWriteConcern - Establecer el asunto de escritura para esta conexión
    • MongoClient::__construct - Crea un nuevo objeto de conexión a base de datos
    • MongoClient::__get - Obtiene una base de datos
    • MongoClient::__toString - Representación de cadena de esta conexión
    • MongoCode::__construct - Crea un nuevo objeto de código
    • MongoCode::__toString - Devuelve este código en forma de texto
    • MongoCollection::aggregate - Realiza una acumulación usando el framework de acumulación
    • MongoCollection::aggregateCursor - Ejecutar un comando de tubería acumulador y recuperar los resultados mediante un cursor
    • MongoCollection::batchInsert - Inserta múltiples documentos en esta colección
    • MongoCollection::count - Cuenta el número de documentos de esta colección
    • MongoCollection::createDBRef - Crea una referencia a una base de datos
    • MongoCollection::createIndex - Crea un índice en el campo o campos especificados, si aún no existen
    • MongoCollection::deleteIndex - Elimina un índice de esta colección
    • MongoCollection::deleteIndexes - Elimina todos los índices de esta colección
    • MongoCollection::distinct - Recupera una lista de valores distintos para una clave dada a través de una colección
    • MongoCollection::drop - Borra esta colección
    • MongoCollection::ensureIndex - Crea un índice en el campo o campos especificados, si aún no existen
    • MongoCollection::find - Consulta esta colección, devolviendo un objeto MongoCursor para el conjunto de resultados
    • MongoCollection::findAndModify - Actualizar un documento y devolverlo
    • MongoCollection::findOne - Realiza una consulta a esta colección, devolviendo sólo un elemento
    • MongoCollection::getDBRef - Captura el documento al que apunta una referencia de base de datos
    • MongoCollection::getIndexInfo - Devuelve información sobre los índices de esta colección
    • MongoCollection::getName - Devuelve el nombre de esta colección
    • MongoCollection::getReadPreference - Obtener la preferencia de lectura psrs esta colección
    • MongoCollection::getSlaveOkay - Consulta el valor de slaveOkay de esta colección
    • MongoCollection::getWriteConcern - Obtener el asunto de escritura para esta colección
    • MongoCollection::group - Lleva a cabo una operación similar al comando GROUP BY de SQL
    • MongoCollection::insert - Inserta un documento en la colección
    • MongoCollection::parallelCollectionScan - Devuelve un array con cursores para recorrer una colección completa en paralelo
    • MongoCollection::remove - Eliminar registros de esta colección
    • MongoCollection::save - Guarda un documento en esta colección
    • MongoCollection::setReadPreference - Establecer la preferencia de lectura para esta colección
    • MongoCollection::setSlaveOkay - Cambia el valor de slaveOkay de esta colección
    • MongoCollection::setWriteConcern - Establecer el asunto de escritura para esta base de datos
    • MongoCollection::toIndexString - Convierte claves especificando un índice para su string de identificación
    • MongoCollection::update - Actualizar registros basándose en los criterios proporcionados
    • MongoCollection::validate - Valida esta colección
    • MongoCollection::__construct - Crea una nueva colección
    • MongoCollection::__get - Obtiene una colección
    • MongoCollection::__toString - Representación en forma de string de esta colección
    • MongoCommandCursor::batchSize - Limita el número de elementos devueltos en un lote
    • MongoCommandCursor::createFromDocument - Crear un nuevo cursor de comando desde un documento de cursor existente
    • MongoCommandCursor::current - Devuelve el elemento actual
    • MongoCommandCursor::dead - Comprueba si hay resultados que aún no han sido enviados desde la base de datos
    • MongoCommandCursor::getReadPreference - Obtener la preferencia de lectura para este comando
    • MongoCommandCursor::info - Obtiene información sobre la creación e iteración del cursor
    • MongoCommandCursor::key - Devuelve el _id del resultado acutal
    • MongoCommandCursor::next - Avanza el cursor al siguiente resultado
    • MongoCommandCursor::rewind - Ejecuta el comando y reinicia el cursor al comienzo del conjunto de resultados
    • MongoCommandCursor::setReadPreference - Establecer la preferencia de lectura para este comando
    • MongoCommandCursor::timeout - Establece el tiempo de espera del lado del cliente para este comando
    • MongoCommandCursor::valid - Comprueba si el cursor está leyendo un resultado válido
    • MongoCommandCursor::__construct - Crear un nuevo cursor de comando
    • MongoCursor::addOption - Añade un par clave/valor de alto nivel a una consulta
    • MongoCursor::awaitData - Establece si el cursor esperará un momento a que un cursor de seguimiento devuelva más datos
    • MongoCursor::batchSize - Limita el número de elementos devueltos en un lote
    • MongoCursor::count - Cuenta el número de resultados de esta consulta
    • MongoCursor::current - Devuelve el elemento actual
    • MongoCursor::dead - Comprueba si hay resultados que no han sido enviados aún de la base de datos
    • MongoCursor::doQuery - Ejecutar un sentencia
    • MongoCursor::explain - Devuelve una explicación de la consulta, útil para la optimización y depuración
    • MongoCursor::fields - Establece los campos para una consulta
    • MongoCursor::getNext - Avanza el cursor al siguiente resultado y devuelve dicho resultado
    • MongoCursor::getReadPreference - Obtener la preferencia de lectura para esta consulta
    • MongoCursor::hasNext - Comprueba si existe algún elemento más en este cursor
    • MongoCursor::hint - Da a la base de datos un indicio sobre la consulta
    • MongoCursor::immortal - Establece si este cursor expirará
    • MongoCursor::info - Obtiene la información sobre la creación e iteración del cursor
    • MongoCursor::key - Devuelve el _id del resultado actual, o su índice dentro del conjunto de resultados
    • MongoCursor::limit - Limita el número de resultados devueltos
    • MongoCursor::maxTimeMS - Establece un tiempo límite en el lado del cliente para esta consulta
    • MongoCursor::next - Avanza el cursor al siguiente resultado, y devuelve dicho resultado
    • MongoCursor::partial - Si esta consulta debería obtener resultados parciales de mongos si un trozo ha caído
    • MongoCursor::reset - Limpia el cursor
    • MongoCursor::rewind - Devuelve el cursor al inicio del conjunto de resultados
    • MongoCursor::setFlag - Establece banderas arbitrarias en caso de que no haya métodos disponibles para una bandera específica
    • MongoCursor::setReadPreference - Establece la preferencia de lectura para esta consulta
    • MongoCursor::skip - Omite un número de resultados
    • MongoCursor::slaveOkay - Establece si esta consulta puede realizarse en un secundario [obsoleto]
    • MongoCursor::snapshot - Usar el modo 'snapshot' para la consulta
    • MongoCursor::sort - Ordena los resultados por el campo que se indique
    • MongoCursor::tailable - Establece si este cursor se dejará abierto después de obtener los últimos resultados
    • MongoCursor::timeout - Establece un tiempo de espera en el lado del cliente para esta consulta
    • MongoCursor::valid - Comprueba si el cursor está leyendo un resultado válido
    • MongoCursor::__construct - Crea un nuevo cursor
    • MongoCursorException::getHost - El nombre de host del servidor que encontró el error
    • MongoCursorInterface::batchSize - Limita el número de elementos devueltos en un lote
    • MongoCursorInterface::dead - Comprueba si existen resultados que aún no han sido enviados desde la base de datos
    • MongoCursorInterface::getReadPreference - Obtener la preferencia de lectura para esta consulta
    • MongoCursorInterface::info - Obtiene información sobre la creación e iteración del cursor
    • MongoCursorInterface::setReadPreference - Establecer la preferencia de lectura para esta consulta
    • MongoCursorInterface::timeout - Establece un tiempo de espera en el lado del cliente para esta consulta
    • MongoDate::toDateTime - Devuelve un objeto DateTime que representa esta fecha
    • MongoDate::__construct - Crea una nueva fecha
    • MongoDate::__toString - Devuelve una representación en forma de texto de esta fecha
    • MongoDB::authenticate - Iniciar sesión en esta base de datos
    • MongoDB::command - Ejecuta una orden de base de datos
    • MongoDB::createCollection - Crea una colección
    • MongoDB::createDBRef - Crea una referencia a base de datos
    • MongoDB::drop - Borra esta base de datos
    • MongoDB::dropCollection - Borra una colección [obsoleto]
    • MongoDB::execute - Ejecuta código JavaScript en el servidor de bases de datos [obsoleto]
    • MongoDB::forceError - Crea un error de base de datos
    • MongoDB::getCollectionInfo - Devuelve información sobre las colecciones de esta base de datos
    • MongoDB::getCollectionNames - Obtiene un array con los nombres de todas las colecciones de esta base de datos
    • MongoDB::getDBRef - Captura el documento que está siendo apuntado por una referencia de base de datos
    • MongoDB::getGridFS - Obtiene un objeto para trabajar con ficheros almacenados en esta base de datos
    • MongoDB::getProfilingLevel - Obtiene el nivel de perfilado (profiling) de la base de datos
    • MongoDB::getReadPreference - Obtener la preferencia de lectura para esta base de datos
    • MongoDB::getSlaveOkay - Devuelve el valor de slaveOkay de esta base de datos
    • MongoDB::getWriteConcern - Obtener el asunto de escritura para esta base de datos
    • MongoDB::lastError - Comprueba si hubo un error en la última operación de base de datos llevada a cabo
    • MongoDB::listCollections - Obtiene un array de objetos MongoCollection para todas las colecciones de esta base de datos
    • MongoDB::prevError - Comprueba el último error emitido durante una operación de base de datos
    • MongoDB::repair - Repara y compacta esta base de datos
    • MongoDB::resetError - Limpia cualquier error de la base de datos que se haya apuntado
    • MongoDB::selectCollection - Obtiene una colección
    • MongoDB::setProfilingLevel - Establece el nivel de perfilado (profiling) de la base de datos
    • MongoDB::setReadPreference - Establece la preferencia de lectura para esta base de datos
    • MongoDB::setSlaveOkay - Cambiar el valor de slaveOkay de esta base de datos
    • MongoDB::setWriteConcern - Establecer el asunto de escritura para esta base de datos
    • MongoDB::__construct - Crea una nueva base de datos
    • MongoDB::__get - Obtiene una colección
    • MongoDB::__toString - Nombre de esta base de datos
    • MongoDBRef::create - Crea una nueva referencia de base de datos
    • MongoDBRef::get - Captura el objeto al que apunta la referencia
    • MongoDBRef::isRef - Comprueba si un array es una referencia en la base de datos
    • MongoDB\BSON\Binary::getData - Returns the Binary's data
    • MongoDB\BSON\Binary::getType - Returns the Binary's type
    • MongoDB\BSON\Binary::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Binary::serialize - Serialize a Binary
    • MongoDB\BSON\Binary::unserialize - Unserialize a Binary
    • MongoDB\BSON\Binary::__construct - Construct a new Binary
    • MongoDB\BSON\Binary::__toString - Returns the Binary's data
    • MongoDB\BSON\BinaryInterface::getData - Returns the BinaryInterface's data
    • MongoDB\BSON\BinaryInterface::getType - Returns the BinaryInterface's type
    • MongoDB\BSON\BinaryInterface::__toString - Returns the BinaryInterface's data
    • MongoDB\BSON\Decimal128::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Decimal128::serialize - Serialize a Decimal128
    • MongoDB\BSON\Decimal128::unserialize - Unserialize a Decimal128
    • MongoDB\BSON\Decimal128::__construct - Construct a new Decimal128
    • MongoDB\BSON\Decimal128::__toString - Returns the string representation of this Decimal128
    • MongoDB\BSON\Decimal128Interface::__toString - Returns the string representation of this Decimal128Interface
    • MongoDB\BSON\fromJSON - Returns the BSON representation of a JSON value
    • MongoDB\BSON\fromPHP - Returns the BSON representation of a PHP value
    • MongoDB\BSON\Javascript::getCode - Returns the Javascript's code
    • MongoDB\BSON\Javascript::getScope - Returns the Javascript's scope document
    • MongoDB\BSON\Javascript::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Javascript::serialize - Serialize a Javascript
    • MongoDB\BSON\Javascript::unserialize - Unserialize a Javascript
    • MongoDB\BSON\Javascript::__construct - Construct a new Javascript
    • MongoDB\BSON\Javascript::__toString - Returns the Javascript's code
    • MongoDB\BSON\JavascriptInterface::getCode - Returns the JavascriptInterface's code
    • MongoDB\BSON\JavascriptInterface::getScope - Returns the JavascriptInterface's scope document
    • MongoDB\BSON\JavascriptInterface::__toString - Returns the JavascriptInterface's code
    • MongoDB\BSON\MaxKey::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\MaxKey::serialize - Serialize a MaxKey
    • MongoDB\BSON\MaxKey::unserialize - Unserialize a MaxKey
    • MongoDB\BSON\MaxKey::__construct - Construct a new MaxKey
    • MongoDB\BSON\MinKey::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\MinKey::serialize - Serialize a MinKey
    • MongoDB\BSON\MinKey::unserialize - Unserialize a MinKey
    • MongoDB\BSON\MinKey::__construct - Construct a new MinKey
    • MongoDB\BSON\ObjectId::getTimestamp - Returns the timestamp component of this ObjectId
    • MongoDB\BSON\ObjectId::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\ObjectId::serialize - Serialize an ObjectId
    • MongoDB\BSON\ObjectId::unserialize - Unserialize an ObjectId
    • MongoDB\BSON\ObjectId::__construct - Construct a new ObjectId
    • MongoDB\BSON\ObjectId::__toString - Returns the hexidecimal representation of this ObjectId
    • MongoDB\BSON\ObjectIdInterface::getTimestamp - Returns the timestamp component of this ObjectIdInterface
    • MongoDB\BSON\ObjectIdInterface::__toString - Returns the hexidecimal representation of this ObjectIdInterface
    • MongoDB\BSON\Regex::getFlags - Returns the Regex's flags
    • MongoDB\BSON\Regex::getPattern - Returns the Regex's pattern
    • MongoDB\BSON\Regex::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Regex::serialize - Serialize a Regex
    • MongoDB\BSON\Regex::unserialize - Unserialize a Regex
    • MongoDB\BSON\Regex::__construct - Construct a new Regex
    • MongoDB\BSON\Regex::__toString - Returns the string representation of this Regex
    • MongoDB\BSON\RegexInterface::getFlags - Returns the RegexInterface's flags
    • MongoDB\BSON\RegexInterface::getPattern - Returns the RegexInterface's pattern
    • MongoDB\BSON\RegexInterface::__toString - Returns the string representation of this RegexInterface
    • MongoDB\BSON\Serializable::bsonSerialize - Provides an array or document to serialize as BSON
    • MongoDB\BSON\Timestamp::getIncrement - Returns the increment component of this Timestamp
    • MongoDB\BSON\Timestamp::getTimestamp - Returns the timestamp component of this Timestamp
    • MongoDB\BSON\Timestamp::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Timestamp::serialize - Serialize a Timestamp
    • MongoDB\BSON\Timestamp::unserialize - Unserialize a Timestamp
    • MongoDB\BSON\Timestamp::__construct - Construct a new Timestamp
    • MongoDB\BSON\Timestamp::__toString - Returns the string representation of this Timestamp
    • MongoDB\BSON\TimestampInterface::getIncrement - Returns the increment component of this TimestampInterface
    • MongoDB\BSON\TimestampInterface::getTimestamp - Returns the timestamp component of this TimestampInterface
    • MongoDB\BSON\TimestampInterface::__toString - Returns the string representation of this TimestampInterface
    • MongoDB\BSON\toCanonicalExtendedJSON - Returns the Canonical Extended JSON representation of a BSON value
    • MongoDB\BSON\toJSON - Returns the Legacy Extended JSON representation of a BSON value
    • MongoDB\BSON\toPHP - Returns the PHP representation of a BSON value
    • MongoDB\BSON\toRelaxedExtendedJSON - Returns the Relaxed Extended JSON representation of a BSON value
    • MongoDB\BSON\Unserializable::bsonUnserialize - Constructs the object from a BSON array or document
    • MongoDB\BSON\UTCDateTime::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\UTCDateTime::serialize - Serialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::toDateTime - Returns the DateTime representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTime::unserialize - Unserialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::__construct - Construct a new UTCDateTime
    • MongoDB\BSON\UTCDateTime::__toString - Returns the string representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTimeInterface::toDateTime - Returns the DateTime representation of this UTCDateTimeInterface
    • MongoDB\BSON\UTCDateTimeInterface::__toString - Returns the string representation of this UTCDateTimeInterface
    • MongoDB\Driver\BulkWrite::count - Count number of write operations in the bulk
    • MongoDB\Driver\BulkWrite::delete - Add a delete operation to the bulk
    • MongoDB\Driver\BulkWrite::insert - Add an insert operation to the bulk
    • MongoDB\Driver\BulkWrite::update - Add an update operation to the bulk
    • MongoDB\Driver\BulkWrite::__construct - Create a new BulkWrite
    • MongoDB\Driver\Command::__construct - Create a new Command
    • MongoDB\Driver\Cursor::current - Returns the current element
    • MongoDB\Driver\Cursor::getId - Returns the ID for this cursor
    • MongoDB\Driver\Cursor::getServer - Returns the server associated with this cursor
    • MongoDB\Driver\Cursor::isDead - Checks if the cursor is exhausted or may have additional results
    • MongoDB\Driver\Cursor::key - Returns the current result's index within the cursor
    • MongoDB\Driver\Cursor::next - Advances the cursor to the next result
    • MongoDB\Driver\Cursor::rewind - Rewind the cursor to the first result
    • MongoDB\Driver\Cursor::setTypeMap - Sets a type map to use for BSON unserialization
    • MongoDB\Driver\Cursor::toArray - Returns an array containing all results for this cursor
    • MongoDB\Driver\Cursor::valid - Checks if the current position in the cursor is valid
    • MongoDB\Driver\Cursor::__construct - Create a new Cursor (not used)
    • MongoDB\Driver\CursorId::serialize - Serialize a CursorId
    • MongoDB\Driver\CursorId::unserialize - Unserialize a CursorId
    • MongoDB\Driver\CursorId::__construct - Create a new CursorId (not used)
    • MongoDB\Driver\CursorId::__toString - String representation of the cursor ID
    • MongoDB\Driver\Exception\RuntimeException::hasErrorLabel - Returns whether an error label is associated with an exception
    • MongoDB\Driver\Exception\WriteException::getWriteResult - Returns the WriteResult for the failed write operation
    • MongoDB\Driver\Manager::createClientEncryption - Create a new ClientEncryption object
    • MongoDB\Driver\Manager::executeBulkWrite - Execute one or more write operations
    • MongoDB\Driver\Manager::executeCommand - Execute a database command
    • MongoDB\Driver\Manager::executeQuery - Execute a database query
    • MongoDB\Driver\Manager::executeReadCommand - Execute a database command that reads
    • MongoDB\Driver\Manager::executeReadWriteCommand - Execute a database command that reads and writes
    • MongoDB\Driver\Manager::executeWriteCommand - Execute a database command that writes
    • MongoDB\Driver\Manager::getReadConcern - Return the ReadConcern for the Manager
    • MongoDB\Driver\Manager::getReadPreference - Return the ReadPreference for the Manager
    • MongoDB\Driver\Manager::getServers - Return the servers to which this manager is connected
    • MongoDB\Driver\Manager::getWriteConcern - Return the WriteConcern for the Manager
    • MongoDB\Driver\Manager::selectServer - Select a server matching a read preference
    • MongoDB\Driver\Manager::startSession - Start a new client session for use with this client
    • MongoDB\Driver\Manager::__construct - Create new MongoDB Manager
    • MongoDB\Driver\Query::__construct - Create a new Query
    • MongoDB\Driver\ReadConcern::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\ReadConcern::getLevel - Returns the ReadConcern's "level" option
    • MongoDB\Driver\ReadConcern::isDefault - Checks if this is the default read concern
    • MongoDB\Driver\ReadConcern::serialize - Serialize a ReadConcern
    • MongoDB\Driver\ReadConcern::unserialize - Unserialize a ReadConcern
    • MongoDB\Driver\ReadConcern::__construct - Create a new ReadConcern
    • MongoDB\Driver\ReadPreference::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\ReadPreference::getHedge - Returns the ReadPreference's "hedge" option
    • MongoDB\Driver\ReadPreference::getMaxStalenessSeconds - Returns the ReadPreference's "maxStalenessSeconds" option
    • MongoDB\Driver\ReadPreference::getMode - Returns the ReadPreference's "mode" option
    • MongoDB\Driver\ReadPreference::getModeString - Returns the ReadPreference's "mode" option as a string
    • MongoDB\Driver\ReadPreference::getTagSets - Returns the ReadPreference's "tagSets" option
    • MongoDB\Driver\ReadPreference::serialize - Serialize a ReadPreference
    • MongoDB\Driver\ReadPreference::unserialize - Unserialize a ReadPreference
    • MongoDB\Driver\ReadPreference::__construct - Create a new ReadPreference
    • MongoDB\Driver\Server::executeBulkWrite - Execute one or more write operations on this server
    • MongoDB\Driver\Server::executeCommand - Execute a database command on this server
    • MongoDB\Driver\Server::executeQuery - Execute a database query on this server
    • MongoDB\Driver\Server::executeReadCommand - Execute a database command that reads on this server
    • MongoDB\Driver\Server::executeReadWriteCommand - Execute a database command that reads and writes on this server
    • MongoDB\Driver\Server::executeWriteCommand - Execute a database command that writes on this server
    • MongoDB\Driver\Server::getHost - Returns the hostname of this server
    • MongoDB\Driver\Server::getInfo - Returns an array of information about this server
    • MongoDB\Driver\Server::getLatency - Returns the latency of this server
    • MongoDB\Driver\Server::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Server::getTags - Returns an array of tags describing this server in a replica set
    • MongoDB\Driver\Server::getType - Returns an integer denoting the type of this server
    • MongoDB\Driver\Server::isArbiter - Checks if this server is an arbiter member of a replica set
    • MongoDB\Driver\Server::isHidden - Checks if this server is a hidden member of a replica set
    • MongoDB\Driver\Server::isPassive - Checks if this server is a passive member of a replica set
    • MongoDB\Driver\Server::isPrimary - Checks if this server is a primary member of a replica set
    • MongoDB\Driver\Server::isSecondary - Checks if this server is a secondary member of a replica set
    • MongoDB\Driver\Server::__construct - Create a new Server (not used)
    • MongoDB\Driver\WriteConcern::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\WriteConcern::getJournal - Returns the WriteConcern's "journal" option
    • MongoDB\Driver\WriteConcern::getW - Returns the WriteConcern's "w" option
    • MongoDB\Driver\WriteConcern::getWtimeout - Returns the WriteConcern's "wtimeout" option
    • MongoDB\Driver\WriteConcern::isDefault - Checks if this is the default write concern
    • MongoDB\Driver\WriteConcern::serialize - Serialize a WriteConcern
    • MongoDB\Driver\WriteConcern::unserialize - Unserialize a WriteConcern
    • MongoDB\Driver\WriteConcern::__construct - Create a new WriteConcern
    • MongoDB\Driver\WriteConcernError::getCode - Returns the WriteConcernError's error code
    • MongoDB\Driver\WriteConcernError::getInfo - Returns metadata document for the WriteConcernError
    • MongoDB\Driver\WriteConcernError::getMessage - Returns the WriteConcernError's error message
    • MongoDB\Driver\WriteError::getCode - Returns the WriteError's error code
    • MongoDB\Driver\WriteError::getIndex - Returns the index of the write operation corresponding to this WriteError
    • MongoDB\Driver\WriteError::getInfo - Returns metadata document for the WriteError
    • MongoDB\Driver\WriteError::getMessage - Returns the WriteError's error message
    • MongoDB\Driver\WriteResult::getDeletedCount - Returns the number of documents deleted
    • MongoDB\Driver\WriteResult::getInsertedCount - Returns the number of documents inserted (excluding upserts)
    • MongoDB\Driver\WriteResult::getMatchedCount - Returns the number of documents selected for update
    • MongoDB\Driver\WriteResult::getModifiedCount - Returns the number of existing documents updated
    • MongoDB\Driver\WriteResult::getServer - Returns the server associated with this write result
    • MongoDB\Driver\WriteResult::getUpsertedCount - Returns the number of documents inserted by an upsert
    • MongoDB\Driver\WriteResult::getUpsertedIds - Returns an array of identifiers for upserted documents
    • MongoDB\Driver\WriteResult::getWriteConcernError - Returns any write concern error that occurred
    • MongoDB\Driver\WriteResult::getWriteErrors - Returns any write errors that occurred
    • MongoDB\Driver\WriteResult::isAcknowledged - Returns whether the write was acknowledged
    • MongoDeleteBatch::__construct - Descripción
    • MongoGridFS::delete - Elimina un fichero y sus trozos de la base de datos
    • MongoGridFS::drop - Da de baja una colección de ficheros y de bloques
    • MongoGridFS::find - Selecciona ficheros
    • MongoGridFS::findOne - Devuelve el fichero que cumpla las condiciones
    • MongoGridFS::get - Obtiene un fichero de la base de datos
    • MongoGridFS::put - Almacena un fichero en la base de datos
    • MongoGridFS::remove - Eliminar ficheros y sus trozos de la base de datos
    • MongoGridFS::storeBytes - Almacena un string de bytes en la base de datos
    • MongoGridFS::storeFile - Almacena un fichero en la base de datos
    • MongoGridFS::storeUpload - Almacena un fichero subido en la base de datos
    • MongoGridFS::__construct - Crea una nueva colección de ficheros
    • MongoGridFSCursor::current - Devuelve el fichero actual
    • MongoGridFSCursor::getNext - Devuelve el siguiente fichero al que apunta este cursor, y avanza el cursor
    • MongoGridFSCursor::key - Devuelve el nombre de fichero del resultado actual
    • MongoGridFSCursor::__construct - Crea un nuevo cursor
    • MongoGridFSFile::getBytes - Devuelve el contenido de este fichero en forma de string de bytes
    • MongoGridFSFile::getFilename - Devuelve el nombre de este fichero
    • MongoGridFSFile::getResource - Devuelve un recurso que puede usarse para leer el fichero almacenado
    • MongoGridFSFile::getSize - Devuelve el tamaño de este fichero
    • MongoGridFSFile::write - Escribe este fichero en disco
    • MongoGridfsFile::__construct - Crea un nuevo fichero GridFS
    • MongoId::getHostname - Obtiene el nombre de host que se usa para el id de esta máquina
    • MongoId::getInc - Obtiene el valor incremental usado para crear este id
    • MongoId::getPID - Obtiene el ID del proceso
    • MongoId::getTimestamp - Devuelve el número de segundos desde la fecha de referencia con el que se creó este id
    • MongoId::isValid - Comprobar si un valor es un ObjectId válido
    • MongoId::__construct - Crea un nuevo id
    • MongoId::__set_state - Crea un objeto MongoId trivial
    • MongoId::__toString - Devuelve la representación hexadecimal de este id
    • MongoInsertBatch::__construct - Descripción
    • MongoInt32::__construct - Crea un nuevo entero de 32 bits
    • MongoInt32::__toString - Devuelve al representación en forma de string de este entero de 32 bits
    • MongoInt64::__construct - Crea un nuevo entero de 64 bits
    • MongoInt64::__toString - Devuelve la representación en forma de texto de este entero de 64 bits
    • MongoLog::getCallback - Obtiene la función de retrollamada establecida anteriormente
    • MongoLog::getLevel - Obtiene el nivel o niveles que están siendo registrados
    • MongoLog::getModule - Devuelve el módulo o módulos que se están registrando actualmente
    • MongoLog::setCallback - Establece una función de retrollamada para ser invocada por eventos
    • MongoLog::setLevel - Establece el nivel o niveles a registrar
    • MongoLog::setModule - Establece el módulo o módulos a registrar
    • MongoPool::getSize - Devuelve el tamaño actual de un agrupamiento de conexiones
    • MongoPool::info - Devuelve información sobre todos los agrupamientos de conexiones
    • MongoPool::setSize - Establece el tamaño de los nuevos agrupamientos de conexiones
    • MongoRegex::__construct - Crea una nueva expresión regular
    • MongoRegex::__toString - Representación en forma de texto de esta expresión regular
    • MongoResultException::getDocument - Recupera el documento resultante completo
    • MongoTimestamp::__construct - Crea una nueva marca temporal
    • MongoTimestamp::__toString - Devuelve la representación en forma de texto de este timestamp
    • MongoUpdateBatch::__construct - Descripción
    • MongoWriteBatch::add - Añade una operación de escritura a un lote
    • MongoWriteBatch::execute - Ejecuta un lote de operaciones de escritura
    • MongoWriteBatch::__construct - Crea un nuevo lote de operaciones de escritura
    • MongoWriteConcernException::getDocument - Obtener el documento del error
    • move_uploaded_file - Mueve un archivo subido a una nueva ubicación
    • mqseries_back - MQSeries MQBACK
    • mqseries_begin - MQseries MQBEGIN
    • mqseries_close - MQSeries MQCLOSE
    • mqseries_cmit - MQSeries MQCMIT
    • mqseries_conn - MQSeries MQCONN
    • mqseries_connx - MQSeries MQCONNX
    • mqseries_disc - MQSeries MQDISC
    • mqseries_get - MQSeries MQGET
    • mqseries_inq - MQSeries MQINQ
    • mqseries_open - MQSeries MQOPEN
    • mqseries_put - MQSeries MQPUT
    • mqseries_put1 - MQSeries MQPUT1
    • mqseries_set - MQSeries MQSET
    • mqseries_strerror - Returns the error message corresponding to a result code (MQRC)
    • msg_get_queue - Crear o adjuntar a una cola de mensajes
    • msg_queue_exists - Verificar si una cola de mensajes existe
    • msg_receive - Recibir un mensaje de la cola de mensajes
    • msg_remove_queue - Destruir una cola de mensajes
    • msg_send - Eviar un mensaje a una cola de mensajes
    • msg_set_queue - Establecer información en la estructura de datos de la cola de mensajes
    • msg_stat_queue - Devuelve información desde la estructura de datos de la cola de mensajes
    • mt_getrandmax - Mostrar el mayor valor aleatorio posible
    • mt_rand - Genera un mejor número entero aleatorio
    • mt_srand - Genera el mejor número aleatorio a partir de una semilla
    • MultipleIterator::attachIterator - Adjunta información al iterador
    • MultipleIterator::containsIterator - Comprueba si un iterador está adjunto
    • MultipleIterator::countIterators - Obtiene el número de instancias de iteradores adjuntos
    • MultipleIterator::current - Obtiene las instancias registradas del iterador
    • MultipleIterator::detachIterator - Desasocia un iterador
    • MultipleIterator::getFlags - Obtiene información de las flags
    • MultipleIterator::key - Obtiene las instancias registradas del iterador
    • MultipleIterator::next - Mueve todas las instancias de iterador adjuntadas hacía la siguiente
    • MultipleIterator::rewind - Rebobina todas las instancias de iterador adjuntadas
    • MultipleIterator::setFlags - Establece las flags
    • MultipleIterator::valid - Comprueba la validez de los subiteradores
    • MultipleIterator::__construct - Construye un nuevo MultipleIterator
    • Mutex::create - Create a Mutex
    • Mutex::destroy - Destroy Mutex
    • Mutex::lock - Acquire Mutex
    • Mutex::trylock - Attempt to Acquire Mutex
    • Mutex::unlock - Release Mutex
    • mysqli::$affected_rows - Obtiene el número de filas afectadas en la última operación MySQL
    • mysqli::$connect_errno - Devuelve el código de error de la última llamada
    • mysqli::$connect_error - Devuelve una cadena con la descripción del último error de conexión
    • mysqli::$errno - Devuelve el código del error de la última función llamada
    • mysqli::$error - Devuelve una cadena que describe el último error
    • mysqli::$error_list - Devuelve una lista de errores desde el último comando ejecutado
    • mysqli::$field_count - Devuelve el número de columnas para la consulta más reciente
    • mysqli::$host_info - Devuelve una cadena que representa el tipo de conexión usada
    • mysqli::$info - Obtiene la información de la última consulta ejecutada
    • mysqli::$insert_id - Devuelve el id autogenerado que se utilizó en la última consulta
    • mysqli::$protocol_version - Devuelve la versión del protocolo MySQL utilizada
    • mysqli::$server_info - Devuelve la versión del servidor MySQL
    • mysqli::$server_version - Devuelve la versión del servidor MySQL como un valor entero
    • mysqli::$sqlstate - Devuelve el error SQLSTATE de la operación de MySQL previa
    • mysqli::$thread_id - Deveulve el ID del hilo de la conexión actual
    • mysqli::$warning_count - Devuelve el número de mensajes de advertencia de la última consulta para un enlace dado
    • mysqli::autocommit - Activa o desactiva las modificaciones de la base de datos autoconsignadas
    • mysqli::begin_transaction - Inicia una transacción
    • mysqli::change_user - Cambia el usuario de la conexión de bases de datos especificada
    • mysqli::character_set_name - Devuelve el juego de caracteres predeterminado para la conexión a la base de datos
    • mysqli::close - Cierra una conexión previamente abierta a una base de datos
    • mysqli::commit - Consigna la transacción actual
    • mysqli::debug - Realiza operaciones de depuración
    • mysqli::dump_debug_info - Volcado de información de depuración en el registro
    • mysqli::get_charset - Devuelve un objeto que contiene el conjunto de caracteres
    • mysqli::get_client_info - Obtiene información de la biblioteca cliente de MySQL
    • mysqli::get_connection_stats - Devuelve estadísticas sobre la conexión del cliente
    • mysqli::get_warnings - Obtiene el resultado de SHOW WARNINGS
    • mysqli::init - Inicializa y devuelve un recurso para utilizarlo con mysqli_real_connect()
    • mysqli::kill - Pide al servidor poner fin a un hilo de MySQL
    • mysqli::more_results - Comprueba si hay más resultados de una multi consulta
    • mysqli::multi_query - Realiza una consulta a la base de datos
    • mysqli::next_result - Prepara el siguiente resultado de multi_query
    • mysqli::options - Establecer opciones
    • mysqli::ping - Comprueba la conexión al servidor, o trata de reconectar si se perdió la conexión
    • mysqli::poll - Almacena en caché conexiones
    • mysqli::prepare - Prepara una sentencia SQL para su ejecución
    • mysqli::query - Realiza una consulta a la base de datos
    • mysqli::real_connect - Abre una conexión a un servidor mysql
    • mysqli::real_escape_string - Escapa los caracteres especiales de una cadena para usarla en una sentencia SQL, tomando en cuenta el conjunto de caracteres actual de la conexión
    • mysqli::real_query - Ejecuta una consulta SQL
    • mysqli::reap_async_query - Obtener el resultado de una consulta asincrónica
    • mysqli::refresh - Refresca
    • mysqli::release_savepoint - Elimina el punto salvado con nombre del conjunto de puntos salvados de la transacción actual
    • mysqli::rollback - Revierte la transacción actual
    • mysqli::savepoint - Define el nombre de un punto de salvaguarda de la transacción
    • mysqli::select_db - Selecciona la base de datos por defecto para realizar las consultas
    • mysqli::set_charset - Establece el conjunto de caracteres predeterminado del cliente
    • mysqli::set_opt - Alias de mysqli_options
    • mysqli::ssl_set - Usada para establece conexiones seguras usando SSL
    • mysqli::stat - Obtiene el estado actual del sistema
    • mysqli::stmt_init - Inicializa una sentencia y devuelve un objeto para usarlo con mysqli_stmt_prepare
    • mysqli::store_result - Transfiere un conjunto de resultados de la última consulta
    • mysqli::thread_safe - Devuelve si la seguridad a nivel de hilos está dada o no
    • mysqli::use_result - Inicia la recuperación de un conjunto de resultados
    • mysqli::__construct - Abre una nueva conexión al servidor de MySQL
    • mysqli_connect - Alias de mysqli::__construct
    • mysqli_driver::$report_mode - Habilita o desabilita las funciones internas de notificación
    • mysqli_driver::embedded_server_end - Detener el servidor incrustado
    • mysqli_driver::embedded_server_start - Inicializa e inicia el servidor embebido
    • mysqli_escape_string - Alias de mysqli_real_escape_string
    • mysqli_execute - Alias para mysqli_stmt_execute
    • mysqli_get_client_stats - Returns client per-process statistics
    • mysqli_get_client_version - Devuelve la versión clientes de MySQL como valor de tipo integer
    • mysqli_get_links_stats - Devolver información sobre enlaces abiertos y almacenados en caché
    • mysqli_report - Alias de mysqli_driver->report_mode
    • mysqli_result::$current_field - Obtener posición del campo actual de un puntero a un resultado
    • mysqli_result::$field_count - Obtiene el número de campos de un resultado
    • mysqli_result::$lengths - Retorna los largos de las columnas de la fila actual en el resultset
    • mysqli_result::$num_rows - Obtiene el número de filas de un resultado
    • mysqli_result::data_seek - Ajustar el puntero de resultado a una fila arbitraria del resultado
    • mysqli_result::fetch_all - Obtener todas las filas en un array asociativo, numérico, o en ambos
    • mysqli_result::fetch_array - Obtiene una fila de resultados como un array asociativo, numérico, o ambos
    • mysqli_result::fetch_assoc - Obtener una fila de resultado como un array asociativo
    • mysqli_result::fetch_field - Retorna el próximo campo del resultset
    • mysqli_result::fetch_fields - Devuelve un array de objetos que representan los campos de un conjunto de resultados
    • mysqli_result::fetch_field_direct - Obtener los metadatos de un único campo
    • mysqli_result::fetch_object - Devuelve la fila actual de un conjunto de resultados como un objeto
    • mysqli_result::fetch_row - Obtener una fila de resultados como un array enumerado
    • mysqli_result::field_seek - Establecer el puntero del resultado al índice del campo especificado
    • mysqli_result::free - Libera la memoria asociada a un resultado
    • mysqli_stmt::$affected_rows - Devuelve el número total de filas cambiadas, borradas, o insertadas por la última sentencia ejecutada
    • mysqli_stmt::$errno - Devuelve el código de error de la llamada de la sentencia más reciente
    • mysqli_stmt::$error - Devuelve una descripción en forma de string del último error de una sentencia
    • mysqli_stmt::$error_list - Devuelve una lista de errores de la última sentencia ejecutada
    • mysqli_stmt::$field_count - Devuelve el número de campos de la sentencia dada
    • mysqli_stmt::$insert_id - Obtener el ID generado en la operación INSERT anterior
    • mysqli_stmt::$num_rows - Devuelve el número de filas de un conjunto de resultados de una sentencia
    • mysqli_stmt::$param_count - Devuelve el número de parámetros de la sentencia dada
    • mysqli_stmt::$sqlstate - Devuelve el error SQLSTATE de la operación de sentencia previa
    • mysqli_stmt::attr_get - Se utiliza para obtener el valor actual de un atributo de la sentencia
    • mysqli_stmt::attr_set - Se utiliza para modificar el comportamiento de una sentencia preparada
    • mysqli_stmt::bind_param - Agrega variables a una sentencia preparada como parámetros
    • mysqli_stmt::bind_result - Vincula variables a una sentencia preparada para el almacenamiento de resultados
    • mysqli_stmt::close - Cierra una sentencia preparada
    • mysqli_stmt::data_seek - Busca una fila arbitraria en un conjunto de resultados de una sentencia
    • mysqli_stmt::execute - Ejecuta una consulta preparada
    • mysqli_stmt::fetch - Obtiene los resultados de una sentencia preparadas en las variables vinculadas
    • mysqli_stmt::free_result - Libera la memoria de los resultados almacenados del gestor de sentencia dado
    • mysqli_stmt::get_result - Obtiene un conjunto de resultados de una sentencia preparada
    • mysqli_stmt::get_warnings - Obtener los resultados de SHOW WARNINGS
    • mysqli_stmt::more_results - Comprobar si existen más resultados de una consulta de consultas múltiples
    • mysqli_stmt::next_result - Lee el siguiente resultado de una consulta múltiple
    • mysqli_stmt::prepare - Preparar una sentencia SQL para su ejecución
    • mysqli_stmt::reset - Reinicia una sentencia preparada
    • mysqli_stmt::result_metadata - Devuelve los metadatos del conjunto de resultados de una sentencia preparada
    • mysqli_stmt::send_long_data - Enviar datos en bloques
    • mysqli_stmt::store_result - Transfiere un conjunto de resultados desde una sentencia preparada
    • mysqli_stmt::__construct - Construye un nuevo objeto mysqli_stmt
    • mysqli_warning::next - El propósito next
    • MysqlndUhConnection::changeUser - Cambia el usuario de la conexión de la base de datos de mysqlnd especificada
    • MysqlndUhConnection::charsetName - Devuelve el conjunto de caracters predeterminado de la conexión de la base de datos
    • MysqlndUhConnection::close - Cierra una conexión a una base de datos abierta previamente
    • MysqlndUhConnection::connect - Abre una nueva conexión al servidor MySQL
    • MysqlndUhConnection::endPSession - Finaliza una conexión persistente
    • MysqlndUhConnection::escapeString - Escapa los caracteres especiales en una cadena para usarla en una sentencia SQL, tomando en cuenta el conjunto de caracteres actual de la conexión
    • MysqlndUhConnection::getAffectedRows - Obtiene el número de filas afectadas en una operación de MySQL anterior
    • MysqlndUhConnection::getErrorNumber - Devuelve el código de error de la llamada más reciente a una función
    • MysqlndUhConnection::getErrorString - Devuelve una descripción del último error
    • MysqlndUhConnection::getFieldCount - Devuelve el número de columnas de la consulta más reciente
    • MysqlndUhConnection::getHostInformation - Devuelve una representación de tipo string del tipo de conexión usada
    • MysqlndUhConnection::getLastInsertId - Devuelve el id autogenerado en la última consulta
    • MysqlndUhConnection::getLastMessage - Recupera información sobre la consulta ejecutadamás recientemente
    • MysqlndUhConnection::getProtocolInformation - Devuelve la versión del protocolo de MySQL usado
    • MysqlndUhConnection::getServerInformation - Devuelve la versión del servidor MySQL
    • MysqlndUhConnection::getServerStatistics - Obtiene el estado actual del sistema
    • MysqlndUhConnection::getServerVersion - Devuelve la versión del servidor MySQL en forma de entero
    • MysqlndUhConnection::getSqlstate - Devuelve el error SQLSTATE de la operación anterior de MySQL
    • MysqlndUhConnection::getStatistics - Devuelve estadísticas sobre la conexión cliente
    • MysqlndUhConnection::getThreadId - Devuelve el ID del hilo de la conexión en uso
    • MysqlndUhConnection::getWarningCount - Devuelve el número de advertencias de la última consulta para el enlace dado
    • MysqlndUhConnection::init - Iniciliza una conexión de mysqlnd
    • MysqlndUhConnection::killConnection - Pregunta al servidor para matar un subproceso de MySQL
    • MysqlndUhConnection::listFields - Enumera los campos de una tabla de MySQL
    • MysqlndUhConnection::listMethod - Envoltura para comandos de listas desordenadas
    • MysqlndUhConnection::moreResults - Comprueba si existen más resultados de consultas en una multiconsulta
    • MysqlndUhConnection::nextResult - Prepara el siguiente resultado de multi_query
    • MysqlndUhConnection::ping - Comprueba una conexión al servidor, o intenta reconectar si la conexión ha caído
    • MysqlndUhConnection::query - Realiza una consulta en la base de datos
    • MysqlndUhConnection::queryReadResultsetHeader - Lee una cabecera del conjunto de resultados
    • MysqlndUhConnection::reapQuery - Obtiene el resultado de una consulta asicrónica
    • MysqlndUhConnection::refreshServer - Vacía o reinicia las tablas y las cachés
    • MysqlndUhConnection::restartPSession - Reinicializa una conexión persistente a mysqlnd
    • MysqlndUhConnection::selectDb - Selecciona la base de datos predeterminada para su consulta
    • MysqlndUhConnection::sendClose - Envía un comando de cierre a MySQL
    • MysqlndUhConnection::sendQuery - Envía una consulta a MySQL
    • MysqlndUhConnection::serverDumpDebugInformation - Vierte la información de depuración en el registro para el servidor MySQL
    • MysqlndUhConnection::setAutocommit - Activa o desactiva la autoconsigna de las modificaciones de la base de datos
    • MysqlndUhConnection::setCharset - Establece el conjunto de caracteres predeterminado del cliente
    • MysqlndUhConnection::setClientOption - Establece una opción del cliente
    • MysqlndUhConnection::setServerOption - Establece una opción del servidor
    • MysqlndUhConnection::shutdownServer - The shutdownServer purpose
    • MysqlndUhConnection::simpleCommand - Envía un comando COM_* básico
    • MysqlndUhConnection::simpleCommandHandleResponse - Procesa una respuesta para un comando COM_* básico enviado al cliente
    • MysqlndUhConnection::sslSet - Usado para establecer conexiones seguras con SSL
    • MysqlndUhConnection::stmtInit - Iniciliza una sentencia y devuelve un recurso para usarlo con mysqli_statement::prepare
    • MysqlndUhConnection::storeResult - Transfiere un conjunto de resultados de la última consulta
    • MysqlndUhConnection::txCommit - Consigna la transacción en uso
    • MysqlndUhConnection::txRollback - Revierte la transacción en uso
    • MysqlndUhConnection::useResult - Inicia una recuperación de un conjunto de resultados
    • MysqlndUhConnection::__construct - The __construct purpose
    • MysqlndUhPreparedStatement::execute - Ejecuta una consulta preparada
    • MysqlndUhPreparedStatement::prepare - Prepara una sentencia SQL para su ejecución
    • MysqlndUhPreparedStatement::__construct - The __construct purpose
    • mysqlnd_memcache_get_config - Devuelve información acerca de la configuración del complemento
    • mysqlnd_memcache_set - Asociar una conexión de MySQL con una conexión de Memcache
    • mysqlnd_ms_dump_servers - Devuelve una lista con los servidores actualmente configurados
    • mysqlnd_ms_fabric_select_global - Cambiar al servidor de fragmentación global para una tabla dada
    • mysqlnd_ms_fabric_select_shard - Cambiar a los fragmentos
    • mysqlnd_ms_get_last_gtid - Devuelve el último ID de transacciones global
    • mysqlnd_ms_get_last_used_connection - Devuelve un array que describe la última conexión usada
    • mysqlnd_ms_get_stats - Devuelve la distribución consultas y las estadísticas de conexión
    • mysqlnd_ms_match_wild - Comprueba si el nombre de una tabla coincide con un patrón comodín
    • mysqlnd_ms_query_is_select - Comprueba si se envía la conslta al servidor maestro, al esclavo, o al último servidor MySQL usado
    • mysqlnd_ms_set_qos - Establece la calidad de servicio necesaria de un clúster
    • mysqlnd_ms_set_user_pick_server - Establece una llamada de retorno para la división de lectura/escritura definida por el usuario
    • mysqlnd_ms_xa_begin - Inicia una transacción distribuida/XA entre servidores de MySQL
    • mysqlnd_ms_xa_commit - Consigna una transacción distribuida/XA entre servidores de MySQL
    • mysqlnd_ms_xa_gc - Recolecta basura de transacciones XA no finalizadas después de algún error del servidor
    • mysqlnd_ms_xa_rollback - Revierte una transacción distribuida/XA entre servidores de MySQL
    • mysqlnd_qc_clear_cache - Vacía todo el contenido de la caché
    • mysqlnd_qc_get_available_handlers - Devuelve una lista de los gestores de almacenamiento disponibles
    • mysqlnd_qc_get_cache_info - Devuelve información sobre el gestor en uso, el número de entradas de la caché y sobre las entradas de la caché, si está disponible
    • mysqlnd_qc_get_core_stats - Estadísticas recopiladas por el núcleo de la caché de consultas
    • mysqlnd_qc_get_normalized_query_trace_log - Devuelve un registro de rastreo de consultas normalizadas para cada consulta inspeccionada por la caché de consultas
    • mysqlnd_qc_get_query_trace_log - Devuelve información de rastreo para cada consulta inspeccionada por la caché de consultas
    • mysqlnd_qc_set_cache_condition - Establece las condiciones para el almacenamiento en caché automático
    • mysqlnd_qc_set_is_select - Instala una llamada de retorno que decide si una sentencia es almacenada en caché
    • mysqlnd_qc_set_storage_handler - Cambia el gestor de almacenamiento en uso
    • mysqlnd_qc_set_user_handlers - Establece las funciones de llamada de retorno para un gestor de almacenamiento procedimental definido por el usuario
    • mysqlnd_uh_convert_to_mysqlnd - Convierte un gestor de conexión de MySQL a uno de mysqlnd
    • mysqlnd_uh_set_connection_proxy - Instala un proxy para las conexiones de mysqlnd
    • mysqlnd_uh_set_statement_proxy - Instala un proxy para sentencias de mysqlnd
    • mysql_affected_rows - Obtiene el número de filas afectadas en la anterior operación de MySQL
    • mysql_client_encoding - Devuelve el nombre del conjunto de caracteres
    • mysql_close - Cerrar una conexión de MySQL
    • mysql_connect - Abre una conexión al servidor MySQL
    • mysql_create_db - Crea una base de datos MySQL
    • mysql_data_seek - Mueve el puntero de resultados interno
    • mysql_db_name - Recupera el nombre de la base de datos desde una llamada a mysql_list_dbs
    • mysql_db_query - Selecciona una base de datos y ejecuta una consulta sobre la misma
    • mysql_drop_db - Elimina (DROP) una base de datos MySQL
    • mysql_errno - Devuelve el valor numérico del mensaje de error de la última operación MySQL
    • mysql_error - Devuelve el texto del mensaje de error de la operación MySQL anterior
    • mysql_escape_string - Escapa una cadena para ser usada en mysql_query
    • mysql_fetch_array - Recupera una fila de resultados como un array asociativo, un array numérico o como ambos
    • mysql_fetch_assoc - Recupera una fila de resultados como un array asociativo
    • mysql_fetch_field - Obtiene la información de una columna de un resultado y la devuelve como un objeto
    • mysql_fetch_lengths - Obtiene la longitud de cada salida en un resultado
    • mysql_fetch_object - Recupera una fila de resultados como un objeto
    • mysql_fetch_row - Obtiene una fila de resultados como un array numérico
    • mysql_field_flags - Obtiene las banderas asociadas al campo especificado de un resultado
    • mysql_field_len - Devuelve la longitud del campo especificado
    • mysql_field_name - Obtiene el nombre del campo especificado de un resultado
    • mysql_field_seek - Establece el puntero del resultado en un índice de campo específicado
    • mysql_field_table - Obtiene el nombre de la tabla en la que está el campo especificado
    • mysql_field_type - Obtiene el tipo del campo especificado de un resultado
    • mysql_free_result - Libera la memoria del resultado
    • mysql_get_client_info - Obtiene información del cliente MySQL
    • mysql_get_host_info - Obtener información del anfitrión de MySQL
    • mysql_get_proto_info - Obtener información del protocolo MySQL
    • mysql_get_server_info - Obtiene información del servidor MySQL
    • mysql_info - Obtiene información sobre la consulta más reciente
    • mysql_insert_id - Obtiene el ID generado en la última consulta
    • mysql_list_dbs - Lista las bases de datos disponibles en un servidor MySQL
    • mysql_list_fields - Lista los campos de una tabla de MySQL
    • mysql_list_processes - Lista los procesos de MySQL
    • mysql_list_tables - Enumerar las tablas de una base de datos MySQL
    • mysql_num_fields - Obtiene el número de campos de un resultado
    • mysql_num_rows - Obtener el número de filas de un conjunto de resultados
    • mysql_pconnect - Abre una conexión persistente a un servidor MySQL
    • mysql_ping - Efectuar un chequeo de respuesta (ping) sobre una conexión al servidor o reconectarse si no hay conexión
    • mysql_query - Enviar una consulta MySQL
    • mysql_real_escape_string - Escapa caracteres especiales en una cadena para su uso en una sentencia SQL
    • mysql_result - Obtener datos de resultado
    • mysql_select_db - Seleccionar una base de datos MySQL
    • mysql_set_charset - Establece el conjunto de caracteres del cliente
    • mysql_stat - Obtiene el estado actual del sistema
    • mysql_tablename - Obtiene el nombre de la tabla de un campo
    • mysql_thread_id - Devuelve el ID del hilo actual
    • mysql_unbuffered_query - Envía una consulta SQL a MySQL, sin recuperar ni almacenar en búfer las filas de resultados
  • n
    • natcasesort - Ordenar un array usando un algoritmo de "orden natural" insensible a mayúsculas-minúsculas
    • natsort - Ordena un array usando un algoritmo de "orden natural"
    • ncurses_addch - Agregar un caracter en la posición actual y avanzar el cursor
    • ncurses_addchnstr - Agregar cadena con atributos y longitud especificada en la posición actual
    • ncurses_addchstr - Agregar una cadena con atributos en la posición actual
    • ncurses_addnstr - Agregar una cadena con la longitud especificada en la posición actual
    • ncurses_addstr - Imprimir texto en la posición actual
    • ncurses_assume_default_colors - Definir colores predeterminados para el color 0
    • ncurses_attroff - Deshabilitar los atributos dados
    • ncurses_attron - Habilitar los atributos dados
    • ncurses_attrset - Establecer los atributos dados
    • ncurses_baudrate - Devuelve la tasa de baudios de la terminal
    • ncurses_beep - Producir un beep en la terminal
    • ncurses_bkgd - Establecer la propiedad de segundo plano para la pantalla de la terminal
    • ncurses_bkgdset - Controla el segundo plano de la pantalla
    • ncurses_border - Dibujar un borde alrededor de la pantalla usando caracteres con atributos
    • ncurses_bottom_panel - Mueve un panel visible al fondo de la pila
    • ncurses_can_change_color - Comprobar si las definiciones de color del terminal se pueden cambiar
    • ncurses_cbreak - Desactivar el búfer de entrada
    • ncurses_clear - Limpiar la pantalla
    • ncurses_clrtobot - Limpiar la pantalla desde la posición actual al final
    • ncurses_clrtoeol - Limpiar la pantalla desde la posición actual al final de la línea
    • ncurses_color_content - Obtiene los componentes RGB de un color
    • ncurses_color_set - Establecer los colores de primer plano y fondo activos
    • ncurses_curs_set - Establecer el estado del cursor
    • ncurses_define_key - Definir un código de tecla
    • ncurses_def_prog_mode - Guarda los modos de terminal (programa)
    • ncurses_def_shell_mode - Guarda los modos de terminal (intérprete de comandos)
    • ncurses_delay_output - Retrasar la salida en la terminal usando caracteres de relleno
    • ncurses_delch - Eliminar un caracter en la posición actual, mover el resto de la línea hacia la izquierda
    • ncurses_deleteln - Eliminar una línea en la posición actual, mover el resto de la pantalla hacia arriba
    • ncurses_delwin - Eliminar una ventana ncurses
    • ncurses_del_panel - Remover un panel de la pila y eliminarlo (pero no la ventana asociada)
    • ncurses_doupdate - Escribir todas las actualizaciones preparadas sobre la terminal
    • ncurses_echo - Activar la repetición de entrada del teclado
    • ncurses_echochar - Salida de un caracter sencillo, incluyendo actualización
    • ncurses_end - Dejar de usar ncurses, limpiar la pantalla
    • ncurses_erase - Limpiar pantalla de terminal
    • ncurses_erasechar - Devuelve el caracter de borrado actual
    • ncurses_filter - Definir LINES para iniscr() y newterm() a 1
    • ncurses_flash - Relampaguear la pantalla de terminal (campana visual)
    • ncurses_flushinp - Volcar el búfer de entrada de teclado
    • ncurses_getch - Leer un caracter desde el teclado
    • ncurses_getmaxyx - Devuelve el tamaño de una ventana
    • ncurses_getmouse - Lee los eventos del ratón
    • ncurses_getyx - Devuelve la posición de cursor actual para una ventana
    • ncurses_halfdelay - Colocar la terminal en modo de medio retraso
    • ncurses_has_colors - Comprueba si el terminal tiene capacidades de color
    • ncurses_has_ic - Chequear por el soporte de inserción y borrado
    • ncurses_has_il - Chequea el soporte de inserción y borrado
    • ncurses_has_key - Chequear por la presencia de una tecla de función en el teclado de la terminal
    • ncurses_hide_panel - Remover un panel de la pila, haciéndolo invisible
    • ncurses_hline - Dibujar una línea horizontal en la posición actual usando un caracter con atributos, y de máximo n caracteres de largo
    • ncurses_inch - Obtener el caracter y los atributos de la posición actual
    • ncurses_init - Inicializar ncurses
    • ncurses_init_color - Definir un color de termimal
    • ncurses_init_pair - Definir una pareja de colores
    • ncurses_insch - Insertar un caracter, moviendo el resto de la línea, incluyendo el caracter en la posición actual
    • ncurses_insdelln - Insertar líneas antes de la línea actual, desplazando hacia abajo (los números negativos eliminan líneas y desplazan hacia arriba)
    • ncurses_insertln - Insertar una línea, mover el resto de la pantalla hacia abajo
    • ncurses_insstr - Insertar cadena en la posición actual, moviendo el resto de la línea hacia la derecha
    • ncurses_instr - Lee una cadena desde la pantalla de terminal
    • ncurses_isendwin - Ncurses está en modo endwin, se puede realizar una salida normal por pantalla
    • ncurses_keyok - Habilitar o deshabilitar un código de tecla
    • ncurses_keypad - Activa o desactiva el teclado numérico
    • ncurses_killchar - Devuelve el caracter de eliminación de línea actual
    • ncurses_longname - Devuelve la descripción de la terminal
    • ncurses_meta - Habilita/deshabilita la meta-información de 8-bits de tecla
    • ncurses_mouseinterval - Establecer el tiempo de espera para clics de botón del mouse
    • ncurses_mousemask - Establece las opciones del ratón
    • ncurses_mouse_trafo - Transforma coordenadas
    • ncurses_move - Mover la posición de salida
    • ncurses_move_panel - Mueve un panel de modo que su esquina superior izquierda se encuentre en [comienzo_x, comienzo_y]
    • ncurses_mvaddch - Mover la posición actual y agregar un caracter
    • ncurses_mvaddchnstr - Mover la posición y agregar una cadena con atributos con la longitud especificada
    • ncurses_mvaddchstr - Mover la posición y agregar una cadena con atributos
    • ncurses_mvaddnstr - Mover la posición y agregar una cadena con la longitud especificada
    • ncurses_mvaddstr - Mover la posición y agregar una cadena
    • ncurses_mvcur - Mover el cursor inmediatamente
    • ncurses_mvdelch - Mover la posición y eliminar un caracter, desplazar el resto de la línea hacia la izquierda
    • ncurses_mvgetch - Mover la posición y obtener el caracter en la nueva posición
    • ncurses_mvhline - Establecer una nueva posición y dibujar una línea horizontal usando un caracter con atributos y una longitud máxima de n caracteres
    • ncurses_mvinch - Mover la posición y obtener el caracter con atributos en la nueva posición
    • ncurses_mvvline - Establecer una nueva posición y dibujar una línea vertical usando un caracter con atributos y una longitud máxima de n caracteres
    • ncurses_mvwaddstr - Añadir una cadena en una posicón nueva de la ventana
    • ncurses_napms - Dormir
    • ncurses_newpad - Crea un nuevo pad (ventana)
    • ncurses_newwin - Crear una nueva ventana
    • ncurses_new_panel - Crear un nuevo panel y asociarlo con una ventana
    • ncurses_nl - Traducir línea nueva y retorno de carro / alimentación de línea
    • ncurses_nocbreak - Cambiar la terminal a modo normal (cooked)
    • ncurses_noecho - Desactivar la repetición de entrada del teclado
    • ncurses_nonl - No traducir línea nueva y retorno de carro / alimentación de línea
    • ncurses_noqiflush - No realizar volcados en caracteres de señales
    • ncurses_noraw - Salir del modo puro en la terminal
    • ncurses_pair_content - Obtiene los colores de primer plano y fondo de una pareja de colores
    • ncurses_panel_above - Devuelve el panel encima del panel indicado
    • ncurses_panel_below - Devuelve el panel por debajo del panel indicado
    • ncurses_panel_window - Devuelve la ventana asociada con el panel
    • ncurses_pnoutrefresh - Copia una región desde un pad a la pantalla virtual
    • ncurses_prefresh - Copia una región desde un pad a la pantalla virtual
    • ncurses_putp - Aplicar la información de márgenes a la cadena e imprimirla
    • ncurses_qiflush - Producir volcado en caracteres de señales
    • ncurses_raw - Colocar la terminal en modo puro
    • ncurses_refresh - Refrescar la pantalla
    • ncurses_replace_panel - Reemplaza la ventana asociada con el panel
    • ncurses_resetty - Restablece el estado guardado de la terminal
    • ncurses_reset_prog_mode - Restablece el modo de programa guardado por def_prog_mode
    • ncurses_reset_shell_mode - Restablece el modo de intérprete de comandos guardado por def_shell_mode
    • ncurses_savetty - Guarda el estado de la terminal
    • ncurses_scrl - Desplazar el contenido de la ventana hacia arriba o abajo sin cambiar la posición actual
    • ncurses_scr_dump - Vuelca el contenido de la pantalla en un archivo
    • ncurses_scr_init - Inicializar la pantalla desde un volcado en un archivo
    • ncurses_scr_restore - Recuperar la pantalla desde un volcado en un archivo
    • ncurses_scr_set - Heredar la pantalla de un volcado en un archivo
    • ncurses_show_panel - Coloca un panel invisible al comienzo de la pila, haciéndola visible
    • ncurses_slk_attr - Devuelve el atributo de la etiqueta suave de teclado
    • ncurses_slk_attroff - Deshabilitar los atributos dados para las etiquetas suaves de teclado
    • ncurses_slk_attron - Habilitar los atributos dados para las etiquetas suaves de funciones de teclado
    • ncurses_slk_attrset - Definir los atributos dados para las etiquetas suaves de funciones de teclado
    • ncurses_slk_clear - Limpia las etiquetas suaves de la pantalla
    • ncurses_slk_color - Establece el color para las etiquetas suaves de teclado
    • ncurses_slk_init - Inicializa las funciones de tecla de etiquetación suave
    • ncurses_slk_noutrefresh - Copia las etiquetas suaves de teclado a la pantalla virtual
    • ncurses_slk_refresh - Copia las etiquetas suaves de teclado a la pantalla
    • ncurses_slk_restore - Recupera las etiquetas suaves de teclado
    • ncurses_slk_set - Establece las etiquetas de teclado
    • ncurses_slk_touch - Obliga a que se produzca salida cuando se ejecute ncurses_slk_noutrefresh
    • ncurses_standend - Dejar de usar el atributo 'standout'
    • ncurses_standout - Comenzar a usar el atributo 'standout'
    • ncurses_start_color - Inicializa la funcionalidad de color
    • ncurses_termattrs - Devuelve un valor OR lógico de todas las banderas de atributos soportados por la terminal
    • ncurses_termname - Devuelve el nombre (corto) de la terminal
    • ncurses_timeout - Establecer el tiempo de espera para secuencias especiales de teclas
    • ncurses_top_panel - Mueve un panel visible al tope de la pila
    • ncurses_typeahead - Especificar un descriptor de archivo diferente para el chequeo de escritura siguiente
    • ncurses_ungetch - Colocar un caracter de vuelta en la secuencia de entrada
    • ncurses_ungetmouse - Coloca un evento de mouse en la cola
    • ncurses_update_panels - Refresca la pantalla virtual, para reflejar las relaciones entre los paneles en la pila
    • ncurses_use_default_colors - Asignar los colores predeterminados de la terminal al id de color -1
    • ncurses_use_env - Controlar el uso de información del entorno sobre el tamaño de la terminal
    • ncurses_use_extended_names - Controlar el uso de nombres extendidos en descripciones de información de terminal
    • ncurses_vidattr - Desplegar la cadena en la terminal con el atributo de modo de video
    • ncurses_vline - Dibujar una línea vertical en la posición actual usando un caracter con atributos y una longitud máxima de n caracteres
    • ncurses_waddch - Agrega un caracter en la posición actual de una ventana y avanza el cursor
    • ncurses_waddstr - Imprime un texto en la posición actual de una ventana
    • ncurses_wattroff - Deshabilita los atributos para una ventana
    • ncurses_wattron - Habilita los atributos para una ventana
    • ncurses_wattrset - Establecer los atributos para una ventana
    • ncurses_wborder - Dibuja un borde alrededor de la ventana usando caracteres con atributos
    • ncurses_wclear - Limpia la ventana
    • ncurses_wcolor_set - Establece parejas de colores en la ventana
    • ncurses_werase - Eliminar los contenidos de la ventana
    • ncurses_wgetch - Lee un caracter desde el teclado (en la ventana)
    • ncurses_whline - Dibuja una línea horizontal en una ventana en la posición actual usando un caracter con atributos y un largo máximo de n caracteres
    • ncurses_wmouse_trafo - Transforma coordenadas de ventana/stdscr
    • ncurses_wmove - Mueve la posición de salida de la ventana
    • ncurses_wnoutrefresh - Copia la ventana a la pantalla virtual
    • ncurses_wrefresh - Refrescar la ventana en la pantalla de terminal
    • ncurses_wstandend - Finaliza el modo standout para una ventana
    • ncurses_wstandout - Ingresar a modo standout en una ventana
    • ncurses_wvline - Dibuja una línea vertical en una ventana en la posición actual usando un caracter con atributos y una longitud máxima de n caracteres
    • next - Avanza el puntero interno de un array
    • ngettext - Versión plural de gettext
    • nl2br - Inserta saltos de línea HTML antes de todas las nuevas líneas de un string
    • nl_langinfo - Consulta información sobre el idioma y la configuración regional
    • NoRewindIterator::current - Obtener el valor actual
    • NoRewindIterator::getInnerIterator - Obtiene el iterador interno
    • NoRewindIterator::key - Obtiene la clave actual
    • NoRewindIterator::next - Avanza al siguiente elemento
    • NoRewindIterator::rewind - Evita la operación de rebobinado en el iterador interno
    • NoRewindIterator::valid - Valida el iterador
    • NoRewindIterator::__construct - Construye un NoRewindIterator
    • Normalizer::getRawDecomposition - Gets the Decomposition_Mapping property for the given UTF-8 encoded code point
    • Normalizer::isNormalized - Comprobar si la cadena proporcionada ya está en la forma de normalización especificada.
    • Normalizer::normalize - Normaliza la entrada provista y devuelve la cadena normalizada
    • NumberFormatter::create - Crear un formateador de números
    • NumberFormatter::format - Dar formato a un número
    • NumberFormatter::formatCurrency - Dar formato a un valor monetario
    • NumberFormatter::getAttribute - Obtener un atributo
    • NumberFormatter::getErrorCode - Obtener el último código de error del formateador
    • NumberFormatter::getErrorMessage - Obtener el último mensaje de error del formateador
    • NumberFormatter::getLocale - Obtener la configuración regional de un formateador
    • NumberFormatter::getPattern - Obtener el patrón del formateador
    • NumberFormatter::getSymbol - Obtener el valor de un símbolo
    • NumberFormatter::getTextAttribute - Obtiene un atributo de texto
    • NumberFormatter::parse - Analiza un número
    • NumberFormatter::parseCurrency - Procesa un número monetario
    • NumberFormatter::setAttribute - Establecer un atributo
    • NumberFormatter::setPattern - Establecer el patrón de un formateador
    • NumberFormatter::setSymbol - Establecer un valor de símbolo
    • NumberFormatter::setTextAttribute - Set a text attribute
    • number_format - Formatear un número con los millares agrupados
  • o
    • OAuth::disableDebug - Desactiva la depuración detallada
    • OAuth::disableRedirects - Desactiva las redirecciones
    • OAuth::disableSSLChecks - Desactiva la verificación SSL
    • OAuth::enableDebug - Activa la depuración detallada
    • OAuth::enableRedirects - Activa las re-direcciones
    • OAuth::enableSSLChecks - Activa la verificación SSL
    • OAuth::fetch - Obtiene un recurso protegido por OAuth
    • OAuth::generateSignature - Generar una firma
    • OAuth::getAccessToken - Obtiene el token de acceso
    • OAuth::getCAPath - Obtiene la información CA
    • OAuth::getLastResponse - Obtiene la última respuesta
    • OAuth::getLastResponseHeaders - Obtener encabezados de la última respuesta
    • OAuth::getLastResponseInfo - Obtiene la información HTTP sobre la última respuesta
    • OAuth::getRequestHeader - Generar un string de firma de cabecera OAuth
    • OAuth::getRequestToken - Obtiene un token de petición
    • OAuth::setAuthType - Establece el tipo de autorización
    • OAuth::setCAPath - Establece la ruta a CA y su información
    • OAuth::setNonce - Configura el nonce para las solicitudes posteriores
    • OAuth::setRequestEngine - El propósito de setRequestEngine
    • OAuth::setRSACertificate - establece el certificado RSA
    • OAuth::setSSLChecks - Ajustar controles específicos de SSL para las solicitudes
    • OAuth::setTimestamp - Establece el timestamp
    • OAuth::setToken - Establece el token y el secreto
    • OAuth::setVersion - Configura la versión OAuth
    • OAuth::__construct - Crea un nuevo objeto OAuth
    • OAuth::__destruct - El destructor
    • OAuthProvider::addRequiredParameter - Agregar parámetros necesarios
    • OAuthProvider::callconsumerHandler - Llama al callback consumerNonceHandler
    • OAuthProvider::callTimestampNonceHandler - Llama al callback timestampNonceHandler
    • OAuthProvider::calltokenHandler - Llama al callback tokenNonceHandler
    • OAuthProvider::checkOAuthRequest - Revisa una petición OAuth
    • OAuthProvider::consumerHandler - Establece el manejador callback consumerHandler
    • OAuthProvider::generateToken - Genera un token aleatorio
    • OAuthProvider::is2LeggedEndpoint - is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint - Establece isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter - Remueve un parámetro requerido
    • OAuthProvider::reportProblem - Reportar un problema
    • OAuthProvider::setParam - Establece un parámetro
    • OAuthProvider::setRequestTokenPath - Establece la ruta de petición del token
    • OAuthProvider::timestampNonceHandler - Establece el callback timestampNonceHandler
    • OAuthProvider::tokenHandler - Establece el manejador callback de tokenHandler
    • OAuthProvider::__construct - Construye un nuevo objeto OAuthProvider
    • oauth_get_sbs - Genera una cadena de firma base
    • oauth_urlencode - Códifica una URI a RFC 3986
    • ob_clean - Limpiar (eliminar) el búfer de salida
    • ob_end_clean - Limpiar (eliminar) el búfer de salida y deshabilitar el almacenamiento en el mismo
    • ob_end_flush - Volcar (enviar) el búfer de salida y deshabilitar el almacenamiento en el mismo
    • ob_flush - Vaciar (enviar) el búfer de salida
    • ob_get_clean - Obtiene el contenido del búfer actual y elimina el búfer de salida actual
    • ob_get_contents - Devolver el contenido del búfer de salida
    • ob_get_flush - Volcar el búfer de salida, devolverlo como una cadena de caracteres y deshabilitar el almacenamiento en el búfer de salida
    • ob_get_length - Devolver la longitud del búfer de salida
    • ob_get_level - Devolver el nivel de anidamiento del mecanismo de almacenamiento en el búfer de salida
    • ob_get_status - Obtener el estado de los búferes de salida
    • ob_gzhandler - Función de llamada de retorno de ob_start para comprimir el búfer de salida con gzip
    • ob_iconv_handler - Convierte la codificación de caracteres al manejador del buffer de salida
    • ob_implicit_flush - Habilitar/deshabilitar el volcado implícito
    • ob_list_handlers - Enumerar todos los gestores de salida en uso
    • ob_start - Activa el almacenamiento en búfer de la salida
    • ob_tidyhandler - Función callback de ob_start para reparar el buffer
    • OCI-Collection::append - Añade un elemento a la colección
    • OCI-Collection::assign - Asigna un valor a la colección desde otra colección existente
    • OCI-Collection::assignElem - Asigna un valor a un elemento de la colección
    • OCI-Collection::free - Libera los recursos asociados con el objeto colección
    • OCI-Collection::getElem - Devuelve el valor de un elemento
    • OCI-Collection::max - Devuelve el número máximo de elementos de la colección
    • OCI-Collection::size - Devuelve el tamaño de la colección
    • OCI-Collection::trim - Elimina elementos del final de la colección
    • OCI-Lob::append - Añade datos a un objeto grande (LOB) desde otro
    • OCI-Lob::close - Cierra un descriptor de LOB
    • OCI-Lob::eof - Comprueba la marca de final de fichero en un descriptor de objetos grandes
    • OCI-Lob::erase - Borra la porción especificada de los datos internos de un LOB
    • OCI-Lob::export - Exporta el contenido de un LOB a un fichero
    • OCI-Lob::flush - Vacía/escribe el búfer de un LOB al servidor
    • OCI-Lob::free - Libera los recursos asociados con el descriptor del LOB
    • OCI-Lob::getBuffering - Devuelve el estado actual del uso del búfer para un objeto grande
    • OCI-Lob::import - Importa datos de un fichero a un LOB
    • OCI-Lob::load - Devuelve el contenido de un objeto grande
    • OCI-Lob::read - Lee parte del objeto grande
    • OCI-Lob::rewind - Mueve el puntero interno al comienzo de un objeto grande
    • OCI-Lob::save - Guarda datos en un objeto grande
    • OCI-Lob::saveFile - Alias de OCI-Lob::import
    • OCI-Lob::seek - Ubica el puntero interno de un objeto grande
    • OCI-Lob::setBuffering - Cambia el estado actual del uso del búfer para objetos grandes
    • OCI-Lob::size - Devuelve el tamaño de un objeto grande
    • OCI-Lob::tell - Devuelve la posición actual del puntero interno de un objeto grande
    • OCI-Lob::truncate - Trunca un objeto grande
    • OCI-Lob::write - Escribe datos en un objeto grande
    • OCI-Lob::writeTemporary - Escribe un objeto grande temporal
    • OCI-Lob::writeToFile - Alias de OCI-Lob::export
    • ocibindbyname - Alias de oci_bind_by_name
    • ocicancel - Alias de oci_cancel
    • ocicloselob - Alias de OCI-Lob::close
    • ocicollappend - Alias de OCI-Collection::append
    • ocicollassign - Alias de OCI-Collection::assign
    • ocicollassignelem - Alias de OCI-Collection::assignElem
    • ocicollgetelem - Alias de OCI-Collection::getElem
    • ocicollmax - Alias de OCI-Collection::max
    • ocicollsize - Alias de OCI-Collection::size
    • ocicolltrim - Alias de OCI-Collection::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 obsoleta de oci_fetch_array, oci_fetch_object, oci_fetch_assoc y oci_fetch_row
    • ocifetchstatement - Alias de oci_fetch_all
    • ocifreecollection - Alias de OCI-Collection::free
    • ocifreecursor - Alias de oci_free_statement
    • ocifreedesc - Alias de OCI-Lob::free
    • ocifreestatement - Alias de oci_free_statement
    • ociinternaldebug - Alias de oci_internal_debug
    • ociloadlob - Alias de OCI-Lob::load
    • 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 OCI-Lob::save
    • ocisavelobfile - Alias de OCI-Lob::import
    • ociserverversion - Alias de oci_server_version
    • ocisetprefetch - Alias de oci_set_prefetch
    • ocistatementtype - Alias de oci_statement_type
    • ociwritelobtofile - Alias de OCI-Lob::export
    • ociwritetemporarylob - Alias de OCI-Lob::writeTemporary
    • oci_bind_array_by_name - Vincula un array de PHP con un parámetro de un array de Oracle PL/SQL
    • oci_bind_by_name - Vincula una variable de PHP a un parámetro de sustitución de Oracle
    • oci_cancel - Cancela la lectura del cursor
    • oci_client_version - Devuelve la versión de la biblioteca cliente de Oracle
    • oci_close - Cierra una conexión a Oracle
    • oci_commit - Consigna la transacción pendiente de la base de datos
    • oci_connect - Conecta a una base de datos de Oracle
    • oci_define_by_name - Asocia una variable de PHP con una columna para la obtención de consultas
    • oci_error - Devuelve el último error encontrado
    • oci_execute - Ejecuta una sentencia
    • oci_fetch - Coloca la siguiente fila de una consulta en los búferes internos
    • oci_fetch_all - Obtiene múltiples filas de una consulta y las ubica en un array bidimiensional
    • oci_fetch_array - Devuelve la siguiente fila de una consulta como un array asociativo o numérico
    • oci_fetch_assoc - Devuelve la siguiente fila de una consulta como un array asociativo
    • oci_fetch_object - Devuelve la siguiente fila de una consulta como un objeto
    • oci_fetch_row - Devuelve la siguiente fila de una consulta como un array numérico
    • oci_field_is_null - Comprueba si un campo de la fila actualmente obtenida es null
    • oci_field_name - Devuelve el nombre de un campo de una sentencia
    • oci_field_precision - Indica la precisión de un campo
    • oci_field_scale - Indica la escala de un campo
    • oci_field_size - Devuelve el tamaño de un campo
    • oci_field_type - Devuelve el nombre del tipo de datos de un campo
    • oci_field_type_raw - Indica el tipo de datos sin tratar de Oracle de un campo
    • oci_free_descriptor - Libera un descriptor
    • oci_free_statement - Libera todos los recursos asociados con una sentencia o cursor
    • oci_get_implicit_resultset - Devuelve el siguiente recurso de sentencia hija desde un recurso de sentencia padre que posee Conjuntos de resultados implícitos de Oracle Database 12c
    • oci_internal_debug - Enables or disables internal debug output
    • oci_lob_copy - Copia objetos grandes
    • oci_lob_is_equal - Compara dos localizadores LOB/FILE
    • oci_new_collection - Asigna un nuevo objeto colección
    • oci_new_connect - Conectar al servidor de Oracle usando una conexión única
    • oci_new_cursor - Asigna y devuelve un nuevo cursor (gestor de sentencia)
    • oci_new_descriptor - Inicializa un nuevo descriptor LOB o FILE vacío
    • oci_num_fields - Devuelve el número de columnas del resultado de una sentencia
    • oci_num_rows - Devuelve el número de filas afectadas durante la ejecución de una sentencia
    • oci_parse - Prepara una sentencia de Oracle para su ejecución
    • oci_password_change - Cambia la contraseña de un usuario de Oracle
    • oci_pconnect - Conectar a una base de datos de Oracle usando una conexión persistente
    • oci_register_taf_callback - Registrar una función de retrollamada definida por el usuario para TAF de Oracle Database
    • oci_result - Devuelve el valor de un campo de la fila obtenida
    • oci_rollback - Revierte la transacción pendiente de la base de datos
    • oci_server_version - Devuelve la versión de Oracle Database
    • oci_set_action - Establece el nombre de una acción
    • oci_set_call_timeout - Sets a millisecond timeout for database calls
    • oci_set_client_identifier - Establece el identificador del cliente
    • oci_set_client_info - Establece la información del cliente
    • oci_set_db_operation - Sets the database operation
    • oci_set_edition - Establece la edición de la base de datos
    • oci_set_module_name - Establece el nombre de un módulo
    • oci_set_prefetch - Establece el número de filas a precargar mediante consultas
    • oci_statement_type - Devuelve el tipo de una sentencia
    • oci_unregister_taf_callback - Unregister a user-defined callback function for Oracle Database TAF
    • octdec - Octal a decimal
    • odbc_autocommit - Activa el comportamiento automático de envío
    • odbc_binmode - Manejo de información de columna binaria
    • odbc_close - Cerrar una conexión ODBC
    • odbc_close_all - Cerrar todas las conexiones ODBC
    • odbc_columnprivileges - Lista las columnas y los privilegios asociados para la tabla dada
    • odbc_columns - Lista los nombres de columnas de la tabla especificada
    • odbc_commit - Envía una transacción ODBC
    • odbc_connect - Conectar a una fuente de datos
    • odbc_cursor - Obtener el nombre del cursor
    • odbc_data_source - Devuelve información sobre una conexión actual
    • odbc_do - Alias de odbc_exec
    • odbc_error - Obtener el último código de error
    • odbc_errormsg - Obtener el último mensaje de error
    • odbc_exec - Preparar y ejecutar una sentencia SQL
    • odbc_execute - Ejecutar una declaración preparada
    • odbc_fetch_array - Obtener una fila de resultados como una matriz asociativa
    • odbc_fetch_into - Traer una fila de resultados en una matriz
    • odbc_fetch_object - Obtener una fila de resultados como un objeto
    • odbc_fetch_row - Traer una fila
    • odbc_field_len - Obtener la longitud (precisión) de un campo
    • odbc_field_name - Obtener el nombre de una columna
    • odbc_field_num - Devolver el número de columna
    • odbc_field_precision - Alias de odbc_field_len
    • odbc_field_scale - Obtener la escala de un campo
    • odbc_field_type - Tipo de datos de un campo
    • odbc_foreignkeys - Recupera información de una lista de claves extranjeras
    • odbc_free_result - Liberar los recursos asociados con un resultado
    • odbc_gettypeinfo - Recupera información sobre los tipos de datos soportados por la fuente de datos
    • odbc_longreadlen - Manejo de columnas LONG
    • odbc_next_result - Verifica si están disponibles múltiples resultados
    • odbc_num_fields - Número de columnas de un resultado
    • odbc_num_rows - Número de filas de un resultado
    • odbc_pconnect - Abrir una conexión persistente a una base de datos
    • odbc_prepare - Prepara una declaración para su ejecución
    • odbc_primarykeys - Obtiene las claves primarias de una tabla
    • odbc_procedurecolumns - Recuperar información sobre los parámetros a procedimientos
    • odbc_procedures - Obtener la lista de procedimientos almacenados en una fuente de datos específica
    • odbc_result - Obtener información de resultado
    • odbc_result_all - Imprimir el resultado como una tabla HTML
    • odbc_rollback - Revertir una transacción
    • odbc_setoption - Ajustar la configuración de ODBC
    • odbc_specialcolumns - Recupera columnas especiales
    • odbc_statistics - Recuperar las estadísticas de un tabla
    • odbc_tableprivileges - Lista las tablas y los privilegios asociados con cada tabla
    • odbc_tables - Obtener la lista de los nombres de las tablas almacenados en una fuente de datos específica
    • ogg:// - Flujos de audio
    • opcache_compile_file - Compiles and caches a PHP script without executing it
    • opcache_get_configuration - Get configuration information about the cache
    • opcache_get_status - Get status information about the cache
    • opcache_invalidate - Invalidates a cached script
    • opcache_is_script_cached - Tells whether a script is cached in OPCache
    • opcache_reset - Resets the contents of the opcode cache
    • Opciones de contexto de HTTP - Listado de opciones de contexto de HTTP
    • Opciones de contexto de MongoDB - Listado de opciones de contexto de MongoDB
    • Opciones de contexto de sockets - Listado de opciones de contexto de sockets
    • Opciones de contexto para CURL - Listado de opciones de contexto para CURL
    • Opciones de contexto para FTP - Listado de opciones de contexto para FTP
    • Opciones de contexto para SSL - Listado de opciones de contexto para SSL
    • Opciones de contexto Phar - Listado de opciones de contexto Phar
    • Opciones del contexto zip - Listado de opciones del contexto zip
    • openal_buffer_create - Genera un buffer OpenAL
    • openal_buffer_data - Carga un buffer con datos
    • openal_buffer_destroy - Destruye un buffer OpenAL
    • openal_buffer_get - Recupera una propiedad del buffer OpenAL
    • openal_buffer_loadwav - Carga un archivo .wav dentro de un buffer
    • openal_context_create - Crea un contexto de procesamiento de audio
    • openal_context_current - Crea el corriente contexto especificado
    • openal_context_destroy - Destruye un contexto
    • openal_context_process - Procesa un contexto especificado
    • openal_context_suspend - Suspende el contexto especificado
    • openal_device_close - Cierra un dispositivo OpenAL
    • openal_device_open - Inicia la capa de audio del OpenAL
    • openal_listener_get - Devuelve una propiedad de oyente
    • openal_listener_set - Establece una propiedad de oyente
    • openal_source_create - Genera una fuente de recursos
    • openal_source_destroy - Destruye una fuente de recursos
    • openal_source_get - Recupera una propiedad de una fuente del OpenAL
    • openal_source_pause - Pausa la fuente
    • openal_source_play - Empieza la reproducción de la fuente
    • openal_source_rewind - Rebobina la fuente
    • openal_source_set - Establece la propiedad de la fuente
    • openal_source_stop - Detiene la reproducción de la fuente
    • openal_stream - Empieza la salida de una fuente
    • opendir - Abre un gestor de directorio
    • openlog - Open connection to system logger
    • openssl_cipher_iv_length - Obtener la longitud del iv de cipher
    • 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 - Exporta una CSR como una cadena
    • openssl_csr_export_to_file - Exporta una CSR a un archivo
    • openssl_csr_get_public_key - Devuelve la clave púbilca de un CERT
    • openssl_csr_get_subject - Devuelve el sujeto de un CERT
    • openssl_csr_new - Genera una CSR
    • openssl_csr_sign - Firmar una CSR con otro certificado (o autofirmar) y generar un certificado
    • openssl_decrypt - Desencripta datos
    • openssl_dh_compute_key - Computa el secreto compartido para un valor público de una clave DH remota y una clave DH local
    • openssl_digest - Computa un método de resumen
    • openssl_encrypt - Cifra datos
    • openssl_error_string - Devolver un mensaje de error openSSL
    • openssl_free_key - Liberar el recurso de clave
    • openssl_get_cert_locations - Obtener las ubicaciones de certificados disponibles
    • openssl_get_cipher_methods - Obtiene los métodos de cifrado disponibles
    • openssl_get_curve_names - Gets list of available curve names for ECC
    • openssl_get_md_methods - Obtener los métodos de resumen disponibles
    • openssl_get_privatekey - Alias de openssl_pkey_get_private
    • openssl_get_publickey - Alias de openssl_pkey_get_public
    • openssl_open - Abre información sellada
    • openssl_pbkdf2 - Genera un string PKCS5 v2 PBKDF2, predeterminado a SHA-1
    • openssl_pkcs7_decrypt - Desencripta un mensaje S/MIME encriptado
    • openssl_pkcs7_encrypt - Encriptar un mensaje S/MIME
    • openssl_pkcs7_read - Export the PKCS7 file to an array of PEM certificates
    • openssl_pkcs7_sign - Firma un mensaje S/MIME
    • openssl_pkcs7_verify - Verifica la firma de un mensaje S/MIME firmado
    • openssl_pkcs12_export - Exporta un Archivo de Almacén de Certificado Compatible con PKCS#12 a una variable
    • openssl_pkcs12_export_to_file - Exporta un Archivo de Almacén de Certificado Compatible con PKCS#12
    • openssl_pkcs12_read - Convierte un Almacén de Certificado PKCS#12 a una matriz
    • openssl_pkey_derive - Computes shared secret for public value of remote and local DH or ECDH key
    • openssl_pkey_export - Obtiene una representación de una clave exportable a una cadena
    • openssl_pkey_export_to_file - Obtiene una representación de una clave exportable a un archivo
    • openssl_pkey_free - Libera una clave privada
    • openssl_pkey_get_details - Devuelve una matriz con los detalles de la clave
    • openssl_pkey_get_private - Obtener una clave privada
    • openssl_pkey_get_public - Extrae la clave pública del certificado y la prepara para usarla
    • openssl_pkey_new - Genera una clave privada nueva
    • openssl_private_decrypt - Desencripta información con la clave privada
    • openssl_private_encrypt - Encripta información con la clave privada
    • openssl_public_decrypt - Desencripta información con la clave pública
    • openssl_public_encrypt - Encripta información con una clave pública
    • openssl_random_pseudo_bytes - Genera una cadena de bytes pseudo-aleatoria
    • openssl_seal - Sellar (encriptar) información
    • openssl_sign - Genera una firma
    • openssl_spki_export - Exports a valid PEM formatted public key signed public key and challenge
    • openssl_spki_export_challenge - Exporta el desafío asociados con una clave pública y desafío firmados
    • openssl_spki_new - Generate a new signed public key and challenge
    • openssl_spki_verify - Verifies a signed public key and challenge
    • openssl_verify - Verificar una firma
    • openssl_x509_checkpurpose - Verifica si un certificado se puede usar para un propósito en particular
    • openssl_x509_check_private_key - Comprueba si una clave privada se corresponde a un certificado
    • openssl_x509_export - Exporta un certificado como una cadena
    • openssl_x509_export_to_file - Exporta un certificado a un archivo
    • openssl_x509_fingerprint - Calculates the fingerprint, or digest, of a given X.509 certificate
    • openssl_x509_free - Liberar un recurso de certificado
    • openssl_x509_parse - Analiza un certificado X509 y devuelve la información como un matriz
    • openssl_x509_read - Analiza un certificado X.509 y devuelve un identificador de recurso para él
    • openssl_x509_verify - Verifies digital signature of x509 certificate against a public key
    • ord - Convierte el primer byte de un string a un valor entre 0 y 255
    • OuterIterator::getInnerIterator - Devuelve el iterador interno de la entrada actual
    • output_add_rewrite_var - Añadir valores al mecanismo de reescritura de URLs
    • output_reset_rewrite_vars - Restablecer los valores del mecanismo de reescritura de URLs
  • p
    • pack - Empaqueta información a una cadena binaria
    • parallel\bootstrap - Bootstrapping
    • parallel\Channel::close - Closing
    • parallel\Channel::make - Access
    • parallel\Channel::open - Access
    • parallel\Channel::recv - Sharing
    • parallel\Channel::send - Sharing
    • parallel\Channel::__construct - Channel Construction
    • parallel\Events::addChannel - Targets
    • parallel\Events::addFuture - Targets
    • parallel\Events::poll - Polling
    • parallel\Events::remove - Targets
    • parallel\Events::setBlocking - Behaviour
    • parallel\Events::setInput - Input
    • parallel\Events::setTimeout - Behaviour
    • parallel\Events\Input::add - Inputs
    • parallel\Events\Input::clear - Inputs
    • parallel\Events\Input::remove - Inputs
    • parallel\Future::cancel - Cancellation
    • parallel\Future::cancelled - State Detection
    • parallel\Future::done - State Detection
    • parallel\Future::value - Resolution
    • parallel\run - Execution
    • parallel\Runtime::close - Runtime Graceful Join
    • parallel\Runtime::kill - Runtime Join
    • parallel\Runtime::run - Execution
    • parallel\Runtime::__construct - Runtime Construction
    • parallel\Sync::get - Access
    • parallel\Sync::notify - Synchronization
    • parallel\Sync::set - Access
    • parallel\Sync::wait - Synchronization
    • parallel\Sync::__construct - Construction
    • parallel\Sync::__invoke - Synchronization
    • ParentIterator::accept - Determina aceptabilidad
    • ParentIterator::getChildren - Devuelve los iteradores hijo contenidos en un ParentIterator
    • ParentIterator::hasChildren - Comprueba si los iteradores internos del elemento actual tiene un hijos
    • ParentIterator::next - Mueve el iterador a la siguiente posición
    • ParentIterator::rewind - Rebobina el iterador
    • ParentIterator::__construct - Construye un ParentIterator
    • Parle\Lexer::advance - Process next lexer rule
    • Parle\Lexer::build - Finalize the lexer rule set
    • Parle\Lexer::callout - Define token callback
    • Parle\Lexer::consume - Pass the data for processing
    • Parle\Lexer::dump - Dump the state machine
    • Parle\Lexer::getToken - Retrieve the current token
    • Parle\Lexer::insertMacro - Insert regex macro
    • Parle\Lexer::push - Add a lexer rule
    • Parle\Lexer::reset - Reset lexer
    • Parle\Parser::advance - Process next parser rule
    • Parle\Parser::build - Finalize the grammar rules
    • Parle\Parser::consume - Consume the data for processing
    • Parle\Parser::dump - Dump the grammar
    • Parle\Parser::errorInfo - Retrieve the error information
    • Parle\Parser::left - Declare a token with left-associativity
    • Parle\Parser::nonassoc - Declare a token with no associativity
    • Parle\Parser::precedence - Declare a precedence rule
    • Parle\Parser::push - Add a grammar rule
    • Parle\Parser::reset - Reset parser state
    • Parle\Parser::right - Declare a token with right-associativity
    • Parle\Parser::sigil - Retrieve a matching part of a rule
    • Parle\Parser::token - Declare a token
    • Parle\Parser::tokenId - Get token id
    • Parle\Parser::trace - Trace the parser operation
    • Parle\Parser::validate - Validate input
    • Parle\RLexer::advance - Process next lexer rule
    • Parle\RLexer::build - Finalize the lexer rule set
    • Parle\RLexer::callout - Define token callback
    • Parle\RLexer::consume - Pass the data for processing
    • Parle\RLexer::dump - Dump the state machine
    • Parle\RLexer::getToken - Retrieve the current token
    • Parle\RLexer::insertMacro - Insert regex macro
    • Parle\RLexer::push - Add a lexer rule
    • Parle\RLexer::pushState - Push a new start state
    • Parle\RLexer::reset - Reset lexer
    • Parle\RParser::advance - Process next parser rule
    • Parle\RParser::build - Finalize the grammar rules
    • Parle\RParser::consume - Consume the data for processing
    • Parle\RParser::dump - Dump the grammar
    • Parle\RParser::errorInfo - Retrieve the error information
    • Parle\RParser::left - Declare a token with left-associativity
    • Parle\RParser::nonassoc - Declare a token with no associativity
    • Parle\RParser::precedence - Declare a precedence rule
    • Parle\RParser::push - Add a grammar rule
    • Parle\RParser::reset - Reset parser state
    • Parle\RParser::right - Declare a token with right-associativity
    • Parle\RParser::sigil - Retrieve a matching part of a rule
    • Parle\RParser::token - Declare a token
    • Parle\RParser::tokenId - Get token id
    • Parle\RParser::trace - Trace the parser operation
    • Parle\RParser::validate - Validate input
    • Parle\Stack::pop - Pop an item from the stack
    • Parle\Stack::push - Push an item into the stack
    • parse_ini_file - Analiza un fichero de configuración
    • parse_ini_string - Analiza una cadena de configuración
    • parse_str - Convierte el string en variables
    • parse_url - Analiza un URL y devuelve sus componentes
    • passthru - Ejecuta un programa externo y muestra la salida en bruto
    • password_algos - Get available password hashing algorithm IDs
    • password_get_info - Devuelve información sobre el hash proporcionado
    • password_hash - Crea un hash de contraseña
    • password_needs_rehash - Comprueba si el hash facilitado coincide con las opciones proporcionadas
    • password_verify - Comprueba que la contraseña coincida con un hash
    • pathinfo - Devuelve información acerca de la ruta de un fichero
    • pclose - Cierra un proceso de un puntero a un fichero
    • pcntl_alarm - Set an alarm clock for delivery of a signal
    • pcntl_async_signals - Enable/disable asynchronous signal handling or return the old setting
    • pcntl_errno - Alias de pcntl_get_last_error
    • pcntl_exec - Executes specified program in current process space
    • pcntl_fork - Forks the currently running process
    • pcntl_getpriority - Get the priority of any process
    • pcntl_get_last_error - Retrieve the error number set by the last pcntl function which failed
    • pcntl_setpriority - Change the priority of any process
    • pcntl_signal - Installs a signal handler
    • pcntl_signal_dispatch - Calls signal handlers for pending signals
    • pcntl_signal_get_handler - Get the current handler for specified signal
    • pcntl_sigprocmask - Sets and retrieves blocked signals
    • pcntl_sigtimedwait - Waits for signals, with a timeout
    • pcntl_sigwaitinfo - Waits for signals
    • pcntl_strerror - Retrieve the system error message associated with the given errno
    • pcntl_wait - Waits on or returns the status of a forked child
    • pcntl_waitpid - Waits on or returns the status of a forked child
    • pcntl_wexitstatus - Returns the return code of a terminated child
    • pcntl_wifexited - Checks if status code represents a normal exit
    • pcntl_wifsignaled - Checks whether the status code represents a termination due to a signal
    • pcntl_wifstopped - Checks whether the child process is currently stopped
    • pcntl_wstopsig - Returns the signal which caused the child to stop
    • pcntl_wtermsig - Returns the signal which caused the child to terminate
    • PDO::beginTransaction - Inicia una transacción
    • PDO::commit - Consigna una transacción
    • PDO::cubrid_schema - Obtiene la información del esquema solicitada
    • PDO::errorCode - Obtiene un SQLSTATE asociado con la última operación en el manejador de la base de datos
    • PDO::errorInfo - Obtiene información extendida del error asociado con la última operación del manejador de la base de datos
    • PDO::exec - Ejecuta una sentencia SQL y devuelve el número de filas afectadas
    • PDO::getAttribute - Devuelve un atributo de la conexión a la base de datos
    • PDO::getAvailableDrivers - Devuelve un array con los controladores de PDO disponibles
    • PDO::inTransaction - Comprueba si una transacción está activa
    • PDO::lastInsertId - Devuelve el ID de la última fila o secuencia insertada
    • PDO::pgsqlCopyFromArray - Copiar datos de un array de PHP a una tabla
    • PDO::pgsqlCopyFromFile - Copiar datos de un fichero a una tabla
    • PDO::pgsqlCopyToArray - Copiar datos de una tabla de una base de datos a un array de PHP
    • PDO::pgsqlCopyToFile - Copiar datos desde una tabla a un fichero
    • PDO::pgsqlGetNotify - Obtener una notificación asíncrona
    • PDO::pgsqlGetPid - Obtener el PID del servidor
    • PDO::pgsqlLOBCreate - Crear un nuevo objeto grande
    • PDO::pgsqlLOBOpen - Abrir un flujo de un objeto grande existente
    • PDO::pgsqlLOBUnlink - Eliminar un objeto grande
    • PDO::prepare - Prepara una sentencia para su ejecución y devuelve un objeto sentencia
    • PDO::query - Ejecuta una sentencia SQL, devolviendo un conjunto de resultados como un objeto PDOStatement
    • PDO::quote - Entrecomilla una cadena de caracteres para usarla en una consulta
    • PDO::rollBack - Revierte una transacción
    • PDO::setAttribute - Establece un atributo
    • PDO::sqliteCreateAggregate - Registra una función acumuladora definida por el usuario para usarla en sentencias SQL
    • PDO::sqliteCreateCollation - Registra una función definida por el usuario para emplearla como función de cotejo en sentencias SQL
    • PDO::sqliteCreateFunction - Registra una función definida por el usuario para utilizarla en sentencias SQL
    • PDO::__construct - Crea una instancia de PDO que representa una conexión a una base de datos
    • PDOStatement::bindColumn - Vincula una columna a una variable de PHP
    • PDOStatement::bindParam - Vincula un parámetro al nombre de variable especificado
    • PDOStatement::bindValue - Vincula un valor a un parámetro
    • PDOStatement::closeCursor - Cierra un cursor, habilitando a la sentencia para que sea ejecutada otra vez
    • PDOStatement::columnCount - Devuelve el número de columnas de un conjunto de resultados
    • PDOStatement::debugDumpParams - Vuelca un comando preparado de SQL
    • PDOStatement::errorCode - Obtiene el SQLSTATE asociado con la última operación del gestor de sentencia
    • PDOStatement::errorInfo - Obtiene información ampliada del error asociado con la última operación del gestor de sentencia
    • PDOStatement::execute - Ejecuta una sentencia preparada
    • PDOStatement::fetch - Obtiene la siguiente fila de un conjunto de resultados
    • PDOStatement::fetchAll - Devuelve un array que contiene todas las filas del conjunto de resultados
    • PDOStatement::fetchColumn - Devuelve una única columna de la siguiente fila de un conjunto de resultados
    • PDOStatement::fetchObject - Obtiene la siguiente fila y la devuelve como un objeto
    • PDOStatement::getAttribute - Recupera un atributo de sentencia
    • PDOStatement::getColumnMeta - Devuelve metadatos de una columna de un conjunto de resultados
    • PDOStatement::nextRowset - Avanza hasta el siguiente conjunto de filas de un gestor de sentencia multiconjunto de filas
    • PDOStatement::rowCount - Devuelve el número de filas afectadas por la última sentencia SQL
    • PDOStatement::setAttribute - Establece un atributo de sentencia
    • PDOStatement::setFetchMode - Establece el modo de obtención para esta sentencia
    • PDO_DBLIB DSN - Conectarse a bases de datos de Microsoft SQL Server y Sybase
    • PDO_FIREBIRD DSN - Conectarse a bases de datos de Firebird
    • PDO_MYSQL DSN - Conectarse a bases de datos de MySQL
    • PDO_PGSQL DSN - Conectarse a bases de datos de PostgreSQL
    • PDO_SQLITE DSN - Conectar a las bases de datos de SQLite
    • pfsockopen - Abre Internet persistente o conexión de socket de dominio Unix
    • pg_affected_rows - Devuelve el número de registros afectados (filas)
    • pg_cancel_query - Cancelar una consulta asíncrona
    • pg_client_encoding - Obtiene la codificación del cliente
    • pg_close - Cierra una conexión PostgreSQL
    • pg_connect - Abre una conexión a PostgreSQL
    • pg_connection_busy - Permite saber si la conexión esta ocupada o no
    • pg_connection_reset - Restablece conexión (reconectar)
    • pg_connection_status - Obtener estado de la conexión
    • pg_connect_poll - Verifica el estado de un intento de conexión asíncrono en curso de PostgreSQL
    • pg_consume_input - Reads input on the connection
    • pg_convert - Conviertir valores de un array asociativo en valores adecuados para sentencias SQL
    • pg_copy_from - Insertar registros dentro de una tabla desde un array
    • pg_copy_to - Copiar una tabla a un array
    • pg_dbname - Obtiene el nombre de la base de datos
    • pg_delete - Borra registros
    • pg_end_copy - Sincronizar con PostgreSQL
    • pg_escape_bytea - Escapar un string para insertarlo en un campo bytea
    • pg_escape_identifier - Escape a identifier for insertion into a text field
    • pg_escape_literal - Escape a literal for insertion into a text field
    • pg_escape_string - Escape a string for query
    • pg_execute - Envía una solicitud para ejecutar una setencia preparada con parámetros dados, y espera el resultado
    • pg_fetch_all - Obtiene todas las filas de un resultado como un array
    • pg_fetch_all_columns - Fetches all rows in a particular result column as an array
    • pg_fetch_array - Fetch a row as an array
    • pg_fetch_assoc - Fetch a row as an associative array
    • pg_fetch_object - Fetch a row as an object
    • pg_fetch_result - Returns values from a result resource
    • pg_fetch_row - Get a row as an enumerated array
    • pg_field_is_null - Test if a field is SQL NULL
    • pg_field_name - Returns the name of a field
    • pg_field_num - Returns the field number of the named field
    • pg_field_prtlen - Returns the printed length
    • pg_field_size - Returns the internal storage size of the named field
    • pg_field_table - Returns the name or oid of the tables field
    • pg_field_type - Devuelve el nombre de tipo para el número de campo correspondiente
    • pg_field_type_oid - Returns the type ID (OID) for the corresponding field number
    • pg_flush - Flush outbound query data on the connection
    • pg_free_result - Free result memory
    • pg_get_notify - Gets SQL NOTIFY message
    • pg_get_pid - Obtiene la ID del proceso del backend
    • pg_get_result - Get asynchronous query result
    • pg_host - Devuelve el nombre de host asociado a la conexión
    • pg_insert - Insert array into table
    • pg_last_error - Obtiene una cadena con el último mensaje de error de la conexión
    • pg_last_notice - Devuelve el último aviso del servidor PostgreSQL
    • pg_last_oid - Returns the last row's OID
    • pg_lo_close - Close a large object
    • pg_lo_create - Create a large object
    • pg_lo_export - Export a large object to file
    • pg_lo_import - Import a large object from file
    • pg_lo_open - Open a large object
    • pg_lo_read - Read a large object
    • pg_lo_read_all - Reads an entire large object and send straight to browser
    • pg_lo_seek - Seeks position within a large object
    • pg_lo_tell - Returns current seek position a of large object
    • pg_lo_truncate - Truncates a large object
    • pg_lo_unlink - Delete a large object
    • pg_lo_write - Write to a large object
    • pg_meta_data - Get meta data for table
    • pg_num_fields - Returns the number of fields in a result
    • pg_num_rows - Returns the number of rows in a result
    • pg_options - Obtener las opciones asociadas con la conexión
    • pg_parameter_status - Looks up a current parameter setting of the server
    • pg_pconnect - Abre una conexión persistente a PostgreSQL
    • pg_ping - Ping a conexión de base de datos
    • pg_port - Devuelve el número de puerto asociado con la conexión
    • pg_prepare - Envía una solicitud para crear una sentencia preparada con los parámetros dados, y espera que se complete
    • pg_put_line - Send a NULL-terminated string to PostgreSQL backend
    • pg_query - Ejecutar una consulta
    • pg_query_params - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
    • pg_result_error - Get error message associated with result
    • pg_result_error_field - Returns an individual field of an error report
    • pg_result_seek - Set internal row offset in result resource
    • pg_result_status - Get status of query result
    • pg_select - Select records
    • pg_send_execute - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)
    • pg_send_prepare - Envía una solicitud para crear una instrucción preparada con los parámetros dados, sin esperar la finalización
    • pg_send_query - Sends asynchronous query
    • pg_send_query_params - Submits a command and separate parameters to the server without waiting for the result(s)
    • pg_set_client_encoding - Set the client encoding
    • pg_set_error_verbosity - Determines the verbosity of messages returned by pg_last_error and pg_result_error
    • pg_socket - Obtener un identificador de sólo lectura en el socket subyacente a una conexión de PostgreSQL
    • pg_trace - Enable tracing a PostgreSQL connection
    • pg_transaction_status - Devuelve el estado actual de la transaccion del servidor
    • pg_tty - Devolver el nombre TTY asociado con la conexión
    • pg_unescape_bytea - Unescape binary for bytea type
    • pg_untrace - Desactivar el rastreo de una conexión de PostgreSQL
    • pg_update - Actualizar tabla
    • pg_version - Devuelve un array con el cliente, protocolo y versión del servidor (si está disponible)
    • phar:// - Archivo PHP
    • Phar::addEmptyDir - Añadir un directorio vacío al archvo phar
    • Phar::addFile - Añadir un fichero desde el sistema de ficheros al archivo phar
    • Phar::addFromString - Añadir un fichero desde un string al archivo phar
    • Phar::apiVersion - Devolver la versión de la API
    • Phar::buildFromDirectory - Construir un archivo phar desde los ficheros de un directorio
    • Phar::buildFromIterator - Construir un archivo phar desde un iterador
    • Phar::canCompress - Devuelve si la extensión phar soporta la compresión usando zlib o bzip2
    • Phar::canWrite - Devolver si la extensión phar soporta la escritura y creación de archivos phar
    • Phar::compress - Comprimir el archivo Phar entero usando la compresión Gzip o Bzip2
    • Phar::compressFiles - Comprime todos los ficheros del archivo Phar actual
    • Phar::convertToData - Convertir un archivo phar en un fichero tar o zip no ejecutable
    • Phar::convertToExecutable - Convertir un archivo phar en otro formato de archivo phar ejecutable
    • Phar::copy - Copiar un fichero interno de un archivo phar a otro fichero nuevo dentro del phar
    • Phar::count - Devuelve el número de entradas (ficheros) en el archivo Phar
    • Phar::createDefaultStub - Crear una rutina de interoperabilidad específica del formato de fichero phar
    • Phar::decompress - Descomprimir un archivo Phar entero
    • Phar::decompressFiles - Descomprimir todos los ficheros del archivo Phar actual
    • Phar::delete - Borrar un fichero dentro de un archivo phar
    • Phar::delMetadata - Eliminar la metainformación global del phar
    • Phar::extractTo - Extraer el contenido de un archivo phar a un directorio
    • Phar::getAlias - Get the alias for Phar
    • Phar::getMetadata - Devolver la metainformación de un archivo phar
    • Phar::getModified - Devolver si el phar fue modificado
    • Phar::getPath - Get the real path to the Phar archive on disk
    • Phar::getSignature - Devolver la firma MD5/SHA1/SHA256/SHA512/OpenSSL de un archivo Phar
    • Phar::getStub - Devolver el cargador de PHP o la rutina de interoperabilidad de un archivo Phar
    • Phar::getSupportedCompression - Devolver un array de los algoritmos de compresión soportados
    • Phar::getSupportedSignatures - Devolver un array con los tipos de firmas soportados
    • Phar::getVersion - Devolver información de la versión del archivo Phar
    • Phar::hasMetadata - Devolver si el phar tiene metainformación global
    • Phar::interceptFileFuncs - Ordenar a phar interceptar fopen, file_get_contents, opendir, y todas las funciones relacionadas con estadísticas
    • Phar::isBuffering - Determinar si las operaciones de escritura de Phar está siendo almacenadas en buffer, o están siendo volcadas directamente al disco
    • Phar::isCompressed - Devuelve Phar::GZ oPHAR::BZ2 si el archivo phar entero está comprimido (.tar.gz/tar.bz, etc.)
    • Phar::isFileFormat - Devolver true si el archivo phar está basado en el formato de fichero tar/phar/zip dependiendo del parámetro
    • Phar::isValidPharFilename - Devolver si el nombre de fichero dado es un nombre de fichero phar válido
    • Phar::isWritable - Devolver si el archivo phar se puede modificar
    • Phar::loadPhar - Cargar cualquier archivo phar con un alias
    • Phar::mapPhar - Leer el fichero (un phar) que está en ejecución y registrar su manifiesto
    • Phar::mount - Montar un fichero o ruta externos en una ubicación virtual dentro de un archivo phar
    • Phar::mungServer - Definir una lista de hasta 4 variables $_SERVER que debería ser modificadas para la ejecución
    • Phar::offsetExists - Determina si un fichero existe en un phar
    • Phar::offsetGet - Obtener un objeto de la clase PharFileInfo para un fichero específico
    • Phar::offsetSet - Establecer el contenido de un fichero interno a aquel de un fichero externo
    • Phar::offsetUnset - Eliminar un fichero de un phar
    • Phar::running - Devolover la ruta completa del disco o el URL completo de phar del archivo Phar que está en ejecución
    • Phar::setAlias - Establecer el alias para un archivo Phar
    • Phar::setDefaultStub - Establecer el cargador o la rutina de interoperabilidad de un archivo Phar al cargador predeterminado
    • Phar::setMetadata - Establecer la metainformación de un archivo phar
    • Phar::setSignatureAlgorithm - Establecer el algoritmo de firma para un phar y aplicarlo
    • Phar::setStub - Establecer el cargador de PHP o la rutina de interoperabilidad de un archivo Phar
    • Phar::startBuffering - Iniciar las operaciones de escritura en buffer de Phar, no modifica el objeto Phar del disco
    • Phar::stopBuffering - Detener las peticiones de escritura en buffer del archivo Phar, y guardar los cambios en disco
    • Phar::unlinkArchive - Elimiar completamente un archivo phar del disco y de la memoria
    • Phar::webPhar - mapPhar para archivos phar basados en web. Controlador principal para aplicaciones web
    • Phar::__construct - Construir un objeto de archivo Phar
    • PharData::addEmptyDir - Añadir un directorio vacío al archivo tar/zip
    • PharData::addFile - Añadir un fichero desde el sistema de ficheros al archivo tar/zip
    • PharData::addFromString - Añadir un fichero desde el sistema de ficheros al archivo tar/zip
    • PharData::buildFromDirectory - Construir un archivo tar/zip desde los ficheros de un directorio
    • PharData::buildFromIterator - Construir un archivo tar o zip desde un iterador
    • PharData::compress - Comprimir el archivo tar/zip entero usando la compresión Gzip o Bzip2
    • PharData::compressFiles - Comprime todos los ficheros del archivo tar/zip actual
    • PharData::convertToData - Convertir un archivo phar en un fichero tar o zip no ejecutable
    • PharData::convertToExecutable - Convertir un archivo tar/zip no ejecutable en un archivo phar ejecutable
    • PharData::copy - Copiar un fichero interno de un archivo phar a otro fichero nuevo dentro del phar
    • PharData::decompress - Descomprimir un archivo Phar entero
    • PharData::decompressFiles - Descomprimir todos los ficheros del archivo zip actual
    • PharData::delete - Borrar un fichero dentro de un archivo tar/zip
    • PharData::delMetadata - Eliminar la metainformación global de un archivo zip
    • PharData::extractTo - Extraer el contenido de un archivo tar/zip a un directorio
    • PharData::isWritable - Devolver si el archivo tar/zip se puede modificar
    • PharData::offsetSet - Establecer el contenido de un fichero dentro de un tar/zip a aquel de un fichero o cadena externos
    • PharData::offsetUnset - Eliminar un ficerho de un archivo tar/zip
    • PharData::setAlias - función sin sentido (Phar::setAlias no es válido para PharData)
    • PharData::setDefaultStub - función sin sentido (Phar::setStub no es válido para PharData)
    • PharData::setStub - función sin sentido (Phar::setStub no es válido para PharData)
    • PharData::__construct - Construir un objeto de archivo tar o zip no ejecutable
    • PharException - La clase PharException ofrece una excepción de clase específica de phar para bloques try/catch
    • PharFileInfo::chmod - Esteblecer los bits de permiso específicos del fichero
    • PharFileInfo::compress - Comprimir la entrada del Phar actual con la compresión zlib o bzip2
    • PharFileInfo::decompress - Descomprimir la entrada Phar actual dentro del phar
    • PharFileInfo::delMetadata - Eliminar la metainformación de una entrada
    • PharFileInfo::getCompressedSize - Devolver el tamaño real de un fichero (con compresión) dentro de un archivo Phar
    • PharFileInfo::getContent - Get the complete file contents of the entry
    • PharFileInfo::getCRC32 - Devolver el códido CRC32 o lanzar una exepción si la CRC no ha sido verificado
    • PharFileInfo::getMetadata - Devolver la metainformación específica de un fichero almacenada con un fichero
    • PharFileInfo::getPharFlags - Devolver las banderas de una entrada de fichero
    • PharFileInfo::hasMetadata - Devolver la metainformación de una entrada
    • PharFileInfo::isCompressed - Devolver si la entrada está comprimida
    • PharFileInfo::isCRCChecked - Devolver si la entrada de fichero tiene su CRC verificada
    • PharFileInfo::setMetadata - Establecer la metainformación específica de un fichero almacenda con un fichero
    • PharFileInfo::__construct - Construir un objeto de entrada Phar
    • php:// - Acceso a distintos flujos de E/S
    • phpcredits - Imprime los créditos de PHP
    • phpdbg_break_file - Inserts a breakpoint at a line in a file
    • phpdbg_break_function - Inserts a breakpoint at entry to a function
    • phpdbg_break_method - Inserts a breakpoint at entry to a method
    • phpdbg_break_next - Inserts a breakpoint at the next opcode
    • phpdbg_clear - Clears all breakpoints
    • phpdbg_color - Sets the color of certain elements
    • phpdbg_end_oplog - Descripción
    • phpdbg_exec - Attempts to set the execution context
    • phpdbg_get_executable - Descripción
    • phpdbg_prompt - Sets the command prompt
    • phpdbg_start_oplog - Descripción
    • phpinfo - Muestra información sobre la configuración de PHP
    • phpversion - Obtiene la versión de PHP
    • php_ini_loaded_file - Recupera la ruta de acceso al archivo php.ini cargado
    • php_ini_scanned_files - Devuelve una lista de ficheros .ini procesados del directorio adicional ini
    • php_sapi_name - Devuelve el tipo de interfaz que hay entre PHP y el servidor
    • php_strip_whitespace - Devuelve el código fuente sin los comentarios y espacios blancos
    • php_uname - Devuelve información sobre el sistema operativo en que se está ejecutando PHP
    • php_user_filter::filter - Llamado cuando se aplica un filtro
    • php_user_filter::onClose - Llamado cuando se cierra el filtro
    • php_user_filter::onCreate - Llamado cuando se crea el filtro
    • pht\AtomicInteger::dec - Decrements the atomic integer's value by one
    • pht\AtomicInteger::get - Gets the atomic integer's value
    • pht\AtomicInteger::inc - Increments the atomic integer's value by one
    • pht\AtomicInteger::lock - Acquires the atomic integer's mutex lock
    • pht\AtomicInteger::set - Sets the atomic integer's value
    • pht\AtomicInteger::unlock - Releases the atomic integer's mutex lock
    • pht\AtomicInteger::__construct - AtomicInteger creation
    • pht\HashTable::lock - Acquires the hash table's mutex lock
    • pht\HashTable::size - Gets the size of the hash table
    • pht\HashTable::unlock - Releases the hash table's mutex lock
    • pht\Queue::front - Returns the first value from a queue
    • pht\Queue::lock - Acquires the queue's mutex lock
    • pht\Queue::pop - Pops a value off of the front of a queue
    • pht\Queue::push - Pushes a value to the end of a queue
    • pht\Queue::size - Gets the size of the queue
    • pht\Queue::unlock - Releases the queue's mutex lock
    • pht\Runnable::run - The entry point of a threaded class
    • pht\Thread::addClassTask - Class threading
    • pht\Thread::addFileTask - File threading
    • pht\Thread::addFunctionTask - Function threading
    • pht\Thread::join - Joins a thread
    • pht\Thread::start - Starts the new thread
    • pht\Thread::taskCount - Gets a thread's task count
    • pht\Threaded::lock - Acquires the mutex lock
    • pht\Threaded::unlock - Releases the mutex lock
    • pht\Vector::deleteAt - Deletes a value in the vector
    • pht\Vector::insertAt - Inserts a value into the vector
    • pht\Vector::lock - Acquires the vector's mutex lock
    • pht\Vector::pop - Pops a value to the vector
    • pht\Vector::push - Pushes a value to the vector
    • pht\Vector::resize - Resizes a vector
    • pht\Vector::shift - Shifts a value from the vector
    • pht\Vector::size - Gets the size of the vector
    • pht\Vector::unlock - Releases the vector's mutex lock
    • pht\Vector::unshift - Unshifts a value to the vector front
    • pht\Vector::updateAt - Updates a value in the vector
    • pht\Vector::__construct - Vector creation
    • pi - Obtener valor de pi
    • png2wbmp - Convertir un archivo de imagen PNG a un archivo de imagen WBMP
    • Pool::collect - Collect references to completed tasks
    • Pool::resize - Resize the Pool
    • Pool::shutdown - Shutdown all workers
    • Pool::submit - Submits an object for execution
    • Pool::submitTo - Submits a task to a specific worker for execution
    • Pool::__construct - Creates a new Pool of Workers
    • popen - Abre un proceso de un puntero a un fichero
    • pos - Alias de current
    • posix_access - Determinar la accesibilidad de un archivo
    • posix_ctermid - Obtener el nombre de la ruta del terminal controlador
    • posix_errno - Alias de posix_get_last_error
    • posix_getcwd - Nombre de la ruta del directorio actual
    • posix_getegid - Devuelve el ID efectivo de grupo del proceso actual
    • posix_geteuid - Devolver el ID efectivo de usuario del proceso actual
    • posix_getgid - Devuelve el ID real de grupo del proceso actual
    • posix_getgrgid - Devolver información sobre un grupo mediante un id de grupo
    • posix_getgrnam - Devolver información sobre un grupo mediante su nombre
    • posix_getgroups - Devolver el conjunto de grupos del proceso actual
    • posix_getlogin - Devuelve el nombre del inicio de sesión
    • posix_getpgid - Obtener el id del grupo de procesos para un control de trabajo
    • posix_getpgrp - Devolver el identificador de grupo de proceso actual
    • posix_getpid - Devolver el identificador del proceso actual
    • posix_getppid - Devolver el identificador del proceso padre
    • posix_getpwnam - Devolver información sobre un usuario mediante su nombre de usuario
    • posix_getpwuid - Devolver información sobre un usuario mediante su id de usuario
    • posix_getrlimit - Devolver información sobre los límites de recursos del sistema
    • posix_getsid - Obtener el sid actual del proceos
    • posix_getuid - Devolver el ID real de usuario del proceso actual
    • posix_get_last_error - Recuperar el número de error establecido por la última función posix que ha fallado
    • posix_initgroups - Calcular la lista de acceso al grupo
    • posix_isatty - Determinar si un descriptor de fichero es un terminal interactiva
    • posix_kill - Enviar una señal a un proceso
    • posix_mkfifo - Crear un archivo especial fifo (un pipe con nombre)
    • posix_mknod - Crear un fichero especial u ordinario (POSIX.1)
    • posix_setegid - Establecer el GID efectivo del proceso actual
    • posix_seteuid - Establecer el UID efectivo del proceso actual
    • posix_setgid - Establecer el GID de proceso actual
    • posix_setpgid - Establecer el id de grupo de procesos para el control de trabajo
    • posix_setrlimit - Establecer los límites de recursos del sistema
    • posix_setsid - Hacer del proceso actual un líder de sesión
    • posix_setuid - Establecer el UID del proceso actual
    • posix_strerror - Recuperar el mensaje de error del sistema asociado con el errno dado
    • posix_times - Obtener los tiempos de procesos
    • posix_ttyname - Determinar el nombre del dispositivo terminal
    • posix_uname - Obtener el nombre del sistema
    • pow - Expresión exponencial
    • preg_filter - Realiza una búsqueda y sustitución de una expresión regular
    • preg_grep - Devuelve entradas de matriz que coinciden con el patrón
    • preg_last_error - Devuelve el código de error de la última ejecución de expresión regular de PCRE
    • preg_last_error_msg - Returns the error message of the last PCRE regex execution
    • preg_match - Realiza una comparación con una expresión regular
    • preg_match_all - Realiza una comparación global de una expresión regular
    • preg_quote - Escapar caracteres en una expresión regular
    • preg_replace - Realiza una búsqueda y sustitución de una expresión regular
    • preg_replace_callback - Realiza una búsqueda y sustitución de una expresión regular usando una llamada de retorno
    • preg_replace_callback_array - Realizar una búsqueda y sustitución de expresión regular con retrollamadas
    • preg_split - Divide un string mediante una expresión regular
    • prev - Rebobina el puntero interno del array
    • print - Mostrar una cadena
    • printf - Imprimir una cadena con formato
    • print_r - Imprime información legible para humanos sobre una variable
    • proc_close - Cierra un proceso abierto mediante proc_open y devuelve el códido de salida de tal proceso
    • proc_get_status - Obtiene información sobre un proceso abierto por proc_open
    • proc_nice - Modificar la prioridad del proceso actual
    • proc_open - Ejecuta un comando y abre un puntero de fichero para entrada/salida
    • proc_terminate - Mata un proceso abierto mediante proc_open
    • property_exists - Comprueba si el objeto o la clase tienen una propiedad
    • pspell_add_to_personal - Añadir una palabra a la lista personal de palabras
    • pspell_add_to_session - Añadir la palabra a la lista de palabras en la sesión actual
    • pspell_check - Verificar una palabra
    • pspell_clear_session - Limpia la sesión actual
    • pspell_config_create - Crear una configuración usada para abrir un diccionario
    • pspell_config_data_dir - Ubicación de los ficheros de información de lenguaje
    • pspell_config_dict_dir - Ubicación de la lista principal de palabras
    • pspell_config_ignore - Ignorar palabras con menos de N caracteres
    • pspell_config_mode - Cambiar el modo de número de sugerencias devueltas
    • pspell_config_personal - Establecer un fichero que contiene una lista personal de palabras
    • pspell_config_repl - Establecer un fichero que contiene pares de sustitución
    • pspell_config_runtogether - Considerar las palabras unidas como compuestos válidos
    • pspell_config_save_repl - Deterinar si se guarda una lista de pares de sustitución junto con la lista de palabras
    • pspell_new - Cargar un nuevo diccionario
    • pspell_new_config - Cargar un nuevo diccionario con ajustes basados en una configuración dada
    • pspell_new_personal - Cargar un nuevo diccionario con una lista personal de palabras
    • pspell_save_wordlist - Guardar la lista de palabras personal a un fichero
    • pspell_store_replacement - Almacenar un par de sustitución de una palabra
    • pspell_suggest - Sugerir ortografías de una palabra
    • ps_add_bookmark - Añadir un marcapáginas a la página actual
    • ps_add_launchlink - Añadir un vínculo que lance un fichero
    • ps_add_locallink - Añadir un vínculo hacia una página del mismo documento
    • ps_add_note - Añadir una nota a la página actual
    • ps_add_pdflink - Añadir un vínculo hacia una página de un segundo documento PDF
    • ps_add_weblink - Añadir un vínculo hacia una ubicación web
    • ps_arc - Dibujar un arco en el sentido contrario a las agujas del reloj
    • ps_arcn - Dibujar un arco en el sentido de las agujas del reloj
    • ps_begin_page - Empezar una nueva página
    • ps_begin_pattern - Iniciar un nuevo patrón
    • ps_begin_template - Iniciar una nueva plantilla
    • ps_circle - Dibujar un círculo
    • ps_clip - Realizar un recorte utilizando el trazado actual
    • ps_close - Cerrar un documento PostScript
    • ps_closepath - Cerrar un trazado
    • ps_closepath_stroke - Cerrar y contornear un trazado
    • ps_close_image - Cerrar una imagen y liberar memoria
    • ps_continue_text - Continuar el texto en la siguiente línea
    • ps_curveto - Dibujar una curva
    • ps_delete - Borrar todos los recursos de un documento PostScript
    • ps_end_page - Finalizar una página
    • ps_end_pattern - Finalizar un patrón
    • ps_end_template - Finalizar una plantilla
    • ps_fill - Rellenar el trazado actual
    • ps_fill_stroke - Rellenar y contornear el trazado actual
    • ps_findfont - Cargar una fuente
    • ps_get_buffer - Obtener el buffer completo que contiene la información generada de PS
    • ps_get_parameter - Obtener ciertos parámetros
    • ps_get_value - Obtener ciertos valores
    • ps_hyphenate - Particionar silábicamente una palabra
    • ps_include_file - Leer un fichero externo con código PostScript sin tratar
    • ps_lineto - Dibujar una línea
    • ps_makespotcolor - Crear un color directo
    • ps_moveto - Establecer el punto actual
    • ps_new - Crear un nuevo objeto de documento PostScript
    • ps_open_file - Abrir un fichero para su impresión
    • ps_open_image - Leer una imagen para su colocación posterior
    • ps_open_image_file - Abre una imagen desde un fichero
    • ps_open_memory_image - Tomar una imagen de GD y devolverla como una imagen para colcarla en un documento PS
    • ps_place_image - Colocar una imágen en la página
    • ps_rect - Dibujar un rectángulo
    • ps_restore - Restaurar un contexto previamente guardado
    • ps_rotate - Establecer el factor de rotación
    • ps_save - Guardar el contexto actual
    • ps_scale - Estalecer el factor de escala
    • ps_setcolor - Establecer el color actual
    • ps_setdash - Establecer la apariencia de una línea discontinua
    • ps_setflat - Establecer la planicidad
    • ps_setfont - Establecer la fuente a usar para la siguiente impresión
    • ps_setgray - Establecer el valor de gris
    • ps_setlinecap - Establecer la apariencia de los extremos de línea
    • ps_setlinejoin - Establecer cómo están unidas las líneas conectadas
    • ps_setlinewidth - Establecer el ancho de una línea
    • ps_setmiterlimit - Establecer el límite del inglete
    • ps_setoverprintmode - Establecer el modo de sobreimpresión
    • ps_setpolydash - Establecer la apariencia de una línea discontinua
    • ps_set_border_color - Establecer el color del borde de las anotaciones
    • ps_set_border_dash - Establece la longitud de las rayas del borde de las anotaciones
    • ps_set_border_style - Establecer el estilo del borde de las anotaciones
    • ps_set_info - Establecer los campos de información del documento
    • ps_set_parameter - Establecer ciertos parámetros
    • ps_set_text_pos - Establecer la posición de la salida de texto
    • ps_set_value - Establecer ciertos valores
    • ps_shading - Crear un sombreado para su uso posterior
    • ps_shading_pattern - Crear un patrón basado en un sombreado
    • ps_shfill - Rellenar un área con un sombreado
    • ps_show - Imprimir texto
    • ps_show2 - Imprimir texto en la posición actual
    • ps_show_boxed - Imprimir texto en una caja
    • ps_show_xy - Imprimir texto en una posición dada
    • ps_show_xy2 - Imprimir texto en una posición
    • ps_stringwidth - Obtener el ancho de una cadena
    • ps_string_geometry - Establecer la geometría de una cadena de caracteres
    • ps_stroke - Dibujar el trazado actual
    • ps_symbol - Imprimir un glifo
    • ps_symbol_name - Obtener el nombre de un glifo
    • ps_symbol_width - Obtener el ancho de un glifo
    • ps_translate - Establecer una traslación
    • putenv - Establece el valor de una variable de entorno
    • px_close - Cerrar una base de datos paradox
    • px_create_fp - Crear una nueva base de datos paradox
    • px_date2string - Convierte una fecha en una cadena.
    • px_delete - Eliminar los recursos de la base de datos paradox
    • px_delete_record - Eliminar los registros de base de datos paradox
    • px_get_field - Devuelve la especificación de un solo campo
    • px_get_info - Devuelve una gran cantidad de información sobre un archivo paradox
    • px_get_parameter - Obtener un parámetro
    • px_get_record - Devuelve registro de base de datos paradox
    • px_get_schema - Devuelve la definición de la base de datos (schema)
    • px_get_value - Obtener un valor
    • px_insert_record - Inserta registro en base de datos paradox
    • px_new - Crear un nuevo objeto paradox
    • px_numfields - Devuelve el número de campos en una base de datos
    • px_numrecords - Devuelve el número de registros en una base de datos
    • px_open_fp - Abrir base de datos paradox
    • px_put_record - Almacenar registro en la base de datos paradox
    • px_retrieve_record - Devolver registro de base de datos paradox
    • px_set_blob_file - Establecer el archivo desde donde los blobs se van a leer
    • px_set_parameter - Establecer un parámetro
    • px_set_tablename - Establecer el nombre de una tabla (obsoleto)
    • px_set_targetencoding - Establecer la codificación de los campos de caracteres (obsoleto)
    • px_set_value - Establecer un valor
    • px_timestamp2string - Convertir la fecha y la hora en una cadena.
    • px_update_record - Actualizar el registro en la base de datos paradox
  • q
    • QuickHashIntHash::add - Este método añade una nueva entrada al hash
    • QuickHashIntHash::delete - Este método elimina una entrada de un hash
    • QuickHashIntHash::exists - Este método comprueba si la clave es parte del hash
    • QuickHashIntHash::get - Este método recupera un valor a partir del hash por su clave
    • QuickHashIntHash::getSize - Devuelve el número de elementos de un hash
    • QuickHashIntHash::loadFromFile - Este método de fabricación crea un hash desde un fichero
    • QuickHashIntHash::loadFromString - Este método de fabricación crea un hash dedsde una cadena de caracteres
    • QuickHashIntHash::saveToFile - Este método almacena un hash en memoria en disco
    • QuickHashIntHash::saveToString - Este método devuelve una versión serializada del hash
    • QuickHashIntHash::set - Este método actualiza una entrada del hash con un nuevo valor, o añade una nueva si la entrada no existe
    • QuickHashIntHash::update - Este método actualiza una entrada del hash con un nuevo valor
    • QuickHashIntHash::__construct - Crea un nuevo objeto QuickHashIntHash
    • QuickHashIntSet::add - Este método añade una nuevas entrada al conjunto
    • QuickHashIntSet::delete - Este método elimina una entrada de un conjunto
    • QuickHashIntSet::exists - Este método comprueba si una clave es parte de un conjunto
    • QuickHashIntSet::getSize - Devuelve el número de elementos del conjunto
    • QuickHashIntSet::loadFromFile - Este método de fabricación crear un conjunto desde un fichero
    • QuickHashIntSet::loadFromString - Este método de fabricación crea un conjunto desde una cadena de caracteres
    • QuickHashIntSet::saveToFile - Este método almacena un conjunto que está en la memoria en el disco
    • QuickHashIntSet::saveToString - Este método devuelve una versión serializada del conjunto
    • QuickHashIntSet::__construct - Crea un nuevo objeto QuickHashIntSet
    • QuickHashIntStringHash::add - Este método añade una nueva entrada a un hash
    • QuickHashIntStringHash::delete - Este método elimina una entrada del hash
    • QuickHashIntStringHash::exists - Este método comprueba si una clave es parte de un hash
    • QuickHashIntStringHash::get - Este método recupera un valor de un hash mediante su clave
    • QuickHashIntStringHash::getSize - Devuelve el número de elementos de un hash
    • QuickHashIntStringHash::loadFromFile - Este método de fabricación crea un hash desde un fichero
    • QuickHashIntStringHash::loadFromString - Este método de fabricación crea un hash desde una cadena de caracteres
    • QuickHashIntStringHash::saveToFile - Este método almacena un hash que esté en memoria en el disco
    • QuickHashIntStringHash::saveToString - Este método devuelve una versión serializada del hash
    • QuickHashIntStringHash::set - Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe
    • QuickHashIntStringHash::update - Este método actualiza una entrada de un hash con un nuevo valor
    • QuickHashIntStringHash::__construct - Crea un nuevo objeto QuickHashIntStringHash
    • QuickHashStringIntHash::add - Este método añade una nueva entrada a un hash
    • QuickHashStringIntHash::delete - Este método elimina una entrada del hash
    • QuickHashStringIntHash::exists - Este método comprueba si una clave es parte de un hash
    • QuickHashStringIntHash::get - Este método recupera un valor de un hash mediante su clave
    • QuickHashStringIntHash::getSize - Devuelve el número de elementos de un hash
    • QuickHashStringIntHash::loadFromFile - Este método de fabricación crea un hash desde un fichero
    • QuickHashStringIntHash::loadFromString - Este método de fabricación crea un hash desde una cadena de caracteres
    • QuickHashStringIntHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashStringIntHash::saveToString - Este método devuelve una versión serializada del hash
    • QuickHashStringIntHash::set - Este método actualiza una entrada de un hash con un nuevo valor, o añade una nueva si la entrada no existe
    • QuickHashStringIntHash::update - Este método actualiza una entrada de un hash con un nuevo valor
    • QuickHashStringIntHash::__construct - Crea un nuevo objeto QuickHashStringIntHash
    • quoted_printable_decode - Convierte un string quoted-printable en un string de 8 bits
    • quoted_printable_encode - Convierte un string de 8 bits en un string quoted-printable
    • quotemeta - Escapa meta caracteres
  • r
    • rad2deg - Convierte el número en radianes a su equivalente en grados
    • radius_acct_open - Crea un manejador Radius para el conteo
    • radius_add_server - Adds a server
    • radius_auth_open - Crea un identificador de Radius para la autenticación
    • radius_close - Libera todos los recursos
    • radius_config - Causes the library to read the given configuration file
    • radius_create_request - Create accounting or authentication request
    • radius_cvt_addr - Converts raw data to IP-Address
    • radius_cvt_int - Converts raw data to integer
    • radius_cvt_string - Converts raw data to string
    • radius_demangle - Demangles data
    • radius_demangle_mppe_key - Derives mppe-keys from mangled data
    • radius_get_attr - Extracts an attribute
    • radius_get_tagged_attr_data - Extracts the data from a tagged attribute
    • radius_get_tagged_attr_tag - Extracts the tag from a tagged attribute
    • radius_get_vendor_attr - Extracts a vendor specific attribute
    • radius_put_addr - Attaches an IP address attribute
    • radius_put_attr - Attaches a binary attribute
    • radius_put_int - Attaches an integer attribute
    • radius_put_string - Attaches a string attribute
    • radius_put_vendor_addr - Attaches a vendor specific IP address attribute
    • radius_put_vendor_attr - Attaches a vendor specific binary attribute
    • radius_put_vendor_int - Attaches a vendor specific integer attribute
    • radius_put_vendor_string - Attaches a vendor specific string attribute
    • radius_request_authenticator - Returns the request authenticator
    • radius_salt_encrypt_attr - Salt-encrypts a value
    • radius_send_request - Sends the request and waits for a reply
    • radius_server_secret - Returns the shared secret
    • radius_strerror - Devuelve un mensaje de error
    • rand - Genera un número entero aleatorio
    • random_bytes - Genera bytes seudoaleatorios criptográficamente seguros
    • random_int - Genera números enteros seudoaleatorios criptográficamente seguros
    • range - Crear un array que contiene un rango de elementos
    • rar:// - RAR
    • RarArchive::close - Cerrar archivo RAR y liberar todos los recursos
    • RarArchive::getComment - Obtener comentarios de texto desde el archivo RAR
    • RarArchive::getEntries - Obtener la lista completa de entradas del archivo RAR
    • RarArchive::getEntry - Obtener el objeto entrada desde el archivo RAR
    • RarArchive::isBroken - Comprobar si un archivo está dañado (incompleto)
    • RarArchive::isSolid - Comprueba si el archivo RAR es sólido
    • RarArchive::open - Abre un archivo RAR
    • RarArchive::setAllowBroken - Determina si la apertura de archivos dañados se permite
    • RarArchive::__toString - Obtener representación de texto
    • RarEntry::extract - Extraer entrada del archivo
    • RarEntry::getAttr - Obtener los atributos de la entrada
    • RarEntry::getCrc - Obtener el CRC de la entrada
    • RarEntry::getFileTime - Devolver entrada última fecha de modificación
    • RarEntry::getHostOs - Obtener sistema operativo anfitrión del archivo de entrada
    • RarEntry::getMethod - Obtener método pack de la entrada
    • RarEntry::getName - Obtener el nombre de la entrada
    • RarEntry::getPackedSize - Obtiene el tamaño empaquetado de la entrada
    • RarEntry::getStream - Obtener manejador de archivo para entrada
    • RarEntry::getUnpackedSize - Obtener el tamaño descomprimido de la entrada
    • RarEntry::getVersion - Obtener la versión mínima del programa RAR requerida para desempaquetar la entrada
    • RarEntry::isDirectory - Comprobar si una entrada representa un directorio
    • RarEntry::isEncrypted - Comprobar si una entrada está cifrada
    • RarEntry::__toString - Obtener texto representación de entrada
    • RarException::isUsingExceptions - Comprobar si el manejador de errores con excepciones está en uso
    • RarException::setUsingExceptions - Activar y desactivar el manejador de errores con excepciones
    • rar_wrapper_cache_stats - Caché de aciertos y errores del URL wrapper
    • rawurldecode - Decodificar cadenas codificadas estilo URL
    • rawurlencode - Codificar estilo URL de acuerdo al RFC 3986
    • readdir - Lee una entrada desde un gestor de directorio
    • readfile - Realizar la salida de un fichero
    • readgzfile - Muestra un archivo gz
    • readline - Lee una línea
    • readline_add_history - Agrega una línea a la historia
    • readline_callback_handler_install - Inicializa la interfaz de llamada de readline y la terminal, imprime el mensaje y retorna inmediatamente
    • readline_callback_handler_remove - Elimina una interfaz de llamada anteriormente agregada y retaura la configuración de terminal
    • readline_callback_read_char - Lee un carácter e informa a la interfaz de llamada de readline cuando una línea es recibida
    • readline_clear_history - Limpia el historial
    • readline_completion_function - Registra una función de autocompletado
    • readline_info - Obtiene/Modifica variables internas a readline
    • readline_list_history - Obtener el historial
    • readline_on_new_line - Informar a readline que el cursor se ha movido a una nueva línea
    • readline_read_history - Lee el historial
    • readline_redisplay - Redibuja la vista
    • readline_write_history - Escribe el historial
    • readlink - Devuelve el objetivo de un enlace simbólico
    • read_exif_data - Alias de exif_read_data
    • realpath - Devuelve el nombre de la ruta absoluta canonizado
    • realpath_cache_get - Obtiene las entradas de la caché de la ruta real
    • realpath_cache_size - Obtiene el tamaño de la caché de la ruta real
    • recode - Alias de recode_string
    • recode_file - Recodificar de fichero a fichero según la petición de recoficación
    • recode_string - Recodifica un string según una petición de recodificación
    • RecursiveArrayIterator::getChildren - Devuelve un iterador para la entrada actual si este es un array o un object
    • RecursiveArrayIterator::hasChildren - Devuelve si la entrada actual es un array o un objeto
    • RecursiveCachingIterator::getChildren - Devuelve los iteradores internos hijos como un RecursiveCachingIterator
    • RecursiveCachingIterator::hasChildren - Comprueba si el elemento actual de un iterador interno tiene hijos
    • RecursiveCachingIterator::__construct - Construct
    • RecursiveCallbackFilterIterator::getChildren - D3evuelve los iteradores internos hijos contenidos en un RecursiveCallbackFilterIterator
    • RecursiveCallbackFilterIterator::hasChildren - Comprueba si los iteradores internos del elemento actual tiene hijos
    • RecursiveCallbackFilterIterator::__construct - Crear un RecursiveCallbackFilterIterator desde un RecursiveIterator
    • RecursiveDirectoryIterator::getChildren - Devuelve un iterador de la entrada actual si se trata de un directorio
    • RecursiveDirectoryIterator::getSubPath - Obtiene sub ruta
    • RecursiveDirectoryIterator::getSubPathname - Obtiene la sub ruta y nombre
    • RecursiveDirectoryIterator::hasChildren - Devuelve si la entrada actual es un directorio y no '.' o '..'
    • RecursiveDirectoryIterator::key - Devuelve la ruta y nombre de fichero del directorio
    • RecursiveDirectoryIterator::next - Mover a la siguiente entrada
    • RecursiveDirectoryIterator::rewind - Rebobina el directorio hasta el inicio
    • RecursiveDirectoryIterator::__construct - Construye un RecursiveDirectoryIterator
    • RecursiveFilterIterator::getChildren - Devuelve los hijos del iterador interno contenidos en un RecursiveFilterIterator
    • RecursiveFilterIterator::hasChildren - Comprueba si el elemento actual del iterador interno tiene hijos
    • RecursiveFilterIterator::__construct - Crear un RecursiveFilterIterator a partir de un RecursiveIterator
    • RecursiveIterator::getChildren - Devuelve un iterador para la entrada actual
    • RecursiveIterator::hasChildren - Retorna si un iterador puede ser creado para la entrada actual
    • RecursiveIteratorIterator::beginChildren - Inicio del hijo
    • RecursiveIteratorIterator::beginIteration - Inicio de la iteración
    • RecursiveIteratorIterator::callGetChildren - Obtener hijo
    • RecursiveIteratorIterator::callHasChildren - Comprueba si tiene hijos
    • RecursiveIteratorIterator::current - Acceder al valor del elemento actual
    • RecursiveIteratorIterator::endChildren - Final de los hijos
    • RecursiveIteratorIterator::endIteration - Final de la iteración
    • RecursiveIteratorIterator::getDepth - Obtener la profundidad actual de la iteración recursiva
    • RecursiveIteratorIterator::getInnerIterator - Obtener el iterador interno
    • RecursiveIteratorIterator::getMaxDepth - Obtener el máximo de profundidad
    • RecursiveIteratorIterator::getSubIterator - El subiterador activo actual
    • RecursiveIteratorIterator::key - Acceder a la clave actual
    • RecursiveIteratorIterator::next - Moverse al siguiente elemento
    • RecursiveIteratorIterator::nextElement - Siguiente elemento
    • RecursiveIteratorIterator::rewind - Rebobina el iterador al primer elemento al nivel superior del iterador interno
    • RecursiveIteratorIterator::setMaxDepth - Establecer el máximo de profundidad
    • RecursiveIteratorIterator::valid - Comprueba si la posición actual es válida
    • RecursiveIteratorIterator::__construct - Construir un objeto RecursiveIteratorIterator
    • RecursiveRegexIterator::getChildren - Devuelve un iterador para la entrada actual
    • RecursiveRegexIterator::hasChildren - Retorna si un iterador puede ser obtenido de la entrada actual
    • RecursiveRegexIterator::__construct - Crea un nuevo RecursiveRegexIterator
    • RecursiveTreeIterator::beginChildren - Inicio de los hijos
    • RecursiveTreeIterator::beginIteration - Inicio de la iteración
    • RecursiveTreeIterator::callGetChildren - Obtener los hijos
    • RecursiveTreeIterator::callHasChildren - Comprobar si tiene hijos
    • RecursiveTreeIterator::current - Obtener el elemento actual
    • RecursiveTreeIterator::endChildren - Final de los hijos
    • RecursiveTreeIterator::endIteration - Fin de la iteración
    • RecursiveTreeIterator::getEntry - obtener la entrada actual
    • RecursiveTreeIterator::getPostfix - Obtiener el postfijo
    • RecursiveTreeIterator::getPrefix - Obtener el prefijo
    • RecursiveTreeIterator::key - Obtiene la clave de el elemento actual
    • RecursiveTreeIterator::next - Mover al siguiente elemento
    • RecursiveTreeIterator::nextElement - Comprueba si hay un siguiente elemento
    • RecursiveTreeIterator::rewind - Rebobina el iterador
    • RecursiveTreeIterator::setPostfix - Set postfix
    • RecursiveTreeIterator::setPrefixPart - Establece la parte de el prefijo
    • RecursiveTreeIterator::valid - Comprueba la validez
    • RecursiveTreeIterator::__construct - Construye un nuevo RecursiveTreeIterator
    • Reflection::export - Exportar
    • Reflection::getModifierNames - Obtener nombres de modificadores
    • ReflectionClass::export - Exporta una clase
    • ReflectionClass::getConstant - Obtener una constante definida
    • ReflectionClass::getConstants - Obtener constantes
    • ReflectionClass::getConstructor - Obtiene el constructor de una clase
    • ReflectionClass::getDefaultProperties - Obtener propiedades predeterminadas
    • ReflectionClass::getDocComment - Obtener los comentarios de documentación
    • ReflectionClass::getEndLine - Consultar línea final
    • ReflectionClass::getExtension - Obtiene un objeto ReflectionExtension para la extensión que definió la clase
    • ReflectionClass::getExtensionName - Obtiene el nombre de la extensión que definió una clase
    • ReflectionClass::getFileName - Obtiene el nombre de fichero en el que está definida la clase
    • ReflectionClass::getInterfaceNames - Obtiene nombres de las interfaces
    • ReflectionClass::getInterfaces - Obtiene las interfaces
    • ReflectionClass::getMethod - Obtiene un objeto ReflectionMethod para un método de una clase
    • ReflectionClass::getMethods - Obtiene un array de métodos
    • ReflectionClass::getModifiers - Obtiene los modificadores de clase
    • ReflectionClass::getName - Obtiene el nombre de la clase
    • ReflectionClass::getNamespaceName - Obtiene el nombre del espacio de nombres
    • ReflectionClass::getParentClass - Obtiene la clase padre
    • ReflectionClass::getProperties - Obtiene las propiedades
    • ReflectionClass::getProperty - Obtiene un objeto ReflectionProperty para una propiedad de una clase
    • ReflectionClass::getReflectionConstant - Gets a ReflectionClassConstant for a class's constant
    • ReflectionClass::getReflectionConstants - Gets class constants
    • ReflectionClass::getShortName - Obtiene el nombre abreviado
    • ReflectionClass::getStartLine - Obtiene el número de linea de inicio
    • ReflectionClass::getStaticProperties - Obtiene las propiedades estáticas
    • ReflectionClass::getStaticPropertyValue - Obtiene el valor de una propiedad estática
    • ReflectionClass::getTraitAliases - Obtiene un array con los alias usados con los traits
    • ReflectionClass::getTraitNames - Devuelve un array con los nombres de los traits usados por esta clase
    • ReflectionClass::getTraits - Obtiene un array con los traits que utiliza esta clase
    • ReflectionClass::hasConstant - Comprueba si una constante está o no definida
    • ReflectionClass::hasMethod - Comprueba si un método está o no definido
    • ReflectionClass::hasProperty - Comprueba si una propiedad está o no definida
    • ReflectionClass::implementsInterface - Comprueba si se implementa una determinada interfaz
    • ReflectionClass::inNamespace - Comprueba si pertenece a un determinado espacio de nombres
    • ReflectionClass::isAbstract - Comprueba si la clase es abstracta
    • ReflectionClass::isAnonymous - Checks if class is anonymous
    • ReflectionClass::isCloneable - Comprueba si la clase es o no clonable
    • ReflectionClass::isFinal - Comprueba si la clase inal
    • ReflectionClass::isInstance - Comprueba si un objeto es instancia de la clase
    • ReflectionClass::isInstantiable - Comprueba si una clase es instanciable
    • ReflectionClass::isInterface - Comprueba una la clase es una interfaz
    • ReflectionClass::isInternal - Comprueba si una clase está definida internamente por una extensión o por el núcleo
    • ReflectionClass::isIterable - Check whether this class is iterable
    • ReflectionClass::isIterateable - Comprueba si es iterable
    • ReflectionClass::isSubclassOf - Comprueba si es una subclase
    • ReflectionClass::isTrait - Comprueba si es un trait
    • ReflectionClass::isUserDefined - Comprueba si es una clase definida por el usuario
    • ReflectionClass::newInstance - Crea una nueva instancia de clase a partir de la lista de parámetros dados
    • ReflectionClass::newInstanceArgs - Crea una nueva instancia de clase a partir de los argumentos dados
    • ReflectionClass::newInstanceWithoutConstructor - Crea una nueva clase sin invocar al constructor
    • ReflectionClass::setStaticPropertyValue - Establece el valor de una propiedad estática
    • ReflectionClass::__construct - Construye un objeto de tipo ReflectionClass
    • ReflectionClass::__toString - Devuelve la representación en forma de string del objeto ReflectionClass
    • ReflectionClassConstant::export - Export
    • ReflectionClassConstant::getDeclaringClass - Gets declaring class
    • ReflectionClassConstant::getDocComment - Gets doc comments
    • ReflectionClassConstant::getModifiers - Gets the class constant modifiers
    • ReflectionClassConstant::getName - Get name of the constant
    • ReflectionClassConstant::getValue - Gets value
    • ReflectionClassConstant::isPrivate - Checks if class constant is private
    • ReflectionClassConstant::isProtected - Checks if class constant is protected
    • ReflectionClassConstant::isPublic - Checks if class constant is public
    • ReflectionClassConstant::__construct - Constructs a ReflectionClassConstant
    • ReflectionClassConstant::__toString - Returns the string representation of the ReflectionClassConstant object
    • ReflectionExtension::export - Exportar
    • ReflectionExtension::getClasses - Obtiene clases
    • ReflectionExtension::getClassNames - Obtiene nombres de las clases
    • ReflectionExtension::getConstants - Obtiene las constantes
    • ReflectionExtension::getDependencies - Obtiene las dependencias
    • ReflectionExtension::getFunctions - Obtiene las funciones de una extensión
    • ReflectionExtension::getINIEntries - Obtiene las entradas INI de la extensión
    • ReflectionExtension::getName - Obtiene el nombre de la extensión
    • ReflectionExtension::getVersion - Obtiene la versión de una extensión
    • ReflectionExtension::info - Imprime información sobre la extensión
    • ReflectionExtension::isPersistent - Indica si la extensión es persistente
    • ReflectionExtension::isTemporary - Indica si la extensión es temporal
    • ReflectionExtension::__clone - Clonar
    • ReflectionExtension::__construct - Constructor de los objetos ReflectionExtension
    • ReflectionExtension::__toString - Convertir a string
    • ReflectionFunction::export - Exporta una función
    • ReflectionFunction::getClosure - Genera dinámicamente una función anónima de esta función
    • ReflectionFunction::invoke - Invoca una función
    • ReflectionFunction::invokeArgs - Invoca a la función con argumentos
    • ReflectionFunction::isDisabled - Comprueba si una función está desactivada
    • ReflectionFunction::__construct - Contruye un objeto de tipo ReflectionFunction
    • ReflectionFunction::__toString - Convertir a string
    • ReflectionFunctionAbstract::getClosureScopeClass - Devuelve el ámbito asociado al cierre
    • ReflectionFunctionAbstract::getClosureThis - Devuelve una función anónima que apunta a esta función
    • ReflectionFunctionAbstract::getDocComment - Obtiene comentarios de documentación
    • ReflectionFunctionAbstract::getEndLine - Obtiene número de linea final
    • ReflectionFunctionAbstract::getExtension - Obtiene información sobre la extensión
    • ReflectionFunctionAbstract::getExtensionName - Obtiene el nombre de la extensión
    • ReflectionFunctionAbstract::getFileName - Obtiene el nombre del fichero
    • ReflectionFunctionAbstract::getName - Obtiene el nombre de la función
    • ReflectionFunctionAbstract::getNamespaceName - Obtiene el nombre del espacio de nombres
    • ReflectionFunctionAbstract::getNumberOfParameters - Obtiene el número total de parámetros
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters - Obtiene el número de parámetros obligatorios
    • ReflectionFunctionAbstract::getParameters - Obtiene los parámetros
    • ReflectionFunctionAbstract::getReturnType - Gets the specified return type of a function
    • ReflectionFunctionAbstract::getShortName - Obtiene el nombre abreviado de la función
    • ReflectionFunctionAbstract::getStartLine - Obtiene el número de la línea de inicio
    • ReflectionFunctionAbstract::getStaticVariables - Obtiene las variable estáticas
    • ReflectionFunctionAbstract::hasReturnType - Checks if the function has a specified return type
    • ReflectionFunctionAbstract::inNamespace - Comprueba si pertenece a un espacio de nombres
    • ReflectionFunctionAbstract::isClosure - Comprobar si es un cierre
    • ReflectionFunctionAbstract::isDeprecated - Comprueba si está obsoleta
    • ReflectionFunctionAbstract::isGenerator - Devuelve si la función es un generador
    • ReflectionFunctionAbstract::isInternal - Comprueba si la función es interna
    • ReflectionFunctionAbstract::isUserDefined - Comprueba si es una función definida por un usuario
    • ReflectionFunctionAbstract::isVariadic - Comprueba si la función es varíadica
    • ReflectionFunctionAbstract::returnsReference - Comprueba si devuelve una referencia
    • ReflectionFunctionAbstract::__clone - Clona una función
    • ReflectionFunctionAbstract::__toString - Convertir a texto
    • ReflectionGenerator::getExecutingFile - Gets the file name of the currently executing generator
    • ReflectionGenerator::getExecutingGenerator - Gets the executing Generator object
    • ReflectionGenerator::getExecutingLine - Gets the currently executing line of the generator
    • ReflectionGenerator::getFunction - Gets the function name of the generator
    • ReflectionGenerator::getThis - Gets the $this value of the generator
    • ReflectionGenerator::getTrace - Gets the trace of the executing generator
    • ReflectionGenerator::__construct - Constructs a ReflectionGenerator object
    • ReflectionMethod::export - Exporta un objeto de tipo ReflectionMethod
    • ReflectionMethod::getClosure - Devuelve un cierre creado dinámicamente para este método
    • ReflectionMethod::getDeclaringClass - Obtiene la clase en la que se ha declarado el método
    • ReflectionMethod::getModifiers - Obtiene los modificadores del método
    • ReflectionMethod::getPrototype - Obtiene el prototipo del método (si lo hubiera)
    • ReflectionMethod::invoke - Invoca un método
    • ReflectionMethod::invokeArgs - Invoca un método con argumentos
    • ReflectionMethod::isAbstract - Comprueba si el método es abstracto
    • ReflectionMethod::isConstructor - Comprueba si el método es un constructor
    • ReflectionMethod::isDestructor - Comprueba si el método es un destructor
    • ReflectionMethod::isFinal - Comprueba si el método es final
    • ReflectionMethod::isPrivate - Comprueba si el método es privado
    • ReflectionMethod::isProtected - Comprueba si el método está protegido
    • ReflectionMethod::isPublic - Comprueba si el método es público
    • ReflectionMethod::isStatic - Comprueba si el método es estático
    • ReflectionMethod::setAccessible - Asigna la accesibilidad del método
    • ReflectionMethod::__construct - Construye un objeto ReflectionMethod
    • ReflectionMethod::__toString - Devuelve la representación en forma de texto de este objeto
    • ReflectionNamedType::getName - Get the text of the type hint
    • ReflectionNamedType::isBuiltin - Checks if it is a built-in type
    • ReflectionObject::export - Exportación
    • ReflectionObject::__construct - Construye un ReflectionObject
    • ReflectionParameter::allowsNull - Comprueba si null es permitido
    • ReflectionParameter::canBePassedByValue - Devuelve si este parámetro de puede pasar por valor
    • ReflectionParameter::export - Exportar
    • ReflectionParameter::getClass - Obtener la clase con declaraciones de tipos
    • ReflectionParameter::getDeclaringClass - Obtiene declaración de la clase
    • ReflectionParameter::getDeclaringFunction - Obtiene declaración de función
    • ReflectionParameter::getDefaultValue - Obtiene el valor del parámetro por defecto
    • ReflectionParameter::getDefaultValueConstantName - Devuelve el nombre de la consntante del valor predeterminado si el valor predeterminado es constante o null
    • ReflectionParameter::getName - Obtener el nombre del parámetro
    • ReflectionParameter::getPosition - Obtiene la posición del parámetro
    • ReflectionParameter::getType - Gets a parameter's type
    • ReflectionParameter::hasType - Checks if parameter has a type
    • ReflectionParameter::isArray - Comprueba si el parámetro espera un array
    • ReflectionParameter::isCallable - Devuelve si el parámetro DEBE ser de tipo callable
    • ReflectionParameter::isDefaultValueAvailable - Comprueba si el valor por defecto está disponible
    • ReflectionParameter::isDefaultValueConstant - Devuelve si el valor predeterminado de este parámetro es constante
    • ReflectionParameter::isOptional - Comprueba si es opcional
    • ReflectionParameter::isPassedByReference - Comprueba si es pasado por referencia
    • ReflectionParameter::isVariadic - Comprueba si el parámetro es varíadico
    • ReflectionParameter::__clone - Clon
    • ReflectionParameter::__construct - Construct
    • ReflectionParameter::__toString - A string
    • ReflectionProperty::export - Exportar
    • ReflectionProperty::getDeclaringClass - Obtiene la clase en la que se declaró
    • ReflectionProperty::getDefaultValue - Returns the default value declared for a property
    • ReflectionProperty::getDocComment - Obtiene los comentarios de documentación de una propiedad
    • ReflectionProperty::getModifiers - Obtiene los modificadores
    • ReflectionProperty::getName - Obtiene el nombre de la propiedad
    • ReflectionProperty::getType - Gets a property's type
    • ReflectionProperty::getValue - Obtiene el valor
    • ReflectionProperty::hasDefaultValue - Checks if property has a default value declared
    • ReflectionProperty::hasType - Checks if property has a type
    • ReflectionProperty::isDefault - Comprueba si una propiedad es predeterminada
    • ReflectionProperty::isInitialized - Checks whether a property is initialized
    • ReflectionProperty::isPrivate - Comprueba si una propiedad es privada
    • ReflectionProperty::isProtected - Comprueba si la propiedad es protegida
    • ReflectionProperty::isPublic - Comprueba si la propiedad es pública
    • ReflectionProperty::isStatic - Comprueba si la propiedad es estática
    • ReflectionProperty::setAccessible - Hace accesible una propiedad
    • ReflectionProperty::setValue - Establece el valor de la propiedad
    • ReflectionProperty::__clone - Clonar
    • ReflectionProperty::__construct - Construir un objeto ReflectionProperty
    • ReflectionProperty::__toString - Convertir a texto
    • ReflectionReference::fromArrayElement - Create a ReflectionReference from an array element
    • ReflectionReference::getId - Get unique ID of a reference
    • ReflectionType::allowsNull - Checks if null is allowed
    • ReflectionType::__toString - To string
    • ReflectionUnionType::getTypes - Returns the types included in the union type
    • ReflectionZendExtension::export - Exportar
    • ReflectionZendExtension::getAuthor - Consultar autor
    • ReflectionZendExtension::getCopyright - Consultar los derechos de copia
    • ReflectionZendExtension::getName - Obtiene el nombre
    • ReflectionZendExtension::getURL - Obtiene la URL
    • ReflectionZendExtension::getVersion - Obtiene la versión
    • ReflectionZendExtension::__clone - Clon de controlador
    • ReflectionZendExtension::__construct - Constructor
    • ReflectionZendExtension::__toString - Convierte a texto
    • Reflector::export - Exportar
    • Reflector::__toString - Convertir a String
    • RegexIterator::accept - Obtener el estado de aceptación
    • RegexIterator::getFlags - Obtener flags
    • RegexIterator::getMode - Devuelve el modo de operación
    • RegexIterator::getPregFlags - Devuelve las flags de expresión regular
    • RegexIterator::getRegex - Devuelve la expresión regular actual
    • RegexIterator::setFlags - Establece las flags
    • RegexIterator::setMode - Establece el modo de operación
    • RegexIterator::setPregFlags - Establece las flags de expresión regular
    • RegexIterator::__construct - Crea un nuevo RegexIterator
    • register_shutdown_function - Registrar una función para que sea ejecutada al cierre
    • register_tick_function - Registrar una función para que sea ejecutada en cada tick
    • rename - Renombra un fichero o directorio
    • reset - Establece el puntero interno de un array a su primer elemento
    • ResourceBundle::count - Obtener el número de elementos de un paquete
    • ResourceBundle::create - Crear un paquete de recursos
    • ResourceBundle::get - Obtener datos de un paquete
    • ResourceBundle::getErrorCode - Obtener el códido del último error del paquete
    • ResourceBundle::getErrorMessage - Obtener el mensaje del último error del paquete
    • ResourceBundle::getLocales - Obtener las configuraciones regionales soportadas
    • restore_error_handler - Recupera la función de gestión de errores previa
    • restore_exception_handler - Restaura la función de gestión de excepciones previamente definida
    • restore_include_path - Restablece el valor de la opción de configuración include_path
    • rewind - Rebobina la posición de un puntero a un archivo
    • rewinddir - Regresar el gestor de directorio
    • rmdir - Elimina un directorio
    • round - Redondea un float
    • rpmaddtag - Add tag retrieved in query
    • rpmdbinfo - Get information from installed RPM
    • rpmdbsearch - Search RPM packages
    • rpminfo - Get information from a RPM file
    • rpmvercmp - RPM version comparison
    • RRDCreator::addArchive - Añade RRA - archivo de valores de datos para cada fuente de datos
    • RRDCreator::addDataSource - Añade definición de origen de datos para la base de datos RRD
    • RRDCreator::save - Guarda la base de datos RRD en un archivo
    • RRDCreator::__construct - Crea una nueva instancia RRDCreator
    • rrdc_disconnect - Close any outstanding connection to rrd caching daemon
    • RRDGraph::save - Guarda el resultado de la consulta en la imagen
    • RRDGraph::saveVerbose - Guarda la consulta de la bases de datos RRD en la imagen y devuelve la información detallada acerca de gráfico generado.
    • RRDGraph::setOptions - Establece las opciones para la exportación gráfica rrd
    • RRDGraph::__construct - Crea una nueva instancia RRDGraph
    • RRDUpdater::update - Actualiza el archivo de base de datos RRD
    • RRDUpdater::__construct - Crea una nueva instancia RRDUpdater
    • rrd_create - Crea un archivo de base de datos rrd
    • rrd_error - Obtener el último mensaje de error
    • rrd_fetch - Recuperar los datos de gráfico como un array
    • rrd_first - Obtiene la marca de tiempo UNIX de la primera muestra desde el archivo rrd
    • rrd_graph - Crea la imagen de un conjunto de datos
    • rrd_info - Obtiene información sobre el archivo rrd
    • rrd_last - Obtiene la marca de tiempo UNIX de la última muestra
    • rrd_lastupdate - Obtiene información sobre los últimos datos actualizados
    • rrd_restore - Restaura el archivo RRD desde el XML dump
    • rrd_tune - Cambia algunas opciones de cabecera del archivo de base de datos RRD database
    • rrd_update - Actualizar la base de datos RRD
    • rrd_version - Obtiene información acerca de la biblioteca subyacente rrdtool
    • rrd_xport - Exporta la información acerca de la base de datos RRD
    • rsort - Ordena un array en orden inverso
    • rtrim - Retira los espacios en blanco (u otros caracteres) del final de un string
    • runkit7_object_id - Return the integer object handle for given object
    • runkit7_zval_inspect - Returns information about the passed in value with data types, reference counts, etc
    • runkit_constant_add - Similar a define(), excepto que también permite definir en definiciones de clase
    • runkit_constant_redefine - Redefinir una constante ya definida
    • runkit_constant_remove - Eliminar/Borrar una constante ya definida
    • runkit_function_add - Añadir una nueva función, similar a create_function
    • runkit_function_copy - Copiar una función a un nombre de función nuevo
    • runkit_function_redefine - Reemplazar una definición de función con una nueva implementación
    • runkit_function_remove - Eliminar una definición de función
    • runkit_function_rename - Cambiar el nombre de una función
    • runkit_import - Procesar un archivo PHP importando definiciones de funciones y clases, sobrescribiendo cuando sea apropiado
    • runkit_method_add - Añadir dinámicamente un nuevo método a una clase dada
    • runkit_method_copy - Copia un método de una clase a otra
    • runkit_method_redefine - Cambiar dinámicamente el código del método dado
    • runkit_method_remove - Eliminar dinámicamente el método dado
    • runkit_method_rename - Cambiar dinámicamente el nombre del método dado
    • runkit_superglobals - Devolver el array indexado numéricamente de las superglobales registradas
  • 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 - Enumera los ficheros y directorios ubicados en la ruta especificada
    • 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 - Mueve la posición del apuntador interno
    • sem_acquire - Adquirir un semáforo
    • sem_get - Obtener el id de un semáforo
    • sem_release - Liberar un semáforo
    • sem_remove - Eliminar un semáforo
    • Serializable::serialize - Representación en formato cadena de un objeto
    • Serializable::unserialize - Construye el objeto
    • serialize - Genera una representación apta para el almacenamiento de un valor
    • SessionHandler::close - Cerrar la sesión
    • SessionHandler::create_sid - Devuelve un nuevo ID de sesión
    • SessionHandler::destroy - Destruir una sesión
    • SessionHandler::gc - Eliminar las sesiones antiguas
    • SessionHandler::open - Inicializar una sesión
    • SessionHandler::read - Leer información de la sesión
    • SessionHandler::write - Escribir información de sesión
    • SessionHandlerInterface::close - Cerrar la sesión
    • SessionHandlerInterface::destroy - Destruir una sesión
    • SessionHandlerInterface::gc - Limpieza de sesiones antiguas
    • SessionHandlerInterface::open - Inicializar una sesión
    • SessionHandlerInterface::read - Leer información de sesión
    • SessionHandlerInterface::write - Escribir información de sesión
    • SessionIdInterface::create_sid - Create session ID
    • SessionUpdateTimestampHandlerInterface::updateTimestamp - Update timestamp
    • SessionUpdateTimestampHandlerInterface::validateId - Validate ID
    • session_abort - Desecha los cambios en el array de sesión y finaliza la sesión
    • session_cache_expire - Devuelve la caducidad de la caché actual
    • session_cache_limiter - Obtener y/o establecer el limitador de caché actual
    • session_commit - Alias de session_write_close
    • session_create_id - Crear un nuevo ID de sesión
    • session_decode - Decodifica la información de sesión desde una cadena de sesión codificada
    • session_destroy - Destruye toda la información registrada de una sesión
    • session_encode - Codifica los datos de la sesión actual como un string codificado de sesión
    • session_gc - Realizar una recolección de basura de datos de sesión
    • session_get_cookie_params - Obtener los parámetros de la cookie de sesión
    • session_id - Obtener y/o establecer el id de sesión actual
    • session_is_registered - Averiguar si una variable global está registrada en una sesión
    • session_module_name - Obtiene y/o establece el módulo de sesión actual
    • session_name - Obtener y/o establecer el nombre de la sesión actual
    • session_regenerate_id - Actualiza el id de sesión actual con uno generado más reciente
    • session_register_shutdown - Función de cierre de sesiones
    • session_reset - Reinicializar el array de sesión con los valores originales
    • session_save_path - Obtener y/o establecer la ruta de almacenamiento de la sesión actual
    • session_set_cookie_params - Establecer los parámetros de la cookie de sesión
    • session_set_save_handler - Establece funciones de almacenamiento de sesiones a nivel de usuario
    • session_start - Iniciar una nueva sesión o reanudar la existente
    • session_status - Devuelve el estado de la sesión actual
    • session_unregister - Deja de registrar una variable global de la sesión actual
    • session_unset - Libera todas las variables de sesión
    • session_write_close - Escribir información de sesión y finalizar la sesión
    • setcookie - Enviar una cookie
    • setlocale - Establecer la información del localismo
    • setproctitle - Establecer el título de proceso
    • setrawcookie - Enviar una cookie sin codificar su valor
    • setthreadtitle - Set the thread title
    • settype - Establece el tipo de una variable
    • set_error_handler - Establecer una función de gestión de errores definida por el usuario
    • set_exception_handler - Establece una función de gestión de excepciones definida por el usuario
    • set_file_buffer - Alias de stream_set_write_buffer
    • set_include_path - Establece la opción de configuración include_path
    • set_time_limit - Limita el tiempo máximo de ejecución
    • sha1 - Calcula el 'hash' sha1 de un string
    • sha1_file - Calcula el hash sha1 de un archivo
    • shell_exec - Ejecutar un comando mediante el intérprete de comandos y devolver la salida completa como una cadena
    • shmop_close - Cerrar un segmento de memoria compartida
    • shmop_delete - Borrar segmento de memoria compartida
    • shmop_open - Crea o abre un segmento de memoria compartida
    • shmop_read - Leer datos desde un segmento de memoria compartida
    • shmop_size - Obtiene el tamaño de un segmento de memoria compartida
    • shmop_write - Escribir datos en un segmento de memoria compartida
    • shm_attach - Crea o abre un segmento de memoria compartida
    • shm_detach - Desconectarse del segmento de memoria compartida
    • shm_get_var - Devuelve una variable desde la memoria compartida
    • shm_has_var - Verificar si existe una entrada específica
    • shm_put_var - Inserta o actualiza una variable en la memoria compartida
    • shm_remove - Elimina la memoria compartida de sistemas Unix
    • shm_remove_var - Eliminar una variable de la memoria compartida
    • show_source - Alias de highlight_file
    • shuffle - Mezcla un array
    • similar_text - Calcula la similitud entre dos strings
    • SimpleXMLElement::addAttribute - Añade un atributo al elemento SimpleXML
    • SimpleXMLElement::addChild - Añade un elemento hijo al nodo XML
    • SimpleXMLElement::asXML - Retorna un string XML correcto basado en un elemento SimpleXML
    • SimpleXMLElement::attributes - Identifica el atributo de un elemento
    • SimpleXMLElement::children - Encuentra los hijos del nodo dado
    • SimpleXMLElement::count - Cuenta los hijos de un elemento
    • SimpleXMLElement::getDocNamespaces - Devuelve los espacios de nombre declarados en el documento
    • SimpleXMLElement::getName - Retorna el nombre del elemento XML
    • SimpleXMLElement::getNamespaces - Devuelve los espacios de nombre usados en el documento
    • SimpleXMLElement::registerXPathNamespace - Crea un contexto prefijo/ns para la siguiente petición XPath
    • SimpleXMLElement::saveXML - Alias de SimpleXMLElement::asXML
    • SimpleXMLElement::xpath - Ejecuta una petición XPath sobre los datos XML
    • SimpleXMLElement::__construct - Crea un nuevo objeto SimpleXMLElement
    • SimpleXMLElement::__toString - Returns the string content
    • SimpleXMLIterator::current - Devuelve el elemento actual
    • SimpleXMLIterator::getChildren - Devuelve los sub elementos de el elemento actual
    • SimpleXMLIterator::hasChildren - Comprueba si el elemento actual tiene sub elementos
    • SimpleXMLIterator::key - Devuelve la clave actual
    • SimpleXMLIterator::next - Mueve al siguiente elemento
    • SimpleXMLIterator::rewind - Rebobina hasta el primer elemento
    • SimpleXMLIterator::valid - Comprueba si el elemento actual es válido
    • simplexml_import_dom - Obtiene un objeto SimpleXMLElement de un nodo DOM
    • simplexml_load_file - Interpreta un fichero XML en un objeto
    • simplexml_load_string - Interpreta un string de XML en un objeto
    • sin - Seno
    • sinh - Seno hiperbólico
    • sizeof - Alias de count
    • sleep - Retrasar la ejecución
    • snmp2_get - Fetch an SNMP object
    • snmp2_getnext - Fetch the SNMP object which follows the given object id
    • snmp2_real_walk - Return all objects including their respective object ID within the specified one
    • snmp2_set - Set the value of an SNMP object
    • snmp2_walk - Fetch all the SNMP objects from an agent
    • snmp3_get - Fetch an SNMP object
    • snmp3_getnext - Fetch the SNMP object which follows the given object id
    • snmp3_real_walk - Return all objects including their respective object ID within the specified one
    • snmp3_set - Set the value of an SNMP object
    • snmp3_walk - Fetch all the SNMP objects from an agent
    • SNMP::close - Cerrar sesión SNMP
    • SNMP::get - Fetch an SNMP object
    • SNMP::getErrno - Get last error code
    • SNMP::getError - Obtiene el último mensaje de error
    • SNMP::getnext - Fetch an SNMP object which follows the given object id
    • SNMP::set - Set the value of an SNMP object
    • SNMP::setSecurity - Configures security-related SNMPv3 session parameters
    • SNMP::walk - Fetch SNMP object subtree
    • SNMP::__construct - Creates SNMP instance representing session to remote SNMP agent
    • snmpget - Fetch an SNMP object
    • snmpgetnext - Fetch the SNMP object which follows the given object id
    • snmprealwalk - Return all objects including their respective object ID within the specified one
    • snmpset - Set the value of an SNMP object
    • snmpwalk - Fetch all the SNMP objects from an agent
    • snmpwalkoid - Query for a tree of information about a network entity
    • snmp_get_quick_print - Fetches the current value of the NET-SNMP library's quick_print setting
    • snmp_get_valueretrieval - Return the method how the SNMP values will be returned
    • snmp_read_mib - Reads and parses a MIB file into the active MIB tree
    • snmp_set_enum_print - Return all values that are enums with their enum value instead of the raw integer
    • snmp_set_oid_numeric_print - Set the OID output format
    • snmp_set_oid_output_format - Set the OID output format
    • snmp_set_quick_print - Set the value of enable within the NET-SNMP library
    • snmp_set_valueretrieval - Specify the method how the SNMP values will be returned
    • SoapClient::__call - Llama a una función de SOAP (obsoleto)
    • SoapClient::__construct - Constructor de SoapClient
    • SoapClient::__doRequest - Realiza una petición SOAP
    • SoapClient::__getCookies - Get list of cookies
    • SoapClient::__getFunctions - Devuelve una lista de todas las funciones SOAP disponibles
    • SoapClient::__getLastRequest - Devuelve la última petición SOAP
    • SoapClient::__getLastRequestHeaders - Devuelve los encabezados SOAP de la última petición
    • SoapClient::__getLastResponse - Devuelve la última respuesta SOAP
    • SoapClient::__getLastResponseHeaders - Devuelve los encabezados SOAP de la última respuesta
    • SoapClient::__getTypes - Devuelve una lista de los tipos SOAP
    • SoapClient::__setCookie - El propósito de __setCookie
    • SoapClient::__setLocation - Define la localización del servicio Web a utilizar
    • SoapClient::__setSoapHeaders - Define los encabezados SOAP para las subsiguentes llamadas
    • SoapClient::__soapCall - Llama a una función SOAP
    • SoapFault::__construct - Constructor de SoapFault
    • SoapFault::__toString - Obtiene una representación en formato cadena de SoapFault
    • SoapHeader::__construct - Constructor de SoapHeader
    • SoapParam::__construct - Constructor de SoapParam
    • SoapServer::addFunction - Añade una o más funciones al controlador de peticiones SOAP
    • SoapServer::addSoapHeader - Añade un encabezado SOAP a la respuesta
    • SoapServer::fault - SoapServer indica que ocurrió un fallo
    • SoapServer::getFunctions - Devuelve una lista de las funciones definidas
    • SoapServer::handle - Controla la petición SOAP
    • SoapServer::setClass - Define la clase que controla las peticiones SOAP
    • SoapServer::setObject - Define el objecto que será usado para controlar las peticiones SOAP
    • SoapServer::setPersistence - Establece el modo de persistencia de SoapServer
    • SoapServer::__construct - Constructor de SoapServer
    • SoapVar::__construct - Constructor de SoapVar
    • socket_accept - Acepta una conexión de 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_bind - Vincula un nombre a un socket
    • socket_clear_error - Limpia el error del socket o el último código de error
    • socket_close - Cierra un recurso socket
    • socket_cmsg_space - Calcular el tamaño del búfer de mensajes
    • socket_connect - Inicia una conexión sobre un socket
    • socket_create - Crear un socket (extremo de comunicación)
    • socket_create_listen - Abre un socket en un puerto para aceptar conexiones
    • socket_create_pair - Crea un par de sockets indistinguibles y los almacena en una matriz
    • socket_export_stream - Export a socket into a stream that encapsulates a socket
    • socket_getopt - Alias de socket_get_option
    • socket_getpeername - Pregunta a la parte remota del socket dado que puede resultar en un host/puerto o en una ruta de sistema de archivos Unix, dependiendo de su tipo
    • socket_getsockname - Preguntar a la parte local del socket dado que puede resultar en un host/puerto o en una ruta de sistema de archivos Unix, dependiendo de su tipo
    • socket_get_option - Obtiene las opciones de socket para el socket
    • socket_get_status - Alias de stream_get_meta_data
    • socket_import_stream - Importar un flujo a stream
    • socket_last_error - Devuelve el último error sobre un socket
    • socket_listen - Escucha una conexión sobre un socket
    • socket_read - Lee un máximo de longitud de bytes desde un socket
    • socket_recv - Recibe información desde un socket conectado
    • socket_recvfrom - Recibe información desde un socket que esté o no orientado a conexión
    • socket_recvmsg - Leer un mensaje
    • socket_select - Ejecuta la llamada a select() del sistema sobre las matrices de sockets dadas con un tiempo límite especificado
    • socket_send - Envía información a un socket conectado
    • socket_sendmsg - Enviar un mensaje
    • socket_sendto - Envía un mensaje a un socket, ya esté conectado o no
    • socket_setopt - Alias de socket_set_option
    • socket_set_block - Establece el modo de bloqueo de un recurso socket
    • socket_set_blocking - Alias de stream_set_blocking
    • socket_set_nonblock - Establece el modo de no-bloqueo para el descriptor de archivo fd
    • socket_set_option - Establece las opciones de socket para el socket
    • socket_set_timeout - Alias de stream_set_timeout
    • socket_shutdown - Cierra un socket para dejar de recibir, enviar, o ambos
    • socket_strerror - Devuelve una cadena que describe un error de socket
    • socket_write - Escribir en 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 - Description
    • sodium_bin2base64 - Description
    • sodium_bin2hex - Encode to hexadecimal
    • sodium_compare - Compare large numbers
    • sodium_crypto_aead_aes256gcm_decrypt - Decrypt in combined mode with precalculation
    • sodium_crypto_aead_aes256gcm_encrypt - Encrypt in combined mode with precalculation
    • sodium_crypto_aead_aes256gcm_is_available - Check if hardware supports AES256-GCM
    • sodium_crypto_aead_aes256gcm_keygen - Get random bytes for key
    • sodium_crypto_aead_chacha20poly1305_decrypt - Verify that the ciphertext includes a valid tag
    • sodium_crypto_aead_chacha20poly1305_encrypt - Encrypt a message
    • sodium_crypto_aead_chacha20poly1305_ietf_decrypt - Verify that the ciphertext includes a valid tag
    • sodium_crypto_aead_chacha20poly1305_ietf_encrypt - Encrypt a message
    • sodium_crypto_aead_chacha20poly1305_ietf_keygen - Get random bytes for key
    • sodium_crypto_aead_chacha20poly1305_keygen - Get random bytes for key
    • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt - Description
    • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt - Description
    • sodium_crypto_aead_xchacha20poly1305_ietf_keygen - Description
    • sodium_crypto_auth - Compute a tag for the message
    • sodium_crypto_auth_keygen - Get random bytes for key
    • sodium_crypto_auth_verify - Verifies that the tag is valid for the message
    • sodium_crypto_box - Encrypt a message
    • sodium_crypto_box_keypair - Randomly generate a secret key and a corresponding public key
    • sodium_crypto_box_keypair_from_secretkey_and_publickey - Description
    • sodium_crypto_box_open - Verify and decrypt a ciphertext
    • sodium_crypto_box_publickey - Description
    • sodium_crypto_box_publickey_from_secretkey - Description
    • sodium_crypto_box_seal - Encrypt a message
    • sodium_crypto_box_seal_open - Decrypt the ciphertext
    • sodium_crypto_box_secretkey - Description
    • sodium_crypto_box_seed_keypair - Deterministically derive the key pair from a single key
    • sodium_crypto_generichash - Get a hash of the message
    • sodium_crypto_generichash_final - Complete the hash
    • sodium_crypto_generichash_init - Initialize a hash
    • sodium_crypto_generichash_keygen - Get random bytes for key
    • sodium_crypto_generichash_update - Add message to a hash
    • sodium_crypto_kdf_derive_from_key - Derive a subkey
    • sodium_crypto_kdf_keygen - Get random bytes for key
    • sodium_crypto_kx_client_session_keys - Description
    • sodium_crypto_kx_keypair - Creates a new sodium keypair
    • sodium_crypto_kx_publickey - Description
    • sodium_crypto_kx_secretkey - Description
    • sodium_crypto_kx_seed_keypair - Description
    • sodium_crypto_kx_server_session_keys - Description
    • sodium_crypto_pwhash - Derive a key from a password
    • sodium_crypto_pwhash_scryptsalsa208sha256 - Derives a key from a password
    • sodium_crypto_pwhash_scryptsalsa208sha256_str - Get an ASCII encoded hash
    • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify - Verify that the password is a valid password verification string
    • sodium_crypto_pwhash_str - Get an ASCII-encoded hash
    • sodium_crypto_pwhash_str_needs_rehash - Description
    • sodium_crypto_pwhash_str_verify - Verifies that a password matches a hash
    • sodium_crypto_scalarmult - Compute a shared secret given a user's secret key and another user's public key
    • sodium_crypto_scalarmult_base - Alias de sodium_crypto_box_publickey_from_secretkey
    • sodium_crypto_secretbox - Encrypt a message
    • sodium_crypto_secretbox_keygen - Get random bytes for key
    • sodium_crypto_secretbox_open - Verify and decrypt a ciphertext
    • sodium_crypto_secretstream_xchacha20poly1305_init_pull - Description
    • sodium_crypto_secretstream_xchacha20poly1305_init_push - Description
    • sodium_crypto_secretstream_xchacha20poly1305_keygen - Description
    • sodium_crypto_secretstream_xchacha20poly1305_pull - Description
    • sodium_crypto_secretstream_xchacha20poly1305_push - Description
    • sodium_crypto_secretstream_xchacha20poly1305_rekey - Description
    • sodium_crypto_shorthash - Compute a fixed-size fingerprint for the message
    • sodium_crypto_shorthash_keygen - Get random bytes for key
    • sodium_crypto_sign - Sign a message
    • sodium_crypto_sign_detached - Sign the message
    • sodium_crypto_sign_ed25519_pk_to_curve25519 - Convert an Ed25519 public key to a Curve25519 public key
    • sodium_crypto_sign_ed25519_sk_to_curve25519 - Convert an Ed25519 secret key to a Curve25519 secret key
    • sodium_crypto_sign_keypair - Randomly generate a secret key and a corresponding public key
    • sodium_crypto_sign_keypair_from_secretkey_and_publickey - Description
    • sodium_crypto_sign_open - Check that the signed message has a valid signature
    • sodium_crypto_sign_publickey - Description
    • sodium_crypto_sign_publickey_from_secretkey - Extract the public key from the secret key
    • sodium_crypto_sign_secretkey - Description
    • sodium_crypto_sign_seed_keypair - Deterministically derive the key pair from a single key
    • sodium_crypto_sign_verify_detached - Verify signature for the message
    • sodium_crypto_stream - Generate a deterministic sequence of bytes from a seed
    • sodium_crypto_stream_keygen - Get random bytes for key
    • sodium_crypto_stream_xor - Encrypt a message
    • sodium_hex2bin - Decodes a hexadecimally encoded binary string
    • sodium_increment - Increment large number
    • sodium_memcmp - Test for equality in constant-time
    • sodium_memzero - Overwrite buf with zeros
    • sodium_pad - Add padding data
    • sodium_unpad - Remove padding data
    • SolrClient::addDocument - Añade un documento al índice
    • SolrClient::addDocuments - Añade una colección de instancias de SolrInputDocument al índice
    • SolrClient::commit - Finaliza todas las añadiduras/eliminaciones hechas al índice
    • SolrClient::deleteById - Eliminar por Id
    • SolrClient::deleteByIds - Elimina mediante Ids
    • SolrClient::deleteByQueries - Elimina todos los documentos que coincidan con cualquiera de las consultas
    • SolrClient::deleteByQuery - Elimina todos los documentos que coincidan con la consulta dada
    • 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 - Devuelve la información de depuración para el último intento de conexión
    • SolrClient::getOptions - Devuelve las opciones de cliente establecidas internamente
    • SolrClient::optimize - Defragmenta el índice
    • SolrClient::ping - Comprueba si el servidor Solr está todavía activo
    • SolrClient::query - Envía una consulta al servidor
    • SolrClient::request - Envía una petición de actualización sin formato
    • SolrClient::rollback - Revierte todos los añadidos/eliminados hechos en el índice desde el último envío
    • SolrClient::setResponseWriter - Establece el autor de la respuesta usado para preparar la respuesta de Solr
    • SolrClient::setServlet - Cambia el servlet especificado a un nuevo valor
    • SolrClient::system - Obtener información del Servidor Solr
    • SolrClient::threads - Verifica el estado de los hilos
    • SolrClient::__construct - Constructor para el objeto SolrClient
    • SolrClient::__destruct - Destructor para SolrClient
    • SolrClientException::getInternalInfo - Devuelve información interna de donde se lanzó la excepción
    • 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 - añade un campo al documento
    • SolrDocument::clear - Borra todos los campos del documento
    • SolrDocument::current - Recupera el campo actual
    • SolrDocument::deleteField - Elimina un campo del documento
    • SolrDocument::fieldExists - Comprueba si existe un campo en el documento
    • SolrDocument::getChildDocuments - Returns an array of child documents (SolrDocument)
    • SolrDocument::getChildDocumentsCount - Returns the number of child documents
    • SolrDocument::getField - Recupera un campo según su nombre
    • SolrDocument::getFieldCount - Devuelve el número de campos de este documento
    • SolrDocument::getFieldNames - Devuelve una matriz con los nombres de campos del documento
    • SolrDocument::getInputDocument - Devuelve un SolrInputDocument equivalente al objeto
    • SolrDocument::hasChildDocuments - Checks whether the document has any child documents
    • SolrDocument::key - Recupera la clave actual
    • SolrDocument::merge - Fusiona la fuente con el objeto SolrDocument actual
    • SolrDocument::next - Mueve el puntero interno al siguiente campo
    • SolrDocument::offsetExists - Comprueba si existe un campo en particular
    • SolrDocument::offsetGet - Recupera un campo
    • SolrDocument::offsetSet - Añade un campo al documento
    • SolrDocument::offsetUnset - Elimina un campo
    • SolrDocument::reset - Este es un alias de SolrDocument::clear()
    • SolrDocument::rewind - Reinicia el puntero interno al principio
    • SolrDocument::serialize - Usado para serialización personalizada
    • SolrDocument::sort - Ordena los campos del documento
    • SolrDocument::toArray - Devuelve una matriz como representación de un documento
    • SolrDocument::unserialize - Serialización personalizada de objetos SolrDocument
    • SolrDocument::valid - Comprueba si la posición actual del puntero interno es aún válida
    • SolrDocument::__clone - Crea una copia de un objeto SolrDocument
    • SolrDocument::__construct - Constructor
    • SolrDocument::__destruct - Destructor
    • SolrDocument::__get - Acceder al campo como una propiedad
    • SolrDocument::__isset - Comprueba si existe un campo
    • SolrDocument::__set - Añade otro campo al documento
    • SolrDocument::__unset - Elimina un campo del documento
    • SolrDocumentField::__construct - Constructor
    • SolrDocumentField::__destruct - Destructor
    • SolrException::getInternalInfo - Devuelve información interna de donde se lanzó la excepción
    • SolrGenericResponse::__construct - Constructor
    • SolrGenericResponse::__destruct - Destructor
    • SolrIllegalArgumentException::getInternalInfo - Devuelve información interna de donde se lanzó la excepción
    • SolrIllegalOperationException::getInternalInfo - Devuelve información interna de donde se lanzó la excepción
    • SolrInputDocument::addChildDocument - Adds a child document for block indexing
    • SolrInputDocument::addChildDocuments - Adds an array of child documents
    • SolrInputDocument::addField - Añade un campo al documento
    • SolrInputDocument::clear - Restablece el documento de entrada
    • SolrInputDocument::deleteField - Elimina un campo del documento
    • SolrInputDocument::fieldExists - Comprueba si existe un campo
    • SolrInputDocument::getBoost - Recupera el valor boost actual del documento
    • SolrInputDocument::getChildDocuments - Returns an array of child documents (SolrInputDocument)
    • SolrInputDocument::getChildDocumentsCount - Returns the number of child documents
    • SolrInputDocument::getField - Recupera un campo por su nombre
    • SolrInputDocument::getFieldBoost - Recupera el valor boost de un campo en particular
    • SolrInputDocument::getFieldCount - Devuelve el número de campos del documento
    • SolrInputDocument::getFieldNames - Devuelve una matriz que contiene todos los campos del documento
    • SolrInputDocument::hasChildDocuments - Returns true if the document has any child documents
    • SolrInputDocument::merge - Fusiona un documento con otro
    • SolrInputDocument::reset - Este es un alias de SolrInputDocument::clear
    • SolrInputDocument::setBoost - Establece el valor boost de este documento
    • SolrInputDocument::setFieldBoost - Establece el valor boost de tiempo del índice de un campo
    • SolrInputDocument::sort - Ordena los campos dentro de un documento
    • SolrInputDocument::toArray - Devuelve una matriz como representación del documento de entrada
    • SolrInputDocument::__clone - Crea una copia de un objeto SolrDocument
    • SolrInputDocument::__construct - Constructor
    • SolrInputDocument::__destruct - Destructor
    • SolrModifiableParams::__construct - Constructor
    • SolrModifiableParams::__destruct - Destructor
    • SolrObject::getPropertyNames - Devuelve una matriz de todos los nombres de las propiedades
    • SolrObject::offsetExists - Comprueba si la propiedad existe
    • SolrObject::offsetGet - Usado para recuperar una propiedad
    • SolrObject::offsetSet - Establece el valor de una propiedad
    • SolrObject::offsetUnset - Desestablece el valor de la propiedad
    • SolrObject::__construct - Crea un objeto Solr
    • SolrObject::__destruct - Destructor
    • SolrParams::add - Esto es un alias de SolrParams::addParam
    • SolrParams::addParam - Añade un parámetro al objeto
    • SolrParams::get - Este es una alias de SolrParams::getParam
    • SolrParams::getParam - Devuelve el valor de un parámetro
    • SolrParams::getParams - Devuelve una matriz de parámetros URL no codificados
    • SolrParams::getPreparedParams - Devuelve una matriz de parámetros URL codificados
    • SolrParams::serialize - Usado para serialización personalizada
    • SolrParams::set - Un alas de SolrParams::setParam
    • SolrParams::setParam - Establece el parámetro al valor especificado
    • SolrParams::toString - Devuelve todos los parámetros de los pares nombre-valor del objeto
    • SolrParams::unserialize - Usado para serialización personalizada
    • SolrPingResponse::getResponse - Devuelve la respuesta del servidor
    • SolrPingResponse::__construct - Constructor
    • SolrPingResponse::__destruct - Destructor
    • SolrQuery::addExpandFilterQuery - Overrides main filter query, determines which documents to include in the main group
    • SolrQuery::addExpandSortField - Orders the documents within the expanded groups (expand.sort parameter)
    • SolrQuery::addFacetDateField - Mapea a facet.date
    • SolrQuery::addFacetDateOther - Añade otro parámetro facet.date.other
    • SolrQuery::addFacetField - Añade otro campo a la faceta
    • SolrQuery::addFacetQuery - Añade una consulta de faceta
    • SolrQuery::addField - Especifica qué campos devolver en el resultado
    • SolrQuery::addFilterQuery - Especifica una consulta de filtro
    • 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 - Mapea a hl.fl
    • SolrQuery::addMltField - Establece un campo para usarlo para similitud
    • SolrQuery::addMltQueryField - Mapea a mlt.qf
    • SolrQuery::addSortField - Usado para controlar cómo deberían ordenarse los resultados
    • SolrQuery::addStatsFacet - Recupera una devolución de subresultados para valores dentro de la faceta dada
    • SolrQuery::addStatsField - Mapea al parámetro 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 - Devuelve el valor del parámetro facet
    • SolrQuery::getFacetDateEnd - Devuelve el valor del parámetro facet.date.end
    • SolrQuery::getFacetDateFields - Devuelve todos los campos de facet.date
    • SolrQuery::getFacetDateGap - Devuelve el valor del parámetro facet.date.gap
    • SolrQuery::getFacetDateHardEnd - Devuelve el valor del parámetro facet.date.hardend
    • SolrQuery::getFacetDateOther - Devuelve el valor del parámetro facet.date.other
    • SolrQuery::getFacetDateStart - Devuelve el límite inferior del primer rango de datos para todas las facetas de fecha de este campo
    • SolrQuery::getFacetFields - Devuelve todos los campos facet
    • SolrQuery::getFacetLimit - Devuelve el número máximo de restricciones que deberían ser devueltas por los campos facet
    • SolrQuery::getFacetMethod - Devuelve el valor del parámetro facet.method
    • SolrQuery::getFacetMinCount - Devuelve el mínimo de facetas que deberían ser incluidas en la respuesta
    • SolrQuery::getFacetMissing - Devuelve el estado acutual del parámetro facet.missing
    • SolrQuery::getFacetOffset - Devuelve un índice dentro de la lista de restricciones para ser usado en paginación
    • SolrQuery::getFacetPrefix - Devuelve el prefijo de faceta
    • SolrQuery::getFacetQueries - Devuelve todas las consultas de facetas
    • SolrQuery::getFacetSort - Devuelve el tipo de ordenación de la faceta
    • SolrQuery::getFields - Devuelve la lista de campos que serán devueltos en la respuesta
    • SolrQuery::getFilterQueries - Devuelve una matriz de consultas de filtro
    • 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 - Devuelve el estado del parámtero hl
    • SolrQuery::getHighlightAlternateField - Devuelve el campo remarcado para usarlo como copia de seguridad o como predeterminado
    • SolrQuery::getHighlightFields - Devuelve todos los campos que Solr debería generar para remarcación de trozos
    • SolrQuery::getHighlightFormatter - Devuelve el formateador de la salida remarcada
    • SolrQuery::getHighlightFragmenter - Devuelve el generador de trozos de texto para el texto remarcado
    • SolrQuery::getHighlightFragsize - Devuelve el número de caracteres de fragmentos a considerar para remarcación
    • SolrQuery::getHighlightHighlightMultiTerm - Devuelve si habilitar o no la remarcación de consultas range/wildcard/fuzzy/prefix
    • SolrQuery::getHighlightMaxAlternateFieldLength - Devuelve el número máximo de caracteres del campo a devolver
    • SolrQuery::getHighlightMaxAnalyzedChars - Devuelve el número máximo de caracteres de un documento para buscar trozos adecuados
    • SolrQuery::getHighlightMergeContiguous - Devuelve si colapsar o no fragmentos contiguos en un único fragmento
    • SolrQuery::getHighlightRegexMaxAnalyzedChars - Devuelve el número máximo de caracteres de un campo cuando se usa el fragmentador de expresiones regulares
    • SolrQuery::getHighlightRegexPattern - Devuelve la expresión regular para la fragmentación
    • SolrQuery::getHighlightRegexSlop - Devuelve el factor de desviación del tamaño de fragmento ideal
    • SolrQuery::getHighlightRequireFieldMatch - Devuelve si un campo será remarcado solamente si la consulta coincide con este campo en particular
    • SolrQuery::getHighlightSimplePost - Devuelve el texto que aparece después de un término remarcado
    • SolrQuery::getHighlightSimplePre - Devuelve el texto que aparece antes de un término remarcado
    • SolrQuery::getHighlightSnippets - Devuelve el número máximo de trozos remarcados a generar por campo
    • SolrQuery::getHighlightUsePhraseHighlighter - Devuelve el estado del parámetro hl.usePhraseHighlighter
    • SolrQuery::getMlt - Devuelve si los resultados MoreLikeThis deberían o no ser habilitados
    • SolrQuery::getMltBoost - Devuelve si la consulta será impulsada (boost) o no mediante la relevancia del térmido de interés
    • SolrQuery::getMltCount - Devuelve el número de documentos similares a devolver para cada resultado
    • SolrQuery::getMltFields - Devuelve todos los campos a usar para similitud
    • SolrQuery::getMltMaxNumQueryTerms - Devuelve el número máximo de términos de consultas que serán incluidos en cualquier consulta generada
    • SolrQuery::getMltMaxNumTokens - Devuelve el número máximo de tokens a analizar en cada campo del documento que no esté almacenado con soporte TermVector
    • SolrQuery::getMltMaxWordLength - Devuelve la longitud máxima de palabra de las palabras que serán ignoradas
    • SolrQuery::getMltMinDocFrequency - Devuelve el umbral de frecuencia en el que las palabras que no ocurran en por lo menos tantos documentos como este serán ignoradas
    • SolrQuery::getMltMinTermFrequency - Devuelve la frecuencia bajo la cual los términos serán ignorados en el documento fuente
    • SolrQuery::getMltMinWordLength - Devuelve la longitud máxima de palabra bajo la cual las palabras serán ignoradas
    • SolrQuery::getMltQueryFields - Devuelve los campos de consultas y sus boosts
    • SolrQuery::getQuery - Devuelve la consulta principal
    • SolrQuery::getRows - Devuelve el número máximo de documentos
    • SolrQuery::getSortFields - Devuelve todos los campos de ordenación
    • SolrQuery::getStart - Devuelve el índice del conjunto de resultados completo
    • SolrQuery::getStats - Devuelve si están habilitadas o no las estadísticas
    • SolrQuery::getStatsFacets - Devuelve todas las estadísticas de las facetas que fueron establecidas
    • SolrQuery::getStatsFields - Devuelve todas las estadísticas de los campos
    • SolrQuery::getTerms - Devuelve si está habilitado o no TermsComponent
    • SolrQuery::getTermsField - Devuelve el campo desde el cuál los términos son recuperados
    • SolrQuery::getTermsIncludeLowerBound - Devuelve si incluir o no el límite inferior en el conjunto de resultados
    • SolrQuery::getTermsIncludeUpperBound - Devuelve si incluir o no el término de límite superior en el conjunto de resultados
    • SolrQuery::getTermsLimit - Devuelve el número máximo de términos que debería devolver Solr
    • SolrQuery::getTermsLowerBound - Devuelve el término en el que comenzar
    • SolrQuery::getTermsMaxCount - Devuelve la frecuencia de documento máxima
    • SolrQuery::getTermsMinCount - Devuelve la frecuencia de documento mínima a devolver para ser incluido
    • SolrQuery::getTermsPrefix - Devuelve el prefijo del término
    • SolrQuery::getTermsReturnRaw - Si devolver o no caracteres en bruto
    • SolrQuery::getTermsSort - Devuelve un entero indicando cómo son ordenados los términos
    • SolrQuery::getTermsUpperBound - Devuelve el término en donde parar
    • SolrQuery::getTimeAllowed - Devuelve el tiempo en milisegundos permitido para que la consulta finalice
    • SolrQuery::removeExpandFilterQuery - Removes an expand filter query
    • SolrQuery::removeExpandSortField - Removes an expand sort field from the expand.sort parameter
    • SolrQuery::removeFacetDateField - Elimina uno de los campos de faceta de fecha
    • SolrQuery::removeFacetDateOther - Elimina uno de los parámetros facet.date.other
    • SolrQuery::removeFacetField - Elimina uno de los parámetros facet.date
    • SolrQuery::removeFacetQuery - Elimina uno de los parámetros facet.query
    • SolrQuery::removeField - Elimina un campo de la lista de campos
    • SolrQuery::removeFilterQuery - Elimina una consulta de filtro
    • SolrQuery::removeHighlightField - Elimina uno de los campos usados para remarcación
    • SolrQuery::removeMltField - Elimina uno de los campos moreLikeThis
    • SolrQuery::removeMltQueryField - Elimina uno de los campos de consulta moreLikeThis
    • SolrQuery::removeSortField - Elimina uno de los campos de ordenación
    • SolrQuery::removeStatsFacet - Elimina uno de los parámetros stats.facet
    • SolrQuery::removeStatsField - Elimina uno de los parámetros stats.field
    • SolrQuery::setEchoHandler - Conmuta el parámetro echoHandler
    • SolrQuery::setEchoParams - Determina qué tipo de parámetros incluir en la respuesta
    • 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 - Establece el parámetro de consulta común explainOther
    • SolrQuery::setFacet - Mapea al parámetro facet. Habilita o deshabilta las facetas
    • SolrQuery::setFacetDateEnd - Mapea a facet.date.end
    • SolrQuery::setFacetDateGap - Mapea a facet.date.gap
    • SolrQuery::setFacetDateHardEnd - Mapea a facet.date.hardend
    • SolrQuery::setFacetDateStart - Mapea a facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency - Establece la frecuencia de documento mínima usada para determinar la cuenta de términos
    • SolrQuery::setFacetLimit - Mapea a facet.limit
    • SolrQuery::setFacetMethod - Especifica el tipo de algoritmo a usar cuando se hace una faceta a un campo
    • SolrQuery::setFacetMinCount - Mapea a facet.mincount
    • SolrQuery::setFacetMissing - Mapea a facet.missing
    • SolrQuery::setFacetOffset - Establece el índice de la lista de restricciones para tener en cuenta la paginación
    • SolrQuery::setFacetPrefix - Especifica un prefijo de cadena con el que limitar los términos a los que hacer una faceta
    • SolrQuery::setFacetSort - Determina el orden de las restricciones de campos de faceta
    • 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 - Habilita o deshabilita la remarcación
    • SolrQuery::setHighlightAlternateField - Especifica el campo de copia de seguridad a usar
    • SolrQuery::setHighlightFormatter - Especifica un formateador para la salida remarcada
    • SolrQuery::setHighlightFragmenter - Establece el generador de trozos de código para texto remarcado
    • SolrQuery::setHighlightFragsize - El tamaño de los fragmentos a considerara para remarcación
    • SolrQuery::setHighlightHighlightMultiTerm - Usa SpanScorer para remarcar términos de frases
    • SolrQuery::setHighlightMaxAlternateFieldLength - Establece el número máximo de caracteres del campo a devolver
    • SolrQuery::setHighlightMaxAnalyzedChars - Especifica el número de caracteres de un documento para buscar trozos apropiados
    • SolrQuery::setHighlightMergeContiguous - Si colapsar o no fragmentos contiguos en un único fragmento
    • SolrQuery::setHighlightRegexMaxAnalyzedChars - Especifica el número máximo de caracteres a analizar
    • SolrQuery::setHighlightRegexPattern - Especifica la expresión regular para la fragmentación
    • SolrQuery::setHighlightRegexSlop - Establece el factor por el cual el fragmentador de expresiones regulares puede desviarse del tamaño de fragmento ideal
    • SolrQuery::setHighlightRequireFieldMatch - Requerir la coincicencia de campos durante el remarcado
    • SolrQuery::setHighlightSimplePost - Establece el texto que aparece antes de un término remarcado
    • SolrQuery::setHighlightSimplePre - Establece el texto que aparece antes de un término remarcado
    • SolrQuery::setHighlightSnippets - Establece el número máximo de trozos remarcados para generar por campo
    • SolrQuery::setHighlightUsePhraseHighlighter - Si remarcar o no términos de frases sólo cuando aparecen en la frase de consulta
    • SolrQuery::setMlt - Habilita o deshabilita moreLikeThis
    • SolrQuery::setMltBoost - Establecer si la consulta será impulsada (boost) por la relevancia del término de interés
    • SolrQuery::setMltCount - Establece el número de documentos similares a devolver en cada resultado
    • SolrQuery::setMltMaxNumQueryTerms - Establece el número máximo de términos de consulta incluidos
    • SolrQuery::setMltMaxNumTokens - Especifica el número máximo de tokens a analizar
    • SolrQuery::setMltMaxWordLength - Establece la longitud de palabra máxima
    • SolrQuery::setMltMinDocFrequency - Establece la frecuencia de mltMinDoc
    • SolrQuery::setMltMinTermFrequency - Establece la frecuencia bajo la cual los términos serán ignorados en los documentos fuente
    • SolrQuery::setMltMinWordLength - Establece la longitud de palabra mínima
    • SolrQuery::setOmitHeader - Excluye la cabecera de los resultados devueltos
    • SolrQuery::setQuery - Establece la consulta de búsqueda
    • SolrQuery::setRows - Especifica el número máximo de filas a devolver en el resultado
    • SolrQuery::setShowDebugInfo - Bandera para mostrar información de depuración
    • SolrQuery::setStart - Especifica el número de filas que se van a saltar
    • SolrQuery::setStats - Habilita o deshablita el componente de estadísticas
    • SolrQuery::setTerms - Habilita o deshablita TermsComponent
    • SolrQuery::setTermsField - Establece el nombre del campo del que obtener los términos
    • SolrQuery::setTermsIncludeLowerBound - Incluir el término de límite inferior en el conjunto de resultados
    • SolrQuery::setTermsIncludeUpperBound - Incluir el término de límite superior en el conjunto de resultados
    • SolrQuery::setTermsLimit - Establece el número máximo de términos a devolver
    • SolrQuery::setTermsLowerBound - Especifica el término de donde empezar
    • SolrQuery::setTermsMaxCount - Establece la frecuencia máxima de documentos
    • SolrQuery::setTermsMinCount - Establece la frecuencia mínima de documentos
    • SolrQuery::setTermsPrefix - Restringe las coincidencias de términos que comienzan con el prefijo
    • SolrQuery::setTermsReturnRaw - Devuelve los caracteres en bruto del término indexado
    • SolrQuery::setTermsSort - Especifica cómo ordenar los términos devueltos
    • SolrQuery::setTermsUpperBound - Establece el término en el que parar
    • SolrQuery::setTimeAllowed - El tiempo permitido para que la búsqueda finalice
    • SolrQuery::__construct - Constructor
    • SolrQuery::__destruct - Destructor
    • SolrQueryResponse::__construct - Constructor
    • SolrQueryResponse::__destruct - Destructor
    • SolrResponse::getDigestedResponse - Devuelve la respueste XML como información de PHP serializada
    • SolrResponse::getHttpStatus - Devuelve el estado HTTP de la respuesta
    • SolrResponse::getHttpStatusMessage - Devuelve más detalles del estado HTTP
    • SolrResponse::getRawRequest - Devuelve la respuesta en bruto enviada al servidor Solr
    • SolrResponse::getRawRequestHeaders - Devuelve las cabeceras de respuesta sin tratar enviadas al servidor Solr
    • SolrResponse::getRawResponse - Devuelve la respuesta sin tratar del servidor
    • SolrResponse::getRawResponseHeaders - Devuelve las cabeceras de respuesta sin tratar del servidor
    • SolrResponse::getRequestUrl - Devuelve la URL completa a la que se envió la respuesta
    • SolrResponse::getResponse - Devuelve un objeto SolrObject que representa la respuesta XML del servidor
    • SolrResponse::setParseMode - Establece el modo de análisis
    • SolrResponse::success - ¿Tuvo éxito la petición?
    • SolrServerException::getInternalInfo - Devuelve información interna de dónde fue lanzada la excepción
    • SolrUpdateResponse::__construct - Constructor
    • SolrUpdateResponse::__destruct - Destructor
    • SolrUtils::digestXmlResponse - Convierte una cadena de respuesta XML a un objeto SolrObject
    • SolrUtils::escapeQueryChars - Escapa un string de consulta lucene
    • SolrUtils::getSolrVersion - Devuelve la versión actual de la extensión Solr
    • SolrUtils::queryPhrase - Prepara una frase desde una cadena lucene sin escapar
    • solr_get_version - Devuelve la versión actual de la extensión Apache Solr
    • sort - Ordena un array
    • soundex - Calcula la clave soundex de un string
    • SphinxClient::addQuery - Add query to multi-query batch
    • SphinxClient::buildExcerpts - Build text snippets
    • SphinxClient::buildKeywords - Extraer las palabras clave de una consulta
    • SphinxClient::close - Cierra conexión persistente previamente abierta
    • SphinxClient::escapeString - Escapa caracteres especiales
    • SphinxClient::getLastError - Obtener el último mensaje de error
    • SphinxClient::getLastWarning - Obtener la última advertencia
    • SphinxClient::open - Abre una conexión persistente con el servidor
    • SphinxClient::query - Execute search query
    • SphinxClient::resetFilters - Clear all filters
    • SphinxClient::resetGroupBy - Clear all group-by settings
    • SphinxClient::runQueries - Ejecutar un lote de consultas de búsqueda
    • SphinxClient::setArrayResult - Change the format of result set array
    • SphinxClient::setConnectTimeout - Establecer el tiempo de conexión
    • SphinxClient::setFieldWeights - Set field weights
    • SphinxClient::setFilter - Add new integer values set filter
    • SphinxClient::setFilterFloatRange - Add new float range filter
    • SphinxClient::setFilterRange - Add new integer range filter
    • SphinxClient::setGeoAnchor - Set anchor point for a geosphere distance calculations
    • SphinxClient::setGroupBy - Set grouping attribute
    • SphinxClient::setGroupDistinct - Set attribute name for per-group distinct values count calculations
    • SphinxClient::setIDRange - Set a range of accepted document IDs
    • SphinxClient::setIndexWeights - Set per-index weights
    • SphinxClient::setLimits - Set offset and limit of the result set
    • SphinxClient::setMatchMode - Set full-text query matching mode
    • SphinxClient::setMaxQueryTime - Establecer el tiempo máximo de consulta
    • SphinxClient::setOverride - Sets temporary per-document attribute value overrides
    • SphinxClient::setRankingMode - Set ranking mode
    • SphinxClient::setRetries - Set retry count and delay
    • SphinxClient::setSelect - Set select clause
    • SphinxClient::setServer - Set searchd host and port
    • SphinxClient::setSortMode - Set matches sorting mode
    • SphinxClient::status - Queries searchd status
    • SphinxClient::updateAttributes - Actualiza los atributos del documento
    • SphinxClient::__construct - Crea un nuevo objeto SphinxClient
    • SplDoublyLinkedList::add - Añadir/insertar un nuevo valor en el índice especificado
    • SplDoublyLinkedList::bottom - Examinar el nodo del comienzo de la lista doblemente enlazada
    • SplDoublyLinkedList::count - Cuenta el número de elementos de la lista doblemente enlazada
    • SplDoublyLinkedList::current - Devuelve la entrada actual del array
    • SplDoublyLinkedList::getIteratorMode - Devuelve el modo de iteración
    • SplDoublyLinkedList::isEmpty - Comprueba si la lista doblemente enlazada está vacía
    • SplDoublyLinkedList::key - Devuelve el índice del nodo actual
    • SplDoublyLinkedList::next - Avanza a la siguiente entrada
    • SplDoublyLinkedList::offsetExists - Devuelve si el índice solicitado existe
    • SplDoublyLinkedList::offsetGet - Devuelve el valor del índice específicado
    • SplDoublyLinkedList::offsetSet - Establece el valor del índice específicado
    • SplDoublyLinkedList::offsetUnset - Borra el valor de el índice específicado
    • SplDoublyLinkedList::pop - Extrae un nodo del final de la lista doblementa enlazada
    • SplDoublyLinkedList::prev - Retrocede a la entrada anterior
    • SplDoublyLinkedList::push - Inserta un elemento al final de la lista doblemente enlazada
    • SplDoublyLinkedList::rewind - Rebobina el iterador hasta el inicio
    • SplDoublyLinkedList::serialize - Serializa el almacenamiento
    • SplDoublyLinkedList::setIteratorMode - Establece el modo de iteración
    • SplDoublyLinkedList::shift - Quita un nodo del inicio de la lista doblemente enlazada
    • SplDoublyLinkedList::top - Examina el nodo del final de la lista doblemente enlazada
    • SplDoublyLinkedList::unserialize - Deserializa el almacenamiento
    • SplDoublyLinkedList::unshift - Antepone un elemento a la lista doblemente enlazada
    • SplDoublyLinkedList::valid - Comprueba si la lista doblemente enlazada contiene más nodos
    • SplDoublyLinkedList::__construct - Construye una nueva lista doblemente enlazada
    • SplFileInfo::getATime - Obtiene la hora del último acceso al fichero
    • SplFileInfo::getBasename - Obtiene el nombre base del fichero
    • SplFileInfo::getCTime - Obtiene el i-nodo de el cambio de tiempo
    • SplFileInfo::getExtension - Obtiene la extensión del fichero
    • SplFileInfo::getFileInfo - Obtiene un objeto SplFileInfo para el fichero
    • SplFileInfo::getFilename - Obtiene el nombre del fichero
    • SplFileInfo::getGroup - Obtiene el grupo de el fichero
    • SplFileInfo::getInode - Obtiene el i-nodo de el fichero
    • SplFileInfo::getLinkTarget - Obtiene el destino de un enlace del sistema de ficheros
    • SplFileInfo::getMTime - Obtiene la fecha de la última modificación
    • SplFileInfo::getOwner - Obtiene el dueño de el fichero
    • SplFileInfo::getPath - Obtiene la ruta sin el nombre de fichero
    • SplFileInfo::getPathInfo - Obtiene un objeto SplFileInfo para la ruta
    • SplFileInfo::getPathname - Obtiene la ruta de un fichero
    • SplFileInfo::getPerms - Obtiene los permisos del fichero
    • SplFileInfo::getRealPath - Obtiene la ruta absoluta al fichero
    • SplFileInfo::getSize - Obtiene el tamaño de el fichero
    • SplFileInfo::getType - Obtiene el tipo del fichero
    • SplFileInfo::isDir - Dice si el fichero es un directorio
    • SplFileInfo::isExecutable - Comprueba si el fichero es ejecutable
    • SplFileInfo::isFile - Dice is el objeto hace referencia a un fichero normal
    • SplFileInfo::isLink - Comprueba si el fichero es un link
    • SplFileInfo::isReadable - Comprueba si el fichero se puede leer
    • SplFileInfo::isWritable - Comprueba si se puede escribir en el fichero
    • SplFileInfo::openFile - Obtiene un objeto SplFileObject para el fichero
    • SplFileInfo::setFileClass - Establece la clase empleada con SplFileInfo::openFile
    • SplFileInfo::setInfoClass - Establece la clase empleada con SplFileInfo::getFileInfo y SplFileInfo::getPathInfo
    • SplFileInfo::__construct - Construir un objeto nuevo SplFileInfo
    • SplFileInfo::__toString - Devuelve la ruta de el fichero como un string
    • SplFileObject::current - Recupera la línea actual del fichero
    • SplFileObject::eof - Comprueba si es el final del fichero
    • SplFileObject::fflush - Vuelca el resultado en el fichero
    • SplFileObject::fgetc - Obtiene un caracter del fichero
    • SplFileObject::fgetcsv - Obtiene la línea del archivo y analiza como campos CSV
    • SplFileObject::fgets - Obtener la línea de el fichero
    • SplFileObject::fgetss - Obtiene la línea de el fichero y elimina etiquetas HTML
    • SplFileObject::flock - Bloqueo de ficheros portable
    • SplFileObject::fpassthru - Imprimir todos los datos restantes en un apuntador de fichero
    • SplFileObject::fputcsv - Escribir un array de campos como una línea CSV
    • SplFileObject::fread - Leer un fichero
    • SplFileObject::fscanf - Analiza la entrada de un fichero de acuerdo a un formato
    • SplFileObject::fseek - Busca una posiciónn
    • SplFileObject::fstat - Obtiene información de el fichero
    • SplFileObject::ftell - Devuelve la posición del fichero actual
    • SplFileObject::ftruncate - Trunca el archivo a una longitud dada
    • SplFileObject::fwrite - Escribe en el fichero
    • SplFileObject::getChildren - Ningún propósito
    • SplFileObject::getCsvControl - Obtiene el carácter delimitador, el circundante y de escape para campos CSV
    • SplFileObject::getCurrentLine - Alias de SplFileObject::fgets
    • SplFileObject::getFlags - Obtener las flags de SplFileObject
    • SplFileObject::getMaxLineLen - Obtener la longitud máxima de línea
    • SplFileObject::hasChildren - SplFileObject no tiene hijos
    • SplFileObject::key - Obtiene el número de línea
    • SplFileObject::next - Leer la siguiente línea
    • SplFileObject::rewind - Rebobina el fichero hasta la primera línea
    • SplFileObject::seek - Mueve el apuntador interno a la línea específicada
    • SplFileObject::setCsvControl - Establece el carácter delimitador, el circundante y el de escape para campos CSV
    • SplFileObject::setFlags - Establece flags para el SplFileObject
    • SplFileObject::setMaxLineLen - Establecer la longitud máxima de una línea
    • SplFileObject::valid - Comprueba si el final del finchero ha sido alcanzado
    • SplFileObject::__construct - Construye un nuevo objeto de fichero
    • SplFileObject::__toString - Alias de SplFileObject::fgets
    • SplFixedArray::count - Devuelve el tamaño del array
    • SplFixedArray::current - Devuelve la entrada del array actual
    • SplFixedArray::fromArray - Importa un array PHP en una instancia SplFixedArray
    • SplFixedArray::getSize - Obtiene el tamaño de el array
    • SplFixedArray::key - Devuelve los índices del array actual
    • SplFixedArray::next - Mover a la siguiente entrada
    • SplFixedArray::offsetExists - Devuelve si el índice solicitado existe
    • SplFixedArray::offsetGet - Devuelve el valor en el índice específicado
    • SplFixedArray::offsetSet - Establece un nuevo valor para el índice específicado
    • SplFixedArray::offsetUnset - Destruye el valor en el índice específicado
    • SplFixedArray::rewind - Rebobina el iterador hasta el inicio
    • SplFixedArray::setSize - Cambiar el tamaño de un array
    • SplFixedArray::toArray - Devuelve un array PHP de un array fijo
    • SplFixedArray::valid - Comprueba si el array contiene más elementos
    • SplFixedArray::__construct - Construye un nuevo array fijo
    • SplFixedArray::__wakeup - Reinicializar el array después de ser deserializado
    • SplHeap::compare - Compara elementos con el fin de colocarlos correctamente en el montón en la parte de arriba
    • SplHeap::count - Cuenta el número de elementos en el montón
    • SplHeap::current - Devuelve el nodo actual señalado por el iterador
    • SplHeap::extract - Extrae un nodo de la parte superior del montón
    • SplHeap::insert - Inserta un elemento en el montón
    • SplHeap::isCorrupted - Tells if the heap is in a corrupted state
    • SplHeap::isEmpty - Comprueba si el montón actual está vacío
    • SplHeap::key - Devuelve el índice de el nodo actual
    • SplHeap::next - Avanzar al siguiente nodo
    • SplHeap::recoverFromCorruption - Recuperarse de un estado dañado y permitir un mayor número de acciones en el montón
    • SplHeap::rewind - Rebobina el iterador al comienzo
    • SplHeap::top - Observar el nodo desde el comienzo del montón
    • SplHeap::valid - Comprueba si el montón contiene más nodos
    • SplHeap::__construct - Construye un nuevo heap vacío
    • split - Divide una cadena en una matriz mediante una expresión regular
    • spliti - Divide una cadena en una matriz mediante una expresión regular insensible a mayúsculas-minúsculas
    • SplMaxHeap::compare - Compara elementos con el fin de colocarlos correctamente en el montón en la parte de arriba
    • SplMinHeap::compare - Comparar elementos con el fin de colocarlos correctamente en el montón em la parte de arriba
    • SplObjectStorage::addAll - Agrega todos los objetos de otro almacenamiento
    • SplObjectStorage::attach - Agrega un objeto en el almacenamiento
    • SplObjectStorage::contains - Comprueba si el almacenamiento contiene un objeto específico
    • SplObjectStorage::count - Devuelve el número de objetos en el almacenamiento
    • SplObjectStorage::current - Devuelve la entrada actual de almacenamiento
    • SplObjectStorage::detach - Quita un object de el almacenamiento
    • SplObjectStorage::getHash - Calcular un identificador único (hash) para los objetos contenidos
    • SplObjectStorage::getInfo - Devuelve los datos asociados con la entrada del iterador actual
    • SplObjectStorage::key - Devuelve el índice en el que se encuentra el iterador actualmente
    • SplObjectStorage::next - Mover a la siguiente entrada
    • SplObjectStorage::offsetExists - Comprueba si un objeto existe en el almacenamiento
    • SplObjectStorage::offsetGet - Devuelve los datos asociados con un object
    • SplObjectStorage::offsetSet - Asocia datos a un objeto en el almacenamiento
    • SplObjectStorage::offsetUnset - Quita un objeto de el almacenamiento
    • SplObjectStorage::removeAll - Remover objetos contenidos en otro almacenamiento de el almacenamiento actual
    • SplObjectStorage::removeAllExcept - Remover objetos excepto los contenidos en otro almacenamiento del almacenamiento actual
    • SplObjectStorage::rewind - Rebobina el iterador a el primer elemento de el almacenamiento
    • SplObjectStorage::serialize - Serializa el almacenamiento
    • SplObjectStorage::setInfo - Establece los datos asociados con el iterador de la entrada actual
    • SplObjectStorage::unserialize - Deserializa un almacenamiento desde su representación string
    • SplObjectStorage::valid - Comprobar si la entrada actual del iterador es válida
    • SplObserver::update - Recibe actualizaciones de sujeto
    • SplPriorityQueue::compare - Comparar las prioridades con el fin de colocar los elementos correctamente en el montón, mientras que tamizar arriba
    • SplPriorityQueue::count - Cuenta el número de elementos en la cola
    • SplPriorityQueue::current - Volver nodo actual que apunta el iterador
    • SplPriorityQueue::extract - Extrae un nodo de la parte superior del montículo y desplaza hacia arriba
    • SplPriorityQueue::getExtractFlags - Get the flags of extraction
    • SplPriorityQueue::insert - Inserta un elemento en la cola en la parte de arriba
    • SplPriorityQueue::isCorrupted - Tells if the priority queue is in a corrupted state
    • SplPriorityQueue::isEmpty - Comprueba si la cola está vacía
    • SplPriorityQueue::key - Devuelve el índice del nodo actual
    • SplPriorityQueue::next - Pasar a la siguiente nodo
    • SplPriorityQueue::recoverFromCorruption - Recuperar desde la condición corrupta y permitir acciones más en la cola
    • SplPriorityQueue::rewind - Rebobinar iterador de vuelta al inicio (no-op)
    • SplPriorityQueue::setExtractFlags - Establece el modo de extracción
    • SplPriorityQueue::top - Mira en el nodo de la parte superior de la cola
    • SplPriorityQueue::valid - Comprobar si la cola contiene más nodos
    • SplPriorityQueue::__construct - Construye una nueva cola vacía
    • SplQueue::dequeue - Quita un nodo de la cola
    • SplQueue::enqueue - Añade un elemento a la cola
    • SplQueue::setIteratorMode - Establece el modo de iteración
    • SplQueue::__construct - Construye una nueva cola implementada usando una lista doblemente enlazada
    • SplStack::setIteratorMode - Establece el modo de iteración
    • SplStack::__construct - Construye una nueva pila implementada mediante una lista doblemente enlazada
    • SplSubject::attach - Adjuntar un SplObserver
    • SplSubject::detach - Separa un observador
    • SplSubject::notify - Notificar un observador
    • SplTempFileObject::__construct - Construir un nuevo objeto de fichero temporal
    • spl_autoload - Implementación predeterminada para __autoload()
    • spl_autoload_call - Probar todos las funciones registradas __autoload() para cargar la clase solicitada
    • spl_autoload_extensions - Registrar y devolver las extensiones de ficheros predeterminadas para spl_autoload
    • spl_autoload_functions - Devolver todas las funciones __autoload() registradas
    • spl_autoload_register - Registrar las funciones dadas como implementación de __autoload()
    • spl_autoload_unregister - Desregistrar una función dada como implementación de __autoload()
    • spl_classes - Devuelve las clases SPL disponibles
    • spl_object_hash - Devuelve el id del hash del objeto dado
    • spl_object_id - Return the integer object handle for given object
    • Spoofchecker::areConfusable - Comprobar si un texto dado contiene carateres que pueden ser confusos
    • Spoofchecker::isSuspicious - Comprobar si un texto dad contiene caracteres sospechosos
    • Spoofchecker::setAllowedLocales - Las configuraciones regionales a usar cuando se ejecutan las comprobaciones
    • Spoofchecker::setChecks - Establecer las comprobaciones a ejecutar
    • Spoofchecker::__construct - Constructor
    • sprintf - Devuelve un string formateado
    • SQLite3::backup - Backup one database to another database
    • SQLite3::busyTimeout - Establecer el gestor de conexión ocupado
    • SQLite3::changes - Devolver el número de filas de la base de datos que fueron cambiadas (o insertadas, o eliminadas) por la sentencia SQL más reciente
    • SQLite3::close - Cerrar la conexión a la base de datos
    • SQLite3::createAggregate - Registrar una función de PHP para usarla como una función totalizadora de SQL
    • SQLite3::createCollation - Registra una función PHP para ser utilizada como una función SQL de ordenación específica
    • SQLite3::createFunction - Registrar una función de PHP para usarla como una función escalar de SQL
    • SQLite3::enableExceptions - Enable throwing exceptions
    • SQLite3::escapeString - Devolver una cadena que ha sido debidamente escapada
    • SQLite3::exec - Ejecutar una consulta que no devuelve resultados en una base de datos dada
    • SQLite3::lastErrorCode - Devolver el código numérico del resultado de la petición SQLite que falló más recientemente
    • SQLite3::lastErrorMsg - Devolver texto en inglés describiendo la petición SQLite que falló más recientemente
    • SQLite3::lastInsertRowID - Devolver el ID de la fila de la sentencia INSERT más reciente realizada en la base de datos
    • SQLite3::loadExtension - Intentar cargar una biblioteca de extensiones de SQLite
    • SQLite3::open - Abrir una base de datos SQLite
    • SQLite3::openBlob - Opens a stream resource to read a BLOB
    • SQLite3::prepare - Preparar una sentencia SQL para su ejecución
    • SQLite3::query - Ejecutar una consulta SQL
    • SQLite3::querySingle - Ejecutar una consulta y devolver un único resultado
    • SQLite3::setAuthorizer - Configures a callback to be used as an authorizer to limit what a statement can do
    • SQLite3::version - Devolver la versión de la biblioteca SQLite3 como una constante de cadena y como un número
    • SQLite3::__construct - Instanciar un objeto de la clase SQLite3 y abrir una base de datos de SQLite 3
    • SQLite3Result::columnName - Devolver el nombre de la columna n-ésima
    • SQLite3Result::columnType - Devolver el tipo de la columna n-ésima
    • SQLite3Result::fetchArray - Obtener una fila de resultados en forma de un array asociativo o indexado o ambos
    • SQLite3Result::finalize - Cerrar el conjunto de resultados
    • SQLite3Result::numColumns - Devolver el número de columnas del conjunto de resultados
    • SQLite3Result::reset - Reiniciar el conjunto de resultados a la primera fila
    • SQLite3Stmt::bindParam - Vincular un parámetro a una variable de sentencia
    • SQLite3Stmt::bindValue - Vincular el valor de un parámetro a una variable de sentencia
    • SQLite3Stmt::clear - Limpiar todos los parámetros vinculados actuales
    • SQLite3Stmt::close - Cerrar una sentencia preparada
    • SQLite3Stmt::execute - Ejecutar una sentencia preparada y devuolver un objeto de conjunto de resultados
    • SQLite3Stmt::getSQL - Get the SQL of the statement
    • SQLite3Stmt::paramCount - Devolver el número de parámetros dentro de la sentencia preparada
    • SQLite3Stmt::readOnly - Returns whether a statement is definitely read only
    • SQLite3Stmt::reset - Reiniciar la sentencia preparada
    • sqlsrv_begin_transaction - Inicia una transacción de base de datos
    • sqlsrv_cancel - Cancela una sentencia de base de datos
    • sqlsrv_client_info - Devuelve información sobre el cliente y la conexión especificada
    • sqlsrv_close - Cierra una conexión abierta y libera los recursos asociados a la conexión
    • sqlsrv_commit - Consolida una transacción que se inició con sqlsrv_begin_transaction
    • sqlsrv_configure - Cambia la configuración de los drivers del gestionador de errores y de log
    • sqlsrv_connect - Abre una conexión a una base de datos Microsoft SQL Server
    • sqlsrv_errors - Devuelve información de errores y alertas (warnings) de la última operación SQLSRV realizada
    • sqlsrv_execute - Ejecuta una sentencia preparada con sqlsrv_prepare
    • sqlsrv_fetch - Hace que esté disponible para ser leída la siguiente fila del conjunto de resultado
    • sqlsrv_fetch_array - Devuelve una fila como un array
    • sqlsrv_fetch_object - Devuelve la siguiente fila de datos de un conjunto resultado como un objeto
    • sqlsrv_field_metadata - Obtiene la metadata de los campos de una consulta preparada por sqlsrv_prepare o sqlsrv_query
    • sqlsrv_free_stmt - Frees all resources for the specified statement
    • sqlsrv_get_config - Returns the value of the specified configuration setting
    • sqlsrv_get_field - Gets field data from the currently selected row
    • sqlsrv_has_rows - Indicates whether the specified statement has rows
    • sqlsrv_next_result - Makes the next result of the specified statement active
    • sqlsrv_num_fields - Retrieves the number of fields (columns) on a statement
    • sqlsrv_num_rows - Retrieves the number of rows in a result set
    • sqlsrv_prepare - Prepares a query for execution
    • sqlsrv_query - Prepares and executes a query
    • sqlsrv_rollback - Rolls back a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_rows_affected - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
    • sqlsrv_send_stream_data - Sends data from parameter streams to the server
    • sqlsrv_server_info - Returns information about the server
    • sql_regcase - Produce una expresión regular para la comparación insensible a mayúscuas-minúsculas
    • sqrt - Raíz cuadrada
    • srand - Genera un número aleatorio a partir de una semilla
    • sscanf - Interpreta un string de entrada de acuerdo con un formato
    • ssdeep_fuzzy_compare - Calculates the match score between two fuzzy hash signatures
    • ssdeep_fuzzy_hash - Create a fuzzy hash from a string
    • ssdeep_fuzzy_hash_filename - Create a fuzzy hash from a file
    • ssh2:// - Secure Shell 2
    • ssh2_auth_agent - Authenticate over SSH using the ssh agent
    • ssh2_auth_hostbased_file - Authenticate using a public hostkey
    • ssh2_auth_none - Authenticate as "none"
    • ssh2_auth_password - Authenticate over SSH using a plain password
    • ssh2_auth_pubkey_file - Authenticate using a public key
    • ssh2_connect - Conecta a un servidor SSH
    • ssh2_disconnect - Close a connection to a remote SSH server
    • ssh2_exec - Execute a command on a remote server
    • ssh2_fetch_stream - Fetch an extended data stream
    • ssh2_fingerprint - Retrieve fingerprint of remote server
    • ssh2_forward_accept - Accept a connection created by a listener
    • ssh2_forward_listen - Bind a port on the remote server and listen for connections
    • ssh2_methods_negotiated - Return list of negotiated methods
    • ssh2_poll - Poll the channels/listeners/streams for events
    • ssh2_publickey_add - Add an authorized publickey
    • ssh2_publickey_init - Initialize Publickey subsystem
    • ssh2_publickey_list - List currently authorized publickeys
    • ssh2_publickey_remove - Remove an authorized publickey
    • ssh2_scp_recv - Solicita un fichero mediante SCP
    • ssh2_scp_send - Envía un fichero mediante SCP
    • ssh2_sftp - Inicializar el subsistema SFTP
    • ssh2_sftp_chmod - Changes file mode
    • ssh2_sftp_lstat - Stat a symbolic link
    • ssh2_sftp_mkdir - Create a directory
    • ssh2_sftp_readlink - Return the target of a symbolic link
    • ssh2_sftp_realpath - Resolve the realpath of a provided path string
    • ssh2_sftp_rename - Rename a remote file
    • ssh2_sftp_rmdir - Remove a directory
    • ssh2_sftp_stat - Stat a file on a remote filesystem
    • ssh2_sftp_symlink - Create a symlink
    • ssh2_sftp_unlink - Delete a file
    • ssh2_shell - Request an interactive shell
    • ssh2_tunnel - Open a tunnel through a remote server
    • stat - Da información acerca de un fichero
    • stats_absolute_deviation - Devuelve la desviación media de una matriz de valores
    • stats_cdf_beta - Calcula un parámetro de la distribución beta según los valores dados a los otros
    • stats_cdf_binomial - Calcula un parámetro de la distribución binomial según los valores dados a los otros
    • stats_cdf_cauchy - No documentada
    • stats_cdf_chisquare - Calcula un parámetro de la distribución ji-cuadrado según los valores dados a los otros
    • stats_cdf_exponential - No documentada
    • stats_cdf_f - Calcula un parámetro de la distribución F según los valores dados a los otros
    • stats_cdf_gamma - Calcula un parámetro de la distribución gamma según los valores dados a los otros
    • stats_cdf_laplace - No documentada
    • stats_cdf_logistic - No documentada
    • stats_cdf_negative_binomial - Calcula un parámetro de la distribución binomial negativa según los valores dados a los otros
    • stats_cdf_noncentral_chisquare - Calcula un parámetro de la distribución ji-cuadrado no central según los valores dados a los otros
    • stats_cdf_noncentral_f - Calcula un parámetro de la distribución F no central según los valores dados a los otros
    • 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 - Calcula un parámetro de la distribución de Poisson según los valores dados a los otros
    • stats_cdf_t - Calcula un parámetro de la distribución T según los valores dados a los otros
    • stats_cdf_uniform - No documentada
    • stats_cdf_weibull - No documentada
    • stats_covariance - Computa la covarianza de dos conjuntos de datos
    • stats_dens_beta - No documentada
    • stats_dens_cauchy - No documentada
    • stats_dens_chisquare - No documentada
    • stats_dens_exponential - No documentada
    • stats_dens_f - Descripción
    • stats_dens_gamma - No documentada
    • stats_dens_laplace - No documentada
    • stats_dens_logistic - No documentada
    • stats_dens_normal - No documentada
    • stats_dens_pmf_binomial - No documentada
    • stats_dens_pmf_hypergeometric - Descripción
    • stats_dens_pmf_negative_binomial - Probability mass function of the negative binomial distribution
    • stats_dens_pmf_poisson - No documentada
    • stats_dens_t - No documentada
    • stats_dens_uniform - Probability density function of the uniform distribution
    • stats_dens_weibull - No documentada
    • stats_harmonic_mean - Devuelve la media armónica de una matriz de valores
    • stats_kurtosis - Computa la curtosis de la información de la matriz
    • stats_rand_gen_beta - Genera una desviación aleatoria beta
    • stats_rand_gen_chisquare - Genera una desviación aleatorio desde una distribución ji-cuadrado con "df" grados de libertad de variable aleatoria
    • stats_rand_gen_exponential - Genera una desviación aleatoria sencilla desde una distribución exponencial con media "av"
    • stats_rand_gen_f - Genera una desviación aleatoria
    • stats_rand_gen_funiform - Genera números de coma flotante uniformes entretes low (exclusive) y high (exclusive)
    • stats_rand_gen_gamma - Genera desviaciones aleatorias desde una distribución gamma
    • stats_rand_gen_ibinomial - Genera una desviación sencilla desde una distribución binomial cuyo número de pruebas es "n" (n >= 0) y cuya probabilidad de un suceso en cada prueba es "pp" ([0;1]). Método : algoritmo BTPE
    • stats_rand_gen_ibinomial_negative - Generates una desviación aleatoria sencilla desde una distribución binomial negativa. Argumentos : n - el número de pruebas de la distribución binomial negativa desde la cuál se va a generar una desviación aleatoria (n > 0), p - la probabilidad de un suceso (0 < p < 1))
    • stats_rand_gen_int - Genera enteros aleatorios entre 1 y 2147483562
    • stats_rand_gen_ipoisson - Genera una desviación aleatoria sencilla desde una distribución Poisson con media "mu" (mu >= 0.0)
    • stats_rand_gen_iuniform - Genera enteros uniformemente distribuidos entre LOW (inclusive) y HIGH (inclusive)
    • stats_rand_gen_noncentral_chisquare - Generates a random deviate from the non-central chi-square distribution
    • stats_rand_gen_noncentral_f - Genera una desviación aleatoria desde una distribución F no central (ratio de varianza) con "dfn" grados de libertad en el numerador y "dfd" grados de libertad en el denominador, y parámetro no central "xnonc". Método : genera directamente el ratio de la desviación ji-cuadrado de numerador no central hasta la variación ji-cuadrado de denominador central
    • stats_rand_gen_noncentral_t - Genera una desviación aleatoria sencilla desde una distribución T no central
    • stats_rand_gen_normal - Genera una desviación aleatoria sencilla desde una distribución normal con media av, y desviación estándar sd (sd >= 0). Método : Renombra SNORM desde TOMS ya que está ligeramente modificado por BWB para usar RANF en lugar de SUNIF
    • stats_rand_gen_t - Genera una desviación aleatoria sencilla desde una distribución T
    • stats_rand_get_seeds - No documentada
    • stats_rand_phrase_to_seeds - Generar dos semillas para el generador de números aleatorios RGN
    • stats_rand_ranf - Devuelve un número de coma flotante desde una distribución uniforme sobre 0 - 1 (los extremos de este intervalo no son devueltos) usando el generador actual
    • stats_rand_setall - No documentada
    • stats_skew - Computa la oblicuidad de los datos de una matriz
    • stats_standard_deviation - Devuelve la desviación estándar
    • stats_stat_binomial_coef - No documentada
    • stats_stat_correlation - No documentada
    • stats_stat_factorial - Returns the factorial of an integer
    • stats_stat_independent_t - No documentada
    • stats_stat_innerproduct - Descripción
    • stats_stat_paired_t - No documentada
    • stats_stat_percentile - No documentada
    • stats_stat_powersum - No documentada
    • stats_variance - Devuelve la varianza de población
    • Stomp::abort - Deshacer una transacción en curso
    • Stomp::ack - Confirmar la recepción y el consumo de un mensaje
    • Stomp::begin - Iniciar una transacción
    • Stomp::commit - Validar una transacción en curso
    • Stomp::error - Obtiene el último error stomp
    • Stomp::getReadTimeout - Obtener la lectura del tiempo de espera de la solicitud
    • Stomp::getSessionId - Obtiene el identificador de sesión actual stomp
    • Stomp::hasFrame - Indica si existe o no una trama lista para leer
    • Stomp::readFrame - Leer la siguiente trama
    • Stomp::send - Envía un mensaje
    • Stomp::setReadTimeout - Establecer el tiempo de espera de lectura
    • Stomp::subscribe - Registrarse para escuchar a un destino dado
    • Stomp::unsubscribe - Dar de baja una suscripción existente
    • Stomp::__construct - Abre una conexión
    • Stomp::__destruct - Cierra una conexión stomp
    • StompException::getDetails - Obtener detalles de la excepción
    • StompFrame::__construct - Constructor
    • stomp_connect_error - Devuelve una cadena descripción de el último error al conectar
    • stomp_version - Obtiene la versión actual de la extensión stomp
    • strcasecmp - Comparación de string segura a nivel binario e insensible a mayúsculas y minúsculas
    • strchr - Alias de strstr
    • strcmp - Comparación de string segura a nivel binario
    • strcoll - Comparación de cadenas basada en la localidad
    • strcspn - Averiguar la longitud del segmento inicial que no coincida con una máscara
    • streamWrapper::dir_closedir - Cerrar un gestor de directorio
    • streamWrapper::dir_opendir - Abrir un gestor de directorio
    • streamWrapper::dir_readdir - Leer una entrada desde el gestor de directorio
    • streamWrapper::dir_rewinddir - Rebobina el gestor de directorio
    • streamWrapper::mkdir - Crear un directorio
    • streamWrapper::rename - Renombra un archivo o directorio
    • streamWrapper::rmdir - Elimina un directorio
    • streamWrapper::stream_cast - Recuperar el recurso subyacente
    • streamWrapper::stream_close - Cerrar un recurso
    • streamWrapper::stream_eof - Comprueba si un puntero a un archivo está en el final del archivo (EOF)
    • streamWrapper::stream_flush - Vuelca la salida
    • streamWrapper::stream_lock - Bloqueo de archivos asesorado
    • streamWrapper::stream_metadata - Cambiar las opciones del flujo
    • streamWrapper::stream_open - Abre un archivo o una URL
    • streamWrapper::stream_read - Leer un flujo
    • streamWrapper::stream_seek - Busca la ubicación específica en un flujo
    • streamWrapper::stream_set_option - Cambiar las opciones del flujo
    • streamWrapper::stream_stat - Recuperar información sobre un recurso de archivo
    • streamWrapper::stream_tell - Recuperar la posición actual de un flujo
    • streamWrapper::stream_truncate - Truncar un flujo
    • streamWrapper::stream_write - Escribir en un flujo
    • streamWrapper::unlink - Borrar un archivo
    • streamWrapper::url_stat - Recuperar información sobre un archivo
    • streamWrapper::__construct - Construye una nueva envoltura de flujo
    • streamWrapper::__destruct - Destruye una envoltura de flujo existente
    • stream_bucket_append - Añade un recipiente a una cadena de recipientes
    • stream_bucket_make_writeable - Devuelve un objeto recipiente desde una cadena de recipientes para operarar con él
    • stream_bucket_new - Crear un nuevo recipiente para usarlo en el flujo actual
    • stream_bucket_prepend - Añade un recipiente al principio de una cadena de recipientes
    • stream_context_create - Crear un contexto de flujo
    • stream_context_get_default - Recuperar el contexto de flujo predeterminado
    • stream_context_get_options - Recuperar las opciones para un flujo/envoltura/contexto
    • stream_context_get_params - Recuperar los parámetros de un contexto
    • stream_context_set_default - Establecer el contexto de flujo predeterminado
    • stream_context_set_option - Establece una opción para un flujo/envoltura/contexto
    • stream_context_set_params - Establecer parámetros para un flujo/envoltura/contexto
    • stream_copy_to_stream - Copia información desde un flujo a otro
    • stream_filter_append - Enlaza un filtro a un flujo
    • stream_filter_prepend - Adjunta un filtro a un flujo
    • stream_filter_register - Registrar un filtro de flujo definido por el usuario
    • stream_filter_remove - Elimina un filtro de un flujo
    • stream_get_contents - Transfiere el resto de un flujo a una cadena
    • stream_get_filters - Recuperar la lista de los filtros registrados
    • stream_get_line - Obtiene una línea del recurso de flujo hasta un delimitador dado
    • stream_get_meta_data - Recuperar meta-información o de cabecera de punteros a flujos/archivo
    • stream_get_transports - Recuperar la lista de transportes de socket registrados
    • stream_get_wrappers - Recupera la lista de los flujos registrados
    • stream_isatty - Check if a stream is a TTY
    • stream_is_local - Comprueba si un flujo es un flujo local
    • stream_notification_callback - Una función de retrollamada para el parámetro de contexto de notificación
    • stream_register_wrapper - Alias de stream_wrapper_register
    • stream_resolve_include_path - Resuelve el nombre de archivo en la ruta incluida
    • stream_select - Ejecuta el equivalente de la llamada al sistema select() sobre las matrices de flujos dadas con un tiempo de espera especificado por tv_sec y tv_usec
    • stream_set_blocking - Establecer el modo bloqueo/no-bloqueo en un flujo
    • stream_set_chunk_size - Establecer el tamaño de trozo de flujo
    • stream_set_read_buffer - Establece el búfer de lectura de archivos en el flujo dado
    • stream_set_timeout - Establecer un perido de tiempo de espera en un flujo
    • stream_set_write_buffer - Establece el búfer para escritura de ficheros en el flujo dado
    • stream_socket_accept - Acepta una conexión sobre un socket creado por stream_socket_server
    • stream_socket_client - Abrir una conexión de socket de dominio de Internet o Unix
    • stream_socket_enable_crypto - Activa/desactiva la encriptación en un socket ya conectado
    • stream_socket_get_name - Recuperar el nombre de los sockets locales o remotos
    • stream_socket_pair - Crea un pareja de flujos de socket conectados e indistinguibles
    • stream_socket_recvfrom - Recibir información de un socket, conectado o no
    • stream_socket_sendto - Envía un mensaje a un socket, ya esté conectado o no
    • stream_socket_server - Crear un socket de servidor de dominio de Internet o de Unix
    • stream_socket_shutdown - Cerrar una conexión full-duplex
    • stream_supports_lock - Indica si el flujo soporta bloqueo
    • stream_wrapper_register - Registra una envoltura de URL implementada como una clase de PHP
    • stream_wrapper_restore - Restablece una envoltura incluida que se dejó de registrar previamente
    • stream_wrapper_unregister - Deja de registrar una envoltura de URL
    • strftime - Formatea una fecha/hora local según una configuración local
    • stripcslashes - Desmarca la cadena marcada con addcslashes
    • stripos - Encuentra la posición de la primera aparición de un substring en un string sin considerar mayúsculas ni minúsculas
    • stripslashes - Quita las barras de un string con comillas escapadas
    • strip_tags - Retira las etiquetas HTML y PHP de un string
    • stristr - strstr insensible a mayúsculas y minúsculas
    • strlen - Obtiene la longitud de un string
    • strnatcasecmp - Comparación de strings, insensible a mayúsculas y minúsculas, utilizando un algoritmo de "orden natural"
    • strnatcmp - Comparación de strings utilizando un algoritmo de "orden natural"
    • strncasecmp - Comparación de los primeros n caracteres de cadenas, segura con material binario e insensible a mayúsculas y minúsculas
    • strncmp - Comparación segura a nivel binario de los primeros n caracteres entre strings
    • strpbrk - Buscar una cadena por cualquiera de los elementos de un conjunto de caracteres
    • strpos - Encuentra la posición de la primera ocurrencia de un substring en un string
    • strptime - Analiza una fecha/hora generada con strftime
    • strrchr - Encuentra la última aparición de un caracter en un string
    • strrev - Invierte una string
    • strripos - Encuentra la posición de la última aparición de un substring insensible a mayúsculas y minúsculas en un string
    • strrpos - Encuentra la posición de la última aparición de un substring en un string
    • strspn - Averigua la longitud del segmento inicial de un string que consista únicamente en caracteres contenidos dentro de una máscara dada
    • strstr - Encuentra la primera aparición de un string
    • strtok - Tokeniza string
    • strtolower - Convierte un string a minúsculas
    • strtotime - Convierte una descripción de fecha/hora textual en Inglés a una fecha Unix
    • strtoupper - Convierte un string a mayúsculas
    • strtr - Convierte caracteres o reemplaza substrings
    • strval - Obtiene el valor de cadena de una variable
    • str_contains - Determine if a string contains a given substring
    • str_ends_with - Checks if a string ends with a given substring
    • str_getcsv - Convierte un string con formato CSV a un array
    • str_ireplace - Versión insensible a mayúsculas y minúsculas de str_replace
    • str_pad - Rellena un string hasta una longitud determinada con otro string
    • str_repeat - Repite un string
    • str_replace - Reemplaza todas las apariciones del string buscado con el string de reemplazo
    • str_rot13 - Realizar la transformación rot13 sobre una cadena
    • str_shuffle - Reordena aleatoriamente una cadena
    • str_split - Convierte un string en un array
    • str_starts_with - Checks if a string starts with a given substring
    • str_word_count - Devuelve información sobre las palabras utilizadas en un string
    • substr - Devuelve parte de una cadena
    • substr_compare - Comparación segura a nivel binario de dos o más strings desde un índice hasta una longitud de caracteres dada
    • substr_count - Cuenta el número de apariciones del substring
    • substr_replace - Reemplaza el texto dentro de una porción de un string
    • SVM::crossvalidate - Test training params on subsets of the training data
    • SVM::getOptions - Return the current training parameters
    • SVM::setOptions - Set training parameters
    • SVM::train - Create a SVMModel based on training data
    • SVM::__construct - Construir un nuevo objeto SVM
    • SVMModel::checkProbabilityModel - Returns true if the model has probability information
    • SVMModel::getLabels - Get the labels the model was trained on
    • SVMModel::getNrClass - Returns the number of classes the model was trained with
    • SVMModel::getSvmType - Get the SVM type the model was trained with
    • SVMModel::getSvrProbability - Get the sigma value for regression types
    • SVMModel::load - Cargar un modelo SVM guardado
    • SVMModel::predict - Predict a value for previously unseen data
    • SVMModel::predict_probability - Return class probabilities for previous unseen data
    • SVMModel::save - Guardar un modelo en un archivo
    • SVMModel::__construct - Construct a new SVMModel
    • svn_add - Programa la adición de un artículo en un directorio de trabajo
    • svn_auth_get_parameter - Recupera un parámetros de autenticación
    • svn_auth_set_parameter - Establece un parámetro de autenticación
    • svn_blame - Obtiene las acusaciones SVN de un archivo
    • svn_cat - Devuelve el contenido de un fichero en un repositorio
    • svn_checkout - Descarga una copia de trabajo desde el repositorio
    • svn_cleanup - Limpieza recursiva del directorio de trabajo, finalizando operaciones no completadas y eliminado bloqueos
    • svn_client_version - Devuelve la versión de las librerias del cliente SVN
    • svn_commit - Envía los cambios desde el directorio local de trabajo al repositorio
    • svn_delete - Elimina ítems de una copia de trabajo o repositorio
    • svn_diff - Compara dos rutas de acceso recursivamente
    • svn_export - Exporta el contenido de un directorio SVN
    • svn_fs_abort_txn - Cancelar una transacción, devuelve true si todo está bien, false de lo contrario
    • svn_fs_apply_text - Crea y devuelve una secuencia que se utilizará para reemplazar
    • svn_fs_begin_txn2 - Crear una nueva transacción
    • svn_fs_change_node_prop - Retorna verdadero si todo está ok, falso en caso contrario
    • svn_fs_check_path - Determina que tipo de elemento está apuntado por una ruta de acceso determinada, en un repositorio fsroot
    • svn_fs_contents_changed - Devuelve verdadero si el contenido es diferente, falso en caso contrario
    • svn_fs_copy - Copia un fichero o un directorio, devuelve true en caso de éxito, de lo contrario devuelve false
    • svn_fs_delete - Elimina un fichero o directorio, devuelve true en caso de éxito, en caso contrario devuele false
    • svn_fs_dir_entries - Enumera los directorios que hay bajo una ruta de acceso determinada; devuelve un array con los nombres de los directorios
    • svn_fs_file_contents - Devuelve un flujo de acceso al contenido de un fichero para una versión del sistema de ficheros dada
    • svn_fs_file_length - Devuelve la longitud de un fichero para una versión dada de sistema de ficheros
    • svn_fs_is_dir - Devuelve true si la ruta apunta a un directorio, false en caso contrario
    • svn_fs_is_file - Devuelve true si la ruta apunta a un fichero, falso en caso contrario
    • svn_fs_make_dir - Crea un nuevo directorio vacío, devuelve true en caso de éxito, en caso contrario devuelve false
    • svn_fs_make_file - Crea un nuevo fichero vacío, devuelve true en caso de éxito, false en caso contrario
    • svn_fs_node_created_rev - Devuelve la revisión en la que la ruta de acceso bajo fsroot fue creado
    • svn_fs_node_prop - Devuelve el valor de una propiedad de un nodo
    • svn_fs_props_changed - Devuelve verdadero si las propiedades son diferentes, falso en caso contrario
    • svn_fs_revision_prop - Recupera el valor de una propiedad con determinado nombre
    • svn_fs_revision_root - Obtiene un gestor en una versión específica del repositorio 'root'
    • svn_fs_txn_root - Crea y retorna una transacción 'root'
    • svn_fs_youngest_rev - Devuelve el número de la revisión más reciente del sistema de ficheros
    • svn_import - Importa una ruta de acceso sin versión, dentro de un repositorio
    • svn_log - Devuelve el log histórico de mensajes de un repositorio URL
    • svn_ls - Devuelve una lista del contenido del directorio en el repositorio URL, opcionalmente el número de revisión
    • svn_mkdir - Crea un directorio en la copia de trabajo actual o repositorio
    • svn_repos_create - Crea un nuevo repositorio de subversión
    • svn_repos_fs - Obtiene un gestor del sistema de ficheros para un repositorio
    • svn_repos_fs_begin_txn_for_commit - Crea una nueva transacción
    • svn_repos_fs_commit_txn - Consolida una transacción y devuelve la nueva revisión
    • svn_repos_hotcopy - Realiza una copia en caliente del repositorio en pathrepospath; y lo copia en destpath
    • svn_repos_open - Abre una cerradura compartida en un repositorio
    • svn_repos_recover - Ejecuta los procesos de recuperación en el repositorio localizado en un path determinado
    • svn_revert - Deshace los cambios en la copia de trabajo
    • svn_status - Devuelve el estado de la copia de trabajo de los ficheros y directorios
    • svn_update - Actualiza la copia de trabajo
    • Swoole\Async::dnsLookup - Async and non-blocking hostname to IP lookup.
    • Swoole\Async::read - Read file stream asynchronously.
    • Swoole\Async::readFile - Read a file asynchronously.
    • Swoole\Async::set - Update the async I/O options.
    • Swoole\Async::write - Write data to a file stream asynchronously.
    • Swoole\Async::writeFile - Description
    • Swoole\Atomic::add - Add a number to the value to the atomic object.
    • Swoole\Atomic::cmpset - Compare and set the value of the atomic object.
    • Swoole\Atomic::get - Get the current value of the atomic object.
    • Swoole\Atomic::set - Set a new value to the atomic object.
    • Swoole\Atomic::sub - Subtract a number to the value of the atomic object.
    • Swoole\Atomic::__construct - Construct a swoole atomic object.
    • Swoole\Buffer::append - Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.
    • Swoole\Buffer::clear - Reset the memory buffer.
    • Swoole\Buffer::expand - Expand the size of memory buffer.
    • Swoole\Buffer::read - Read data from the memory buffer based on offset and length.
    • Swoole\Buffer::recycle - Release the memory to OS which is not used by the memory buffer.
    • Swoole\Buffer::substr - Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.
    • Swoole\Buffer::write - Write data to the memory buffer. The memory allocated for the buffer will not be changed.
    • Swoole\Buffer::__construct - Fixed size memory blocks allocation.
    • Swoole\Buffer::__destruct - Destruct the Swoole memory buffer.
    • Swoole\Buffer::__toString - Get the string value of the memory buffer.
    • Swoole\Channel::pop - Read and pop data from swoole channel.
    • Swoole\Channel::push - Write and push data into Swoole channel.
    • Swoole\Channel::stats - Get stats of swoole channel.
    • Swoole\Channel::__construct - Construct a Swoole Channel
    • Swoole\Channel::__destruct - Destruct a Swoole channel.
    • Swoole\Client::close - Close the connection established.
    • Swoole\Client::connect - Connect to the remote TCP or UDP port.
    • Swoole\Client::getpeername - Get the remote socket name of the connection.
    • Swoole\Client::getsockname - Get the local socket name of the connection.
    • Swoole\Client::isConnected - Check if the connection is established.
    • Swoole\Client::on - Add callback functions triggered by events.
    • Swoole\Client::pause - Pause receiving data.
    • Swoole\Client::pipe - Redirect the data to another file descriptor.
    • Swoole\Client::recv - Receive data from the remote socket.
    • Swoole\Client::resume - Resume receiving data.
    • Swoole\Client::send - Send data to the remote TCP socket.
    • Swoole\Client::sendfile - Send file to the remote TCP socket.
    • Swoole\Client::sendto - Send data to the remote UDP address.
    • Swoole\Client::set - Set the Swoole client parameters before the connection is established.
    • Swoole\Client::sleep - Remove the TCP client from system event loop.
    • Swoole\Client::wakeup - Add the TCP client back into the system event loop.
    • Swoole\Client::__construct - Create Swoole sync or async TCP/UDP client, with or without SSL.
    • Swoole\Client::__destruct - Destruct the Swoole client.
    • Swoole\Connection\Iterator::count - Count connections.
    • Swoole\Connection\Iterator::current - Return current connection entry.
    • Swoole\Connection\Iterator::key - Return key of the current connection.
    • Swoole\Connection\Iterator::next - Move to the next connection.
    • Swoole\Connection\Iterator::offsetExists - Check if offet exists.
    • Swoole\Connection\Iterator::offsetGet - Offset to retrieve.
    • Swoole\Connection\Iterator::offsetSet - Assign a Connection to the specified offset.
    • Swoole\Connection\Iterator::offsetUnset - Unset an offset.
    • Swoole\Connection\Iterator::rewind - Rewinds iterator
    • Swoole\Connection\Iterator::valid - Check if current position is valid.
    • Swoole\Coroutine::call_user_func - Call a callback given by the first parameter
    • Swoole\Coroutine::call_user_func_array - Call a callback with an array of parameters
    • Swoole\Coroutine::cli_wait - Description
    • Swoole\Coroutine::create - Description
    • Swoole\Coroutine::getuid - Description
    • Swoole\Coroutine::resume - Description
    • Swoole\Coroutine::suspend - Description
    • Swoole\Coroutine\Client::close - Description
    • Swoole\Coroutine\Client::connect - Description
    • Swoole\Coroutine\Client::getpeername - Description
    • Swoole\Coroutine\Client::getsockname - Description
    • Swoole\Coroutine\Client::isConnected - Description
    • Swoole\Coroutine\Client::recv - Description
    • Swoole\Coroutine\Client::send - Description
    • Swoole\Coroutine\Client::sendfile - Description
    • Swoole\Coroutine\Client::sendto - Description
    • Swoole\Coroutine\Client::set - Description
    • Swoole\Coroutine\Client::__construct - Description
    • Swoole\Coroutine\Client::__destruct - Description
    • Swoole\Coroutine\Http\Client::addFile - Description
    • Swoole\Coroutine\Http\Client::close - Description
    • Swoole\Coroutine\Http\Client::execute - Description
    • Swoole\Coroutine\Http\Client::get - Description
    • Swoole\Coroutine\Http\Client::getDefer - Description
    • Swoole\Coroutine\Http\Client::isConnected - Description
    • Swoole\Coroutine\Http\Client::post - Description
    • Swoole\Coroutine\Http\Client::recv - Description
    • Swoole\Coroutine\Http\Client::set - Description
    • Swoole\Coroutine\Http\Client::setCookies - Description
    • Swoole\Coroutine\Http\Client::setData - Description
    • Swoole\Coroutine\Http\Client::setDefer - Description
    • Swoole\Coroutine\Http\Client::setHeaders - Description
    • Swoole\Coroutine\Http\Client::setMethod - Description
    • Swoole\Coroutine\Http\Client::__construct - Description
    • Swoole\Coroutine\Http\Client::__destruct - Description
    • Swoole\Coroutine\MySQL::close - Description
    • Swoole\Coroutine\MySQL::connect - Description
    • Swoole\Coroutine\MySQL::getDefer - Description
    • Swoole\Coroutine\MySQL::query - Description
    • Swoole\Coroutine\MySQL::recv - Description
    • Swoole\Coroutine\MySQL::setDefer - Description
    • Swoole\Coroutine\MySQL::__construct - Description
    • Swoole\Coroutine\MySQL::__destruct - Description
    • Swoole\Event::add - Add new callback functions of a socket into the EventLoop.
    • Swoole\Event::defer - Add a callback function to the next event loop.
    • Swoole\Event::del - Remove all event callback functions of a socket.
    • Swoole\Event::exit - Exit the eventloop, only available at client side.
    • Swoole\Event::set - Update the event callback functions of a socket.
    • Swoole\Event::wait - Description
    • Swoole\Event::write - Write data to the socket.
    • Swoole\Http\Client::addFile - Add a file to the post form.
    • Swoole\Http\Client::close - Close the http connection.
    • Swoole\Http\Client::download - Download a file from the remote server.
    • Swoole\Http\Client::execute - Send the HTTP request after setting the parameters.
    • Swoole\Http\Client::get - Send GET http request to the remote server.
    • Swoole\Http\Client::isConnected - Check if the HTTP connection is connected.
    • Swoole\Http\Client::on - Register callback function by event name.
    • Swoole\Http\Client::post - Send POST http request to the remote server.
    • Swoole\Http\Client::push - Push data to websocket client.
    • Swoole\Http\Client::set - Update the HTTP client paramters.
    • Swoole\Http\Client::setCookies - Set the http request cookies.
    • Swoole\Http\Client::setData - Set the HTTP request body data.
    • Swoole\Http\Client::setHeaders - Set the HTTP request headers.
    • Swoole\Http\Client::setMethod - Set the HTTP request method.
    • Swoole\Http\Client::upgrade - Upgrade to websocket protocol.
    • Swoole\Http\Client::__construct - Construct the async HTTP client.
    • Swoole\Http\Client::__destruct - Destruct the HTTP client.
    • Swoole\Http\Request::rawcontent - Get the raw HTTP POST body.
    • Swoole\Http\Request::__destruct - Destruct the HTTP request.
    • Swoole\Http\Response::cookie - Set the cookies of the HTTP response.
    • Swoole\Http\Response::end - Send data for the HTTP request and finish the response.
    • Swoole\Http\Response::gzip - Enable the gzip of response content.
    • Swoole\Http\Response::header - Set the HTTP response headers.
    • Swoole\Http\Response::initHeader - Init the HTTP response header.
    • Swoole\Http\Response::rawcookie - Set the raw cookies to the HTTP response.
    • Swoole\Http\Response::sendfile - Send file through the HTTP response.
    • Swoole\Http\Response::status - Set the status code of the HTTP response.
    • Swoole\Http\Response::write - Append HTTP body content to the HTTP response.
    • Swoole\Http\Response::__destruct - Destruct the HTTP response.
    • Swoole\Http\Server::on - Bind callback function to HTTP server by event name.
    • Swoole\Http\Server::start - Start the swoole http server.
    • Swoole\Lock::lock - Try to acquire the lock. It will block if the lock is not available.
    • Swoole\Lock::lock_read - Lock a read-write lock for reading.
    • Swoole\Lock::trylock - Try to acquire the lock and return straight away even the lock is not available.
    • Swoole\Lock::trylock_read - Try to lock a read-write lock for reading and return straight away even the lock is not available.
    • Swoole\Lock::unlock - Release the lock.
    • Swoole\Lock::__construct - Construct a memory lock.
    • Swoole\Lock::__destruct - Destory a Swoole memory lock.
    • Swoole\Mmap::open - Map a file into memory and return the stream resource which can be used by PHP stream operations.
    • Swoole\MySQL::close - Close the async MySQL connection.
    • Swoole\MySQL::connect - Connect to the remote MySQL server.
    • Swoole\MySQL::getBuffer - Description
    • Swoole\MySQL::on - Register callback function based on event name.
    • Swoole\MySQL::query - Run the SQL query.
    • Swoole\MySQL::__construct - Construct an async MySQL client.
    • Swoole\MySQL::__destruct - Destory the async MySQL client.
    • Swoole\Process::alarm - High precision timer which triggers signal with fixed interval.
    • Swoole\Process::close - Close the pipe to the child process.
    • Swoole\Process::daemon - Change the process to be a daemon process.
    • Swoole\Process::exec - Execute system commands.
    • Swoole\Process::exit - Stop the child processes.
    • Swoole\Process::freeQueue - Destroy the message queue created by swoole_process::useQueue.
    • Swoole\Process::kill - Send signal to the child process.
    • Swoole\Process::name - Set name of the process.
    • Swoole\Process::pop - Read and pop data from the message queue.
    • Swoole\Process::push - Write and push data into the message queue.
    • Swoole\Process::read - Read data sending to the process.
    • Swoole\Process::signal - Send signal to the child processes.
    • Swoole\Process::start - Start the process.
    • Swoole\Process::statQueue - Get the stats of the message queue used as the communication method between processes.
    • Swoole\Process::useQueue - Create a message queue as the communication method between the parent process and child processes.
    • Swoole\Process::wait - Wait for the events of child processes.
    • Swoole\Process::write - Write data into the pipe and communicate with the parent process or child processes.
    • Swoole\Process::__construct - Construct a process.
    • Swoole\Process::__destruct - Destory the process.
    • Swoole\Redis\Server::format - Description
    • Swoole\Redis\Server::setHandler - Description
    • Swoole\Redis\Server::start - Description
    • Swoole\Serialize::pack - Serialize the data.
    • Swoole\Serialize::unpack - Unserialize the data.
    • Swoole\Server::addlistener - Add a new listener to the server.
    • Swoole\Server::addProcess - Add a user defined swoole_process to the server.
    • Swoole\Server::after - Trigger a callback function after a period of time.
    • Swoole\Server::bind - Bind the connection to a user defined user ID.
    • Swoole\Server::clearTimer - Stop and destory a timer.
    • Swoole\Server::close - Close a connection to the client.
    • Swoole\Server::confirm - Check status of the connection.
    • Swoole\Server::connection_info - Get the connection info by file description.
    • Swoole\Server::connection_list - Get all of the established connections.
    • Swoole\Server::defer - Delay execution of the callback function at the end of current EventLoop.
    • Swoole\Server::exist - Check if the connection is existed.
    • Swoole\Server::finish - Used in task process for sending result to the worker process when the task is finished.
    • Swoole\Server::getClientInfo - Get the connection info by file description.
    • Swoole\Server::getClientList - Get all of the established connections.
    • Swoole\Server::getLastError - Get the error code of the most recent error.
    • Swoole\Server::heartbeat - Check all the connections on the server.
    • Swoole\Server::listen - Listen on the given IP and port, socket type.
    • Swoole\Server::on - Register a callback function by event name.
    • Swoole\Server::pause - Stop receiving data from the connection.
    • Swoole\Server::protect - Set the connection to be protected mode.
    • Swoole\Server::reload - Restart all the worker process.
    • Swoole\Server::resume - Start receving data from the connection.
    • Swoole\Server::send - Send data to the client.
    • Swoole\Server::sendfile - Send file to the connection.
    • Swoole\Server::sendMessage - Send message to worker processes by ID.
    • Swoole\Server::sendto - Send data to the remote UDP address.
    • Swoole\Server::sendwait - Send data to the remote socket in the blocking way.
    • Swoole\Server::set - Set the runtime settings of the swoole server.
    • Swoole\Server::shutdown - Shutdown the master server process, this function can be called in worker processes.
    • Swoole\Server::start - Start the Swoole server.
    • Swoole\Server::stats - Get the stats of the Swoole server.
    • Swoole\Server::stop - Stop the Swoole server.
    • Swoole\Server::task - Send data to the task worker processes.
    • Swoole\Server::taskwait - Send data to the task worker processes in blocking way.
    • Swoole\Server::taskWaitMulti - Execute multiple tasks concurrently.
    • Swoole\Server::tick - Repeats a given function at every given time-interval.
    • Swoole\Server::__construct - Construct a Swoole server.
    • Swoole\Server\Port::on - Register callback functions by event.
    • Swoole\Server\Port::set - Set protocol of the server port.
    • Swoole\Server\Port::__construct - Construct a server port
    • Swoole\Server\Port::__destruct - Destory server port
    • Swoole\Table::column - Set the data type and size of the columns.
    • Swoole\Table::count - Count the rows in the table, or count all the elements in the table if $mode = 1.
    • Swoole\Table::create - Create the swoole memory table.
    • Swoole\Table::current - Get the current row.
    • Swoole\Table::decr - Decrement the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::del - Delete a row in the Swoole table by $row_key.
    • Swoole\Table::destroy - Destroy the Swoole table.
    • Swoole\Table::exist - Check if a row is existed by $row_key.
    • Swoole\Table::get - Get the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::incr - Increment the value by $row_key and $column_key.
    • Swoole\Table::key - Get the key of current row.
    • Swoole\Table::next - Iterator the next row.
    • Swoole\Table::rewind - Rewind the iterator.
    • Swoole\Table::set - Update a row of the table by $row_key.
    • Swoole\Table::valid - Check current if the current row is valid.
    • Swoole\Table::__construct - Construct a Swoole memory table with fixed size.
    • Swoole\Timer::after - Trigger a callback function after a period of time.
    • Swoole\Timer::clear - Delete a timer by timer ID.
    • Swoole\Timer::exists - Check if a timer is existed.
    • Swoole\Timer::tick - Repeats a given function at every given time-interval.
    • Swoole\WebSocket\Server::exist - Check if the file descriptor exists.
    • Swoole\WebSocket\Server::on - Register event callback function
    • Swoole\WebSocket\Server::pack - Get a pack of binary data to send in a single frame.
    • Swoole\WebSocket\Server::push - Push data to the remote client.
    • Swoole\WebSocket\Server::unpack - Unpack the binary data received from the client.
    • swoole_async_dns_lookup - Async and non-blocking hostname to IP lookup
    • swoole_async_read - Read file stream asynchronously
    • swoole_async_readfile - Read a file asynchronously
    • swoole_async_set - Update the async I/O options
    • swoole_async_write - Write data to a file stream asynchronously
    • swoole_async_writefile - Write data to a file asynchronously
    • swoole_client_select - Get the file description which are ready to read/write or error
    • swoole_cpu_num - Get the number of CPU
    • swoole_errno - Get the error code of the latest system call
    • swoole_event_add - Add new callback functions of a socket into the EventLoop
    • swoole_event_defer - Add callback function to the next event loop
    • swoole_event_del - Remove all event callback functions of a socket
    • swoole_event_exit - Exit the eventloop, only available at the client side
    • swoole_event_set - Update the event callback functions of a socket
    • swoole_event_wait - Start the event loop
    • swoole_event_write - Write data to a socket
    • swoole_get_local_ip - Get the IPv4 IP addresses of each NIC on the machine
    • swoole_last_error - Get the lastest error message
    • swoole_load_module - Load a swoole extension
    • swoole_select - Select the file descriptions which are ready to read/write or error in the eventloop
    • swoole_set_process_name - Set the process name
    • swoole_strerror - Convert the Errno into error messages
    • swoole_timer_after - Trigger a one time callback function in the future
    • swoole_timer_exists - Check if a timer callback function is existed
    • swoole_timer_tick - Trigger a timer tick callback function by time interval
    • swoole_version - Get the version of Swoole
    • symlink - Crea un enlace simbólico
    • SyncEvent::fire - Fires/sets the event
    • SyncEvent::reset - Resets a manual event
    • SyncEvent::wait - Waits for the event to be fired/set
    • SyncEvent::__construct - Constructs a new SyncEvent object
    • SyncMutex::lock - Waits for an exclusive lock
    • SyncMutex::unlock - Unlocks the mutex
    • SyncMutex::__construct - Constructs a new SyncMutex object
    • SyncReaderWriter::readlock - Waits for a read lock
    • SyncReaderWriter::readunlock - Releases a read lock
    • SyncReaderWriter::writelock - Waits for an exclusive write lock
    • SyncReaderWriter::writeunlock - Releases a write lock
    • SyncReaderWriter::__construct - Constructs a new SyncReaderWriter object
    • SyncSemaphore::lock - Decreases the count of the semaphore or waits
    • SyncSemaphore::unlock - Increases the count of the semaphore
    • SyncSemaphore::__construct - Constructs a new SyncSemaphore object
    • SyncSharedMemory::first - Check to see if the object is the first instance system-wide of named shared memory
    • SyncSharedMemory::read - Copy data from named shared memory
    • SyncSharedMemory::size - Returns the size of the named shared memory
    • SyncSharedMemory::write - Copy data to named shared memory
    • SyncSharedMemory::__construct - Constructs a new SyncSharedMemory object
    • syslog - Genera un mensaje log de sistema
    • system - Ejecutar un programa externo y mostrar su salida
    • sys_getloadavg - Obtiene la carga media del sistema
    • sys_get_temp_dir - Devuelve la ruta del directorio para archivos temporales
  • t
    • taint - Corrompe un string
    • tan - Tangente
    • tanh - Tangente hiperbólica
    • tcpwrap_check - Realiza una comprobación tcpwrap
    • tempnam - Crea un fichero con un nombre de fichero único
    • textdomain - Establece el dominio actual
    • Thread::detach - Ejecución
    • Thread::getCreatorId - Identificación
    • Thread::getCurrentThread - Identificación
    • Thread::getCurrentThreadId - Identification
    • Thread::getThreadId - Identification
    • Thread::globally - Execution
    • Thread::isJoined - State Detection
    • Thread::isStarted - State Detection
    • Thread::join - Synchronization
    • Thread::kill - Ejecución
    • Thread::start - Execution
    • Threaded::chunk - Manipulation
    • Threaded::count - Manipulation
    • Threaded::extend - Runtime Manipulation
    • Threaded::from - Creation
    • Threaded::getTerminationInfo - Error Detection
    • Threaded::isRunning - State Detection
    • Threaded::isTerminated - State Detection
    • Threaded::isWaiting - State Detection
    • Threaded::lock - Synchronization
    • Threaded::merge - Manipulation
    • Threaded::notify - Synchronization
    • Threaded::notifyOne - Synchronization
    • Threaded::pop - Manipulation
    • Threaded::run - Execution
    • Threaded::shift - Manipulation
    • Threaded::synchronized - Synchronization
    • Threaded::unlock - Synchronization
    • Threaded::wait - Synchronization
    • Throwable::getCode - Obtener el código de la excepción
    • Throwable::getFile - Obtiene el fichero en el que se creó el objeto
    • Throwable::getLine - Obtiene la línea en la que el objeto fue instanciado
    • Throwable::getMessage - Obtiene el mensaje
    • Throwable::getPrevious - Devuelve el objeto Throwable previo
    • Throwable::getTrace - Obtener la traza de la pila
    • Throwable::getTraceAsString - Obtener la traza de la pila como un string
    • Throwable::__toString - Obtiene un representación de string del objeto lanzado
    • tidy::$errorBuffer - Devuelve advertencias y errores que ocurrieron al analizar el documento especificado
    • tidy::body - Devuelve un objeto tidyNode empezando con la etiqueta <body>
    • tidy::cleanRepair - Ejecuta una operación de limpieza y reparación de las etiquetas HTML
    • tidy::diagnose - Ejecuta un diagnóstico sobre documento analizado y reparado
    • tidy::getConfig - Obtiene la configuración actual de Tidy
    • tidy::getHtmlVer - Obtiene la versión detectada de HTML en un documento especificado
    • tidy::getOpt - Devuelve el valor de la opción de configuración especificada para el documento tidy
    • tidy::getOptDoc - Devuelve la documentación correspondiente a un nombre de opción dado
    • tidy::getRelease - Obtiene la fecha de lanzamiento (versión) de la librería Tidy
    • tidy::getStatus - Obtiene el status de un documento especificado
    • tidy::head - Devuelve un objeto tidyNode empezando con la etiqueta <head>
    • tidy::html - Devuelve un objeto tidyNode empezando con la etiqueta <html>
    • tidy::isXhtml - Indica si el documento es XHTML
    • tidy::isXml - Indica si el documento es XML (no HTML/XHTML)
    • tidy::parseFile - Analiza las etiquetas de un fichero o URI
    • tidy::parseString - Analiza un documento almacenado en una cadena
    • tidy::repairFile - Repara un archivo y lo devuelve como una cadena
    • tidy::repairString - Repara una cadena HTML usando un archivo de configuración opcional
    • tidy::root - Devuelve un objeto tidyNode que representa la raíz del árbol analizado por tidy
    • tidy::__construct - Construye un nuevo objeto tidy
    • tidyNode::getParent - Devuelve el nodo padre del nodo actual
    • tidyNode::hasChildren - Indica si un nodo tiene hijos
    • tidyNode::hasSiblings - Indica si un nodo tiene hermanos
    • tidyNode::isAsp - Comprueba si el nodo es ASP
    • tidyNode::isComment - Comprueba el nodo actual es un comentario
    • tidyNode::isHtml - Comprueba si el nodo es parte de un documento HTML
    • tidyNode::isJste - Comprueba si el nodo es JSTE
    • tidyNode::isPhp - Comprueba si el nodo es PHP
    • tidyNode::isText - Comprueba si un nodo representa un texto (no HTML)
    • tidyNode::__construct - Private constructor to disallow direct instantiation
    • tidy_access_count - Devuelve el número de alertas de accesibilidad Tidy encontradas en un documento dado
    • tidy_config_count - Devuelve el número de errores de configuración Tidy encontrados en un documento dado
    • tidy_error_count - Devuelve el número de errores Tidy encontrados en un documento dado
    • tidy_get_output - Devuelve una cadena que contiene las etiquetas analizadas por Tidy
    • tidy_warning_count - Devuelve el número de alertas encontradas en un documendo dado
    • time - Devuelve la fecha Unix actual
    • 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 - Devuelve el nombre de la zona horaria desde su abreviatura
    • 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 - Obtiene la versión de la base de datos timezonedb
    • time_nanosleep - Retrasar por un número de segundos y nanosegundos
    • time_sleep_until - Hacer que el script duerma hasta el momento especificado
    • tmpfile - Crea un archivo temporal
    • token_get_all - Divide la fuente dada en tokens PHP
    • token_name - Obtiene el nombre simbólico de un token PHP dado
    • TokyoTyrant::add - Adds to a numeric key
    • TokyoTyrant::connect - Connect to a database
    • TokyoTyrant::connectUri - Connects to a database
    • TokyoTyrant::copy - Copies the database
    • TokyoTyrant::ext - Execute a remote script
    • TokyoTyrant::fwmKeys - Returns the forward matching keys
    • TokyoTyrant::get - The get purpose
    • TokyoTyrant::getIterator - Get an iterator
    • TokyoTyrant::num - Number of records in the database
    • TokyoTyrant::out - Removes records
    • TokyoTyrant::put - Puts values
    • TokyoTyrant::putCat - Concatenates to a record
    • TokyoTyrant::putKeep - Puts a record
    • TokyoTyrant::putNr - Puts value
    • TokyoTyrant::putShl - Concatenates to a record
    • TokyoTyrant::restore - Restore the database
    • TokyoTyrant::setMaster - Set the replication master
    • TokyoTyrant::size - Returns the size of the value
    • TokyoTyrant::stat - Get statistics
    • TokyoTyrant::sync - Synchronize the database
    • TokyoTyrant::tune - Tunes connection values
    • TokyoTyrant::vanish - Empties the database
    • TokyoTyrant::__construct - Construct a new TokyoTyrant object
    • TokyoTyrantIterator::current - Get the current value
    • TokyoTyrantIterator::key - Returns the current key
    • TokyoTyrantIterator::next - Move to next key
    • TokyoTyrantIterator::rewind - Rewinds the iterator
    • TokyoTyrantIterator::valid - Rewinds the iterator
    • TokyoTyrantIterator::__construct - Construct an iterator
    • TokyoTyrantQuery::addCond - Adds a condition to the query
    • TokyoTyrantQuery::count - Counts records
    • TokyoTyrantQuery::current - Returns the current element
    • TokyoTyrantQuery::hint - Get the hint string of the query
    • TokyoTyrantQuery::key - Returns the current key
    • TokyoTyrantQuery::metaSearch - Retrieve records with multiple queries
    • TokyoTyrantQuery::next - Moves the iterator to next entry
    • TokyoTyrantQuery::out - Removes records based on query
    • TokyoTyrantQuery::rewind - Rewinds the iterator
    • TokyoTyrantQuery::search - Searches records
    • TokyoTyrantQuery::setLimit - Limit results
    • TokyoTyrantQuery::setOrder - Orders results
    • TokyoTyrantQuery::valid - Checks the validity of current item
    • TokyoTyrantQuery::__construct - Construct a new query
    • TokyoTyrantTable::add - Adds a record
    • TokyoTyrantTable::genUid - Generate unique id
    • TokyoTyrantTable::get - Get a row
    • TokyoTyrantTable::getIterator - Get an iterator
    • TokyoTyrantTable::getQuery - Get a query object
    • TokyoTyrantTable::out - Remove records
    • TokyoTyrantTable::put - Store a row
    • TokyoTyrantTable::putCat - Concatenates to a row
    • TokyoTyrantTable::putKeep - Put a new record
    • TokyoTyrantTable::putNr - Puts value
    • TokyoTyrantTable::putShl - Concatenates to a record
    • TokyoTyrantTable::setIndex - Sets index
    • touch - Establece el momento de acceso y modificación de un archivo
    • trader_acos - Arcocoseno trigonométrico de vectores
    • trader_ad - Línea A/D Chaikin
    • trader_add - Suma aritmética de vectores
    • trader_adosc - Oscilador A/D Chaikin
    • trader_adx - Índice de movimiento direccional medio
    • trader_adxr - Tasación del índice de movimiento direccional medio
    • trader_apo - Oscilador de precio absoluto
    • trader_aroon - Aroon
    • trader_aroonosc - Oscilador Aroon
    • trader_asin - Arcoseno trigonométrico de vectores
    • trader_atan - Arcotangente trigonométrica de vectores
    • trader_atr - Rango verdadero medio
    • trader_avgprice - Precio medio
    • trader_bbands - Bandas de Bollinger
    • trader_beta - Beta
    • trader_bop - Equilibrio de poder
    • trader_cci - Índice de Canal de Comodidad
    • trader_cdl2crows - Dos Cuervos
    • trader_cdl3blackcrows - Tres Cuervos Negros
    • trader_cdl3inside - Tres Velas Interiores Alcistas/Bajistas
    • trader_cdl3linestrike - Triple Golpe
    • trader_cdl3outside - Tres Velas Exteriores Alcistas/Bajistas
    • trader_cdl3starsinsouth - Tres Estrellas en el Sur
    • trader_cdl3whitesoldiers - Tres Soldados Blancos Avanzando
    • trader_cdlabandonedbaby - Bebé Abandonado
    • trader_cdladvanceblock - Avance en Bloque
    • trader_cdlbelthold - Belt-hold
    • trader_cdlbreakaway - Escape
    • trader_cdlclosingmarubozu - Vela Cerrada Marubozu
    • trader_cdlconcealbabyswall - Pequeña Golondrina Escondida
    • trader_cdlcounterattack - Contraataque
    • trader_cdldarkcloudcover - Cubierta de Nube Oscura
    • trader_cdldoji - Doji
    • trader_cdldojistar - Estrella Doji
    • trader_cdldragonflydoji - Doji Libélula
    • trader_cdlengulfing - Patrón envolvente
    • trader_cdleveningdojistar - Estrella Vespertina Doji
    • trader_cdleveningstar - Estrella de Atardecer
    • trader_cdlgapsidesidewhite - Velas blancas paralelas de hueco alcista/bajista
    • trader_cdlgravestonedoji - Doji Lápida
    • trader_cdlhammer - Martillo
    • trader_cdlhangingman - Hombre Colgado
    • trader_cdlharami - Patrón Harami
    • trader_cdlharamicross - Patrón Cruz Harami
    • trader_cdlhighwave - Vela de Onda Alta
    • trader_cdlhikkake - Patrón Hikkake
    • trader_cdlhikkakemod - Patrón Hikkake Modificado
    • trader_cdlhomingpigeon - Paloma Mensajera
    • trader_cdlidentical3crows - Tres Cuervos Idénticos
    • trader_cdlinneck - Patrón Formación en el cuello
    • trader_cdlinvertedhammer - Martilllo Invertido
    • trader_cdlkicking - Patada
    • trader_cdlkickingbylength - Patada - alza/baja determinada por el marubozu más largo
    • trader_cdlladderbottom - Suelo de escalera
    • trader_cdllongleggeddoji - Doji Zancudo
    • trader_cdllongline - Vela de Línea Larga
    • trader_cdlmarubozu - Marubozu
    • trader_cdlmatchinglow - Mínimos coincidentes
    • trader_cdlmathold - Mat Hold
    • trader_cdlmorningdojistar - Lucero del Alba Doji
    • trader_cdlmorningstar - Lucero del Alba
    • trader_cdlonneck - Patrón Sobre el cuello
    • trader_cdlpiercing - Patrón penetrante
    • trader_cdlrickshawman - Calesero
    • trader_cdlrisefall3methods - Triple Formación Alcista/Bajista
    • trader_cdlseparatinglines - Lineas Separadas
    • trader_cdlshootingstar - Estrella Fugaz
    • trader_cdlshortline - Vela de Línea Corta
    • trader_cdlspinningtop - Peonza
    • trader_cdlstalledpattern - Patrón Añejo
    • trader_cdlsticksandwich - Bocadillo
    • trader_cdltakuri - Takuri (Libélula Doji con sombra muy larga)
    • trader_cdltasukigap - Hueco Tasuki
    • trader_cdlthrusting - Patrón de empuje
    • trader_cdltristar - Patrón de tres estrellas
    • trader_cdlunique3river - Tres ríos únicos
    • trader_cdlupsidegap2crows - Dos Cuervos tras un Huevo al Alza
    • trader_cdlxsidegap3methods - Métodos de Tres Huevos al Alza/Baja
    • trader_ceil - Redondeo hacia arriba de vectores
    • trader_cmo - Oscilador de momento de Chande
    • trader_correl - Coeficiente de correlación de Pearson (r)
    • trader_cos - Coseno trigonométrico de vectores
    • trader_cosh - Coseno hiperbólico de un vector
    • trader_dema - Media móvil exponencial doble
    • trader_div - División aritmética de vectores
    • trader_dx - Índice de movimiento direccional
    • trader_ema - Media móvil exponencial
    • trader_errno - Obtener el código de error
    • trader_exp - Exponencial aritmética de vectores
    • trader_floor - Redondeo hacia abajo de vectores
    • trader_get_compat - Obtiene el modo de compatibilidad
    • trader_get_unstable_period - Obtiene el periodo inestable
    • trader_ht_dcperiod - Transformación de Hilbert - Período de ciclo dominante
    • trader_ht_dcphase - Transformación de Hilbert - Fase de ciclo dominante
    • trader_ht_phasor - Transformación de Hilbert - Componentes de un fasor
    • trader_ht_sine - Transformación de Hilbert - Sinusoide
    • trader_ht_trendline - Transformación de Hilbert - Línea de tendencia instantánea
    • trader_ht_trendmode - Transformación de Hilbert - Tendencia vs Modo de ciclo
    • trader_kama - Media móvil adaptativa de Kaufman
    • trader_linearreg - Regresión lineal
    • trader_linearreg_angle - Ángulo de regresión lineal
    • trader_linearreg_intercept - Intercepción de regresión lineal
    • trader_linearreg_slope - Pendiente de regresión lineal
    • trader_ln - Logaritmo natural de vectores
    • trader_log10 - Logaritmo en base 10 de vectores
    • trader_ma - Media móvil
    • trader_macd - Convergencia/divergencia de la media móvil
    • trader_macdext - MACD con tipo MA controlable
    • trader_macdfix - Convergencia/divergencia fija 12/26 de la media móvil
    • trader_mama - Media móvil adaptativa MESA
    • trader_mavp - Media móvil con periodo variable
    • trader_max - Valor mayor sobre un periodo especificado
    • trader_maxindex - Índice del valor mayor sobre un periodo especificado
    • trader_medprice - Precio medio
    • trader_mfi - Índice de flujo de dinero
    • trader_midpoint - Punto medio sobre un periodo
    • trader_midprice - Precio de punto medio sobre un periodo
    • trader_min - Valor más bajo sobre un periodo especificado
    • trader_minindex - Índice del valor más bajo sobre un periodo especificado
    • trader_minmax - Valores más altos y bajos sobre un periodo especificado
    • trader_minmaxindex - Índices de los valores más bajos y altos sobre un periodo especificado
    • trader_minus_di - Indicador direccional menos
    • trader_minus_dm - Movimiento direccional menos
    • trader_mom - Momentum
    • trader_mult - Multiplicación aritmética de vectores
    • trader_natr - Rango verdadero de la media normalizada
    • trader_obv - Volumen sobre balance
    • trader_plus_di - Indicador direccional más
    • trader_plus_dm - Movimiento direccional más
    • trader_ppo - Oscilador de precio porcentual
    • trader_roc - Ritmo de cambio : ((precio/precioAnterior)-1)*100
    • trader_rocp - Porcentaje del ritmo de cabio: (precio-precioAnterior)/precioAnterior
    • trader_rocr - Ratio del ritmo de cambio: (precio/precioAnterior)
    • trader_rocr100 - Ratio del ritmo de cambio en escala 100: (precio/precioAnterior)*100
    • trader_rsi - Índice de fuerza relativa
    • trader_sar - Sistema parabólico
    • trader_sarext - Sistema parabólico - Extendido
    • trader_set_compat - Establece el modo de compatibilidad
    • trader_set_unstable_period - Establece el periodo inestable
    • trader_sin - Seno trigonométrico de vectores
    • trader_sinh - Seno hiperbólico de vectores
    • trader_sma - Media móvil simple
    • trader_sqrt - Raíz cuadrada de vectores
    • trader_stddev - Desviación estándar
    • trader_stoch - Estocástico
    • trader_stochf - Estocástico rápido
    • trader_stochrsi - Índice de fuerza relativa estocástica
    • trader_sub - Sustracción artimética de vectores
    • trader_sum - Sumatorio
    • trader_t3 - Media móvil exponencial triple (T3)
    • trader_tan - Tangente trigonométrica de vectores
    • trader_tanh - Tangente hiperbólica trigonométrica de vectores
    • trader_tema - Media móvil exponencial triple
    • trader_trange - Rango verdadero
    • trader_trima - Media móvil triangular
    • trader_trix - Ritmo de cambio de 1 día (RDC) de una MME suave triple
    • trader_tsf - Previsión de series de tiempo
    • trader_typprice - Precio típico
    • trader_ultosc - Oscilador final
    • trader_var - Varianza
    • trader_wclprice - Precio de cierre ponderado
    • trader_willr - %R de Williams
    • trader_wma - Media móvil ponderada
    • trait_exists - Comprobar si el trait existe
    • Transliterator::create - Crear un transliterador
    • Transliterator::createFromRules - Crear un transliterador desdes normas
    • Transliterator::createInverse - Cerar una transliteración inversa
    • Transliterator::getErrorCode - Obtener el código del último error
    • Transliterator::getErrorMessage - Obtener el mensaje del último error
    • Transliterator::listIDs - Obtener los IDs de los transliterardores
    • Transliterator::transliterate - Transliterar una cadena
    • Transliterator::__construct - Constructor privado para denegar la instanciación
    • trigger_error - Generar un mensaje de error/advertencia/aviso de nivel de usuario
    • trim - Elimina espacio en blanco (u otro tipo de caracteres) del inicio y el final de la cadena
  • u
    • uasort - Ordena un array con una función de comparación definida por el usuario y mantiene la asociación de índices
    • ucfirst - Convierte el primer caracter de una cadena a mayúsculas
    • UConverter::convert - Convertir un string de un juego de caracteres a otro
    • UConverter::fromUCallback - Función de retrollamada "from" predeterminada
    • UConverter::getAliases - Obtener los alias del nombre dado
    • UConverter::getAvailable - Obtener los nombres canónicos de los convertidores disponibles
    • UConverter::getDestinationEncoding - Obtener la codificación de destino
    • UConverter::getDestinationType - Obtener el tipo del convertidor de destino
    • UConverter::getErrorCode - Obtener el código del último error del objeto
    • UConverter::getErrorMessage - Obtener el último mensaje de error del objeto
    • UConverter::getSourceEncoding - Obtener la codificación de origen
    • UConverter::getSourceType - Obtener el tipo de convertidor de origen
    • UConverter::getStandards - Obtener los estándares asociados a los nombres de los convertidores
    • UConverter::getSubstChars - Obtener los caracteres de sustitución
    • UConverter::reasonText - Obtener la representación de string de la razón de la retrollamada
    • UConverter::setDestinationEncoding - Establecer la codificación destino
    • UConverter::setSourceEncoding - Establecer la codificación origen
    • UConverter::setSubstChars - Establecer los caracteres de sustitución
    • UConverter::toUCallback - Función de retrollamada "to" predeterminada
    • UConverter::transcode - Convertir un string de un juego de caracteres a otro
    • UConverter::__construct - Crea un objeto UConverter
    • ucwords - Convierte a mayúsculas el primer caracter de cada palabra de una cadena
    • 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 - Manipulación de color
    • UI\Draw\Color::setChannel - Manipulación de color
    • UI\Draw\Color::__construct - Construye un nuevo color
    • UI\Draw\Matrix::invert - Invertir matriz
    • UI\Draw\Matrix::isInvertible - Detección de invertido
    • UI\Draw\Matrix::multiply - Multiplica la matriz
    • UI\Draw\Matrix::rotate - Rota la matriz
    • UI\Draw\Matrix::scale - Escala la Matriz
    • UI\Draw\Matrix::skew - Inclina la Matriz
    • UI\Draw\Matrix::translate - Traduce la matriz
    • UI\Draw\Path::addRectangle - Dibuja un rectángulo
    • UI\Draw\Path::arcTo - Dibuja un arco
    • UI\Draw\Path::bezierTo - Draw Bezier Curve
    • UI\Draw\Path::closeFigure - Cerrar Figura
    • UI\Draw\Path::end - Finalizar Ruta
    • UI\Draw\Path::lineTo - Dibuja una línea
    • UI\Draw\Path::newFigure - Dibuja figura
    • UI\Draw\Path::newFigureWithArc - Dibuja figura con arco
    • UI\Draw\Path::__construct - Construye una nueva ruta
    • UI\Draw\Pen::clip - Clip a Path
    • UI\Draw\Pen::fill - Llena una ruta
    • UI\Draw\Pen::restore - Restaura
    • UI\Draw\Pen::save - Guarda
    • UI\Draw\Pen::stroke - Traza una ruta
    • UI\Draw\Pen::transform - Transformación de la matriz
    • UI\Draw\Pen::write - Dibuja el texto en el punto
    • UI\Draw\Stroke::getCap - Get Line Cap
    • UI\Draw\Stroke::getJoin - Obtiene la unión de línea
    • UI\Draw\Stroke::getMiterLimit - Obtiene el límite de inglete
    • UI\Draw\Stroke::getThickness - Obtiene el grosor
    • UI\Draw\Stroke::setCap - Set Line Cap
    • UI\Draw\Stroke::setJoin - Establece la línea de unión
    • UI\Draw\Stroke::setMiterLimit - Establece el límite de ingletes
    • UI\Draw\Stroke::setThickness - Establece el grosor
    • UI\Draw\Stroke::__construct - Construye un nuevo trazo
    • UI\Draw\Text\Font::getAscent - Métricas de la fuente
    • UI\Draw\Text\Font::getDescent - Métricas de la fuente
    • UI\Draw\Text\Font::getLeading - Métricas de la fuente
    • UI\Draw\Text\Font::getUnderlinePosition - Métricas de la fuente
    • UI\Draw\Text\Font::getUnderlineThickness - Métricas de la fuente
    • UI\Draw\Text\Font::__construct - Construye una nueva fuente
    • 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 - Recuperar las familias de fuentes
    • UI\Draw\Text\Layout::setColor - Establece el color
    • UI\Draw\Text\Layout::setWidth - Establece el ancho
    • UI\Draw\Text\Layout::__construct - Construir un nuevo diseño de texto
    • 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 - Añade elemento de menú
    • UI\Menu::appendAbout - Añade elemento de menú Acerca de
    • UI\Menu::appendCheck - Añade un elemento de menú comprobable
    • UI\Menu::appendPreferences - Añade elemento de menú de preferencias
    • UI\Menu::appendQuit - Añade elemento de menú salir
    • UI\Menu::appendSeparator - Añade separador de elementos del menú
    • UI\Menu::__construct - Construye un nuevo menú
    • UI\MenuItem::disable - Desactiva elemento del menú
    • UI\MenuItem::enable - Activa elemento de menú
    • UI\MenuItem::isChecked - Detecta Marcado
    • UI\MenuItem::onClick - Llamada de retorno On Click
    • UI\MenuItem::setChecked - Establece marcado
    • UI\Point::at - Tamaño de coerción
    • UI\Point::getX - Recupera X
    • UI\Point::getY - Recupera Y
    • UI\Point::setX - Establece X
    • UI\Point::setY - Establece Y
    • UI\Point::__construct - Construye un nuevo punto
    • UI\quit - Quit UI Loop
    • UI\run - Enter UI Loop
    • UI\Size::getHeight - Recupera la altura
    • UI\Size::getWidth - Recupera el ancho
    • UI\Size::of - Punto de coerción
    • UI\Size::setHeight - Establece la altura
    • UI\Size::setWidth - Establece el ancho
    • UI\Size::__construct - Construye un nuevo tamaño
    • UI\Window::add - Añade un control
    • UI\Window::error - Mostrar cuadro de error
    • UI\Window::getSize - Obtiene el tamaño de la ventana
    • UI\Window::getTitle - Obtiene el título
    • UI\Window::hasBorders - Detección del Borde
    • UI\Window::hasMargin - Detección de Margen
    • UI\Window::isFullScreen - Detección de pantalla completa
    • UI\Window::msg - Mostrar Cuadro de Mensajes
    • UI\Window::onClosing - Cierre de la devolución de llamada
    • UI\Window::open - Abrir Diálogo
    • UI\Window::save - Guarda Diálogo
    • UI\Window::setBorders - Uso de Bordes
    • UI\Window::setFullScreen - Uso de la pantalla completa
    • UI\Window::setMargin - Uso del Margen
    • UI\Window::setSize - Establece Tamaño
    • UI\Window::setTitle - Título de la Vetana
    • UI\Window::__construct - Construye una nueva ventana
    • uksort - Ordena un array según sus claves usando una función de comparación definida por el usuario
    • umask - Cambia la máscara de usuario actual
    • uniqid - Generar un ID único
    • unixtojd - Convertir una fecha Unix en una Fecha Juliana
    • unlink - Borra un fichero
    • unpack - Desempaqueta datos de una cadena binaria
    • unregister_tick_function - Dejar de registrar una función para su ejecución en cada tick
    • unserialize - Crea un valor PHP a partir de una representación almacenada
    • unset - Destruye una variable especificada
    • untaint - Sanea un string
    • uopz_add_function - Adds non-existent function or method
    • uopz_allow_exit - Allows control over disabled exit opcode
    • uopz_backup - Backup a function
    • uopz_compose - Compose a class
    • uopz_copy - Copy a function
    • uopz_delete - Delete a function
    • uopz_del_function - Deletes previously added function or method
    • uopz_extend - Extend a class at runtime
    • uopz_flags - Get or set flags on function or class
    • uopz_function - Creates a function at runtime
    • uopz_get_exit_status - Retrieve the last set exit status
    • uopz_get_hook - Gets previously set hook on function or method
    • uopz_get_mock - Get the current mock for a class
    • uopz_get_property - Gets value of class or instance property
    • uopz_get_return - Gets a previous set return value for a function
    • uopz_get_static - Gets the static variables from function or method scope
    • uopz_implement - Implements an interface at runtime
    • uopz_overload - Overload a VM opcode
    • uopz_redefine - Redefine a constant
    • uopz_rename - Rename a function at runtime
    • uopz_restore - Restore a previously backed up function
    • uopz_set_hook - Sets hook to execute when entering a function or method
    • uopz_set_mock - Use mock instead of class for new objects
    • uopz_set_property - Sets value of existing class or instance property
    • uopz_set_return - Provide a return value for an existing function
    • uopz_set_static - Sets the static variables in function or method scope
    • uopz_undefine - Undefine a constant
    • uopz_unset_hook - Removes previously set hook on function or method
    • uopz_unset_mock - Unset previously set mock
    • uopz_unset_return - Unsets a previously set return value for a function
    • urldecode - Decodifica una cadena cifrada como URL
    • urlencode - Codifica como URL una cadena
    • user_error - Alias de trigger_error
    • use_soap_error_handler - Establecer si se desea utilizar el manejador de errores de SOAP
    • usleep - Retrasar la ejecución en microsegundos
    • usort - Ordena un array según sus valores usando una función de comparación definida por el usuario
    • utf8_decode - Convierte una cadena con los caracteres codificados ISO-8859-1 con UTF-8 a un sencillo byte ISO-8859-1
    • utf8_encode - Codifica un string ISO-8859-1 a UTF-8
  • v
    • V8Js::executeString - Execute a string as Javascript code
    • V8Js::getExtensions - Devolver un array de extensiones registradas
    • V8Js::getPendingException - Return pending uncaught Javascript exception
    • V8Js::registerExtension - Register Javascript extensions for V8Js
    • V8Js::__construct - Construct a new V8Js object
    • V8JsException::getJsFileName - El propósito getJsFileName
    • V8JsException::getJsLineNumber - El propósito getJsLineNumber
    • V8JsException::getJsSourceLine - El propósito getJsSourceLine
    • V8JsException::getJsTrace - El propósito getJsTrace
    • variant_abs - Devuelve el valor absoluto de una variante
    • variant_add - "Suma" dos variantes y devuelve el resultado
    • variant_and - Realiza una operación AND a nivel de bits entre dos variantes
    • variant_cast - Convertir una variante en un nuevo objeto variante de otro tipo
    • variant_cat - Concatena dos valores de variantes y devuelve el resultado
    • variant_cmp - Compara dos variantes
    • variant_date_from_timestamp - Devuelve una representación de variante de fecha de una fecha Unix
    • variant_date_to_timestamp - Convierte un valor de una variante de fecha/hora en una fecha Unix
    • variant_div - Devuelve el resultado de dividir dos variantes
    • variant_eqv - Realiza una equivalencia a nivel de bits en dos variantes
    • variant_fix - Devuelve la parte entera de una variante
    • variant_get_type - Devuelve el tipo de un objeto variante
    • variant_idiv - Convierte variantes a enteros y después devuelve el resultado dividiéndolos
    • variant_imp - Realiza una implicación a nivel de bits de dos variantes
    • variant_int - Devuelve la parte entera de una variante
    • variant_mod - Divide dos variantes y devuelve sólo el resto
    • variant_mul - Multiplica los valores de dos variantes
    • variant_neg - Realiza una negación lógica de una variante
    • variant_not - Realiza una negación NOT a nivel de bits en una variante
    • variant_or - Realiza una disyunción lógica de dos variantes
    • variant_pow - Devuelve el resultado de realizar la exponenciación con dos variantes
    • variant_round - Redondea una variante al número de lugares decimales especificado
    • variant_set - Asigna un nuevo valor para un objeto variante
    • variant_set_type - Convierte una variante en otro tipo "in situ"
    • variant_sub - Resta el valor de la variante derecha del valor de la varienta izquierda
    • variant_xor - Realiza una exclución lógica de dos variantes
    • VarnishAdmin::auth - Autentificar en una instancia de varnish
    • VarnishAdmin::ban - Prohibe URLs usando una expresión VCL
    • VarnishAdmin::banUrl - Prohibe una URL usando una expresión VCL
    • VarnishAdmin::clearPanic - Limpia mensajes de pánico de la instancia varnish
    • VarnishAdmin::connect - Conectarse a una interfaz de administración de instancias de varnish
    • VarnishAdmin::disconnect - Desconecta interfaz de administración de la instancia de varnish
    • VarnishAdmin::getPanic - Obtener el último mensaje de pánico en una instancia varnish
    • VarnishAdmin::getParams - Busca los parámetros de configuración de la instancia varnish actual
    • VarnishAdmin::isRunning - Comprueba si el proceso varnish esclavo está actualmente en marcha
    • VarnishAdmin::setCompat - Establece el parámetro de configuración de la clase compacta
    • VarnishAdmin::setHost - Establece el parámetro de configuración del host de la clase
    • VarnishAdmin::setIdent - Establece el parámetro de configuración de la identificación de la clase
    • VarnishAdmin::setParam - Establece los parámetros de configuración en la instancia varnish actual
    • VarnishAdmin::setPort - Establece el parámetro de configuración del puerto de clase
    • VarnishAdmin::setSecret - Establece los parámetros secretos de configuración de la clase
    • VarnishAdmin::setTimeout - Configura el parámetro de tiempo de espera de la clase
    • VarnishAdmin::start - Iniciar el proceso de varnish
    • VarnishAdmin::stop - Detener el proceso de varnish
    • VarnishAdmin::__construct - VarnishAdmin constructor
    • VarnishLog::getLine - Obtiene la siguiente línea de registro
    • VarnishLog::getTagName - Obtener la etiqueta de registro representada por su índice
    • VarnishLog::__construct - Constructor de Varnishlog
    • VarnishStat::getSnapshot - Obtener la instantánea actual de las estadísticas de instancia varnish
    • VarnishStat::__construct - Constructor VarnishStat
    • var_dump - Muestra información sobre una variable
    • var_export - Imprime o devuelve una representación string de una variable analizable
    • version_compare - Compara dos números de versiones estandarizados de PHP
    • vfprintf - Escribe un string con formato en un flujo
    • virtual - Realiza una sub-petición de Apache
    • vprintf - Muestra una cadena con formato
    • vsprintf - Devuelve una cadena con formato
    • Vtiful\Kernel\Excel::addSheet - Vtiful\Kernel\Excel addSheet
    • Vtiful\Kernel\Excel::autoFilter - Vtiful\Kernel\Excel autoFilter
    • Vtiful\Kernel\Excel::constMemory - Vtiful\Kernel\Excel constMemory
    • Vtiful\Kernel\Excel::data - Vtiful\Kernel\Excel data
    • Vtiful\Kernel\Excel::fileName - Vtiful\Kernel\Excel fileName
    • Vtiful\Kernel\Excel::getHandle - Vtiful\Kernel\Excel getHandle
    • Vtiful\Kernel\Excel::header - Vtiful\Kernel\Excel header
    • Vtiful\Kernel\Excel::insertFormula - Vtiful\Kernel\Excel insertFormula
    • Vtiful\Kernel\Excel::insertImage - Vtiful\Kernel\Excel insertImage
    • Vtiful\Kernel\Excel::insertText - Vtiful\Kernel\Excel insertText
    • Vtiful\Kernel\Excel::mergeCells - Vtiful\Kernel\Excel mergeCells
    • Vtiful\Kernel\Excel::output - Vtiful\Kernel\Excel output
    • Vtiful\Kernel\Excel::setColumn - Vtiful\Kernel\Excel setColumn
    • Vtiful\Kernel\Excel::setRow - Vtiful\Kernel\Excel setRow
    • Vtiful\Kernel\Excel::__construct - Vtiful\Kernel\Excel constructor
    • Vtiful\Kernel\Format::align - Vtiful\Kernel\Format align
    • Vtiful\Kernel\Format::bold - Vtiful\Kernel\Format bold
    • Vtiful\Kernel\Format::italic - Vtiful\Kernel\Format italic
    • Vtiful\Kernel\Format::underline - Vtiful\Kernel\Format underline
  • w
    • wddx_add_vars - Agrega variables a un paquete WDDX con un ID específico
    • wddx_deserialize - Deserializa un packet WDDX
    • wddx_packet_end - Finaliza un paquete WDDX con un ID específico
    • wddx_packet_start - Inicia un nuevo paquete WDDX con una estructura a dentro
    • wddx_serialize_value - Serializa una simple valor dentro de un paquete WDDX
    • wddx_serialize_vars - Serializa variables en un paquete WDDX
    • WeakMap::count - Cuenta el número de entradas vivas de un mapa
    • WeakMap::current - Devuelve el valor actual de la iteración
    • WeakMap::key - Devuelve la clave actual de la iteración
    • WeakMap::next - Avanza al siguiente elemento del mapa
    • WeakMap::offsetExists - Comprueba si un cierto objeto está en un mapa
    • WeakMap::offsetGet - Devuelve el valor apuntado por un cierto objeto
    • WeakMap::offsetSet - Actualiza el mapa con un nuevo par clave-valor
    • WeakMap::offsetUnset - Elimina una entrada del mapa
    • WeakMap::rewind - Sitúa el iterador al comienzo del mapa
    • WeakMap::valid - Devuelve si el iterador aún está sobre un elemento válido de un mapa
    • WeakMap::__construct - Construye un nuevo mapa
    • Weakref::acquire - Adquiere una referencia fuerte de un objeto
    • Weakref::get - Devuelve el objeto apuntado por una referencia débil
    • Weakref::release - Libera una referencia previmente adquirida
    • Weakref::valid - Comprueba si el objeto referenciado aún existe
    • Weakref::__construct - Construye una nueva referencia débil
    • WeakReference::create - Crea una nueva referencia débil
    • WeakReference::get - Obtiene un objeto débilmente referenciado
    • WeakReference::__construct - Constructor que no permite la instanciación
    • win32_continue_service - Reanuda un servicio pausado
    • win32_create_service - Crea una nueva entrada de servicio en la base de datos del ACS
    • win32_delete_service - Borra una entrada de servicio de la base de datos del ACS
    • win32_get_last_control_message - Devuelve el último mensaje de control que fue enviado a este servicio
    • win32_pause_service - Pausa un servicio
    • win32_query_service_status - Pregunta sobre el estado de un servicio
    • win32_send_custom_control - Enviar un control personalizado al servicio
    • win32_set_service_exit_code - Define o devuelve el código de salida para el servicio en curso
    • win32_set_service_exit_mode - Define o devuelve el modo de salida para el servicio en curso
    • win32_set_service_status - Actualiza el estado del servicio
    • win32_start_service - Inicia un servicio
    • win32_start_service_ctrl_dispatcher - Registra el script con el ACS, por lo que puede actuar como el servicio con el nombre dado
    • win32_stop_service - Detiene un servicio
    • wincache_fcache_fileinfo - Retrieves information about files cached in the file cache
    • wincache_fcache_meminfo - Recupera información sobre el uso de memoria caché de ficheros
    • wincache_lock - Obtiene un bloqueo exclusivo en una clave dada
    • wincache_ocache_fileinfo - Retrieves information about files cached in the opcode cache
    • wincache_ocache_meminfo - Retrieves information about opcode cache memory usage
    • wincache_refresh_if_changed - Refreshes the cache entries for the cached files
    • wincache_rplist_fileinfo - Retrieves information about resolve file path cache
    • wincache_rplist_meminfo - Retrieves information about memory usage by the resolve file path cache
    • wincache_scache_info - Retrieves information about files cached in the session cache
    • wincache_scache_meminfo - Recupera información sobre el uso de memoria caché de sesión
    • wincache_ucache_add - Adds a variable in user cache only if variable does not already exist in the cache
    • wincache_ucache_cas - Compara la variable con el valor antiguo y le asigna un nuevo valor a este
    • wincache_ucache_clear - Elimina todo el contenido de la caché del usuario
    • wincache_ucache_dec - Disminuye el valor asociado a la clave
    • wincache_ucache_delete - Elimina las variables de la memoria caché del usuario
    • wincache_ucache_exists - Comprueba si una variable existe en la caché del usuario
    • wincache_ucache_get - Obtiene una variable almacenada en la caché del usuario
    • wincache_ucache_inc - Incrementa el valor asociado a la clave
    • wincache_ucache_info - Recupera información sobre los datos almacenados en la caché del usuario
    • wincache_ucache_meminfo - Recupera información sobre el uso de memoria caché de usuario
    • wincache_ucache_set - Adds a variable in user cache and overwrites a variable if it already exists in the cache
    • wincache_unlock - Libera un bloqueo exclusivo sobre una clave dada
    • wkhtmltox\Image\Converter::convert - Realiza la conversión de la imagen
    • wkhtmltox\Image\Converter::getVersion - Determina la versión del convertidor
    • wkhtmltox\Image\Converter::__construct - Create a new Image converter
    • wkhtmltox\PDF\Converter::add - Añade un objeto para su conversión
    • wkhtmltox\PDF\Converter::convert - Realiza la conversión a PDF
    • wkhtmltox\PDF\Converter::getVersion - Determina la versión del convertidor
    • wkhtmltox\PDF\Converter::__construct - Create a new PDF converter
    • wkhtmltox\PDF\Object::__construct - Create a new PDF Object
    • wordwrap - Ajusta un string hasta un número dado de caracteres
    • Worker::collect - Collect references to completed tasks
    • Worker::getStacked - Gets the remaining stack size
    • Worker::isShutdown - State Detection
    • Worker::isWorking - State Detection
    • Worker::shutdown - Shutdown the worker
    • Worker::stack - Stacking work
    • Worker::unstack - Unstacking work
  • x
    • xattr_get - Obtener un atributo extendido
    • xattr_list - Obtener una lista de atributos extendidos
    • xattr_remove - Elimina un atributo extendido
    • xattr_set - Establece un atributo extendido
    • xattr_supported - Comprueba si soporta los atributos extendidos del sistema de archivos
    • xdiff_file_bdiff - Realiza una diferencia binaria de dos archivos
    • xdiff_file_bdiff_size - Lee el tamaño de un archivo creado tras aplicar una diferencia binaria
    • xdiff_file_bpatch - Parchea un archivo con una diferencia binaria
    • xdiff_file_diff - Hacer un diff unificado de dos archivos
    • xdiff_file_diff_binary - Alias de xdiff_file_bdiff
    • xdiff_file_merge3 - Une 3 archivos en uno
    • xdiff_file_patch - Parchea un archivo con un diff unificado
    • xdiff_file_patch_binary - Alias de xdiff_file_bpatch
    • xdiff_file_rabdiff - Hacer una diferencia binaria de dos archivos utilizando el algoritmo polinomial de huella digital (fingerprinting) de Rabin
    • xdiff_string_bdiff - Hacer una diferencia binaria de dos cadenas
    • xdiff_string_bdiff_size - Lee el tamaño de un archivo creado tras aplicar una diferencia binaria
    • xdiff_string_bpatch - Parchear una cadena con una diferencia binaria
    • xdiff_string_diff - Hacer un diff unificado de dos strings
    • xdiff_string_diff_binary - Alias de xdiff_string_bdiff
    • xdiff_string_merge3 - Unir tres cadenas en una
    • xdiff_string_patch - Parchear una cadena con un diff unificado
    • xdiff_string_patch_binary - Alias de xdiff_string_bpatch
    • xdiff_string_rabdiff - Hacer una diferencia binaria de dos cadenas utilizando el algoritmo polinomial de huella digital (fingerprinting) de Rabin
    • xhprof_disable - Detiene el perfilador xhprof
    • xhprof_enable - Inicia perfil xhprof
    • xhprof_sample_disable - Detiene la muestra del perfilador xhprof
    • xhprof_sample_enable - Iniciar el analisis de XHProf en modo de muestreo
    • XMLDiff\Base::diff - Produce diferencias de dos documentos XML
    • XMLDiff\Base::merge - Produce un nuevo documento XML basado en diferencias
    • XMLDiff\Base::__construct - Constructor
    • XMLDiff\DOM::diff - Diferencia dos objetos DOMDocument
    • XMLDiff\DOM::merge - Produce DOMDocument unido
    • XMLDiff\File::diff - Diferencia dos archivos XML
    • XMLDiff\File::merge - Produce un documento XML unido
    • XMLDiff\Memory::diff - Diferenciar dos documentos XML
    • XMLDiff\Memory::merge - Produce un documento XML unido
    • XMLReader::close - Cierra la entrada del XMLReader
    • XMLReader::expand - Devuelve una copia del actual nodo como un objeto DOM
    • XMLReader::getAttribute - Obtiener el valor del atributo nombrado
    • XMLReader::getAttributeNo - Obtiene el valor de un atributo por el indice
    • XMLReader::getAttributeNs - Obtiene el valor de un atributo por su nombre local y URI
    • XMLReader::getParserProperty - Indica si la porpiedad especificada ha sido establecida
    • XMLReader::isValid - Indica si el documento analizado es válido
    • XMLReader::lookupNamespace - Busca el namespace para un prefijo
    • XMLReader::moveToAttribute - Mueve el cursor a un atributo nombrado
    • XMLReader::moveToAttributeNo - Mueve el cursor a un atributo por su índice
    • XMLReader::moveToAttributeNs - Mover el cursor a un atributo dado
    • XMLReader::moveToElement - Posiciona el cursor en el eleménto padre del actual atributo
    • XMLReader::moveToFirstAttribute - Posiciona el cursor en el primer atributo
    • XMLReader::moveToNextAttribute - Posiciona el cursor en el siguiente atributo
    • XMLReader::next - Mueve el cursor al siguiente nodo saltandose todos los subárboles
    • XMLReader::open - Establece el URI conteniendo el XML a analizar
    • XMLReader::read - Se mueve al siguiente nodo en el documento
    • XMLReader::readInnerXML - Recupera el XML del actual nodo
    • XMLReader::readOuterXML - Recupera el XML del actual nodo, incluyendo él mismo
    • XMLReader::readString - Lee el contenido del nodo actual como string
    • XMLReader::setParserProperty - Establecer las opciones del analizador
    • XMLReader::setRelaxNGSchema - Establece el nomb re del archivo o el URI para un esquema RelaxNG
    • XMLReader::setRelaxNGSchemaSource - Establece los datos contenidos en un esquema RelaxNG
    • XMLReader::setSchema - Valida el documento en contra del XSD
    • XMLReader::XML - Establece el contenido del XML a analizar
    • xmlrpc_decode - Decodifica el XML en los tipos de PHP nativos
    • xmlrpc_decode_request - Decodifica el XML en los tipos de PHP nativos
    • xmlrpc_encode - Genera XML para un valor PHP
    • xmlrpc_encode_request - Genera XML para el requerimiento de un método
    • xmlrpc_get_type - Obtiene el tipo del xmlrpc para un valor PHP
    • xmlrpc_is_fault - Determina si el valor de un arreglo representa una falla del XMLRPC
    • xmlrpc_parse_method_descriptions - Decodifica el XML en una lista de las descripciones del método
    • xmlrpc_server_add_introspection_data - Agrega una documentación introspectiva
    • xmlrpc_server_call_method - Analiza los requerimientos del XML y las llamadas de los métodos
    • xmlrpc_server_create - Crea un servidor xmlrpc
    • xmlrpc_server_destroy - Destruye los recursos del servidor
    • xmlrpc_server_register_introspection_callback - Registra una función PHP para generar la documentación
    • xmlrpc_server_register_method - Registra una función PHP para que el recurso del método coincida con method_name
    • xmlrpc_set_type - Establece el tipo del xmlrpc, base64 o fecha-hora, para un valor de cadena PHP
    • XMLWriter::endAttribute - End attribute
    • XMLWriter::endCdata - End current CDATA
    • XMLWriter::endComment - Create end comment
    • XMLWriter::endDocument - End current document
    • XMLWriter::endDtd - End current DTD
    • XMLWriter::endDtdAttlist - End current DTD AttList
    • XMLWriter::endDtdElement - End current DTD element
    • XMLWriter::endDtdEntity - End current DTD Entity
    • XMLWriter::endElement - End current element
    • XMLWriter::endPi - End current PI
    • XMLWriter::flush - Flush current buffer
    • XMLWriter::fullEndElement - End current element
    • XMLWriter::openMemory - Create new xmlwriter using memory for string output
    • XMLWriter::openUri - Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory - Returns current buffer
    • XMLWriter::setIndent - Toggle indentation on/off
    • XMLWriter::setIndentString - Set string used for indenting
    • XMLWriter::startAttribute - Create start attribute
    • XMLWriter::startAttributeNs - Create start namespaced attribute
    • XMLWriter::startCdata - Create start CDATA tag
    • XMLWriter::startComment - Create start comment
    • XMLWriter::startDocument - Create document tag
    • XMLWriter::startDtd - Create start DTD tag
    • XMLWriter::startDtdAttlist - Create start DTD AttList
    • XMLWriter::startDtdElement - Create start DTD element
    • XMLWriter::startDtdEntity - Create start DTD Entity
    • XMLWriter::startElement - Create start element tag
    • XMLWriter::startElementNs - Create start namespaced element tag
    • XMLWriter::startPi - Create start PI tag
    • XMLWriter::text - Write text
    • XMLWriter::writeAttribute - Write full attribute
    • XMLWriter::writeAttributeNs - Write full namespaced attribute
    • XMLWriter::writeCdata - Write full CDATA tag
    • XMLWriter::writeComment - Write full comment tag
    • XMLWriter::writeDtd - Write full DTD tag
    • XMLWriter::writeDtdAttlist - Write full DTD AttList tag
    • XMLWriter::writeDtdElement - Write full DTD element tag
    • XMLWriter::writeDtdEntity - Write full DTD Entity tag
    • XMLWriter::writeElement - Write full element tag
    • XMLWriter::writeElementNs - Write full namespaced element tag
    • XMLWriter::writePi - Writes a PI
    • XMLWriter::writeRaw - Write a raw XML text
    • xml_error_string - Obtiene la cadena de un error dado en un intérprete XML
    • xml_get_current_byte_index - Obtiene la indexación del byte actual en un intérprete XML
    • xml_get_current_column_number - Obtiene el número de columna actual para un intérprete XML
    • xml_get_current_line_number - Obtiene el número de línea actual para un intérprete XML
    • xml_get_error_code - Obtiene un código de error en un intérprete XML
    • xml_parse - Inicia un intérprete sobre un documento XML
    • xml_parser_create - Crea un intérprete XML
    • xml_parser_create_ns - Crea un analizador XML con soporte para espacios de nombres
    • xml_parser_free - Liberar una analizador XML
    • xml_parser_get_option - Obtiene el valor de las opciones de un intérprete XML
    • xml_parser_set_option - Configura las opciones en un intérprete XML
    • xml_parse_into_struct - Interpreta datos XML en una estructura de array
    • xml_set_character_data_handler - Configura el manejador de los datos de caracteres
    • xml_set_default_handler - Configura el manejador predeterminado
    • xml_set_element_handler - Configura los manejadores para los elementos de inicio y final
    • xml_set_end_namespace_decl_handler - Configura el manejador de declaración de final del namespace
    • xml_set_external_entity_ref_handler - Configura el manejador de referencia a entidades externas
    • xml_set_notation_decl_handler - Configura el manejador de declaraciones de notación
    • xml_set_object - Usa un intérprete XML Parser dentro de un objeto
    • xml_set_processing_instruction_handler - Configura el manejador de instrucciones de proceso (PI)
    • xml_set_start_namespace_decl_handler - Configura el manejador de declaración de inicio del namespace
    • xml_set_unparsed_entity_decl_handler - Configura el manejador de declaración de entidades no analizadas
    • XSLTProcessor::getParameter - Obtiene el valor de un parámetro
    • XSLTProcessor::getSecurityPrefs - Obtiene las preferencias de seguridad
    • XSLTProcessor::hasExsltSupport - Determina si PHP tiene soporte para EXSLT
    • XSLTProcessor::importStylesheet - Importa una hoja de estilos
    • XSLTProcessor::registerPHPFunctions - Activa la capacidad de usar funciones PHP como funciones XSLT
    • XSLTProcessor::removeParameter - Elimina un parámetro
    • XSLTProcessor::setParameter - Establece el valor para uno o varios parámetros
    • XSLTProcessor::setProfiling - Establece el fichero de salida para la información resultado del proceso
    • XSLTProcessor::setSecurityPrefs - Establece las preferencias de seguridad
    • XSLTProcessor::transformToDoc - Transforma en un DOMDocument
    • XSLTProcessor::transformToUri - Transformar a URI
    • XSLTProcessor::transformToXml - Transforma a XML
    • XSLTProcessor::__construct - Crea un nuevo objeto XSLTProcessor
  • y
    • Yac::add - Guardar en caché
    • Yac::delete - Eliminar los artículos de la memoria caché
    • Yac::dump - Volcar cache
    • Yac::flush - Limpiar el caché
    • Yac::get - Recuperar los valores de caché
    • Yac::info - Estado del caché
    • Yac::set - Guardar en el caché
    • Yac::__construct - Constructor
    • Yac::__get - Getter
    • Yac::__set - Setter
    • Yaconf::get - Recuperar un elemento
    • Yaconf::has - Determinar si un elemento existe
    • Yaf_Action_Abstract::execute - Punto de entrada de una acción
    • Yaf_Action_Abstract::getController - Recupera el objeto controlador
    • Yaf_Action_Abstract::getControllerName - Obtener el nombre del controlador
    • Yaf_Application::app - Recuperar una instancia de la clase Application
    • Yaf_Application::bootstrap - Llamar al arranque
    • Yaf_Application::clearLastError - Limpiar la información del último error
    • Yaf_Application::environ - Recuperar el entorno
    • Yaf_Application::execute - Ejecutar una llamada de retorno
    • Yaf_Application::getAppDirectory - Obtener el directorio de la aplicación
    • Yaf_Application::getConfig - Recuperar la instancia de configuración
    • Yaf_Application::getDispatcher - Obtener la instancia de la clase Yaf_Dispatcher
    • Yaf_Application::getLastErrorMsg - Obtener el mensaje del último error ocurrido
    • Yaf_Application::getLastErrorNo - Pbetner el código del último error ocurrido
    • Yaf_Application::getModules - Obtener los nombres de los modulos definidos
    • Yaf_Application::run - Iniciar una instancia de la clase Yaf_Application
    • Yaf_Application::setAppDirectory - Cambiar el directorio de la aplicación
    • Yaf_Application::__construct - El constructor de la clase Yaf_Application
    • Yaf_Application::__destruct - El propósito de __destruct
    • Yaf_Config_Abstract::get - Consultor
    • Yaf_Config_Abstract::readonly - Buscar si una configuración es de sólo lectura
    • Yaf_Config_Abstract::set - Modificador
    • Yaf_Config_Abstract::toArray - Convertir en un array
    • Yaf_Config_Ini::count - Contar todos los elementos en Yaf_Config.ini
    • Yaf_Config_Ini::current - Recuperar el valor actual
    • Yaf_Config_Ini::key - Buscar la clave del elemento actual
    • Yaf_Config_Ini::next - Avanzar el puntero interno
    • Yaf_Config_Ini::offsetExists - El propósito de offsetExists
    • Yaf_Config_Ini::offsetGet - El propósito de offsetGet
    • Yaf_Config_Ini::offsetSet - El propósito de offsetSet
    • Yaf_Config_Ini::offsetUnset - El propósito de offsetUnset
    • Yaf_Config_Ini::readonly - El propósito de readonly
    • Yaf_Config_Ini::rewind - El propósito de rewind
    • Yaf_Config_Ini::toArray - Devuelve la configuración como un array PHP
    • Yaf_Config_Ini::valid - El propósito de valid
    • Yaf_Config_Ini::__construct - Constructor de Yaf_Config_Ini
    • Yaf_Config_Ini::__get - Recuperar un elemento
    • Yaf_Config_Ini::__isset - Determinar si existe una clave
    • Yaf_Config_Ini::__set - El propósito de __set
    • Yaf_Config_Simple::count - El propósito de count
    • Yaf_Config_Simple::current - El propósito de current
    • Yaf_Config_Simple::key - El propósito de key
    • Yaf_Config_Simple::next - El propósito de next
    • Yaf_Config_Simple::offsetExists - El propósito de offsetExists
    • Yaf_Config_Simple::offsetGet - El propósito de offsetGet
    • Yaf_Config_Simple::offsetSet - El propósito de offsetSet
    • Yaf_Config_Simple::offsetUnset - El propósito de offsetUnset
    • Yaf_Config_Simple::readonly - El propósito de readonly
    • Yaf_Config_Simple::rewind - El propósito de rewind
    • Yaf_Config_Simple::toArray - Devuelve un array de PHP
    • Yaf_Config_Simple::valid - El propósito de valid
    • Yaf_Config_Simple::__construct - El propósito de __construct
    • Yaf_Config_Simple::__get - El propósito de __get
    • Yaf_Config_Simple::__isset - El propósito de __isset
    • Yaf_Config_Simple::__set - El propósito de __set
    • Yaf_Controller_Abstract::display - El propósito de display
    • Yaf_Controller_Abstract::forward - Avanza a la siguiente acción
    • Yaf_Controller_Abstract::getInvokeArg - El propósito de getInvokeArg
    • Yaf_Controller_Abstract::getInvokeArgs - El propósito de getInvokeArgs
    • Yaf_Controller_Abstract::getModuleName - Obtiene el nombre del módulo
    • Yaf_Controller_Abstract::getName - Obtener el nombre propio
    • Yaf_Controller_Abstract::getRequest - Recupera el objeto petición actual
    • Yaf_Controller_Abstract::getResponse - Recupera el objeto respuesta actual
    • Yaf_Controller_Abstract::getView - Recupera el motor de vistas
    • Yaf_Controller_Abstract::getViewpath - El propósito de getViewpath
    • Yaf_Controller_Abstract::init - Inicializador del controlador
    • Yaf_Controller_Abstract::initView - El propósito de initView
    • Yaf_Controller_Abstract::redirect - Redirige a un URL
    • Yaf_Controller_Abstract::render - Interpreta una plantilla de vista
    • Yaf_Controller_Abstract::setViewpath - El propósito de setViewpath
    • Yaf_Controller_Abstract::__construct - Constructor de Yaf_Controller_Abstract
    • Yaf_Dispatcher::autoRender - Activa/desactiva la autointerpretación
    • Yaf_Dispatcher::catchException - Activar/desactivar la captura de excepciones
    • Yaf_Dispatcher::disableView - Deshabilita la interpretación de vistas
    • Yaf_Dispatcher::dispatch - Despachar una petición
    • Yaf_Dispatcher::enableView - Habilita la interpretación de vistas
    • Yaf_Dispatcher::flushInstantly - Activa/desactiva el vaciado instantáneo
    • Yaf_Dispatcher::getApplication - Recupera la aplicación
    • Yaf_Dispatcher::getDefaultAction - Recupera el nombre de la acción por defecto
    • Yaf_Dispatcher::getDefaultController - Recupera el nombre del controlador predeterminado
    • Yaf_Dispatcher::getDefaultModule - Recupera el nombre del módulo por defecto
    • Yaf_Dispatcher::getInstance - Recupeara la instancia despachadora
    • Yaf_Dispatcher::getRequest - Recupera la instancia de petición
    • Yaf_Dispatcher::getRouter - Recuperar la instancia de envío
    • Yaf_Dispatcher::initView - Inicializa una vista y la devuelve
    • Yaf_Dispatcher::registerPlugin - Registra un complemento
    • Yaf_Dispatcher::returnResponse - El propósito de returnResponse
    • Yaf_Dispatcher::setDefaultAction - Cambia el nombre de la acción predeterminada
    • Yaf_Dispatcher::setDefaultController - Cambia el nombre del controlador predeterminado
    • Yaf_Dispatcher::setDefaultModule - Cambia el nombre del módulo predeterminado
    • Yaf_Dispatcher::setErrorHandler - Establece el gestor de errores
    • Yaf_Dispatcher::setRequest - El propósito de setRequest
    • Yaf_Dispatcher::setView - Establecer un motor de vistas personalizado
    • Yaf_Dispatcher::throwException - Activa/desactiva el lanzamiento de excepciones
    • Yaf_Dispatcher::__construct - Constructor de la clase Yaf_Dispatcher
    • Yaf_Exception::getPrevious - El propósito de getPrevious
    • Yaf_Exception::__construct - El propósito de __construct
    • Yaf_Loader::autoload - El propósito de autoload
    • Yaf_Loader::clearLocalNamespace - El propósito de clearLocalNamespace
    • Yaf_Loader::getInstance - El propósito de getInstance
    • Yaf_Loader::getLibraryPath - Obtener la ruta de la biblioteca
    • Yaf_Loader::getLocalNamespace - Recupera toda la información de un espacio de nombre
    • Yaf_Loader::getNamespacePath - Recupera la ruta de un espacio de nombres registrado
    • Yaf_Loader::import - El propósito de import
    • Yaf_Loader::isLocalName - El propósito de isLocalName
    • Yaf_Loader::registerLocalNamespace - Registra un prefijo de clase local
    • Yaf_Loader::registerNamespace - Registra un espacio de nombre con ruta de búsqueda
    • Yaf_Loader::setLibraryPath - Cmabiar la ruta de la biblioteca
    • Yaf_Loader::__construct - El propósito de __construct
    • Yaf_Plugin_Abstract::dispatchLoopShutdown - El propósito de dispatchLoopShutdown
    • Yaf_Plugin_Abstract::dispatchLoopStartup - Enganchar antes del bucle de envío
    • Yaf_Plugin_Abstract::postDispatch - El propósito de postDispatch
    • Yaf_Plugin_Abstract::preDispatch - El propósito de preDispatch
    • Yaf_Plugin_Abstract::preResponse - El propósito de preResponse
    • Yaf_Plugin_Abstract::routerShutdown - El propósito de routerShutdown
    • Yaf_Plugin_Abstract::routerStartup - Enganche deEl propósito de routerStartup
    • Yaf_Registry::del - Elimina un elemento del registro
    • Yaf_Registry::get - Recupera un elemento del registro
    • Yaf_Registry::has - Comprueba si existe un elemento
    • Yaf_Registry::set - Añade un elemento al registro
    • Yaf_Registry::__construct - Yaf_Registry implementa «singleton»
    • Yaf_Request_Abstract::clearParams - Eliminar todos los parámetros
    • Yaf_Request_Abstract::getActionName - El propósito de getActionName
    • Yaf_Request_Abstract::getBaseUri - El propósito de getBaseUri
    • Yaf_Request_Abstract::getControllerName - El propósito de getControllerName
    • Yaf_Request_Abstract::getEnv - Recupera la variable ENV
    • Yaf_Request_Abstract::getException - El propósito de getException
    • Yaf_Request_Abstract::getLanguage - Recupera el lenguaje preferido del cliente
    • Yaf_Request_Abstract::getMethod - Recupera el método de solicitud
    • Yaf_Request_Abstract::getModuleName - El propósito de getModuleName
    • Yaf_Request_Abstract::getParam - Recupera el parámetro de llamada
    • Yaf_Request_Abstract::getParams - Recupera todos los parámetros de llamada
    • Yaf_Request_Abstract::getRequestUri - El propósito de getRequestUri
    • Yaf_Request_Abstract::getServer - Recupera la variable SERVER
    • Yaf_Request_Abstract::isCli - Determina si la solicitud es una solicitud CLI
    • Yaf_Request_Abstract::isDispatched - Determina si la solicitud es enviada
    • Yaf_Request_Abstract::isGet - Determina si la solicitud es una solicitud GET
    • Yaf_Request_Abstract::isHead - Determina si la solicitud es una solicitud HEAD
    • Yaf_Request_Abstract::isOptions - Determina si la solicitud es una solicitud de OPCIONES
    • Yaf_Request_Abstract::isPost - Determina si la solicitud es una solicitud POST
    • Yaf_Request_Abstract::isPut - Determina si la solicitud es una solicitud PUT
    • Yaf_Request_Abstract::isRouted - Determina si la solicitud ha sido enrutada
    • Yaf_Request_Abstract::isXmlHttpRequest - Determina si la solicitud es una solicitud AJAX
    • Yaf_Request_Abstract::setActionName - Establece el nombre de la acción
    • Yaf_Request_Abstract::setBaseUri - Establecer el URI base
    • Yaf_Request_Abstract::setControllerName - El propósito de setControllerName
    • Yaf_Request_Abstract::setDispatched - El propósito de setDispatched
    • Yaf_Request_Abstract::setModuleName - El propósito de setModuleName
    • Yaf_Request_Abstract::setParam - El propósito de setParam
    • Yaf_Request_Abstract::setRequestUri - El propósito de setRequestUri
    • Yaf_Request_Abstract::setRouted - El propósito de setRouted
    • Yaf_Request_Http::get - Recupera una variable del cliente
    • Yaf_Request_Http::getCookie - Recupera una varible de Cookie
    • Yaf_Request_Http::getFiles - El propósito de getFiles
    • Yaf_Request_Http::getPost - Recupera una variable de POST
    • Yaf_Request_Http::getQuery - Obtiene un parámetro de una consulta
    • Yaf_Request_Http::getRaw - Recupera el cuerpo de la solicitud de raw
    • Yaf_Request_Http::getRequest - El propósito de getRequest
    • Yaf_Request_Http::isXmlHttpRequest - Determina si la solicitud es una solicitud de Ajax
    • Yaf_Request_Http::__construct - Constructor de Yaf_Request_Http
    • Yaf_Request_Simple::get - El propósito de get
    • Yaf_Request_Simple::getCookie - El propósito de getCookie
    • Yaf_Request_Simple::getFiles - El propósito de getFiles
    • Yaf_Request_Simple::getPost - El propósito de getPost
    • Yaf_Request_Simple::getQuery - El propósito de getQuery
    • Yaf_Request_Simple::getRequest - El propósito de getRequest
    • Yaf_Request_Simple::isXmlHttpRequest - Determina si la solicitud es una solicitud AJAX
    • Yaf_Request_Simple::__construct - Constructor de Yaf_Request_Simple
    • Yaf_Response_Abstract::appendBody - Añadir contenido al cuerpo de respuesta
    • Yaf_Response_Abstract::clearBody - Descarta todo el cuerpo de respuesta existente
    • Yaf_Response_Abstract::clearHeaders - Descarta todas las cabeceras establecidas
    • Yaf_Response_Abstract::getBody - Recupera un contenido existente
    • Yaf_Response_Abstract::getHeader - El propósito de getHeader
    • Yaf_Response_Abstract::prependBody - El propósito de prependBody
    • Yaf_Response_Abstract::response - Envía una respuesta
    • Yaf_Response_Abstract::setAllHeaders - El propósito de setAllHeaders
    • Yaf_Response_Abstract::setBody - Establece el contenido de una respuesta
    • Yaf_Response_Abstract::setHeader - Establece cabecera de respuesta
    • Yaf_Response_Abstract::setRedirect - El propósito de setRedirect
    • Yaf_Response_Abstract::__construct - El propósito de __construct
    • Yaf_Response_Abstract::__destruct - El propósito de __destruct
    • Yaf_Response_Abstract::__toString - Recupera todo el cuerpo como un string
    • Yaf_Router::addConfig - Añadir rutas definidas en configuración al Enrutador
    • Yaf_Router::addRoute - Añadir una nueva ruta al Enrutador
    • Yaf_Router::getCurrentRoute - Obtener el nombre de la ruta efectiva
    • Yaf_Router::getRoute - Recupera una ruta por su nombre
    • Yaf_Router::getRoutes - Recupera las rutas registradas
    • Yaf_Router::route - El propósito de route
    • Yaf_Router::__construct - El constructor de Yaf_Router
    • Yaf_Route_Interface::assemble - Ensamblar una petición
    • Yaf_Route_Interface::route - Enruta una petición
    • Yaf_Route_Map::assemble - Ensamblar un URL
    • Yaf_Route_Map::route - El propósito de route
    • Yaf_Route_Map::__construct - El propósito de __construct
    • Yaf_Route_Regex::assemble - Ensamblar un URL
    • Yaf_Route_Regex::route - El propósito de route
    • Yaf_Route_Regex::__construct - Constructor de Yaf_Route_Regex
    • Yaf_Route_Rewrite::assemble - Ensamblar un URL
    • Yaf_Route_Rewrite::route - El propósito de route
    • Yaf_Route_Rewrite::__construct - Constructor de Yaf_Route_Rewrite
    • Yaf_Route_Simple::assemble - Ensamblar un URL
    • Yaf_Route_Simple::route - Enviar una petición
    • Yaf_Route_Simple::__construct - El constructor de la clase Yaf_Route_Simple
    • Yaf_Route_Static::assemble - Ensamblar un URL
    • Yaf_Route_Static::match - El propósito de match
    • Yaf_Route_Static::route - Enviar una petición
    • Yaf_Route_Supervar::assemble - Ensamblar un URL
    • Yaf_Route_Supervar::route - El propósito de route
    • Yaf_Route_Supervar::__construct - El propósito de __construct
    • Yaf_Session::count - El propósito de count
    • Yaf_Session::current - El propósito de current
    • Yaf_Session::del - El propósito de del
    • Yaf_Session::getInstance - El propósito de getInstance
    • Yaf_Session::has - El propósito de has
    • Yaf_Session::key - El propósito de key
    • Yaf_Session::next - El propósito de next
    • Yaf_Session::offsetExists - El propósito de offsetExists
    • Yaf_Session::offsetGet - El propósito de offsetGet
    • Yaf_Session::offsetSet - El propósito de offsetSet
    • Yaf_Session::offsetUnset - El propósito de offsetUnset
    • Yaf_Session::rewind - El propósito de rewind
    • Yaf_Session::start - El propósito de start
    • Yaf_Session::valid - El propósito de valid
    • Yaf_Session::__construct - Constructor de Yaf_Session
    • Yaf_Session::__get - El propósito de __get
    • Yaf_Session::__isset - El propósito de __isset
    • Yaf_Session::__set - El propósito de __set
    • Yaf_Session::__unset - El propósito de __unset
    • Yaf_View_Interface::assign - Asignar valores al motor de Vistas
    • Yaf_View_Interface::display - Interpretar e imprimir una plantilla
    • Yaf_View_Interface::getScriptPath - El propósito de getScriptPath
    • Yaf_View_Interface::render - Interpretar una plantilla
    • Yaf_View_Interface::setScriptPath - El propósito de setScriptPath
    • Yaf_View_Simple::assign - Asignar valores
    • Yaf_View_Simple::assignRef - El propósito de assignRef
    • Yaf_View_Simple::clear - Limpiar valores asignados
    • Yaf_View_Simple::display - Interpretar y mostrar
    • Yaf_View_Simple::eval - Interpreta una plantilla
    • Yaf_View_Simple::getScriptPath - Obtiene el directorio de plantillas
    • Yaf_View_Simple::render - Interpreta una plantilla
    • Yaf_View_Simple::setScriptPath - Establece el directorio de plantillas
    • Yaf_View_Simple::__construct - El constructor de Yaf_View_Simple
    • Yaf_View_Simple::__get - Recupera una variable asignada
    • Yaf_View_Simple::__isset - El propósito de __isset
    • Yaf_View_Simple::__set - Establece el valor para el motor
    • yaml_emit - Devuelve la representación de un valor YAML
    • yaml_emit_file - Enviar la representación YAML de un valor a un fichero
    • yaml_parse - Analiza una secuencia de texto en formato YAML
    • yaml_parse_file - Analiza una secuencia de texto en formato YAML desde un fichero
    • yaml_parse_url - Analiza una secuencia de texto Yaml desde una URL
    • Yar_Client::setOpt - Establecer los contextos de una llamada
    • Yar_Client::__call - Llamar a un servicio
    • Yar_Client::__construct - Crear un cliente
    • Yar_Client_Exception::getType - El propósito de getType
    • Yar_Concurrent_Client::call - Registrar una llamada concurrente
    • Yar_Concurrent_Client::loop - Enviar todas las llamadas
    • Yar_Concurrent_Client::reset - Limpiar todas las llamadas registradas
    • Yar_Server::handle - Iniciar un servidor RPC
    • Yar_Server::__construct - Registrar un servidor
    • Yar_Server_Exception::getType - Recuperar el tipo de excepción
    • yaz_addinfo - Devuelve un error adicional de información
    • yaz_ccl_conf - Configura el analizador CCL
    • yaz_ccl_parse - Inviocar el analizador Invoke CCL
    • yaz_close - Close YAZ connection
    • yaz_connect - Prepara una conexión a un servidor Z39.50
    • yaz_database - Especifica las bases de datos dentro de una sesión
    • yaz_element - Especifica el nombre del elemento establecido para recuperar
    • yaz_errno - Devuelve el número de error
    • yaz_error - Devuelve la descripción del error
    • yaz_es - Prepara para una solicitud de servicio extendido
    • yaz_es_result - Resulados de Servicios Extendidos de Inspección
    • yaz_get_option - Devuelve el valor de opción para la conexión
    • yaz_hits - Devuelve el número de éxitos de la última búsqueda
    • yaz_itemorder - Prepara para la solicitud Z39.50 Item Order con el paquete ILL-Request
    • yaz_present - Se prepara para la recuperación (Z39.50 presente)
    • yaz_range - Específica un rango de registros a recuperar
    • yaz_record - Devuelve un registro
    • yaz_scan - Prepara para un escaneo YAZ
    • yaz_scan_result - Devuelve el resultado de un escaneado
    • yaz_schema - Especifica el esquema para la recuperación
    • yaz_search - Prepara una búsqueda
    • yaz_set_option - Configura una o más opciones de la conexión
    • yaz_sort - Configura los criterios de búsqueda
    • yaz_syntax - Especifica la sintaxis de registro preferida para la recuperación
    • yaz_wait - Espera que las peticiones Z39.50 se completeten
  • z
    • zend_thread_id - Devuelve un identificador único del thread actual
    • zend_version - Obtiene la versión del motor Zend actual
    • ZipArchive::addEmptyDir - Añadir un nuevo directorio
    • ZipArchive::addFile - Añade un fichero al archivo ZIP para la ruta dada
    • ZipArchive::addFromString - Añadir un fichero al archivo ZIP usando su contenido
    • ZipArchive::addGlob - Añadir ficheros de un directorio mediante un patrón glob
    • ZipArchive::addPattern - Añade ficheros de un directorio a partir de un patrón PCRE
    • ZipArchive::close - Cierra el fichero activo (abierto o el nuevo creado)
    • ZipArchive::count - Cuenta el número de archivos en el archivo
    • ZipArchive::deleteIndex - Elimina una entrada en el archivo usando su índice
    • ZipArchive::deleteName - Elimina una entrada en el archivo por su nombre
    • ZipArchive::extractTo - Extraer el contenido del archivo
    • ZipArchive::getArchiveComment - Devuelve el comentario del archivo ZIP
    • ZipArchive::getCommentIndex - Devuelve el comentario de una entrada usando la entrada díndice
    • ZipArchive::getCommentName - Devuelve el comentario de una entrada usando el nombre de la entrada
    • ZipArchive::getExternalAttributesIndex - Obtener los atributos externos de una entrada definida por su índice
    • ZipArchive::getExternalAttributesName - Obtener los atributos externos de una entrada definida por su nombre
    • ZipArchive::getFromIndex - Devuelve el contenido de la entrada usando su índice
    • ZipArchive::getFromName - Devuelve el contenido de la entrada utilizando su nombre
    • ZipArchive::getNameIndex - Devuelve el nombre de una entrada utilizando su índice
    • ZipArchive::getStatusString - Devuelve mensajes de: estado de error, de sistema y/o mensajes de zip
    • ZipArchive::getStream - Obtener un manejador de fichero para la entrada definido por su nombre (sólo lectura)
    • ZipArchive::isCompressionMethodSupported - Check if a compression method is supported by libzip
    • ZipArchive::isEncryptionMethodSupported - Check if a encryption method is supported by libzip
    • ZipArchive::locateName - Devuelve el índice de la entrada en el archivo
    • ZipArchive::open - Abrir un fichero de archivo en formato ZIP
    • ZipArchive::registerCancelCallback - Registrar una llamada para permitir la cancelación durante el cierre del archivo
    • ZipArchive::registerProgressCallback - Registra una llamada para proporcionar actualizaciones durante el cierre del archivo
    • ZipArchive::renameIndex - Renombra una entrada definida por su índice
    • ZipArchive::renameName - Renombra una entrada definida por su nombre
    • ZipArchive::replaceFile - Reemplaza fichero en el archivo ZIP con una ruta determinada
    • ZipArchive::setArchiveComment - Establece el comentario de un archivo ZIP
    • ZipArchive::setCommentIndex - Establece el comentario de una entrada definido por su índice
    • ZipArchive::setCommentName - Establece el comentario de una entrada definido por su nombre
    • ZipArchive::setCompressionIndex - Establecer el método de compresión de una entrada definida por su índice
    • ZipArchive::setCompressionName - Establecer el método de compresión de una entrada definida por su nombre
    • ZipArchive::setEncryptionIndex - Establece el método de cifrado de una entrada definida por su índice
    • ZipArchive::setEncryptionName - Establece el método de cifrado de una entrada definida por su nombre
    • ZipArchive::setExternalAttributesIndex - Establece los atributos externos de una entrada definida por su índice
    • ZipArchive::setExternalAttributesName - Establece los atributos externos de una entrada definida por su nombre
    • ZipArchive::setMtimeIndex - Establece el tiempo de modificación de una entrada definido por su índice
    • ZipArchive::setMtimeName - Establece la hora de modificación de una entrada definida por su nombre
    • ZipArchive::setPassword - Establece la contraseña para el archivo activo
    • ZipArchive::statIndex - Obtiene los detalles de una entrada definida por su índice
    • ZipArchive::statName - Obtener los detalles de una entrada definida por su nombre
    • ZipArchive::unchangeAll - Deshacer todos los cambios hechos en el archivo
    • ZipArchive::unchangeArchive - Revertir todos los cambios globales hechos en el archivo
    • ZipArchive::unchangeIndex - Revertir todos los cambios hechos a una entrada en el índice dado
    • ZipArchive::unchangeName - Deshace todos los cambios realizados a una entrada con un nombre dado
    • zip_close - Cierra un fichero ZIP
    • zip_entry_close - Cierra la entrada a un directorio
    • zip_entry_compressedsize - Obtiene el tamaño comprimido de una entrada de directorio
    • zip_entry_compressionmethod - Devuelve el método de compresión de una entrada de directorio
    • zip_entry_filesize - Devuelve el tamaño del fichero actual de una entrada de directorio
    • zip_entry_name - Devuelve el nombre de la entrada de un directorio
    • zip_entry_open - Abrir una entrada de directorio para lectura
    • zip_entry_read - Leer desde una entrada de directorio abierta
    • zip_open - Abre un fichero ZIP
    • zip_read - Leer la siguiente entrada en el fichero ZIP
    • zlib:// - Flujos de compresión
    • zlib_decode - Descomprime datos codificados en craw/gzip/zlib
    • zlib_encode - Comprime datos con la codificación especificada
    • zlib_get_coding_type - Retorna el tipo de codificación utilizada para hacer la compresión
    • ZMQ::__construct - El constructor de ZMQ
    • ZMQContext::getOpt - Obtener la opción de contexto
    • ZMQContext::getSocket - Crear un nuevo socket
    • ZMQContext::isPersistent - Indicar si el contexto es persistente
    • ZMQContext::setOpt - Establecer una opción de socket
    • ZMQContext::__construct - Construir un nuevo objeto ZMQContext
    • ZMQDevice::getIdleTimeout - Obtener el tiempo de espera de inactividad
    • ZMQDevice::getTimerTimeout - Obtener el tiempo de espera del temporizador
    • ZMQDevice::run - Ejecutar el nuevo dispositivo
    • ZMQDevice::setIdleCallback - Establecer la función de retrollamada de inactividad
    • ZMQDevice::setIdleTimeout - Establecer el tiempo de espera para la inactividad
    • ZMQDevice::setTimerCallback - Establecer la función de retrollamada del temporizador
    • ZMQDevice::setTimerTimeout - Establecer el tiempo de espera del temporizador
    • ZMQDevice::__construct - Construir un nuevo dispositivo
    • ZMQPoll::add - Añadir un elemento al conjunto de sondeo
    • ZMQPoll::clear - Limpiar el conjunto de sondeo
    • ZMQPoll::count - Contar los elementos del conjunto de sondeo
    • ZMQPoll::getLastErrors - Obtener los errores del sondeo
    • ZMQPoll::poll - Sondear los elementos
    • ZMQPoll::remove - Eliminar un elemento del conjunto de sondeo
    • ZMQSocket::bind - Vincular el socket
    • ZMQSocket::connect - Contectar el socket
    • ZMQSocket::disconnect - Desconectar un socket
    • ZMQSocket::getEndpoints - Obtener una lista de los extremos
    • ZMQSocket::getPersistentId - Obtener el ID de persistencia
    • ZMQSocket::getSocketType - Obtener el tipo de socket
    • ZMQSocket::getSockOpt - Obtener la opción de un socket
    • ZMQSocket::isPersistent - Comprobrar si un socket es persistente
    • ZMQSocket::recv - Recibir un mensaje
    • ZMQSocket::recvMulti - Recibir un mensaje multiparte
    • ZMQSocket::send - Enviar un mensaje
    • ZMQSocket::sendmulti - Enviar un mensaje multiparte
    • ZMQSocket::setSockOpt - Establecer una opción de socket
    • ZMQSocket::unbind - Desvincular el socket
    • ZMQSocket::__construct - Construir un nuevo 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 - Intenta cargar una clase sin definir
    • __halt_compiler - Detiene la ejecución del compilador

User Contributed Notes

tudorsfatosu at yahoo dot dot com 20-Jun-2019 01:18
A new update regarding the number of entries in the list. We are currently at 11033 entries, in June 2019
crabovwik at yandex dot ru 07-Jan-2019 04:40
Today 07-01-2019 [dd.mm.yyyy]

10934 functions in this list ??
valbou26 at hotmail dot com 13-Apr-2018 09:29
Today : 2018-04-13
10641 functions in this list !

Keep growing ;)
Pieter Bootsma 10-Nov-2017 10:11
As of today, 10-11-2017 [dd-mm-yyyy], there are exactly 10102 functions listed above.
Geordy James 21-Apr-2017 06:18
In case anybody wondering as of 21/04/2017 [dd/mm/yyyy] there are exactly 9957 Functions listed above.
php at vanviegen dot net 14-Feb-2017 08:23
Here's a little script that scrapes all PHP function names from this page, and outputs a prefix-compressed Perl Compatible Regular Expression matching them. Useful for syntax highlighting.

<?php

$html = file_get_contents('http://php.net/manual/en/indexes.functions.php');

preg_match_all('/<li><a href="function.[^>]*>([a-zA-Z0-9_]*)<\/a>/', $html, $matches);
$funcs = $matches[1];

print '\b(?:';
$prefixes = [''];

foreach($funcs as $i => $func) {
    while(substr($func, 0, strlen($prefixes[0])) !== $prefixes[0]) {
        print ")";
        array_shift($prefixes);
    }
    if ($i) print '|';

    while(true) {
        $common = $func;
        for($j = $i+1; $j < count($funcs); $j++) {
            $lookAhead = $funcs[$j];
            $maxLen = min(strlen($lookAhead), strlen($func));
            for($ch = 0; $ch < $maxLen; $ch++) {
                if ($lookAhead[$ch] !== $func[$ch]) break;
            }
            $newCommon = substr($common, 0, $ch);
            if (strlen($newCommon) < strlen($prefixes[0])+2) break;
            $common = $newCommon;
        }
        if ($j < $i+4) break; // at least 4 functions with a common prefix of at least 2 chars
        print substr($common, strlen($prefixes[0])) . "(?:";
        array_unshift($prefixes, $common);
    }

    print substr($func, strlen($prefixes[0]));
}

print ')\b';
pn at bptv dot eu 13-Jul-2016 09:02
There are (07/13/2016 [mm/dd/yyyy]) exactly 9455 Functions listed above.
DIA 14-Apr-2016 09:42
Total number of functions listed above: 9450.
(04/14/2016 [mm/dd/yyyy])
M.A.Y 01-Jan-2016 07:39
Total number of php functions/methods listed above are 9634.
Today's date is 1/1/2016. (mm/dd/yy)
counter at county dot co 07-Apr-2015 02:17
In case anyone was wondering, the total function/method count in this list as of this date is exactly 9457


Listado de ejemplos

Lista todos los ejemplos del manual

  • Example#0 - Un ejemplo introductorio
  • Example#1 - Nuestro primer script de PHP: hola.php
  • Example#2 - Obtener la información del sistema desde PHP
  • Example#3 - Imprimir una variable (elemento de array)
  • Example#4 - Ejemplo usando estructuras de control y funciones
  • Example#5 - Mezcla de los modos HTML y PHP
  • Example#6 - Un formulario HTML sencillo
  • Example#7 - Mostrar información de nuestro formulario
  • Example#8 - Instrucciones de instalación (Versión de módulo compartido de Apache) para PHP
  • Example#9 - Instrucciones de instalación (Instalación de módulo estático para Apache) para PHP
  • Example#10 - Comandos de ejemplo para reiniciar Apache
  • Example#11 -
  • Example#12 -
  • Example#13 -
  • Example#14 -
  • Example#15 -
  • Example#16 -
  • Example#17 -
  • Example#18 -
  • Example#19 -
  • Example#20 -
  • Example#21 -
  • Example#22 -
  • Example#23 -
  • Example#24 - Extracto de lighttpd.conf
  • Example#25 - Lanzando oyentes FastCGI
  • Example#26 - Conexión a instancias de php-fastcgi remotas
  • Example#27 -
  • Example#28 -
  • Example#29 - Ejemplo de instalación de paquete de OpenBSD
  • Example#30 - Ejemplo de Instalación en Debian con Apache 2
  • Example#31 - Deteniendo e iniciando Apache una vez que PHP está instalado
  • Example#32 - Métodos para listar paquetes relacionados con PHP 5
  • Example#33 - Instalar PHP con MySQL, cURL
  • Example#34 - Configuración recomendada de WinCache
  • Example#35 - Configuración recomendada de WinCache
  • Example#36 - Linea de órdenes para configurar IIS y PHP
  • Example#37 - PHP 5 paquete de estructura
  • Example#38 - Configuración CGI y FastCGI en php.ini
  • Example#39 - Configuración de la extensión FastCGI para manejar las solicitudes de PHP
  • Example#40 - Configuración del fichero de los permisos de acceso
  • Example#41 - Configuración FastCGI y reciclaje PHP
  • Example#42 - Configuración de los ajustes de tiempo de espera FastCGI
  • Example#43 - Cambiar la ubicación del fichero php.ini
  • Example#44 - CGI y FastCGI en la configuración php.ini
  • Example#45 - >Creación del proceso del grupo IIS FastCGI
  • Example#46 - Creación de mapas manejador de peticiones PHP
  • Example#47 - La determinación de la cuenta utilizada como IIS identidad anónima
  • Example#48 - Configuración de archivo de los permisos de acceso
  • Example#49 - Establecer index.php como un documento predeterminado en IIS
  • Example#50 - Configuración de PHP FastCGI y el reciclaje
  • Example#51 - Configuración de los ajustes de tiempo de espera FastCGI
  • Example#52 - Cambiar la ubicación del fichero php.ini
  • Example#53 - PHP como módulo de Apache 1.3.x
  • Example#54 - PHP y Apache 1.3.x como CGI
  • Example#55 - PHP and Apache 2.x como controlador
  • Example#56 -
  • Example#57 - PHP y Apache 2.x como CGI
  • Example#58 - Configurar Apache para ejecutar PHP como FastCGI
  • Example#59 - Configuracion de Sambar ISAPI
  • Example#60 - Habilitar la extensión Bzip2 para PHP-Windows
  • Example#61 - Registro de cambios
  • Example#62 - Pasando variables de entorno y ajustando las configuraciones de PHP por grupos
  • Example#63 - Establecer ajustes PHP en nginx.conf
  • Example#64 - llamada a phpinfo
  • Example#65 - Variables de entorno de php.ini
  • Example#66 - Ejemplo de php.ini
  • Example#67 - Ejemplo de configuración de Apache
  • Example#68 - Salida avanzada usando condiciones
  • Example#69 - Etiquetas de apertura y de cierre de PHP
  • Example#70 - Literales de números enteros
  • Example#71 - Desbordamiento de enteros en sistemas de 32 bit
  • Example#72 - Desbordamiento de enteros en sistemas de 64 bit
  • Example#73 - Ejemplo no válido
  • Example#74 - Ejemplo de entrecomillado de string en Heredoc
  • Example#75 - Ejemplo de Heredoc en argumentos
  • Example#76 - Usar Heredoc para inicializar valores estáticos
  • Example#77 - Emplear comillas dobles en Heredoc
  • Example#78 - Ejemplo de entrecomillado de string de Nowdoc
  • Example#79 - Ejemplo de datos estáticos
  • Example#80 - Ejemplo de sintaxis simple
  • Example#81 - Algunos ejemplos de string
  • Example#82 - Diferencias entre PHP 5.3 y PHP 5.4
  • Example#83 - Un array simple
  • Example#84 - Ejemplo de amoldamiento de tipo y sobrescritura
  • Example#85 - Claves mixtas integer y string
  • Example#86 - Arrays indexados sin clave
  • Example#87 - Claves no en todos los elementos
  • Example#88 - Acceso a elementos de un array
  • Example#89 - Hacer referencia al resultado array de funciones
  • Example#90 - Uso de array()
  • Example#91 - Colección
  • Example#92 - Cambiando elemento en el bucle
  • Example#93 - Índice con base 1
  • Example#94 - Llenado de un array
  • Example#95 - Ordenado de un array
  • Example#96 - Arrays recursivos y multi-dimensionales
  • Example#97 - Ejemplo de de tipo de parámetro iterable
  • Example#98 - Ejemplo de valor predeterminado de un parámetro iterable
  • Example#99 - Ejemplo de tipo de retorno iterable
  • Example#100 - Ejemplo de tipo de retorno de generadro iterable
  • Example#101 - Ejemplo de varianza del tipo iterable
  • Example#102 - Ejemplos de funciones de llamadas de retorno
  • Example#103 - Ejemplo de retrollamada utilizando un cierre
  • Example#104 -
  • Example#105 - Basic class type declaration
  • Example#106 - Basic interface type declaration
  • Example#107 - Basic return type declaration
  • Example#108 - Returning an object
  • Example#109 - Nullable argument type declaration
  • Example#110 - Nullable return type declaration
  • Example#111 - Old way to make arguments nullable
  • Example#112 - Strict typing for arguments values
  • Example#113 - Coercive typing for argument values
  • Example#114 - Strict typing for return values
  • Example#115 - Example of types being coerced into a type part of the union
  • Example#116 - Typed pass-by-reference Parameters
  • Example#117 - Catching TypeError
  • Example#118 - Valores predeterminados en variables sin inicializar
  • Example#119 - Uso de global
  • Example#120 - Uso de $GLOBALS en lugar de global
  • Example#121 - Ejemplo que demuestra las superglobales y el ámbito
  • Example#122 - Ejemplo que demuestra la necesidad de variables estáticas
  • Example#123 - Ejemplo del uso de variables estáticas
  • Example#124 - Variables estáticas con funciones recursivas
  • Example#125 - Declaración de variables estáticas
  • Example#126 - Ejemplo de propiedad variable
  • Example#127 - Un formulario HTML sencillo
  • Example#128 - Acceso a datos de un formulario HTML sencillo con POST
  • Example#129 - Old methods of accessing user input
  • Example#130 - Variables de formulario más complejas
  • Example#131 - Un ejemplo de setcookie
  • Example#132 - Nombres de constantes correctos e incorrectos
  • Example#133 - Definición de constantes
  • Example#134 - Definición de constantes usando el la palabra reservada const
  • Example#135 - Asociatividad
  • Example#136 - Orden de evaluación no definido
  • Example#137 - +, - y . tienen la misma precedencia
  • Example#138 - Asignación por referencia
  • Example#139 - Operaciones AND, OR y XOR bit a bit sobre integers
  • Example#140 - Operaciones XOR bit a bit sobre strings
  • Example#141 - Desplazamiento de bits sobre integers
  • Example#142 - Comparación boolean/null
  • Example#143 - Transcripción de la comparación estándar de arrays
  • Example#144 - Asignación de un valor predeterminado
  • Example#145 - Comportamiento Ternario poco obvio
  • Example#146 - Operaciones aritméticas sobre variables de caracteres
  • Example#147 - Los operadores lógicos ilustrados
  • Example#148 - Comparando arrays
  • Example#149 - Utilizando instanceof con clases
  • Example#150 - Utilizando instanceof con clases heredadas
  • Example#151 - Utilizando instanceof para verificar si un objeto no es una instancia de una clase
  • Example#152 - Utilizando instanceof para la clase
  • Example#153 - Utilizando instanceof con otras variables
  • Example#154 - Usar instanceof para comprobar otras variables
  • Example#155 - Evitando búsquedas del nombre de clase y errores fatales con instanceof en PHP 5.0
  • Example#156 - Estructura switch
  • Example#157 - Estrutura switch permite el uso de strings
  • Example#158 - Structure of a match expression
  • Example#159 - Example of an unhandled match expression
  • Example#160 - Using a generalized match expressions to branch on integer ranges
  • Example#161 - Using a generalized match expressions to branch on string content
  • Example#162 - Ejemplo de uso del tick
  • Example#163 - Ejemplo de uso de ticks
  • Example#164 - Declarando un encoding para el script
  • Example#165 - Ejemplo básico de include
  • Example#166 - Incluyendo dentro de funciones
  • Example#167 - include por medio de HTTP
  • Example#168 - Comparando el valor de retorno de include
  • Example#169 - include y la sentencia return
  • Example#170 - Usando buffering de salida para incluir un archivo PHP dentro de una cadena
  • Example#171 - Ejemplo de goto
  • Example#172 - Ejemplo de goto en un bucle
  • Example#173 - Esto no funcionará
  • Example#174 - Seudocódigo para demostrar el uso de funciones
  • Example#175 - Funciones condicionales
  • Example#176 - Funciones dentro de funciones
  • Example#177 - Funciones recursivas
  • Example#178 - Pasar arrays a funciones
  • Example#179 - Paso de parámetros de una función por referencia
  • Example#180 - Uso de parámetros predeterminados en funciones
  • Example#181 - Usar tipos no escalares como valores predeterminados
  • Example#182 - Uso incorrecto de argumentos predeterminados en una función
  • Example#183 - Uso correcto de argumentos predeterminados en una función
  • Example#184 -
  • Example#185 - Declaración básica de tipo clase
  • Example#186 - Declaración básica de tipo interfaz
  • Example#187 - Tipos de parámetros pasados por referencia
  • Example#188 - Declaración de tipo nulo
  • Example#189 - Tipificación estricta
  • Example#190 - Tipificación débil
  • Example#191 - Capturar la excepción TypeError
  • Example#192 - Usando ... para acceder a argumentos variables
  • Example#193 - Usar ... para proporcionar argumentos
  • Example#194 - Argumentos variables de declaración de tipo
  • Example#195 - Acceder a argumentos variables en PHP 5.5 y anteriores
  • Example#196 - Named argument syntax
  • Example#197 - Positional arguments versus named arguments
  • Example#198 - Same example as above with a different order of parameters
  • Example#199 - Combining named arguments with positional arguments
  • Example#200 - Error exception when passing the same parameter multiple times
  • Example#201 - Empleo de return
  • Example#202 - Devolver un array para obtener múltiples valores
  • Example#203 - Devolver una referencia desde una función
  • Example#204 - Declaración básica de tipo de devolución
  • Example#205 - El modo estricto en acción
  • Example#206 - Devolver un objeto
  • Example#207 - Declaración de tipo de retorno anulable (a partir de PHP 7.1.0)
  • Example#208 - Ejemplo de función variable
  • Example#209 - Ejemplo de método variable
  • Example#210 - Ejemplo de método variable con propiedades estáticas
  • Example#211 - Llamables complejos
  • Example#212 - Ejemplo de función anónima
  • Example#213 - Ejemplo de asignación de variable de una función anónima
  • Example#214 - Heredar variables de un ámbito padre
  • Example#215 - Cierres y ámbito
  • Example#216 - Vinculación automática de $this
  • Example#217 - Intentar usar $this dentro de una función anónima estática
  • Example#218 - Intentar vincular un objeto a una función anónima estática
  • Example#219 - Las funciones de flecha capturan las variables por valor automáticamente
  • Example#220 - Las funciones de flecha capturan variables por valor automáticamente, incluso cuando están anidadas
  • Example#221 - Ejemplos de funciones de flecha
  • Example#222 - Los valores del alcance exterior no pueden ser modificados por las funciones de flecha
  • Example#223 - Definición de una clase sencilla
  • Example#224 - Algunos ejemplos de la pseudovariable $this
  • Example#225 - Creación de una instancia
  • Example#226 - Asignación de objetos
  • Example#227 - Creación de nuevos objetos
  • Example#228 - Acceder a un mimebro de un objeto recién creado
  • Example#229 - Acceso a propiedad contra llamada a método
  • Example#230 - Llamar a una función anónima almacenada en una propiedad
  • Example#231 - Herencia de clases sencilla
  • Example#232 - Compatible child methods
  • Example#233 - Fatal error when a child method removes a parameter
  • Example#234 - Fatal error when a child method makes an optional parameter mandatory
  • Example#235 - Error when using named arguments and parameters were renamed in a child class
  • Example#236 - Resolución de nombres de clases
  • Example#237 - Missing class name resolution
  • Example#238 - Object name resolution
  • Example#239 - Nullsafe Operator
  • Example#240 - Declaración de propiedades
  • Example#241 - Ejemplo del uso de nowdoc para inicializar una propiedad
  • Example#242 - Definición y uso de una constante
  • Example#243 - Ejemplo de datos estáticos
  • Example#244 - Ejemplo de ::class en espacio de nombres
  • Example#245 - Ejemplo de expresión constante
  • Example#246 - Modificadores de visibilidad de constantes de clase
  • Example#247 - Ejemplo de autocarga
  • Example#248 - Otro ejemplo de autocarga
  • Example#249 - Autocarga con manejo de excepciones para 5.3.0+
  • Example#250 - Autocarga con manejo de excepciones para 5.3.0+: Excepción personalizada ausente
  • Example#251 - Utilización de nuevos constructores unificados
  • Example#252 - Using constructor arguments
  • Example#253 - Using constructor property promotion
  • Example#254 - Using static creation methods
  • Example#255 - Ejemplo de Destructor
  • Example#256 - Declaración de propiedades
  • Example#257 - Declaración de métodos
  • Example#258 - Declaración de constantes a partir de PHP 7.1.0
  • Example#259 - Accediendo a miembros private del mismo tipo de objeto
  • Example#260 - Ejemplo de herencia
  • Example#261 - :: desde el exterior de la definición de la clase
  • Example#262 - :: desde el interior de la definición de la clase
  • Example#263 - Invocando a un método parent
  • Example#264 - Ejemplo de método estático
  • Example#265 - Ejemplo de propiedad estática
  • Example#266 - Ejemplo de clase abstracta
  • Example#267 - Ejemplo de clase abstracta
  • Example#268 - Ejemplo de interfaz
  • Example#269 - Interfaces extensibles
  • Example#270 - Herencia múltiple de interfaces
  • Example#271 - Interfaces con constantes
  • Example#272 - Ejemplo de rasgo
  • Example#273 - Ejemplo de Orden de Precedencia
  • Example#274 - Ejemplo de Orden de Precedencia #2
  • Example#275 - Uso de varios rasgos
  • Example#276 - Resolución de Conflictos
  • Example#277 - Modificar la Visibilidad de un Método
  • Example#278 - Traits compuestos de traits
  • Example#279 - Expresar Resquisitos con Métodos Abstractos
  • Example#280 - Variables estáticas
  • Example#281 - Métodos Estáticos
  • Example#282 - Definir Propiedades
  • Example#283 - Resolución de Conflictos
  • Example#284 - Sobrecarga de propiedades mediante los métodos __get(), __set(), __isset() y __unset()
  • Example#285 - Sobrecarga de métodos mediante los métodos __call() and __callStatic()
  • Example#286 - Iteración simple de un objeto
  • Example#287 - Iteración de un objeto implementando Iterator
  • Example#288 - Iteración de un objeto implementando IteratorAggregate
  • Example#289 - Sleep y wakeup
  • Example#290 - Ejemplo simple
  • Example#291 - Uso de __invoke()
  • Example#292 - Uso de __set_state() (desde PHP 5.1.0)
  • Example#293 - Utilizar __debugInfo()
  • Example#294 - Ejemplo de métodos Final
  • Example#295 - Ejemplo de clase Final
  • Example#296 - Clonación de un objeto
  • Example#297 - Acceder a un miembre del objeto recién clonado
  • Example#298 - Ejemplo de comparación de objetos en PHP 5
  • Example#299 - Uso de self::
  • Example#300 - Uso básico de static::
  • Example#301 - Uso de static:: en un contexto no estático
  • Example#302 - Llamadas que propagan y que no propagan la información de llamada
  • Example#303 - Referencias y Objetos
  • Example#304 - Ejemplo de sintaxis de espacios de nombres
  • Example#305 - Declarar un único espacio de nombres
  • Example#306 - Declarar un único espacio de nombres
  • Example#307 - Declarar un único espacio de nombres con jerarquía
  • Example#308 - Declarar varios espacios de nombres, sintaxis de combinación simple
  • Example#309 - Declarar varios espacios de nombres, sintaxis de llaves
  • Example#310 - Declarar múltiples espacios de nombres y código que no es de espacio de nombres
  • Example#311 - Declarar varios espacios de nombres y código que no es de espacio de nombres
  • Example#312 - Acceder a clases, funciones y constantes globales desde un espacio de nombres
  • Example#313 - Acceder dinámicamente a elementos
  • Example#314 - Acceder dinámicamente a elementos de un espacio de nombres
  • Example#315 - Ejemplo de __NAMESPACE__, código de espacio de nombres
  • Example#316 - Ejemplo de __NAMESPACE__, código global
  • Example#317 - Empleo de __NAMESPACE__ para la construcción dinámica de nombres
  • Example#318 - El operador namespace, dentro de un espacio de nombres
  • Example#319 - El operador namespace, en código global
  • Example#320 - Importar/apodar con el operador use
  • Example#321 - Importar/apodar con el operador use, varias sentencias use combinadas
  • Example#322 - La importación y los nombres dinámicos
  • Example#323 - La importación y los nombres completamente cualificados
  • Example#324 - Regla de importación ilegal
  • Example#325 - Usar la especificación de espacio global
  • Example#326 - Acceder a clases globales dentro de un espacio de nombres
  • Example#327 - Recurrir a funciones/constantes globales dentro de un espacio de nombres
  • Example#328 - Las resoluciones de nombres ilustradas
  • Example#329 - Acceder a clases globales fuera de un espacio de nombres
  • Example#330 - Acceder a clases globales fuera de un espacio de nombres
  • Example#331 - Acceder a clases internas en espacios de nombres
  • Example#332 - Acceder a clases, funciones o constantes internas en un espacio de nombres
  • Example#333 - Nombres completamente cualificados
  • Example#334 - Nombres cualificados
  • Example#335 - Nombres de clases no cualificados
  • Example#336 - Nombres de funciones o constantes no cualificados
  • Example#337 - Peligros de usar nombres de espacios de nombres dentro de una cadena entre comillas dobles
  • Example#338 - Constantes no definidas
  • Example#339 - Constantes no definidas
  • Example#340 - La clase Exception Interna
  • Example#341 - Extender la clase Exception (PHP 5.3.0+)
  • Example#342 - Lanzar una Excepción
  • Example#343 - Manejo de excepciones con un bloque finally
  • Example#344 - Excepciones anidadas
  • Example#345 - Implementando range como generador
  • Example#346 - Ejemplo sencillo de facilitar valores con yield
  • Example#347 - Facilitar un par clave-valor
  • Example#348 - Yielding nulls
  • Example#349 - Facilitar valores por referencia
  • Example#350 - yield from con iterator_to_array
  • Example#351 - Uso básico de yield from
  • Example#352 - yield from y valores devueltos
  • Example#353 - Implementing optional methods of an interface with Attributes
  • Example#354 - Attribute Syntax
  • Example#355 - Reading Attributes using Reflection API
  • Example#356 - Reading Specific Attributes using Reflection API
  • Example#357 - Using target specification to restrict where attributes can be used
  • Example#358 - Simple Attribute Class
  • Example#359 - Using IS_REPEATABLE to allow attribute on a declaration multiple times
  • Example#360 - Usar referencias con variables no definidas
  • Example#361 - Refenciar variables globales dentro de funciones
  • Example#362 - Referencias y la sentencia foreach
  • Example#363 - Ejemplo de $GLOBALS
  • Example#364 - Ejemplo de $_SERVER
  • Example#365 - Ejemplo de $_GET
  • Example#366 - Ejemplo de $_POST
  • Example#367 - Ejemplo de $_ENV
  • Example#368 - Ejemplo de $_COOKIE
  • Example#369 - Ejemplo de $php_errormsg
  • Example#370 - Ejemplo de $http_response_header
  • Example#371 - Ejemplo de $argc
  • Example#372 - Ejemplo de $argv
  • Example#373 - Ejemplo de Exception::getMessage
  • Example#374 - Ejemplo de Exception::getPrevious
  • Example#375 - Ejemplo de Exception::getCode
  • Example#376 - Ejemplo de Exception::getFile
  • Example#377 - Ejemplo de Exception::getLine
  • Example#378 - Ejemplo de Exception::getTrace
  • Example#379 - Ejemplo de Exception::getTraceAsString
  • Example#380 - Ejemplo de Exception::__toString
  • Example#381 - Utilizar set_error_handler para convertir mensajes de error en objetos ErrorException.
  • Example#382 - Ejemplo de ErrorException::getSeverity
  • Example#383 - Ejemplo de Error::getMessage
  • Example#384 - Ejemplo de Error::getPrevious
  • Example#385 - Ejemplo de Error::getCode
  • Example#386 - Ejemplo de Error::getFile
  • Example#387 - Ejemplo de Error::getLine
  • Example#388 - Ejemplo de Error::getTrace
  • Example#389 - Ejemplo de Error::getTraceAsString
  • Example#390 - Ejemplo de Error::__toString
  • Example#391 - Uso básico
  • Example#392 - Uso básico
  • Example#393 - Uso básico
  • Example#394 - Ejemplo de ArrayAccess::offsetExists
  • Example#395 - Uso básico
  • Example#396 - Ejemplo de Closure::bind
  • Example#397 - Ejemplo de Closure::bindTo
  • Example#398 - Ejemplo de Closure::call
  • Example#399 - Ejemplo de Generator::getReturn
  • Example#400 - Ejemplo de Generator::key
  • Example#401 - Empleo de Generator::send para inyectar valores
  • Example#402 - Lanzar una ecepión dentro de un generador
  • Example#403 - Uso básico de WeakReference
  • Example#404 - Ejemplo de uso básico de bindto
  • Example#405 - Obtener una página y enviar datos POST
  • Example#406 - Ignorar las redirecciones, aunque obtener las cabeceras y el contenido
  • Example#407 - Obtener una página y enviar datos POST
  • Example#408 - Ejemplo de uso básico password
  • Example#409 - Detectar la URL en la que se finaliza tras las redirecciones
  • Example#410 - php://temp/maxmemory
  • Example#411 - php://filter/resource=<flujo a filtrar>
  • Example#412 - php://filter/read=<lista de filtros a aplicar a la cadena de lectura>
  • Example#413 - php://filter/write=<lista de filtros a aplicar a la cadena de escritura>
  • Example#414 - php://memory y php://temp no son reutilizables
  • Example#415 - Mostrar contenidos de data://
  • Example#416 - Obtener el Tipo de Medio
  • Example#417 - Uso básico
  • Example#418 - Abriendo un flujo a partir de una conexión activa
  • Example#419 - ¡La variable $session debe permanecer disponible!
  • Example#420 - Recorriendo un archivo RAR
  • Example#421 - Abriendo un fichero encriptado (encriptación de cabeceras)
  • Example#422 - Un control pobre puede llevar a ....
  • Example#423 - ... Un ataque al sistema de archivos
  • Example#424 - Comprobación más segura del nombre de archivo
  • Example#425 - Comprobación más segura del nombre de archivo
  • Example#426 - Script vulnerable a bytes nulos
  • Example#427 - Validando correctamente la entrada
  • Example#428 - Campo de contraseña con hash
  • Example#429 - Contraseña con hash utilizando crypt
  • Example#430 - Dividir el conjunto de resultados en páginas ... y crear superusuarios (PostgreSQL)
  • Example#431 - Enumerar artículos ... y algunas contraseñas (cualquier servidor de bases de datos)
  • Example#432 - Desde restablecer una contraseña ... hasta obtener más privilegios (cualquier servidor de bases de datos)
  • Example#433 - Atacar el sistema operativo que hospeda la base de datos (Servidor MSSQL)
  • Example#434 - Una forma más segura de componer una consulta para paginación
  • Example#435 - Atacando variables con una página HTML personalizada
  • Example#436 - Explotando variables comunes de depuración
  • Example#437 - Buscando variables peligrosas con E_ALL
  • Example#438 - Uso Peligroso de Variables
  • Example#439 - Ocultando PHP como si fuera otro lenguaje
  • Example#440 - Utilizar tipos desconocidos para extensiones de PHP
  • Example#441 - Utilizar tipos HTML para extensiones de PHP
  • Example#442 - Ejemplo de autenticación HTTP 'Basic'
  • Example#443 - Ejemplo de autenticación HTTP 'Digest'
  • Example#444 - Ejemplo de autenticación HTTP forzando un nuevo usuario/contraseña
  • Example#445 - Un formulario simple de búsqueda con XForms
  • Example#446 - Empleo de un Xform para rellenar $_POST
  • Example#447 - Formulario para la subida de ficheros
  • Example#448 - Validación de la subida de ficheros
  • Example#449 - Subir un array de ficheros
  • Example#450 - Subida de varios ficheros
  • Example#451 - Guardar ficheros PUT de HTTP
  • Example#452 - Obtener el título de una página remota
  • Example#453 - Almacenar datos en un servidor remoto
  • Example#454 - Ejemplo que muestra las diferencias respecto a la SAPI CGI:
  • Example#455 -
  • Example#456 - Muestra los módulos PHP y Zend incorporados (y habilitados)
  • Example#457 - Obteniendo un error sintáctico usando comillas dobles
  • Example#458 - Usando comillas simples para prevenir la sustitución de variables de la consola
  • Example#459 - Usando las opciones -B, -R y -E para contar el número de líneas de un proyecto.
  • Example#460 - Al usar -v obtenemos el nombre de la SAPI y la versión de PHP y Zend
  • Example#461 - Ejemplo de --ini
  • Example#462 - Uso básico de --rf
  • Example#463 - Ejemplo de --rc
  • Example#464 - Ejemplo de --re
  • Example#465 - Ejemplo de --ri
  • Example#466 - Ejecutando un script PHP como un script de consola
  • Example#467 - Script destinado a ejecutarse desde la línea de comandos (script.php)
  • Example#468 - Fichero por lotes para ejecutar un script PHP en línea de comandos (script.bat)
  • Example#469 - Ejecutando código desde la consola interactiva
  • Example#470 - Autocompletado con el tabulador
  • Example#471 - Estableciendo configuraciones de php.ini en la shell interactiva
  • Example#472 - Iniciando el servidor web
  • Example#473 - Iniciando con una raíz de documentos específica
  • Example#474 - Utilizando un Script enrutador
  • Example#475 - Revisión del uso de la CLI del servidor web
  • Example#476 - Manejando tipos de ficheros no soportados
  • Example#477 - Accediendo a la CLI del servidor web desde máquinas remotas
  • Example#478 - Creación de un nuevo contenedor zval
  • Example#479 - Mostrar información de zval
  • Example#480 - Incremento de refcount de un zval
  • Example#481 - Decremento de refcount de zval
  • Example#482 - Crear un zval de tipo array
  • Example#483 - Añadir un elemento existente a un array
  • Example#484 - Eliminar un elemento de un array
  • Example#485 - Añadir el propio array como elemento de sí mismo
  • Example#486 - Eliminar $a
  • Example#487 - Ejemplo de uso de memoria
  • Example#488 - Influencia en rendimiento de Recolector de Basuras
  • Example#489 - Ejecutando el script anterior
  • Example#490 - Recompilando PHP para habilitar el análisis del Recolector de Basuras
  • Example#491 - Estadísticas de Recolección de Basuras
  • Example#492 - all_probes.d para monitorizar todos los Sondeos Estáticos en PHP con DTrace
  • Example#493 - all_probes.stp para monitorizar todas los Sondeos Estáticos de PHP con SystemTap
  • Example#494 - A apcu_add example
  • Example#495 - Un ejemplo de apcu_cache_info
  • Example#496 - Ejemplo de apcu_cas
  • Example#497 - Ejemplo de apcu_dec
  • Example#498 - Un ejemplo deapcu_delete
  • Example#499 - An apcu_entry example
  • Example#500 - apcu_exists example
  • Example#501 - A apcu_fetch example
  • Example#502 - apcu_inc example
  • Example#503 - A apcu_key_info example
  • Example#504 - A apcu_sma_info example
  • Example#505 - A apcu_store example
  • Example#506 - Un ejemplo de APCUIterator::__construct
  • Example#507 - Usar el manejo de errores en un script
  • Example#508 - Ejemplo de debug_backtrace
  • Example#509 - Ejemplo de debug_print_backtrace
  • Example#510 - Un ejemplo de error_clear_last
  • Example#511 - Un ejemplo de error_get_last
  • Example#512 - Ejemplos de error_log
  • Example#513 - Ejemplos de error_reporting
  • Example#514 - Ejemplo de restore_error_handler
  • Example#515 - Ejemplo de restore_exception_handler
  • Example#516 - Manejo de errores con set_error_handler y trigger_error
  • Example#517 - Ejemplo de set_exception_handler
  • Example#518 - Ejemplo de trigger_error
  • Example#519 - Calling a function from shared library
  • Example#520 - Calling a function, returning a structure through an argument
  • Example#521 - Accessing existing C variables
  • Example#522 - Creating and Modifying C variables
  • Example#523 - Working with C arrays
  • Example#524 - Working with C enums
  • Example#525 -
  • Example#526 -
  • Example#527 - Crear una matriz grande en una función
  • Example#528 - Ejemplo de control de la salida
  • Example#529 - Ejemplo de ob_end_clean
  • Example#530 - Ejemplo de ob_end_flush
  • Example#531 - Un ejemplo sencillo de ob_get_clean
  • Example#532 - Un ejemplo sencillo de ob_get_contents
  • Example#533 - Ejemplo de ob_get_flush
  • Example#534 - Un ejemplo sencillo de ob_get_length
  • Example#535 - Ejemplo de ob_gzhandler
  • Example#536 - Ejemplo de ob_list_handlers
  • Example#537 - Ejemplo de una función de llamada de retorno definida por el usuario
  • Example#538 - Crear un búfer de salida imborrable de forma compatible con PHP 5.3 y 5.4
  • Example#539 - Ejemplo de output_add_rewrite_var
  • Example#540 - Ejemplo de output_reset_rewrite_vars
  • Example#541 - Ejemplo de assert_options
  • Example#542 - Handle a failed assertion with a custom handler
  • Example#543 - Using a custom handler to print a description
  • Example#544 - Expectations without a custom exception
  • Example#545 - Expectations with a custom exception
  • Example#546 - cli_get_process_title example
  • Example#547 - cli_set_process_title example
  • Example#548 - Ejemplos de dl
  • Example#549 - Ejemplo de extension_loaded
  • Example#550 - Ejemplo de gc_enabled
  • Example#551 - gc_status Usage
  • Example#552 - get_current_user ejemplo
  • Example#553 - Ejemplo de get_defined_constants
  • Example#554 - Imprime las funciones XML
  • Example#555 - Ejemplo de get_include_path
  • Example#556 - Ejemplo de get_included_files
  • Example#557 - get_loaded_extensions
  • Example#558 - get_magic_quotes_runtime ejemplo
  • Example#559 - Unfiltered get_resources
  • Example#560 - Filtered get_resources
  • Example#561 - Ejemplo de getenv
  • Example#562 - Ejemplo de getlastmod
  • Example#563 - Ejemplo de getopt: Lo básico
  • Example#564 - Ejemplo de getopt: Introducir opciones long
  • Example#565 - Ejemplo de getopt: Pasar varias opciones como una
  • Example#566 - getrusage ejemplo
  • Example#567 - ini_get_all ejemplos
  • Example#568 - Disabling details
  • Example#569 - Unos cuantos ejemplos de la función ini_get
  • Example#570 - ini_restore ejemplo
  • Example#571 - Establece una opción ini
  • Example#572 - A memory_get_usage ejemplo
  • Example#573 - php_ini_loaded_file ejemplo
  • Example#574 - Un ejemplo simple para enumerar los archivos ini devueltos
  • Example#575 - Ejemplo de php_sapi_name
  • Example#576 - Algúnos ejemplos de php_uname
  • Example#577 - Algunos ejemplos de las constantes relacionadas al SO
  • Example#578 - Imprimir los créditos generales
  • Example#579 - Imprimir los desarrolladores principales y el grupo de documentación
  • Example#580 - Imprimir todos los créditos
  • Example#581 - Ejemplo de phpinfo
  • Example#582 - phpversion Ejemplo básico
  • Example#583 - PHP_VERSION_ID Ejemplo y uso
  • Example#584 - Definición de una variable de entorno
  • Example#585 - Ejemplo de restore_include_path
  • Example#586 - Ejemplo de set_include_path
  • Example#587 - Añadir a la ruta de inclusión
  • Example#588 - sys_get_temp_dir example
  • Example#589 - Ejemplos de version_compare
  • Example#590 - Ejemplo de zend_thread_id
  • Example#591 - Ejemplo de zend_version
  • Example#592 - Superglobales personalizadas con runkit.superglobal=_FOO,_BAR en php.ini
  • Example#593 - Un ejemplo de runkit_function_add
  • Example#594 - Un ejemplo de runkit_function_copy
  • Example#595 - Un ejemplo de runkit_function_redefine
  • Example#596 - Ejemplo de runkit_import
  • Example#597 - Ejemplo de runkit_method_add
  • Example#598 - Ejemplo de runkit_method_copy
  • Example#599 - Ejemplo de runkit_method_redefine
  • Example#600 - Ejemplo de runkit_method_remove
  • Example#601 - Ejemplo derunkit_method_rename
  • Example#602 - Basic uopz_add_function Usage
  • Example#603 - uopz_allow_exit example
  • Example#604 - uopz_backup example
  • Example#605 - uopz_compose example
  • Example#606 - uopz_copy example
  • Example#607 - Basic uopz_del_function Usage
  • Example#608 - uopz_delete example
  • Example#609 - uopz_delete class example
  • Example#610 - uopz_extend example
  • Example#611 - uopz_flags example
  • Example#612 - "Unfinalize" a Class
  • Example#613 - uopz_function example
  • Example#614 - uopz_function class example
  • Example#615 - uopz_get_exit_status example
  • Example#616 - Basic uopz_get_hook Usage
  • Example#617 - uopz_get_mock example
  • Example#618 - Basic uopz_get_property Usage
  • Example#619 - uopz_get_return example
  • Example#620 - Basic uopz_get_static Usage
  • Example#621 - uopz_implement example
  • Example#622 - uopz_overload example
  • Example#623 - uopz_redefine example
  • Example#624 - uopz_rename example
  • Example#625 - uopz_rename class example
  • Example#626 - uopz_restore example
  • Example#627 - Basic uopz_set_hook Usage
  • Example#628 - uopz_set_mock example
  • Example#629 - uopz_set_mock example
  • Example#630 - uopz_set_mock and static members
  • Example#631 - Basic uopz_set_property Usage
  • Example#632 - uopz_set_return example
  • Example#633 - uopz_set_return example
  • Example#634 - uopz_set_return class example
  • Example#635 - Basic uopz_set_static Usage
  • Example#636 - uopz_undefine example
  • Example#637 - Basic uopz_unset_hook Usage
  • Example#638 - uopz_unset_mock example
  • Example#639 - uopz_unset_return example
  • Example#640 - Ejemplo de uso de Weakref
  • Example#641 - Ejemplo de uso de WeakRef
  • Example#642 - Ejemplo de Weakref::acquire
  • Example#643 - Ejemplo de acquire/release anidados
  • Example#644 - Ejemplo de Weakref::__construct
  • Example#645 - Ejemplo de Weakref::release
  • Example#646 - Ejemplo de uso de Weakmap
  • Example#647 - Ejemplo de wincache.ignorelist
  • Example#648 - Authentication configuration for wincache.php
  • Example#649 - Enabling WinCache session handler
  • Example#650 - Enabling WinCache functions reroutes
  • Example#651 - Reroute.ini file content
  • Example#652 - A wincache_fcache_fileinfo example
  • Example#653 - Un ejemplo de wincache_fcache_meminfo
  • Example#654 - Empleo de wincache_lock
  • Example#655 - A wincache_ocache_fileinfo example
  • Example#656 - A wincache_ocache_meminfo example
  • Example#657 - A wincache_refresh_if_changed example
  • Example#658 - A wincache_rplist_fileinfo example
  • Example#659 - A wincache_rplist_meminfo example
  • Example#660 - A wincache_scache_info example
  • Example#661 - Ejemplo de wincache_scache_meminfo
  • Example#662 - wincache_ucache_add with key as a string
  • Example#663 - wincache_ucache_add with key as an array
  • Example#664 - Usando wincache_ucache_cas
  • Example#665 - Usando wincache_ucache_clear
  • Example#666 - Usando wincache_ucache_dec
  • Example#667 - Usando wincache_ucache_delete con key como un string
  • Example#668 - Usingwincache_ucache_delete con key como un array
  • Example#669 - Using wincache_ucache_delete con key como un array donde algunos elementos no se pueden eliminar
  • Example#670 - Usando wincache_ucache_exists
  • Example#671 - wincache_ucache_get con key como un string
  • Example#672 - wincache_ucache_get con key como un array
  • Example#673 - Usando wincache_ucache_inc
  • Example#674 - Usar wincache_ucache_info
  • Example#675 - Ejemplo de wincache_ucache_meminfo
  • Example#676 - wincache_ucache_set with key as a string
  • Example#677 - wincache_ucache_set with key as an array
  • Example#678 - Usar wincache_unlock
  • Example#679 - Ejemplo Xhprof con interfaz gráfica de usuario opcional
  • Example#680 - xhprof_disable ejemplo
  • Example#681 - Ejemplos de xhprof_enable
  • Example#682 - Ejemplo de xhprof_sample_disable
  • Example#683 - Asegúrate de que el artículo se almacene
  • Example#684 - Using CHAP passwords
  • Example#685 - radius_acct_open example
  • Example#686 - radius_add_server example
  • Example#687 - Ejemplo de radius_auth_open
  • Example#688 - radius_create_request example
  • Example#689 - radius_cvt_addr example
  • Example#690 - radius_cvt_int example
  • Example#691 - radius_cvt_string example
  • Example#692 - radius_get_attr example
  • Example#693 - radius_get_tagged_attr_data example
  • Example#694 - radius_get_tagged_attr_tag example
  • Example#695 - radius_get_vendor_attr example
  • Example#696 - radius_put_attr example
  • Example#697 - radius_put_int example
  • Example#698 - radius_put_string example
  • Example#699 - radius_put_vendor_attr example
  • Example#700 - Writing a string with a specified color to the screen
  • Example#701 - Ejemplo de ncurses_getmouse
  • Example#702 - Escribir una cadena con un color especificado en la pantalla
  • Example#703 - Escrivir una cadena con un color especificado en la pantalla
  • Example#704 - Ejemplo de ncurses_mousemask
  • Example#705 - Writing a string with a specified color to the screen
  • Example#706 - Ejemplo de interfaz de llamada readline
  • Example#707 - Ejemplo de readline
  • Example#708 - Pequeño ejemplo de bzip2
  • Example#709 - Comprimiendo datos
  • Example#710 - Descompresión de un String
  • Example#711 - Ejemplo de bzerror
  • Example#712 - Ejemplo de bzopen
  • Example#713 - ejemplo de bzread
  • Example#714 - Ejemplo de bzwrite
  • Example#715 - Utilizar un fichero externo
  • Example#716 - Utilizar un fichero dentro de un archivo phar
  • Example#717 - Convertir un archivo phar, desde phar al formato de fichero tar
  • Example#718 - phar.extract_list usage example
  • Example#719 - Ejemplo de uso de phar.cache_list
  • Example#720 - Un ejemplo de Phar::addEmptyDir
  • Example#721 - Un ejemplo de Phar::addFile
  • Example#722 - Un ejemplo de Phar::addFromString
  • Example#723 - Un ejemplo de Phar::apiVersion
  • Example#724 - Un ejemplo de Phar::buildFromDirectory
  • Example#725 - Un ejemplo de Phar::buildFromIterator con SplFileInfo
  • Example#726 - Un ejemplo de Phar::buildFromIterator con otros iteradores
  • Example#727 - Un ejemplo de Phar::canCompress
  • Example#728 - Un ejemplo de Phar::canWrite
  • Example#729 - Un ejemplo de Phar::compress
  • Example#730 - Un ejemplo de Phar::compressFiles
  • Example#731 - Un ejemplo de Phar::__construct
  • Example#732 - Un ejemplo de Phar::convertToData
  • Example#733 - Un ejemplo de Phar::convertToExecutable
  • Example#734 - Un ejemplo de Phar::copy
  • Example#735 - Phar::count ejemplo
  • Example#736 - Un ejemplo de Phar::createDefaultStub
  • Example#737 - Un ejemplo de Phar::decompress
  • Example#738 - Un ejemplo de Phar::decompressFiles
  • Example#739 - Un ejemplo de Phar::delMetaData
  • Example#740 - Un ejemplo de Phar::delete
  • Example#741 - Un ejemplo de Phar::extractTo
  • Example#742 - Un ejemplo de Phar::getMetadata
  • Example#743 - Un ejemplo de Phar::getStub
  • Example#744 - Un ejemplo de Phar::hasMetadata
  • Example#745 - Un ejemplo de Phar::interceptFileFuncs
  • Example#746 - Un ejemplo de Phar::interceptFileFuncs
  • Example#747 - Un ejemplo de Phar::isBuffering
  • Example#748 - Un ejemplo de Phar::isCompressed
  • Example#749 - Un ejemplo de Phar::loadPhar
  • Example#750 - Un ejemplo de Phar::mapPhar
  • Example#751 - Un ejemplo de Phar::mount
  • Example#752 - Un ejemplo de Phar::mungServer
  • Example#753 - Un ejemplo de Phar::offsetExists
  • Example#754 - Ejemplo de Phar::offsetGet
  • Example#755 - Un ejemplo de Phar::offsetSet
  • Example#756 - Un ejemplo de Phar::offsetUnset
  • Example#757 - Un ejemplo de Phar::running
  • Example#758 - Un ejemplo de Phar::setAlias
  • Example#759 - Un ejemplo de Phar::setDefaultStub
  • Example#760 - Un ejemplo de Phar::setMetadata
  • Example#761 - Un ejemplo de Phar::setStub
  • Example#762 - Un ejemplo de Phar::startBuffering
  • Example#763 - Un ejemplo de Phar::stopBuffering
  • Example#764 - Un ejemplo de Phar::unlinkArchive
  • Example#765 - Un ejemplo de Phar::webPhar
  • Example#766 - Un ejemplo de PharData::addEmptyDir
  • Example#767 - Un ejemplo de PharData::addFile
  • Example#768 - Un ejemplo de PharData::addFromString
  • Example#769 - Un ejemplo de PharData::buildFromDirectory
  • Example#770 - Un ejemplo de PharData::buildFromIterator con SplFileInfo
  • Example#771 - Un ejemplo de PharData::buildFromIterator con otros iteradores
  • Example#772 - Un ejemplo de PharData::compress
  • Example#773 - Un ejemplo de PharData::compressFiles
  • Example#774 - Un ejemplo de PharData::__construct
  • Example#775 - Un ejemplo de PharData::convertToData
  • Example#776 - Un ejemplo de PharData::convertToExecutable
  • Example#777 - Un ejemplo de Phar::copy
  • Example#778 - Un ejemplo de PharData::decompress
  • Example#779 - Un ejemplo de PharData::decompressFiles
  • Example#780 - Un ejemplo de PharData::delMetaData
  • Example#781 - Un ejemplo de PharData::delete
  • Example#782 - Un ejemplo de PharData::extractTo
  • Example#783 - Un ejemplo de PharData::offsetSet
  • Example#784 - Un ejemplo de PharData::offsetUnset
  • Example#785 - Un ejemplo de Phar::setMetadata
  • Example#786 - Un ejemplo de PharFileInfo::chmod
  • Example#787 - Un ejemplo de PharFileInfo::compress
  • Example#788 - Un ejemplo de PharFileInfo::__construct
  • Example#789 - Un ejemplo de PharFileInfo::decompress
  • Example#790 - Un ejemplo de PharFileInfo::delMetaData
  • Example#791 - Un ejemplo de PharFileInfo::getCRC32
  • Example#792 - Un ejemplo de PharFileInfo::getCompressedSize
  • Example#793 - Un ejemplo de PharFileInfo::getMetadata
  • Example#794 - Un ejemplo de PharFileInfo::getPharFlags
  • Example#795 - Un ejemplo de PharFileInfo::isCRCChecked
  • Example#796 - Un ejemplo de PharFileInfo::isCompressed
  • Example#797 - Un ejemplo de PharFileInfo::setMetadata
  • Example#798 - Instalación Rar
  • Example#799 - Descompresión "al vuelo"
  • Example#800 - Ejemplo de sistema de extracción de archivos Rar
  • Example#801 - Estilo orientado a objetos
  • Example#802 - Estilo por procedimientos
  • Example#803 - Estilo orientado a objetos
  • Example#804 - Estilo por procedimientos
  • Example#805 - Estilo orientado a objetos
  • Example#806 - Estilo por procedimientos
  • Example#807 - Estilo orientado a objetos
  • Example#808 - Estilo por procedimientos
  • Example#809 - Estilo orientado a objetos
  • Example#810 - Estilo por procedimientos
  • Example#811 - Estilo orientado a objetos
  • Example#812 - Estilo por procedimientos
  • Example#813 - Estilo orientado a objetos
  • Example#814 - Estilo por procedimientos
  • Example#815 - Volume Callback
  • Example#816 - Estilo orientado a objetos
  • Example#817 - Estilo por procedimientos
  • Example#818 - Ejemplo de RarArchive::__toString
  • Example#819 - Ejemplo de RarEntry::extract
  • Example#820 - ¿Cómo extraer todos los archivos en archivo?:
  • Example#821 - Ejemplo de RarEntry::getAttr
  • Example#822 - Ejemplo de RarEntry::getHostOs (version >= 2.0.0)
  • Example#823 - RarEntry::getHostOs example (version <= 1.0.0)
  • Example#824 - Ejemplo de RarEntry::getMethod
  • Example#825 - Ejemplo de RarEntry::getName
  • Example#826 - Ejemplo de RarEntry::getPackedSize
  • Example#827 - Ejemplo de RarEntry::getStream
  • Example#828 - Ejemplo de RarEntry::getUnpackedSize
  • Example#829 - Ejemplo de RarEntry::getVersion
  • Example#830 - Ejemplo de RarException::isUsingExceptions
  • Example#831 - Ejemplo de RarException::setUsingExceptions
  • Example#832 - Crear un fichero Zip
  • Example#833 - Volcar la información del archivo y listarlos
  • Example#834 - Usando contenedor Zip, leer meta info de OpenOffice
  • Example#835 - Ejemplo del uso de Zip
  • Example#836 - Crea un nuevo directorio en un archivo
  • Example#837 - Abrir y extraer
  • Example#838 - Añade una entrada al nuevo fichero
  • Example#839 - Añade un fichero en un directorio dentro de un archivo
  • Example#840 - Ejemplo con ZipArchive::addGlob
  • Example#841 - Ejemplo con ZipArchive::addPattern
  • Example#842 - Elimina el fichero desde el archivo usando su índice
  • Example#843 - Eliminado un fichero y un directorio desde un archivo, usando nombres
  • Example#844 - Extraer todas las entradas
  • Example#845 - Extraer dos entradas
  • Example#846 - Vuelca el comentario del archivo
  • Example#847 - Vuelca el comentario de la entrada
  • Example#848 - Vuelca el comentario de la entrada
  • Example#849 - Extraer todas las entradas con permisos Unix
  • Example#850 - Obtener el contenido del fichero
  • Example#851 - Obtener el contenido de los ficheros
  • Example#852 - Convierte una imagen desde una entrada de fichero zip
  • Example#853 - Ejemplo de ZipArchive::getNameIndex
  • Example#854 - Obtiene los contenidos de entrada con fread y lo almacena
  • Example#855 - Lo mismo como el ejemplo anterior pero con fopen y el envoltorio de flujo de zip
  • Example#856 - El flujo de envoltorio y la imagen, también pueden ser utilizados con la función xml
  • Example#857 - Crear un archivo y luego utilizarlo con ZipArchive::locateName
  • Example#858 - Abrir y extraer
  • Example#859 - Crear un fichero
  • Example#860 - Crear un fichero temporal
  • Example#861 - Archive a file
  • Example#862 - Archive a file
  • Example#863 - Renombra una entrada
  • Example#864 - Renombra una entrada
  • Example#865 - Abrir y reemplazar
  • Example#866 - Crear un archivo y establecer un comentario
  • Example#867 - Abrir un archivo y establecer un comentario para una entrada
  • Example#868 - Abrir un archivo y establecer un comentario para una entrada
  • Example#869 - Añadir ficheros con diferentes métodos de compresión a un archivo
  • Example#870 - Añadir ficheros con diferentes métodos de compresión a un archivo
  • Example#871 - Añadir fichero y establecer el método de compresión
  • Example#872 - Archivar y encriptar un archivo
  • Example#873 - Archivar un fichero, con sus permisos Unix
  • Example#874 - Archivar un fichero
  • Example#875 - Archivar un fichero
  • Example#876 - Volcar la información estadística de una entrada
  • Example#877 - Volcar la información estadística de una entrada
  • Example#878 - Pequeño Ejemplo de Zlib
  • Example#879 - Trabajando con la API de compresión y descompresión increemental desde PHP 7.0.0
  • Example#880 - Ejemplo de gzclose
  • Example#881 - Ejemplo de gzcompress
  • Example#882 - Ejemplo de gzdeflate
  • Example#883 - Creando un archivo gzip
  • Example#884 - Ejemplo de gzeof
  • Example#885 - Ejemplo de gzfile
  • Example#886 - Ejemplo de gzgetc
  • Example#887 - Ejemplo de gzgets
  • Example#888 - Ejemplo de gzgetss
  • Example#889 - Ejemplo de gzinflate
  • Example#890 - Ejemplo de gzopen
  • Example#891 - Ejemplo de gzpassthru
  • Example#892 - Ejemplo de gzread
  • Example#893 - Ejamplo de gzseek
  • Example#894 - Ejemplo de gzuncompress
  • Example#895 - Ejemplo de gzwrite
  • Example#896 - Ejemplo de zlib_encode
  • Example#897 - Ejemplo de random_bytes
  • Example#898 - Ejmplo de random_int
  • Example#899 - hash_algos ejemplo
  • Example#900 - Ejemplo de hash_copy
  • Example#901 - Ejemplo
  • Example#902 - Usando hash_file
  • Example#903 - Ejemplo de hash_final
  • Example#904 - hash_hkdf example
  • Example#905 - hash_hmac_algos example
  • Example#906 - Ejemplo de hash_hmac_file
  • Example#907 - hash_hmac example
  • Example#908 - Ejemplo de hashing incremental
  • Example#909 - Ejemplo de uso básico de hash_pbkdf2
  • Example#910 - Ejemplo de hash_update_stream
  • Example#911 - Un ejemplo de hash
  • Example#912 - Calcular unos 'hashes' Tiger anteriores a PHP 5.4 con PHP 5.4 y superior
  • Example#913 - Cifrar un valor de entrada con AES con una clave de 256 bits bajo 2.4.x y superiores en modo CBC
  • Example#914 - Ejemplo de mcrypt_create_iv
  • Example#915 - Ejemplo de mcrypt_enc_get_algorithms_name
  • Example#916 - Ejemplo de mcrypt_enc_get_modes_name
  • Example#917 - Ejemplo de mcrypt_enc_get_supported_key_sizes
  • Example#918 - Ejemplo de mcrypt_encrypt
  • Example#919 - Ejemplo de mcrypt_get_block_size
  • Example#920 - Ejemplo de mcrypt_get_cipher_name
  • Example#921 - Ejemplo de mcrypt_get_iv_size
  • Example#922 - Ejemplo de mcrypt_get_key_size
  • Example#923 - Ejemplo de mcrypt_list_algorithms
  • Example#924 - Ejemplo de mcrypt_list_modes
  • Example#925 - Ejemplo de mcrypt_module_open
  • Example#926 - Utilizando mcrypt_module_open en el proceso de cifrado
  • Example#927 - Ejemplo de mcrypt_module_self_test
  • Example#928 - Ejemplo de mdecrypt_generic
  • Example#929 - Calcula el MD5 y el hmac, y lo imprime como hexadecimal
  • Example#930 - Atravesando todos los hash
  • Example#931 - Ejemplo de mhash_get_block_size
  • Example#932 - Ejemplo de mhash_get_hash_name
  • Example#933 - Ejemplo de openssl_cipher_iv_length
  • Example#934 - Crear un certificado autofirmado
  • Example#935 - Ejemplo de openssl_csr_sign - firmar una CSR (cómo implementar su propia AC)
  • Example#936 - Ejemplo de openssl_error_string
  • Example#937 - Ejemplo de openssl_get_cert_locations
  • Example#938 - Ejemplo de openssl_get_cipher_methods
  • Example#939 - openssl_get_curve_names example
  • Example#940 - Ejemplo de openssl_get_md_methods
  • Example#941 - Ejemplo de openssl_open
  • Example#942 - Ejemplo de openssl_pkcs12_read
  • Example#943 - Ejemplo de openssl_pkcs7_decrypt
  • Example#944 - Ejemplo de openssl_pkcs7_encrypt
  • Example#945 - Ejemplo de openssl_pkcs7_sign
  • Example#946 - openssl_pkey_derive example
  • Example#947 - Ejemplo de openssl_random_pseudo_bytes
  • Example#948 - Ejemplo de openssl_seal
  • Example#949 - Ejemplo de openssl_sign
  • Example#950 - Ejemplo de openssl_sign
  • Example#951 - Ejemplo de openssl_spki_export_challenge
  • Example#952 - Ejemplo de openssl_spki_export_challenge desde <keygen>
  • Example#953 - openssl_spki_export example
  • Example#954 - openssl_spki_export example from <keygen>
  • Example#955 - openssl_spki_new example
  • Example#956 - openssl_spki_verify example
  • Example#957 - openssl_spki_verify example from <keygen>
  • Example#958 - Ejemplo de openssl_verify
  • Example#959 - openssl_verify example
  • Example#960 - openssl_x509_verify example
  • Example#961 - Basic password usage
  • Example#962 - Ejemplo de password_hash
  • Example#963 - Ejemplo de password_hash estableciendo el coste manualmente
  • Example#964 - Ejemplo de password_hash estableciendo la sal manualmente
  • Example#965 - Ejemplo de password_hash buscando un buen coste
  • Example#966 - Empleo de password_needs_rehash
  • Example#967 - Ejemplo de password_verify
  • Example#968 - sodium_crypto_kx_keypair usage
  • Example#969 - password_hash example
  • Example#970 - password_hash example
  • Example#971 - Ejemplo de DBA
  • Example#972 - Atravesar una base de datos
  • Example#973 - Ejemplo de dba_handlers
  • Example#974 - Conexiones sin DSN
  • Example#975 - Ejemplo de odbc_execute y odbc_prepare
  • Example#976 - Ejemplos de odbc_fetch_into
  • Example#977 - odbc_next_result
  • Example#978 - Ejemplo de odbc_execute y odbc_prepare
  • Example#979 - Ejemplos de odbc_result
  • Example#980 - Ejemplos de odbc_setoption
  • Example#981 - Uso de PDO::ATTR_DRIVER_NAME
  • Example#982 - Conectarse a MySQL
  • Example#983 - Manejo de errores de conexión
  • Example#984 - Cerrar una conexión
  • Example#985 - Conexiones persistentes
  • Example#986 - Ejecución de un lote en una transacción
  • Example#987 - Inserciones repetidas utilizando sentencias preparadas
  • Example#988 - Inserciones repetidas utilizando sentencias preparadas
  • Example#989 - Obtener datos empleando sentencias preparadas
  • Example#990 - Llamar a un procedimiento almacenado con un parámetro de salida
  • Example#991 - Llamar a un procedimiento almacenado con un parámetro de entrada/salida
  • Example#992 - Uso inválido de un marcador de posición
  • Example#993 - Crear una instancia de PDO y establecer el modo de error
  • Example#994 - Crear una instancia de PDO y establecer el modo de error desde el constructor
  • Example#995 - Mostrar una imagen desde una base de datos
  • Example#996 - Insertar una imagen en una base de datos
  • Example#997 - Insertar una imagen en una base de datos: Oracle
  • Example#998 - Revertir una transacción
  • Example#999 - Consignar una transacción básica
  • Example#1000 - Consignar una transacción DDL
  • Example#1001 - Crear una instancia PDO a través de una invocación al controlador
  • Example#1002 - Crear una instancia PDO a través de una invocación a la URI
  • Example#1003 - Crear una instancia de PDO usando un alias
  • Example#1004 - Recuperación de un código SQLSTATE
  • Example#1005 - Muestra los campos de errorInfo() para una conexión PDO_ODBC a una base de datos DB2
  • Example#1006 - Ejecutando una sentencia DELETE
  • Example#1007 - Obtiene los atributos de la conexión a la base de datos
  • Example#1008 - Un ejemplo de PDO::getAvailableDrivers
  • Example#1009 - Prepara una sentencia SQL con parámetros de sustitución nombrados
  • Example#1010 - Prepara una sentencia SQL con parámetros de signos de interrogación
  • Example#1011 - Demostración de PDO::query
  • Example#1012 - Entrecomillar una cadena de caracteres normal
  • Example#1013 - Entrecomillar una cadena peligrosa
  • Example#1014 - Entrecomillar una cadena compleja
  • Example#1015 - Revertir una transacción
  • Example#1016 - Vincular la salida de un conjunto de resultados a variables de PHP
  • Example#1017 - Ejecutar una sentencia preparada con parámetros de sustitución con nombre
  • Example#1018 - Ejecutar una sentencia preparada con parámetros de sustitución de signos de interrogación
  • Example#1019 - Llamar a un procedimiento almacenado con un parámetro INOUT
  • Example#1020 - Ejecutar una sentencia preparada con parámetros de sustitución con nombre
  • Example#1021 - Ejecutar una sentencia preparada con parámetros de sustitución de signos de interrogación
  • Example#1022 - Un ejemplo de PDOStatement::closeCursor
  • Example#1023 - Contar columnas
  • Example#1024 - Ejemplo de PDOStatement::debugDumpParams con parámetros con nombre
  • Example#1025 - Ejemplo de PDOStatement::debugDumpParams con parámetros sin nombre
  • Example#1026 - Recuperar un código SQLSTATE
  • Example#1027 - Mostrar los campos de errorInfo() para una conexión PDO_ODBC a una base de datos de DB2
  • Example#1028 - Ejecutar una sentencia preparada con una variable y valor vinculados
  • Example#1029 - Ejecutar una sentencia preparada con un array de valores de inserción (parámetros con nombre)
  • Example#1030 - Ejecutar una sentencia preparada con un array de valores de inserción (parámetros de sustitución)
  • Example#1031 - Ejecutar una sentencia preparada con parámetros de sustitución de signos de interrogación
  • Example#1032 - Ejecutar una sentencia preparada usando un array para la cláusula IN
  • Example#1033 - Obtención de filas usando diferentes tipos de obtención
  • Example#1034 - Obtener filas con un cursor desplazable
  • Example#1035 - Orden de construcción
  • Example#1036 - Obtener todas las filas restantes de un conjunto de resultados
  • Example#1037 - Obtener todos los valores de una única columna de un conjunto de resultados
  • Example#1038 - Agrupar todos los valores según una única columna
  • Example#1039 - Instanciar una clase para cada resultado
  • Example#1040 - Invocar a una función por cada resultado
  • Example#1041 - Devolver la primera columna de la siguiente fila
  • Example#1042 - Recuperar metadatos de una columna
  • Example#1043 - Obtener múltiples conjuntos de filas devueltas por un procedimiento almacenado
  • Example#1044 - Devolver el número de filas eliminadas
  • Example#1045 - Contar las filas devueltas por una sentencia SELECT
  • Example#1046 - Establece el modo de obtención
  • Example#1047 - Insertar LOBs en CUBRID PDO
  • Example#1048 - Obtener LOBs en CUBRID PDO
  • Example#1049 - Insertar un conjunto en CUBRID PDO con el tipo de datos predeterminado.
  • Example#1050 - Especificar un tipo de datos al insertar un conjunto en CUBRID PDO
  • Example#1051 - Ejemplos de DSN de PDO_CUBRID
  • Example#1052 - Un ejemplo de PDO::cubrid_schema
  • Example#1053 - PDO_DBLIB DSN examples
  • Example#1054 - Ejemplo de DSN de PDO_FIREBIRD DSN con ruta
  • Example#1055 - Ejemplo de DSN de PDO_FIREBIRD DSN con puerto y ruta
  • Example#1056 - Ejemplo de DSN de PDO_FIREBIRD con localhost y ruta hacia empleado.fdb en un sistema Debian
  • Example#1057 - Ejemplo de DSN de PDO_IBM DSN usando db2cli.ini
  • Example#1058 - Ejemplo de DSN de PDO_IBM usando una cadena de conexión
  • Example#1059 - Ejemplo de DSN de PDO_INFORMIX usando odbc.ini
  • Example#1060 - Ejemplo de DSN de PDO_INFORMIX usando una cadena de conexión
  • Example#1061 - Forzar consultas para que sean guardadas en el búfer en mysql
  • Example#1062 - Establecer el juego de caracteres de la conexión a UTF-8, antes de PHP 5.3.6
  • Example#1063 - ejemplos PDO_MYSQL DSN
  • Example#1064 - Ejemplos de DSN de PDO_SQLSRV
  • Example#1065 - Ejemplos del DSN de PDO_OCI
  • Example#1066 - Ejemplo de DSN de PDO_ODBC (administrador de controladores de ODBC)
  • Example#1067 - Ejemplo de DSN de PDO_ODBC (conexión no catalogada de IBM DB2)
  • Example#1068 - Ejemplo de DSN de PDO_ODBC (conexión no catalogada de Microsoft Access)
  • Example#1069 - Ejemplos de DSN de PDO_PGSQL
  • Example#1070 - Un ejemplo de PDO::pgsqlLOBCreate
  • Example#1071 - Un ejemplo de PDO::pgsqlLOBOpen
  • Example#1072 - Un ejemplo de PDO::pgsqlLOBUnlink
  • Example#1073 - Ejemplos de PDO_SQLITE DSN
  • Example#1074 - Ejemplo de función acumuladora max_length
  • Example#1075 - Ejemplo de PDO::sqliteCreateCollation
  • Example#1076 - Ejemplo de PDO::sqliteCreateFunction
  • Example#1077 - Ejemplo de Recuperación de Datos
  • Example#1078 - Ejemplo de Inserción de Datos
  • Example#1079 - Ejemplo de cubrid_bind
  • Example#1080 - Ejemplo de BLOB/CLOB de cubrid_bind
  • Example#1081 - Ejemplo de BLOB/CLOB de cubrid_bind
  • Example#1082 - Ejemplo de cubrid_close_prepare
  • Example#1083 - Ejemplo de cubrid_close_request
  • Example#1084 - Ejemplo de cubrid_col_get
  • Example#1085 - Ejemplo de cubrid_col_size
  • Example#1086 - Ejemplo de cubrid_column_names
  • Example#1087 - Ejemplo de cubrid_column_types
  • Example#1088 - Ejemplo de cubrid_commit
  • Example#1089 - Ejemplo de cubrid_connect_with_url, url sin propiedades
  • Example#1090 - Ejemplo de cubrid_connect_with_url, url con propiedades
  • Example#1091 - Ejemplo de cubrid_connect
  • Example#1092 - Ejemplo de cubrid_current_oid
  • Example#1093 - Ejemplo de cubrid_disconnect
  • Example#1094 - Ejemplo de cubrid_drop
  • Example#1095 - Ejemplo de cubrid_error_code_facility
  • Example#1096 - Ejemplo de cubrid_error_code
  • Example#1097 - Ejemplo de cubrid_error_msg
  • Example#1098 - Ejemplo de cubrid_execute
  • Example#1099 - Ejemplo de cubrid_fetch
  • Example#1100 - Ejemplo de cubrid_free_result
  • Example#1101 - Ejemplo de cubrid_get_charset
  • Example#1102 - Ejemplo de cubrid_get_class_name
  • Example#1103 - Ejemplo de cubrid_get_client_info
  • Example#1104 - Ejemplo de cubrid_get_db_parameter
  • Example#1105 - Ejemplo de cubrid_get_query_timeout
  • Example#1106 - Ejemplo de cubrid_get_server_info
  • Example#1107 - Ejemplo de cubrid_get
  • Example#1108 - Ejemplo de cubrid_insert_id
  • Example#1109 - Ejemplo de cubrid_is_instance
  • Example#1110 - Ejemplo de cubrid_lob_close
  • Example#1111 - Ejemplo de cubrid_lob_export
  • Example#1112 - Ejemplo de cubrid_lob_get
  • Example#1113 - Ejemplo de cubrid_lob_send
  • Example#1114 - Ejemplo de cubrid_lob_size
  • Example#1115 - Ejemplo de cubrid_lob2_bind
  • Example#1116 - Ejemplo de cubrid_lob2_export
  • Example#1117 - Ejemplo de cubrid_lob2_export
  • Example#1118 - Ejemplo 1 de cubrid_lob2_read
  • Example#1119 - Ejemplo 2 cubrid_lob2_read
  • Example#1120 - Ejemplo de cubrid_lob2_seek64
  • Example#1121 - Ejemplo de cubrid_lob2_seek
  • Example#1122 - Ejemplo 1 de cubrid_lob2_write
  • Example#1123 - Ejemplo 2 de cubrid_lob2_write
  • Example#1124 - Ejemplo de cubrid_lock_read
  • Example#1125 - Ejemplo de cubrid_lock_write
  • Example#1126 - Ejemplo de cubrid_move_cursor
  • Example#1127 - cubrid_next_result ejemplo
  • Example#1128 - Ejemplo de cubrid_num_cols
  • Example#1129 - Ejemplo de cubrid_num_rows
  • Example#1130 - Ejemplo de url de cubrid_pconnect_with_url sin propiedades
  • Example#1131 - Ejemplo de url de cubrid_pconnect_with_url con propiedades
  • Example#1132 - Ejemplo de cubrid_pconnect
  • Example#1133 - Ejemplo de cubrid_prepare
  • Example#1134 - Ejemplo de cubrid_put
  • Example#1135 - Ejemplo de cubrid_rollback
  • Example#1136 - Ejemplo de cubrid_schema
  • Example#1137 - Ejemplo de cubrid_seq_drop
  • Example#1138 - Ejemplo de cubrid_seq_insert
  • Example#1139 - Ejemplo de cubrid_seq_put
  • Example#1140 - Ejemplo de cubrid_set_add
  • Example#1141 - Ejemplo de cubrid_get_db_parameter
  • Example#1142 - Ejemplo de cubrid_set_drop
  • Example#1143 - Ejemplo de cubrid_version
  • Example#1144 - Ejemplo de cubrid_affected_rows
  • Example#1145 - Ejemplo de cubrid_client_encoding
  • Example#1146 - Ejemplo de cubrid_close
  • Example#1147 - Ejemplo de cubrid_data_seek
  • Example#1148 - Ejemplo de cubrid_db_name
  • Example#1149 - Ejemplo de cubrid_errno
  • Example#1150 - Ejemplo de cubrid_error
  • Example#1151 - Ejemplo de cubrid_fetch_array
  • Example#1152 - Ejemplo de cubrid_fetch_assoc
  • Example#1153 - Ejemplo de cubrid_fetch_field
  • Example#1154 - Ejemplo de cubrid_fetch_lengths
  • Example#1155 - Ejemplo de cubrid_fetch_object
  • Example#1156 - Ejemplo de cubrid_fetch_row
  • Example#1157 - Ejemplo de cubrid_field_flags
  • Example#1158 - Ejemplo de cubrid_field_len
  • Example#1159 - Ejemplo de cubrid_field_name
  • Example#1160 - Ejemplo de cubrid_field_seek
  • Example#1161 - Ejemplo de cubrid_field_table
  • Example#1162 - Ejemplo de cubrid_field_type
  • Example#1163 - Ejemplo de cubrid_list_dbs
  • Example#1164 - Ejemplo de cubrid_num_fields
  • Example#1165 - Ejemplo de cubrid_ping
  • Example#1166 - Consulta No Válida
  • Example#1167 - Consulta Válida
  • Example#1168 - Ejemplo de cubrid_real_escape_string
  • Example#1169 - Ejemplo de cubrid_result
  • Example#1170 - Ejemplo de cubrid_unbuffered_query
  • Example#1171 - Ejemplo de cubrid_load_from_glo
  • Example#1172 - Ejemplo de cubrid_new_glo
  • Example#1173 - Ejemplo de cubrid_save_to_glo
  • Example#1174 - Ejemplo de cubrid_send_glo
  • Example#1175 - Insertar un registro en una base de datos dBase
  • Example#1176 - Cerrar un archivo de base de datos de dBase
  • Example#1177 - Crear un archivo de base de datos dBase
  • Example#1178 - Mostrar la información de cabecera de un archivo de base de datos dBase
  • Example#1179 - Listar todos los miembros registrados en la base de datos
  • Example#1180 - Ejemplo de dbase_numfields
  • Example#1181 - Recorrer todos los registros de la base de datos
  • Example#1182 - Abrir un archivo de base de datos de dBase
  • Example#1183 - Vaciar una base de datos dBase
  • Example#1184 - Actualizar un registro en la base de datos
  • Example#1185 - Ejemplo de ibase_blob_get
  • Example#1186 - Ejemplo de ibase_blob_import
  • Example#1187 - Ejemplo de ibase_connect
  • Example#1188 - Ejemplo de ibase_execute
  • Example#1189 - Ejemplo de ibase_fetch_object
  • Example#1190 - Ejemplo de ibase_field_info
  • Example#1191 - Ejemplo de ibase_name_result
  • Example#1192 - Ejemplo de ibase_num_fields
  • Example#1193 - Ejemplo de ibase_query
  • Example#1194 - Ejemplo de ibase_set_event_handler
  • Example#1195 - Ejemplo de fbsql_close
  • Example#1196 - Ejemplo de fbsql_connect
  • Example#1197 - Ejemplo de fbsql_create_blob
  • Example#1198 - fbsql_create_clob example
  • Example#1199 - Ejemplo de fbsql_create_db.
  • Example#1200 - fbsql_data_seek example
  • Example#1201 - Ejemplo de fbsql_database_password
  • Example#1202 - Ejemplo de fbsql_errno
  • Example#1203 - Ejemplo de fbsql_error
  • Example#1204 - Ejemplo de fbsql_fetch_array
  • Example#1205 - fbsql_fetch_assoc example
  • Example#1206 - Ejemplo de fbsql_fetch_field
  • Example#1207 - Ejemplo de fbsql_fetch_object
  • Example#1208 - Ejemplo de fbsql_field_name
  • Example#1209 - Ejemplo de fbsql_field_type
  • Example#1210 - Ejemplo de fbsql_list_dbs
  • Example#1211 - fbsql_list_fields example
  • Example#1212 - fbsql_next_result ejemplo
  • Example#1213 - Ejemplo de fbsql_num_rows
  • Example#1214 - Ejemplo fbsql_query
  • Example#1215 - Ejemplo fbsql_query
  • Example#1216 - Ejemplo de fbsql_read_blob
  • Example#1217 - Ejemplo de fbsql_read_clob
  • Example#1218 - Ejemplo de fbsql_table_name
  • Example#1219 - Consultando el valor de AUTOCOMMIT de una conexión
  • Example#1220 - Asignando el valor de AUTOCOMMIT en una conexión
  • Example#1221 - Vinculando variables PHP a sentencias preparadas
  • Example#1222 - Llamada a procedimientos almacenados con parámetros de Entrada y Salida
  • Example#1223 - Insertando un objeto extenso binario (BLOB) directamente desde un fichero
  • Example#1224 - Ejemplo de db2_client_info
  • Example#1225 - Cierre de una conexión
  • Example#1226 - Extrayendo el valor SQLSTATE de un intento de conexión fallido
  • Example#1227 - Extrayendo el mensaje de error devuelto por un intento de conexión fallido
  • Example#1228 - Creando una conexión catalogada
  • Example#1229 - Creando una conexión no catalogada
  • Example#1230 - Creando una conexión con confirmaciones automáticas de transacciones deshabilitadas
  • Example#1231 - Optimizando en i5/OS
  • Example#1232 - Usando contexto de confianza
  • Example#1233 - Ejemplo de db2_escape_string
  • Example#1234 - Creando una tabla con db2_exec
  • Example#1235 - Ejecutando una sentencia SELECT con cursor de tipo SCROLLABLE
  • Example#1236 - Devolviendo datos XML como resultado
  • Example#1237 - Ejecutando un JOIN con datos XML
  • Example#1238 - Devolviendo datos SQL como parte de un documento XML extenso
  • Example#1239 - Preparando y ejecutando una sentencia SQL con marcadores de parámetros
  • Example#1240 - Llamando a un procedimiento almacenado con un parámetro OUT
  • Example#1241 - Devolviendo datos XML como resultado SQL
  • Example#1242 - Ejecutando un "JOIN" con datos XML
  • Example#1243 - Devolviendo datos SQL como parte un documento XML más extenso
  • Example#1244 - Iterando a través de un cursor de no-recorrido (sólo hacia adelante)
  • Example#1245 - Extrayendo filas específicas con db2_fetch_array con un cursor de recorrido
  • Example#1246 - Iterando a través de un cursor de no-recorrido (sólo hacia adelante)
  • Example#1247 - Extrayendo filas específicas con db2_fetch_assoc a partir de un cursor de recorrido
  • Example#1248 - Iterando a través de un cursor de no-recorrido (sólo hacia adelante)
  • Example#1249 - Extrayendo filas específicas con db2_fetch_both a partir de un cursor de recorrido
  • Example#1250 - Ejemplo de db2_fetch_object
  • Example#1251 - Iterando a través de un bloque de resultados
  • Example#1252 - Alternativas recomendadas para db2_fetch_row/db2_result en i5/OS
  • Example#1253 - Estableciendo y extrayendo parámetros a través de una conexión
  • Example#1254 - Ejemplo de db2_last_insert_id
  • Example#1255 - Iterando a través de diferentes tipos de datos
  • Example#1256 - Llamando a un procedimiento almacenado que devuelve múltiples resultados
  • Example#1257 - Extrayendo el número de campos de un resultado
  • Example#1258 - Cerrando una conexión persistente
  • Example#1259 - Ejemplo de db2_pconnect
  • Example#1260 - Utilizando contexto de confianza
  • Example#1261 - Preparando y ejecutando un comando SQL con marcadores de parámetros.
  • Example#1262 - Ejemplo de db2_result
  • Example#1263 - Cancelando una sentencia DELETE
  • Example#1264 - A db2_server_info example
  • Example#1265 - Setting one parameter with a connection resource
  • Example#1266 - Setting multiple parameters with a connection resource
  • Example#1267 - Setting multiple parameters with an invalid key
  • Example#1268 - Setting multiple parameters with an invalid value
  • Example#1269 - Setting multiple parameters with a connection resource and the wrong type
  • Example#1270 - Setting multiple parameters with the wrong resource
  • Example#1271 - Putting it all together
  • Example#1272 - i5/OS cursors are read-only
  • Example#1273 - Ejemplo de uso de PassEnv para Ingres
  • Example#1274 - Simple Ingres Example
  • Example#1275 - ingres_charset - Obtener el conjunto de caracteres de la instalación
  • Example#1276 - Abrir una conexión a un base de datos de Ingres
  • Example#1277 - Obtener el nombre del cursor para un recurso de consultas
  • Example#1278 - Obtener el númeor del último error generado de Ingres
  • Example#1279 - Obtener un mensaje del último error generado
  • Example#1280 - Obtener el código del último error SQLSTATE generado
  • Example#1281 - Escape special characters for use in a query
  • Example#1282 - Obtener una fila de resultados en un array
  • Example#1283 - Obtener una fila en un array asociativo
  • Example#1284 - Obtener una fila en un objeto
  • Example#1285 - Obtener el valor de retorno de una llamada a un procedimiento
  • Example#1286 - Obttener una fila de resultados en un array enumerado
  • Example#1287 - Liberar un recurso de resultados
  • Example#1288 - Enviar un simple select
  • Example#1289 - Pasar parámetros de consulta a ingres_query
  • Example#1290 - Insertar datos BLOB con tipos de parámetros
  • Example#1291 - Posicionar el cursor a la 3ª fila
  • Example#1292 - Establecer el formato de fecha a ISO4
  • Example#1293 - Set timezone to HONG-KONG
  • Example#1294 - Ejecutar un SELECT sencillo no almacenado en búfer
  • Example#1295 - Passing query parameters to ingres_unbuffered_query
  • Example#1296 - Insertar datos BLOB con tipos de parámetros
  • Example#1297 -
  • Example#1298 -
  • Example#1299 -
  • Example#1300 -
  • Example#1301 -
  • Example#1302 -
  • Example#1303 -
  • Example#1304 -
  • Example#1305 -
  • Example#1306 -
  • Example#1307 -
  • Example#1308 -
  • Example#1309 -
  • Example#1310 -
  • Example#1311 -
  • Example#1312 - Preferencias de lectura de URI de coneción con sintaxis de cadena de consulta
  • Example#1313 - Establecer las preferencias de lectura con sintaxis de array para conjuntos de etiquetas
  • Example#1314 - Pasar un WriteConcern a una operación de escritura
  • Example#1315 - WriteConcerns en cadena de conexión
  • Example#1316 - MongoDB::setWriteConcern y MongoCollection::setWriteConcern
  • Example#1317 - Asunto de escritura no reconocido, seguido de una escritura reconocida
  • Example#1318 - Escrituras reconocidas
  • Example#1319 - Escritura reconocida por la mayoría
  • Example#1320 - Escritura reconocida y esctrita en el diario
  • Example#1321 - Conectar a una instancia de MongoDB con encriptación SSL
  • Example#1322 - Conectar a una instancia de MongoDB con encriptación SSL, verificando que es quien se espera
  • Example#1323 - Conectar a una instancia de MongoDB que requiera certificados cliente
  • Example#1324 - Autenticación con certificados X.509
  • Example#1325 - Autenticación en la base de datos "admin"
  • Example#1326 - Autenticación en bases de datos normales
  • Example#1327 - Lista de semillas de ReplicaSet
  • Example#1328 - Duplicación errónea de un nombre de un conjunto de réplica
  • Example#1329 - Uso correcto de dos nombres de conjuntos de réplica
  • Example#1330 -
  • Example#1331 -
  • Example#1332 -
  • Example#1333 -
  • Example#1334 -
  • Example#1335 -
  • Example#1336 - Herencia de las preferencias de lectura del nivel de la base de datos hacia el cursor
  • Example#1337 -
  • Example#1338 -
  • Example#1339 -
  • Example#1340 -
  • Example#1341 -
  • Example#1342 -
  • Example#1343 -
  • Example#1344 - Uso básido de MongoClient
  • Example#1345 - Ejemplo de MongoClient::close
  • Example#1346 - Ejemplo de conjunto de réplica con MongoClient::__construct
  • Example#1347 - Conectarse a un socket de dominio
  • Example#1348 - Ejemplo de autenticación con MongoClient::__construct
  • Example#1349 - Ejemplo de preferencia de lectura con MongoClient::__construct
  • Example#1350 - Ejemplo de opciones de MongoClient::__construct
  • Example#1351 - Ejemplo de preferencia de lectura de MongoClient::__construct
  • Example#1352 - Ejemplo de MongoClient::getConnections
  • Example#1353 - Ejemplo de valor devuelto por MongoClient::getReadPreference
  • Example#1354 - Ejemplo del valor devuelto por MongoClient::getWriteConcern
  • Example#1355 - Ejemplo de MongoClient::killCursor
  • Example#1356 - Ejemplo de MongoClient::listDBs
  • Example#1357 - Ejemplo de MongoClient::selectCollection
  • Example#1358 - Ejemplo de sintaxis de array de conjunto de etiquetas con MongoClient::setReadPreference
  • Example#1359 - Ejemplo de MongoClient::setWriteConcern
  • Example#1360 - Seleccionar una base de datos
  • Example#1361 - Ejemplo de MongoDB::command con "distinct"
  • Example#1362 - Ejemplo de MongoDB::command con "distinct"
  • Example#1363 - Ejemplo de MongoDB::command con MapReduce
  • Example#1364 - Ejemplo de MongoDB::command con "geoNear"
  • Example#1365 - Ejemplo de MongoDB::createCollection para colección de tamaño fijo
  • Example#1366 - Ejemplo de MongoDB::createDBRef
  • Example#1367 - Ejemplo de MongoDB::createDBRef
  • Example#1368 - Ejemplo de MongoDB::drop
  • Example#1369 - Ejemplo sencillo de MongoDB::execute
  • Example#1370 - Ejemplo de parámetros en MongoDB::execute
  • Example#1371 - Ejemplo de ámbito
  • Example#1372 - Ejemplo de MongoDB::getCollectionInfo
  • Example#1373 - Ejemplo de MongoDB::getCollectionNames
  • Example#1374 - Ejemplo de MongoDB::getDBRef
  • Example#1375 - Ejemplo de MongoDB::getGridFS
  • Example#1376 - Ejemplo de valor devuelto de MongoDB::getReadPreference
  • Example#1377 - Ejemplo del valor devuelto por MongoDB::getWriteConcern
  • Example#1378 - Ejemplo de error null de MongoDB::lastError
  • Example#1379 - Ejemplo de error de clave duplicada con MongoDB::lastError
  • Example#1380 - Ejemplo de MongoDB::listCollections
  • Example#1381 - Ejemplo de MongoDB::repair
  • Example#1382 - Ejemplo de sintaxis de array de conjunto de etiquetas con MongoDB::setReadPreference
  • Example#1383 - Ejemplo de MongoDB::setWriteConcern
  • Example#1384 - Ejemplo de MongoCollection::aggregate
  • Example#1385 - Ejemplo de MongoCollection::aggregate
  • Example#1386 - Ejemplo de MongoCollection::aggregate
  • Example#1387 - MongoCollection::aggregate con opciones de comandos
  • Example#1388 - Ejemplo de MongoCollection::aggregateCursor
  • Example#1389 - Ejemplo de MongoCollection::aggregateCursor con un tamaño inicial de lote diferente
  • Example#1390 - Ejemplo de MongoCollection::batchInsert
  • Example#1391 - Ejemplo de MongoCollection::batchInsert ignorando errores
  • Example#1392 - Ejemplo de MongoCollection::count
  • Example#1393 - Ejemplo de MongoCollection::createDBRef
  • Example#1394 - Ejemplo de MongoCollection::ensureIndex
  • Example#1395 - Indexación geoespacial
  • Example#1396 - Ejemplo de eliminación de duplicados
  • Example#1397 - Ejemplo de MongoCollection::deleteIndex
  • Example#1398 - Ejemplo de MongoCollection::deleteIndexes
  • Example#1399 - Ejemplo de MongoCollection::distinct
  • Example#1400 - Ejemplo de MongoCollection::distinct sobre un documento embebido
  • Example#1401 - MongoCollection::drop example
  • Example#1402 - Ejemplo de MongoCollection::ensureIndex
  • Example#1403 - Indexación geoespacial
  • Example#1404 - Ejemplo de eliminación de duplicados
  • Example#1405 - Ejemplo de MongoCollection::find
  • Example#1406 - Ejemplo de MongoCollection::find
  • Example#1407 - Ejemplo de MongoCollection::find usando $where
  • Example#1408 - Ejemplo de MongoCollection::find usando $in
  • Example#1409 - Obtener resultados en forma de array
  • Example#1410 - Ejemplo de MongoCollection::findAndModify
  • Example#1411 - Manejo de errores de MongoCollection::findAndModify
  • Example#1412 - Ejemplo de MongoCollection::findOne buscando por id.
  • Example#1413 - Ejemplo de MongoCollection::findOne a partir de una condición.
  • Example#1414 - Ejemplo de MongoCollection::getDBRef
  • Example#1415 - Ejemplo de MongoCollection::getIndexInfo
  • Example#1416 - Ejemplo de MongoCollection::getName
  • Example#1417 - Ejemplo de valor devueto por MongoCollection::getReadPreference
  • Example#1418 - Ejemplo del valor devuelto por MongoCollection::getWriteConcern
  • Example#1419 - Ejemplo de MongoCollection::group
  • Example#1420 - Ejemplo de MongoCollection::group
  • Example#1421 - Pasar una función a keys
  • Example#1422 - Ejemplo de MongoCollection::insert con _id
  • Example#1423 - Ejemplo de escritura aceptada con MongoCollection::insert
  • Example#1424 - Ejmplo de MongoCollection::parallelCollectionScan
  • Example#1425 - Ejemplo de MongoCollection::remove con justOne
  • Example#1426 - Ejemplo de MongoCollection::save
  • Example#1427 - Ejemplo de sintaxis de array de conjunto de etiquetas con MongoCollection::setReadPreference
  • Example#1428 - Ejemplo de MongoDB::setWriteConcern
  • Example#1429 - Ejemplo de MongoCollection::toIndexString
  • Example#1430 - Ejemplo de MongoCollection::__toString
  • Example#1431 - MongoCollection::update
  • Example#1432 - Ejemplos de MongoCollection::update con upsert
  • Example#1433 - Ejemplo de múltiples MongoCollection::update
  • Example#1434 - Uso básico de MongoCursor
  • Example#1435 - Iterar sobre MongoCursor
  • Example#1436 - Añadir opciones a MongoCursor
  • Example#1437 - Ejemplo para añadir un comentario con MongoCursor::addOption
  • Example#1438 - Ejemplo de MongoCursor::addOption
  • Example#1439 - Ejemplo de MongoCursor::awaitData
  • Example#1440 - MongoCursor::batchSize y combinaciones con MongoCursor::limit
  • Example#1441 - Ejemplo de MongoCursor::count
  • Example#1442 - Ejemplo de MongoCursor::doQuery
  • Example#1443 - Ejemplo de MongoCursor::explain
  • Example#1444 - Ejemplo de valor devuelto de MongoCursor::getReadPreference
  • Example#1445 - Ejemplo de MongoCursor::info
  • Example#1446 - Ejemplo de MongoCursor::maxTimeMS
  • Example#1447 - Ejemplo de MongoCursor::setFlag
  • Example#1448 - Ejemplo de sintaxis de array de conjunto de etiquetas con MongoCursor::setReadPreference
  • Example#1449 - Ejemplo de MongoCursor::slaveOkay
  • Example#1450 - Ejemplo de MongoCursor::sort
  • Example#1451 - Ejemplo de MongoCursor::tailable
  • Example#1452 - Ejemplo de MongoCursor::timeout
  • Example#1453 - Añadir opciones a MongoCommandCursor
  • Example#1454 - MongoCommandCursor::batchSize
  • Example#1455 - Ejemplo de MongoCommandCursor
  • Example#1456 - MongoCommandCursor::createFromDocument
  • Example#1457 - Ejemplo de valor devuelto por MongoCommandCursor::getReadPreference
  • Example#1458 - Ejemplo de MongoCommandCursor::info
  • Example#1459 - MongoCommandCursor::rewind
  • Example#1460 - Ejemplo de sintaxis de array de conjunto de etiquetas de MongoCommandCursor::setReadPreference
  • Example#1461 - Ejemplo de MongoCommandCursor::timeout
  • Example#1462 - MongoId::__construct example
  • Example#1463 - Ejemplo con parámetros
  • Example#1464 - Ejemplo de MongoId::__toString
  • Example#1465 - Ejemplo de MongoCode::__construct
  • Example#1466 - Usando MongoCode con $where
  • Example#1467 - Ejemplo de MongoCode::__toString
  • Example#1468 - Almacenar datos con MongoDate
  • Example#1469 - Ejemplo de MongoDate::__construct
  • Example#1470 - Ejemplo de MongoDate::toDateTime
  • Example#1471 - Patrón de una expresión regular
  • Example#1472 - Ejemplo de MongoRegex::__construct
  • Example#1473 - Ejemplo de MongoRegex::__toString
  • Example#1474 -
  • Example#1475 - Vincular documentos
  • Example#1476 - Crear vínculos MongoDBRef
  • Example#1477 - Ejemplo de MongoDBRef::create
  • Example#1478 - Ejemplo de MongoCollection::createDBRef
  • Example#1479 - Ejemplo de MongoGridFS::findOne
  • Example#1480 - MongoGridFS::storeBytes com metadatos adicionales
  • Example#1481 - MongoGridFS::storeFile con metadatos adicionales
  • Example#1482 - Ejemplo de forumulario HTML con MongoGridFS::storeUpload
  • Example#1483 - Ejemplo de MongoGridFSFile::getBytes
  • Example#1484 - Ejemplo de MongoGridFSFile::getResource
  • Example#1485 - Ejemplo de MongoGridFSFile::write
  • Example#1486 - Ejemplo de MongoWriteBatch
  • Example#1487 - Ejemplo de MongoWriteBatch::add
  • Example#1488 - Ejemplo de MongoWriteBatch::add
  • Example#1489 - Ejemplo de MongoWriteBatch::add
  • Example#1490 - Ejemplo de MongoWriteBatch::add
  • Example#1491 - Ejemplo de MongoWriteBatch::add
  • Example#1492 - Ejemplo de MongoWriteBatch::add
  • Example#1493 - Ejemplo de MongoLog::setCallback
  • Example#1494 - Cambiar el tamaño de un agrupamiento
  • Example#1495 - Ejemplo de Mongo::setPoolSize
  • Example#1496 - Cambiar el tamaño de la agrupación
  • Example#1497 - Ejemplo de Mongo::setPoolSize
  • Example#1498 - Ejemplo de MongoResultException::getDocument
  • Example#1499 - Capturar una MongoDuplicateKeyException
  • Example#1500 - Capturar una MongoProtocolException
  • Example#1501 - MongoDB\Driver\Manager::__construct basic example
  • Example#1502 - MongoDB\Driver\Manager::__construct basic examples
  • Example#1503 - MongoDB\Driver\Manager::executeBulkWrite example
  • Example#1504 - MongoDB\Driver\Manager::executeCommand with a command returning a single result document
  • Example#1505 - MongoDB\Driver\Manager::executeCommand with a command returning a cursor
  • Example#1506 - Limiting execution time for a command
  • Example#1507 - MongoDB\Driver\Manager::executeQuery example
  • Example#1508 - Limiting execution time for a query
  • Example#1509 - MongoDB\Driver\Manager::getReadConcern example
  • Example#1510 - MongoDB\Driver\Manager::getReadPreference example
  • Example#1511 - MongoDB\Driver\Manager::getServers example
  • Example#1512 - MongoDB\Driver\Manager::getWriteConcern example
  • Example#1513 - Composing MongoDB\Driver\Command to provide a helper to create collections
  • Example#1514 - MongoDB\Driver\Command::__construct example
  • Example#1515 - MongoDB\Driver\Command::__construct example
  • Example#1516 - MongoDB\Driver\Query::__construct example
  • Example#1517 - Mixed write operations are grouped by type
  • Example#1518 - Ordered write operations causing an error
  • Example#1519 - MongoDB\Driver\BulkWrite::__construct example
  • Example#1520 - MongoDB\Driver\BulkWrite::count example
  • Example#1521 - MongoDB\Driver\BulkWrite::delete example
  • Example#1522 - MongoDB\Driver\BulkWrite::insert example
  • Example#1523 - MongoDB\Driver\BulkWrite::update example
  • Example#1524 - MongoDB\Driver\WriteConcern::bsonSerialize with majority write concern
  • Example#1525 - MongoDB\Driver\WriteConcern::bsonSerialize with wtimeout and journal
  • Example#1526 - MongoDB\Driver\WriteConcern::__construct example
  • Example#1527 - MongoDB\Driver\WriteConcern::getJournal example
  • Example#1528 - MongoDB\Driver\WriteConcern::getW example
  • Example#1529 - MongoDB\Driver\WriteConcern::getWtimeout example
  • Example#1530 - MongoDB\Driver\WriteConcern::isDefault example
  • Example#1531 - MongoDB\Driver\ReadPreference::bsonSerialize with primary read preference
  • Example#1532 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and tag sets
  • Example#1533 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and max staleness
  • Example#1534 - MongoDB\Driver\ReadPreference::__construct example
  • Example#1535 - MongoDB\Driver\ReadPreference::getMaxStalenessSeconds example
  • Example#1536 - MongoDB\Driver\ReadPreference::getMode example
  • Example#1537 - MongoDB\Driver\ReadPreference::getModeString example
  • Example#1538 - MongoDB\Driver\ReadPreference::getTagSets example
  • Example#1539 - MongoDB\Driver\ReadConcern::bsonSerialize with empty read concern
  • Example#1540 - MongoDB\Driver\ReadConcern::bsonSerialize with local read concern
  • Example#1541 - MongoDB\Driver\ReadConcern::__construct example
  • Example#1542 - MongoDB\Driver\ReadConcern::getLevel example
  • Example#1543 - MongoDB\Driver\ReadConcern::isDefault example
  • Example#1544 - Reading a result set
  • Example#1545 - Reading a result set for a tailable cursor
  • Example#1546 - MongoDB\Driver\Cursor::getId example
  • Example#1547 - MongoDB\Driver\Cursor::getServer example
  • Example#1548 - MongoDB\Driver\Cursor::isDead example
  • Example#1549 - MongoDB\Driver\Cursor::setTypeMap example
  • Example#1550 - MongoDB\Driver\Cursor::toArray example
  • Example#1551 - MongoDB\Driver\CursorId::__toString example
  • Example#1552 - MongoDB\Driver\Server::getHost example
  • Example#1553 - MongoDB\Driver\Server::getInfo example
  • Example#1554 - MongoDB\Driver\Server::getLatency example
  • Example#1555 - MongoDB\Driver\Server::getPort example
  • Example#1556 - MongoDB\Driver\WriteConcernError::getCode example
  • Example#1557 - MongoDB\Driver\WriteConcernError::getInfo example
  • Example#1558 - MongoDB\Driver\WriteConcernError::getMessage example
  • Example#1559 - MongoDB\Driver\WriteError::getCode example
  • Example#1560 - MongoDB\Driver\WriteError::getIndex example
  • Example#1561 - MongoDB\Driver\WriteError::getMessage example
  • Example#1562 - MongoDB\Driver\WriteResult::getDeletedCount example
  • Example#1563 - MongoDB\Driver\WriteResult::getInsertedCount example
  • Example#1564 - MongoDB\Driver\WriteResult::getMatchedCount example
  • Example#1565 - MongoDB\Driver\WriteResult::getModifiedCount example
  • Example#1566 - MongoDB\Driver\WriteResult::getServer example
  • Example#1567 - MongoDB\Driver\WriteResult::getUpsertedCount example
  • Example#1568 - MongoDB\Driver\WriteResult::getUpsertedIds example
  • Example#1569 - MongoDB\Driver\WriteResult::getWriteConcernError example
  • Example#1570 - MongoDB\Driver\WriteResult::getWriteErrors with a single error
  • Example#1571 - MongoDB\Driver\WriteResult::getWriteErrors with multiple errors
  • Example#1572 - MongoDB\Driver\WriteResult::isAcknowledged with acknowledged write concern
  • Example#1573 - MongoDB\Driver\WriteResult::isAcknowledged with unacknowledged write concern
  • Example#1574 - MongoDB\BSON\fromJSON example
  • Example#1575 - MongoDB\BSON\fromPHP example
  • Example#1576 - MongoDB\BSON\toCanonicalExtendedJSON example
  • Example#1577 - MongoDB\BSON\toJSON example
  • Example#1578 - MongoDB\BSON\toPHP example
  • Example#1579 - MongoDB\BSON\toRelaxedExtendedJSON example
  • Example#1580 - MongoDB\BSON\Binary::__construct example
  • Example#1581 - MongoDB\BSON\Binary::getData example
  • Example#1582 - MongoDB\BSON\Binary::getType example
  • Example#1583 - MongoDB\BSON\Binary::__toString example
  • Example#1584 - MongoDB\BSON\Decimal128::__construct example
  • Example#1585 - MongoDB\BSON\Decimal128::__toString example
  • Example#1586 - MongoDB\BSON\Javascript::__construct example
  • Example#1587 - MongoDB\BSON\Javascript::getCode example
  • Example#1588 - MongoDB\BSON\Javascript::getScope example
  • Example#1589 - MongoDB\BSON\Javascript::__toString example
  • Example#1590 - MongoDB\BSON\MaxKey::__construct example
  • Example#1591 - MongoDB\BSON\MinKey::__construct example
  • Example#1592 - MongoDB\BSON\ObjectId::__construct example
  • Example#1593 - MongoDB\BSON\ObjectId::getTimestamp example
  • Example#1594 - MongoDB\BSON\ObjectId::__toString example
  • Example#1595 - MongoDB\BSON\Regex::__construct example
  • Example#1596 - MongoDB\BSON\Regex::getFlags example
  • Example#1597 - MongoDB\BSON\Regex::getPattern example
  • Example#1598 - MongoDB\BSON\Regex::__toString example
  • Example#1599 - MongoDB\BSON\Timestamp::__construct example
  • Example#1600 - MongoDB\BSON\Timestamp::__toString example
  • Example#1601 - MongoDB\BSON\UTCDateTime::__construct example
  • Example#1602 - MongoDB\BSON\UTCDatetime::toDateTime example
  • Example#1603 - MongoDB\BSON\UTCDateTime::__toString example
  • Example#1604 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for root document
  • Example#1605 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for root document
  • Example#1606 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for document field
  • Example#1607 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for document field
  • Example#1608 - MongoDB\BSON\Unserializable::bsonUnserialize example
  • Example#1609 - MongoDB\Driver\Exception\WriteException::getWriteResult example
  • Example#1610 - Comparación de las tres API de MySQL
  • Example#1611 - Comandos de configuración para usar mysqlnd o libmysqlclient
  • Example#1612 - Ejemplo de consulta no almacenada en buffer: mysqli
  • Example#1613 - Ejemplo de consulta no almacenada en buffer: pdo_mysql
  • Example#1614 - Ejemplo de consulta no almacenada en buffer: mysql
  • Example#1615 - Problemas al establecer el conjunto de caracteres con SQL
  • Example#1616 - Ejemplo para establecer el conjunto de caracteres: mysqli
  • Example#1617 - Ejemplo para establecer el conjunto de caracteres: pdo_mysql
  • Example#1618 - Ejemplo para establecer el conjunto de caracteres: mysql
  • Example#1619 - Migración sencilla desde la antigua extensión mysql
  • Example#1620 - Interfaz orientada a objetos y procedimental
  • Example#1621 - Estilo de codificación malo
  • Example#1622 - Significado especial de localhost
  • Example#1623 - Configuración predeterminada
  • Example#1624 - Conectando a MySQL
  • Example#1625 - Navegación a través de resultados almacenados en buffer
  • Example#1626 - Navegación a través de resultados no almacenados en buffer
  • Example#1627 - El protocolo de texto devuelve cadenas de manera predeterminado
  • Example#1628 - Tipos de datos nativos con mysqlnd y la opción de conexión
  • Example#1629 - Primera etapa: prepación
  • Example#1630 - Segunda etapa: vincular y ejecutar
  • Example#1631 - INSERT preparada una vez, ejecutada múltiples veces
  • Example#1632 - Menos viajes de ida y vuelta usando SQL multi-INSERT
  • Example#1633 - Tipos de datos nativos
  • Example#1634 - Vinculación de variables de salida
  • Example#1635 - Usar mysqli_result para obtener los resultados
  • Example#1636 - Conjunto de resultados almacenado en buffer para la lectura flexible
  • Example#1637 - Llamar a un procedimiento almacenado
  • Example#1638 - Usar variables de sesión
  • Example#1639 - Obtener los resultados de procedimientos almacenados
  • Example#1640 - Procedimientos Almacenados y Sentencias Preparadas
  • Example#1641 - Procedimientos Almacenados y Sentencias Preparadas usando la API de vinculación
  • Example#1642 - Sentencias múltiples
  • Example#1643 - Inyección SQL
  • Example#1644 - Establecer el modo de autoconsignación con SQL y a través de la API
  • Example#1645 - Consignación y reinicio
  • Example#1646 - Acceder a los metadatos de un conjunto de resultados
  • Example#1647 - Metadatos de sentencias preparadas
  • Example#1648 - Ejemplo resumen de la extensión MySQLi
  • Example#1649 - Ejemplo de $mysqli->affected_rows
  • Example#1650 - Ejemplo de mysqli::autocommit
  • Example#1651 - Ejemplo de $mysqli->begin_transaction
  • Example#1652 - Ejemplo del método mysqli::change_user
  • Example#1653 - Ejemplo de mysqli::character_set_name
  • Example#1654 - Ejemplo de mysqli::commit
  • Example#1655 - $mysqli->connect_errno example
  • Example#1656 - Ejemplo de $mysqli->connect_error
  • Example#1657 - Ejemplo de mysqli::__construct
  • Example#1658 - Generando un fichero de prueba (traza)
  • Example#1659 - Ejemplo de $mysqli->errno
  • Example#1660 - Ejemplo de $mysqli->error_list
  • Example#1661 - Ejemplo de $mysqli->error
  • Example#1662 - Ejemplo de $mysqli->field_count
  • Example#1663 - mysqli::get_charset example
  • Example#1664 - mysqli_get_client_info
  • Example#1665 - mysqli_get_client_version
  • Example#1666 - Un ejemplo de mysqli_get_connection_stats
  • Example#1667 - Ejemplo de $mysqli->host_info
  • Example#1668 - Ejemplo de $mysqli->protocol_version
  • Example#1669 - Ejemplo de $mysqli->server_info
  • Example#1670 - Ejemplo de $mysqli->server_version
  • Example#1671 - Ejemplo de $mysqli->info
  • Example#1672 - Ejemplo de $mysqli->insert_id
  • Example#1673 - Ejemplo de mysqli::kill
  • Example#1674 - Ejemplo de mysqli::multi_query
  • Example#1675 - Ejemplo de mysqli::ping
  • Example#1676 - Un ejemplo de mysqli_poll
  • Example#1677 - Ejemplo de mysqli::prepare
  • Example#1678 - Ejemplo de mysqli::query
  • Example#1679 - Ejemplo de mysqli::real_connect
  • Example#1680 - Ejemplo de mysqli::real_escape_string
  • Example#1681 - Ejemplo de mysqli::rollback
  • Example#1682 - Ejemplo de mysqli::select_db
  • Example#1683 - Ejemplo de mysqli::set_charset
  • Example#1684 - Ejemplo de $mysqli->sqlstate
  • Example#1685 - Ejemplo de mysqli::stat
  • Example#1686 - Ejemplo $mysqli->thread_id
  • Example#1687 - Ejemplo de mysqli::use_result
  • Example#1688 - Ejemplo de $mysqli->warning_count
  • Example#1689 - Estilo orientado a objetos
  • Example#1690 - Estilo por procedimientos
  • Example#1691 - Estilo orientado a objetos
  • Example#1692 - Estilo por procedimientos
  • Example#1693 - Estilo orientado a objetos
  • Example#1694 - Estilo por procedimientos
  • Example#1695 - Estilo orientado a objetos
  • Example#1696 - Estilo por procedimientos
  • Example#1697 - Estilo orientado a objetos
  • Example#1698 - Estilo por procedimientos
  • Example#1699 - Estilo orientado a objetos
  • Example#1700 - Estilo por procedimientos
  • Example#1701 - Estilo orientado a objetos
  • Example#1702 - Estilo por procedimientos
  • Example#1703 - Estilo orientado a objetos
  • Example#1704 - Estilo por procedimientos
  • Example#1705 - Estilo orientado a objetos
  • Example#1706 - Estilo por procedimientos
  • Example#1707 - Estilo orientado a objetos
  • Example#1708 - Estilo por procedimientos
  • Example#1709 - Estilo orientado a objetos
  • Example#1710 - Estilo por procedimientos
  • Example#1711 - Estilo orientado a objetos
  • Example#1712 - Estilo por procedimientos
  • Example#1713 - Estilo orientado a objetos
  • Example#1714 - Estilo por procedimientos
  • Example#1715 - Estilo orientado a objetos
  • Example#1716 - Estilo por procedimientos
  • Example#1717 - Estilo orientado a objetos
  • Example#1718 - Estilo orientado a objetos
  • Example#1719 - Estilo por procedimientos
  • Example#1720 - Estilo orientado a objetos
  • Example#1721 - Estilo por procedimientos
  • Example#1722 - Estilo orientado a objetos
  • Example#1723 - Estilo por procedimientos
  • Example#1724 - Estilo orientado a objetos
  • Example#1725 - Estilo por procedimientos
  • Example#1726 - Estilo orientado a objetos
  • Example#1727 - Estilo por procedimientos
  • Example#1728 - Estilo orientado a objetos
  • Example#1729 - Estilo por procedimientos
  • Example#1730 - Un ejemplo de mysqli_result comparando el uso de iterator
  • Example#1731 - Estilo orientado a objetos
  • Example#1732 - Estilo por procedimientos
  • Example#1733 - Estilo orientado a objetos
  • Example#1734 - Estilo por procedimientos
  • Example#1735 - Estilo orientado a objetos
  • Example#1736 - Estilo por procedimientos
  • Example#1737 - Estilo orientado a objetos
  • Example#1738 - Estilo por procedimientos
  • Example#1739 - Estilo orientado a objetos
  • Example#1740 - Estilo por procedimientos
  • Example#1741 - Estilo orientado a objetos
  • Example#1742 - Estilo por procedimientos
  • Example#1743 - Estilo orientado a objetos
  • Example#1744 - Estilo por procedimientos
  • Example#1745 - Estilo orientado a objetos
  • Example#1746 - Estilo por procedimientos
  • Example#1747 - Estilo orientado a objetos
  • Example#1748 - Estilo por procedimientos
  • Example#1749 - Estilo orientado a objetos
  • Example#1750 - Estilo por procedimientos
  • Example#1751 - Ejemplo de mysqli_connect
  • Example#1752 - A mysqli_get_client_stats example
  • Example#1753 - Ejemplo general de la extensión MySQL
  • Example#1754 - Ejemplo de mysql_affected_rows
  • Example#1755 - Ejemplo de mysql_affected_rows al utilizar transacciones
  • Example#1756 - Ejemplo de mysql_client_encoding
  • Example#1757 - Ejemplo de mysql_close
  • Example#1758 - Ejemplo de mysql_connect
  • Example#1759 - Ejemplo de mysql_connect usando la sintaxis nombre_anfitrión:puerto
  • Example#1760 - Ejemplo de mysql_connect usando la sintaxis ":/rota/al/socket"
  • Example#1761 - Ejemplo alternativo de mysql_create_db
  • Example#1762 - Ejemplo de mysql_data_seek
  • Example#1763 - Ejemplo de mysql_db_name
  • Example#1764 - Ejemplo alternativo de mysql_db_query
  • Example#1765 - Ejemplo alternativo de mysql_drop_db
  • Example#1766 - Ejemplo de mysql_errno
  • Example#1767 - Ejemplo de mysql_error
  • Example#1768 - Ejemplo de mysql_escape_string
  • Example#1769 - Consulta con nombres de campos duplicados con alias
  • Example#1770 - mysql_fetch_array con MYSQL_NUM
  • Example#1771 - mysql_fetch_array con MYSQL_ASSOC
  • Example#1772 - mysql_fetch_array con MYSQL_BOTH
  • Example#1773 - Un ejemplo desarrolado de mysql_fetch_assoc
  • Example#1774 - Ejemplo de mysql_fetch_field
  • Example#1775 - Un ejemplo de mysql_fetch_lengths
  • Example#1776 - Ejemplo de mysql_fetch_object
  • Example#1777 - Ejemplo de mysql_fetch_object
  • Example#1778 - Recuperar una fila con mysql_fetch_row
  • Example#1779 - Un ejemplo de mysql_field_flags
  • Example#1780 - Ejemplo de mysql_field_len
  • Example#1781 - Ejemplo de mysql_field_name
  • Example#1782 - Un ejemplo de mysql_field_table
  • Example#1783 - Ejemplo de mysql_field_type
  • Example#1784 - Un ejemplo de mysql_free_result
  • Example#1785 - Ejemplo de mysql_get_client_info
  • Example#1786 - Ejemplo de mysql_get_host_info
  • Example#1787 - Ejemplo de mysql_get_proto_info
  • Example#1788 - Ejemplo de mysql_get_server_info
  • Example#1789 - Sentencias MySQL Relevantes
  • Example#1790 - Ejemplo de mysql_insert_id
  • Example#1791 - Ejemplo de mysql_list_dbs
  • Example#1792 - Alternativa para la obsoleta mysql_list_fields
  • Example#1793 - Ejemplo de mysql_list_processes
  • Example#1794 - Ejemplo alternativo de mysql_list_tables
  • Example#1795 - Un ejemplo de mysql_num_fields
  • Example#1796 - Ejemplo de mysql_num_rows
  • Example#1797 - Un ejemplo de mysql_ping
  • Example#1798 - Consulta inválida
  • Example#1799 - Consulta válida
  • Example#1800 - Ejemplo sencillo de mysql_real_escape_string
  • Example#1801 - mysql_real_escape_string requiere una conexión
  • Example#1802 - Un ejemplo de ataque de inyección de SQL
  • Example#1803 - Ejemplo de mysql_result
  • Example#1804 - Ejemplo mysql_select_db
  • Example#1805 - Ejemplo de mysql_stat
  • Example#1806 - Ejemplo alternativo de mysql_stat
  • Example#1807 - Ejemplo de mysql_tablename
  • Example#1808 - Ejemplo de mysql_thread_id
  • Example#1809 - Habilitar el complemento (php.ini)
  • Example#1810 - Fichero de configuración mínima específico del complemento (mysqlnd_ms_plugin.ini)
  • Example#1811 - Configuración mínima recomendada específica del complemento (mysqlnd_ms_plugin.ini)
  • Example#1812 - Usar un servidor como maestro y esclavo (¡solamente para pruebas!)
  • Example#1813 - Fichero de configuración específico del complemento (mysqlnd_ms_plugin.ini)
  • Example#1814 - Abrir una conexión con equilibrado de carga
  • Example#1815 - Ejecutar sentencias
  • Example#1816 - Configuración del complemento con un esclavo y un maestro
  • Example#1817 - Problema: estado de conexión y variables SQL de usuario
  • Example#1818 - Configuración del complemento con un esclavo y un maestro
  • Example#1819 - Sugerencias SQL para evitar el intercambio de conexión
  • Example#1820 - Enfrentarse a la demora de replicación
  • Example#1821 - Creación de una tabla en un esclavo
  • Example#1822 - Configuración del complemento con un esclavo y un maestro
  • Example#1823 - Usar sugerencias SQL para transacciones
  • Example#1824 - Equilibrado de carga considerando transacciones: el ajuste trx_stickiness
  • Example#1825 - Consideración de transacciones
  • Example#1826 - Patrón general para transacciones XA
  • Example#1827 - Las transacciones locales y globales son mutuamente exclusivas
  • Example#1828 - Almacenamiento del estado del coordinador de transacciones
  • Example#1829 - Consistencia de sesión: lectura de sus escrituras
  • Example#1830 - Solicitud de consistencia de sesión
  • Example#1831 - Edad máxima/demora del esclavo
  • Example#1832 - Limitar la demora del esclavo
  • Example#1833 - La tolerancia a fallos no está establecida
  • Example#1834 - No hay esclavos dentro del límite de tiempo
  • Example#1835 - Crear una tabla contador en el maestro
  • Example#1836 - Configuración del complemento: SQL para la inyección del GTID en el lado del cliente
  • Example#1837 - Inyección transparente del ID de transacciones global
  • Example#1838 - Configuración del complemento: SQL para obtener el GTID
  • Example#1839 - Obtener el GTID después de la ejecución
  • Example#1840 - Configuración del complemento: comprobar un GTID en particular
  • Example#1841 - Nivel de servicio de consistencia de sesión y GTID combinados
  • Example#1842 - Configuración de complemento: usar la característica del GTID interna de MySQL 5.6.5-m8
  • Example#1843 - Resumen: calidad del servicio para solicitar la lectura de sus escrituras
  • Example#1844 - Configuración del complemento: sin entradas especiales para la caché
  • Example#1845 - Almacenar en caché una petición a un servidor
  • Example#1846 - Lectura de sus escrituras y almacenamiento en la caché combinados
  • Example#1847 - Tolerancia a fallos manual, opcional automática
  • Example#1848 - Tolerancia a fallos manual
  • Example#1849 - Clúster de grupos de nodos
  • Example#1850 - Particionamiento manual usando sugerencias SQL
  • Example#1851 - Configuración del complemento: hosts de Fabric en lugar de servidores MySQL
  • Example#1852 - Particionameinto manual usando sugerencias SQL
  • Example#1853 - Provocar un error de conexión
  • Example#1854 - Error de conexión en la ejecución de una consulta
  • Example#1855 - Provocar un error de conexión
  • Example#1856 - Tolerancia a fallos más básica
  • Example#1857 - Provocar un error transitorio
  • Example#1858 - Bucle de reintentos del error transitorio
  • Example#1859 - Habilitar el complemento (php.ini)
  • Example#1860 - Configuración básica del complemento (mysqlnd_ms_plugin.ini) para la Replicación de MySQL
  • Example#1861 - Múltiples primarios - multimaestro (php.ini)
  • Example#1862 - Copia primaria con múltiples primarios y particionamiento
  • Example#1863 - Múltiples primarios - multimaestro (php.ini)
  • Example#1864 - Clúster de actualización en cualquier sitio sincrónico
  • Example#1865 - Patrón general para transacciones XA
  • Example#1866 - Convertir un array de PHP (hash) al formato JSON
  • Example#1867 - Ejemplo del uso de nombres de sección
  • Example#1868 - Lista de esclavos anónimos
  • Example#1869 - Lista de maestros usando nombres simbólicos
  • Example#1870 - Palabras clave para configurar un servidor
  • Example#1871 - El nuevo filtro roundrobin, funcionalidad antigua
  • Example#1872 - El filtro user reemplaza a mysqlnd_ms_set_user_pick_server
  • Example#1873 - Mensaje de error común en caso de problemas con el fichero de configuración (hasta la versión 1.5.0)
  • Example#1874 - Validación mejorada del fichero de configuración desde 1.5.0
  • Example#1875 - Error posiblemente más preciso debido a mysqlnd_ms.force_config_usage=1
  • Example#1876 - Configuración mínima del complemento para usar con MySQL Fabric
  • Example#1877 - Tiempo de espera opcional para la comunicación con Fabric
  • Example#1878 - Advertencias sobre la violación de límites de transacciones
  • Example#1879 - Secuencia de filtros inválida
  • Example#1880 - Equilibrado de carga aleatorio con el filtro random
  • Example#1881 - Equilibrado de carga "aleatoria una vez" con el filtro random
  • Example#1882 - Error de referencia
  • Example#1883 - Asignar weight para el equilibrado de carga
  • Example#1884 - Filtro roundrobin
  • Example#1885 - Establecer una llamada de retorno
  • Example#1886 - Utilizar una llamada de retorno
  • Example#1887 - Devolver maestros y esclavos aleatorios
  • Example#1888 - Particionamiento manual
  • Example#1889 - Límite global de la demora de los esclavos
  • Example#1890 - Tolerancia a fallos opcional en el maestro al fallar una conexión a un esclavo
  • Example#1891 - Nueva sintaxis desde 1.4.0
  • Example#1892 - Deshabilitar las conexiones retardadas
  • Example#1893 - Escapado de cadenas de texto sobre un gestor de conexiones retardadas
  • Example#1894 - master_on_write para lecturas consistentes
  • Example#1895 - Utilizar el maestro para ejecutar transacciones
  • Example#1896 - Sin tolerancia a fallos automáticia, inconveniente al manejar errores
  • Example#1897 - Bucle de reintentos para errores transitorios
  • Example#1898 - Definición SQL para la tabla de transacciones de almacenamiento de estado de MySQL
  • Example#1899 - Definición SQL para la tabla de transacciones de almacenamiento de estado de MySQL
  • Example#1900 - Definición SQL para la tabla de transacciones de almacenamiento de estado de MySQL
  • Example#1901 - Ejemplo del uso de nombres de sección
  • Example#1902 - Sintaxis de lista
  • Example#1903 - Comprobar la actividad del complemento en un modelo de desarrollo sin hilos
  • Example#1904 - Registrar las estadístcias durante el cierre
  • Example#1905 - Ejemplo demostrando el uso de constantes de mysqlnd_ms
  • Example#1906 - Ejemplo de mysqlnd_ms_dump_servers
  • Example#1907 - Ejemplo de mysqlnd_ms_get_last_gtid
  • Example#1908 - Ejemplo de mysqlnd_ms_get_last_used_connection
  • Example#1909 - Ejemplo de mysqlnd_ms_get_stats
  • Example#1910 - Ejemplo de mysqlnd_ms_match_wild
  • Example#1911 - Ejemplo de mysqlnd_ms_query_is_select
  • Example#1912 - Ejemplo de mysqlnd_ms_set_qos
  • Example#1913 - Ejemplo de mysqlnd_ms_set_user_pick_server
  • Example#1914 - Habilitar el complemento (php.ini)
  • Example#1915 - Usar la sugerencia SQL MYSQLND_QC_ENABLE_SWITCH
  • Example#1916 - Usar la sugerencia SQL MYSQLND_QC_DISABLE_SWITCH
  • Example#1917 - Ejemplo que muestra qué tipos de sentencias no son almacenadas en la caché
  • Example#1918 - Habilitar el almacenamiento en caché de todas las sentencias usando el ajuste ini mysqlnd_qc.cache_no_table
  • Example#1919 - Establecer el TTL con el ajuste ini mysqlnd_qc.ttl
  • Example#1920 - Establecer el TTL con sugerencias SQL
  • Example#1921 - Establecer una llamada de retorno con mysqlnd_qc_set_is_select
  • Example#1922 - Habilitar el mecanismo de defensa de cierre
  • Example#1923 - Recopilar un rastreo de consulta
  • Example#1924 - Establecer la profundidad de la búsqueda de rastros con el ajuste ini mysqlnd_qc.query_trace_bt_depth
  • Example#1925 - Recopilar datos de estadísticas con el ajuste ini mysqlnd_qc.time_statistics
  • Example#1926 - Ejemplo del uso de mysqlnd_qc_get_cache_info
  • Example#1927 - Ejemplo del uso de mysqlnd_qc_get_normalized_query_trace_log
  • Example#1928 - Utilizar un gestor de almacenamiento definido por el usuario
  • Example#1929 - Usar constantes de sugerencias SQL
  • Example#1930 - Ejemplo del uso de mysqlnd_qc_set_cache_condition
  • Example#1931 - Ejemplo de mysqlnd_qc_get_available_handlers
  • Example#1932 - Ejemplo de mysqlnd_qc_get_cache_info
  • Example#1933 - Ejemplo de mysqlnd_qc_get_core_stats
  • Example#1934 - Ejemplo de mysqlnd_qc_get_normalized_query_trace_log
  • Example#1935 - Ejemplo de mysqlnd_qc_get_query_trace_log
  • Example#1936 - Ejemplo de mysqlnd_qc_set_cache_condition
  • Example#1937 - Ejemplo de mysqlnd_qc_set_is_select
  • Example#1938 - Ejemplo de mysqlnd_qc_set_storage_handler
  • Example#1939 - Habilitar el complemento (php.ini)
  • Example#1940 - Pseudocódigo: qué hace la clase interna
  • Example#1941 - Instalar un proxy
  • Example#1942 - Registro del proxy, mysqlnd_uh.enable=1
  • Example#1943 - La instalación del proxy deshabilitada
  • Example#1944 - Proxy de conexión
  • Example#1945 - Proxy de sentencia preparada
  • Example#1946 - Monitorización básica
  • Example#1947 - Ejemplo de MysqlndUhConnection::changeUser
  • Example#1948 - Ejemplo de MysqlndUhConnection::charsetName
  • Example#1949 - Ejemplo de MysqlndUhConnection::close
  • Example#1950 - Ejemplo de MysqlndUhConnection::connect
  • Example#1951 - Ejemplo de MysqlndUhConnection::endPSession
  • Example#1952 - Ejemplo de MysqlndUhConnection::escapeString
  • Example#1953 - Ejemplo de MysqlndUhConnection::getAffectedRows
  • Example#1954 - Ejemplo de MysqlndUhConnection::getErrorNumber
  • Example#1955 - Ejemplo de MysqlndUhConnection::getErrorString
  • Example#1956 - Ejemplo de MysqlndUhConnection::getFieldCount
  • Example#1957 - Ejemplo de MysqlndUhConnection::getHostInformation
  • Example#1958 - Ejemplo de MysqlndUhConnection::getLastInsertId
  • Example#1959 - Ejemplo de MysqlndUhConnection::getLastMessage
  • Example#1960 - Ejemplo de MysqlndUhConnection::getProtocolInformation
  • Example#1961 - Ejemplo de MysqlndUhConnection::getServerInformation
  • Example#1962 - Ejemplo de MysqlndUhConnection::getServerStatistics
  • Example#1963 - Ejemplo de MysqlndUhConnection::getServerVersion
  • Example#1964 - Ejemplo de MysqlndUhConnection::getSqlstate
  • Example#1965 - Ejemplo de MysqlndUhConnection::getStatistics
  • Example#1966 - Ejemplo de MysqlndUhConnection::getThreadId
  • Example#1967 - Ejemplo de MysqlndUhConnection::getWarningCount
  • Example#1968 - Ejemplo de MysqlndUhConnection::init
  • Example#1969 - Ejemplo de MysqlndUhConnection::kill
  • Example#1970 - Ejemplo de MysqlndUhConnection::listFields
  • Example#1971 - Ejemplo de MysqlndUhConnection::listMethod
  • Example#1972 - Ejemplo de MysqlndUhConnection::moreResults
  • Example#1973 - Ejemplo de MysqlndUhConnection::nextResult
  • Example#1974 - Ejemplo de MysqlndUhConnection::ping
  • Example#1975 - Ejemplo de MysqlndUhConnection::query
  • Example#1976 - Ejemplo de MysqlndUhConnection::queryReadResultsetHeader
  • Example#1977 - Ejemplo de MysqlndUhConnection::reapQuery
  • Example#1978 - Ejemplo de MysqlndUhConnection::refreshServer
  • Example#1979 - Ejemplo de MysqlndUhConnection::restartPSession
  • Example#1980 - Ejemplo de MysqlndUhConnection::selectDb
  • Example#1981 - Ejemplo de MysqlndUhConnection::sendClose
  • Example#1982 - Ejemplo de MysqlndUhConnection::sendQuery
  • Example#1983 - Ejemplo de MysqlndUhConnection::serverDumpDebugInformation
  • Example#1984 - Ejemplo de MysqlndUhConnection::setAutocommit
  • Example#1985 - Ejemplo de MysqlndUhConnection::setCharset
  • Example#1986 - Ejemplo de MysqlndUhConnection::setClientOption
  • Example#1987 - Ejemplo de MysqlndUhConnection::setServerOption
  • Example#1988 - Ejemplo de MysqlndUhConnection::simpleCommand
  • Example#1989 - Ejemplo de MysqlndUhConnection::simpleCommandHandleResponse
  • Example#1990 - Ejemplo de MysqlndUhConnection::sslSet
  • Example#1991 - Ejemplo de MysqlndUhConnection::stmtInit
  • Example#1992 - Ejemplo de MysqlndUhConnection::storeResult
  • Example#1993 - Ejemplo de MysqlndUhConnection::txCommit
  • Example#1994 - Ejemplo de MysqlndUhConnection::txRollback
  • Example#1995 - Ejemplo de MysqlndUhConnection::useResult
  • Example#1996 - Ejemplo de MysqlndUhPreparedStatement::execute
  • Example#1997 - Ejemplo de MysqlndUhPreparedStatement::prepare
  • Example#1998 - Ejemplo de mysqlnd_uh_convert_to_mysqlnd
  • Example#1999 - Ejemplo de mysqlnd_uh_set_connection_proxy
  • Example#2000 - Habilitar el complemento (php.ini)
  • Example#2001 - Tabla SQL empleada para la Guía rápida
  • Example#2002 - Ejemplo básico
  • Example#2003 - Ejemplo de mysqlnd_memcache_get_config
  • Example#2004 - Ejemplo de mysqlnd_memcache_set con var_dump como una retrollama de depuración simple.
  • Example#2005 - Consulta básica
  • Example#2006 - Inserción con variables vinculadas
  • Example#2007 - Vincular la cláusula WHERE a una consulta
  • Example#2008 - Insertar datos en una columna CLOB
  • Example#2009 - Usar una función almacenada de PL/SQL
  • Example#2010 - Utilizar un procedimiento almacenado de PL/SQL
  • Example#2011 - Llamar a una función de PL/SQL que devuelve un REF CURSOR
  • Example#2012 -
  • Example#2013 - user_oci8_probes.d para rasrear todos los Sondeos estáticos de OCI8 para PHP al nivel de usuario con DTrace
  • Example#2014 - Ejemplo de oci_bind_array_by_name
  • Example#2015 - Insertar datos con oci_bind_by_name
  • Example#2016 - Vincular una vez para múltiples ejecuciones
  • Example#2017 - Vinculación con un bucle foreach
  • Example#2018 - Vinculación en una cláusula WHERE
  • Example#2019 - Vinculación con una cláusula LIKE
  • Example#2020 - Vinculación con REGEXP_LIKE
  • Example#2021 - Vinculación de múltiples valores en una cláusula IN
  • Example#2022 - Vinculación de un ROWID devuelto por una consulta
  • Example#2023 - Vinculación de un ROWID sobre INSERT
  • Example#2024 - Vinculación para una función almacenada de PL/SQL
  • Example#2025 - Vinculación de parámetros para un procedimiento almacenado de PL/SQL
  • Example#2026 - Vinculación de una columna CLOB
  • Example#2027 - Vincular un BOOLEAN de PL/SQL
  • Example#2028 - Ejemplo de oci_client_version
  • Example#2029 - Cerrar una conexión
  • Example#2030 - Las conexiones a bases de datos no se cierran hasta que todas las referencias sean cerradas
  • Example#2031 - Cerrar una conexión abierta más de una vez
  • Example#2032 - Las conexsiones se cierran cuando las variables salen de su ámbito
  • Example#2033 - Ejemplo de oci_commit
  • Example#2034 - Uso básico de oci_connect utilizando la sintaxis de Easy Connect
  • Example#2035 - Uso básico de oci_connect utilizando un nombre de Network Connect
  • Example#2036 - oci_connect con un conjunto de caracteres explícito
  • Example#2037 - Usar múltiples llamadas a oci_connect
  • Example#2038 - Ejemplo de oci_define_by_name
  • Example#2039 - oci_define_by_name con nombres de columna sensibles al uso de mayúsculas/minúsculas
  • Example#2040 - oci_define_by_name con columnas de tipo LOB
  • Example#2041 - oci_define_by_name con un tipo explícito
  • Example#2042 - Mostrar el mensaje de error de Oracle después de un error de conexión
  • Example#2043 - Mostrar el mensaje de error de Oracle después de un error de análisis
  • Example#2044 - Mostrar el mensaje de error de Oracle, la sentencia problemática, y la posición del problema en un error de ejecución
  • Example#2045 - oci_execute para consultas
  • Example#2046 - Ejemplo de oci_execute sin especificar un modo
  • Example#2047 - Ejemplo de oci_execute con OCI_NO_AUTO_COMMIT
  • Example#2048 - Ejemplo de oci_execute con diferentes modos de consolidación
  • Example#2049 - Ejemplo de oci_execute con OCI_DESCRIBE_ONLY
  • Example#2050 - Ejemplo de oci_fetch_all
  • Example#2051 - Ejemplo de oci_fetch_all con OCI_FETCHSTATEMENT_BY_ROW
  • Example#2052 - oci_fetch_all con OCI_NUM
  • Example#2053 - oci_fetch_array con OCI_BOTH
  • Example#2054 - oci_fetch_array con OCI_NUM
  • Example#2055 - oci_fetch_array con OCI_ASSOC
  • Example#2056 - oci_fetch_array con OCI_RETURN_NULLS
  • Example#2057 - oci_fetch_array con OCI_RETURN_LOBS
  • Example#2058 - oci_fetch_array con nombres de columna sensibles al uso de mayúsculas/minúsculas
  • Example#2059 - oci_fetch_array con columnas que tienen nombres duplicados
  • Example#2060 - oci_fetch_array con columnas DATE
  • Example#2061 - oci_fetch_array con REF CURSOR
  • Example#2062 - Paginación con oci_fetch_array usando una consulta como LIMIT
  • Example#2063 - oci_fetch_array con Conjuntos de Resultados Implícitos de Oracle Database 12c
  • Example#2064 - Ejemplo de oci_fetch_assoc
  • Example#2065 - Ejemplo de oci_fetch_object
  • Example#2066 - oci_fetch_object con nombres de columnas sensibles al uso de mayúsculas/minúsculas
  • Example#2067 - oci_fetch_object con LOBs
  • Example#2068 - Ejemplo de oci_fetch_row
  • Example#2069 - oci_fetch con variables definidas
  • Example#2070 - oci_fetch con oci_result
  • Example#2071 - Ejemplo de oci_field_name
  • Example#2072 - Ejemplo de oci_field_name
  • Example#2073 - Ejemplo de oci_field_precision
  • Example#2074 - oci_field_scale Example
  • Example#2075 - Ejemplo de oci_field_size
  • Example#2076 - oci_field_type_raw Example
  • Example#2077 - Ejemplo de oci_field_type
  • Example#2078 - Obtener Conjuntos de resultados implícitos en un blucle
  • Example#2079 - Obtener gestores de sentencias hijas individualemente
  • Example#2080 - Establecer explícitamente la Cuenta de precarga
  • Example#2081 - Ejemplo de Conjunto de resultados implícitos sin usar oci_get_implicit_resultset
  • Example#2082 - Ejemplo de oci_new_connect
  • Example#2083 - Vincular un REF CURSOR en una llamada a un procedimiento almacenado de Oracle
  • Example#2084 - Ejemplo de oci_new_descriptor
  • Example#2085 - Ejemplo de oci_new_descriptor
  • Example#2086 - Ejemplo de oci_num_fields
  • Example#2087 - Ejemplo de oci_num_rows
  • Example#2088 - Ejemplo de oci_parse para sentencias SQL
  • Example#2089 - Ejemplo de oci_parse para sentencias PL/SQL
  • Example#2090 - Ejemplo de oci_password_change cambiando la contraseña de un usuario ya conectado
  • Example#2091 - Ejemplo de oci_password_change conectando y cambiando la contraseña en un solo paso
  • Example#2092 - Ejemplo básico de oci_pconnect usando la sintaxis de Easy Connect
  • Example#2093 - oci_fetch con oci_result
  • Example#2094 - Ejemplo de oci_rollback
  • Example#2095 - Ejemplo de reversión a un SAVEPOINT
  • Example#2096 - Ejemplo de oci_server_version
  • Example#2097 - Establecer la acción
  • Example#2098 - Setting the timeout
  • Example#2099 - Establecer el identificador del cliente para el usuario de la aplicación
  • Example#2100 - Establecer la información del cliente
  • Example#2101 - Setting the DBOP
  • Example#2102 - Dos scripts pueden usar diferentes versiones de myfunc() a la vez
  • Example#2103 - Establecer el nombre del módulo
  • Example#2104 - Cambiar el valor de precarga predeterminado para una consulta
  • Example#2105 - Cambiar la precarga predeterminada para la obtención de un REF CURSOR
  • Example#2106 - Establecer el valor de precarga cuando se vuelve a pasar un REF CURSOR a Oracle
  • Example#2107 - Ejemplo de oci_statement_type
  • Example#2108 - Creación de una base de datos Paradox con dos campos
  • Example#2109 - Convierte una fecha en el archivo paradox en un formato legible por humanos
  • Example#2110 - Establece los campos fecha/hora en una base de datos paradox a la fecha/hora actual
  • Example#2111 - Abrir una base de datos Paradox
  • Example#2112 - Abrir una base de datos Paradox
  • Example#2113 - Conversión de una fecha y hora paradox en un formato legible por humanos
  • Example#2114 - Ejemplo resumido de la extensión PostgreSQL
  • Example#2115 - Ejemplo de pg_affected_rows
  • Example#2116 - Ejemplo de pg_cancel_query
  • Example#2117 - Ejemplo de pg_client_encoding
  • Example#2118 - Ejemplo de pg_close
  • Example#2119 - Usando pg_connect
  • Example#2120 - Ejemplo de pg_connection_busy
  • Example#2121 - Ejemplo de pg_connection_reset
  • Example#2122 - Ejemplo de pg_connection_status
  • Example#2123 - Ejemplo de pg_convert
  • Example#2124 - Ejemplo de la función pg_copy_from
  • Example#2125 - Ejemplo de pg_copy_to
  • Example#2126 - Ejemplo de pg_dbname
  • Example#2127 - Ejemplo de la función pg_delete
  • Example#2128 - pg_end_copy example
  • Example#2129 - Ejemplo de pg_escape_bytea
  • Example#2130 - pg_escape_identifier example
  • Example#2131 - pg_escape_literal example
  • Example#2132 - pg_escape_string example
  • Example#2133 - Usando pg_execute
  • Example#2134 - pg_fetch_all_columns example
  • Example#2135 - PostgreSQL fetch all
  • Example#2136 - pg_fetch_array example
  • Example#2137 - pg_fetch_assoc example
  • Example#2138 - pg_fetch_object example
  • Example#2139 - pg_fetch_result example
  • Example#2140 - pg_fetch_row example
  • Example#2141 - pg_field_is_null example
  • Example#2142 - Getting information about fields
  • Example#2143 - Getting information about fields
  • Example#2144 - Getting information about fields
  • Example#2145 - Getting information about fields
  • Example#2146 - Getting table information about a field
  • Example#2147 - Getting information about fields
  • Example#2148 - Obtención de información sobre los campos
  • Example#2149 - pg_free_result example
  • Example#2150 - PostgreSQL NOTIFY message
  • Example#2151 - PostgreSQL backend PID
  • Example#2152 - pg_get_result example
  • Example#2153 - Ejemplo de pg_host
  • Example#2154 - pg_insert example
  • Example#2155 - Ejemplo depg_last_error
  • Example#2156 - Ejemplo de pg_last_notice
  • Example#2157 - pg_last_oid example
  • Example#2158 - pg_lo_close example
  • Example#2159 - pg_lo_create example
  • Example#2160 - pg_lo_export example
  • Example#2161 - pg_lo_import example
  • Example#2162 - pg_lo_open example
  • Example#2163 - pg_lo_read_all example
  • Example#2164 - pg_lo_read example
  • Example#2165 - pg_lo_seek example
  • Example#2166 - pg_lo_tell example
  • Example#2167 - pg_lo_truncate example
  • Example#2168 - pg_lo_unlink example
  • Example#2169 - pg_lo_write example
  • Example#2170 - Getting table metadata
  • Example#2171 - pg_num_fields example
  • Example#2172 - pg_num_rows example
  • Example#2173 - Ejemplo de pg_options
  • Example#2174 - pg_parameter_status example
  • Example#2175 - Usando pg_pconnect
  • Example#2176 - Ejemplo de pg_ping
  • Example#2177 - Ejemplo de pg_port
  • Example#2178 - Usando pg_prepare
  • Example#2179 - pg_put_line example
  • Example#2180 - Using pg_query_params
  • Example#2181 - Ejemplo de pg_query
  • Example#2182 - Uso de pg_query con varias sentencias
  • Example#2183 - pg_result_error_field example
  • Example#2184 - pg_result_error example
  • Example#2185 - pg_result_seek example
  • Example#2186 - pg_result_status example
  • Example#2187 - pg_select example
  • Example#2188 - Using pg_send_execute
  • Example#2189 - Utilizando pg_send_prepare
  • Example#2190 - Using pg_send_query_params
  • Example#2191 - pg_send_query example
  • Example#2192 - pg_set_client_encoding example
  • Example#2193 - pg_set_error_verbosity example
  • Example#2194 - pg_trace example
  • Example#2195 - Ejemplo de pg_transaction_status
  • Example#2196 - Ejemplo de pg_tty
  • Example#2197 - pg_unescape_bytea example
  • Example#2198 - Ejemplo de pg_untrace
  • Example#2199 - Ejemplo de pg_update
  • Example#2200 - Ejemplo de pg_version
  • Example#2201 - Backup an existing database
  • Example#2202 - Ejemplo de SQLite3::changes
  • Example#2203 - Ejemplo de SQLite3::close
  • Example#2204 - Ejemplo de SQLite3::__construct
  • Example#2205 - SQLite3::createCollation
  • Example#2206 - Ejemplo de SQLite3::createFunction
  • Example#2207 - SQLite3::enableExceptions example
  • Example#2208 - Ejemplo de SQLite3::exec
  • Example#2209 - Ejemplo de SQLite3::loadExtension
  • Example#2210 - Ejemplo de SQLite3::open
  • Example#2211 - SQLite3::openBlob example
  • Example#2212 - Incrementally writing a BLOB
  • Example#2213 - Ejemplo de SQLite3::prepare
  • Example#2214 - Ejemplo de SQLite3::query
  • Example#2215 - Ejemplo de SQLite3::querySingle
  • Example#2216 - SQLite3::setAuthorizer example
  • Example#2217 - Ejemplo de SQLite3::version
  • Example#2218 - Ejemplo de SQLite3Stmt::bindValue
  • Example#2219 - Inspecting the expanded SQL
  • Example#2220 - Ejemplo de sqlsrv_begin_transaction
  • Example#2221 - Ejemplo de sqlsrv_cancel
  • Example#2222 - Ejemplo de sqlsrv_client_info
  • Example#2223 - Ejemplo de sqlsrv_close
  • Example#2224 - Ejemplo de sqlsrv_commit
  • Example#2225 - Conectar utilizando autenticación Windows.
  • Example#2226 - Conectar especificando nombre de usuario y contraseña.
  • Example#2227 - Conectar a un puerto específico.
  • Example#2228 - ejemplo de functionname
  • Example#2229 - ejemplo de sqlsrv_execute
  • Example#2230 - Devolver un array asociativo.
  • Example#2231 - Devolver un array numérico.
  • Example#2232 - Ejemplo con sqlsrv_fetch_object
  • Example#2233 - Ejemplo con sqlsrv_fetch
  • Example#2234 - Ejemplo con sqlsrv_field_metadata
  • Example#2235 - sqlsrv_free_stmt example
  • Example#2236 - sqlsrv_get_field example
  • Example#2237 - sqlsrv_has_rows example
  • Example#2238 - sqlsrv_next_result example
  • Example#2239 - sqlsrv_num_fields example
  • Example#2240 - sqlsrv_num_rows example
  • Example#2241 - sqlsrv_prepare example
  • Example#2242 - sqlsrv_query example
  • Example#2243 - sqlsrv_rollback example
  • Example#2244 - sqlsrv_rows_affected example
  • Example#2245 - sqlsrv_send_stream_data example
  • Example#2246 - sqlsrv_server_info example
  • Example#2247 - Putting and getting a key-value pair
  • Example#2248 - TokyoTyrant::add example
  • Example#2249 - TokyoTyrant::connect example
  • Example#2250 - TokyoTyrant::connectUri example
  • Example#2251 - TokyoTyrant::copy example
  • Example#2252 - TokyoTyrant::ext example
  • Example#2253 - TokyoTyrant::fwmKeys example
  • Example#2254 - TokyoTyrant::get example
  • Example#2255 - TokyoTyrant::getIterator example
  • Example#2256 - TokyoTyrant::num example
  • Example#2257 - TokyoTyrant::out example
  • Example#2258 - TokyoTyrant::put example
  • Example#2259 - TokyoTyrant::putCat example
  • Example#2260 - tokyotyrant::putKeep example
  • Example#2261 - TokyoTyrant::putNr example
  • Example#2262 - TokyoTyrant::putShl example
  • Example#2263 - TokyoTyrant::setMaster example
  • Example#2264 - TokyoTyrant::size example
  • Example#2265 - TokyoTyrant::stat example
  • Example#2266 - TokyoTyrant::vanish example
  • Example#2267 - TokyoTyrantTable::genUid example
  • Example#2268 - TokyoTyrantTable::get example
  • Example#2269 - TokyoTyrantTable::getIterator example
  • Example#2270 - TokyoTyrantTable::getQuery example
  • Example#2271 - TokyoTyrantTable::out example
  • Example#2272 - TokyoTyrantTable::put example
  • Example#2273 - TokyoTyrantTable::putCat example
  • Example#2274 - TokyoTyrantTable::putKeep example
  • Example#2275 - TokyoTyrantQuery::addCond example
  • Example#2276 - TokyoTyrantQuery::__construct example
  • Example#2277 - TokyoTyrantQuery::count example
  • Example#2278 - TokyoTyrantQuery iterator example
  • Example#2279 - TokyoTyrantQuery::hint example
  • Example#2280 - TokyoTyrantQuery iterator example
  • Example#2281 - TokyoTyrantQuery::metaSearch example
  • Example#2282 - TokyoTyrantQuery iterator example
  • Example#2283 - TokyoTyrantQuery::out example
  • Example#2284 - TokyoTyrantQuery iterator example
  • Example#2285 - TokyoTyrantQuery::search example
  • Example#2286 - TokyoTyrantQuery iterator example
  • Example#2287 - TokyoTyrantIterator::__construct example
  • Example#2288 - Ejemplo de cal_days_in_month
  • Example#2289 - Ejemplo de cal_from_jd
  • Example#2290 - Ejemplo de cal_info
  • Example#2291 - Ejemplo de easter_date
  • Example#2292 - Ejemplo de easter_days
  • Example#2293 - Funciones de calendario
  • Example#2294 - Ejemplo de jdtojewish
  • Example#2295 - DateTime::add/sub, añadir intervalos que cubren el tiempo transcurrido
  • Example#2296 - DateTime::modify y strtotime, aumentar o disminuir valores de componentes individuales
  • Example#2297 - Añadir o restar horas puede sobrepasar o subpasar fechas
  • Example#2298 - Ejemplo de DateTime::add
  • Example#2299 - Más ejemplos de DateTime::add
  • Example#2300 - Cuidado al añadir meses
  • Example#2301 - Ejemplo de DateTime::__construct
  • Example#2302 - Complejidades de DateTime::__construct
  • Example#2303 - Ejemplo de DateTime::createFromFormat
  • Example#2304 - Complejidades de DateTime::createFromFormat
  • Example#2305 - Cadena de formato con caracteres literales
  • Example#2306 - Creating a mutable date time object
  • Example#2307 - Creating a mutable date time object
  • Example#2308 - Ejemplo de DateTime::getLastErrors
  • Example#2309 - Ejemplo de DateTime::modify
  • Example#2310 - Cuidado al añadir o sustraer meses
  • Example#2311 - Ejemplo de DateTime::setDate
  • Example#2312 - Los valores que exceden rangos son añadidos a sus valores padre
  • Example#2313 - Ejemplo de DateTime::setISODate
  • Example#2314 - Los valores que execen rangos son añadidos a sus valores padre
  • Example#2315 - Buscar el mes en el que se encuentra una semana
  • Example#2316 - Ejemplo de DateTime::setTime
  • Example#2317 - Los valores que exceden rangos son añadidos a sus valores padre
  • Example#2318 - Ejemplo de DateTime::setTimestamp
  • Example#2319 - Alternativa de DateTime::setTimestamp en PHP 5.2
  • Example#2320 - Ejemplo de DateTime::setTimeZone
  • Example#2321 - Ejemplo de DateTime::sub
  • Example#2322 - Más ejemplos de DateTime::sub
  • Example#2323 - Cuidado al sustraer meses
  • Example#2324 - Creating an immutable date time object
  • Example#2325 - Crear un objeto de fecha y hora inmutable
  • Example#2326 - Ejemplo de DateTime::diff
  • Example#2327 - Comparación de objetos DateTime
  • Example#2328 - Ejemplo de DateTime::format
  • Example#2329 - Ejemplo de DateTime::getOffset
  • Example#2330 - Ejemplo de DateTime::getTimestamp
  • Example#2331 - Ejemplo de DateTime::getTimezone
  • Example#2332 - Atrapar errores cuando se instancia un DateTimeZone
  • Example#2333 - Ejemplo de DateTimeZone::getLocation
  • Example#2334 - Ejemplo de DateTimeZone::getOffset
  • Example#2335 - Un ejemplo de timezone_transitions_get
  • Example#2336 - Un ejemplo de timezone_abbreviations_list
  • Example#2337 - Un ejemplo de timezone_identifiers_list
  • Example#2338 - Ejemplo de DateInterval
  • Example#2339 - Analizar intervalos de fechas válidos
  • Example#2340 - Ejemplo de DateInterval
  • Example#2341 - DateInterval y excesos
  • Example#2342 - DateInterval y DateTime::diff con los modificadores %a y %d
  • Example#2343 - Ejemplo de DatePeriod
  • Example#2344 - Ejemplo de DatePeriod con DatePeriod::EXCLUDE_START_DATE
  • Example#2345 - Ejemplo de DatePeriod::getDateInterval
  • Example#2346 - Ejemplo de DatePeriod::getEndDate
  • Example#2347 - DatePeriod::getEndDate sin una fecha final
  • Example#2348 - Ejemplo de DatePeriod::getStartDate
  • Example#2349 - Ejemplo de checkdate
  • Example#2350 - Obtener la zona horaria por defecto
  • Example#2351 - Obtener la abreviatura de una zona horaria
  • Example#2352 - Obtener la zona horaria por defecto
  • Example#2353 - Ejemplo de date_parse_from_format
  • Example#2354 - Un ejemplo de date_parse
  • Example#2355 - date_parse con formatos relativos
  • Example#2356 - Un ejemplo de date_sun_info
  • Example#2357 - Ejemplo de date_sunrise
  • Example#2358 - Ejemplo de date_sunset
  • Example#2359 - Ejemplo de date
  • Example#2360 - Escapar caracteres en date
  • Example#2361 - Ejemplo de date y mktime
  • Example#2362 - date Formatting
  • Example#2363 - Ejemplo de getdate
  • Example#2364 - Ejemplo de gettimeofday
  • Example#2365 - Ejemplo de gmdate
  • Example#2366 - Ejemplo básico de gmmktime
  • Example#2367 - Ejemplo de gmstrftime
  • Example#2368 - Ejemplo de idate
  • Example#2369 - Ejemplo de localtime
  • Example#2370 - Ejecución de un script de cronometraje con microtime
  • Example#2371 - Ejecución de un script de cronometraje en PHP 5
  • Example#2372 - microtime y REQUEST_TIME_FLOAT (desde PHP 5.4.0)
  • Example#2373 - Ejemplo básico de mktime
  • Example#2374 - Ejemplo de mktime
  • Example#2375 - El último día del mes
  • Example#2376 - Ejemplos de localismos con strftime
  • Example#2377 - Ejemplo de número de semana del ISO 8601:1988
  • Example#2378 - Ejemplo multiplataforma compatible del modificador %e
  • Example#2379 - Mostrar todos los formatos conocidos y desconocidos.
  • Example#2380 - Ejemplo de strptime
  • Example#2381 - Un ejemplo de strtotime
  • Example#2382 - Comprobar si falla
  • Example#2383 - Ejemplo de time
  • Example#2384 - Un ejemplo de timezone_name_from_abbr
  • Example#2385 - Obtener la versión de timezonedb
  • Example#2386 - Medir la ejecución de varios bloques de código y obtener el total
  • Example#2387 - Cerrando un descriptor de fichero
  • Example#2388 - Bloqueando y desbloqueando
  • Example#2389 - Abrir un descriptor de fichero
  • Example#2390 - Posicionamiento de un fichero
  • Example#2391 - Asignando la tasa de baudios del puerto serie
  • Example#2392 - chdir ejemplo
  • Example#2393 - Ejemplo de chroot
  • Example#2394 - closedir ejemplo
  • Example#2395 - Ejemplo de dir
  • Example#2396 - getcwd ejemplo
  • Example#2397 - opendir ejemplo
  • Example#2398 - Listar todas las entradas de un directorio
  • Example#2399 - Listar todas las entradas del directorio actual y descartar . y ..
  • Example#2400 - Un simple ejemplo de scandir
  • Example#2401 - Ejemplo de finfo_buffer
  • Example#2402 - Un ejemplo de finfo_file
  • Example#2403 - Estilo orientado a objetos
  • Example#2404 - Estilo por procedimientos
  • Example#2405 - Ejemplo mime_content_type
  • Example#2406 - Ejemplo de basename
  • Example#2407 - Cambiar el grupo de un archivo
  • Example#2408 - Uso sencillo de chown
  • Example#2409 - Ejemplo de clearstatcache
  • Example#2410 - Ejemplo de copy
  • Example#2411 - Ejemplo de dirname
  • Example#2412 - Ejemplo de disk_free_space
  • Example#2413 - Ejemplo de disk_total_space
  • Example#2414 - Un ejemplo sencillo de fclose
  • Example#2415 - Manejar tiempos de espera con feof
  • Example#2416 - Ejemplo de feof con un puntero a un archivo no válido
  • Example#2417 - Ejemplo de escritura de un archivo usando fflush
  • Example#2418 - Un ejemplo de fgetc
  • Example#2419 - Leer e imprimir el contenido completo de un fichero CSV
  • Example#2420 - Leer un fichero línea a línea
  • Example#2421 - Leer un archivo PHP línea a línea
  • Example#2422 - Comprobar si existe un fichero
  • Example#2423 - Obtiene y muestra el código fuente de la página de inicio de un sitio web
  • Example#2424 - Buscar dentro de include_path
  • Example#2425 - Leer una sección de un fichero
  • Example#2426 - Usar contextos de flujo
  • Example#2427 - Ejemplo sencillo de uso
  • Example#2428 - Usar banderas
  • Example#2429 - Ejemplo de file
  • Example#2430 - Ejemplo de fileatime
  • Example#2431 - Un ejemplo de filectime
  • Example#2432 - Encontrar el grupo de un archivo
  • Example#2433 - Comparar el i-nodo de un archivo con el archivo actual
  • Example#2434 - Ejemplo de filemtime
  • Example#2435 - Encontrar el propietario de un archivo
  • Example#2436 - Muestra los permisos como un valor octal
  • Example#2437 - Muestra los permisos completos
  • Example#2438 - Ejemplo de filesize
  • Example#2439 - Ejemplo de filetype
  • Example#2440 - Ejemplo de flock
  • Example#2441 - flock usando la opción LOCK_NB
  • Example#2442 - Comprobar un adjetivo con un patrón comodín tipo shell
  • Example#2443 - Ejemplos de fopen
  • Example#2444 - Usar fpassthru con archivos binarios
  • Example#2445 - Ejemplo de fputcsv
  • Example#2446 - Un ejemplo sencillo de fread
  • Example#2447 - Ejemplo de lectura binaria de fread
  • Example#2448 - Ejemplos de lectura remota con fread
  • Example#2449 - Ejemplo de fscanf
  • Example#2450 - Contenido de usuarios.txt
  • Example#2451 - Ejemplo de fseek
  • Example#2452 - Ejemplo de fstat
  • Example#2453 - Ejemplo de ftell
  • Example#2454 - Ejemplo de truncar un archivo
  • Example#2455 - Un ejemplo sencillo de fwrite
  • Example#2456 - Manera conveniente de cómo glob puede remplazar a opendir y similares.
  • Example#2457 - Ejemplo de is_dir
  • Example#2458 - Ejemplo de is_executable
  • Example#2459 - Ejemplo de is_file
  • Example#2460 - Crear y confirmar si un archivo es un enlace simbólico
  • Example#2461 - Ejemplo de is_readable
  • Example#2462 - Ejemplo de is_uploaded_file
  • Example#2463 - Ejemplo de is_writable
  • Example#2464 - Cambiar el grupo de un enlace simbólico
  • Example#2465 - Cambiar el propietario de un enlace simbólico
  • Example#2466 - Crear un simple enlace duro
  • Example#2467 - Ejmeplo de linkinfo
  • Example#2468 - Comparación de stat y lstat
  • Example#2469 - Ejmplo de mkdir
  • Example#2470 - mkdir usando el parámetro recursive
  • Example#2471 - Subida de múltiples archivos
  • Example#2472 - Contenido de ejemplo.ini
  • Example#2473 - Ejemplo de parse_ini_file
  • Example#2474 - parse_ini_file analizando un fichero de php.ini
  • Example#2475 - Ejemplo de pathinfo
  • Example#2476 - Ejemplo de pathinfo mostrando las diferencias entre null y no utilizar extensión
  • Example#2477 - Ejemplo de pathinfo para un fichero que comienza con punto
  • Example#2478 - Ejemplo de pclose
  • Example#2479 - Ejemplo de popen
  • Example#2480 - Ejemplo de popen
  • Example#2481 - Forzar un descarga empleando readfile
  • Example#2482 - Ejemplo de readlink
  • Example#2483 - Ejemplo de realpath_cache_get
  • Example#2484 - Ejemplo de realpath_cache_size
  • Example#2485 - Ejemplo de realpath
  • Example#2486 - realpath en Windows
  • Example#2487 - Ejemplo con rename
  • Example#2488 - Ejemplo de sobrescritura con rewind
  • Example#2489 - Ejemplo de rmdir
  • Example#2490 - Ejemplo de stat
  • Example#2491 - Usar la información de stat junto con touch
  • Example#2492 - Crear un enlace simbólico
  • Example#2493 - Ejemplo de tempnam
  • Example#2494 - Ejemplo de tmpfile
  • Example#2495 - Ejemplo de touch
  • Example#2496 - touch usando el parámetro time
  • Example#2497 - Ejemplo de umask
  • Example#2498 - Uso básico de unlink
  • Example#2499 - Ejemplo de uso de inotify
  • Example#2500 - Ejemplo de setproctitle
  • Example#2501 - setthreadtitle ejemplo
  • Example#2502 - Comprueba si el administrador del sistema firmó el archivo
  • Example#2503 - Imprime los nombres de todos los atributos extendidos del archivo
  • Example#2504 - Elimina todos los atributos extendidos de un archivo
  • Example#2505 - Establece atributos extendidos en archivo .wav
  • Example#2506 - Ejemplo de xattr_supported
  • Example#2507 - Ejemplo de xdiff_file_bdiff_size
  • Example#2508 - Ejemplo de xdiff_file_bdiff
  • Example#2509 - xdiff_file_bpatch example
  • Example#2510 - Ejemplo de xdiff_file_diff_binary
  • Example#2511 - Ejemplo de xdiff_file_diff
  • Example#2512 - Ejemplo de xdiff_file_merge3
  • Example#2513 - Ejemplo de xdiff_file_patch_binary
  • Example#2514 - Ejemplo de xdiff_file_patch
  • Example#2515 - Ejemplo de parche invertido
  • Example#2516 - Ejemplo de xdiff_file_rabdiff
  • Example#2517 - Ejemplo de xdiff_string_bdiff_size
  • Example#2518 - Ejemplo de xdiff_string_diff
  • Example#2519 - Ejemplo de xdiff_string_patch
  • Example#2520 - Ejemplos de Uso de Enchant
  • Example#2521 - Listar los entornos proporcionados por el agente dado
  • Example#2522 - Un ejemplo de enchant_broker_dict_exists
  • Example#2523 - Listar todos los diccionarios disponibles para un agente
  • Example#2524 - Un ejemplo de enchant_broker_request_dict
  • Example#2525 - Añadir una palabra a un PWL
  • Example#2526 - Adding a word to a PWL
  • Example#2527 - Un ejemplo de enchant_dict_describe
  • Example#2528 - Un ejemplo de enchant_dict_quick_check
  • Example#2529 - Un ejemplo de enchant_dict_suggest
  • Example#2530 - Ejemplo de uso.
  • Example#2531 - Uso de Gender\Gender::country
  • Example#2532 - Ejemplo de bindtextdomain
  • Example#2533 - gettext-check
  • Example#2534 - Ejemplo de ngettext
  • Example#2535 - Ejemplo de iconv_get_encoding
  • Example#2536 - Ejemplo de iconv_mime_decode_headers
  • Example#2537 - Ejemplo de la función iconv_mime_decode
  • Example#2538 - Ejemplo de iconv_mime_encode
  • Example#2539 - Ejemplo de iconv_set_encoding
  • Example#2540 - Ejemplo de iconv
  • Example#2541 - Ejemplo de ob_iconv_handler
  • Example#2542 - Ejemplo usando la API procedimental
  • Example#2543 - Ejemplo usando la API orientada a objetos
  • Example#2544 - Reglas de FRENCH_COLLATION
  • Example#2545 - Reglas de ALTERNATE_HANDLING
  • Example#2546 - Reglas de CASE_FIRST
  • Example#2547 - Reglas de CASE_LEVEL
  • Example#2548 - Ejemplo de collator_asort
  • Example#2549 - Ejemplo de collator_compare
  • Example#2550 - Ejemplo de Collator::__construct
  • Example#2551 - Ejemplo de collator_create
  • Example#2552 - Ejemplo de collator_get_attribute
  • Example#2553 - Ejemplo collator_get_error_code
  • Example#2554 - Ejemplo de collator_get_error_message
  • Example#2555 - Ejemplo collator_get_locale
  • Example#2556 - Ejemplo de collator_get_sort_key
  • Example#2557 - Ejemplo de collator_get_strength
  • Example#2558 - Ejemplo de collator_set_attribute
  • Example#2559 - Ejemplo de collator_set_strength
  • Example#2560 - Ejemplo de collator_sort_with_sort_keys
  • Example#2561 - Ejemplo de collator_sort
  • Example#2562 - Ejemplo de numfmt_create
  • Example#2563 - Ejemplo de NumberFormatter::create
  • Example#2564 - Ejemplo de numfmt_format_currency
  • Example#2565 - Ejemplo orientado a objetos
  • Example#2566 - Ejemplo de numfmt_format
  • Example#2567 - Ejemplo orientado a objetos
  • Example#2568 - Ejemplo de numfmt_get_attribute
  • Example#2569 - Ejemplo orientado a objetos
  • Example#2570 - Ejemplo de numfmt_get_error_code
  • Example#2571 - Ejemplo orientado a objetos
  • Example#2572 - Ejemplo de numfmt_get_error_message
  • Example#2573 - Ejemplo orientado a objetos
  • Example#2574 - Ejemplo de numfmt_get_locale
  • Example#2575 - Ejemplo de numfmt_get_pattern
  • Example#2576 - OO example
  • Example#2577 - Ejemplo de numfmt_get_symbol
  • Example#2578 - OO example
  • Example#2579 - Ejemplo de numfmt_get_text_attribute
  • Example#2580 - OO example
  • Example#2581 - Ejemplo de numfmt_parse_currency
  • Example#2582 - OO example
  • Example#2583 - Ejemplo de numfmt_parse
  • Example#2584 - Ejemplo O.O.
  • Example#2585 - Ejemplo de numfmt_set_attribute
  • Example#2586 - OO example
  • Example#2587 - Ejemplo de numfmt_set_pattern
  • Example#2588 - OO example
  • Example#2589 - Ejemplo de numfmt_set_symbol
  • Example#2590 - OO example
  • Example#2591 - Ejemplo de numfmt_set_text_attribute
  • Example#2592 - OO example
  • Example#2593 - Ejemplo de locale_accept_from_http
  • Example#2594 - Ejemplo orientado a objetos
  • Example#2595 - Ejemplo de locale_compose
  • Example#2596 - Ejemplo orientado a objetos
  • Example#2597 - Ejemplo de locale_filter_matches
  • Example#2598 - Ejemplo orientado a objetos
  • Example#2599 - Ejepmplo de locale_get_all_variants
  • Example#2600 - Ejemplo orientado a objetos
  • Example#2601 - Ejemplo de locale_get_default
  • Example#2602 - Ejemplo orientado a objetos
  • Example#2603 - Ejemplo de locale_get_display_language
  • Example#2604 - Ejemplo orientado a objetos
  • Example#2605 - Ejemplo de locale_get_display_name
  • Example#2606 - Ejemplo orientado a objetos
  • Example#2607 - Ejemplo de locale_get_display_region
  • Example#2608 - Ejemplo orientado a objetos
  • Example#2609 - Ejemplo de locale_get_display_script
  • Example#2610 - Ejemplo orientado a objetos
  • Example#2611 - Ejemplo de locale_get_display_variant
  • Example#2612 - Ejemplo orientado a objetos
  • Example#2613 - Ejemplo de locale_get_keywords
  • Example#2614 - Ejemplo orientado a objetos
  • Example#2615 - Ejemplo de locale_get_primary_language
  • Example#2616 - Ejemplo orientado a objetos
  • Example#2617 - Ejemplo de locale_get_region
  • Example#2618 - Ejemplo orientado a objetos
  • Example#2619 - Ejemplo de locale_get_script
  • Example#2620 - Ejemplo orientado a objetos
  • Example#2621 - Ejemplo de locale_lookup
  • Example#2622 - Ejemplo orientado a objetos
  • Example#2623 - Ejemplo locale_parse
  • Example#2624 - Ejemplo orientado a objetos
  • Example#2625 - Ejemplo de locale_set_default
  • Example#2626 - Ejemplo orientado a objetos
  • Example#2627 - Normalizer::getRawDecomposition example
  • Example#2628 - Ejemplo de normalizer_is_normalized
  • Example#2629 - Ejemplo orientado a objetos
  • Example#2630 - Ejemplo de normalizer_normalize
  • Example#2631 - Ejemplo Orientado a Objetos
  • Example#2632 - Ejemplo de msgfmt_create
  • Example#2633 - Ejemplo orientado a objetos
  • Example#2634 - Ejemplo de msgfmt_format_message
  • Example#2635 - Ejemplo orientado a objetos
  • Example#2636 - Ejemplo de msgfmt_format
  • Example#2637 - Ejemplo orientado a objetos
  • Example#2638 - Ejemplo de msgfmt_get_error_code
  • Example#2639 - Ejemplo orientado a objetos
  • Example#2640 - Ejemplo de msgfmt_get_error_message
  • Example#2641 - Ejemplo orientado a objetos
  • Example#2642 - Ejemplo de msgfmt_get_locale
  • Example#2643 - Ejemplo orientado a objetos
  • Example#2644 - Ejemplo de msgfmt_get_pattern
  • Example#2645 - Ejemplo orientado a objetos
  • Example#2646 - Ejemplo de msgfmt_parse_message
  • Example#2647 - Ejemplo orientado a objetos
  • Example#2648 - Ejemplo de msgfmt_parse
  • Example#2649 - Ejemplo orientado a objetos
  • Example#2650 - Ejemplo de msgfmt_set_pattern
  • Example#2651 - Ejemplo orientado a objetos
  • Example#2652 - IntlCalendar::add
  • Example#2653 - IntlCalendar::after
  • Example#2654 - Ejemplod de IntlCalendar::clear
  • Example#2655 - IntlCalendar::createInstance
  • Example#2656 - IntlCalendar::equals
  • Example#2657 - IntlCalendar::fieldDifference
  • Example#2658 - IntlCalendar::fromDateTime
  • Example#2659 - IntlCalendar::get
  • Example#2660 - IntlCalendar::getActualMaximum
  • Example#2661 - IntlCalendar::getAvailableLocales()
  • Example#2662 - IntlCalendar::getDayOfWeekType
  • Example#2663 - IntlCalendar::getErrorCode y IntlCalendar::getErrorMessage
  • Example#2664 - IntlCalendar::getErrorMessage
  • Example#2665 - IntlCalendar::getFirstDayOfWeek
  • Example#2666 - IntlCalendar::getKeyworkValuesForLocale
  • Example#2667 - Ejemplos de máximos
  • Example#2668 - IntlCalendar::getLocale
  • Example#2669 - IntlCalendar::getMinimalDaysInFirstWeek
  • Example#2670 - IntlCalendar::getNow
  • Example#2671 - IntlCalendar::getRepeatedWallTimeOption
  • Example#2672 - IntlCalendar::getSkippedWallTimeOption
  • Example#2673 - IntlCalendar::getTime
  • Example#2674 - IntlCalendar::getTimeZone
  • Example#2675 - IntlCalendar::getType
  • Example#2676 - IntlCalendar::inDaylightTime
  • Example#2677 - IntlCalendar::isEquivalentTo
  • Example#2678 - IntlCalendar::isLenient
  • Example#2679 - IntlCalendar::isWeekend
  • Example#2680 - IntlCalendar::roll
  • Example#2681 - IntlCalendar::set
  • Example#2682 - IntlCalendar::setFirstDayOfWeek
  • Example#2683 - IntlCalendar::setTime
  • Example#2684 - IntlCalendar::setTimeZone
  • Example#2685 - IntlCalendar::toDateTime
  • Example#2686 - Ejemplo de datefmt_create
  • Example#2687 - Ejemplo orientado a objetos
  • Example#2688 - Ejemplo de datefmt_format
  • Example#2689 - Ejemplo orientado a objetos
  • Example#2690 - Con un objeto IntlCalendar
  • Example#2691 - Ejemplos de IntlDateFormatter::formatObject
  • Example#2692 - Ejemlo de datefmt_get_calendar
  • Example#2693 - Ejemplo orientado a objetos
  • Example#2694 - Ejemlo de datefmt_get_datetype
  • Example#2695 - Ejemplo orientado a objetos
  • Example#2696 - Ejemplo de datefmt_get_error_code
  • Example#2697 - Ejemplo orientado a objetos
  • Example#2698 - Ejemplo de datefmt_get_error_message
  • Example#2699 - Ejemplo orientado a objetos
  • Example#2700 - Ejemplo de datefmt_get_locale
  • Example#2701 - Ejemplo orientado a objetos
  • Example#2702 - Ejemplo de datefmt_get_pattern
  • Example#2703 - Ejemplo orientado a objetos
  • Example#2704 - Ejemplo de datefmt_get_timetype
  • Example#2705 - Ejemplo orientado a objetos
  • Example#2706 - Ejemplo de datefmt_get_timezone_id
  • Example#2707 - Ejemplo orientado a objetos
  • Example#2708 - Ejemplo IntlDateFormatter::getCalendarObject
  • Example#2709 - Ejemplos de IntlDateFormatter::getTimeZone
  • Example#2710 - Ejmplo de datefmt_is_lenient
  • Example#2711 - Ejemplo orientado a objetos
  • Example#2712 - Ejemplo de datefmt_localtime
  • Example#2713 - Ejemplo orientado a objetos
  • Example#2714 - Ejemplo orientado a objetos
  • Example#2715 - Ejemplo de datefmt_parse
  • Example#2716 - Ejemplo de datefmt_set_calendar
  • Example#2717 - Ejemplo orientado a objetos
  • Example#2718 - Ejemplo con el argumento IntlCalendar
  • Example#2719 - Ejemplo de datefmt_set_lenient
  • Example#2720 - Ejemplo orientado a objetos
  • Example#2721 - Ejemplo de datefmt_set_pattern
  • Example#2722 - Ejemplo orientado a objetos
  • Example#2723 - Ejemplos de IntlDateFormatter::setTimeZone
  • Example#2724 - Ejemplo de resourcebundle_count
  • Example#2725 - Ejemplo orientado a objetos
  • Example#2726 - Ejemplo de resourcebundle_create
  • Example#2727 - Ejemplo de ResourceBundle::create
  • Example#2728 - Ejemplo de resourcebundle_get_error_code
  • Example#2729 - Ejemplo orientado a objetos
  • Example#2730 - Ejemplo de resourcebundle_get_error_message
  • Example#2731 - Ejemplo orientado a objetos
  • Example#2732 - Ejemplo de resourcebundle_get
  • Example#2733 - Ejemplo orientado a objetos
  • Example#2734 - Ejemplo de resourcebundle_locales
  • Example#2735 - Ejemplo orientado a objetos
  • Example#2736 - Converting escaped UTF-16 code units
  • Example#2737 - Ejemplo de grapheme_extract
  • Example#2738 - Ejemplo de grapheme_stripos
  • Example#2739 - Ejemplo de grapheme_stristr
  • Example#2740 - Ejemplo de grapheme_strlen
  • Example#2741 - Ejemplo de grapheme_strpos
  • Example#2742 - Ejemplo de grapheme_strripos
  • Example#2743 - Ejemplo de grapheme_strrpos
  • Example#2744 - Ejemplo de grapheme_strstr
  • Example#2745 - Ejemplo de grapheme_substr
  • Example#2746 - Ejemplo de idn_to_ascii
  • Example#2747 - Ejemplo de idn_to_utf8
  • Example#2748 - Probar diferentes puntos de código
  • Example#2749 - Probar diferentes puntos de código
  • Example#2750 - Probar diferentes puntos de código
  • Example#2751 - Probar diferentes puntos de código
  • Example#2752 - Probar diferentes puntos de código
  • Example#2753 - Probar diferentes puntos de código
  • Example#2754 - Probar diferentes puntos de código
  • Example#2755 - Probar diferentes puntos de código
  • Example#2756 - Probar diferentes puntos de código
  • Example#2757 - Enumeración de un rango de muestra de puntos de código
  • Example#2758 - Enumeración de un rango de muestra de puntos de código
  • Example#2759 - Probar diferentes puntos de código
  • Example#2760 - Probar diferentes puntos de código
  • Example#2761 - Probar diferentes puntos de código
  • Example#2762 - Probar diferentes puntos de código
  • Example#2763 - Probar diferentes puntos de código
  • Example#2764 - Probar diferentes propiedades
  • Example#2765 - Probar diferentes propiedades
  • Example#2766 - Probar diferentes propiedades
  • Example#2767 - Probar diferentes puntos de código
  • Example#2768 - Probar diferentes propiedades
  • Example#2769 - Probar diferentes propiedades
  • Example#2770 - Probar diferentes propiedades
  • Example#2771 - Probar diferentes propiedades
  • Example#2772 - Probar diferentes propiedades
  • Example#2773 - Probar diferentes propiedades
  • Example#2774 - Probar diferentes puntos de código
  • Example#2775 - Probar diferentes puntos de código
  • Example#2776 - Probar diferentes puntos de código
  • Example#2777 - Probar diferentes puntos de código
  • Example#2778 - Probar diferentes puntos de código
  • Example#2779 - Probar diferentes puntos de código
  • Example#2780 - Probar diferentes puntos de código
  • Example#2781 - Probar diferentes puntos de código
  • Example#2782 - Probar diferentes puntos de código
  • Example#2783 - Probar diferentes puntos de código
  • Example#2784 - Probar diferentes puntos de código
  • Example#2785 - Probar diferentes puntos de código
  • Example#2786 - Probar diferentes puntos de código
  • Example#2787 - Probar diferentes puntos de código
  • Example#2788 - Probar diferentes puntos de código
  • Example#2789 - Probar diferentes puntos de código
  • Example#2790 - Probar diferentes puntos de código
  • Example#2791 - Probar diferentes puntos de código
  • Example#2792 - Probar diferentes puntos de código
  • Example#2793 - Probar diferentes puntos de código
  • Example#2794 - Probar diferentes puntos de código
  • Example#2795 - Probar diferentes puntos de código
  • Example#2796 - Probar diferentes puntos de código
  • Example#2797 - Probar diferentes puntos de código
  • Example#2798 - Probar diferentes puntos de código
  • Example#2799 - Probar diferentes puntos de código
  • Example#2800 - Probar diferentes puntos de código
  • Example#2801 - Probar diferentes puntos de código
  • Example#2802 - Probar diferentes puntos de código
  • Example#2803 - Probar diferentes puntos de código
  • Example#2804 - Probar diferentes puntos de código
  • Example#2805 - Probar diferentes puntos de código
  • Example#2806 - intl_error_name ejemplo
  • Example#2807 - intl_get_error_code ejemplo
  • Example#2808 - intl_get_error_message ejemplo
  • Example#2809 - intl_is_failure ejemplo
  • Example#2810 - Ejemplos de ajustes de php.ini
  • Example#2811 - Ajustes de php.ini para usuarios de EUC-JP
  • Example#2812 - Ajustes de php.ini para usuarios de SJIS
  • Example#2813 - Desactivar la conversión de caracteres de la entrada HTTP en php.ini
  • Example#2814 - Ejemplo de configuración de php.ini
  • Example#2815 - Ejemplo de script
  • Example#2816 - Ejemplo de mb_convert_case
  • Example#2817 - Ejemplo de mb_convert_case con texto no latino en UTF-8
  • Example#2818 - Ejemplo de mb_convert_encoding
  • Example#2819 - Ejemplo de mb_convert_kana
  • Example#2820 - Ejemplo de mb_convert_variables
  • Example#2821 - Ejemplo de convmap
  • Example#2822 - Ejemplo de convmap escapando cadenas de JavaScript
  • Example#2823 - Ejemplo de mb_detect_encoding
  • Example#2824 - Ejemplo de mb_detect_order
  • Example#2825 - Ejemplo mostrando un orden de detección inútil
  • Example#2826 - Ejemplo de mb_encode_mimeheader
  • Example#2827 - Ejemplo de convmap
  • Example#2828 - Ejemplo de mb_encode_numericentity
  • Example#2829 - Ejemplo de mb_encoding_aliases
  • Example#2830 - Ejemplo de mb_ereg_replace_callback
  • Example#2831 - mb_ereg_replace_callback usando una función anónima admitida en PHP 5.3.0 o posterior
  • Example#2832 - Ejemplo de mb_internal_encoding
  • Example#2833 - Ejemplo de mb_list_encodings
  • Example#2834 - Ejemplo de mb_output_handler
  • Example#2835 - Ejemplo de mb_preferred_mime_name
  • Example#2836 - Ejemplo de mb_strimwidth
  • Example#2837 - Ejemplo de mb_strtolower
  • Example#2838 - Ejemplo de mb_strtolower con texto no latino
  • Example#2839 - Ejemplo de mb_strtoupper
  • Example#2840 - Ejemplo de mb_strtoupper con texto UTF-8 no latino
  • Example#2841 - Ejemplo de mb_substitute_character
  • Example#2842 - Ejemplo de mb_substr_count
  • Example#2843 - pspell_add_to_personal
  • Example#2844 - Ejemplo de pspell_check
  • Example#2845 - Ejemplo de pspell_add_to_personal
  • Example#2846 - pspell_config_create
  • Example#2847 - pspell_config_ignore
  • Example#2848 - Ejemplo de pspell_config_mode
  • Example#2849 - pspell_config_personal
  • Example#2850 - pspell_config_repl
  • Example#2851 - pspell_config_runtogether
  • Example#2852 - pspell_new_config
  • Example#2853 - pspell_new_personal
  • Example#2854 - pspell_new
  • Example#2855 - pspell_add_to_personal
  • Example#2856 - pspell_store_replacement
  • Example#2857 - Ejemplo de pspell_suggest
  • Example#2858 - Ejemplo básico de recode_file
  • Example#2859 - Ejemplo básico de recode_string
  • Example#2860 - Ejemplo de exif_imagetype
  • Example#2861 - Ejemplo de exif_read_data
  • Example#2862 - Ejemplo exif_tagname
  • Example#2863 - Ejemplo de exif_thumbnail
  • Example#2864 - Creación de un PNG con PHP
  • Example#2865 - Añadir marcas de agua a imágenes usando canales alfa
  • Example#2866 - Usar imagecopymerge para crear una marca de agua translúcida
  • Example#2867 - Empleo de gd_info
  • Example#2868 - getimagesize y tipos MIME
  • Example#2869 - Ejemplo degetimagesize
  • Example#2870 - getimagesize (URL)
  • Example#2871 - getimagesize() devolviendo IPTC
  • Example#2872 - Ejemplo de getimagesizefromstring
  • Example#2873 - Ejemplo de image_type_to_extension
  • Example#2874 - Ejemplo de image_type_to_mime_type
  • Example#2875 - Ejemplo de image2wbmp
  • Example#2876 - Ejemplo de uso de imagealphablending
  • Example#2877 - Una comparación de dos líneas, una con antialias activado
  • Example#2878 - Dibujar un círculo con imagearc
  • Example#2879 - Saving a BMP file
  • Example#2880 - Ejemplo de imagechar
  • Example#2881 - Ejemplo de imagecharup
  • Example#2882 - Ejemplo de imagecolorallocate
  • Example#2883 - Ejemplo usando imagecolorallocatealpha
  • Example#2884 - Acceder a los distintos valores RGB
  • Example#2885 - Valores RGB legibles para humanos usando imagecolorsforindex
  • Example#2886 - Buscar un conjunto de colores en una imagen
  • Example#2887 - Buscar un conjunto de colores en una imagen
  • Example#2888 - Ejemplo usando imagecolorclosesthwb
  • Example#2889 - Usar imagecolordeallocate
  • Example#2890 - Obtener colores del logotipo de GD
  • Example#2891 - Obtener colores del logotipo de GD
  • Example#2892 - Ejemplo de imagecolormatch
  • Example#2893 - Usar imagecoloresolve para obtener colores de una imagen
  • Example#2894 - Usar imagecoloresolvealpha para obtener colores de una imagen
  • Example#2895 - Ejemplo de imagecolorset
  • Example#2896 - Ejemplo de imagecolorsforindex
  • Example#2897 - Obtener el número total de colores de una imagen usando imagecolorstotal
  • Example#2898 - Ejemplo de imagecolortransparent
  • Example#2899 - Poner en relieve el logotipo de PHP.net
  • Example#2900 - Borrosidad gaussiana
  • Example#2901 - Recortar el logotipo de PHP.net
  • Example#2902 - Fusionar dos copias del logotipo de PHP.net con 75% de transparencia
  • Example#2903 - Uso de imagecopymergegray
  • Example#2904 - Ejemplo sencillo
  • Example#2905 - Redimensionar una imagen proporcionalmente
  • Example#2906 - Cambiar el tamaño de una imagen
  • Example#2907 - Crear un nuevo flujo de imagen GD e imprimir una imagen.
  • Example#2908 - Convert an BMP image to a PNG image using imagecreatefrombmp
  • Example#2909 - Ejemplo de imagecreatefromgd2
  • Example#2910 - Ejemplo de imagecreatefromgd2part
  • Example#2911 - Ejemplo de imagecreatefromgd
  • Example#2912 - Ejemplo de manejar un error durante la carga de un GIF
  • Example#2913 - Ejemplo de manejar un error durante la carga de un JPEG
  • Example#2914 - Ejemplo de manejar un error durante la carga de un PNG
  • Example#2915 - Ejemplo de imagecreatefromstring
  • Example#2916 - Ejemplo de manejar un error durante la carga de un WBMP
  • Example#2917 - Convertir una image WebP a una imagen jpeg usando imagecreatefromwebp
  • Example#2918 - Convertir una imagen XBM en una imagen png usando imagecreatefromxbm
  • Example#2919 - Crear una instancia de imagen usando imagecreatefromxpm
  • Example#2920 - Crear un nuevo flujo a una imagen GD e imprimir una imagen.
  • Example#2921 - Ejemplo de imagedashedline
  • Example#2922 - Alternativa a imagedashedline
  • Example#2923 - Ejemplo de uso de imagedestroy
  • Example#2924 - Ejemplo de imageellipse
  • Example#2925 - Ejemplo de imagefill
  • Example#2926 - Crear una gráfico de tarta en 3D
  • Example#2927 - Ejemplo de imagefilledellipse
  • Example#2928 - Ejemplo de imagefilledpolygon
  • Example#2929 - Uso de imagefilledrectangle
  • Example#2930 - Rellenar una elipse con un color
  • Example#2931 - Ejemplo de escala de grises con imagefilter
  • Example#2932 - Ejemplo de brillo con imagefilter
  • Example#2933 - Ejemplo de coloración con imagefilter
  • Example#2934 - Ejemplo de inversión de color con imagefilter
  • Example#2935 - Ejemplo de pixelación con imagefilter
  • Example#2936 - Voltea una imagen verticalmente
  • Example#2937 - Voltea la imagen horizontalmente
  • Example#2938 - Usar imagefontheight con fuentes incorporadas
  • Example#2939 - Usar imagefontheight junto con imageloadfont
  • Example#2940 - Usar imagefontwidth con fuentes incorporadas
  • Example#2941 - Usar imagefontwidth junto con imageloadfont
  • Example#2942 - Ejemplo de imageftbbox
  • Example#2943 - Ejemplo de imagefttext
  • Example#2944 - Uso de imagegammacorrect
  • Example#2945 - Imprimir una imagen GD2
  • Example#2946 - Guardar una imagen GD2
  • Example#2947 - Imprimir una imagen GD
  • Example#2948 - Saving a GD image
  • Example#2949 - imagegetclip example
  • Example#2950 - Imprimir una imagen usando imagegif
  • Example#2951 - Convertir una imagen PNG en GIF usando imagegif
  • Example#2952 - Ejemplo de imagegrabscreen
  • Example#2953 - Ejemplo de imagegrabwindow
  • Example#2954 - Activar el entrelazamiento usando imageinterlace
  • Example#2955 - Simple detección de instancias de imagen de color verdadero usando imageistruecolor
  • Example#2956 - Imprimir una imagen JPEG
  • Example#2957 - Guardar una imagen JPEG
  • Example#2958 - Imprimir la imagen al 75% de calidad
  • Example#2959 - Ejemplo de imagelayereffect
  • Example#2960 - Dibujar una línea gruesa
  • Example#2961 - Ejemplo de uso de imageloadfont
  • Example#2962 - imageopenpolygon example
  • Example#2963 - Ejemplo de imagepalettecopy
  • Example#2964 - Convertir cualquier recurso de imagaen a color verdadero
  • Example#2965 - Ejemplo de imagepolygon
  • Example#2966 - Ejemplo sencillo de imagerectangle
  • Example#2967 - Setting and getting the resolution of an image
  • Example#2968 - Rotar una imagen 180 grados
  • Example#2969 - Ejemplo de imagesavealpha
  • Example#2970 - Ejemplo de imagesetbrush
  • Example#2971 - Ejemplo de imagesetinterpolation
  • Example#2972 - Ejemplo de imagesetpixel
  • Example#2973 - Ejemplo de imagesetstyle
  • Example#2974 - Ejemplo de imagesetthickness
  • Example#2975 - Ejemplo de imagesettile
  • Example#2976 - Ejemplo de imagestring
  • Example#2977 - Ejemplo de imagestringup
  • Example#2978 - Usar imagesx
  • Example#2979 - Usar imagesy
  • Example#2980 - Convertir una imagen de color verdadero en una imagen de paleta
  • Example#2981 - Ejemplo de imagettfbbox
  • Example#2982 - Ejemplo de imagettftext
  • Example#2983 - Comprobar el soporte para PNG
  • Example#2984 - Imprimir una imagen WBMP
  • Example#2985 - Guardar una imagen WBMP
  • Example#2986 - Imprimir la imagen con un primer plano diferente
  • Example#2987 - Guardar un fichero WebP
  • Example#2988 - Guardar un fichero XBM
  • Example#2989 - Guardar un fichero XBM con un color de primer plano diferente
  • Example#2990 - Incluir información IPTC a un JPEG
  • Example#2991 - iptcparse() usado junto con getimagesize
  • Example#2992 - Ejemplo de jpeg2wbmp
  • Example#2993 - Ejmplo de png2wbmp
  • Example#2994 - Ejemplo de Gmagick
  • Example#2995 - Ejemplo de Gmagick::despeckleimage
  • Example#2996 - Gmagick::setCompressionQuality
  • Example#2997 - Crear una miniatura con Imagick
  • Example#2998 - Hacer una miniatura de todos los archivos JPG de un directorio
  • Example#2999 - Crear un reflejo de una imagen
  • Example#3000 - Rellenar un texto con un gradiente
  • Example#3001 - Leer una imágen GIF y redimensionar todos los fotogramas
  • Example#3002 - Crear un logo de PHP
  • Example#3003 - Usar Imagick::adaptiveBlurImage:
  • Example#3004 - Usar Imagick::adaptiveResizeImage
  • Example#3005 - Un ejemplo de Imagick::adaptiveSharpenImage
  • Example#3006 - Imagick::adaptiveThresholdImage
  • Example#3007 - Imagick::addNoiseImage
  • Example#3008 - Imagick::affineTransformImage
  • Example#3009 - Usar Imagick::annotateImage:
  • Example#3010 - Ejemplo de Imagick::appendImages
  • Example#3011 - Imagick::autoLevelImage
  • Example#3012 - Imagick::blackThresholdImage
  • Example#3013 - Imagick::blueShiftImage
  • Example#3014 - Usar Imagick::blurImage:
  • Example#3015 - Imagick::borderImage
  • Example#3016 - Imagick::brightnessContrastImage
  • Example#3017 - Imagick::charcoalImage
  • Example#3018 - Usar Imagick::chopImage:
  • Example#3019 - Clonación de un objeto Imagick en diferentes versiones de imagick
  • Example#3020 - Usar Imagick::clutImage:
  • Example#3021 - Imagick::colorizeImage
  • Example#3022 - Imagick::colorMatrixImage
  • Example#3023 - Usar Imagick::commentImage:
  • Example#3024 - Usar Imagick::compareImageLayers
  • Example#3025 - Uso de Imagick::compareImages:
  • Example#3026 - Empleo de Imagick::compositeImage:
  • Example#3027 - Imagick::contrastImage
  • Example#3028 - Imagick::convolveImage
  • Example#3029 - Imagick::cropImage
  • Example#3030 - Imagick::deskewImage
  • Example#3031 - Imagick::despeckleImage
  • Example#3032 - Usar Imagick::distortImage:
  • Example#3033 - Imagick::edgeImage
  • Example#3034 - Imagick::embossImage
  • Example#3035 - Imagick::enhanceImage
  • Example#3036 - Imagick::equalizeImage
  • Example#3037 - Usando Imagick::evaluateImage
  • Example#3038 - Usar Imagick::exportImagePixels
  • Example#3039 - Imagick::filter
  • Example#3040 - Imagick::flipImage
  • Example#3041 - Ejemplo de Imagick::floodfillPaintImage
  • Example#3042 - Imagick::flopImage
  • Example#3043 - Imagick::forwardFourierTransformImage
  • Example#3044 - Imagick::frameImage
  • Example#3045 - Crear un degradado sinusoide
  • Example#3046 - Crear un degradado desde el polinomio (4x^2 - 4x + 1)
  • Example#3047 - Crear un degradao complejo a partir del polinomio (4x^2 - 4x^2 + 1) modulado por un degradao sinusoide
  • Example#3048 - Imagick::fxImage
  • Example#3049 - Imagick::gammaImage
  • Example#3050 - Imagick::gaussianBlurImage
  • Example#3051 - Imagick::getImageGeometry
  • Example#3052 - Generates Imagick::getImageHistogram
  • Example#3053 - Usar Imagick::getImageLength:
  • Example#3054 - Usar Imagick::getImageProperties:
  • Example#3055 - Usando Imagick::getImageProperty:
  • Example#3056 - Usar Imagick::getIteratorIndex:
  • Example#3057 - Imagick::getPixelIterator
  • Example#3058 - Ejemplo de Imagick::getPixelRegionIterator
  • Example#3059 - Imagick::haldClutImage
  • Example#3060 - Imagick::identifyFormat
  • Example#3061 - Ejemplo de formato resultante
  • Example#3062 - Imagick::implodeImage
  • Example#3063 - Ejemplo deImagick::importImagePixels
  • Example#3064 - Imagick::levelImage
  • Example#3065 - Imagick::linearStretchImage
  • Example#3066 - Imagick::magnifyImage
  • Example#3067 - Imagick::medianFilterImage
  • Example#3068 - Imagick::mergeImageLayers
  • Example#3069 - Imagick::modulateImage
  • Example#3070 - Convolve Imagick::morphology
  • Example#3071 - Correlate Imagick::morphology
  • Example#3072 - Erode Imagick::morphology
  • Example#3073 - Erode Intensity Imagick::morphology
  • Example#3074 - Dilate Imagick::morphology
  • Example#3075 - Dilate intensity Imagick::morphology
  • Example#3076 - Distance with Chebyshev kernel Imagick::morphology
  • Example#3077 - Distance with Manhattan kernel Imagick::morphology
  • Example#3078 - Distance with ocatagonal kernel Imagick::morphology
  • Example#3079 - Distance with Euclidean kernel Imagick::morphology
  • Example#3080 - Edge Imagick::morphology
  • Example#3081 - Open Imagick::morphology
  • Example#3082 - Open intensity Imagick::morphology
  • Example#3083 - Close Imagick::morphology
  • Example#3084 - Close Intensity Imagick::morphology
  • Example#3085 - Smooth Imagick::morphology
  • Example#3086 - Edge in Imagick::morphology
  • Example#3087 - Edge out Imagick::morphology
  • Example#3088 - 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#3089 - 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#3090 - Hit and Miss Imagick::morphology
  • Example#3091 - Thinning Imagick::morphology
  • Example#3092 - Thicken Imagick::morphology
  • Example#3093 - Thick to generate a convex hull Imagick::morphology
  • Example#3094 - Iterative morphology Imagick::morphology
  • Example#3095 - Helper functon to get an image silhouette Imagick::morphology
  • Example#3096 - Imagick::motionBlurImage
  • Example#3097 - Imagick::negateImage
  • Example#3098 - Usar Imagick::newImage:
  • Example#3099 - Imagick::newPseudoImage
  • Example#3100 - Imagick::normalizeImage
  • Example#3101 - Imagick::oilPaintImage
  • Example#3102 - Usar Imagick::optimizeImageLayers
  • Example#3103 - Imagick::orderedPosterizeImage
  • Example#3104 - Usar Imagick::pingImageBlob
  • Example#3105 - Usar Imagick::pingImageFile
  • Example#3106 - Un ejemplo de Imagick::polaroidImage
  • Example#3107 - Imagick::posterizeImage
  • Example#3108 - Imagick::quantizeImage
  • Example#3109 - Usar Imagick::queryFontMetrics:
  • Example#3110 - Imagick::queryFonts
  • Example#3111 - Imagick::queryFormats
  • Example#3112 - Imagick::radialBlurImage
  • Example#3113 - Imagick::raiseImage
  • Example#3114 - Imagick::randomThresholdImage
  • Example#3115 - Imagick::readImageBlob
  • Example#3116 - Imagick::recolorImage
  • Example#3117 - Imagick::reduceNoiseImage
  • Example#3118 - Imagick::resampleImage
  • Example#3119 - Imagick::resizeImage
  • Example#3120 - Imagick::rollImage
  • Example#3121 - Imagick::rotateImage
  • Example#3122 - Imagick::rotationalBlurImage
  • Example#3123 - Usar Imagick::roundCorners:
  • Example#3124 - Imagick::scaleImage
  • Example#3125 - Imagick::segmentImage
  • Example#3126 - Imagick::selectiveBlurImage
  • Example#3127 - Imagick::separateImageChannel
  • Example#3128 - Imagick::sepiaToneImage
  • Example#3129 - Imagick::setCompressionQuality
  • Example#3130 - Un ejemplo de Imagick::setFont
  • Example#3131 - Un ejemplo de Imagick::setImage
  • Example#3132 - Imagick::setImageArtifact
  • Example#3133 - Imagick::setImageBias
  • Example#3134 - Imagick::setImageClipMask
  • Example#3135 - Imagick::setImageCompressionQuality
  • Example#3136 - Modificar un GIF animado con Imagick::setImageDelay
  • Example#3137 - Uso básido ce Imagick::setImageIterations
  • Example#3138 - Un ejemplo de Imagick::setImageOpacity
  • Example#3139 - Imagick::setImageOrientation
  • Example#3140 - Usar Imagick::setImageProperty:
  • Example#3141 - Imagick::setImageResolution
  • Example#3142 - Modificar un GIF animado con Imagick::setImageTicksPerSecond
  • Example#3143 - Usar Imagick::setIteratorIndex:
  • Example#3144 - Attempt to reach '$extent' sizeImagick::setOption
  • Example#3145 - Imagick::setOption
  • Example#3146 - Imagick::setOption
  • Example#3147 - Un ejemplo de Imagick::setPointSize
  • Example#3148 - Imagick::setProgressMonitor
  • Example#3149 - Imagick::setSamplingFactors
  • Example#3150 - Imagick::shadeImage
  • Example#3151 - Imagick::shadowImage
  • Example#3152 - Imagick::sharpenImage
  • Example#3153 - Imagick::shaveImage
  • Example#3154 - Imagick::shearImage
  • Example#3155 - Crear una imagen degradada usando Imagick::sigmoidalContrastImage apta para mezclar dos imágenes suavemente, con la mezcla definida por $contraste y el $punto_medio
  • Example#3156 - Imagick::sketchImage
  • Example#3157 - Imagick::smushImages
  • Example#3158 - Imagick::solarizeImage
  • Example#3159 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#3160 - SPARSECOLORMETHOD_BILINEAR Imagick::sparseColorImage
  • Example#3161 - SPARSECOLORMETHOD_SPEPARDS Imagick::sparseColorImage
  • Example#3162 - SPARSECOLORMETHOD_VORONOI Imagick::sparseColorImage
  • Example#3163 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#3164 - createGradientImage is used by other examples. Imagick::sparseColorImage
  • Example#3165 - Imagick::spliceImage
  • Example#3166 - Imagick::spreadImage
  • Example#3167 - Imagick::statisticImage
  • Example#3168 - Imagick::subImageMatch
  • Example#3169 - Imagick::swirlImage
  • Example#3170 - Imagick::textureImage
  • Example#3171 - Imagick::thresholdImage
  • Example#3172 - Imagick::thumbnailImage
  • Example#3173 - Imagick::tintImage
  • Example#3174 - Usar Imagick::transformImage:
  • Example#3175 - Ejemplo de Imagick::transformImageColorspace
  • Example#3176 - Imagick::transformImageColorspace
  • Example#3177 - Imagick::transparentPaintImage
  • Example#3178 - Imagick::transposeImage
  • Example#3179 - Imagick::transverseImage
  • Example#3180 - Usar Imagick::trimImage:
  • Example#3181 - Imagick::uniqueImageColors
  • Example#3182 - Imagick::unsharpMaskImage
  • Example#3183 - Imagick::vignetteImage
  • Example#3184 - WaveImage can be quite slow Imagick::waveImage
  • Example#3185 - Imagick::whiteThresholdImage
  • Example#3186 - ImagickDraw::affine
  • Example#3187 - ImagickDraw::arc
  • Example#3188 - ImagickDraw::bezier
  • Example#3189 - ImagickDraw::circle
  • Example#3190 - ImagickDraw::composite
  • Example#3191 - ImagickDraw::ellipse
  • Example#3192 - ImagickDraw::line
  • Example#3193 - ImagickDraw::matte
  • Example#3194 - ImagickDraw::pathCurveToQuadraticBezierAbsolute
  • Example#3195 - ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
  • Example#3196 - ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
  • Example#3197 - ImagickDraw::pathStart
  • Example#3198 - ImagickDraw::point
  • Example#3199 - ImagickDraw::polygon
  • Example#3200 - ImagickDraw::polyline
  • Example#3201 - ImagickDraw::popDefs
  • Example#3202 - ImagickDraw::push
  • Example#3203 - ImagickDraw::pushPattern
  • Example#3204 - ImagickDraw::rectangle
  • Example#3205 - ImagickDraw::rotate
  • Example#3206 - ImagickDraw::roundRectangle
  • Example#3207 - ImagickDraw::scale
  • Example#3208 - ImagickDraw::setClipPath
  • Example#3209 - ImagickDraw::setClipRule
  • Example#3210 - ImagickDraw::setClipUnits
  • Example#3211 - ImagickDraw::setFillAlpha
  • Example#3212 - ImagickDraw::setFillColor
  • Example#3213 - ImagickDraw::setFillOpacity
  • Example#3214 - ImagickDraw::setFillRule
  • Example#3215 - ImagickDraw::setFont
  • Example#3216 - ImagickDraw::setFontFamily
  • Example#3217 - ImagickDraw::setFontSize
  • Example#3218 - ImagickDraw::setFontStretch
  • Example#3219 - ImagickDraw::setFontStyle
  • Example#3220 - ImagickDraw::setFontWeight
  • Example#3221 - ImagickDraw::setGravity
  • Example#3222 - ImagickDraw::setStrokeAlpha
  • Example#3223 - ImagickDraw::setStrokeAntialias
  • Example#3224 - ImagickDraw::setStrokeColor
  • Example#3225 - ImagickDraw::setStrokeDashArray
  • Example#3226 - ImagickDraw::setStrokeDashOffset
  • Example#3227 - ImagickDraw::setStrokeLineCap
  • Example#3228 - ImagickDraw::setStrokeLineJoin
  • Example#3229 - ImagickDraw::setStrokeMiterLimit
  • Example#3230 - ImagickDraw::setStrokeOpacity
  • Example#3231 - ImagickDraw::setStrokeWidth
  • Example#3232 - ImagickDraw::setTextAlignment
  • Example#3233 - ImagickDraw::setTextAntialias
  • Example#3234 - ImagickDraw::setTextDecoration
  • Example#3235 - ImagickDraw::setTextUnderColor
  • Example#3236 - ImagickDraw::setVectorGraphics
  • Example#3237 - ImagickDraw::setViewBox
  • Example#3238 - ImagickDraw::skewX
  • Example#3239 - ImagickDraw::skewY
  • Example#3240 - ImagickDraw::translate
  • Example#3241 - ImagickPixel::construct
  • Example#3242 - Uso básico de Imagick::getColor
  • Example#3243 - Uso básico de Imagick::getColorAsString
  • Example#3244 - getColorCount de ImagickPixel
  • Example#3245 - Uso básico de Imagick::getColorValue
  • Example#3246 - ImagickPixel::getColorValueQuantum
  • Example#3247 - Uso básico de Imagick::getHSL
  • Example#3248 - ImagickPixel::isSimilar
  • Example#3249 - ImagickPixel::setColor
  • Example#3250 - Uso básico de Imagick::setColorValue
  • Example#3251 - ImagickPixel::setColorValueQuantum
  • Example#3252 - Usar ImagickPixel::setHSL para modificar un color
  • Example#3253 - ImagickPixelIterator::clear
  • Example#3254 - ImagickPixelIterator::construct
  • Example#3255 - ImagickPixelIterator::getNextIteratorRow
  • Example#3256 - ImagickPixelIterator::resetIterator
  • Example#3257 - ImagickPixelIterator::setIteratorRow
  • Example#3258 - ImagickKernel::addKernel
  • Example#3259 - ImagickKernel::addUnityKernel
  • Example#3260 - ImagickKernel::addUnityKernel
  • Example#3261 - ImagickKernel::fromBuiltin
  • Example#3262 - ImagickKernel::fromMatrix
  • Example#3263 - ImagickKernel::getMatrix
  • Example#3264 - ImagickKernel::scale
  • Example#3265 - ImagickKernel::separate
  • Example#3266 - Ejemplo de imap_append
  • Example#3267 - Ejemplo de imap_check
  • Example#3268 - Ejemplo de imap_createmailbox
  • Example#3269 - Ejemplo de imap_delete
  • Example#3270 - Ejemplo de imap_fetch_overview
  • Example#3271 - Ejemplo de imap_gc
  • Example#3272 - Ejemplo de imap_get_quota
  • Example#3273 - Ejemplo de imap_get_quota 4.3 o superiro
  • Example#3274 - Ejemplo de imap_get_quotaroot
  • Example#3275 - Ejemplo de imap_getacl
  • Example#3276 - Ejemplo de imap_getmailboxes
  • Example#3277 - Ejemplo de imap_list
  • Example#3278 - Ejemplo de imap_mail_compose
  • Example#3279 - Ejemplo de imap_mailboxmsginfo
  • Example#3280 - Ejemplo de imap_mime_header_decode
  • Example#3281 - Diferentes usos de imap_open
  • Example#3282 - Ejemplo de imap_open
  • Example#3283 - Ejemplo de imap_ping
  • Example#3284 - Ejemplo de imap_reopen
  • Example#3285 - Ejemplo de imap_rfc822_parse_adrlist
  • Example#3286 - Ejemplo de imap_rfc822_write_address
  • Example#3287 - imap_search example
  • Example#3288 - Ejemplo de imap_set_quota
  • Example#3289 - Ejemplo de imap_setflag_full
  • Example#3290 - Ejemplo de imap_status
  • Example#3291 - Ejemplo de imap_thread
  • Example#3292 - Ejemplo de imap_timeout
  • Example#3293 - Calcular el hash de un usuario suscriptor.
  • Example#3294 - Enviar un correo.
  • Example#3295 - Enviar un correo con cabeceras extra.
  • Example#3296 - Enviar un correo con parámetros de línea de comando adicionales.
  • Example#3297 - Envío de un correo HTML
  • Example#3298 - Ejemplo de mailparse_determine_best_xfer_encoding
  • Example#3299 - Ejemplo de mailparse_rfc822_parse_addresses
  • Example#3300 - Ejemplo de mailparse_stream_encode
  • Example#3301 - Ejemplo de mailparse_uudecode_all
  • Example#3302 - Ejemplo bcadd
  • Example#3303 - Ejemplobccomp
  • Example#3304 - Ejemplo bcdiv
  • Example#3305 - Ejemplo bcmod
  • Example#3306 - Ejemplo bcmul
  • Example#3307 - Ejemplo bcpow
  • Example#3308 - Ejemplo de escalado de bcpow
  • Example#3309 - Ejemplo bcscale
  • Example#3310 - Ejemplo bcsqrt
  • Example#3311 - Ejemplo bcsub
  • Example#3312 - Función factorial usando GMP
  • Example#3313 - Ejemplo de gmp_abs
  • Example#3314 - Ejemplo de gmp_add
  • Example#3315 - Ejemplo de gmp_and
  • Example#3316 - Ejemplo de gmp_clrbit
  • Example#3317 - gmp_cmp example
  • Example#3318 - Ejemplo de gmp_com
  • Example#3319 - Ejemplo de gmp_div_q
  • Example#3320 - División de números GMP
  • Example#3321 - gmp_div_r example
  • Example#3322 - Ejemplo degmp_divexact
  • Example#3323 - Ejemplo de gmp_export
  • Example#3324 - Ejemplo degmp_fact
  • Example#3325 - Ejemplo degmp_gcd
  • Example#3326 - Resolver ecuaciones de diofántica lineal
  • Example#3327 - Ejemplo degmp_hamdist
  • Example#3328 - Ejemplo de gmp_import
  • Example#3329 - Creación de un número GMP
  • Example#3330 - Ejemplo de gmp_intval
  • Example#3331 - Ejemplo de gmp_invert
  • Example#3332 - Ejemplo de gmp_jacobi
  • Example#3333 - Ejemplo de gmp_legendre
  • Example#3334 - Ejemplo de gmp_mod
  • Example#3335 - Ejemplo degmp_mul
  • Example#3336 - Ejemplo degmp_neg
  • Example#3337 - Ejemplo de gmp_nextprime
  • Example#3338 - Ejemplo de gmp_or
  • Example#3339 - Ejemplo de gmp_perfect_square
  • Example#3340 - Ejemplo de gmp_popcount
  • Example#3341 - Ejemplo de gmp_pow
  • Example#3342 - gmp_powm example
  • Example#3343 - Ejemplo de gmp_prob_prime
  • Example#3344 - Ejemplo de gmp_random_bits
  • Example#3345 - Ejemplo de gmp_random_range
  • Example#3346 - Ejemplo de gmp_random_seed
  • Example#3347 - Ejemplo de gmp_random
  • Example#3348 - Ejemplo de gmp_scan0
  • Example#3349 - Ejemplo de gmp_scan1
  • Example#3350 - Ejemplo de gmp_setbit - índice 0
  • Example#3351 - Ejemplo de gmp_setbit - índice 1
  • Example#3352 - Ejemplo de gmp_setbit - limpiar un bit
  • Example#3353 - Ejemplo de gmp_sign
  • Example#3354 - Ejemplo de gmp_sqrt
  • Example#3355 - Ejemplo degmp_sqrtrem
  • Example#3356 - Converting a GMP number to a string
  • Example#3357 - Ejemplo de gmp_sub
  • Example#3358 - Ejemplo degmp_testbit
  • Example#3359 - Ejemplo degmp_xor
  • Example#3360 - Ejemplo de abs
  • Example#3361 - Ejemplo de base_convert
  • Example#3362 - Ejemplo de bindec
  • Example#3363 - bindec interpreta las entradas como enteros sin signo
  • Example#3364 - Ejemplo de ceil
  • Example#3365 - Ejemplo de cos
  • Example#3366 - Ejemplo de decbin
  • Example#3367 - Ejemplo dechex
  • Example#3368 - Ejemplo de dechex con números enteros grandes
  • Example#3369 - Ejemplo de decoct
  • Example#3370 - Ejemplo de deg2rad
  • Example#3371 - Ejemplo de exp
  • Example#3372 - Using fdiv
  • Example#3373 - Ejemplo de floor
  • Example#3374 - Uso de fmod
  • Example#3375 - Ejemplo de hexdec
  • Example#3376 - Ejemplo de intdiv
  • Example#3377 - Ejemplo de is_nan
  • Example#3378 - Ejemplos de uso de max
  • Example#3379 - Ejemplos de uso de min
  • Example#3380 - Calcular un número de coma flotante aleatorio
  • Example#3381 - Ejemplo de mt_rand
  • Example#3382 - Ejemplo de mt_srand
  • Example#3383 - Ejemplo de octdec
  • Example#3384 - Ejemplo de pi
  • Example#3385 - Algunos ejemplos de pow
  • Example#3386 - Ejemplo de rad2deg
  • Example#3387 - Ejemplo de rand
  • Example#3388 - Ejemplos de round
  • Example#3389 - Ejemplos de mode
  • Example#3390 - Ejemplos de mode con precisión
  • Example#3391 - Ejemplo de sin
  • Example#3392 - Ejemplo de sqrt
  • Example#3393 - Ejemplo de srand
  • Example#3394 - Ejemplo de tan
  • Example#3395 - Evaluar un documento FDF
  • Example#3396 - Añadiendo código JavaScript a un FDF
  • Example#3397 - Poblar un documento PDF
  • Example#3398 - Guardando un fichero subido por FDF
  • Example#3399 - Detección de todos los nombres de campo en un FDF
  • Example#3400 - Accediendo a los datos de un formulario
  • Example#3401 - Acceso a datos de formulario
  • Example#3402 - Salvando un FDF como string
  • Example#3403 - Paso de datos FDF a un segundo formulario
  • Example#3404 - Ejemplo de firma (clearsign) gnupg mediante funciones
  • Example#3405 - Ejemplo de firma gnupg (clearsign) mediante orientación a objetos
  • Example#3406 - keylistiterator
  • Example#3407 - Ejemplo de gnupg_adddecryptkey mediante funciones
  • Example#3408 - Ejemplo de gnupg_adddecryptkey mediante OO
  • Example#3409 - Ejemplo de gnupg_addencryptkey mediante funciones
  • Example#3410 - Ejemplo de gnupg_addencryptkey mediante OO
  • Example#3411 - Ejemplo de gnupg_addsignkey mediante funciones
  • Example#3412 - Ejemplo de gnupg_addsignkey mediante OO
  • Example#3413 - Ejemplo de gnupg_cleardecryptkeys mediante funciones
  • Example#3414 - Ejemplo de gnupg_cleardecryptkeys mediante OO
  • Example#3415 - Ejemplo de gnupg_clearencryptkeys mediante funciones
  • Example#3416 - Ejemplo de gnupg_clearencryptkeys mediante OO
  • Example#3417 - Ejemplo de gnupg_clearsignkeys mediante funciones
  • Example#3418 - Ejemplo de gnupg_clearsignkeys mediante OO
  • Example#3419 - Ejemplo de gnupg_decrypt mediante funciones
  • Example#3420 - Ejemplo de gnupg_encrypt mediante OO
  • Example#3421 - Ejemplo de gnupg_decryptverify mediante funciones
  • Example#3422 - Ejemplo de gnupg_decryptverify mediante OO
  • Example#3423 - Ejemplo de gnupg_encrypt mediante funciones
  • Example#3424 - Ejemplo de gnupg_encrypt mediante OO
  • Example#3425 - Ejemplo de gnupg_encryptsign mediante funciones
  • Example#3426 - Ejemplo de gnupg_encryptsign mediante OO
  • Example#3427 - Ejemplo de gnupg_export mediante funciones
  • Example#3428 - Ejemplo de gnupg_export mediante OO
  • Example#3429 - Ejemplo de gnupg_geterror mediante funciones
  • Example#3430 - Ejemplo de gnupg_geterror mediante OO
  • Example#3431 - Ejemplo de gnupg_getprotocol mediante funciones
  • Example#3432 - Ejemplo de gnupg_getprotocol mediante
  • Example#3433 - Ejemplo de gnupg_import mediante funciones
  • Example#3434 - Ejemplo de gnupg_import mediante OO
  • Example#3435 - Ejemplo de gnupg_init mediante funciones
  • Example#3436 - Ejemplo del inicializador gnupg mediante OO
  • Example#3437 - Ejemplo de gnupg_keyinfo mediante funciones
  • Example#3438 - Ejemplo de gnupg_keyinfo mediante OO
  • Example#3439 - Ejemplo de gnupg_setarmor mediante funciones
  • Example#3440 - Ejemplo de gnupg_setarmor mediante OO
  • Example#3441 - Pejemplo de gnupg_seterrormode mediante funciones
  • Example#3442 - Ejemplo de gnupg_seterrormode mediante OO
  • Example#3443 - Ejemplo de gnupg_setsignmode mediante funciones
  • Example#3444 - Ejemplo de gnupg_setsignmode mediante OO
  • Example#3445 - Ejemplo de gnupg_sign mediante funciones
  • Example#3446 - Ejemplo de gnupg_sign mediante OO
  • Example#3447 - Ejemplo de gnupg_verify mediante funciones
  • Example#3448 - Ejemplo de gnupg_verify mediante OO
  • Example#3449 - Crear y usar un patrón
  • Example#3450 - Crear y utilizar una plantilla
  • Example#3451 - Particionar silábicamente un texto
  • Example#3452 - Dibujar un rectángulo
  • Example#3453 - Crear y utilizar un color directo
  • Example#3454 - Rotación del sistema de coordenadas
  • Example#3455 - Colocar texto en una posición dada
  • Example#3456 - Dibujar una línea discontinua
  • Example#3457 - Traslación del sistema de coordenadas
  • Example#3458 - A rpmdbinfo example
  • Example#3459 - Searching for the package owning a file
  • Example#3460 - A rpminfo example
  • Example#3461 - ejemplo
  • Example#3462 - ejemplo
  • Example#3463 - ejemplo
  • Example#3464 - ejemplo
  • Example#3465 - ejemplo
  • Example#3466 - ejemplo
  • Example#3467 - ejemplo
  • Example#3468 - ejemplo
  • Example#3469 - ejemplo
  • Example#3470 - ejemplo
  • Example#3471 - ejemplo
  • Example#3472 - ejemplo
  • Example#3473 - ejemplo
  • Example#3474 - ejemplo
  • Example#3475 - ejemplo
  • Example#3476 - ejemplo
  • Example#3477 - ejemplo
  • Example#3478 - ejemplo
  • Example#3479 - ejemplo
  • Example#3480 - Incorrect requests
  • Example#3481 - Llamar a una petición desde una llamada de retorno de petición
  • Example#3482 - Llamar a una petición desde una llamada de retorno de petición
  • Example#3483 - Usar eio con libevent
  • Example#3484 - Cancelar una petición
  • Example#3485 - Llamar a eio_chmod
  • Example#3486 - Realizar una petición personalizada
  • Example#3487 - Agrupar peticiones
  • Example#3488 - Emplear eio con la extensión libevent
  • Example#3489 - Emplear eio con la extensión event
  • Example#3490 - Ejemplo de eio_cancel
  • Example#3491 - Ejemplo de eio_custom
  • Example#3492 - Ejemplo de eio_event_loop
  • Example#3493 - Ejemplo de eio_lstat
  • Example#3494 - Usar eio con libevent
  • Example#3495 - Agrupar peticiones
  • Example#3496 - Ejemplo de eio_grp
  • Example#3497 - Ejemplo de eio_link
  • Example#3498 - Ejemplo de eio_lstat
  • Example#3499 - Ejemplo de eio_mkdir
  • Example#3500 - Ejemplo de eio_mknod
  • Example#3501 - Ejepmlo de eio_nreqs
  • Example#3502 - Ejemplo de eio_open
  • Example#3503 - Ejemplo de eio_poll
  • Example#3504 - Ejemplo de eio_read
  • Example#3505 - eio_readdir example
  • Example#3506 - Ejemplo de eio_readlink
  • Example#3507 - Ejemplo deeio_realpath
  • Example#3508 - Ejemplo de eio_rename
  • Example#3509 - Ejemplo de eio_rmdir
  • Example#3510 - Ejemplo de eio_stat
  • Example#3511 - Ejemplo de eio_statvfs
  • Example#3512 - eio_symlink example
  • Example#3513 - Simple timers
  • Example#3514 - Periodic timer. Tick each 10.5 seconds
  • Example#3515 - Periodic timer. Use reschedule callback
  • Example#3516 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3517 - Wait until STDIN is readable
  • Example#3518 - Use some async I/O to access a socket
  • Example#3519 - Embedding one loop into another
  • Example#3520 - Embedding loop created with kqueue backend into the default loop
  • Example#3521 - Handle SIGTERM signal
  • Example#3522 - Monitor changes of /var/log/messages
  • Example#3523 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3524 - Process status changes
  • Example#3525 - Using reschedule callback
  • Example#3526 - Embedding loop created with kqueue backend into the default loop
  • Example#3527 - Embedding one loop into another
  • Example#3528 - Embedding loop created with kqueue backend into the default loop
  • Example#3529 - Embedding loop created with kqueue backend into the default loop
  • Example#3530 - Periodic timer. Use reschedule callback
  • Example#3531 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3532 - Hourly watcher
  • Example#3533 - Manejar la señal SIGTERM
  • Example#3534 - Monitor changes of /var/log/messages
  • Example#3535 - Monitor changes of /var/log/messages
  • Example#3536 - Simple timers
  • Example#3537 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3538 - Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.
  • Example#3539 - Ejemplo de uso de Expect
  • Example#3540 - Otro ejemplo de uso de Expect
  • Example#3541 - Ejemplo de expect_expectl
  • Example#3542 - Ejemplo de expect_popen
  • Example#3543 - Process Control Example
  • Example#3544 - pcntl_fork example
  • Example#3545 - pcntl_signal_dispatch example
  • Example#3546 - pcntl_signal_get_handler example
  • Example#3547 - pcntl_signal example
  • Example#3548 - pcntl_sigprocmask example
  • Example#3549 - pcntl_sigwaitinfo example
  • Example#3550 - Ejemplo de posix_access
  • Example#3551 - Ejemplo de posix_ctermid
  • Example#3552 - Ejemplo de posix_get_last_error
  • Example#3553 - Ejemplo de posix_getcwd
  • Example#3554 - Ejemplo de posix_getegid
  • Example#3555 - Ejemplo de posix_geteuid
  • Example#3556 - Ejemplo de posix_getgid
  • Example#3557 - Ejemplo de uso deposix_getgrgid
  • Example#3558 - Ejemplo de uso de posix_getgrnam
  • Example#3559 - Ejemplo de uso de posix_getgroups
  • Example#3560 - Ejemplo de uso de posix_getlogin
  • Example#3561 - Ejemplo de uso de posix_getpgid
  • Example#3562 - Ejemplo de uso de posix_getpid
  • Example#3563 - Ejemplo de uso de posix_getppid
  • Example#3564 - Ejemplo de uso de posix_getpwnam
  • Example#3565 - Ejemplo de uso de posix_getpwuid
  • Example#3566 - Ejemplo de uso de posix_getrlimit
  • Example#3567 - Ejemplo de uso de posix_getsid
  • Example#3568 - Ejemplo de uso de posix_getuid
  • Example#3569 - Un ejemplo de posix_mknod
  • Example#3570 - Ejemplo de posix_setegid
  • Example#3571 - Ejemplo de posix_setgid
  • Example#3572 - Ejemplo de posix_setuid
  • Example#3573 - Ejemplo de posix_strerror
  • Example#3574 - Ejemplo de uso de posix_times
  • Example#3575 - Ejemplo de uso de posix_uname
  • Example#3576 - Ejemplo de escapeshellarg
  • Example#3577 - Ejemplo de escapeshellcmd
  • Example#3578 - Un ejemplo de exec
  • Example#3579 - Ejemplo de proc_open
  • Example#3580 - Un ejemplo de shell_exec
  • Example#3581 - Ejemplo de system
  • Example#3582 - Example showing Future as return value
  • Example#3583 - Example showing Future as synchronization point
  • Example#3584 - Fetch a chunk of the property table
  • Example#3585 - Counting the properties of an object
  • Example#3586 - Runtime inheritance
  • Example#3587 - Thread safe objects from closures
  • Example#3588 - Detecting fatal errors in Threads
  • Example#3589 - Detect the state of the referenced object
  • Example#3590 - Detect the state of the referenced object
  • Example#3591 - Detect the state of the referenced object
  • Example#3592 - Locking Object Properties
  • Example#3593 - Merging into the property table of a threaded object
  • Example#3594 - Notifications and Waiting
  • Example#3595 - Notifications and Waiting
  • Example#3596 - Popping the last item from the property table of a threaded object
  • Example#3597 - Shifting the first item from the property table of a threaded object
  • Example#3598 - Synchronizing
  • Example#3599 - Locking the property table of a threaded object
  • Example#3600 - Notifications and Waiting
  • Example#3601 - Devuelve la identificación del hilo o proceso que el hilo referenciado creó.
  • Example#3602 - Devuelve el hilo que se está ejecutando
  • Example#3603 - Return the identity of the currently executing Thread
  • Example#3604 - Return the identity of the referenced Thread
  • Example#3605 - Execute in the global scope
  • Example#3606 - Detect the state of the referenced Thread
  • Example#3607 - Tell if the referenced Thread was started
  • Example#3608 - Join with the referenced Thread
  • Example#3609 - Termina el hilo referenciado
  • Example#3610 - Starting Threads
  • Example#3611 - A basic example of Worker::collect
  • Example#3612 - A basic example of Worker::getStacked
  • Example#3613 - Detect the state of a worker
  • Example#3614 - Detect the state of a Worker
  • Example#3615 - Shutdown the referenced worker
  • Example#3616 - Stacking a task for execution onto a worker
  • Example#3617 - Removing objects from the stack of Workers
  • Example#3618 - Ejemplo de método protegido: los métodos protegidos solamente pueden ser ejecutados por un Thread a la vez.
  • Example#3619 - Ejemplo de método privado: los métodos privados solamente pueden ser ejecutados por el objeto Threaded durante su ejecución
  • Example#3620 - A basic example of Pool::collect
  • Example#3621 - Creating Pools
  • Example#3622 - Shutting down a pool
  • Example#3623 - Submitting Tasks
  • Example#3624 - Submitting tasks to a specific worker
  • Example#3625 - Mutex Creation and Destruction
  • Example#3626 - Mutex Creation and Destruction
  • Example#3627 - Mutex Locking and Unlocking
  • Example#3628 - Mutex Locking and Unlocking
  • Example#3629 - Mutex Locking and Unlocking
  • Example#3630 - Condition Broadcasting
  • Example#3631 - Condition Creation and Destruction
  • Example#3632 - Condition Creation and Destruction
  • Example#3633 - Condition Signalling
  • Example#3634 - Waiting for Conditions
  • Example#3635 - Adding a new class task to a thread
  • Example#3636 - Adding a new file task to a thread
  • Example#3637 - Adding a new function task to a thread
  • Example#3638 - Joining a thread
  • Example#3639 - Starting a new thread
  • Example#3640 - Getting the task count of a thread
  • Example#3641 - Locking a hash table's mutex lock
  • Example#3642 - Getting a hash table's size
  • Example#3643 - Locking a hash table's mutex lock
  • Example#3644 - Creating a new vector
  • Example#3645 - Deleting values in a vector
  • Example#3646 - Inserting a value into a vector
  • Example#3647 - Locking a vector's mutex lock
  • Example#3648 - Popping a value from a vector
  • Example#3649 - Pushing values to a vector
  • Example#3650 - Resizing a vector
  • Example#3651 - Shifting a value from a vector
  • Example#3652 - Getting a vector's size
  • Example#3653 - Locking a vector's mutex lock
  • Example#3654 - Unshifting a value to the front of a vector
  • Example#3655 - Updating a value in a vector
  • Example#3656 - Retrieving the front value of a queue
  • Example#3657 - Retrieving the front value in a loop (bad example - don't do this)
  • Example#3658 - Retrieving the front value in a loop (good example)
  • Example#3659 - Locking a queue's mutex lock
  • Example#3660 - Popping a value from a queue
  • Example#3661 - Pushing a value to a queue
  • Example#3662 - Getting a queue's size
  • Example#3663 - Locking a queue's mutex lock
  • Example#3664 - Creating a new atomic integer
  • Example#3665 - Decrementing an atomic integer's value
  • Example#3666 - Getting an atomic integer's value
  • Example#3667 - Incrementing an atomic integer's value
  • Example#3668 - Grouping together an atomic integer's operations (requiring a mutex lock)
  • Example#3669 - Setting an atomic integer's value
  • Example#3670 - Grouping together an atomic integer's operations (requiring a mutex lock)
  • Example#3671 -
  • Example#3672 - Resumen de las operaciones con Memoria Compartida
  • Example#3673 - Cerrando segmento de memoria compartida
  • Example#3674 - Borrando segmento de memoria compartida
  • Example#3675 - Crear un nuevo segmento de memoria compartida
  • Example#3676 - Lectura de un segmento de memoria compartida
  • Example#3677 - Obtención del tamaño de un segmento de memoria compartida
  • Example#3678 - Escribiendo en un segmento de memoria compartida
  • Example#3679 - SyncMutex::__construct named mutex with lock timeout example
  • Example#3680 - SyncMutex::__construct unnamed mutex example
  • Example#3681 - SyncMutex::lock example
  • Example#3682 - SyncMutex::unlock example
  • Example#3683 - SyncSemaphore::__construct example
  • Example#3684 - SyncSemaphore::lock example
  • Example#3685 - SyncSemaphore::unlock example
  • Example#3686 - SyncEvent::__construct example
  • Example#3687 - SyncEvent::fire example
  • Example#3688 - SyncEvent::reset example
  • Example#3689 - SyncEvent::wait example
  • Example#3690 - SyncReaderWriter::__construct example
  • Example#3691 - SyncReaderWriter::readlock example
  • Example#3692 - SyncReaderWriter::readunlock example
  • Example#3693 - SyncReaderWriter::writelock example
  • Example#3694 - SyncReaderWriter::writeunlock example
  • Example#3695 - SyncSharedMemory::__construct example
  • Example#3696 - SyncSharedMemory::first example
  • Example#3697 - SyncSharedMemory::__construct example
  • Example#3698 - SyncSharedMemory::size example
  • Example#3699 - SyncSharedMemory::write example
  • Example#3700 - Un ejemplo de geoip_asnum_by_name
  • Example#3701 - Un ejemplo de geoip_continent_code_by_name
  • Example#3702 - Ejemplo de geoip_country_code_by_name
  • Example#3703 - Ejemplo de geoip_country_code3_by_name
  • Example#3704 - Ejemplo de geoip_country_name_by_name
  • Example#3705 - Ejemplo de geoip_database_info
  • Example#3706 - Un ejemplo de geoip_db_avail
  • Example#3707 - Ejemplo de geoip_db_filename
  • Example#3708 - Ejemplo de geoip_db_get_all_info
  • Example#3709 - Ejemplo de geoip_db_get_all_info
  • Example#3710 - Un ejemplo de geoip_domain_by_name
  • Example#3711 - Ejemplo de geoip_id_by_name
  • Example#3712 - Ejemplo de geoip_isp_by_name
  • Example#3713 - Un ejemplo de geoip_netspeedcell_by_name
  • Example#3714 - Ejemplo de geoip_org_by_name
  • Example#3715 - Ejemplo de geoip_record_by_name
  • Example#3716 - Ejemplo de geoip_region_by_name
  • Example#3717 - Ejemplo de geoip_region_name_by_code usando código de región para EEUU/Cánada
  • Example#3718 - Ejemplo de geoip_region_name_by_code usando códigos FIPS
  • Example#3719 - Un ejemplo de geoip_setup_custom_directory
  • Example#3720 - Ejemplo de geoip_time_zone_by_country_and_region usando códigos de región de EEUU/Canadá
  • Example#3721 - Ejemplo de geoip_time_zone_by_country_and_region usando códigos FIPS
  • Example#3722 - Fichero xor.data
  • Example#3723 - Entrenamiento sencillo
  • Example#3724 - Prueba sencilla
  • Example#3725 - Ejemplo de fann_create_train_from_callback
  • Example#3726 - Ejemplo de fann_read_train_from_file
  • Example#3727 - Ejemplo de JsonSerializable::jsonSerialize devolviendo un array
  • Example#3728 - Ejemplo de JsonSerializable::jsonSerialize devolviendo un array asociativo
  • Example#3729 - Ejemplo de JsonSerializable::jsonSerialize devolviento un integer
  • Example#3730 - Ejemplo de JsonSerializable::jsonSerialize devolviendo un string
  • Example#3731 - Ejemplos de json_decode
  • Example#3732 - Acceder a propiedades de objeto no válidas
  • Example#3733 - Errores comunes al usar json_decode
  • Example#3734 - Errores con depth
  • Example#3735 - json_decode de enteros grandes
  • Example#3736 - Un ejemplo de json_encode
  • Example#3737 - Un ejemplo de json_encode mostrando algunas de las opciones en acción
  • Example#3738 - Ejemplo de la opción JSON_NUMERIC_CHECK
  • Example#3739 - Ejemplo de array secuencial contra array no secuencial
  • Example#3740 - Ejemplo de la opción JSON_PRESERVE_ZERO_FRACTION
  • Example#3741 - Ejemplo de json_last_error
  • Example#3742 - json_last_error en json_encode
  • Example#3743 - Ejemplo de Lua::assign
  • Example#3744 - Ejemplo de la función Lua::call
  • Example#3745 - Ejemplo de la función Lua::eval
  • Example#3746 - Ejemplo de Lua::registerCallback
  • Example#3747 - Ejemplo de LuaClosure::__invoke
  • Example#3748 - Execute some Lua code
  • Example#3749 - Calling a Lua function
  • Example#3750 - Profiling Lua code
  • Example#3751 - Loading code into Lua
  • Example#3752 - Manipulating the usage timer
  • Example#3753 - Registering PHP functions to call from Lua
  • Example#3754 - Calling a Lua function
  • Example#3755 - Calling a Lua function
  • Example#3756 - Ejemplo de constant
  • Example#3757 - Definir Constantes
  • Example#3758 - Comprobar constantes
  • Example#3759 - Ejemplo de eval - fusión de texto sencillo
  • Example#3760 - Ejemplo de exit
  • Example#3761 - Ejemplo de status de exit
  • Example#3762 - Las funciones Shutdown y los destructores se ejecutan igualmente
  • Example#3763 - Listar toda la información sobre el navegador del usuario
  • Example#3764 - Un Ejemplo de __halt_compiler
  • Example#3765 - Ejemplo de highlight_string
  • Example#3766 - hrtime usage
  • Example#3767 - Un ejemplo ignore_user_abort
  • Example#3768 - Ejemplo de pack
  • Example#3769 - Ejemplo de php_strip_whitespace
  • Example#3770 - Basic sapi_windows_generate_ctrl_event Usage
  • Example#3771 - Basic sapi_windows_set_ctrl_handler Usage
  • Example#3772 - sapi_windows_vt100_support default state
  • Example#3773 - sapi_windows_vt100_support changing state
  • Example#3774 - Example usage of VT100 support enabled
  • Example#3775 - Ejemplo de sleep
  • Example#3776 - Ejemplo de sys_getloadavg
  • Example#3777 - Ejemplo de time_nanosleep
  • Example#3778 - Un ejemplo de time_sleep_until
  • Example#3779 - Ejemplo de uniqid
  • Example#3780 - Ejemplo de unpack
  • Example#3781 - Ejemplo de unpack con un repetidor
  • Example#3782 - Ejemplo unpack con claves sin nombre
  • Example#3783 - Ejemplo de usleep
  • Example#3784 - Get and set base path
  • Example#3785 - Get and set logger
  • Example#3786 - Fast write log
  • Example#3787 - Fast count some type of log count value
  • Example#3788 - Acquisit some type of log list
  • Example#3789 - seaslog_get_author example
  • Example#3790 - seaslog_get_version example
  • Example#3791 - SeasLog::alert example
  • Example#3792 - SeasLog::analyzerCount example
  • Example#3793 - SeasLog::analyzerDetail example
  • Example#3794 - SeasLog::closeLoggerStream example
  • Example#3795 - SeasLog::__construct example
  • Example#3796 - SeasLog::critical example
  • Example#3797 - SeasLog::debug example
  • Example#3798 - SeasLog::__destruct example
  • Example#3799 - SeasLog::emergency example
  • Example#3800 - SeasLog::error example
  • Example#3801 - SeasLog::flushBuffer example
  • Example#3802 - SeasLog::getBasePath example
  • Example#3803 - SeasLog::getBuffer example
  • Example#3804 - SeasLog::getBufferEnabled example
  • Example#3805 - SeasLog::getDatetimeFormat example
  • Example#3806 - SeasLog::getLastLogger example
  • Example#3807 - SeasLog::getRequestID example
  • Example#3808 - SeasLog::getRequestVariable example
  • Example#3809 - SeasLog::info example
  • Example#3810 - SeasLog::log example
  • Example#3811 - SeasLog::notice example
  • Example#3812 - SeasLog::setBasePath example
  • Example#3813 - SeasLog::setDatetimeFormat example
  • Example#3814 - SeasLog::setLogger example
  • Example#3815 - SeasLog::setRequestID example
  • Example#3816 - SeasLog::setRequestVariable example
  • Example#3817 - SeasLog::warning example
  • Example#3818 - Ejemplo de SplDoublyLinkedList::__construct
  • Example#3819 - Ejemplo de SplStack::__construct
  • Example#3820 - Ejemplo de SplQueue::__construct
  • Example#3821 - Manejo eficiente de las tareas con SplQueue
  • Example#3822 - Ejemplo de uso SplFixedArray
  • Example#3823 - Ejemplo de SplFixedArray::__construct
  • Example#3824 - Ejemplo de SplFixedArray::count
  • Example#3825 - Ejemplo de SplFixedArray::fromArray
  • Example#3826 - Ejemplo de SplFixedArray::getSize
  • Example#3827 - Ejemplo de SplFixedArray::setSize
  • Example#3828 - Ejemplo de SplFixedArray::toArray
  • Example#3829 - SplObjectStorage como un conjunto
  • Example#3830 - SplObjectStorage como un mapa
  • Example#3831 - Ejemplo de SplObjectStorage::addAll
  • Example#3832 - Ejemplo de SplObjectStorage::attach
  • Example#3833 - Ejemplo de SplObjectStorage::contains
  • Example#3834 - Ejemplo de SplObjectStorage::count
  • Example#3835 - Ejemplo de SplObjectStorage::current
  • Example#3836 - Ejemplo de SplObjectStorage::detach
  • Example#3837 - Ejemplo de SplObjectStorage::getHash
  • Example#3838 - Ejemplo de SplObjectStorage::getInfo
  • Example#3839 - Ejemplo de SplObjectStorage::key
  • Example#3840 - Ejemplo de SplObjectStorage::next
  • Example#3841 - Ejemplo de SplObjectStorage::offsetExists
  • Example#3842 - Ejemplo de SplObjectStorage::offsetGet
  • Example#3843 - Ejemplo de SplObjectStorage::offsetSet
  • Example#3844 - Ejemplo de SplObjectStorage::offsetUnset
  • Example#3845 - Ejemplo de SplObjectStorage::removeAll
  • Example#3846 - Ejemplo de SplObjectStorage::removeAllExcept
  • Example#3847 - Ejemplo de SplObjectStorage::rewind
  • Example#3848 - Ejemplo de SplObjectStorage::serialize
  • Example#3849 - Ejemplo de SplObjectStorage::setInfo
  • Example#3850 - Ejemplo de SplObjectStorage::unserialize
  • Example#3851 - Ejemplo de SplObjectStorage::valid
  • Example#3852 - Ejemplo de AppendIterator::append
  • Example#3853 - Recorriendo AppendIterator con foreach
  • Example#3854 - Recorriendo AppendIterator con la API de AppendIterator
  • Example#3855 - Ejemplo de AppendIterator::getInnerIterator
  • Example#3856 - Ejemplo básico de AppendIterator.getIteratorIndex
  • Example#3857 - Ejemplo básico de AppendIterator::key
  • Example#3858 - Ejemplo de ArrayIterator::current
  • Example#3859 - Ejemplo de ArrayIterator::key
  • Example#3860 - Ejemplo de ArrayIterator::next
  • Example#3861 - Ejemplo de ArrayIterator::rewind
  • Example#3862 - Ejemplo de ArrayIterator::valid
  • Example#3863 - Ejemplo de CachingIterator::getCache.
  • Example#3864 - Argumentos disponibles de la llamada de retorno
  • Example#3865 - Ejemplos básicos de llamada de retorno
  • Example#3866 - Un DirectoryIterator::__construct ejemplo
  • Example#3867 - Ejemplo de DirectoryIterator::current
  • Example#3868 - Ejemplo de DirectoryIterator::getATime
  • Example#3869 - Ejemplo de DirectoryIterator::getBasename
  • Example#3870 - DirectoryIterator::getCTime example
  • Example#3871 - Ejemplo de DirectoryIterator::getExtension
  • Example#3872 -
  • Example#3873 - Ejemplo de DirectoryIterator::getFilename
  • Example#3874 - Ejemplo de DirectoryIterator::getGroup
  • Example#3875 - Ejemplo de DirectoryIterator::getInode
  • Example#3876 - Ejemplo de DirectoryIterator::getMTime
  • Example#3877 - Ejemplo de DirectoryIterator::getOwner
  • Example#3878 - Ejemplo de DirectoryIterator::getPath
  • Example#3879 - Ejemplo de DirectoryIterator::getPathname
  • Example#3880 - Ejemplo de DirectoryIterator::getPerms
  • Example#3881 - Ejemplo de DirectoryIterator::getSize
  • Example#3882 - Ejemplo de DirectoryIterator::getType
  • Example#3883 - Ejemplo de DirectoryIterator::isDir
  • Example#3884 - Ejemplo de DirectoryIterator::isDot
  • Example#3885 - Ejemplo de DirectoryIterator::isExecutable
  • Example#3886 - Ejemplo de DirectoryIterator::isFile
  • Example#3887 - Ejemplo de DirectoryIterator::isLink
  • Example#3888 - Ejemplo de DirectoryIterator::isReadable
  • Example#3889 - Ejemplo de DirectoryIterator::isWritable
  • Example#3890 - Ejemplo de DirectoryIterator::key
  • Example#3891 - Ejemplo de DirectoryIterator::next
  • Example#3892 - Ejemplo de DirectoryIterator::rewind
  • Example#3893 - Ejemplo de DirectoryIterator::seek
  • Example#3894 - Ejemplo de DirectoryIterator::__toString
  • Example#3895 - Ejemplo de DirectoryIterator::valid
  • Example#3896 - Ejemplo de FilesystemIterator::__construct
  • Example#3897 - Ejemplo de FilesystemIterator::current
  • Example#3898 - Ejemplo de FilesystemIterator::key
  • Example#3899 - Ejemplo de FilesystemIterator::next
  • Example#3900 - Ejemplo de FilesystemIterator::rewind
  • Example#3901 - Ejemplo de FilesystemIterator::key
  • Example#3902 - Ejemplo de FilterIterator::accept
  • Example#3903 - Ejemplo de GlobIterator
  • Example#3904 - Ejemplo de GlobIterator::count
  • Example#3905 - Ejemplo de InfiniteIterator::__construct
  • Example#3906 - Ejemplo de uso de LimitIterator
  • Example#3907 - Ejemplo de LimitIterator::__construct
  • Example#3908 - Ejemplo de LimitIterator::getPosition
  • Example#3909 - Iterar un MultipleIterator
  • Example#3910 - Ejemplo de NoRewindIterator::__construct
  • Example#3911 - Ejemplo de NoRewindIterator::rewind
  • Example#3912 - Ejemplo de RecursiveArrayIterator::getChildren
  • Example#3913 - Ejemplo de RecursiveArrayIterator::hasChildren
  • Example#3914 - Argumentos disponibles de la llamada de retorno
  • Example#3915 - Ejemplo básico de llamada de retorno recursiva
  • Example#3916 - Uso básico de RecursiveCallbackFilterIterator::hasChildren
  • Example#3917 - Ejemplo de RecursiveDirectoryIterator
  • Example#3918 - Ejemplo de getSubPath
  • Example#3919 - Ejemplo de getSubPathname
  • Example#3920 - Ejemplo básico de RecursiveFilterIterator
  • Example#3921 - Ejemplo de RecursiveFilterIterator
  • Example#3922 - Iterar un RecursiveIteratorIterator
  • Example#3923 - Ejemplo de RecursiveRegexIterator::__construct
  • Example#3924 - Ejemplo de RecursiveRegexIterator::getChildren
  • Example#3925 - Ejemplo de RecursiveRegexIterator::hasChildren
  • Example#3926 - RegexIterator::accept example
  • Example#3927 - Ejemplo de RegexIterator::__construct
  • Example#3928 - Ejemplo de RegexIterator::getFlags
  • Example#3929 - Ejemplo de RegexIterator::getMode
  • Example#3930 - Ejemplo de RegexIterator::getPregFlags
  • Example#3931 - Ejemplo de RegexIterator::setFlags
  • Example#3932 - Ejemplo de RegexIterator::setMode
  • Example#3933 - Ejemplo de RegexIterator::setPregFlags
  • Example#3934 - Ejemplo de Countable::count
  • Example#3935 - Uso básico
  • Example#3936 - Ejemplo de SeekableIterator::seek
  • Example#3937 - Ejemplo de class_implements
  • Example#3938 - Ejemplo de class_parents
  • Example#3939 - Ejemplo de class_uses
  • Example#3940 - Ejemplo de iterator_apply
  • Example#3941 - Ejemplo de iterator_count
  • Example#3942 - iterator_count modifica la posición
  • Example#3943 - iterator_count en bucles foreach
  • Example#3944 - Ejemplo de iterator_to_array
  • Example#3945 - spl_autoload_register como sustituto de una función __autoload
  • Example#3946 - Ejemplo de spl_autoload_register donde la clase no es cargada
  • Example#3947 - Ejemplo de spl_classes
  • Example#3948 - Ejemplo de spl_object_hash
  • Example#3949 - A spl_object_id example
  • Example#3950 - SplFileInfo::__construct ejemplo
  • Example#3951 - SplFileInfo::getBasenameejemplo
  • Example#3952 - Ejemplo de SplFileInfo::getCTime
  • Example#3953 - SplFileInfo::getExtension ejemplo
  • Example#3954 -
  • Example#3955 - SplFileInfo::getFilename ejemplo
  • Example#3956 - Ejemplo de SplFileInfo::getGroup
  • Example#3957 - Ejemplo de SplFileInfo::getLinkTarget
  • Example#3958 - Ejemplo de SplFileInfo::getOwner
  • Example#3959 - Ejemplo de SplFileInfo::getPath
  • Example#3960 - Ejemplo de SplFileInfo::getPathInfo
  • Example#3961 - Ejemplo de SplFileInfo::getPathname
  • Example#3962 - Ejemplo de SplFileInfo::getPerms
  • Example#3963 - Ejemplo de SplFileInfo::getRealPath
  • Example#3964 - Ejemplo de SplFileInfo::getType
  • Example#3965 - Ejemplo de SplFileInfo::isDir
  • Example#3966 - Ejemplo de SplFileInfo::isExecutable
  • Example#3967 - Ejemplo de SplFileInfo::isFile
  • Example#3968 - Ejemplo de SplFileInfo::isLink
  • Example#3969 - Ejemplo de SplFileInfo::isReadable
  • Example#3970 - Ejemplo de SplFileInfo::openFile
  • Example#3971 - Ejemplo de SplFileInfo::setFileClass
  • Example#3972 - Ejemplo de SplFileInfo::setFileClass
  • Example#3973 - Ejemplo de SplFileInfo::__toString
  • Example#3974 - Ejemplo de SplFileObject::__construct
  • Example#3975 - Ejemplo de SplFileObject::current
  • Example#3976 - Ejemplo de SplFileObject::eof
  • Example#3977 - Ejemplo de SplFileObject::fflush
  • Example#3978 - Ejemplo de SplFileObject::fgetc
  • Example#3979 - Ejemplo de SplFileObject::fgetcsv
  • Example#3980 - Ejemplo de SplFileObject::READ_CSV
  • Example#3981 - Ejemplo de SplFileObject::fgets
  • Example#3982 - Ejemplo de SplFileObject::fgetss
  • Example#3983 - Ejemplo de SplFileObject::flock
  • Example#3984 - Ejemplo de SplFileObject::fpassthru
  • Example#3985 - Ejemplo de SplFileObject::fputcsv
  • Example#3986 - Ejemplo de SplFileObject::fread
  • Example#3987 - Ejemplo de SplFileObject::fscanf
  • Example#3988 - Ejemplo de SplFileObject::fseek
  • Example#3989 - Ejemplo de SplFileObject::fstat
  • Example#3990 - Ejemplo de SplFileObject::ftell
  • Example#3991 - Ejemplo de SplFileObject::ftruncate
  • Example#3992 - Ejemplo de SplFileObject::fwrite
  • Example#3993 - Ejemplo de SplFileObject::getCsvControl
  • Example#3994 - Ejemplo de SplFileObject::getFlags
  • Example#3995 - Ejemplo de SplFileObject::getMaxLineLen
  • Example#3996 - Ejemplo de SplFileObject::key
  • Example#3997 - SplFileObject::key ejemplo con SplFileObject::setMaxLineLen
  • Example#3998 - Ejemplo de SplFileObject::next
  • Example#3999 - Ejemplo de SplFileObject::rewind
  • Example#4000 - Ejemplo de SplFileObject::seek
  • Example#4001 - Ejemplo de SplFileObject::setCsvControl
  • Example#4002 - Ejemplo de SplFileObject::setFlags
  • Example#4003 - Ejemplo de SplFileObject::setMaxLineLen
  • Example#4004 - Ejemplo de SplFileObject::valid
  • Example#4005 - Ejemplo de SplTempFileObject
  • Example#4006 - Ejemplo de ArrayObject::append
  • Example#4007 - ArrayObject::asort example
  • Example#4008 - Ejemplo de ArrayObject::__construct
  • Example#4009 - Ejemplo de ArrayObject::count
  • Example#4010 - ArrayObject::exchangeArray example
  • Example#4011 - ArrayObject::getArrayCopy example
  • Example#4012 - Ejemplo de ArrayObject::getFlags
  • Example#4013 - Ejemplo de ArrayObject::getIterator
  • Example#4014 - ArrayObject::getIteratorClass example
  • Example#4015 - Ejemplo de ArrayObject::ksort
  • Example#4016 - Ejemplo de ArrayObject::natcasesort
  • Example#4017 - Ejemplo de ArrayObject::natsort
  • Example#4018 - Ejemplo de ArrayObject::offsetExists
  • Example#4019 - Ejemplo de ArrayObject::offsetGet
  • Example#4020 - Ejemplo de ArrayObject::offsetSet
  • Example#4021 - Ejemplo de ArrayObject::offsetUnset
  • Example#4022 - Ejemplo de ArrayObject::serialize
  • Example#4023 - Ejemplo de ArrayObject::setFlags
  • Example#4024 - Ejemplo de ArrayObject::setIteratorClass
  • Example#4025 - Ejemplo de ArrayObject::uasort
  • Example#4026 - Ejemplo de ArrayObject::uksort
  • Example#4027 - Usar file_get_contents para recuperar información desde múltiples fuentes
  • Example#4028 - Hacer una petición POST a un servidor https
  • Example#4029 - Escribir información en un archivo compirmido
  • Example#4030 - Un Flujo para leer/escribir variables globales
  • Example#4031 - Listar los ficheros de archivos tar
  • Example#4032 - Ejemplos de stream_bucket_prepend
  • Example#4033 - Usar stream_context_create
  • Example#4034 - Usar stream_context_get_default
  • Example#4035 - Ejemplo de stream_context_get_options
  • Example#4036 - Ejemplo de stream_context_get_params
  • Example#4037 - Ejemplo de stream_context_set_default
  • Example#4038 - Un ejemplo de stream_copy_to_stream
  • Example#4039 - Controlar dónde son aplicados los filtros
  • Example#4040 - Filtro para poner en mayúsculas caracteres en el flujo foo-bar.txt
  • Example#4041 - Registrar una clase de filtro genérica para comparar múltiples nombres de filtro.
  • Example#4042 - Refiltrar dináminamente un flujo
  • Example#4043 - Ejemplo de stream_get_contents
  • Example#4044 - Usar stream_get_filters
  • Example#4045 - Ejemplo de stream_get_meta_data
  • Example#4046 - Usar stream_get_transports
  • Example#4047 - Ejemplo de stream_get_wrappers
  • Example#4048 - Comprobar la existencia de una envoltura de flujo
  • Example#4049 - Ejemplo de stream_is_local
  • Example#4050 - stream_isatty example
  • Example#4051 - Ejemplo de stream_notification_callback
  • Example#4052 - Barra de progreso sencilla para la descarga por parte del cliente por línea de comandos
  • Example#4053 - Ejemplo de stream_resolve_include_path
  • Example#4054 - Ejemplo de stream_select
  • Example#4055 - Ejemplo de stream_set_timeout
  • Example#4056 - Ejemplo de stream_set_write_buffer
  • Example#4057 - Ejemplo de stream_socket_client
  • Example#4058 - Usar una conexión UDP
  • Example#4059 - Ejemplo de stream_socket_enable_crypto
  • Example#4060 - Un ejemplo de stream_socket_pair
  • Example#4061 - Ejemplo de stream_socket_recvfrom
  • Example#4062 - Ejemplo de stream_socket_sendto
  • Example#4063 - Usar sockets de servidor de TCP
  • Example#4064 - Usar sockets de servidor de UDP
  • Example#4065 - Un ejemplo de stream_socket_shutdown
  • Example#4066 - Cómo registrar una envoltura de flujo
  • Example#4067 - Uso Básico Tidy
  • Example#4068 - Ejemplo de tidy::getBody
  • Example#4069 - Ejemplo de tidy::cleanrepair
  • Example#4070 - Ejemplo de tidy::__construct
  • Example#4071 - Ejemplo de tidy::diagnose
  • Example#4072 - Ejemplo de tidy_get_error_buffer
  • Example#4073 - Ejemplo de tidy::getConfig
  • Example#4074 - Ejemplo de tidy_getopt
  • Example#4075 - Imprimir todas las opciones, junto con su documentación y sus valores por omisión
  • Example#4076 - Ejemplo de tidy::getStatus
  • Example#4077 - Ejemplo de tidy::head
  • Example#4078 - Ejemplo de tidy::html
  • Example#4079 - Ejemplo de tidy::parseFile
  • Example#4080 - Ejemplo de tidy::parseString
  • Example#4081 - Ejemplo de tidy::repairFile
  • Example#4082 - Ejemplo de tidy::repairString
  • Example#4083 - tidy::root ejemplo
  • Example#4084 - Ejemplo de tidyNode::hasChildren
  • Example#4085 - Ejemplo de tidyNode::hasChildren
  • Example#4086 - Ejemplo de tidyNode::hasSiblings
  • Example#4087 - Extraer el código ASP embebido en un documento HTML
  • Example#4088 - Extraer los comentarios de un documento HTML
  • Example#4089 - Extraer el código HTML de un documento HTML
  • Example#4090 - Extrer el código JSTE de un documento HTML
  • Example#4091 - Extraer el código PHP embebido en un documento HTML
  • Example#4092 - Extraer el texto de un documento HTML
  • Example#4093 - Ejemplo de ob_tidyhandler
  • Example#4094 - Ejemplo de la función tidy_access_count
  • Example#4095 - Ejemplo de la función tidy_config_count
  • Example#4096 - Ejemplo de la función tidy_error_count
  • Example#4097 - Ejemplo de la función tidy_get_output
  • Example#4098 - Ejemplo de la función tidy_warning_count
  • Example#4099 - Quitar comentarios con el tokenizer
  • Example#4100 - token_get_all ejemplos
  • Example#4101 - token_name ejemplo
  • Example#4102 - Ejemplo de base64_decode
  • Example#4103 - Ejemplo de base64_encode
  • Example#4104 - Ejemplo de get_headers
  • Example#4105 - get_headers using HEAD example
  • Example#4106 - Lo que procesa get_meta_tags
  • Example#4107 - Lo que devuelve get_meta_tags
  • Example#4108 - Uso simple de http_build_query
  • Example#4109 - http_build_query con elementos indexados numéricamente.
  • Example#4110 - con arrays complejos http_build_query
  • Example#4111 - Uso de http_build_query con un objeto
  • Example#4112 - Un ejemplo de parse_url
  • Example#4113 - Un ejemplo de parse_url con el esquema ausente
  • Example#4114 - Ejemplo de rawurldecode
  • Example#4115 - Inclusión de una contraseña en una URL FTP
  • Example#4116 - Ejemplo 2 de rawurlencode
  • Example#4117 - Ejemplo de urldecode
  • Example#4118 - Ejemplo de urlencode
  • Example#4119 - Ejemplo de urlencode y ejemplo de htmlentities
  • Example#4120 - Básica ejecución Javascript
  • Example#4121 - Yaml Example
  • Example#4122 - Ejemplo de análisis de callback
  • Example#4123 - Ejemplo de emisión de callback
  • Example#4124 - Ejemplo de yaml_emit
  • Example#4125 - Ejemplo de yaml_parse
  • Example#4126 - Distribución clásica del directorio Application
  • Example#4127 - Entrada
  • Example#4128 - Regla de sobrescritura
  • Example#4129 - Configuración de la aplicación
  • Example#4130 - Controlador predeterminado
  • Example#4131 - Plantilla de vistas predeterminada
  • Example#4132 - Ejecutar la aplicación
  • Example#4133 - Un ejemplo de array de PHP
  • Example#4134 - Un ejemplo de un fichero ini
  • Example#4135 - Un ejemplo de A Bootstrap
  • Example#4136 - Ejemplo de Yaf_Application::bootstrap
  • Example#4137 - Ejemplo de Yaf_Application::clearLastError
  • Example#4138 - A ini config file example
  • Example#4139 - Ejemplo de Yaf_Application::__construct
  • Example#4140 - Ejemplo de Yaf_Application::__construct
  • Example#4141 - Ejemplo de Yaf_Application::environ
  • Example#4142 - Ejemplo de Yaf_Application::execute
  • Example#4143 - Ejemplo de Yaf_Application::getConfig
  • Example#4144 - Ejemplo de Yaf_Application::getDispatcher
  • Example#4145 - Ejemplo de Yaf_Application::getLastErrorMsg
  • Example#4146 - Ejemplo de Yaf_Application::getLastErrorNo
  • Example#4147 - Ejemplo de Yaf_Application::getModules
  • Example#4148 - Ejemplo de arranque
  • Example#4149 - Ejemplo de Yaf_Dispatcher::autoRender
  • Example#4150 - Ejemplo de Yaf_Dispatcher::catchException
  • Example#4151 - Yaf_Dispatcher::registerPluginexample
  • Example#4152 - Ejemplo de un motor de Vistas personalizado
  • Example#4153 - Ejemplo de Yaf_Dispatcher::setView
  • Example#4154 - Ejemplo de Yaf_Dispatcher::throwexception
  • Example#4155 - Ejemplo de Yaf_Dispatcher::throwexception
  • Example#4156 - Ejemplo de Yaf_Config_Ini
  • Example#4157 - Definir una acción en un fichero aparte
  • Example#4158 - Dummy_action.php
  • Example#4159 - Ejemplo de Yaf_Controller_Abstract::forward
  • Example#4160 - Ejemplo de Yaf_Action_Abstract::execute
  • Example#4161 - Ejemplo de Yaf_Action_Abstract::execute
  • Example#4162 - Ejemplo de Yaf_View_Simple::assign
  • Example#4163 - Ejemplo de template
  • Example#4164 - Ejemplo de Yaf_View_Simple::assignRef
  • Example#4165 - Ejemplo de template
  • Example#4166 - Ejemplo de Yaf_View_Simple::clear
  • Example#4167 - Ejemplo de Yaf_View_Simple::__constructor
  • Example#4168 - Ejemplo de Yaf_View_Simple::__set
  • Example#4169 - Ejemplo de configuración
  • Example#4170 - Registrar el espacio de nombres local
  • Example#4171 - Load class example
  • Example#4172 - Ejemplo de carga de una clase en el espacio de nombres
  • Example#4173 - Ejemplo de carga de clase MVC
  • Example#4174 - Distinciones de clases MVC
  • Example#4175 - Ejemplo de carga MVC
  • Example#4176 - Ejemplo de Yaf_Loader::registerNamespace
  • Example#4177 - Ejemplo de Yaf_Loader::registerLocalNamespace
  • Example#4178 - Ejemplo de Yaf_Loader::registerNamespace
  • Example#4179 - Plugin example
  • Example#4180 - Ejemplo de Yaf_Plugin_Abstract::routerShutdown
  • Example#4181 - Ejemplo de Yaf_Response_Abstract::appendBody
  • Example#4182 - Ejemplo de Yaf_Response_Abstract::getBody
  • Example#4183 - Ejemplo de Yaf_Response_Abstract::prependBody
  • Example#4184 - Ejemplo de Yaf_Response_Abstract::response
  • Example#4185 - Ejemplo de Yaf_Response_Abstract::setBody
  • Example#4186 - Ejemplo de Yaf_Route_Map::assemble
  • Example#4187 - Ejemplo de Yaf_Route_Map
  • Example#4188 - Ejemplo de Yaf_Route_Map
  • Example#4189 - Yaf_Route_Mapexample
  • Example#4190 - Ejemplo de Yaf_Route_Regex::assemble
  • Example#4191 - Ejemplo de Yaf_Route_Regex
  • Example#4192 - Ejemplo de Yaf_Route_Regex(como en 2.3.0)
  • Example#4193 - Ejemplo de Yaf_Route_Regex y el nombre de la zona de captura (a partir de 2.3.0)
  • Example#4194 - Ejemplo de Yaf_Route_Regex
  • Example#4195 - Ejemplo de Yaf_Route_Rewrite::assemble
  • Example#4196 - Ejemplo de Yaf_Route_Rewrite
  • Example#4197 - Ejemplo de Yaf_Route_Rewrite
  • Example#4198 - Ejemplo de Yaf_Route_Rewrite (como en 2.3.0)
  • Example#4199 - Regla de reescritura para Apache
  • Example#4200 - Regla de reescritura para Apache
  • Example#4201 - Regla de reescritura para Lighttpd
  • Example#4202 - Regla de reescritura para Nginx
  • Example#4203 - Ejemplo de Yaf_Route_Static (ruta predeterminada)
  • Example#4204 - Ejemplo de application.ini
  • Example#4205 - Ejemplo de Yaf_Dispatcher::autoConfig
  • Example#4206 - Ejemplo de Yaf_Dispatcher::autoRender
  • Example#4207 - Registrar algunas rutas en el Arranque
  • Example#4208 - Complemento Dummy.php (bajo application.directory/plugins)
  • Example#4209 - Ejemplo de Yaf_Route_Simple::assemble
  • Example#4210 - Ejemplo de Yaf_Route_Simple::route
  • Example#4211 - Ejemplo de Yaf_Route_Simple::route
  • Example#4212 - Ejemplo de Yaf_Route_Static::assemble
  • Example#4213 - Ejemplo de Yaf_Route_Static::route
  • Example#4214 - Ejemplo de Yaf_Route_Supervar::assemble
  • Example#4215 - Ejemplo de Yaf_Route_Supervar
  • Example#4216 - INI example
  • Example#4217 - Ejemplo de secciones INI
  • Example#4218 - Ejemplo de INI
  • Example#4219 - Ejemplo de taint
  • Example#4220 - Vector
  • Example#4221 - Map
  • Example#4222 - Ds\Collection::clear example
  • Example#4223 - Ds\Collection::copy example
  • Example#4224 - Ds\Collection::isEmpty example
  • Example#4225 - Ds\Collection::toArray example
  • Example#4226 - Ds\Hashable::hash example
  • Example#4227 - Ds\Sequence::allocate example
  • Example#4228 - Ds\Sequence::apply example
  • Example#4229 - Ds\Sequence::capacity example
  • Example#4230 - Ds\Sequence::contains example
  • Example#4231 - Ds\Sequence::filter example using callback function
  • Example#4232 - Ds\Sequence::filter example without a callback function
  • Example#4233 - Ds\Sequence::find example
  • Example#4234 - Ds\Sequence::first example
  • Example#4235 - Ds\Sequence::get example
  • Example#4236 - Ds\Sequence::get example using array syntax
  • Example#4237 - Ds\Sequence::insert example
  • Example#4238 - Ds\Sequence::join example using a separator string
  • Example#4239 - Ds\Sequence::join example without a separator string
  • Example#4240 - Ds\Sequence::last example
  • Example#4241 - Ds\Sequence::map example
  • Example#4242 - Ds\Sequence::merge example
  • Example#4243 - Ds\Sequence::pop example
  • Example#4244 - Ds\Sequence::push example
  • Example#4245 - Ds\Sequence::reduce with initial value example
  • Example#4246 - Ds\Sequence::reduce without an initial value example
  • Example#4247 - Ds\Sequence::remove example
  • Example#4248 - Ds\Sequence::reverse example
  • Example#4249 - Ds\Sequence::reversed example
  • Example#4250 - Ds\Sequence::rotate example
  • Example#4251 - Ds\Sequence::set example
  • Example#4252 - Ds\Sequence::set example using array syntax
  • Example#4253 - Ds\Sequence::shift example
  • Example#4254 - Ds\Sequence::slice example
  • Example#4255 - Ds\Sequence::sort example
  • Example#4256 - Ds\Sequence::sort example using a comparator
  • Example#4257 - Ds\Sequence::sorted example
  • Example#4258 - Ds\Sequence::sorted example using a comparator
  • Example#4259 - Ds\Sequence::sum integer example
  • Example#4260 - Ds\Sequence::sum float example
  • Example#4261 - Ds\Sequence::unshift example
  • Example#4262 - Ds\Vector::allocate example
  • Example#4263 - Ds\Vector::apply example
  • Example#4264 - Ds\Vector::capacity example
  • Example#4265 - Ds\Vector::clear example
  • Example#4266 - Ds\Vector::__construct example
  • Example#4267 - Ds\Vector::contains example
  • Example#4268 - Ds\Vector::copy example
  • Example#4269 - Ds\Vector::filter example using callback function
  • Example#4270 - Ds\Vector::filter example without a callback function
  • Example#4271 - Ds\Vector::find example
  • Example#4272 - Ds\Vector::first example
  • Example#4273 - Ds\Vector::get example
  • Example#4274 - Ds\Vector::get example using array syntax
  • Example#4275 - Ds\Vector::insert example
  • Example#4276 - Ds\Vector::isEmpty example
  • Example#4277 - Ds\Vector::join example using a separator string
  • Example#4278 - Ds\Vector::join example without a separator string
  • Example#4279 - Ds\Vector::last example
  • Example#4280 - Ds\Vector::map example
  • Example#4281 - Ds\Vector::merge example
  • Example#4282 - Ds\Vector::pop example
  • Example#4283 - Ds\Vector::push example
  • Example#4284 - Ds\Vector::reduce with initial value example
  • Example#4285 - Ds\Vector::reduce without an initial value example
  • Example#4286 - Ds\Vector::remove example
  • Example#4287 - Ds\Vector::reverse example
  • Example#4288 - Ds\Vector::reversed example
  • Example#4289 - Ds\Vector::rotate example
  • Example#4290 - Ds\Vector::set example
  • Example#4291 - Ds\Vector::set example using array syntax
  • Example#4292 - Ds\Vector::shift example
  • Example#4293 - Ds\Vector::slice example
  • Example#4294 - Ds\Vector::sort example
  • Example#4295 - Ds\Vector::sort example using a comparator
  • Example#4296 - Ds\Vector::sorted example
  • Example#4297 - Ds\Vector::sorted example using a comparator
  • Example#4298 - Ds\Vector::sum integer example
  • Example#4299 - Ds\Vector::sum float example
  • Example#4300 - Ds\Vector::toArray example
  • Example#4301 - Ds\Vector::unshift example
  • Example#4302 - Ds\Deque::allocate example
  • Example#4303 - Ds\Deque::apply example
  • Example#4304 - Ds\Deque::capacity example
  • Example#4305 - Ds\Deque::clear example
  • Example#4306 - Ds\Deque::__construct example
  • Example#4307 - Ds\Deque::contains example
  • Example#4308 - Ds\Deque::copy example
  • Example#4309 - Ds\Deque::filter example using callback function
  • Example#4310 - Ds\Deque::filter example without a callback function
  • Example#4311 - Ds\Deque::find example
  • Example#4312 - Ds\Deque::first example
  • Example#4313 - Ds\Deque::get example
  • Example#4314 - Ds\Deque::get example using array syntax
  • Example#4315 - Ds\Deque::insert example
  • Example#4316 - Ds\Deque::isEmpty example
  • Example#4317 - Ds\Deque::join example using a separator string
  • Example#4318 - Ds\Deque::join example without a separator string
  • Example#4319 - Ds\Deque::last example
  • Example#4320 - Ds\Deque::map example
  • Example#4321 - Ds\Deque::merge example
  • Example#4322 - Ds\Deque::pop example
  • Example#4323 - Ds\Deque::push example
  • Example#4324 - Ds\Deque::reduce with initial value example
  • Example#4325 - Ds\Deque::reduce without an initial value example
  • Example#4326 - Ds\Deque::remove example
  • Example#4327 - Ds\Deque::reverse example
  • Example#4328 - Ds\Deque::reversed example
  • Example#4329 - Ds\Deque::rotate example
  • Example#4330 - Ds\Deque::set example
  • Example#4331 - Ds\Deque::set example using array syntax
  • Example#4332 - Ds\Deque::shift example
  • Example#4333 - Ds\Deque::slice example
  • Example#4334 - Ds\Deque::sort example
  • Example#4335 - Ds\Deque::sort example using a comparator
  • Example#4336 - Ds\Deque::sorted example
  • Example#4337 - Ds\Deque::sorted example using a comparator
  • Example#4338 - Ds\Deque::sum integer example
  • Example#4339 - Ds\Deque::sum float example
  • Example#4340 - Ds\Deque::toArray example
  • Example#4341 - Ds\Deque::unshift example
  • Example#4342 - Ds\Map::allocate example
  • Example#4343 - Ds\Map::apply example
  • Example#4344 - Ds\Map::capacity example
  • Example#4345 - Ds\Map::clear example
  • Example#4346 - Ds\Map::__construct example
  • Example#4347 - Ds\Map::copy example
  • Example#4348 - Ds\Map::diff example
  • Example#4349 - Ds\Map::filter example using callback function
  • Example#4350 - Ds\Map::filter example without a callback function
  • Example#4351 - Ds\Map::first example
  • Example#4352 - Ds\Map::get example
  • Example#4353 - Ds\Map::get example using array syntax
  • Example#4354 - Ds\Map::hasKey example
  • Example#4355 - Ds\Map::hasValue example
  • Example#4356 - Ds\Map::intersect example
  • Example#4357 - Ds\Map::isEmpty example
  • Example#4358 - Ds\Map::keys example
  • Example#4359 - Ds\Map::ksort example
  • Example#4360 - Ds\Map::ksort example using a comparator
  • Example#4361 - Ds\Map::ksorted example
  • Example#4362 - Ds\Map::ksorted example using a comparator
  • Example#4363 - Ds\Map::last example
  • Example#4364 - Ds\Map::map example
  • Example#4365 - Ds\Map::merge example
  • Example#4366 - Ds\Map::pairs example
  • Example#4367 - Ds\Map::put example
  • Example#4368 - Ds\Map::put example using objects as keys
  • Example#4369 - Ds\Map::putAll example
  • Example#4370 - Ds\Map::reduce with initial value example
  • Example#4371 - Ds\Map::reduce without an initial value example
  • Example#4372 - Ds\Map::remove example
  • Example#4373 - Ds\Map::reverse example
  • Example#4374 - Ds\Map::reversed example
  • Example#4375 - Ds\Map::skip example
  • Example#4376 - Ds\Map::slice example
  • Example#4377 - Ds\Map::sort example
  • Example#4378 - Ds\Map::sort example using a comparator
  • Example#4379 - Ds\Map::sort example
  • Example#4380 - Ds\Map::sort example using a comparator
  • Example#4381 - Ds\Map::sum integer example
  • Example#4382 - Ds\Map::sum float example
  • Example#4383 - Ds\Map::toArray example
  • Example#4384 - Ds\Map::union example
  • Example#4385 - Ds\Map::values example
  • Example#4386 - Ds\Map::xor example
  • Example#4387 - Ds\Pair::clear example
  • Example#4388 - Ds\Pair::copy example
  • Example#4389 - Ds\Pair::isEmpty example
  • Example#4390 - Ds\Pair::toArray example
  • Example#4391 - Ds\Set::add example using integers
  • Example#4392 - Ds\Set::add example using objects
  • Example#4393 - Ds\Set::allocate example
  • Example#4394 - Ds\Set::capacity example
  • Example#4395 - Ds\Set::clear example
  • Example#4396 - Ds\Set::__construct example
  • Example#4397 - Ds\Set::contains example
  • Example#4398 - Ds\Set::copy example
  • Example#4399 - Ds\Set::diff example
  • Example#4400 - Ds\Set::filter example using callback function
  • Example#4401 - Ds\Set::filter example without a callback function
  • Example#4402 - Ds\Set::first example
  • Example#4403 - Ds\Set::get example
  • Example#4404 - Ds\Set::get example using array syntax
  • Example#4405 - Ds\Set::intersect example
  • Example#4406 - Ds\Set::isEmpty example
  • Example#4407 - Ds\Set::join example using a separator string
  • Example#4408 - Ds\Set::join example without a separator string
  • Example#4409 - Ds\Set::last example
  • Example#4410 - Ds\Set::merge example
  • Example#4411 - Ds\Set::reduce with initial value example
  • Example#4412 - Ds\Set::reduce without an initial value example
  • Example#4413 - Ds\Set::remove example
  • Example#4414 - Ds\Set::reverse example
  • Example#4415 - Ds\Set::reversed example
  • Example#4416 - Ds\Set::slice example
  • Example#4417 - Ds\Set::sort example
  • Example#4418 - Ds\Set::sort example using a comparator
  • Example#4419 - Ds\Set::sorted example
  • Example#4420 - Ds\Set::sorted example using a comparator
  • Example#4421 - Ds\Set::sum integer example
  • Example#4422 - Ds\Set::sum float example
  • Example#4423 - Ds\Set::toArray example
  • Example#4424 - Ds\Set::union example
  • Example#4425 - Ds\Set::xor example
  • Example#4426 - Ds\Stack::clear example
  • Example#4427 - Ds\Stack::__construct example
  • Example#4428 - Ds\Stack::copy example
  • Example#4429 - Ds\Stack::isEmpty example
  • Example#4430 - Ds\Stack::peek example
  • Example#4431 - Ds\Stack::pop example
  • Example#4432 - Ds\Stack::push example
  • Example#4433 - Ds\Stack::toArray example
  • Example#4434 - Ds\Queue::allocate example
  • Example#4435 - Ds\Queue::capacity example
  • Example#4436 - Ds\Queue::clear example
  • Example#4437 - Ds\Queue::__construct example
  • Example#4438 - Ds\Queue::copy example
  • Example#4439 - Ds\Queue::isEmpty example
  • Example#4440 - Ds\Queue::peek example
  • Example#4441 - Ds\Queue::pop example
  • Example#4442 - Ejemplo de Ds\Queue::push
  • Example#4443 - Ejemplo de Ds\Queue::toArray
  • Example#4444 - Ds\PriorityQueue::allocate example
  • Example#4445 - Ds\PriorityQueue::capacity example
  • Example#4446 - Ds\PriorityQueue::clear example
  • Example#4447 - Ds\PriorityQueue::__construct example
  • Example#4448 - Ds\PriorityQueue::copy example
  • Example#4449 - Ds\PriorityQueue::isEmpty example
  • Example#4450 - Ds\PriorityQueue::peek example
  • Example#4451 - Ds\PriorityQueue::pop example
  • Example#4452 - Ds\PriorityQueue::push example
  • Example#4453 - Ds\PriorityQueue::toArray example
  • Example#4454 - Uso del módulo cURL de PHP para capturar página principal de example.com
  • Example#4455 - Inicializar una nueva sesión CURL y capturar una página web
  • Example#4456 - Copiar un recurso cURL
  • Example#4457 - curl_errno ejemplo
  • Example#4458 - Ejemplo de curl_error
  • Example#4459 - Ejemplo con curl_escape
  • Example#4460 - Capturar una página web
  • Example#4461 - Ejemplo de curl_getinfo
  • Example#4462 - Ejemplo de curl_getinfo con el parámetro opt
  • Example#4463 - Inicia una nueva sesión cURL y captura una página web
  • Example#4464 - curl_multi_add_handle example
  • Example#4465 - curl_multi_close example
  • Example#4466 - curl_multi_exec example
  • Example#4467 - Un ejemplo de curl_multi_info_read
  • Example#4468 - curl_multi_init example
  • Example#4469 - Ejemplo con curl_multi_strerror
  • Example#4470 - Ejemplo con curl_reset
  • Example#4471 - Iniciando una nueva sesión cURL y capturando una página web
  • Example#4472 - O nuestra implementación de curl_setopt_array
  • Example#4473 - Inicializar una nueva sesión de cURL y obtener una página web
  • Example#4474 - Subir un fichero (obsoleto a partir de PHP 5.5.0)
  • Example#4475 - Ejemplo con curl_share_setopt
  • Example#4476 - Ejemplo con curl_share_init
  • Example#4477 - Ejemplo de curl_share_setopt
  • Example#4478 - Ejemplo de curl_errno
  • Example#4479 - Ejemplo de curl_escape
  • Example#4480 - ejemplo de curl_version
  • Example#4481 - Ejemplo con CURLFile::__construct
  • Example#4482 - Simple HTTP client
  • Example#4483 - HTTP client using asynchronous DNS resolver
  • Example#4484 - Echo server
  • Example#4485 - SSL echo server
  • Example#4486 - Signal handler
  • Example#4487 - Use libevent's loop to process requests of `eio' extension
  • Example#4488 - Miscellaneous
  • Example#4489 - Simple HTTP server
  • Example#4490 - Simple HTTPS server
  • Example#4491 - OpenSSL connection
  • Example#4492 - EventHttpConnection::makeRequest example
  • Example#4493 - Connection listener based on a UNIX domain socket
  • Example#4494 - Simple SMTP server
  • Example#4495 - Handling SIGTERM signal
  • Example#4496 - Event::addSignal example
  • Example#4497 - Event::addTimer example
  • Example#4498 - Ejemplo con EventBase::getFeatures
  • Example#4499 - Ejemplo con EventBase::getMethod
  • Example#4500 - EventBuffer::search example
  • Example#4501 - EventBufferEvent::connect example
  • Example#4502 - Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console
  • Example#4503 - EventBufferEvent::connectHost example
  • Example#4504 - Buffer event's read callback
  • Example#4505 - EventBufferEvent::getOutput example
  • Example#4506 - EventBufferEvent::sslError example
  • Example#4507 - Simple SMTP server
  • Example#4508 - EventConfig::avoidMethod example
  • Example#4509 - EventConfig::__construct example
  • Example#4510 - EventConfig::requireFeatures example
  • Example#4511 - EventHttp::accept example
  • Example#4512 - EventHttp::addServerAlias example
  • Example#4513 - EventHttp::bind example
  • Example#4514 - Simple HTTP server
  • Example#4515 - EventHttp::setCallback example
  • Example#4516 - EventHttp::setDefaultCallback example
  • Example#4517 - EventHttpConnection::makeRequest example
  • Example#4518 - EventHttpConnection::setCloseCallback example
  • Example#4519 - EventHttpRequest::__construct example
  • Example#4520 - EventHttpRequest::sendError example
  • Example#4521 - EventListener::__construct example
  • Example#4522 - EventSslContext::__construct example
  • Example#4523 - Ejemplo FTP
  • Example#4524 - Ejemplo de ftp_alloc
  • Example#4525 - Ejemplo de ftp_cdup
  • Example#4526 - Ejemplo de ftp_chdir
  • Example#4527 - Ejemplo de ftp_chmod
  • Example#4528 - Ejemplo de ftp_close
  • Example#4529 - Ejemplo de ftp_connect
  • Example#4530 - Ejemplo de ftp_delete
  • Example#4531 - Ejemplo de ftp_exec
  • Example#4532 - Ejemplo de ftp_fget
  • Example#4533 - Ejemplo de ftp_fput
  • Example#4534 - Ejemplo de ftp_get_option
  • Example#4535 - Ejemplo de ftp_get
  • Example#4536 - Ejemplo de ftp_login
  • Example#4537 - Ejemplo de ftp_mdtm
  • Example#4538 - Ejemplo de ftp_mkdir
  • Example#4539 - ftp_mlsd example
  • Example#4540 - Ejemplo de ftp_nb_continue
  • Example#4541 - Ejemplo de ftp_nb_fget
  • Example#4542 - Ejemplo de ftp_nb_fput
  • Example#4543 - Ejemplo de ftp_nb_get
  • Example#4544 - Reanudar una descarga con ftp_nb_get
  • Example#4545 - Reanudar una descarga en la posición 100 a un nuevo archivo con ftp_nb_get
  • Example#4546 - Ejemplo de ftp_nb_put
  • Example#4547 - Reanudación de un proceso de carga con ftp_nb_put
  • Example#4548 - Ejemplo de ftp_nlist
  • Example#4549 - Ejemplo de ftp_pasv
  • Example#4550 - Ejemplo de ftp_put
  • Example#4551 - Ejemplo de ftp_pwd
  • Example#4552 - Uso de ftp_raw para iniciar sesión en un servidor FTP de forma manual.
  • Example#4553 - Ejemplo de ftp_rawlist
  • Example#4554 - Ejemplo de ftp_rename
  • Example#4555 - Ejemplo de ftp_rmdir
  • Example#4556 - Ejemplo de ftp_set_option
  • Example#4557 - Envío de un comando SITE a un servidor FTP
  • Example#4558 - Ejemplo de ftp_size
  • Example#4559 - Ejemplo de ftp_ssl_connect
  • Example#4560 - Ejemplo de ftp_systype
  • Example#4561 - Cliente y trabajador básicos en Gearman
  • Example#4562 - Cliente y trabajador básicos en Gearman, trabajo en segundo plano
  • Example#4563 - Cliente y trabajador básicos, enviando tareas
  • Example#4564 - Añadir dos servidores de trabajos
  • Example#4565 - Añade dos servidores de trabajos
  • Example#4566 - Envío básico de dos tareas
  • Example#4567 - Envío básico de dos tareas pasando contexto de la aplicación
  • Example#4568 - Dos tareas, una en segundo plano y la otra no
  • Example#4569 - Una tarea de prioridad alta junto con dos tareas de prioridad normal
  • Example#4570 - Una tarea de baja prioridad junto con dos tareas de prioridad normal
  • Example#4571 - Monitor para el estado de finalización de múltiples tareas en segundo plano
  • Example#4572 - Envío de un trabajo con retorno inmediato
  • Example#4573 - Envío de un trabajo y obtención del estado incremental
  • Example#4574 - Envío y monitorización de un trabajo en segundo plano
  • Example#4575 - Envío de un trabajo sencillo con retorno inmediato
  • Example#4576 - Enviar un trabajo y recuperar el estado incremental
  • Example#4577 - Obtiene el estado de un trabajo en ejecución de larga duración
  • Example#4578 - Monitorización del estado de un trabajo ejecutandose en segundo plano
  • Example#4579 - Sencillo trabajador que usa los datos de contexto de aplicación
  • Example#4580 - Añade servidores Gearman alternativos
  • Example#4581 - Añade dos servidores de trabajo
  • Example#4582 - Ejemplo de GearmanWorker::setId
  • Example#4583 - Un trabajador sencillo con un tiempo de espera de 5 segundos
  • Example#4584 - Running worker in non-blocking mode
  • Example#4585 - GearmanWorker::work example
  • Example#4586 - Testing support for paged result control
  • Example#4587 - Ejemplo de búsqueda LDAP
  • Example#4588 - Ejemplo completo con enlace autenticado
  • Example#4589 - Ejemplo de autenticación
  • Example#4590 - Ejemplo de autenticación anónima
  • Example#4591 - Ejemplo completo de revisión de contraseña
  • Example#4592 - Ejemplo de conexión a un servidor LDAP.
  • Example#4593 - Ejemplo de conexión segura a un servidor LDAP.
  • Example#4594 - Paginación LDAP
  • Example#4595 - Paginación LDAP
  • Example#4596 - Ejemplo de ldap-count-entries
  • Example#4597 - Enumerando todos los mensajes de error de LDAP
  • Example#4598 - Generación y captura de un error
  • Example#4599 - PASSWD extended operation
  • Example#4600 - Whoami extended operation
  • Example#4601 - Mostrar la lista de atributos mantenida por una entrada de directorio en particular
  • Example#4602 - Revisar la versión del protocolo
  • Example#4603 - Listar todos los valores del atributo "correo" para una entrada de directorio
  • Example#4604 - Producir una lista de todas las unidades organizacionales de una organización
  • Example#4605 - Add a telephone number to a contact
  • Example#4606 - Rename a user
  • Example#4607 - Add two e-mail addresses to a user
  • Example#4608 - Change a user's password
  • Example#4609 - Change a user's password (Active Directory)
  • Example#4610 - Ejemplo de ldap_parse_result
  • Example#4611 - Búsqueda LDAP
  • Example#4612 - Establecer la versión del protocolo
  • Example#4613 - Establecer controles del servidor
  • Example#4614 - Clasificador de LDAP
  • Example#4615 - Ejemplos de la extensión memcache extension
  • Example#4616 - Usando el gestor de sesiones de memcache
  • Example#4617 - Ejemplo Memcache::add
  • Example#4618 - Ejemplo Memcache::addServer
  • Example#4619 - Ejemplo Memcache::close
  • Example#4620 - Memcache::connect example
  • Example#4621 - Ejemplo Memcache::decrement
  • Example#4622 - Ejemplo de Memcache::delete
  • Example#4623 - Ejemplo de Memcache::flush
  • Example#4624 - Ejemplo de Memcache::get
  • Example#4625 - Ejemplo de Memcache::getExtendedStats
  • Example#4626 - Ejemplo de Memcache::getServerStatus
  • Example#4627 - Ejemplo de Memcache::getVersion
  • Example#4628 - Ejemplo de Memcache::increment
  • Example#4629 - Ejemplo de Memcache::pconnect
  • Example#4630 - Ejemplo de Memcache::replace
  • Example#4631 - Ejemplo de Memcache::set
  • Example#4632 - Ejemplo de Memcache::set
  • Example#4633 - Ejemplo de Memcache::setCompressThreshold
  • Example#4634 - Ejemplo de Memcache::setServerParams
  • Example#4635 - Ejemplo retrollamada de resultados
  • Example#4636 - Ejemplo de lectura de retrollamada
  • Example#4637 - Ejemplo de Memcached::addServer
  • Example#4638 - Ejemplo de Memcached::addServers
  • Example#4639 - Ejemplo de Memcached::append
  • Example#4640 - Ejemplo de Memcached::cas
  • Example#4641 - Crear un objeto Memcached
  • Example#4642 - Ejemplo de Memcached::decrement
  • Example#4643 - Ejemplo de Memcached::delete
  • Example#4644 - Ejemplo de Memcached::fetch
  • Example#4645 - Ejemplo de Memcached::getDelayed
  • Example#4646 - Ejemplo de Memcached::flush
  • Example#4647 - Ejemplo 1 Memcached::get
  • Example#4648 - Otro ejemplo de Memcached::get
  • Example#4649 - Ejemplo de Memcached::getDelayed
  • Example#4650 - Ejemplo de Memcached::getMulti
  • Example#4651 - Ejemplo de Memcached::GET_PRESERVE_ORDER
  • Example#4652 - Obtener opciones de Memcached
  • Example#4653 - Ejemplo de Memcached::getResultCode
  • Example#4654 - Ejemplo de Memcached::getResultMessage
  • Example#4655 - Ejemplo de Memcached::getServerByKey
  • Example#4656 - Ejemplo de Memcached::getServerList
  • Example#4657 - Ejemplo de Memcached::getStats
  • Example#4658 - Ejemplo de Memcached::getVersion
  • Example#4659 - Ejemplo de Memcached::increment
  • Example#4660 - Ejemplo de Memcached::prepend
  • Example#4661 - Ejemplo de Memcached::set
  • Example#4662 - Ejemplo de Memcached::setByKey
  • Example#4663 - Ejemplo de Memcached::setMulti
  • Example#4664 - Establecer una opción de Memcached
  • Example#4665 - Establecer opciones de Memcached
  • Example#4666 - mqseries_back example
  • Example#4667 - mqseries_begin example
  • Example#4668 - mqseries_close example
  • Example#4669 - mqseries_cmit example
  • Example#4670 - mqseries_conn example
  • Example#4671 - mqseries_connx example
  • Example#4672 - mqseries_connx example using SSL connection & OCSP Responder URL
  • Example#4673 - mqseries_disc example
  • Example#4674 - mqseries_get example
  • Example#4675 - mqseries_inq example
  • Example#4676 - mqseries_open example
  • Example#4677 - mqseries_put example
  • Example#4678 - mqseries_strerror example
  • Example#4679 - Using dns_get_record
  • Example#4680 - Using dns_get_record and DNS_ANY
  • Example#4681 - Ejemplo de fsockopen
  • Example#4682 - Utilización de una conexión UDP
  • Example#4683 - Un ejemplo sencillo de gethostbyaddr
  • Example#4684 - Ejemplo simple de gethostbyname
  • Example#4685 - Ejemplo de gethostbynamel
  • Example#4686 - Un ejemplo simple de gethostname
  • Example#4687 - Ejemplo de getprotobyname
  • Example#4688 - Ejemplo de getservbyname
  • Example#4689 - header_register_callback example
  • Example#4690 - Eliminar un encabezado específico.
  • Example#4691 - Eliminar todos los encabezados previamente establecidos.
  • Example#4692 - Diálogo de descarga
  • Example#4693 - Directivas caché
  • Example#4694 - Ejemplos usando headers_list
  • Example#4695 - Ejemplos usando headers_sent
  • Example#4696 - Empleo de http_response_code en un entorno de servidor web
  • Example#4697 - Empleo de http_response_code en un entorno CLI
  • Example#4698 - Ejemplo de inet_ntop
  • Example#4699 - Ejemplo de inet_pton
  • Example#4700 - Ejemplo de ip2long
  • Example#4701 - Desplegar una dirección IP
  • Example#4702 - Ejemplo de envío con setcookie
  • Example#4703 - Ejemplo de eliminación con setcookie
  • Example#4704 - setcookie y los arrays
  • Example#4705 - Uso de syslog
  • Example#4706 - Procedimiento de utilización de rrd
  • Example#4707 - Procedimiento de utilización de OOP rrd
  • Example#4708 - Ejemplo de RRDGraph::setOptions
  • Example#4709 - Establecer varias opciones de color
  • Example#4710 - Ejemplos de RRDUpdater::update
  • Example#4711 - Fetch instrumented calls
  • Example#4712 - Fetch the list of functions scoutapm will instrument
  • Example#4713 - snmp_get_quick_print example
  • Example#4714 - Using snmp_get_valueretrieval
  • Example#4715 - Using snmp_read_mib
  • Example#4716 - Using snmp_set_enum_print
  • Example#4717 - Using snmprealwalk
  • Example#4718 - Using snmp_set_quick_print
  • Example#4719 - Using snmp_set_valueretrieval
  • Example#4720 - Using snmp2_get
  • Example#4721 - Using snmp2_get_next
  • Example#4722 - Using snmp2_real_walk
  • Example#4723 - Using snmp2_set
  • Example#4724 - Using snmp2_set for setting BITS SNMP object id
  • Example#4725 - snmp2_walk Example
  • Example#4726 - Using snmp3_get
  • Example#4727 - Using snmp3_getnext
  • Example#4728 - Using snmp3_real_walk
  • Example#4729 - Using snmp3_set
  • Example#4730 - Using snmp3_set for setting BITS SNMP object id
  • Example#4731 - snmp3_walk Example
  • Example#4732 - Using snmpget
  • Example#4733 - Using snmpgetnext
  • Example#4734 - Using snmprealwalk
  • Example#4735 - Using snmpset
  • Example#4736 - Using snmpset for setting BITS SNMP object id
  • Example#4737 - snmpwalk Example
  • Example#4738 - snmpwalkoid Example
  • Example#4739 - Ejemplo de SNMP::close
  • Example#4740 - Fetching sysLocation
  • Example#4741 - Single SNMP object
  • Example#4742 - Multiple SNMP objects
  • Example#4743 - Ejemplo de SNMP::getErrno
  • Example#4744 - Ejemplo de SNMP::getError
  • Example#4745 - Single SNMP object
  • Example#4746 - Miltiple SNMP objects
  • Example#4747 - Set single SNMP object id
  • Example#4748 - Set multiple values using single SNMP::set call
  • Example#4749 - Using SNMP::set for setting BITS SNMP object id
  • Example#4750 - SNMP::setSecurity example
  • Example#4751 - SNMP::walk example
  • Example#4752 - suffixAsKey example
  • Example#4753 - Ejemplo de socket: Servidor TCP/IP sencillo
  • Example#4754 - Ejemplo de socket: Cliente TCP/IP sencillo
  • Example#4755 - Usar socket_bind para establecer la dirección de origen
  • Example#4756 - Ejemplo de socket_create_pair
  • Example#4757 - Ejemplo IPC de socket_create_pair
  • Example#4758 - Ejemplo de socket_get_option
  • Example#4759 - Ejemplo de socket_import_stream
  • Example#4760 - Un ejemplo de socket_last_error
  • Example#4761 - Un ejemplo de socket_recv
  • Example#4762 - Un ejemplo de socket_recvfrom
  • Example#4763 - Usar null con socket_select
  • Example#4764 - Comprender el resultado de socket_select
  • Example#4765 - Un ejemplo de socket_select
  • Example#4766 - Ejemplo de socket_sendto
  • Example#4767 - Un ejemplo de socket_set_block
  • Example#4768 - Un ejemplo de socket_set_nonblock
  • Example#4769 - Un ejemplo de socket_set_option
  • Example#4770 - Ejemplo de socket_strerror
  • Example#4771 - Authenticating with a ssh agent
  • Example#4772 - Authentication using a public hostkey
  • Example#4773 - Retrieving a list of authentication methods
  • Example#4774 - Authenticating with a password
  • Example#4775 - Authentication using a public key
  • Example#4776 - ssh2_connect
  • Example#4777 - Executing a command
  • Example#4778 - Opening a shell and retrieving the stderr stream associated with it
  • Example#4779 - Checking the fingerprint against a known value
  • Example#4780 - Determining what methods were negotiated
  • Example#4781 - Adding a publickey with ssh2_publickey_add
  • Example#4782 - Listing authorized keys with ssh2_publickey_list
  • Example#4783 - Descargar un fichero mediante SCP
  • Example#4784 - Cargar un fichero via SCP
  • Example#4785 - Changing the mode of a file on a remote server
  • Example#4786 - Stating a symbolic link via SFTP
  • Example#4787 - Creating a directory on a remote server
  • Example#4788 - Reading a symbolic link
  • Example#4789 - Resolving a pathname
  • Example#4790 - Renaming a file via sftp
  • Example#4791 - Removing a directory on a remote server
  • Example#4792 - Stating a file via SFTP
  • Example#4793 - Creating a symbolic link
  • Example#4794 - Deleting a file
  • Example#4795 - Abrir un fichero a través de SFTP
  • Example#4796 - Requesting an interactive shell
  • Example#4797 - Opening a tunnel to an arbitrary host
  • Example#4798 - Estilo orientado a objetos
  • Example#4799 - Estilo por procedimientos
  • Example#4800 - Ejemplo de stomp_connect_error
  • Example#4801 - Ejemplo de stomp_version
  • Example#4802 - Estilo orientado a objetos
  • Example#4803 - Estilo por procedimientos
  • Example#4804 - Estilo orientado a objetos
  • Example#4805 - Estilo por procedimientos
  • Example#4806 - Estilo orientado a objetos
  • Example#4807 - Estilo por procedimientos
  • Example#4808 - Estilo orientado a objetos
  • Example#4809 - Estilo por procedimientos
  • Example#4810 - Estilo orientado a objetos
  • Example#4811 - Estilo por procedimientos
  • Example#4812 - Estilo orientado a objetos
  • Example#4813 - Estilo por procedimientos
  • Example#4814 - Estilo orientado a objetos
  • Example#4815 - Estilo procedural
  • Example#4816 - Estilo orientado a objetos
  • Example#4817 - Estilo por procedimientos
  • Example#4818 - Estilo orientado a objetos
  • Example#4819 - Estilo por procedimientos
  • Example#4820 - Train from array
  • Example#4821 - Train from a file
  • Example#4822 - Ejemplo de svn_add
  • Example#4823 - Ejemplo de autenticación por omisión
  • Example#4824 - Ejemplo de svn_blame
  • Example#4825 - Ejemplo básico
  • Example#4826 - Ejemplo básico
  • Example#4827 - Ejemplo básico
  • Example#4828 - Ejemplo básico
  • Example#4829 - Ejemplo básico
  • Example#4830 - Ejemplo básico
  • Example#4831 - Comparando dos revisiones de una ruta de acceso a repositorio
  • Example#4832 - Comparativa portable de dos ficheros locales
  • Example#4833 - Ejemplo de svn_export
  • Example#4834 - Ejemplo básico
  • Example#4835 - svn_log example
  • Example#4836 - svn_ls example
  • Example#4837 - Ejemplo básico
  • Example#4838 - Ejemplo básico
  • Example#4839 - Denegar todas las conexiones desde localhost
  • Example#4840 - Prohibición de una URL
  • Example#4841 - Obtención de una instantánea de las estadísticas
  • Example#4842 - Lectura del log de varnish en la memoria compartida
  • Example#4843 - ejemplo de VarnishAdmin::__construct
  • Example#4844 - Busqueda Paralela usando YAZ
  • Example#4845 - Configuración del CCL
  • Example#4846 - Análisis CCL
  • Example#4847 - Actualizar registro
  • Example#4848 - Array para registro GRS-1
  • Example#4849 - Trabajar con MARCXML
  • Example#4850 - función PHP que escanea títulos
  • Example#4851 - Query Examples
  • Example#4852 - Criterios de Ordenación
  • Example#4853 - Un ejemplo de ZMQContext
  • Example#4854 - Un ejemplo de ZMQContext
  • Example#4855 - Un ejemplo de ZMQContext
  • Example#4856 - Un ejemplo de ZMQSocket
  • Example#4857 - Un ejemplo de send/recv
  • Example#4858 - Un ejemplo de ZMQPoll
  • Example#4859 - zookeeper_dispatch example #1
  • Example#4860 - zookeeper_dispatch example #2
  • Example#4861 - Zookeeper::addAuth example
  • Example#4862 - Zookeeper::create example
  • Example#4863 - Zookeeper::delete example
  • Example#4864 - Zookeeper::exists example
  • Example#4865 - Zookeeper::get example
  • Example#4866 - Zookeeper::get stat example
  • Example#4867 - Zookeeper::getAcl example
  • Example#4868 - Zookeeper::getChildren example
  • Example#4869 - Zookeeper::set example
  • Example#4870 - Zookeeper::setAcl example
  • Example#4871 - Zookeeper::setDebugLevel example
  • Example#4872 - ZookeeperConfig::add example
  • Example#4873 - ZookeeperConfig::get example
  • Example#4874 - ZookeeperConfig::remove example
  • Example#4875 - ZookeeperConfig::set example
  • Example#4876 - Ejemplo de solr_get_version
  • Example#4877 - Contenido del archivo BootStrap
  • Example#4878 - Añadir un documento al índice
  • Example#4879 - Fusionar un documento con otro documento
  • Example#4880 - Buscar documentos - respuestas de SolrObject
  • Example#4881 - Buscar documentos - respuestas de SolrDocument
  • Example#4882 - Ejemplo sencillo de TermsComponent - básico
  • Example#4883 - Ejemplo sencillo de TermsComponent - usar un prefijo
  • Example#4884 - Ejemplo sencillo de TermsComponent - especificar una frecuencia mínima
  • Example#4885 - Ejemplo sencillo de Facet
  • Example#4886 - Ejemplo sencillo de Facet - con sobrescritura de campo opcional para mincount
  • Example#4887 - Ejemplo de fecha de faceta
  • Example#4888 - Conectar a un Servidor con SSL Habilitado
  • Example#4889 - Colapsar un SolrQuery
  • Example#4890 - Ejemplo de conseguir el tiempo real Solr(RTG) SolrClient::getById
  • Example#4891 - SolrInputDocument::addChildDocument example
  • Example#4892 - SolrInputDocument::addChildDocuments example
  • Example#4893 - Ejemplo de SolrDocument::toArray
  • Example#4894 - Ejemplo de SolrObject::__construct
  • Example#4895 - Ejemplo de SolrObject::offsetUnset
  • Example#4896 - Ejemplo de SolrClient::addDocument
  • Example#4897 - Ejemplo 2 de SolrClient::addDocument
  • Example#4898 - Ejemplo de SolrClient::addDocuments
  • Example#4899 - Ejemplo de SolrClient::__construct
  • Example#4900 - Ejemplo de SolrQuery::deleteByQuery
  • Example#4901 - SolrClient::getById example
  • Example#4902 - SolrClient::getByIds example
  • Example#4903 - Ejemplo de SolrClient::ping
  • Example#4904 - Ejemplo de SolrClient::query
  • Example#4905 - Ejemplo de SolrClient::request
  • Example#4906 - Ejemplo de SolrClient::setResponseWriter
  • Example#4907 - Ejemplo de SolrParams::setParam
  • Example#4908 - Ejemplo de SolrQuery::addFacetField
  • Example#4909 - Ejemplo de SolrQuery::addFacetField
  • Example#4910 - Ejemplo de SolrQuery::addFilterQuery
  • Example#4911 - SolrQuery::addGroupSortField example
  • Example#4912 - SolrQuery::collapse example
  • Example#4913 - SolrQuery::setExpand example
  • Example#4914 - SolrDisMaxQuery::addBigramPhraseField example
  • Example#4915 - SolrDisMaxQuery::addBoostQuery example
  • Example#4916 - SolrDisMaxQuery::addPhraseField example
  • Example#4917 - SolrDisMaxQuery::addQueryField example
  • Example#4918 - SolrDisMaxQuery::addTrigramPhraseField example
  • Example#4919 - SolrDisMaxQuery::addUserField example
  • Example#4920 - SolrDisMaxQuery::__construct example
  • Example#4921 - SolrDisMaxQuery::removeBigramPhraseField example
  • Example#4922 - SolrDisMaxQuery::removeBoostQuery example
  • Example#4923 - SolrDisMaxQuery::removePhraseField example
  • Example#4924 - SolrDisMaxQuery::removeQueryField example
  • Example#4925 - SolrDisMaxQuery::removeTrigramPhraseField example
  • Example#4926 - SolrDisMaxQuery::removeUserField example
  • Example#4927 - SolrDisMaxQuery::setBigramPhraseFields example
  • Example#4928 - SolrDisMaxQuery::setBigramPhraseSlop example
  • Example#4929 - SolrDisMaxQuery::setBoostFunction example
  • Example#4930 - SolrDisMaxQuery::setBoostQuery example
  • Example#4931 - SolrDisMaxQuery::setMinimumMatch example
  • Example#4932 - SolrDisMaxQuery::setPhraseFields example
  • Example#4933 - SolrDisMaxQuery::setPhraseSlop example
  • Example#4934 - SolrDisMaxQuery::setQueryAlt example
  • Example#4935 - SolrDisMaxQuery::setQueryPhraseSlop example
  • Example#4936 - SolrDisMaxQuery::setTieBreaker example
  • Example#4937 - SolrDisMaxQuery::setTrigramPhraseFields example
  • Example#4938 - SolrDisMaxQuery::setTrigramPhraseSlop example
  • Example#4939 - SolrDisMaxQuery::setUserFields example
  • Example#4940 - SolrDisMaxQuery::useDisMaxQueryParser example
  • Example#4941 - SolrDisMaxQuery::useEDisMaxQueryParser example
  • Example#4942 - SolrCollapseFunction::__construct example
  • Example#4943 - SolrCollapseFunction::setHint example
  • Example#4944 - SolrCollapseFunction::setMax example
  • Example#4945 - Ejemplo de uso básico
  • Example#4946 - Desactivar el intérprete de PHP en un directorio utilizando .htaccess
  • Example#4947 - Ejemplo de apache_get_modules
  • Example#4948 - Ejemplo de apache_get_version
  • Example#4949 - Ejemplo de apache_getenv
  • Example#4950 - apache_lookup_uri example
  • Example#4951 - Paso de información entre PHP y Perl
  • Example#4952 - Registro de valores en access.log
  • Example#4953 - Ejemplo de apache_request_headers
  • Example#4954 - Ejemplo de apache_response_headers
  • Example#4955 - Estableciendo una variable de entorno de Apache usando apache_setenv
  • Example#4956 - Ejemplo de getallheaders
  • Example#4957 - Registrar una variable con $_SESSION.
  • Example#4958 - Desregistrar una variable con $_SESSION
  • Example#4959 - Contar el número de peticiones de un sólo usuario
  • Example#4960 - Ejemplo de información
  • Example#4961 - Ejemplo de session_cache_expire
  • Example#4962 - Ejemplo de session_cache_limiter
  • Example#4963 - Ejemplo de session_create_id con session_regenerate_id
  • Example#4964 - Destruir una sesión con $_SESSION
  • Example#4965 - Ejemplo de session_gc para administradores de tareas como cron
  • Example#4966 - Ejemplo de session_gc para un script accesible al usuario
  • Example#4967 - Ejemplo de session_name
  • Example#4968 - Un ejemplo de session_regenerate_id
  • Example#4969 - Gestor de seseiones personalizado: véase el código completo en la sinopsis de SessionHandlerInterface.
  • Example#4970 - Gestor de almacenamiento de sesiones personalizado usando objetos
  • Example#4971 - pagina1.php
  • Example#4972 - pagina2.php
  • Example#4973 - Sobrescribir el tiempo de vida de la cookie
  • Example#4974 - Leer la sesión y cerrarla
  • Example#4975 - Usar SessionHandler para añadir encriptación a los gestores de almacenamiento internos de PHP.
  • Example#4976 - Ejemplo usando SessionHandlerInterface
  • Example#4977 - Tokenize comma separated integer list
  • Example#4978 - Tokenize assign statement
  • Example#4979 - Simple calculator
  • Example#4980 - Parse words out from a sentence
  • Example#4981 - Ejemplos de patrones válidos
  • Example#4982 - Ejemplos de patrones no válidos
  • Example#4983 - Ejemplo comparando preg_filter con preg_replace
  • Example#4984 - Ejemplo de preg_grep
  • Example#4985 - preg_last_error_msg example
  • Example#4986 - Ejemplo de preg_last_error
  • Example#4987 - Obtener todos los números de teléfono de algún texto.
  • Example#4988 - Buscar coincidencias de etiquetas HTML (codicioso)
  • Example#4989 - Usar sub-patrones nominados
  • Example#4990 - Busca la cadena de texto "php"
  • Example#4991 - Busca la palabra "web"
  • Example#4992 - Obtener el nombre de dominio de una URL
  • Example#4993 - Usar sub-patrones nominados
  • Example#4994 - Ejemplo de preg_quote
  • Example#4995 - Poner en cursiva una palabra dentro de un texto
  • Example#4996 - Ejemplo de preg_replace_callback_array
  • Example#4997 - preg_replace_callback y función anónima
  • Example#4998 - Ejemplo de preg_replace_callback
  • Example#4999 - preg_replace_callback usando una estructura recursiva para manejar el código BB encapsulado
  • Example#5000 - Usar retroreferencias seguidas de literales numéricos
  • Example#5001 - Emplear arrays indexados con preg_replace
  • Example#5002 - Sustituir varios valores
  • Example#5003 - Quitar los espacios en blanco
  • Example#5004 - Usar el parámetro count
  • Example#5005 - Ejemplo de preg_split : Obtener las partes de un string de búsqueda
  • Example#5006 - Dividir un string en sus caracteres constituyentes
  • Example#5007 - Dividir un string mediante coincidencias y sus índices
  • Example#5008 - Ejemplos de Expresiones Regulares
  • Example#5009 - Ejemplo de ereg_replace
  • Example#5010 - Ejemplo de ereg_replace
  • Example#5011 - Sustituye URLs por vínculos
  • Example#5012 - Ejemplo de ereg
  • Example#5013 - Destaca los resultados buscados
  • Example#5014 - Ejemplo de eregi
  • Example#5015 - Ejemplo de split
  • Example#5016 - Ejemplo de split
  • Example#5017 - Ejemplo de spliti
  • Example#5018 - Ejemplo de sql_regcase
  • Example#5019 - Ejemplo de addcslashes
  • Example#5020 - Un ejemplo de addslashes
  • Example#5021 - chr Ejemplo
  • Example#5022 - Ejemplo de chunk_split
  • Example#5023 - Ejemplo de convert_uudecode
  • Example#5024 - Ejemplo de convert_uuencode
  • Example#5025 - count_chars example
  • Example#5026 - Mostrar una suma de verificación crc32
  • Example#5027 - crypt examples
  • Example#5028 - Using crypt with htpasswd
  • Example#5029 - Using crypt with different hash types
  • Example#5030 - Ejemplos de echo
  • Example#5031 - Ejemplo de explode
  • Example#5032 - Ejemplos de la devolución de explode
  • Example#5033 - Ejemplos del parámetro limit
  • Example#5034 - fprintf: enteros con relleno de ceros
  • Example#5035 - fprintf: dando formato a valores monetarios
  • Example#5036 - Ejemplo de tabla de traducción
  • Example#5037 - Ejemplo de hex2bin
  • Example#5038 - Decodificación de entidades HTML
  • Example#5039 - Un ejemplo de htmlentities
  • Example#5040 - Uso de ENT_IGNORE
  • Example#5041 - Un ejemplo de htmlspecialchars_decode
  • Example#5042 - Ejemplo de htmlspecialchars
  • Example#5043 - Ejemplo de implode
  • Example#5044 - Ejemplo de lcfirst
  • Example#5045 - Ejemplo de levenshtein
  • Example#5046 - Ejemplo de localeconv
  • Example#5047 - Ejemplo de uso de ltrim
  • Example#5048 - Ejemplo de uso de md5_file
  • Example#5049 - Ejemplo de md5
  • Example#5050 - Ejemplo básico de metaphone
  • Example#5051 - Utilizando el parámetro phonemes
  • Example#5052 - Ejemplos de money_format
  • Example#5053 - Usar nl2br
  • Example#5054 - Generar marcado HTML válido utilizando el parámetro is_xhtml
  • Example#5055 - Varios separadores de nueva línea
  • Example#5056 - Ejemplo de number_format
  • Example#5057 - Ejemplo de ord
  • Example#5058 - Examinar los bytes individuales de un string UTF-8
  • Example#5059 - Utilizando parse_str
  • Example#5060 - Ejemplos de print
  • Example#5061 - Ejemplo de uso de rtrim
  • Example#5062 - Ejemplos de setlocale
  • Example#5063 - Ejemplos para Windows de setlocale
  • Example#5064 - Ejemplo de sha1_file
  • Example#5065 - Ejemplo de sha1
  • Example#5066 - Ejemplos de soundex
  • Example#5067 - Intercambio de argumentos
  • Example#5068 - Intercambio de argumentos
  • Example#5069 - Intercambio de argumentos
  • Example#5070 - Intercambio de argumentos
  • Example#5071 - Especificar un carácter de relleno
  • Example#5072 - Especificador de posición con otros especificadores
  • Example#5073 - printf: ejemplos varios
  • Example#5074 - printf: especificadores de string
  • Example#5075 - sprintf: valores de tipo integer rellenados con ceros
  • Example#5076 - sprintf: formato de moneda
  • Example#5077 - sprintf: notación científica
  • Example#5078 - Ejemplo de sscanf
  • Example#5079 - sscanf - using optional parameters
  • Example#5080 - Using the empty string ''
  • Example#5081 - Showing case-sensitivity
  • Example#5082 - Using the empty string ''
  • Example#5083 - Showing case-sensitivity
  • Example#5084 - Ejemplo de str_ireplace
  • Example#5085 - Ejemplo de str_pad
  • Example#5086 - Ejemplo de str_repeat
  • Example#5087 - Ejemplos básicos de str_replace
  • Example#5088 - Ejemplos de trampas potenciales con str_replace
  • Example#5089 - Ejemplo de str_rot13
  • Example#5090 - Ejemplo de str_shuffle
  • Example#5091 - Ejemplos de uso de str_split
  • Example#5092 - Using the empty string ''
  • Example#5093 - Showing case-sensitivity
  • Example#5094 - Ejemplo de str_word_count
  • Example#5095 - Ejemplo de strcasecmp
  • Example#5096 - Ejemplo de strcmp
  • Example#5097 - Ejemplo de strcspn
  • Example#5098 - Ejemplo de strip_tags
  • Example#5099 - Ejemplos de stripos
  • Example#5100 - Un ejemplo de stripslashes
  • Example#5101 - Utilizando stripslashes en un array
  • Example#5102 - Ejemplo de stristr
  • Example#5103 - Probando si un string se encuentra o no
  • Example#5104 - Utilizando un needle no "string"
  • Example#5105 - Un ejemplo destrlen
  • Example#5106 - Ejemplo de strpbrk
  • Example#5107 - Usando ===
  • Example#5108 - Usando !==
  • Example#5109 - Uso de offset
  • Example#5110 - Ejemplo de strrchr
  • Example#5111 - Invertir una cadena con strrev
  • Example#5112 - Un ejemplo simple de strripos
  • Example#5113 - Verificando si hay una aguja en el pajar
  • Example#5114 - Buscando con desplazamientos
  • Example#5115 - Ejemplo de strspn
  • Example#5116 - Ejemplo de strstr
  • Example#5117 - Ejemplo de strtok
  • Example#5118 - Comportamiento anterior de strtok
  • Example#5119 - Comportamiento nuevo de strtok
  • Example#5120 - Ejemplo de strtolower
  • Example#5121 - Ejemplo de strtoupper
  • Example#5122 - Ejemplo de strtr
  • Example#5123 - Ejemplo de strtr con dos argumentos
  • Example#5124 - Comparación del comportamiento de strtr
  • Example#5125 - Un ejemplo de substr_compare
  • Example#5126 - Ejemplo de substr_count
  • Example#5127 - Ejemplo desubstr_replace
  • Example#5128 - Usando substr_replace para reemplazar múltiples strings de una vez
  • Example#5129 - Usando un start negativo
  • Example#5130 - Usando un length negativo
  • Example#5131 - Uso básico de substr
  • Example#5132 - Comportamiento de casting de substr
  • Example#5133 -
  • Example#5134 - Ejemplo de uso de trim
  • Example#5135 - Uso de trim en valores de un array
  • Example#5136 - Ejemplo de ucfirst
  • Example#5137 - Ejemplo de ucwords
  • Example#5138 - Ejemplo de ucwords con delimitadores personalizados
  • Example#5139 - vfprintf: números extendidos con ceros
  • Example#5140 - vprintf: zero-padded integers
  • Example#5141 - vsprintf: zero-padded integers
  • Example#5142 - Ejemplo de wordwrap
  • Example#5143 - Ejemplo de wordwrap
  • Example#5144 - Ejemplo de wordwrap
  • Example#5145 - Ejemplo de array_change_key_case
  • Example#5146 - Ejemplo de array_chunk
  • Example#5147 - Obtener la columna de nombres del conjunto de resultados
  • Example#5148 - Obtener la columna de apellidos del conjunto de resultados, indexada por la columna "id"
  • Example#5149 - Obtener la columna de nombres de usuarios de la propiedad pública "nombre_usuario" de un objeto
  • Example#5150 - Obtener la columna de nombres de la propiedad privada "nombre" de un objeto empleando el método mágico __get.
  • Example#5151 - Ejemplo simple de array_combine
  • Example#5152 - Ejemplo de array_count_values
  • Example#5153 - Ejemplo de array_diff_assoc
  • Example#5154 - Ejemplo de array_diff_assoc
  • Example#5155 - Ejemplo de array_diff_key
  • Example#5156 - Ejemplo de array_diff_uassoc
  • Example#5157 - Ejemplo de array_diff_ukey
  • Example#5158 - Ejemplo de array_diff
  • Example#5159 - Ejemplo de array_fill_keys
  • Example#5160 - Ejemplo de array_fill
  • Example#5161 - Ejemplo de array_filter
  • Example#5162 - array_filter sin callback
  • Example#5163 - array_filter con flag
  • Example#5164 - Ejemplo de array_flip
  • Example#5165 - Ejemplo de array_flip : collision
  • Example#5166 - Ejemplo de array_intersect_assoc
  • Example#5167 - Ejemplo de array_intersect_key
  • Example#5168 - Ejemplo de array_intersect_uassoc
  • Example#5169 - Ejemplo de array_intersect_ukey
  • Example#5170 - Ejemplo de array_intersect
  • Example#5171 - Ejemplo de array_key_exists
  • Example#5172 - array_key_exists vs isset
  • Example#5173 - Uso básico de array_key_first
  • Example#5174 - Ejemplo de array_keys
  • Example#5175 - Ejemplo de array_map
  • Example#5176 - array_map usando una función lambda (desde PHP 5.3.0)
  • Example#5177 - array_map - usando más arrays
  • Example#5178 - Crear un array de arrays
  • Example#5179 - array_map - con claves de tipo string
  • Example#5180 - Ejemplo de array_merge_recursive
  • Example#5181 - Ejemplo de array_merge
  • Example#5182 - Ejemplo de sencillo de array_merge
  • Example#5183 - array_merge con tipos que no son array
  • Example#5184 - Ordenar varios arrays
  • Example#5185 - Ordenar un array multidimensional
  • Example#5186 - Ordenar resultados de una base de datos
  • Example#5187 - Ordenación sin considerar mayúsculas/minúsculas
  • Example#5188 - Ejemplo de array_pad
  • Example#5189 - Ejemplo de array_pop
  • Example#5190 - Ejemplo de array_product
  • Example#5191 - Ejemplo de array_push
  • Example#5192 - Ejemplo de array_rand
  • Example#5193 - Ejemplo de array_reduce
  • Example#5194 - Ejemplo de array_replace_recursive
  • Example#5195 - array_replace_recursive y comportamiento recursivo
  • Example#5196 - Ejemplo de array_replace
  • Example#5197 - Ejemplo de array_reverse
  • Example#5198 - Ejemplo de array_search
  • Example#5199 - Ejemplo de array_shift
  • Example#5200 - Ejemplos de array_slice
  • Example#5201 - Ejemplos de array_splice
  • Example#5202 - Ejemplos de array_splice
  • Example#5203 - Ejemplos de array_sum
  • Example#5204 - Ejemplo de array_udiff_assoc
  • Example#5205 - Ejemplo de array_udiff_uassoc
  • Example#5206 - Ejemplo de array_udiff usando objetos de stdClass
  • Example#5207 - Ejemplo de array_udiff usando objetos de DateTime
  • Example#5208 - Ejemplo de array_uintersect_assoc
  • Example#5209 - Ejemplo de array_uintersect_uassoc
  • Example#5210 - Ejemplo de array_uintersect
  • Example#5211 - Ejemplo de array_unique
  • Example#5212 - array_unique y tipos
  • Example#5213 - Ejemplo de array_unshift
  • Example#5214 - Ejemplo de array_values
  • Example#5215 - Ejemplo de array_walk_recursive
  • Example#5216 - Ejemplo de array_walk
  • Example#5217 - Ejemplo de array
  • Example#5218 - Array con índice automático
  • Example#5219 - array con índice de base 1
  • Example#5220 - Accessing an array inside double quotes
  • Example#5221 - Ejemplo de arsort
  • Example#5222 - Ejemplo de la función asort
  • Example#5223 - Ejemplo de compact
  • Example#5224 - Ejemplo de count
  • Example#5225 - Ejemplo de count recursivo
  • Example#5226 - Ejemplo de uso de current y similares
  • Example#5227 - Ejemplo de each
  • Example#5228 - Atravesar un array con each
  • Example#5229 - Ejemplo de end
  • Example#5230 - Ejemplo de extract
  • Example#5231 - Ejemplo de in_array
  • Example#5232 - Ejemplo de in_array en modo estricto
  • Example#5233 - in_array con un array como aguja
  • Example#5234 - Ejemplo de key
  • Example#5235 - Ejemplo de krsort
  • Example#5236 - Ejemplo de ksort
  • Example#5237 - Ejemplos de list
  • Example#5238 - Un ejemplo del uso de list
  • Example#5239 - Empleo de list anidados
  • Example#5240 - Uso de list con índices de array
  • Example#5241 - list y orden de definiciones de índices
  • Example#5242 - Ejemplo de natcasesort
  • Example#5243 - Ejemplos de natsort demostrando su uso básico
  • Example#5244 - Ejemplos de natsort demostrando trampas potenciales
  • Example#5245 - Ejemplo del uso de next y similares
  • Example#5246 - Ejemplo de uso de prev and friends
  • Example#5247 - Ejemplos de range
  • Example#5248 - Ejemplo de reset
  • Example#5249 - Ejemplo de rsort
  • Example#5250 - Ejemplo de shuffle
  • Example#5251 - Ejemplo de sort
  • Example#5252 - Ejemplo de sort usando la ordenación insensible a mayúsculas/minúsculas natural
  • Example#5253 - Ejemplo básico de uasort
  • Example#5254 - Ejemplo de uksort
  • Example#5255 - Ejemplo de usort
  • Example#5256 - Ejemplo de usort usando un array multidimensional
  • Example#5257 - Ejemplo de usort usando una función miembro de un objeto
  • Example#5258 - Ejemplo de usort usando un cierre para ordenar un array multidimensional
  • Example#5259 - classes.inc
  • Example#5260 - test_script.php
  • Example#5261 - Ejemplo de class_alias
  • Example#5262 - Ejemplo de class_exists
  • Example#5263 - Ejemplo del parámetro autoload
  • Example#5264 - Usar get_called_class
  • Example#5265 - Ejemplo de get_class_methods
  • Example#5266 - Ejemplo de get_class_vars
  • Example#5267 - get_class_vars y comportamiento de ámbito
  • Example#5268 - Usar get_class
  • Example#5269 - Usar get_class en superclass
  • Example#5270 - Ejemplo de get_declared_classes
  • Example#5271 - Ejemplo de get_declared_interfaces
  • Example#5272 - Uso de get_object_vars
  • Example#5273 - Usar get_parent_class
  • Example#5274 - Ejemplo de interface_exists
  • Example#5275 - Ejemplo de is_a
  • Example#5276 - Usar el operador instanceof en PHP 5
  • Example#5277 - Ejemplo de is_subclass_of
  • Example#5278 - Ejemplo de is_subclass_of usando una interfaz
  • Example#5279 - Ejemplo de method_exists
  • Example#5280 - Ejemplo de method_exists estático
  • Example#5281 - Un ejemplo de property_exists
  • Example#5282 - Ejemplo de classkit_import
  • Example#5283 - Ejemplo de classkit_method_add
  • Example#5284 - Ejemplo de classkit_method_copy
  • Example#5285 - Ejemplo de classkit_method_redefine
  • Example#5286 - Ejemplo de classkit_method_remove
  • Example#5287 - Ejemplo de classkit_method_rename
  • Example#5288 - Un ejemplo de ctype_alnum (usando la localización predeterminada)
  • Example#5289 - Un ejemplo de ctype_alpha (usando la localización predeterminada)
  • Example#5290 - Un ejemplo de ctype_cntrl
  • Example#5291 - Un ejemplo de ctype_digit
  • Example#5292 - Un ejemplo de ctype_digit comparando strings con integers
  • Example#5293 - Un ejemplo de ctype_graph
  • Example#5294 - Un ejemplo de ctype_lower (usando la localidad predeterminada)
  • Example#5295 - Un ejemplo de ctype_print
  • Example#5296 - Un ejemplo de ctype_punct
  • Example#5297 - Un ejemplo de ctype_space
  • Example#5298 - Un ejemplo de ctype_upper (usando la localidad predeterminada)
  • Example#5299 - Un ejemplo de ctype_xdigit
  • Example#5300 - Configuring the default filter to act like htmlspecialchars
  • Example#5301 - Configurar el filtro predeterminado para que actúe como htmlspecialchars
  • Example#5302 - Validación de direcciones de correo con filter_var
  • Example#5303 - Validación de direcciones IP con filter_var
  • Example#5304 - Pasando opciones a filter_var
  • Example#5305 - Saneando y validando direcciones de correo
  • Example#5306 - Configuración de un filtro por omisión
  • Example#5307 - Un ejemplo con filter_input_array
  • Example#5308 - Un ejemplo de filter_input
  • Example#5309 - Ejemplo de filter_list
  • Example#5310 - Ejemplo de filter_var_array
  • Example#5311 - Un ejemplo de filter_var
  • Example#5312 - Ejemplo de call_user_func_array
  • Example#5313 - call_user_func_array usando un nombre de espacio de nombres
  • Example#5314 - Usar una función lambda
  • Example#5315 - Ejemplo de call_user_func y referencias
  • Example#5316 - Ejemplo de call_user_func
  • Example#5317 - call_user_func usando un nombre de espacios de nombres
  • Example#5318 - Usar un método de clase con call_user_func
  • Example#5319 - Usar una función lambda con call_user_func
  • Example#5320 - Crear una función anónima con create_function
  • Example#5321 - Hacer una función de proceso general con create_function
  • Example#5322 - Usar funciones anónimas como funciones de llamada de retorno
  • Example#5323 - Ejemplo de forward_static_call_array
  • Example#5324 - Ejemplo de forward_static_call
  • Example#5325 - Ejemplo de func_get_arg
  • Example#5326 - Ejemplo de func_get_arg antes y después de PHP 5.3
  • Example#5327 - func_get_arg ejemplo de argumentos byref (pasa un objeto como referencia) y byval (pasa un objeto como valor)
  • Example#5328 - Ejemplo de func_get_args
  • Example#5329 - Ejemplo de func_get_args antes y después de PHP 5.3
  • Example#5330 - func_get_args ejemplo de argumentos byref (pasa un objeto como referencia) y byval (pasa un objeto como valor)
  • Example#5331 - Ejemplo de func_num_args
  • Example#5332 - Ejemplo de func_num_args antes y después de PHP 5.3
  • Example#5333 - Ejemplo de function_exists
  • Example#5334 - Ejemplo de get_defined_functions
  • Example#5335 - Ejemplo de register_shutdown_function
  • Example#5336 - Ejemplo de register_tick_function
  • Example#5337 - Ejemplo de Quickhash
  • Example#5338 - Ejemplo de Quickhash con ArrayAccess
  • Example#5339 - Ejemplo de Quickhash con Iterator
  • Example#5340 - Ejemplo de valores de tipo string de Quickhash
  • Example#5341 - Ejemplo de QuickHashIntSet::add
  • Example#5342 - Ejemplo de QuickHashIntSet::__construct
  • Example#5343 - Ejemplo de QuickHashIntSet::delete
  • Example#5344 - Ejempl0 de QuickHashIntSet::exists
  • Example#5345 - Ejemplo de QuickHashIntSet::getSize
  • Example#5346 - Ejemplo de QuickHashIntSet::loadFromFile
  • Example#5347 - Ejemplo de QuickHashIntSet::loadFromString
  • Example#5348 - Ejemplo de QuickHashIntSet::saveToFile
  • Example#5349 - Ejemplo de QuickHashIntSet::saveToString
  • Example#5350 - Ejemplo de QuickHashIntHash::add
  • Example#5351 - Ejemplo de QuickHashIntHash::__construct
  • Example#5352 - Ejemplo de QuickHashIntHash::delete
  • Example#5353 - Ejemplo de QuickHashIntHash::exists
  • Example#5354 - Ejemplo de QuickHashIntHash::get
  • Example#5355 - Ejemplo de QuickHashIntHash::getSize
  • Example#5356 - Formato de fichero de IntHash de QuickHash
  • Example#5357 - Formato de fichero de IntHash de QuickHash
  • Example#5358 - Ejemplo de QuickHashIntHash::loadFromFile
  • Example#5359 - Ejemplo de QuickHashIntHash::loadFromString
  • Example#5360 - Ejemplo de QuickHashIntHash::saveToFile
  • Example#5361 - Ejemplo de QuickHashIntHash::saveToString
  • Example#5362 - Ejemplo de QuickHashIntHash::set
  • Example#5363 - Ejemplo de QuickHashIntHash::update
  • Example#5364 - Ejemplo de QuickHashStringIntHash::add
  • Example#5365 - Ejemplo de QuickHashStringIntHash::__construct
  • Example#5366 - Ejemplo de QuickHashStringIntHash::delete
  • Example#5367 - Ejemplo de QuickHashStringIntHash::get
  • Example#5368 - Ejemplo de QuickHashStringIntHash::getSize
  • Example#5369 - Formato de fichero de StringIntHash de QuickHash
  • Example#5370 - Formato de fichero de StringIntHash de QuickHash
  • Example#5371 - Ejemplo de QuickHashStringIntHash::loadFromFile
  • Example#5372 - Ejemplo de QuickHashStringIntHash::loadFromString
  • Example#5373 - Ejemplo de QuickHashStringIntHash::saveToFile
  • Example#5374 - Ejemplo de QuickHashStringIntHash::saveToString
  • Example#5375 - Ejemplo de QuickHashStringIntHash::set
  • Example#5376 - Ejemplo de QuickHashStringIntHash::update
  • Example#5377 - Ejemplo de QuickHashIntStringHash::add
  • Example#5378 - Ejemplo de QuickHashIntStringHash::__construct
  • Example#5379 - Ejemplo de QuickHashIntStringHash::delete
  • Example#5380 - Ejemplo de QuickHashIntStringHash::get
  • Example#5381 - Ejemplo de QuickHashIntStringHash::getSize
  • Example#5382 - Formato de fichero de IntString de QuickHash
  • Example#5383 - Formato de fichero de IntString de QuickHash
  • Example#5384 - Ejemplo de QuickHashIntStringHash::loadFromFile
  • Example#5385 - Ejemplo de QuickHashIntStringHash::loadFromString
  • Example#5386 - Ejemplo de QuickHashIntStringHash::saveToFile
  • Example#5387 - Ejemplo de QuickHashIntStringHash::saveToString
  • Example#5388 - Ejemplo de QuickHashIntStringHash::set
  • Example#5389 - Ejemplo de QuickHashIntStringHash::update
  • Example#5390 - Ejemplo de Reflection desde Shell (un terminal)
  • Example#5391 - Extendiendo las clases incorporadas
  • Example#5392 - Funcionamiento básico de ReflectionClass
  • Example#5393 - Uso básico de ReflectionClass::export
  • Example#5394 - Uso básico de ReflectionClass::getConstructor
  • Example#5395 - Ejemplo de ReflectionClass::getDefaultProperties
  • Example#5396 - Ejemplo de ReflectionClass::getDocComment
  • Example#5397 - Ejemplo de ReflectionClass::getEndLine
  • Example#5398 - Uso básico de ReflectionClass::getExtension
  • Example#5399 - Uso básico de ReflectionClass::getExtensionName
  • Example#5400 - Ejemplo de ReflectionClass::getInterfaceNames
  • Example#5401 - Ejemplo de ReflectionClass::getInterfaces
  • Example#5402 - Uso básico de ReflectionClass::getMethod
  • Example#5403 - Uso básico de ReflectionClass::getMethods
  • Example#5404 - Filtrar los resultados de ReflectionClass::getMethods
  • Example#5405 - Ejemplo de ReflectionClass::getName
  • Example#5406 - Ejemplo de ReflectionClass::getNamespaceName
  • Example#5407 - Ejemplo de filtrado con ReflectionClass::getProperties
  • Example#5408 - Uso básico de ReflectionClass::getProperty
  • Example#5409 - Basic ReflectionClass::getReflectionConstants example
  • Example#5410 - Ejemplo de ReflectionClass::getShortName
  • Example#5411 - Uso básico de ReflectionClass::getStaticPropertyValue
  • Example#5412 - Ejemplo de ReflectionClass::hasConstant
  • Example#5413 - Ejemplo de ReflectionClass::hasMethod
  • Example#5414 - Ejemplo de ReflectionClass::hasProperty
  • Example#5415 - Ejemplo de ReflectionClass::inNamespace
  • Example#5416 - Ejemplo de ReflectionClass::isAbstract
  • Example#5417 - ReflectionClass::isAnonymous example
  • Example#5418 - Uso básico de ReflectionClass::isCloneable
  • Example#5419 - Ejemplo de ReflectionClass::isFinal
  • Example#5420 - Ejemplo relacionado con ReflectionClass::isInstance
  • Example#5421 - Ejemplo de ReflectionClass::isInstantiable
  • Example#5422 - Uso básico de ReflectionClass::isInterface
  • Example#5423 - Uso básico de ReflectionClass::isInternal
  • Example#5424 - Basic ReflectionClass::isIterable Usage
  • Example#5425 - Ejemplo de ReflectionClass::isIterateable
  • Example#5426 - Uso básico de ReflectionClass::newInstanceArgs
  • Example#5427 - Ejemplo de ReflectionClass::__toString
  • Example#5428 - Ejemplo de ReflectionExtension
  • Example#5429 - Ejemplo de ReflectionExtension::getClasses
  • Example#5430 - Ejemplo de ReflectionExtension::getClassNames
  • Example#5431 - Ejemplo de ReflectionExtension::getConstants
  • Example#5432 - Ejemplo de ReflectionExtension::getDependencies
  • Example#5433 - Ejemplo de ReflectionExtension::getFunctions
  • Example#5434 - Ejemplo de ReflectionExtension::getINIEntries
  • Example#5435 - Ejemplo de ReflectionExtension::getName
  • Example#5436 - Ejemplo de ReflectionExtension::getVersion
  • Example#5437 - Ejemplo de ReflectionExtension::info
  • Example#5438 - Ejemplo de ReflectionFunction::__construct
  • Example#5439 - Ejemplo de ReflectionFunction::invoke example
  • Example#5440 - Ejemplo de ReflectionFunction::invokeArgs
  • Example#5441 - Ejemplo de ReflectionFunction::invokeArgs con argumentos por referencia
  • Example#5442 - Ejemplo de ReflectionFunction::__toString
  • Example#5443 - ReflectionFunctionAbstract::getReturnType example
  • Example#5444 - Usage on built-in functions
  • Example#5445 - ReflectionFunctionAbstract::hasReturnType example
  • Example#5446 - Usage on built-in functions
  • Example#5447 - Ejemplo de ReflectionFunctionAbstract::isClosure
  • Example#5448 - Ejemplo de ReflectionFunctionAbstract::isDeprecated
  • Example#5449 - Ejemplo de ReflectionMethod::__construct
  • Example#5450 - Ejemplo de ReflectionMethod::getDeclaringClass
  • Example#5451 - Ejemplo de ReflectionMethod::getModifiers
  • Example#5452 - Ejemplo de ReflectionMethod::getPrototype
  • Example#5453 - Ejemplo de ReflectionMethod::invoke
  • Example#5454 - Ejemplo de ReflectionMethod::invokeArgs
  • Example#5455 - Ejemplo de ReflectionMethod::__toString
  • Example#5456 - ReflectionNamedType::isBuiltin example
  • Example#5457 - Usando la clase ReflectionParameter
  • Example#5458 - Utilizar la clase ReflectionParameter
  • Example#5459 - Obtener la clase que declaró el método
  • Example#5460 - Obtención de los valores por defecto de los parámetros de la función
  • Example#5461 - ReflectionParameter::getType Usage as of PHP 7.1.0
  • Example#5462 - ReflectionParameter::getType Usage before PHP 7.1.0
  • Example#5463 - ReflectionParameter::hasType example
  • Example#5464 - Ejemplo de ReflectionProperty::__construct
  • Example#5465 - Obtener el valor de propiedades privadas y protegidas con ReflectionProperty
  • Example#5466 - ReflectionClass::getDefaultValue example
  • Example#5467 - Ejemplo de ReflectionProperty::getDocComment
  • Example#5468 - ReflectionProperty::getType example
  • Example#5469 - Ejemplo de ReflectionProperty::getValue
  • Example#5470 - ReflectionClass::hasDefaultValue example
  • Example#5471 - ReflectionProperty::hasType example
  • Example#5472 - Ejemplo de ReflectionClass::isDefault
  • Example#5473 - ReflectionProperty::isInitialized example
  • Example#5474 - Ejemplo de ReflectionProperty::setValue
  • Example#5475 - ReflectionType::allowsNull example
  • Example#5476 - ReflectionType::__toString example
  • Example#5477 - ReflectionUnionType::getTypes example
  • Example#5478 - ReflectionGenerator::__construct example
  • Example#5479 - ReflectionGenerator::getExecutingFile example
  • Example#5480 - ReflectionGenerator::getExecutingGenerator example
  • Example#5481 - ReflectionGenerator::getExecutingLine example
  • Example#5482 - ReflectionGenerator::getFunction example
  • Example#5483 - ReflectionGenerator::getThis example
  • Example#5484 - ReflectionGenerator::getTrace example
  • Example#5485 - Basic ReflectionReference::getId usage
  • Example#5486 - Ejemplos de boolval
  • Example#5487 - Ejemplo debug_zval_dump
  • Example#5488 -
  • Example#5489 -
  • Example#5490 - Una simple comparación empty / isset
  • Example#5491 - empty en índices de string
  • Example#5492 - Ejemplo de floatval
  • Example#5493 - Ejemplo de floatval con caracteres a la izquierda no numéricos
  • Example#5494 - Ejemplo de get_defined_vars
  • Example#5495 - get_resource_id example
  • Example#5496 - Ejemplo deget_resource_type
  • Example#5497 - Ejemplo de gettype
  • Example#5498 - Ejemplos de intval
  • Example#5499 - Comprobar que la variable es un array
  • Example#5500 - Ejemplos de is_bool
  • Example#5501 - Ejemplo de is_callable
  • Example#5502 - Función is_callable y constructores
  • Example#5503 - ejemplos de is_countable
  • Example#5504 - Ejemplo de is_float
  • Example#5505 - Ejemplo de is_int
  • Example#5506 - ejemplos de is_iterable
  • Example#5507 - Ejemplo is_null
  • Example#5508 - Ejemplos de is_numeric
  • Example#5509 - Ejemplo is_object
  • Example#5510 - Ejemplo de is_resource
  • Example#5511 - Ejemplo is_scalar
  • Example#5512 - Ejemplo is_string
  • Example#5513 - Ejemplos isset
  • Example#5514 - isset en indices de String
  • Example#5515 - Ejemplo print_r
  • Example#5516 - Ejemplo del parámetro devolver
  • Example#5517 - Ejemplo serialize
  • Example#5518 - Ejemplo settype
  • Example#5519 - strval usando el método mágico __toString() de PHP 5
  • Example#5520 - Ejemplo de unserialize
  • Example#5521 - Ejemplo de unserialize_callback_func
  • Example#5522 - Ejemplo de unset
  • Example#5523 - Usando el forzado a (unset)
  • Example#5524 - Ejemplo var_dump
  • Example#5525 - Ejemplos de var_export
  • Example#5526 - Exportación de clases a partir de PHP 5.1.0
  • Example#5527 - Uso de __set_state (a partir de PHP 5.1.0)
  • Example#5528 -
  • Example#5529 - Ejemplo de OAuth::fetch
  • Example#5530 - Ejemplo de OAuth::getAccessToken
  • Example#5531 - Ejemplo de OAuth::getRequestToken
  • Example#5532 - Ejemplo de OAuth::setRequestEngine
  • Example#5533 - Ejemplo de OAuth::setRsaCertificate
  • Example#5534 - Ejemplo OAuth::setToken
  • Example#5535 - Ejemplo de OAuthProvider::__construct
  • Example#5536 - Ejemplo del callback OAuthProvider::consumerHandler
  • Example#5537 - Ejemplo de OAuthProvider::generateToken
  • Example#5538 - Ejemplo de OAuthProvider::is2LeggedEndpoint
  • Example#5539 - Ejemplo de OAuthProvider::timestampNonceHandler
  • Example#5540 - Ejemplo del callback OAuthProvider::tokenHandler
  • Example#5541 - Ejemplo de is_soap_fault
  • Example#5542 - El método estándar de SOAP para el informe de errores con las excepciones
  • Example#5543 - Ejemplo de SoapClient::__doRequest
  • Example#5544 - Ejemplo de SoapClient::__getFunctions
  • Example#5545 - Ejemplo de SoapClient::__getLastRequest()
  • Example#5546 - Ejemplo de SoapClient::__getLastRequestHeaders()
  • Example#5547 - Ejemplo de SoapClient::__getLastResponse()
  • Example#5548 - Ejemplo de SoapClient::__getLastResponse()
  • Example#5549 - Ejemplo de SoapClient::__getTypes
  • Example#5550 - Ejemplo de SoapClient::__setLocation
  • Example#5551 - Ejemplo de SoapClient::__setSoapHeaders
  • Example#5552 - Definir múltiples encabezados
  • Example#5553 - Ejemplo de SoapClient::__soapCall
  • Example#5554 - Ejemplos de SoapServer::addFunction
  • Example#5555 - Ejemplo de SoapServer::getFunctions
  • Example#5556 - Ejemplo de SoapServer::handle
  • Example#5557 - Ejemplo de SoapServer::setPersistence
  • Example#5558 - Ejemplo de servidor de Yar
  • Example#5559 - Acceder al servidor desde el navegador (petición GET)
  • Example#5560 - Ejemplo de cliente de Yar
  • Example#5561 - Ejemplo de cliente concurrente de Yar
  • Example#5562 - Ejemplo de Yar_Server::__construct
  • Example#5563 - Ejemplo de Yar_Server::handle
  • Example#5564 - Ejemplo de Yar_Client::__call
  • Example#5565 - Ejemplo de Yar_Client::__construct
  • Example#5566 - Ejemplo de Yar_Client::setOpt
  • Example#5567 - Ejemplo de Yar_Concurrent_Client::call
  • Example#5568 - Ejemplo de Yar_Concurrent_Client::loop
  • Example#5569 - Ejemplo de Yar_Concurrent_Client::reset
  • Example#5570 - Ejemplo de Yar_Server_Exception::getType
  • Example#5571 - Ejemplo de Yar_Client_Exception::getType
  • Example#5572 - Ejmeplo de las funciones de clietes de XMLRPC
  • Example#5573 - Ejemplo de tipo de XML-RPC
  • Example#5574 - A xmlrpc_set_type example
  • Example#5575 - For Each en ASP
  • Example#5576 - while() ... Next() en PHP 4
  • Example#5577 - foreach en PHP 5
  • Example#5578 - Ejemplo COM (1)
  • Example#5579 - Ejemplo COM (2)
  • Example#5580 - Ejemplo DOTNET
  • Example#5581 - Ejemplo de una clase VARIANT, utilizada en PHP 4.x
  • Example#5582 - Ejemplo de una clase VARIANT, utilizada en PHP 5
  • Example#5583 - Basic COMPersistHelper::saveToFile Usage
  • Example#5584 - Ejemplo de absorción de un evento COM
  • Example#5585 - Registrar un script de PHP para ejecutarlo como un servicio
  • Example#5586 - Dejar de registrar un servicio
  • Example#5587 - Ejecutar como un servicio
  • Example#5588 - Un ejemplo de win32_create_service
  • Example#5589 - Un ejemplo de win32_delete_service
  • Example#5590 - Un ejemplo de win32_start_service_ctrl_dispatcher
  • Example#5591 - book.xml
  • Example#5592 - Creación de un nuevo objeto DOMAttr
  • Example#5593 - Ejemplo de DOMAttr::isId()
  • Example#5594 - Crear un nuevo objeto DOMCdataSection
  • Example#5595 - Creando un nuevo DOMComment
  • Example#5596 - Creando un nuevo DOMDocument
  • Example#5597 - Crear un nuevo elemento e insertarlo como raíz
  • Example#5598 - Pasando texto que contiene un & sin escapar como valor
  • Example#5599 - Crear un nuevo elemento e insertarlo como raíz
  • Example#5600 - Un ejemplo de prefijo de nombre de espacio
  • Example#5601 - Ejemplo de DOMDocument::getElementById()
  • Example#5602 - Ejemplo de uso básico
  • Example#5603 - Obtener todos los elementos XInclude
  • Example#5604 - DOMDocument::importNode ejemplo
  • Example#5605 - Creando un Documento
  • Example#5606 - Creando un Documento
  • Example#5607 - Crear un Documento
  • Example#5608 - Crear un Documento
  • Example#5609 - Invocación estática de loadXML
  • Example#5610 - Añadir un nuevo método a DOMElement para facilitar su código
  • Example#5611 - Recuperar elementos como clase personalizada
  • Example#5612 - Recuperar un propio documento
  • Example#5613 - Guardar un árbol DOM en un fichero
  • Example#5614 - Salvar un árbol HTML en una cadena
  • Example#5615 - Guardar un árbol HTML en un archivo
  • Example#5616 - Guardar un árbol DOM en un string
  • Example#5617 - Ejemplo de validación de DTD
  • Example#5618 - Ejemplo de DOMDocument::xinclude()
  • Example#5619 - Añadir información XML a su documento
  • Example#5620 - Crear un nuevo objeto DOMElement
  • Example#5621 - Establecer un atributo
  • Example#5622 - Crear un nuevo objeto DOMEntityReference
  • Example#5623 - Crear un documento con un DTD adjunto
  • Example#5624 - Comprobar su Implementación DOM
  • Example#5625 - Añadiendo un hijo
  • Example#5626 - Hijos anidados
  • Example#5627 - Ejemplo de DOMNode::getLineNo
  • Example#5628 - Ejemplo de DOMNode::getNodePath
  • Example#5629 - Eliminar un hijo
  • Example#5630 - Atravesar todas las entradas de una tabla
  • Example#5631 - Crear un nuevo objeto DOMProcessingInstruction
  • Example#5632 - Crear un nuevo objeto DOMText
  • Example#5633 - Obtener el número de todos los libros en inglés
  • Example#5634 - Obtener todos los libros en inglés
  • Example#5635 - book.xml
  • Example#5636 - DOMXPath::registerPHPFunctions con php:functionString
  • Example#5637 - DOMXPath::registerPHPFunctions con php:function
  • Example#5638 - Importar SimpleXML a DOM con dom_import_simplexml
  • Example#5639 - Ejemplo de libxml_get_errors
  • Example#5640 - Ejemplo de libxml_set_external_entity_loader
  • Example#5641 - Ejemplo de libxml_set_streams_context
  • Example#5642 - Ejemplo de libxml_use_internal_errors
  • Example#5643 - El fichero ejemplo.php a incluir con el string XML
  • Example#5644 - Obtener <argumento>
  • Example#5645 - Obtener <frase>
  • Example#5646 - Acceder a elementos no únicos en SimpleXML
  • Example#5647 - Utilizar atributos
  • Example#5648 - Comparar elementos y atributos con texto
  • Example#5649 - Comparar dos elementos
  • Example#5650 - Utilizar XPath
  • Example#5651 - Establecer valores
  • Example#5652 - Añadir elementos y atributos
  • Example#5653 - Interoperatibilidad con DOM
  • Example#5654 - Cargar un string XML erróneo
  • Example#5655 - Añadir atributos e hijos a un elemento SimpleXML
  • Example#5656 - Añade atributos e hijos a un elemento SimpleXML
  • Example#5657 - Retornar XML
  • Example#5658 - Usando asXML() en resultados SimpleXMLElement::xpath
  • Example#5659 - Interpreta un string XML
  • Example#5660 - Recorre el pseudo-array children()
  • Example#5661 - Usando espacio de nombres
  • Example#5662 - Crea un objeto SimpleXMLElement
  • Example#5663 - Crea un objeto SimpleXMLElement a partir de una URL
  • Example#5664 - Cuenta el número de hijos
  • Example#5665 - Obtener los espacios de nombres del documento
  • Example#5666 - Trabajando con múltiples espacios de nombre
  • Example#5667 - Retornar el nombre del elemento XML
  • Example#5668 - Obtener el nombre de espacio del documento en uso
  • Example#5669 - Estableciendo un prefijo para el namespace a usar en una petición XPath
  • Example#5670 - Get string content
  • Example#5671 - Xpath
  • Example#5672 - Devuelve el elemento actual
  • Example#5673 - Devuelve los sub elementos de el elemento actual
  • Example#5674 - Comprobar si el elemento actual tiene sub elementos
  • Example#5675 - Obtener la clave actual de etiquetas XML
  • Example#5676 - Mover a el siguiente elemento
  • Example#5677 - Rebobinar hasta el primer elemento
  • Example#5678 - Comprobar si el elemento actual es válido
  • Example#5679 - Importando desde DOM
  • Example#5680 - Interpreta un documento XML
  • Example#5681 - Interpreta un string XML
  • Example#5682 - Serializando un simple valor con WDDX
  • Example#5683 - Usando paquetes incrementales con WDDX
  • Example#5684 - Ejemplo wddx_serialize_vars
  • Example#5685 - Mostrar la estructura de elementos XML
  • Example#5686 - Asignar XML a HTML
  • Example#5687 - Ejemplo de entidades XML externas
  • Example#5688 - xmltest.xml
  • Example#5689 - xmltest2.xml
  • Example#5690 - Ejemplo de xml_parse_into_struct
  • Example#5691 - moldb.xml - pequeña base de datos de información molecular
  • Example#5692 - parsemoldb.php - interpreta moldb.xml dentro de un array de objetos moleculares
  • Example#5693 - Ejemplo xml_set_object
  • Example#5694 - Validando el XML
  • Example#5695 - Crear un simple documento XML
  • Example#5696 - Trabajar con espacios de nombres XML
  • Example#5697 - Trabajando con el OO API
  • Example#5698 - Direct output of XML
  • Example#5699 - XMLWriter::setIndent and mixed Content
  • Example#5700 - Basic XMLWriter::startAttribute Usage
  • Example#5701 - Intermixing Sub-elements and Attributes
  • Example#5702 - Basic xmlwriter_write_cdata Usage
  • Example#5703 - collection.xml
  • Example#5704 - collection.xsl
  • Example#5705 - fruits.xml
  • Example#5706 - fruits.xsl
  • Example#5707 - Errores de compaginación e impresión
  • Example#5708 - Creando un XSLTProcessor
  • Example#5709 - Comprobando si tiene EXSLT
  • Example#5710 - Sencilla llamada a una función de PHP desde una hoja de estilos
  • Example#5711 - Changing the owner before the transformation
  • Example#5712 - Ejemplo de salida de información
  • Example#5713 - Transformando en un DOMDocument
  • Example#5714 - Transformando a un fichero HTML
  • Example#5715 - Transformando a un string
  • Example#5716 - Un elemento oculto de un formulario HTML
  • Example#5717 - Datos a editar por el usuario
  • Example#5718 - En un URL
  • Example#5719 - Generación de Javascript con PHP
  • Example#5720 - Ejemplo de Código PHP/FI
  • Example#5721 - Activar la notificación completa de errores por pantalla para el dominio dev.
  • Example#5722 - Añadir un script de seguridad para aréas protegidas
  • Example#5723 - include_path en Unix
  • Example#5724 - include_path en Windows
  • Example#5725 - include_path en Unix usando la variable de entorno ${USER}
  • Example#5726 - string.rot13
  • Example#5727 - string.toupper
  • Example#5728 - string.tolower
  • Example#5729 - string.strip_tags
  • Example#5730 - convert.base64-encode & convert.base64-decode
  • Example#5731 - convert.quoted-printable-encode & convert.quoted-printable-decode
  • Example#5732 - convert.iconv.*
  • Example#5733 - zlib.deflate y zlib.inflate
  • Example#5734 - zlib.deflate simple
  • Example#5735 - bzip2.compress y bzip2.decompress
  • Example#5736 - Encriptar/Desencriptar con Blowfish
  • Example#5737 - Encriptar el archivo usando AES-128 CBC con SHA256 HMAC en PHP 5.5+

User Contributed Notes

There are no user contributed notes for this page.


Registro de cambios

A las funciones de las extensiones incluidas se han realizado los siguientes cambios.

Version | Function | Description
PHP 7.0.15, PHP 7.1.1 | get_defined_functions | Se ha añadido el parámetro exclude_disabled.
PHP 5.3.19 | imagecreatefromxpm | imagecreatefromxpm está disponible en Windows.
8.0.0 / 1.18.0 | ZipArchive::getStatusString | Este método puede ser llamado en un archivo cerrado.
8.0.0 | curl_init | url es ahora nullable.
curl_init | En caso de éxito, esta función devuelve una instancia CurlHandle ahora; anteriormente, se devolvía un resource.
deflate_add | context expects a DeflateContext instance now; previously, a resource was expected.
deflate_init | On success, this function returns a DeflateContext instance now; previously, a resource was returned.
enchant_dict_add | dictionary expects an EnchantDictionary instance now; previoulsy, a recurso was expected.
enchant_dict_is_added | dictionary expects an EnchantDictionary instance now; previoulsy, a recurso was expected.
gmp_binomial | This function no longer returns false on failure.
inflate_add | context expects an InflateContext instance now; previously, a resource was expected.
inflate_get_read_len | context expects an InflateContext instance now; previously, a resource was expected.
inflate_get_status | context expects an InflateContext instance now; previously, a resource was expected.
inflate_init | On success, this function returns an InflateContext instance now; previously, a resource was returned.
ldap_add_ext | controls is nullable now; previously, it defaulted to [].
ldap_bind_ext | controls is nullable now; previously, it defaulted to [].
ldap_delete_ext | controls is nullable now; previously, it defaulted to [].
ldap_exop_passwd | controls is nullable now; previously, it defaulted to [].
ldap_modify_batch | controls is nullable now; previously, it defaulted to [].
ldap_mod_add_ext | controls is nullable now; previously, it defaulted to [].
ldap_mod_del_ext | controls is nullable now; previously, it defaulted to [].
ldap_mod_replace_ext | controls is nullable now; previously, it defaulted to [].
ldap_rename_ext | controls is nullable now; previously, it defaulted to [].
mb_chr | encoding is nullable now.
mb_ord | encoding is nullable now.
mb_scrub | encoding is nullable now.
mb_str_split | encoding is nullable now.
mb_str_split | This function no longer returns false on failure.
openssl_spki_new | private_key accepts an OpenSSLAsymmetricKey instance now; previously, a recurso of type OpenSSL key was accepted.
openssl_x509_fingerprint | certificate accepts an OpenSSLCertificate instance now; previously, a recurso of type OpenSSL X.509 was accepted.
openssl_x509_verify | public_key accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a recurso of type OpenSSL key or OpenSSL X.509 was accepted.
openssl_x509_verify | certificate accepts an OpenSSLCertificate instance now; previously, a recurso of type OpenSSL X.509 was accepted.
socket_addrinfo_bind | address is an AddressInfo instance now; previously, it was a resource.
socket_addrinfo_bind | On success, this function returns a Socket instance now; previously, a resource was returned.
socket_addrinfo_connect | On success, this function returns a Socket instance now; previously, a resource was returned.
socket_addrinfo_connect | address is an AddressInfo instance now; previously, it was a resource.
socket_addrinfo_explain | address is an AddressInfo instance now; previously, it was a resource.
socket_addrinfo_lookup | service is nullable now.
socket_addrinfo_lookup | On success, this function returns a array of AddressInfo instances now; previously, an array of resources was returned.
socket_export_stream | socket is a Socket instance now; previously, it was a resource.
socket_wsaprotocol_info_export | socket is a Socket instance now; previously, it was a resource.
socket_wsaprotocol_info_import | On success, this function returns a Socket instance now; previously, a resource was returned.
ReflectionClass::getConstants | Se añadió el parámetro filter.
ReflectionClass::getReflectionConstants | filter has been added.
ReflectionProperty::isInitialized | object is nullable now.
XMLWriter::endAttribute | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::endCdata | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::endComment | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::endDocument | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::endDtd | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::endDtdAttlist | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::endDtdElement | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::endDtdEntity | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::endElement | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::endPi | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::flush | This function can no longer return false.
XMLWriter::flush | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::fullEndElement | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::openMemory | This function returns now an XMLWriter instance on success. Previouly, a recurso has been returned in this case.
XMLWriter::openUri | This function returns now an XMLWriter instance on success. Previouly, a recurso has been returned in this case.
XMLWriter::outputMemory | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::setIndent | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::setIndentString | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startAttribute | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startAttributeNs | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startAttributeNs | prefix is nullable now.
XMLWriter::startCdata | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startComment | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startDocument | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startDtd | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startDtdAttlist | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startDtdElement | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startDtdEntity | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startElement | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startElementNs | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::startPi | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::text | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writeAttribute | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writeAttributeNs | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writeCdata | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writeComment | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writeDtd | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writeDtdAttlist | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writeDtdElement | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writeDtdEntity | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writeDtdEntity | publicId, systemId and notationData are nullable now.
XMLWriter::writeElement | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writeElementNs | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writePi | writer expects an XMLWriter instance now; previously, a resource was expected.
XMLWriter::writeRaw | writer expects an XMLWriter instance now; previously, a resource was expected.
7.4.0 | get_magic_quotes_gpc | Esta función ha quedado en desuso.
get_magic_quotes_runtime | Esta función es obsoleta.
implode | Pasar el parámetro glue después de el parámetro pieces (es decir, sin utilizar el orden documentado de los parámetros) es obsoleto.
SplFileObject::fgetcsv | El parámetro escape ahora también acepta un string vacío para desactivar el mecanismo de escape propio.
SplFileObject::fwrite | La función ahora devuelve false en vez de cero en caso de error.
SplFileObject::getCsvControl | El carácter de escape puede ser ahora un string vacío.
SplFileObject::setCsvControl | El parámetro escape ahora acepta un string vacío para desactivar el mecanismo de escape.
7.3.0 | apache_request_headers | Esta función se hizo disponible en el SAPI de FPM.
array_unshift | Esta función ahora puede ser llamada con un solo parámetro. Anteriormente, se requerían al menos dos parámetros.
curl_getinfo | Introdujo CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, CURLINFO_CONTENT_LENGTH_UPLOAD_T, CURLINFO_HTTP_VERSION, CURLINFO_PROTOCOL, CURLINFO_PROXY_SSL_VERIFYRESULT, CURLINFO_SCHEME, CURLINFO_SIZE_DOWNLOAD_T, CURLINFO_SIZE_UPLOAD_T, CURLINFO_SPEED_DOWNLOAD_T, CURLINFO_SPEED_UPLOAD_T, CURLINFO_APPCONNECT_TIME_T, CURLINFO_CONNECT_TIME_T, CURLINFO_FILETIME_T, CURLINFO_NAMELOOKUP_TIME_T, CURLINFO_PRETRANSFER_TIME_T, CURLINFO_REDIRECT_TIME_T, CURLINFO_STARTTRANSFER_TIME_T, CURLINFO_TOTAL_TIME_T.
getallheaders | Esta función se hizo disponible en el SAPI de FPM.
is_countable | is_countable ha sido añadido.
json_encode | JSON_THROW_ON_ERROR Se añadió a flags.
setcookie | Una alternativa que soporta un array options ha sido añadida. Esta alternativa soporta también la configuración del atributo de la cookie de SameSite.
setrawcookie | Una alternativa que soporta un array options ha sido añadida. Esta alternativa soporta también la configuración del atributo de la cookie de SameSite.
7.3 | ldap_exop | Support for serverctrls added
ldap_exop_passwd | Support for controls added
ldap_modify_batch | Support for controls added
ldap_mod_add_ext | Support for controls added
ldap_mod_del_ext | Support for controls added
ldap_mod_replace_ext | Support for controls added
ldap_rename_ext | Support for controls added
ldap_search | Se añadión soporte para serverctrls
7.2.19, 7.3.6 | SplFileObject::__toString | Cambiado de un alias de SplFileObject::current a un alias de SplFileObject::fgets.
7.2.0 | array_unique | Si el parámetro sort_flags es SORT_STRING, el array anterior ha sido copiado y se han eliminado los elementos no únicos (sin empaquetar el array posteriormente), pero ahora se construye un nuevo array añadiendo los elementos únicos. Esto puede dar lugar a diferentes índices numéricos.
count | count generará una advertencia si se pasan tipos contables no válido al parámetro array_or_countable.
date_parse_from_format | El elemento de zone devuelto representa ahora segundos en lugar de minutos, y su signo está invertido. Por ejemplo -120 es ahora 7200.
hash_init | Uso de funciones de hash no criptográficas (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) con HASH_HMAC ha sido deshabilitado.
hash_init | Devuelve HashContext en lugar de recurso.
is_object | is_object ahora devuelve true para objetos no seriados sin una definición de clase (clase de __PHP_Incomplete_Class). Anteriormente false era devuelto.
json_encode | JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE Se añadieron a flags.
mail | El parámetro additional_headers ahora también acepta array.
session_abort | El tipo de retorno de esta función es bool ahora. Anteriormente, ha sido void.
SQLite3::openBlob | The flags parameter has been added, allowing to write BLOBs; formerly only reading was supported.
7.1.0 | array_rand | El algoritmo de aleatorización interno se ha cambiado para usar el generador de números aleatorios Mersenne Twister en lugar de la función libc rand.
file_get_contents | Se añadió soporte para valores negativos de offset.
get_headers | El parámetro context fue agregado.
iconv_strpos | Añadido soporte para offsets negativos.
json_encode | JSON_UNESCAPED_LINE_TERMINATORS Se añadió a flags.
json_encode | serialize_precision se utiliza en lugar de precision al codificar 'doubles'.
mb_ereg_replace | El modificador e está ahora obsoleto.
mb_eregi_replace | El modificador e está ahora obsoleto.
output_reset_rewrite_vars | Antes de PHP 7.1.0, la variables reescritas por output_add_rewrite_var utilizaban el mismo buffer de salida del módulo de sesión trans sid. Desde PHP 7.1.0, se usa un buffer de salida dedicado y output_reset_rewrite_vars solo elimina las variables reescritas definidas por output_add_rewrite_var.
pcntl_signal | As of PHP 7.1.0 the handler callback is given a second argument containing the siginfo of the specific signal. This data is only supplied if the operating system has the siginfo_t structure. If the OS does not implement siginfo_t NULL is supplied.
pcntl_signal_get_handler | pcntl_signal_get_handler has been added.
pg_fetch_all | El parametro result_type fue agregado.
pg_last_notice | El parameto option fue agregado.
pg_select | The result_type parameter was added.
unserialize | El elemento allowed_classes de options) es ahora estrictamente tipado, es decir: si cualquier cosa distinta de un array o un boolean es proporcionada, unserialize retornará false y lanzará un E_WARNING.
ReflectionType::__toString | ReflectionType::__toString has been deprecated.
7.0.16, 7.1.2 | dns_get_record | Added support for CAA record type.
fopen | Se añadió la opción 'e'.
7.0.11 | iconv_substr | Si la longitud de caracteres de str es igual a offset, devolverá un string vacío. Antes de ésta versión, un false era devuelto en éste caso.
7.0.7 | curl_setopt | Se introdujeron CURL_HTTP_VERSION_2, CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, CURL_HTTP_VERSION_2TLS, CURL_REDIR_POST_301, CURL_REDIR_POST_302, CURL_REDIR_POST_303, CURL_REDIR_POST_ALL, CURL_VERSION_KERBEROS5, CURL_VERSION_PSL, CURL_VERSION_UNIX_SOCKETS, CURLAUTH_NEGOTIATE, CURLAUTH_NTLM_WB, CURLFTP_CREATE_DIR, CURLFTP_CREATE_DIR_NONE, CURLFTP_CREATE_DIR_RETRY, CURLHEADER_SEPARATE, CURLHEADER_UNIFIED, CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_PIPELINE_LENGTH, CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPT_CONNECT_TO, CURLOPT_DEFAULT_PROTOCOL, CURLOPT_DNS_INTERFACE, CURLOPT_DNS_LOCAL_IP4, CURLOPT_DNS_LOCAL_IP6, CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPT_HEADEROPT, CURLOPT_LOGIN_OPTIONS, CURLOPT_PATH_AS_IS, CURLOPT_PINNEDPUBLICKEY, CURLOPT_PIPEWAIT, CURLOPT_PROXY_SERVICE_NAME, CURLOPT_PROXYHEADER, CURLOPT_SASL_IR, CURLOPT_SERVICE_NAME, CURLOPT_SSL_ENABLE_ALPN, CURLOPT_SSL_ENABLE_NPN, CURLOPT_SSL_FALSESTART, CURLOPT_SSL_VERIFYSTATUS, CURLOPT_STREAM_WEIGHT, CURLOPT_TCP_FASTOPEN, CURLOPT_TFTP_NO_OPTIONS, CURLOPT_UNIX_SOCKET_PATH, CURLOPT_XOAUTH2_BEARER, CURLPROTO_SMB, CURLPROTO_SMBS, CURLPROXY_HTTP_1_0, CURLSSH_AUTH_AGENT y CURLSSLOPT_NO_REVOKE.
7.0.0 | array_column | Se añadió la capacidad de que el parámetro input sea un array de objetos.
Aserción | assert is now a language construct and not a function. assertion can now be an expression. The second parameter is now interpreted either as an exception (if a Throwable object is given), or as the description supported from PHP 5.4.8 onwards.
curl_setopt | Se ha eliminado el soporte para inhabilitar la opción CURLOPT_SAFE_UPLOAD. Todas las subidas de ficheros de curl deben emplear CURLFile.
current | array ahora siempre se pasa por el valor. Antes de esta versión, se pasaba por referencia si era posible, y por el valor de lo contrario.
define | Están permitidos valores array.
dirname | Añadido el parámetro opcional levels.
dl | dl está deshabilitado en PHP-FPM.
getrusage | Esta función ahora está soportada en Windows
gmmktime | El parámetro is_dst ha sido eliminado.
key | array ahora siempre se pasa por el valor. Antes de esta versión, se pasaba por referencia si era posible, y por el valor de lo contrario.
list | Los strings ya no pueden ser desempaquetados.
list | Las expresiones de list ya no pueden estar completamente vacías.
list | El orden en el que se realizan las operaciones de asignación ha cambiado.
mktime | El parámetro is_dst ha sido eliminado.
ob_start | En caso de utilizar ob_start dentro de una retrollamada del búfer de salida, esta función ya no emitirá un E_ERROR, si no un E_RECOVERABLE_ERROR, permitiendo a los manejadores de errores propios capturar tales errores.
preg_replace | Se ha eliminado el soporte para el modificador /e. Emplee preg_replace_callback en su lugar.
session_start | Se añadió el parámetro options.
set_exception_handler | Cambiado el tipo de parámetro pasado a exception_handler de Exception a Throwable
setlocale | Se ha eliminado el soporte para el parámetro category pasado como string. En esta versión, solamente se pueden utilizar las constantes LC_*.
shmop_close | El tipo de shmid ha sido cambiado de int a resource.
shmop_delete | El tipo de shmid ha sido cambiado de int a resource.
shmop_open | El tipo devuelto de shmop_open ha sido cambiado de int a resource.
shmop_read | El tipo de shmid ha sido cambiado de int a resource.
shmop_size | El tipo de shmid ha sido cambiado de int a resource.
shmop_write | El tipo de shmid ha sido cambiado de int a resource.
substr | Si la longitud de caracteres de string es igual a start, se devolverá una cadena vacía. Antes de esta versión, en este caso se devolvía false.
unserialize | Se añadió el parámetro options.
5.6.25, 7.0.10 | SplFileObject::getCsvControl | Se añadió el carácter de escape al array devuelto.
5.6.16 | mysqli::real_connect | Se añadió la bandera MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT para el Controlador Nativo de MySQL
5.6.12 | gd_info | Se añadió WebP Support.
5.6.5 | crypt | Cuando se da la cadena de fallo "*0" como salt, ahora se devuelve "*1" por consistencia con otras implementaciones de crypt. Antes de esta versión, PHP 5.6 devolvía incorrectamente un hash DES.
5.6.3 | pack | Se añadieron los códigos "q", "Q", "J" y "P" para habilitar el trabajo con número de 64 bit.
5.6.1 | sem_acquire | Se añadió el parámetro $nowait.
5.6.0 | array_fill | num ahora puede ser cero. Anteriormente, se requería que num fuera maoyor que cero.
array_filter | Se añadió el parámetro opcional flag y las constantes ARRAY_FILTER_USE_KEY y ARRAY_FILTER_USE_BOTH
crypt | Se emite una advertencia de seguridad E_NOTICE si se omite salt.
curl_setopt | CURLOPT_SAFE_UPLOAD ahore es true de forma predeterminada.
curl_setopt | Se eliminó CURLOPT_CLOSEPOLICY y sus valores asociados.
hash_algos | Se añadió soprte para gost-crypto. Este implementa la función de hash GOST empleando las tablas CryptoPro S-box como está especificado en la RFC 4357, sección 11.2.
html_entity_decode | El valor predeterminado para el parámetro encoding se cambió para que fuera el valor de la opción de configuración default_charset.
htmlentities | El valor predeterminado para el parámetro encoding se cambió para que fuera el valor de la opción de configuración default_charset.
htmlspecialchars | El valor predeterminado para el parámetro encoding se cambió para que fuera el valor de la opción de configuración default_charset.
json_decode | Ya no se aceptan variantes que no estén en minúsculas de los literales true, false y null como entradas válidas, por lo que se generarán advertencias.
mb_regex_encoding | La codificación predeterminada se cambió a UTF-8. Anteriormente era EUC-JP.
mcrypt_create_iv | MCRYPT_DEV_URANDOM ahora es el valor predetermniado de source.
mcrypt_decrypt | Tamaños incorrectos en key y iv ya no son admitidos. mcrypt_decrypt emitirá una advertencia y devolverá false si los datos de entrada son incorrectos. Anteriormente la clave y el IV eran rellenados con bytes '\0' hasta el siguiente tamaño válido.
mcrypt_encrypt | Tamaños incorrectos en key y iv ya no son admitidos. mcrypt_encrypt emitirá una advertencia y devolverá false si los datos de entrada son incorrectos. Anteriormente la clave y el IV eran rellenados con bytes '\0' hasta el siguiente tamaño válido.
pg_connect | El soporte para la constante PGSQL_CONNECT_ASYNC se ha añadido con el parametro connect_type.
pg_convert | Ya no es experimental. Se admiten los tipos de datos boolean/NULL. Los tipos de datos desconocidos/no soportados son escapados sin validación. Se podría emplear pg_convert con cualquier tipo de dato.
pg_delete | Ya no es experimental. Se añadió la constante PGSQL_DML_ESCAPE, se admiten los tipos de datos true/false y null.
pg_insert | Unless PGSQL_DML_STRING is passed, the function now returns the connection resource instead of true on success.
pg_insert | No longer experimental. Added PGSQL_DML_ESCAPE constant, true/false and null data type support.
pg_lo_seek | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.
pg_lo_tell | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.
pg_lo_truncate | Added truncate function. It supports PostgreSQL 9.3's 64bit large object. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.
pg_meta_data | No longer experimental. Added "is enum" as default attribute. extended flag is added.
pg_select | No longer experimental. Added PGSQL_DML_ESCAPE constant, true/false and null data type support.
pg_update | Ya no es experimental. Se ha añadido la constante PGSQL_DML_ESCAPE, true/false y null son los tipo de datos soportados.
stream_socket_enable_crypto | crypto_type ahora es opcional.
unserialize | Manipular los datos serializados reemplazando C: con O: para forzar la instanciación de objetos sin llamar al constructor ahora fallará.
ReflectionClass::newInstanceWithoutConstructor | Ahora todas las clases internas pueden ser instanciadas, excepto aquellas declaradas final.
5.5.22, 5.6.6 | flock | Se añadió soporte para el parámetro wouldblock en Windows.
SplFileObject::flock | Añadido soporte para el parámetro wouldblock en Windows.
5.5.21, 5.6.5 | SplFileObject::fputcsv | Se añadió el parámetro escape.
5.5.21 | crypt | Cuando se da la cadena de fallo "*0" como salt, ahora se devuelve "*1" por consistencia con otras implementaciones de crypt. Antes de esta versión, PHP 5.5 (y ramificaciones anteriores) devolvía incorrectamente un hash DES.
5.5.19/5.6.3 | imagescale | Se ha arreglado el cálculo de la altura si new_height era negativo o se omitía; antes de estas versiones, la proporción de aspecto no se mantenía correctamente.
5.5.11 | substr_compare | length ahora puede ser 0.
5.5.10 | DateTimeZone::__construct | El parámetro timezone acepta valores de índice.
5.5.8 | DatePeriod::__construct | El tipo de end se cambió a DateTimeInterface. Anteriormente era DateTime.
5.5.4 | fputcsv | Se añadió el parámetro escape_char
5.5.3/5.4.19 | pg_delete | La inyección SQL directa a table_name y la inyección SQL indirecta a identificadores son fijasinjection.
pg_insert | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.
pg_select | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.
pg_update | La inyección directa SQL a table_name y la inyección indirecta SQL a los indetificadores a sido arreglada.
5.5.2 | DOMDocument::schemaValidate | Se añadió el parámetro flags
DOMDocument::schemaValidateSource | Se añadió el parámetro flags
5.5.1 | hex2bin | Se emite una advertencia si el string de entrada es un string hexadecimal no válido.
pg_unescape_bytea | A warning is thrown if the input string is invalid.
session_set_save_handler | Se añadió el parámetro opcional create_sid.
5.5.0/PECL 3.0.0 | IntlDateFormatter::create | Se permite un objeto IntlCalendar para calendar. Los objetos de tipo IntlTimeZone y DateTimeZone están permitidos para timezone. Los identificadores de zonas horarias válidos (incluyendo string vacíos) ya no están permitidos para timezone. Si se proporciona null a timezone, el identificador de la zona horaria dado por date_default_timezone_get se usará en lugar del predeterminado de ICU.
IntlDateFormatter::format | Se añadió el soporta para proporcionar objetos IntlCalendar al parámetro value.
IntlDateFormatter::setCalendar | Ahora es posible pasar un objeto IntlCalendar.
5.5.0 | DatePeriod::__construct | start se cambió a DateTimeImmutable. Anteriormente era DateTime.
curl_getinfo | Introdujo CURLINFO_RESPONSE_CODE, CURLINFO_HTTP_CONNECTCODE, CURLINFO_HTTPAUTH_AVAIL, CURLINFO_PROXYAUTH_AVAIL, CURLINFO_OS_ERRNO, CURLINFO_NUM_CONNECTS, CURLINFO_SSL_ENGINES, CURLINFO_COOKIELIST, CURLINFO_FTP_ENTRY_PATH, CURLINFO_APPCONNECT_TIME, CURLINFO_CONDITION_UNMET, CURLINFO_RTSP_CLIENT_CSEQ, CURLINFO_RTSP_CSEQ_RECV, CURLINFO_RTSP_SERVER_CSEQ y CURLINFO_RTSP_SESSION_ID.
curl_setopt | Se introdujo CURLOPT_SHARE.
curl_setopt | Se añadió el recurso cURL como el primer parámetro de la llamada de retorno CURLOPT_PROGRESSFUNCTION.
empty | empty ahora soporta expresiones, en vez de únicamente variables.
imagerotate | Esta función ahora se ve afectada por el método de interpolación establecido por la función imagesetinterpolation.
iterator_to_array | iterator_to_array da soporte a tipos de claves diferentes a integer y string cuando el parámetro use_keys está habilitado.
mysql_connect | Esta función generará un error de nivel E_DEPRECATED.
mysql_db_name | La función mysql_list_dbs es obsoleta, por lo que emite un error de nivel E_DEPRECATED.
mysql_pconnect | Esta función generará un error de nivel E_DEPRECATED.
mysql_tablename | La función mysql_tablename es obsoleta, por lo que emite un error de nivel E_DEPRECATED.
pack | Se añadió el código "Z" con funcionalidad equivalente a "a" por compatibilidad con Perl.
phpinfo | Los GUIDs de logos fueron reemplazados con URIs de datos, por lo que desactivar ahora expose_php no tiene efecto sobre el resutaldo de phpinfo(). Los créditos ahora también han sido embebidos en la salida misma en vez mediante enlaces.
preg_replace | El modificador /e está obsoleto. Utilice preg_replace_callback en su lugar. Véase la documentación de PREG_REPLACE_EVAL para obtener información adicional sobre riesgos de seguridad.
set_error_handler | error_handler ahora acepta null.
set_exception_handler | Anteriormente, si se pasaba null, esta función devolvía true. Devuelve el manejador anterior desde PHP 5.5.0.
setcookie | Ahora se incluye un atributo Max-Age en la cabecera Set-Cookie enviada al cliente.
setrawcookie | Ahora se incluye un atributo Max-Age en la cabecera Set-Cookie enviada al cliente.
unpack | Cambios realizados para poner esta función en línea con Perl: El código "a" ahora guarda bytes NULL sobrantes de cola. El código "A" ahora elimina todos los espacios en blanco ASCII sobrantes de cola (espacios, tabulaciones, nuevas líneas, retorno de carro, y bytes NULL). Se añadió en código "Z" para cadenas rellenadas con NULL, y elimina los bytes NULL sobrantes de cola.
mysqli::commit | Se añadieron los parámetros flags y name.
mysqli::options | Se añadieron las opciones MYSQLI_SERVER_PUBLIC_KEY y MYSQLI_SERVER_PUBLIC_KEY.
mysqli::rollback | Se añadieron los parámetros flags y name.
5.4.32, 5.5.16 | ucwords | Se añadió el parámetro delimiters.
5.4.8 | Aserción | The description parameter was added. The description is also now provided to a callback function in ASSERT_CALLBACK mode as the fourth argument.
mb_strcut | Pasar NULL al parámetro length extrae todos los bytes hasta el final de string. Antes de esta versión, NULL era tratado de igual modo que 0.
mb_substr | Pasar NULL al parámetro length extrae todos los caracteres hasta el final de string. Antes de esta versión, NULL era tratado de igual modo que 0.
5.4.7 | curl_getinfo | Introdujo CURLINFO_PRIMARY_IP, CURLINFO_PRIMARY_PORT, CURLINFO_LOCAL_IP y CURLINFO_LOCAL_PORT.
parse_url | Arreglado el reconocimiento de host cuando scheme es omitido y está presente un separador de componentes que lo encabeza.
5.4.4 | hex2bin | Se emite una advertencia si la cadena de entrada tiene una longitud impar. En PHP 5.4.0 la cadena era aceptada de forma silenciosa, pero el último byte era truncado.
5.4.0/PECL 2.0.0b1 | idn_to_ascii | Se añadieron los parámetros variant y idna_info; y el soporte para UTS #46.
idn_to_utf8 | Se añadieron los parámetros variant y idna_info; y el soporte para UTS #46.
5.4.0 | DOMDocument::loadHTML | Se añadió el parámero options.
DOMDocument::loadHTMLFile | Se añadió el parámero options.
apache_child_terminate | Esta función está disponible bajo FastCGI. Anteriormente, estaba soportada solo cuando había sido instalado un módulo PHP en Apache.
array_combine | Versiones previas emiten un E_WARNING y devuelven false para arrays vacíos.
array_multisort | Se añadieron SORT_NATURAL y SORT_FLAG_CASE a array1_sort_flags como posibles banderas de ordenación.
date_default_timezone_get | La zona horaria ya no se adivina de la información disponible a través del sistema operativo, la zona horaria adivinada no puede invocarse.
date_default_timezone_get | La variable de entorno TZ ya no se usa para adivinar la zona horaria.
debug_backtrace | Añadido el parámetro opcional limit.
debug_print_backtrace | Añadido el parámetro opcional limit.
empty | Verificación de índices no numéricos de strings devuelve true.
error_reporting | Ahora E_STRICT es parte de E_ALL.
filter_input_array | Se añadió el parámetro add_empty.
filter_var_array | Se añadió el parámetro add_empty.
get_html_translation_table | El valor por defecto para el parámetro encoding se cambió a UTF-8.
get_html_translation_table | Se añadieron las constantes ENT_HTML401, ENT_XML1, ENT_XHTML y ENT_HTML5.
get_magic_quotes_runtime | Siempre devuelve false debido a que la característica de comillas mágicas ha sido eliminada de PHP.
gzcompress | Se añadió el parámetro encoding.
gzdeflate | Se añadió el parámetro encoding.
gzencode | FORCE_DEFLATE ahora genera una salida que cumple el RFC 1950.
hash | El algoritmo tiger ahora utiliza orden de byte «big-endian». Véase también el ejemplo de más abajo.
hash_algos | Se añade soporte para joaat, fnv132 y para fnv164. Soporte para Salsa10 y Salsa20 fué eliminado.
html_entity_decode | Se añadieron las constantes ENT_HTML401, ENT_XML1, ENT_XHTML y ENT_HTML5.
html_entity_decode | La codificación predeterminada se cambió de ISO-8859-1 a UTF-8.
htmlentities | El valor por defecto del parámetro encoding se cambió a UTF-8.
htmlentities | Se añadieron las constantes ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML y ENT_HTML5.
htmlspecialchars | El valor predeterminado del parámetro encoding se cambió a UTF-8.
htmlspecialchars | Se añadieron las constantes ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML y ENT_HTML5.
htmlspecialchars_decode | Fueron agregadas las constantes ENT_HTML401, ENT_XML1, ENT_XHTML y ENT_HTML5.
http_build_query | Se agregó el parámetro enc_type.
imagecolorset | Se añadió el parámetro alpha.
imagegd2 | Se añadió soporte para pasar un resource de flujo a to.
imagejpeg | Se añadió soporte para pasar un resource de flujo a to.
imagejpeg | Se deshabilitó el paso de un string vacío a filename para saltar este argumeto.
imagewebp | Se añadió soporte para pasar un resource de flujo a to.
isset | Comprobación de indices no numéricos de strings ahora retorna false.
json_decode | Se añadió el parámetro options.
mb_encode_numericentity | Añadido el parámetro is_hex.
number_format | Esta función ahora admite múltiples bytes en dec_point y thousands_sep. En versiones anteriors solamente se utilizaba el primer byte de cada separador.
ob_start | Un tamaño de segmento de 1 ahora resulta en segmentos de 1 byte que se van a enviar al búfer de salida.
ob_start | El tercer parámetro de ob_start se cambió de un parámetro boolean llamado erase (el cual, si se establecía a false, prevenía al búfer de salida de ser eliminado hasta el final de la ejecución del script) a un parámetro integer llamado flags. Desafortunadamente, esto resulta en una rotura de compatibilidad de la API para código escrito antes de PHP 5.4.0 que use el tercer parámetro. Véase el ejemplo de banderas para saber cómo manejar esto con código que necesite ser compatible con ambas.
openssl_decrypt | raw_output se cambió a options.
openssl_encrypt | raw_output se cambió a options.
preg_match_all | El parámetro matches ahora es opcional.
scandir | Se añadieron las constantes de sorting_order. En versiones anteriores, cualquir valor distinto de cero ocasionaba un ordenamiento descendente. Por lo tanto, para todas las versiones de PHP, use 0 para el orden ascendente, y 1 para el orden descendente. No existía una opción para el comportamiento de SCANDIR_SORT_NONE antes de PHP 5.4.0.
session_set_save_handler | Se añadió SessionHandlerInterface para la implementación de gestores de sesión y SessionHandler para exponer gestores de sesión internos de PHP.
sort | Se añadió el soporte para SORT_NATURAL y SORT_FLAG_CASE como sort_flags
PDOStatement::getColumnMeta | Se añadió el soporte para el controlador PDO_DBLIB
Phar::setStub | Se añadió el parámetro len.
PharData::setStub | Se añadió el parámetro len.
SimpleXMLElement::getDocNamespaces | Se añadió el parámetro from_root.
5.4 | grapheme_substr | Si se proporciona length y es positivo, y el argumento string es más corto que la longitud especificada, se devuelve el resto de la cadena de acuerdo al parámetro start. Anteriormente devolvía false.
5.3.9 | DateTime::createFromFormat | Se añadió el especficador + para format.
dl | dl está deshabilitado en PHP-FPM, aunque se desaconseja.
is_a | Se añadió el parámetro allow_string
is_subclass_of | Se añadió el parámetro allow_string
5.3.7 | crypt | Se añadieron los modos de Blowfish $2x$ y $2y$ para tratar con ataques de bit alto potenciales.
curl_getinfo | Introdujo CURLINFO_REDIRECT_URL.
is_subclass_of | Se añadió el soporte para class_name para trabajar con interfaces
5.3.6 | DateTime::modify | Las sentencias de fecha/hora absolutas ahora toman efecto. Anteriormente, sólo se utilizaban las partes relativas.
DOMDocument::saveHTML | El parámetro node fue añadido.
array_product | El producto de un array vacío ahora es 1, mientras que antes esta función devolvía 0 para un array vacío.
debug_backtrace | Se cambió el parámetro provide_object a options y se añadió la opción adicional DEBUG_BACKTRACE_IGNORE_ARGS.
debug_print_backtrace | Añadido el parámetro opcional options.
preg_match | Devuelve false si offset es mayor que la longitud de subject.
preg_match_all | Devuelve false si offset es mayor que la longitud de subject.
PDO_MYSQL DSN | Antes de la versión 5.3.6, charset era ignorado.
5.3.4 | copy | Se cambió el parámetro context para que realmente tenga efecto. Anteriormente, se ignoraba cualquier context.
get_html_translation_table | Se añadió el parámetro encoding.
mt_rand | Emite un error de nivel E_WARNING y devuelve false si max < min.
rawurlencode | Los caracteres con tilde ya no son condificados al usar rawurlencode con EBCDIC en cadenas.
sleep | Antes de PHP 5.3.4, en Windows, sleep siempre devuelve null cuando el sueño ha sucedido, si tener en cuenta si el sueño fue interrumpido o no.
strip_tags | strip_tags ignora las etiquetas de autocierre de XHTML en allowable_tags.
IntlDateFormatter::format | Se añadió el soporte para proporcionar objetos de la clase DateTime al parámetro value.
mysqli_driver::$report_mode | El cambio de modo de notificación ahora es por solicitud, en vez de por proceso.
5.3.3 | DOMXPath::evaluate | Se añadió el parámetro registerNodeNS.
DOMXPath::query | Se añadió el parámetro registerNodeNS.
ldap_sasl_bind | Se añadió soporte en Windows.
openssl_decrypt | Se añadió el parámetro iv.
openssl_encrypt | Se añadió el parámetro iv.
parse_url | Eliminado el E_WARNING que era producido cuando fallaba el análisis de la URL.
5.3.2 (PECL OCI8 1.4) | oci_set_prefetch | Antes de esta versión, rows debe ser >= 1.
5.3.2 | crypt | Agregado el crypt SHA-256 y SHA-512 basado en la implementación de Ulrich Drepper.
crypt | Corregido el comportamiento de Blowfish sobre rondas no válidas para devolver el string "failure" ("*0" or "*1"), en lugar de caer al DES.
flock | Se eliminó la liberación del bloqueo automática al cerrarse el manejador del recurso. La liberación del bloqueo ahora siempre tiene que realizarse manualmente.
gmp_init | La base fue extendidad de 2 a 36, a 2 a 62 y -2 a -36.
gmp_strval | La base fue extendida de 2 a 36, a 2 a 62 y -2 a -36.
imap_append | Se añadió el soporte de INTERNALDATE para imap_append.
imap_open | Se añadió params
SplFileObject::flock | Se eliminó el desbloqueo automático cuando se cierra el manejador de recursos del archivo. El desbloqueo ahora siempre tiene que hacerse manualmente.
5.3.1 | get_defined_constants | Sólo para Windows: las constantes fundamentales se clasifican en Core, previamente mhash.
ibase_query | Si no hay rows afectados, la función ahora devuelve true en caso de éxito, donde anteriormente devolvía 0 (un cero seguido por un espacio en blanco).
rename | rename ahora puede renombrar ficheros a través de controladores de Windows.
5.3.0 (PECL OCI8 1.3.4) | oci_set_prefetch | Antes de esta versión, la precarga estaba limitada al menor valor de rows filas y 1024 * rows bytes. La restricción del tamaño de bytes ahora ha sido eliminada.
5.3.0 | DateTime::__construct | Si time contiene un formato de fecha/hora no válido, se lanzará una excepción. Anteriormente se emitía un error.
DateTime::modify | Se ha cambiado el valor devuelto en caso de éxito de null a DateTime.
DateTime::setDate | Se ha cambiado el valor devuelto en caso de éxito de null a DateTime.
DateTime::setISODate | Se ha cambiado el valor devuelto en caso de éxito de null a DateTime.
DateTime::setTime | Se ha cambiado el valor devuelto en caso de éxito de null a DateTime.
DateTime::setTimezone | Se ha cambiado el valor devuelto en caso de éxito de null a DateTime.
DateTimeZone::getTransitions | Se añadieron los parámetros opcionales timestamp_begin y timestamp_end.
DateTimeZone::listIdentifiers | Añadidos los parámteros opcionales what y country.
DirectoryIterator::__construct | Lanza una UnexpectedValueException si path no se puede abrir.
acosh | La función esta disponible en todas las plataformas
array_multisort | Se añadió SORT_LOCALE_STRING a array1_sort_flags como posible bandera de ordenación.
array_reduce | Se cambió el parámetro initial para permitir mixed, anteriormente era integer.
array_search | Al igual que con todas las funciones internas de PHP a partir de la versión 5.3.0, array_search devuelve null si se le pasan parámetros inválidos.
asinh | La función esta disponible en todas las plataformas
atanh | La función esta disponible en todas las plataformas
call_user_func | La interpretación de palabras clave orientadas a objetos como parent y self ha cambiado. Anteriormente al llamarlas usando la sintaxis de dobles dos puntos emitiría una advertencia E_STRICT porque eran interpretadas como estáticas.
call_user_func_array | La interpretación de palabras clave orientadas a objetos como parent y self ha cambiado. Anteriormente al llamarlas usando la sintaxis de dobles dos puntos emitiría una advertencia E_STRICT porque eran interpretadas como estáticas.
checkdnsrr | Esta función está disponible en plataformas Windows.
clearstatcache | Se añadieron los parámetros opcionales clear_realpath_cache y filename.
copy | Se añadió el soporte para el contexto.
crypt | PHP ahora contiene su propia implementación de los algoritmos MD5, DES estándar, DES extendido y Blowfish y los utilizará si el sistema carece de soporte para uno o varios de los algoritmos.
curl_getinfo | Introdujo CURLINFO_CERTINFO.
curl_setopt | Se introdujo CURLOPT_PROGRESSFUNCTION.
date_default_timezone_set | Ahora se lanza un E_WARNING en vez de un E_STRICT.
dl | dl está desactivado en algunos módulos SAPI por problemas de estabilidad. Los únicos modulos SAPI que permiten dl son: CLI, CGI and Embed. En su lugar usar las directivas Directivas de carga de extensiones
error_reporting | Se introdujo E_DEPRECATED y E_USER_DEPRECATED.
exif_imagetype | Se añadió soporte para iconos.
expm1 | Esta función está ahora disponible en todas las plataformas.
fgetcsv | Se añadió el parámetro escape
fnmatch | Esta función ahora está disponible en plataformas Windows.
func_get_arg | Si esta función es llamada desde el ámbito último de un archivo que ha sido incluido mediante una llamada a include o require desde dentro de una función en el archivo de llamada, ahora genera una advertencia y devuelve false.
func_get_arg | Esta función ahora se puede usar en listas de parámetros.
func_get_args | Esta función ahora se puede usar en listas de parámetros.
func_get_args | Si esta función es llamada desde el ámbito último de un archivo que ha sido incluido mediante una llamada a include o require desde dentro de una función en el archivo de llamada, ahora genera una advertencia y devuelve false.
func_num_args | Si esta función es llamada desde el ámbito último de un fichero que ha sido incluido mediante una llamada a include o require desde dentro de una función en el fichero de llamada, ahora genera una advertencia y devuelve -1.
func_num_args | Esta función ahora se puede usar en listas de parámetros.
gd_info | El atributo JPG Support se renombró a JPEG Support.
get_cfg_var | get_cfg_var se fijó para ser capaz de retornar un "array" con las opciones ini.
get_class | El valor predeterminado de object ahora es null, por lo que pasar el valor null a object tiene el mismo resultado que no pasar ningún valor.
get_defined_constants | Constantes fundamentales se clasifican en Core, antes internal. En Windows, las constantes fundamentales se clasifican en mhash.
get_object_vars | Esta función ahora devuelve null si object no es un objeto. Anteriormente devolvía false
getimagesize | Se añadió el soporte para iconos.
getmxrr | Esta función ahora está disponible en plataformas Windows.
getopt | Esta función ya no depende del sistema y funciona también en Windows.
getopt | Añadido soporte para valores opcionales (especificado mediante "::").
getopt | El parámetro longopts está disponible en todos los sistemas.
getopt | Añadido soporte para usar "=" como separador de argumento/valor.
hash_algos | Se añade soporte para md2, ripemd256, ripemd320, salsa10, salsa20, snefru256 y para sha224
htmlentities | Se añadió la constante ENT_IGNORE.
htmlspecialchars | Se añadió la constante ENT_IGNORE.
imagecolorclosesthwb | Está función ahora está disponible en Windows
imagefilter | Se añadió el soporete de pixelación (IMG_FILTER_PIXELATE).
inet_ntop | Esta función ahora está disponible en plataformas Windows.
inet_pton | Esta función ahora está disponible en plataformas Windows.
ini_get | Anteriormente, se devolvía un string si la opción de configuración no existía. Ahora en su lugar se devuelve false.
ini_get_all | Se añadió details.
is_a | Esta función ya no está obsoleta, y por lo tanto ya no lanza advertencias de tipo E_STRICT.
json_decode | Se añadió el parámetro opcional depth. La profundidad de recursividad predeterminada se aumentó de 128 a 512
link | Esta función ahora está disponible en plataformas Windows (Vista, Server 2008 o superiores).
linkinfo | Esta función ahora está disponible en plataformas Windows (Vista, Server 2008 o mayores).
log1p | Esta función está disponible en todas las plataformas.
mb_get_info | Está disponible la entrada "http_output_conv_mimetypes".
mcrypt_create_iv | MCRYPT_DEV_RANDOM y MCRYPT_DEV_URANDOM se volvieron disponibles en plataformas Windows.
mcrypt_create_iv | Ya no se requiere invocar primero a srand. Esto ahora se realiza de forma automática.
mktime | mktime ahora lanza un aviso de tipo E_DEPRECATED si se usa el parámetro is_dst.
mysql_db_query | Ésta función ahora lanza ahora un aviso E_DEPRECATED.
mysql_escape_string | Ahora, esta función lanza un aviso E_DEPRECATED.
nl2br | Se agregó el parámetro opcional is_xhtml. Antes de esta versión, siempre se insertaba '<br />'.
openssl_seal | Se añadió el parámetro method.
preg_quote | El carácter - ahora es escapado
property_exists | Esta función comprueba la existencia de una propiedad independientemente de su accesibilidad.
rawurlencode | Ahora sigue el RFC 3986.
readlink | Esta función ahora está disponible en plataformas Windows (Vista, Server 2008 o mayores).
realpath | Antes de esta versión, si en sistemas *BSD el último componente de path no existía, realpath no fallaba. Ahora realpath también falla en este caso.
register_tick_function | Los ticks ahora están soportados en los módulos de servidores web que usan hilos.
round | Se introdujo el parámetro mode.
session_start | Si una sesión falla al iniciarse, se devuelve false. Anteriormente se devolvía true.
setlocale | Está función ahora emite un aviso E_DEPRECATED si se pasa un string al parámetro category en lugar de una de las constantes LC_*.
shm_attach | Esta función ahora devuelve un recurso en vez de un integer.
socket_create_pair | Esta función ya está disponible en las plataformas de Windows.
spl_autoload_register | Se añadio el parámetro prepend.
spl_autoload_register | Se introdujo el soporte para espacios de nombres.
stream_context_create | Se añadió el argumento opcional params.
stream_socket_pair | Esta función ahora está disponible en plataformas Windows.
stristr | Agregado el parámetro opcional before_needle.
strlen | Las versiones anteriores trataban los arrays como el string Array, devolviendo así una longitud de string de 5 y emitiendo un error de nivel E_NOTICE.
strstr | Se añadió el parámetro opcional before_needle.
strtotime | Antes de PHP 5.3.0, formatos de tiempo relativo que se suministran al parámetro time de la función strtotime como this week, previous week, last week, y next week se interpreta como un período de 7 días en relación con la fecha y hora actual, en lugar de un período de semana de Monday a Sunday.
strtotime | Antes de PHP 5.3.0, 24:00 no era un formato válido y strtotime devolvía false.
symlink | Esta función ahora es compatible con las plataformas Windows (Vista, Server 2008 o superior).
time_nanosleep | Esta función ahora está disponible en plataformas Windows.
time_sleep_until | Esta función ahora está disponible en plataformas Windows.
touch | Se hizo posible cambiar el momento de modificación de un directorio bajo Windows.
mysqli::__construct | Se añadió la capacidad de conexiones persistentes.
mysqli::options | Se añadierons las opciones MYSQLI_OPT_INT_AND_FLOAT_NATIVE, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, MYSQLI_OPT_NET_READ_BUFFER_SIZE, y MYSQLI_OPT_SSL_VERIFY_SERVER_CERT.
mysqli::query | Se agregó la posibilidad de realizar consultas asíncronas.
ReflectionFunction::__construct | ahora name puede representar una función anónima.
SplFileObject::setCsvControl | Añadido el parámetro escape.
SplObjectStorage::attach | Añadido el parámetro data.
5.2.15 | mysqli_driver::$report_mode | El cambio de modo de notificación ahora es por solicitud, en vez de por proceso.
5.2.11 | get_defined_constants | El parámetro categorize ahora funciona correctamente. Anteriormente, el parámetro categorize era interpretado como !is_null($categorize), por lo que cualquier valor distinto de null fuerza a las constantes a ser clasificadas.
5.2.10 | array_rand | El array de claves resultante ya no se mezcla.
array_unique | Se volvió a cambiar el valor predeterminado de sort_flags a SORT_STRING.
curl_setopt | Se introdujo CURLOPT_PROTOCOLS, y CURLOPT_REDIR_PROTOCOLS.
ip2long | Antes de esta versión, ip2long según como devolverá un número válido incluso si el valor no es una dirección con puntos (IPv4) Internet Protocol.
natsort | Las cadenas numéricas rellenadas con ceros (p.ej., '00005') ahora ignoran el relleno de 0.
5.2.9 | array_unique | Se añadió el parámetro opcional sort_flags con el valor predeterminado SORT_REGULAR. Antes de 5.2.9, esta función se usaba para ordenar el array con SORT_STRING internamente.
5.2.8 | XSLTProcessor::importStylesheet | Acepta SimpleXMLElement de nuevo; no funcionaba desde PHP 5.2.6.
5.2.7 | error_log | El valor posible de 4 se añadió a message_type.
round | El funcionamiento interno en round se modificó para adecuarse al estándar C99.
strtotime | En PHP 5 anterior a 5.2.7, las peticiones de una incidencia de un día de la semana dado en un mes donde ese día de la semana era el primer día del mes, añadía incorrectamente una semana a la marca de tiempo devuelta. Esto ha sido corregido en 5.2.7 y versiones posteriores.
5.2.6 | fopen | Se añadieron las opciones 'c' y 'c+'
5.2.5 | addcslashes | Se añadieron las secuencias de escape \v y \f.
debug_backtrace | Se añadió el parámetro opcional provide_object.
imagefilter | Se añadió el soporte de alfa para IMG_FILTER_COLORIZE.
5.2.4 | array_slice | El valor predeterminado del parámetro length se cambió a NULL. Una length NULL ahora indica a la función que use la longitud de array. Antes de esta versión, una length NULL se tomaba como de longitud cero (no se devolvía nada).
checkdnsrr | Se añadió el type TXT.
curl_getinfo | Introdujo CURLINFO_PRIVATE.
curl_setopt | Se introdujo CURLOPT_PRIVATE.
get_loaded_extensions | Fue añadido el parámetro opcional zend_extensions
ldap_first_attribute | ber_identifier ha sido retirado. Este ahora es manejado automáticamente por PHP.
ldap_next_attribute | El parámetro ber_identifier fue removido. Este se maneja ahora automáticamente por PHP.
stream_wrapper_register | Añadido el parámetro flags.
5.2.3 | getimagesize | Los errores de lectura generados por esta función se degradaron desde E_WARNING a E_NOTICE.
htmlentities | Se añadió el parámetro double_encode.
htmlspecialchars | Se añadió el parámetro double_encode.
json_decode | La profundidad de recursividad predeterminada se aumentó de 20 a 128
PDOStatement::getColumnMeta | El campo table
5.2.2 - 5.2.6 | substr | Si el parámetro start indica una posición negativa de truncamiento o más allá, se devolverá false. En otras versiones de PHP obtienen la cadena desde el principio.
5.2.2 | DOMDocument::registerNodeClass | Antes de 5.2.2, una extendedclass previamente registrada teniá que ser desregistrada antes de poder registrar una nueva clase que extendiese a la misma baseclass.
ftp_ssl_connect | La función se ha cambiado para devolver false cuando no se puede utilizar una conexión SSL, en lugar de recurrir a una conexión no-SSL como hacía en versiones anteriores.
phpinfo | Se añadió la información del "Fichero de configuración cargado", mientras que anteriormente solo existía "Ruta del fichero de configuración (php.ini).
preg_match | Los sub-patrones nominados ahora aceptan la sintaxis (?<nombre>) y (?'nombre') así como (?P<nombre>). Las versiones anteriores sólo aceptaban (?P<nombre>).
preg_match_all | Los sub-patrones nominados ahora aceptan la sintaxis (?<nombre>) y (?'nombre') así como (?P<nombre>). Versiones anteriores sólo aceptaban (?P<nombre>).
proc_terminate | Versiones previas usadas para destruir el recurso de un proceso dado.
token_get_all | Los números de línea son devueltos en el elemento 2
5.2.1 | iterator_to_array | Añadido el parámetro use_keys.
json_decode | Se añadió soporte para la decodificación de JSON de tipos básicos.
memory_get_peak_usage | Compilar con --enable-memory-limit ya no es necesario para que esta función exista.
memory_get_usage | Compilar con --enable-memory-limit ya no es necesario para que exista esta función.
mt_srand | La implementación de Mersenne Twister en PHP ahora usa un nuevo algoritmo para la semilla de Richard Wagner. La misma semilla ahora ya no produce la misma secuencia de valores como sucedía en anteriores versiones. No se espera que se vuelva a cambiar de nuevo este comportamiento, aunque, no obstante, se considera inseguro confiar en él.
proc_open | Añadida la opción bypass_shell al parámetro other_options.
realpath | Antes de esta versión, realpath devolvía false si path era un string vacío o null.
5.2.0 | base64_decode | Añadido strict
curl_multi_info_read | msgs_in_queue fue añadido.
error_reporting | Se introdujo E_RECOVERABLE_ERROR.
imagettftext | Ahora es posible especificar una entidad hexadecimal en text.
imap_open | Se añadió n_retries
imap_reopen | Se añadió n_retries
mb_strrpos | Se añadió el parámetro opcional offset.
memory_get_peak_usage | Se añade real_usage.
memory_get_usage | Se añadió real_usage.
openssl_verify | Se añadió el parámetro signature_alg.
pathinfo | Se añadió la constante PATHINFO_FILENAME.
pg_escape_bytea | Se agregó el parámetro connection
session_get_cookie_params | La entrada "httponly" fue añadida en la matriz devuelta.
session_set_cookie_params | Se añadió el parámetro httponly.
set_error_handler | El gestor de errores debe devolver false para rellenar $php_errormsg.
setcookie | Se añadió el parámetro httponly.
setrawcookie | Se añadió el parámetro httponly.
simplexml_load_file | Se añadió el parámetro opcional is_prefix.
simplexml_load_string | Se añadió el parámetro opcional is_prefix.
PDOStatement::execute | Las claves de input_parameters deben coincidir con aquellas declaradas en la sentencia SQL. Antes de PHP 5.2.0 esto se ignoraba silenciosamente.
SimpleXMLElement::attributes | Se añadió el parámetro opcional is_prefix.
SimpleXMLElement::children | Se añade el parámetro opcional is_prefix.
SimpleXMLElement::__construct | Añadidos los parámetros ns y is_prefix.
XMLReader::open | encoding y options fueron agregadas.
XMLReader::XML | encoding ay options fueron agregados.
5.1.3 | DirectoryIterator::__construct | Lanza una RuntimeException si path es una cadena vacía.
curl_getinfo | Introdujo CURLINFO_HEADER_OUT.
get_headers | Esta función usa el contexto de secuencia predeterminado, el cual puede ser definido/modificado con la función stream_context_set_default.
http_build_query | Los corchetes cuadrados son escapados.
imagecolorallocate | Devuelve false si falló la asignación. Anteriormente devolvía -1.
imagecolorallocatealpha | Devuelve false si falló la asignación. Anteriormente devolvía -1.
imagepng | Añadido el parámetro filters.
mb_get_info | Están disponibles las entradas "mail_charset", "mail_header_encoding", y "mail_body_encoding".
SoapClient::__doRequest | Se añadió el parámetro one_way.
XMLReader::getAttribute | Devuelve null si no se encuentra ningún atributo. Antes, devolvía una cadena de texto vacía.
5.1.2 | date_default_timezone_set | La función comenzo a validar el parámetro timezone_identifier.
header | Esta función ahora previene que se pueda enviar más de un encabezado a la vez como protección en contra de ataques de inyección de encabezados.
http_build_query | Se agregó el parámetro arg_separator.
imagepng | Añadido el parámetro quality.
parse_url | Se agregó el parámetro component.
SimpleXMLElement::__construct | Añadidos los parámetros options y data_is_url.
5.1.1 | date | Hay constantes útiles de los formatos estándar de fecha/hora que pueden utilizarse para especificar el parámetro format.
debug_backtrace | Se añadió el object actual como posible elemento devuelto.
gmdate | Hay constantes útiles de formatos de fecha/hora estándar que se pueden usar para especificar el parámetro format.
5.1.0 | DirectoryIterator::__construct | Lanza una RuntimeException en caso de error. Anteriormente lanzaba una Exception.
DOMDocument::save | Se añadió el parámetro options
DOMDocument::saveXML | Se añadió el parámetro options
class_implements | Añadida la opción para pasar el parámetro class como un string. Añadido el parámetro autoload.
class_parents | Añadida la opción para pasar el parámetro class como un string. Añadido el parámetro autoload.
ctype_digit | En versiones anteriores a PHP 5.1.0, esta función devolvía true cuando text era una cadena vacía.
curl_setopt | Se introdujo CURLOPT_AUTOREFERER, CURLOPT_BINARYTRANSFER, CURLOPT_FTPSSLAUTH, CURLOPT_PROXYAUTH, y CURLOPT_TIMECONDITION.
date | El rango válido de una marca de tiempo es típicamente desde Fri, 13 Dec 1901 20:45:54 GMT a Tue, 19 Jan 2038 03:14:07 GMT. (Estas son las fechas que corresponden a los valores mínimo y máximo de un entero con signo de 32 bit). Sin embargo, antes de PHP 5.1.0 este rango estaba limitado desde 01-01-1970 a 19-01-2038 en algunos sistemas (p.ej. Windows).
date | Ahora muestra un error E_STRICT y E_NOTICE cuando ocurren errores con zonas horarias.
date_sunrise | Ahora muestra un error E_STRICT y E_NOTICE cuando ocurren errores con zonas horarias.
date_sunset | Ahora muestra un error E_STRICT y E_NOTICE cuando ocurren errores con zonas horarias.
explode | Se añadió soporte para limit negativo.
fgetcsv | El parámetro length ahora es opcional. El valor predeterminado es 0, significando sin límite de longitud.
file_get_contents | Se añadieron los parámetros offset y maxlen.
file_put_contents | Añadido el soporte para LOCK_EX y la capacidad de pasar un recurso de flujo al parámetro data
get_parent_class | Si se llamaba sin parámetro fuera del objeto, está función devolvía null con una advertencia, pero ahora devuelve false.
gettimeofday | Se añadió el parámetro return_float.
glob | Se añadió GLOB_ERR
gmdate | El rango válido de una marca de tiempo es típicamente desde Fri, 13 Dec 1901 20:45:54 GMT a Tue, 19 Jan 2038 03:14:07 GMT. (Estas son las fechas que corresponden a los valores mínimo y máximo de un entero con signo de 32-bit). Sin embargo, antes de PHP 5.1.0 este rango estaba limitado desde 01-01-1970 a 19-01-2038 en algunos sistemas (p.ej. Windows).
gmmktime | A partir de PHP 5.1.0, el parámetro is_dst se volvió obsoleto. Como resultado, se podría usar en su lugar las nuevas características de manejo de zonas horarias.
idate | Ahora muestra un error E_STRICT y E_NOTICE cuando ocurren errores con zonas horarias.
imagerotate | Se añadió ignore_transparent.
intval | Lanza E_NOTICE y devuelve 1, cuando se pasa un objecto a var.
localtime | Ahora muestra un error E_STRICT y E_NOTICE cuando ocurren errores con zonas horarias.
md5_file | Se modificó la función para usar la API de secuencias. Esto quiere decir que se puede usar con envolturas, como md5_file('http://example.com/..')
mktime | Cuando se hace la llamada sin argumento, mktime lanza un aviso E_STRICT. Use la función time en su lugar.
mktime | Ahora muestra un error E_STRICT y E_NOTICE cuando ocurren errores con zonas horarias.
mktime | El parámetro is_dst se volvió obsoleto. Hacía que la funcion devolviese false si se pruducía un error, en vez de -1. Arreglada la función para que acepte el año, mes y día pasados como cero.
openssl_pkcs7_verify | Se añadió el parámetro content.
preg_replace | Añadido el parámetro count
preg_replace_callback | Se añadió el parámetro count
session_regenerate_id | Añadido el parámetro delete_old_session.
sha1_file | Cambiada la función para utilizar el API de flujo de datos. Esto significa que se puede utilizar con envolturas, como en sha1_file('http://ejemplo.com/..')
str_word_count | Agregado el parámetro charlist
stream_copy_to_stream | Se añadió el parámetro offset
stream_filter_append | Antes de PHP 5.1.0, esta función devolvía true si se tuvo éxito o false en caso de error.
stream_filter_prepend | Antes de PHP 5.1.0, esta función devolvía true en caso de éxito o false en caso de error.
stream_get_contents | Se añadió el parámetro offset.
strftime | Ahora muestra un error E_STRICT y E_NOTICE cuando ocurren errores con zonas horarias.
strtotime | Ahora devuelve false si falla, en vez de -1.
strtotime | Ahora muestra un error E_STRICT y E_NOTICE cuando ocurren errores con zonas horarias.
substr_compare | Se añadió la posibilidad de usar un offset negativo.
substr_count | Los parámetros offset y length fueron agregados
var_export | Posibilidad de exportar las clases y los arrays que contienen las clases utilizando el método mágico __set_state.
XSLTProcessor::registerPHPFunctions | Se añadió el parámetro restrict.
5.0.3 | get_class_vars | get_class_vars devolverá sólo las propiedades que pueden ser accedidas desde el ámbito actual.
is_subclass_of | Es posible especificar también el parámetro object como una cadena (el nombre de la clase)
5.0.2 | array_slice | Se añadió el parámetro opcional preserve_keys.
class_exists | Ya no devuelve true para interfaces definidas. En ese caso se debe usar interface_exists.
get_class_vars | Al llamar a get_class_vars ahora se expondrán todas las propiedades como una matriz, a diferencia del comportamiento anterior donde las propieades protected y private eran prefijadas con bytes nul.
sort | Se añadió SORT_LOCALE_STRING
strtotime | En PHP 5 hasta 5.0.2, "now" y otros momentos relativos son computados erróneamente como la medianoche de hoy. Esto difiere de otras versiones donde es computado como el momento actual.
5.0.1 | get_class_vars | Al llamar a get_class_vars se expondrán todas las propiedades, como cuando se convierte un objeto en una clase.
5.0.0 | curl_setopt | Se introdujo CURLOPT_FTP_USE_EPRT, CURLOPT_NOSIGNAL, CURLOPT_UNRESTRICTED_AUTH, CURLOPT_BUFFERSIZE, CURLOPT_HTTPAUTH, CURLOPT_PROXYPORT, CURLOPT_PROXYTYPE, CURLOPT_SSLCERTTYPE, y CURLOPT_HTTP200ALIASES.
is_a | Esta funcion se volvió obsoleta en favor del operador instanceof. Llamar a esta función resultará en una advertencia de tipo E_STRICT.
opendir | ruta soporta dentro de la URL la envoltura ftp://.
rename | rename ahora también puede emplearse con algunas envolturas de URL. Consulte para un listado de las envolturas que admite rename.
strip_tags | strip_tags ahora es segura a nivel binario.
strrpos | needle puede ser ahora un string de más de un carácter.
strtotime | Los microsegundos comenzaron a estar permitidos, pero son ignorados.

User Contributed Notes

There are no user contributed notes for this page.


HTML edición de ayuda

  • Sobre Esta Edición
  • Uso de la Edición CHM del Manual de PHP
    • La Barra de Herramientas de la Ayuda HTML
    • El Panel de Navegación
    • Combinaciones de Teclado
  • La Búsqueda de Texto Completo
    • Reglas generales de búsqueda
    • Búsquedas sobre palabras o frases
    • Definición de términos de búsqueda
    • Uso de expresiones anidadas en búsquedas
  • Integración del manual de PHP

User Contributed Notes

There are no user contributed notes for this page.


Sobre Esta Edición

La Edición de Ayuda HTML Windows del Manual de PHP está dirigida a desarrolladores, quienes desean tener el manual a mano todo el tiempo, y desean leer páginas del manual y notas de usuarios sin tener que esperar a que descargue una página web remota. Esta edición le ofrece el contenido completo del manual más las anotaciones de usuarios, con algunas excelentes características adicionales ofrecidas por la aplicación visora, por los scripts que usamos para generar éste formato y por otros contribuyentes en forma de skins.

Esta distribución del manual de PHP contiene varios archivos, incluyendo el archivo principal del manual, php_manual_en.chm. Puede ver el manual haciendo doble clic sobre éste archivo (tal y como ya lo habrá adivinado). También puede ver un archivo php_manual_en.chw en el directorio, éste es generado la primera vez que usa la pestaña del índice, y contiene un índice con las páginas del manual.

Para aquellos interesados en los detalles técnicos del formato Microsoft HTML Help, » http://www.helpware.net/ constituye un excelente recurso. Para más información, y saber del lugar de Windows HTML Help entre los formatos de ayuda de Microsoft y su historia de servicios, consulte este » artículo de WinWriters.

User Contributed Notes

There are no user contributed notes for this page.


Uso de la Edición CHM del Manual de PHP

Tabla de contenidos

  • La Barra de Herramientas de la Ayuda HTML
  • El Panel de Navegación
  • Combinaciones de Teclado

Cuando realiza doble-clic sobre un archivo CHM, una ventana del Visor de Ayuda HTML es abierta con tres páneles. En el lado izquierdo de la ventana se encuentra el panel de Navegación. Éste contiene cuatro solapas de navegación: las solapas de Contenido, índice, Búsqueda y Favoritos. En el lado derecho de la ventana se encuentra el panel de Tópico. Éste despliega el tema de ayuda seleccionado, o el tema de ayuda predeterminado en el arranque. Las páginas de ayuda son todas archivos HTML separados, su instalación de Internet Explorer despliega las páginas en el panel de Tópico. El tercer panel es la barra de herramientas, la cual está ubicada por debajo de la barra de título de la ventana de ayuda. Puede ajustar la apariencia horizontal al arrastrar el borde vertical entre el panel de Navegación y el panel de Tópico.

Note que cuando abre el documento CHM por primera vez, puede aparecer con una posición y tamaño extraños. Desde entonces, windows recuerda la posición de la ventana, su tamaño y la solapa abierta por última vez. Toda esta información, incluyendo sus favoritos, es almacenada en un archivo llamado hh.dat. Si mueve su archivo a otro directorio, todas estas preferencias recordadas se perderán (¡incluyendo su lista de favoritos!). Aunque, si reemplaza su archivo CHM por uno nuevo, con el mismo nombre, no será un problema. Los nombres de archivo y valores de ruta son almacenados en hh.dat.

User Contributed Notes

There are no user contributed notes for this page.


La Barra de Herramientas de la Ayuda HTML

La Barra de Herramientas de la Ayuda HTML contiene los siguientes íconos, cuando se encuentra consultando el Manual de PHP:

  • Esconder/Mostrar - Esconde/muestra el panel de navegación.
  • Ubicar - Ubica un tópico en la solapa de contenidos (en caso de que haya encontrado un tópico a travÉs de la búsqueda, el índice o los favoritos, y quisiera ver en dónde se encuentra en la vista de árbol de la tabla de contenidos).
  • Atrás - Va hacia atrás en el historial.
  • Adelante - Va hacia adelante en el historial.
  • Refrescar - Recarga la página actual.
  • Inicio - Abre la página de inicio del documento CHM.
  • Imprimir - Abre el cuadro de diálogo de impresión.
  • Opciones - Provee una lista con más opciones.
El uso de esta barra de herramientas es realmente sencillo, muchos de los íconos de la barra de herramientas están relacionados fuertemente con sus equivalentes en Internet Explorer.

User Contributed Notes

There are no user contributed notes for this page.


El Panel de Navegación

El Panel de Navegación contiene cuatro solapas de navegación: las solapas de Contenido, índice, Búsqueda y Favoritos. Éstas proveen mÉtodos diferentes para acceder a un tópico en el archivo de ayuda.

  • La solapa de contenidos revela una tabla de contenidos en forma de árbol, en donde puede navegar al tópico deseado al abrir y cerrar partes del árbol. Puede incluso acceder a las secciones más profundas usando Ésta tabla de contenidos. Si hace clic derecho sobre un item aquí y selecciona "Imprimir...", tendrá la opción de imprimir el tópico seleccionado o el tópico seleccionado junto con todos los sub-temas. Sin embargo, la impresión no es el objetivo inicial de esta versión del manual (la versión PDF es apropiada para su impresión).
  • La solapa de índice lista un gran número de "palabras clave" (en realidad, títulos de páginas del manual). Puede seleccionar una, o comenzar a escribir una palabra clave, ver la lista ajustarse a su entrada, y luego hacer clic sobre un tema, o presionar enter si el tema seleccionado es el que desea consultar.
  • La solapa de búsqueda muestra una de las características más poderosas del Visor de Ayuda HTML, la búsqueda de texto completo (tambiÉn conocida como FTS, por sus siglas en InglÉs). Aquí puede escribir su expresión de búsqueda, conectando palabras opcionalmente con AND/OR/NEAR/NOT. Antes de que haga clic sobre 'Listar temas', tambiÉn puede definir algunas opciones en la parte baja. Luego de que los resultados de búsqueda son desplegados, notará que el texto del manual y los resultados de notas de usuario son separados. Para ordenar ambos tipos, pulse sobre la cabecera de la columna 'Ubicación'. Ahora, desde la lista de resultados de la búsqueda, puede seleccionar un tema, y ver su página. Las palabras que ha buscado son resaltadas en la página.
  • La solapa de favoritos le permite guardar una lista con los temas más usados, para su fácil acceso. Aquí puede ver la lista, agregar un tema a ella, eliminar un tema, o desplegar un item seleccionado. TambiÉn puede especificar su propio título para el favorito, escribiÉndolo en el cuadro 'Tema actual:'. Los títulos de páginas de notas de usuario son precedidos de la cadena 'N:', de modo que pueda distinguirlas de las páginas normales del manual en el listado de favoritos.

User Contributed Notes

There are no user contributed notes for this page.


Combinaciones de Teclado

Hay varias combinaciones de teclas que puede usar para incrementar su productividad. Muchos usuarios encuentran más cómodo usar Éstas combinaciones de teclado para acceder a los temas, en lugar de hacer uso de clics.

Combinaciones de Teclado Generales del Visor de Ayuda
Para | Presione
Cerrar el Visor de Ayuda | ALT+F4
Mostrar el menú de Opciones | ALT+O
Esconder o mostrar el panel de Navegación | ALT+O, y luego T
Imprimir un tema | ALT+O, y luego P
Moverse al tema anterior | ALT+FLECHA IZQUIERDA
Moverse al tema siguiente (provisto que lo ha visitado anteriormente) | ALT+FLECHA DERECHA
Activar o desactivar el resaltado de búsquedas. | ALT+O, y luego O
Regresar al inicio del archivo de ayuda | ALT+O, y luego H
Cambiar entre el panel de Navegación y el panel de Tópico | F6
Desplazarse a travÉs de todos los enlaces en un tema o a travÉs de todas las opciones en una solapa del panel de Navegación | TAB
Mostrar el menú de contexto (clic derecho) | SHIFT+F10
Combinaciones de Teclado de la Solapa de Contenidos
Para | Presione
Mostrar la solapa de Contenidos | ALT+C
Abrir y cerrar un libro o carpeta | SIGNO MáS y SIGNO MENOS, o FLECHA IZQUIERDA y FLECHA DERECHA
Seleccionar un tema | FLECHA HACIA ABAJO y FLECHA HACIA ARRIBA
Mostrar el tema seleccionado | ENTER
Combinaciones de Teclado de la Solapa de índice
Para | Presione
Mostrar la solapa de índice | ALT+N
Escribir una palabra clave a buscar | ALT+W, y luego escriba la palabra
Seleccionar una palabra clave en la lista | FLECHA HACIA ABAJO y FLECHA HACIA ARRIBA
Mostrar el tema asociado | ENTER o ALT+D
Combinaciones de Teclado de la Solapa de Búsqueda
Para | Presione
Mostrar la solapa de Búsqueda | ALT+S
Escribir una palabra clave a buscar | ALT+W, y luego escriba la palabra
Iniciar una búsqueda | ALT+L
Seleccioner un tema en la lista de resultados | ALT+T, y luego FLECHA HACIA ABAJO y FLECHA HACIA ARRIBA
Mostrar el tema seleccionado | ENTER o ALT+D
Buscar por una palabra clave en la lista de resultados de una búsqueda previa | ALT+U
Buscar por palabras similares a la palabra clave. Por ejemplo para encontrar palabras como "corriendo" y "corre" para la palabra clave "correr" | ALT+M
Buscar sólo a travÉs de los títulos de los temas | ALT+R
Combinaciones de Teclado de la Solapa de Favoritos
Para | Presione
Mostrar la solapa de Favoritos | ALT+I
Agregar el tema mostrado actualmente a la lista de Favoritos | ALT+A
Seleccionar un tema en la lista de Favoritos | ALT+P, y luego FLECHA HACIA ABAJO y FLECHA HACIA ARRIBA
Mostrar el tema seleccionado | ENTER o ALT+D
Eliminar el tema seleccionado de la lista | ALT+R
Combinaciones de Teclado del Panel de Tópico
Para | Presione
Consultar en el índice | Seleccione las palabras que quiere consultar y presione F1
Encontrar en la página | CTRL+F, y luego ajuste las opciones
Refrescar la página | F5

User Contributed Notes

There are no user contributed notes for this page.


La Búsqueda de Texto Completo

Tabla de contenidos

  • Reglas generales de búsqueda
  • Búsquedas sobre palabras o frases
  • Definición de términos de búsqueda
  • Uso de expresiones anidadas en búsquedas

Esta edición del Manual de PHP incluye una característica avanzada de búsqueda de texto completo ofrecida por la aplicación visora. Esto le permite a los usuarios buscar por cada palabra en el archivo de ayuda para encontrar una coincidencia. Por ejemplo, si un usuario realiza una búsqueda de texto completo sobre la palabra "Apache", cada tópico que contega la palabra "Apache" será listado. La búsqueda de texto completo le permite a un usuario efectuar búsquedas usando expresiones anidadas, booleanas y comodines. Un usuario también puede limitar la búsqueda a resultados previos, coincidencias con palabras similares, o buscar únicamente en títulos de temas.

El uso de la característica de búsqueda es bastante directo. Pulse sobre la solapa de búsqueda, escriba las palabras deseadas y presione ENTER (o pulse sobre "Listar Tópicos"). Entonces recibirá una lista de coincidencias del Manual de PHP (y las notas). Puede usar el botón con una flecha derecha y agregar operadores booleanos a su búsqueda (o puede escribirlos). Como puede ver en los resultados, puede usar las cabeceras de columna (Título, Ubicación y Rango) para ordenar la lista de tópicos. El orden predeterminado es por Rank. También puede ordenar algunos parámetros al final de la ésta solapa.

Las palabras encontradas son resaltadas en la página actual del panel de Tópico por defecto. Puede deshabilitar ésta característica seleccionando el item "Search Highlight Off" en el menú de Opciones. Si está observando un tópico largo, sólo las primeras 500 instancias de una palabra o frase de búsqueda serán resaltadas, debido a una limitación del visor.

User Contributed Notes

There are no user contributed notes for this page.


Reglas generales de búsqueda

Una búsqueda básica consiste de la palabra o frase que desea encontrar. Puede usar expresiones con comodines, expresiones anidadas, operadores booleanos, coincidencias de palabras similares, una lista de resultados previos, o títulos de temas para refinar su búsqueda.

Las reglas básicas para formular consultas son las siguientes:

  • Las búsquedas no son sensibles a mayúsculas y minúsculas, de modo que puede escribir su búsqueda usando cualquier estilo.
  • Puede realizar búsquedas sobre cualquier combinación de letras (a-z) y números (0-9). No puede realizar búsquedas sobre letras sencillas (a, b, c, etc.) y palabras comunes, como: un, y, como, en, pero, por, para, tener, el, en, eso, no, de, sobre, ella, alla, esto, nosotros, cual, con, usted.
  • Los signos de puntuación como el punto (.), los dos-puntos (:), el punto-y-coma (;), la coma (,), y el guión (-) son ignorados durante una búsqueda.
  • Agrupe los elementos de su búsqueda usando comillas dobles o paréntesis para separar cada elemento. No puede hacer búsquedas sobre signos de comillas.

Nota:

Si está buscando por un nombre de archivo con una extensión, debe agrupar la cadena completa en comillas dobles, ("nombre_archivo.ext"). De otra forma, el punto separará el nombre de archivo en dos términos diferentes. La operación predeterminada entre términos es AND, de modo que creará el equivalente lógico de "nombre_archivo AND ext".

User Contributed Notes

There are no user contributed notes for this page.


Búsquedas sobre palabras o frases

Puede realizar búsquedas sobre palabras o frases y usar expresiones con comodines. Las expresiones con comodines le permiten buscar por uno o más caracteres usando un signo de interrogación o un asterisco. La siguiente tabla describe los resultados de éstos tipos distintos de búsqueda.

Búsquedas por palabra y frase
Buscar por | Ejemplo | Resultados
Una palabra sencilla | seleccionar | Tópicos que contienen la palabra "seleccionar". (También encontrará sus variaciones gramaticales, como "seleccionador" y "selección".)
Una frase | "nuevo operador" o nuevo operador | Tópicos que contienen la frase literal "nuevo operador" y todas sus variaciones gramaticales. Sin las comillas, la consulta es equivalente a especificar "nuevo AND operador,", lo que encontrará los tópicos que contienen ambas palabras individuales, en lugar de la frase.
Expresiones comodín | esc* o HT?? | Los resultados del primer ejemplo incluyen los tópicos que contengan los términos "ESC", "escapar", "escalabilidad", y demás. El asterisco no puede ser el único caracter en el término. Los resultados para el segundo ejemplo incluyen los tópicos que contengan los términos "HTTP", "HTML" y demás. El signo de interrogación no puede ser el único caracter en el término.

Nota:

Seleccione el campo "Match similar words" para incluir variaciones gramaticales menores de la frase que busca. Esta característica solo ubica variacones de la palabra con sufijos comunes. Por ejemplo, una búsqueda sobre la palabra "add", encontrará "added," pero no encontrará "additive". Esta opción es independiente de otras opciones o sintaxis. Si realiza una búsqueda sólo sobre títulos, las variaciones del títulos serán consideradas. Si usa comillas (o cualquier otro operador de consulta), puede aparecer cualquier variación de la palabra; por ejemplo "stemmed search" también coincidirá con "stemming search".

User Contributed Notes

There are no user contributed notes for this page.


Definición de términos de búsqueda

Los operadores AND, OR, NOT y NEAR le permiten definir con precisión su búsqueda, creando una relación entre términos de búsqueda. La siguiente tabla le muestra cómo puede mostrar cada uno de estos operadores. Si no se especifica un operador, se usa AND. Por ejemplo, la consulta "servidor cgi seguridad" es equivalente a "servidor AND cgi AND seguridad".

Operadores de búsqueda
Buscar por | Ejemplo | Resultados
Ambos términos en el mismo tópico | http AND apache | Tópicos que contienen las palabras "http" y "apache".
Cualquier término en un tópico | ming OR swflib | Tópicos que contienen ya sea la palabra "ming" o la palabra "swflib", o ambas.
El primer término sin el segundo | xml NOT expat | Tópicos que contienen la palabra "xml", pero no la palabra "expat".
Ambos términos en el mismo tópico, cerca uno del otro | database NEAR security | Tópicos que contienen la palabra "database" a ocho palabras de distancia de la palabra "security".

Nota:

Los caracteres |, &, y ! pueden ser usados también en lugar de OR, AND y NOT respectivamente. Puede que esto no funcione si usa una versión antigua del visor.

User Contributed Notes

There are no user contributed notes for this page.


Uso de expresiones anidadas en búsquedas

Las expresiones anidadas le permiten crear búsquedas de información complejas. Por ejemplo "html AND ((smtp OR pop3) NEAR mail)" encuentra tópicos que contienen la palabra "html" junto con las palabras "smtp" y "mail" cercanas una de la otra, o que contengan "html" junto con las palabras "pop3" y "mail" cercanas entre sí.

Las reglas básicas para buscar tópicos de ayuda usando expresiones anidadas son las siguientes:

  • Puede usar paréntesis para anidar expresiones al interior de una consulta. Las expresiones entre paréntesis son evaluadas antes del resto de la consulta.
  • Si una consulta no contiene una expresión anidada, ésta es evaluada de izquierda a derecha. Por ejemplo: "mail NOT pop3 OR smtp" encuentra los tópicos que contienen la palabra "mail" sin la palabra "pop3", o tópicos que contienen la palabra "smtp". Por otra parte, "mail NOT (pop3 OR smtp)" encuentra los tópicos que contienen la palabra "mail" sin ninguna de las palabras "pop3" ni "smtp".
  • No puede anidar expresiones con más de cinco niveles de profundidad.

User Contributed Notes

There are no user contributed notes for this page.


Integración del manual de PHP

Nota:

La información ofrecida aquí está dirigida principalmente a autores de IDEs, o usuarios avanzados que quisieran integrar éste archivo CHM con sus IDEs favoritos u otros componentes de entornos de producción.

Existen varios editores en la actualidad que ofrecen integración con CHM, pero puede que necesite saber algunas cosas sobre los contenidos CHM para integrar satisfactoriamente el manual a su entorno.

El documento CHM es construido usando tablas de estilos XSL a partir de fuentes XML. Este hecho es único actualmente en la familia del Manual de PHP, ya que todas las otras versiones son generadas usando tablas de estilo DSSSL. Esto también quiere decir que pueden surgir algunas diferencias de visualización no intencionales. Un script especial de conversión es ejecutado sobre la salida XSLT, agregando varias características interesantes, y empaquetando el manual con los archivos de preferencias y muestras de skins.

Si nunca ha trabajado con CHMs, puede pensar en ellos como archivos comprimidos con soporte integrado del SO para el acceso a archivos y soporte adicional para búsquedas e índices. Aunque los archivos CHM sólo pueden consultarse usando el Visor de Ayuda HTML, se puede acceder directamente a archivos al interior de documentos CHM usando un prefijo de URL especial, el nombre del archivo CHM y el archivo que desea en el interior. Ya que todo el contenido de la ayuda es almacenado en archivos HTML, puede desplegar páginas del CHM en Internet Explorer.

Asumiendo que usted colocó su archivo php_manual_en.chm en c:\phpmanual, el archivo índice del manual (aquel que ve la primera vez) puede ser consultado con la siguiente URL: mk:@MSITStore:C:\phpmanual\php_manual_en.chm::/_index.html. Aquí, mk:@MSITStore: es el "protocolo" especial, C:\phpmanual\php_manual_en.chm es el documento CHM con su ruta completa. La parte /_index.html es la ruta al archivo índice dentro del CHM y :: es simplemente lo que necesita colocar entre la ruta CHM y ésta ruta de archivo.

Nota:

Todos los archivos se encuentran en el directorio raíz del CHM, a diferencia de versiones previas de CHM que incluían un directorio de lenguaje. Las imágenes, tables de estilos y otros archivos suplementarios tienen nombres que inician con un caracter de subrayado (como ocurre con el índice principal mostrado anteriormente), para evitar colisiones de nombres.

Los nombres de los archivos generados siguen las mismas reglas que el manual en línea, excepto que la extensión es .html y no .php. La más importante es que los archivos de documentación de funciones reciben nombres de la forma function.FUNCNAME.html, en donde FUNCNAME es el nombre de la función, con todos los signos de subrayado convertidos en guiones. Algunos ejemplos son function.echo.html, function.mysql-close.html, function.imagecopy.html.

Usando toda esta información, usted puede mostrar una página del manual para una función solicitada por un usuario. Un ejemplo simple es incluido en la distribución, llamado php_quickref.hta. ésta es una » Aplicación HTML parA demostrar el simple proceso de mostrar una página del manual que hace referencia a una función. La función quickRef() definida allí cumple con esta tarea.

Si se quiere integrar el manual en un IDE sin soporte directo para el manual de PHP (en realidad, la conversión de signos de subrayado en guiones), puede usar el archivo _function.html incluido para acceder a una página de función, Este archivo es simplemente un enrutador, y puede ser parametrizado a través de la URL, como _function.html#mysql_close. Esta página le redireccionará a la página de la función mysql_close (function.mysql-close.html) automáticamente. Puede proveer la ruta completa de este archivo si su IDE soporta la ayuda sensible a contexto, y proveer la cadena especificada por el IDE como el parámetro. Un ejemplo de esto es la integración de UltraEdit 9 (vea la página web de edición).

El índice del manual (asequible a través de la pestaña de índice en el panel de navegación) puede ser usado también para propósitos de integración. Todas las páginas HTML son incluidas en el índice con sus títulos como términos de indexación (incluyendo páginas de descripción de funciones).

Si usted es un desarrollador de aplicaciones de escritorio y quiesiera integrar profundamente el CHM con su programa (como por ejemplo desplegando el árbol de la tabla de contenidos en el cuadro de ayuda de su IDE), puede encontrar más información en » http://www.helpware.net/, así como en otros recursos útiles. El sitio oficial del formato HTML Help se encuentra en » http://www.microsoft.com/download/en/details.aspx?id=21138.

User Contributed Notes

There are no user contributed notes for this page.