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
    • WDDX Funciones
  • 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 — La clase XMLReader
  • 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::after — Adds nodes after the character data
    • DOMCharacterData::appendData — Añade el string de caracteres al final de los datos de carácter del nodo.
    • DOMCharacterData::before — Adds nodes before the node
    • DOMCharacterData::deleteData — Eliminar una serie de caracteres del nodo
    • DOMCharacterData::insertData — Inserta un string en la posición de 16-bit especificada
    • DOMCharacterData::remove — Removes the character data
    • DOMCharacterData::replaceData — Reemplaza un substring dentro de un nodo DOMCharacterData
    • DOMCharacterData::replaceWith — Replaces the character data with new nodes
    • DOMCharacterData::substringData — Extrae una serie de datos del nodo
  • DOMComment — Clase DOMComment
    • DOMComment::__construct — Crea un nuevo objeto DOMComment
  • DOMDocument — Clase DOMDocument
    • DOMDocument::adoptNode — Transfer a node from another document
    • DOMDocument::append — Appends nodes after the last child node
    • 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::prepend — Prepends nodes before the first child node
    • 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::replaceChildren — Replace children in document
    • 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::append — Appends nodes after the last child node
    • DOMDocumentFragment::appendXML — Añade información XML sin formato
    • DOMDocumentFragment::__construct — Constructs a DOMDocumentFragment object
    • DOMDocumentFragment::prepend — Prepends nodes before the first child node
    • DOMDocumentFragment::replaceChildren — Replace children in fragment
  • DOMDocumentType — La clase DOMDocumentType
  • DOMElement — La clase DOMElement
    • DOMElement::after — Adds nodes after the element
    • DOMElement::append — Appends nodes after the last child node
    • DOMElement::before — Adds nodes before the element
    • DOMElement::__construct — Crea un nuevo objeto DOMElement
    • DOMElement::getAttribute — Devuelve el valor de un atributo
    • DOMElement::getAttributeNames — Get attribute names
    • 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::insertAdjacentElement — Insert adjacent element
    • DOMElement::insertAdjacentText — Insert adjacent text
    • DOMElement::prepend — Prepends nodes before the first child node
    • DOMElement::remove — Removes the element
    • DOMElement::removeAttribute — Elimina un atributo
    • DOMElement::removeAttributeNode — Elimina un atributo
    • DOMElement::removeAttributeNS — Elimina un atributo
    • DOMElement::replaceChildren — Replace children in element
    • DOMElement::replaceWith — Replaces the element with new nodes
    • 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::toggleAttribute — Toggle attribute
  • 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::getIterator — Retrieve an external iterator
    • 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::contains — Checks if node contains other node
    • DOMNode::getLineNo — Obtener el número de línea de un nodo
    • DOMNode::getNodePath — Obtener un XPath de un nodo
    • DOMNode::getRootNode — Get root node
    • 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::isEqualNode — Checks that both nodes are equal
    • 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::getIterator — Retrieve an external iterator
    • 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 mb_convert_encoding(), UConverter::transcode(), or iconv() to handle other encodings.

User Contributed Notes

captainjester at hotmail dot com 27-Mar-2020 12:59
Be careful when using this for partial HTML. This will only take complete HTML documents with at least an HTML element and a BODY element. If you are working on partial HTML and you fill in the missing elements around it and don't specify in META elements the character encoding then it will be treated as ISO-8859-1 and will mangle UTF-8 strings. Example:

<?php
$body = getHtmlBody();
$doc = new DOMDocument();
$doc->loadHtml("<html><body>".$body."</body></html>");
// $doc will treat your HTML ISO-8859-1.
// this is correct but may not be what you want if your source is UTF-8
?>

<?php
$body = getHtmlBody();
$doc = new DOMDocument();
$doc->loadHtml("<html><head><meta charset=\"UTF-8\"><meta http-equiv=\"Content-Type\" content=\"text/html; CHARSET=Windows-1252\"></head><body>".$body."</body></html>");
// $doc will treat your HTML correctly as UTF-8.
?>


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

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 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, PHP 8)

Introducción

DOMAttr representa un atributo en el objeto DOMElement.

Sinopsis de la Clase

class 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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, PHP 8)

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, PHP 8)

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, PHP 8)

Introducción

DOMCdataSection hereda de DOMText para la representación textural de constructores CData.

Sinopsis de la Clase

class 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::after(DOMNode|string ...$nodes): void
public DOMCharacterData::appendData(string $data): void
public DOMCharacterData::before(DOMNode|string ...$nodes): void
public DOMCharacterData::deleteData(int $offset, int $count): void
public DOMCharacterData::insertData(int $offset, string $data): void
public DOMCharacterData::remove(): void
public DOMCharacterData::replaceData(int $offset, int $count, string $data): void
public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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, PHP 8)

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, PHP 8)

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

class 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 after(DOMNode|string ...$nodes): void
public appendData(string $data): void
public before(DOMNode|string ...$nodes): void
public deleteData(int $offset, int $count): void
public insertData(int $offset, string $data): void
public remove(): void
public replaceData(int $offset, int $count, string $data): void
public replaceWith(DOMNode|string ...$nodes): 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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::after — Adds nodes after the character data
  • DOMCharacterData::appendData — Añade el string de caracteres al final de los datos de carácter del nodo.
  • DOMCharacterData::before — Adds nodes before the node
  • DOMCharacterData::deleteData — Eliminar una serie de caracteres del nodo
  • DOMCharacterData::insertData — Inserta un string en la posición de 16-bit especificada
  • DOMCharacterData::remove — Removes the character data
  • DOMCharacterData::replaceData — Reemplaza un substring dentro de un nodo DOMCharacterData
  • DOMCharacterData::replaceWith — Replaces the character data with new nodes
  • 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


Adds nodes after the character data

  • « DOMCharacterData
  • DOMCharacterData::appendData »
  • PHP Manual
  • DOMCharacterData
  • Adds nodes after the character data

DOMCharacterData::after

(PHP 8)

DOMCharacterData::after — Adds nodes after the character data

Descripción

public DOMCharacterData::after(DOMNode|string ...$nodes): void

Adds the passed nodes after the element.

Ejemplos

Ejemplo #1 DOMCharacterData::after() example

Adds nodes after the character data.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[hello]]></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->after("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<container><![CDATA[hello]]>beautiful<world/></container>

Ver también

  • DOMChildNode::after()
  • DOMCharacterData::before() - Adds nodes before the node

User Contributed Notes

There are no user contributed notes for this page.


Añade el string de caracteres al final de los datos de carácter del nodo.

  • « DOMCharacterData::after
  • DOMCharacterData::before »
  • 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, PHP 8)

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.


Adds nodes before the node

  • « DOMCharacterData::appendData
  • DOMCharacterData::deleteData »
  • PHP Manual
  • DOMCharacterData
  • Adds nodes before the node

DOMCharacterData::before

(PHP 8)

DOMCharacterData::before — Adds nodes before the node

Descripción

public DOMCharacterData::before(DOMNode|string ...$nodes): void

Adds the passed nodes before the node.

Ejemplos

Ejemplo #1 DOMCharacterData::before() example

Adds nodes before the character data.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[world]]></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->before("hello", $doc->createElement("beautiful"));

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<container>hello<beautiful/><![CDATA[world]]></container>

Ver también

  • DOMChildNode::before()
  • DOMCharacterData::after() - Adds nodes after the character data

User Contributed Notes

There are no user contributed notes for this page.


Eliminar una serie de caracteres del nodo

  • « DOMCharacterData::before
  • DOMCharacterData::insertData »
  • PHP Manual
  • DOMCharacterData
  • Eliminar una serie de caracteres del nodo

DOMCharacterData::deleteData

(PHP 5, PHP 7, PHP 8)

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::remove »
  • PHP Manual
  • DOMCharacterData
  • Inserta un string en la posición de 16-bit especificada

DOMCharacterData::insertData

(PHP 5, PHP 7, PHP 8)

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.


Removes the character data

  • « DOMCharacterData::insertData
  • DOMCharacterData::replaceData »
  • PHP Manual
  • DOMCharacterData
  • Removes the character data

DOMCharacterData::remove

(PHP 8)

DOMCharacterData::remove — Removes the character data

Descripción

public DOMCharacterData::remove(): void

Removes the character data.

Ejemplos

Ejemplo #1 DOMCharacterData::remove() example

Removes the character data.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[hello]]><world/></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->remove();

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<container><world/></container>

Ver también

  • DOMChildNode::remove()
  • DOMCharacterData::after() - Adds nodes after the character data
  • DOMCharacterData::before() - Adds nodes before the node
  • DOMCharacterData::replaceWith() - Replaces the character data with new nodes
  • DOMNode::removeChild() - Elimina un hijo de la lista de hijos.

User Contributed Notes

There are no user contributed notes for this page.


Reemplaza un substring dentro de un nodo DOMCharacterData

  • « DOMCharacterData::remove
  • DOMCharacterData::replaceWith »
  • PHP Manual
  • DOMCharacterData
  • Reemplaza un substring dentro de un nodo DOMCharacterData

DOMCharacterData::replaceData

(PHP 5, PHP 7, PHP 8)

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.


Replaces the character data with new nodes

  • « DOMCharacterData::replaceData
  • DOMCharacterData::substringData »
  • PHP Manual
  • DOMCharacterData
  • Replaces the character data with new nodes

DOMCharacterData::replaceWith

(PHP 8)

DOMCharacterData::replaceWith — Replaces the character data with new nodes

Descripción

public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void

Replaces the character data with new nodes.

Ejemplos

Ejemplo #1 DOMCharacterData::replaceWith() example

Replaces the character data with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[hello]]></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<container>beautiful<world/></container>

Ver también

  • DOMChildNode::replaceWith()
  • DOMCharacterData::after() - Adds nodes after the character data
  • DOMCharacterData::before() - Adds nodes before the node
  • DOMCharacterData::remove() - Removes the character data

User Contributed Notes

There are no user contributed notes for this page.


Extrae una serie de datos del nodo

  • « DOMCharacterData::replaceWith
  • DOMComment »
  • PHP Manual
  • DOMCharacterData
  • Extrae una serie de datos del nodo

DOMCharacterData::substringData

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

Introducción

Representa nodos comentario, caracteres delimitados por <!-- y -->.

Sinopsis de la Clase

class 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::after(DOMNode|string ...$nodes): void
public DOMCharacterData::appendData(string $data): void
public DOMCharacterData::before(DOMNode|string ...$nodes): void
public DOMCharacterData::deleteData(int $offset, int $count): void
public DOMCharacterData::insertData(int $offset, string $data): void
public DOMCharacterData::remove(): void
public DOMCharacterData::replaceData(int $offset, int $count, string $data): void
public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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

npelov at croler dot net 09-Sep-2021 04:41
Note that textContent property of a comment is not entity decoded, it is decoded in DOMElement::textContent :

<?php

   $xml = new DOMDocument();
    $xml->loadXML('<?xml version="1.0" encoding="utf-8"?>
      <configuration version="2">
      <!-- test &#45;&#45;&gt; -->
      test &#45;&#45;&gt;
      </configuration>'
    );
$xpath = new DOMXPath($xml);
$comments = $xpath->query('//comment()');
$elements = $xpath->query('//configuration');

echo $comments[0]->textContent;
// result: test &#45;&#45;&gt;

echo $elements[0]->textContent;
// result: test -->

?>


Crea un nuevo objeto DOMComment

  • « DOMComment
  • DOMDocument »
  • PHP Manual
  • DOMComment
  • Crea un nuevo objeto DOMComment

DOMComment::__construct

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

Introducción

Representa un documento HTML o XML en su totalidad; sirve como raíz del árbol de documento.

Sinopsis de la Clase

class 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 adoptNode(DOMNode $node): DOMNode|false
public append(DOMNode|string ...$nodes): void
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 prepend(DOMNode|string ...$nodes): void
public registerNodeClass(string $baseclass, string $extendedclass): bool
public relaxNGValidate(string $filename): bool
public relaxNGValidateSource(string $source): bool
public replaceChildren(DOMNode|string ...$nodes): void
public save(string $filename, int $options = 0): int
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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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::adoptNode — Transfer a node from another document
  • DOMDocument::append — Appends nodes after the last child node
  • 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::prepend — Prepends nodes before the first child node
  • 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::replaceChildren — Replace children in document
  • 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

610010559 at qq dot com 17-Mar-2022 02:39
when you add the new element to formatted XML data through appendChild() method, you would the new element you add is not be formatted(that is not indexed, not line break).  here is my solution (in short load the xml without preserve white space, ), example show as below:
<?php
$doc = new \DOMDocument();
$doc->formatOutput = true;
$doc->preserveWhiteSpace = false;//that is key, default value is true.
$doc->loadXML($xmlStr);
$doc->appendChild($doc->createElement('php', '666'))
$formattedXMLStr = $doc->saveXML();//DOMDocument wold format the xml str for you
echo $formattedXMlStr;
?>
it take me some time to try it out. hope it save your time.
andreas at userbrain dot com 17-Nov-2021 01:16
After struggling with parsing and modifying partial HTML content for several hours, I came to this solution which does work for me and is relatively simple compared to what else I found online.

This solution fixes unwanted DOCTYPE and html, body tags as well as encoding issues.

<?php

// Assumption: content is utf-8 encoded
$content = "<h1>This is a heading</h1><p>This is a paragraph</p>";

// Load content to a div and specify encoding with a meta tag
$temp_dom = new DOMDocument();
$temp_dom->loadHTML("<meta http-equiv='Content-Type' content='CHARSET=Windows-1252' /><div>$content</div>");

// As loadHTML() adds a DOCTYPE as well as <html> and <body> tag, let’s create another DOMDocument and import just the nodes we want
$dom = new DOMDocument();
$first_div = $temp_dom->getElementsByTagName('div')[0];
$first_div_node = $dom->importNode($first_div, true);
$dom->appendChild($first_div_node);

// Do whatever you want to do
$dom->getElementsByTagName('h1')[0]->setAttribute('class', 'happy');

// You could also just echo $dom->saveHtml() if you don’t mind the div and whitespace
echo substr(trim($dom->saveHtml()), 5, -6);

// Outputs: <h1 class="happy">This is a heading</h1><p>This is a paragraph</p>
?>
pastormontesinos at gmail dot com 04-Mar-2021 10:34
For using safely with script nodes when parsing, best option is extending DOMDocument, keeping script tags while DOMDocument process and rearrange them just after saveHTML function is called. Here is my custom class.

<?php

class SafeDOMDocument extends \DOMDocument
{
    const REGEX_JS            = '#(\s*<!--(\[if[^\n]*>)?\s*(<script.*</script>)+\s*(<!\[endif\])?-->)|(\s*<script.*</script>)#isU';
    const SUBSTITUTION_FORMAT = '<!--<script class="script_%s"></script>-->';
    private $matchedScripts = [];

    public function loadHTML($source, $options = 0)
    {
        $this->formatOutput        = false;
        $this->preserveWhiteSpace  = true;
        $this->validateOnParse     = false;
        $this->strictErrorChecking = false;
        $this->recover             = false;
        $this->resolveExternals    = false;
        $this->substituteEntities  = false;
        $matches = [];
        $success = preg_match_all(self::REGEX_JS, $source, $matches);

        if ($success && !empty($matches)) {
            foreach ($matches[0] as $match) {
                $storedScript = rtrim(ltrim($match, "\n\r\t "), "\n\r\t ");
                $scriptId = md5($storedScript);
                $key = sprintf(self::SUBSTITUTION_FORMAT, $scriptId);
                $source = str_replace($match, $key, $source);
                $this->matchedScripts[$key] = $storedScript;
            }
        }

        return parent::loadHTML($source, $options);
    }

    public function saveHTML(DOMNode $node = null)
    {
        $output = parent::saveHTML($node);

        if (count($this->matchedScripts)) {
            foreach ($this->matchedScripts as $substitution => $originalSnippet) {
                $output = str_replace($substitution, $originalSnippet, $output);
            }
        }

        return $output;
    }
}
?>
ashjkshdu283 at gmail dot com 07-Jul-2018 11:39
/* Function evolved from jay at jaygilford dot com post
  * This function will return an array of the values of the specified
  * attribute ($attr) for all the Dom Document object's elements
  */

<?php

function getAttrData(string $attr, DomDocument $dom) {
    // Empty array to hold all classes to return
    $attrData = array();

    //Loop through each tag in the dom and add it's attribute data to the array
    foreach($dom->getElementsByTagName('*') as $tag) {
        if(empty($tag->getAttribute($attr)) === false) {
            array_push($attrData, $tag->getAttribute($attr));
        }
    }

    //Return the array of attribute data
    return array_unique($attrData);
}

$html = '
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<a href="#someLink" id="someLink" class="link-class">Some Link</a>
<a href="#someOtherLink" id="someOtherLink" class="link-class">Some Other Link</a>
<h1 id="header1" class="header-class">My First Heading</h1>
<p id="para1" class="para-class">My first paragraph.</p>
</body>
</html>';
$dom = new DOMDocument();
$dom->loadHtml($html);
$dom->saveHTML();
var_dump(getAttrData('class', $dom));
biker dot mike at gmx dot com 22-Aug-2016 01:36
Look out for the following gotcha when loading XML from a string:

<?php
$doc = new \DOMDocument;
$doc->documentURI = $myXmlFilename;
$doc->loadXML($myXmlString);
?>

documentURI is now set to the value of $myXmlFilename, right?

Wrong!

It's set to the current working directory.  If you want to manually set documentURI to something other than the CWD, do so AFTER the call to loadXML().

E.g.:
<?php
$doc = new \DOMDocument;
$doc->loadXML($myXmlString);
$doc->documentURI = $myXmlFilename;
?>

documentURI really is now set to the value of $myXmlFilename.
developer at nabtron dot com 17-Dec-2015 07:34
For those landing here and checking for encoding issue with utf-8 characteres, it's pretty easy to correct it, without adding any additional output tag to your html.

We'll be utilizing: mb_convert_encoding

Thanks to the user who shared: SmartDOMDocument in previous comments, I got the idea of solving it. However I truly wish that he shared the method instead of giving a link.

Anyway coming back to the solution, you can simply use:

<?php

            // checks if the content we're receiving isn't empty, to avoid the warning
            if ( empty( $content ) ) {
                return false;
            }

            // converts all special characters to utf-8
            $content = mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8');

            // creating new document
            $doc = new DOMDocument('1.0', 'utf-8');

            //turning off some errors
            libxml_use_internal_errors(true);

            // it loads the content without adding enclosing html/body tags and also the doctype declaration
            $doc->LoadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

            // do whatever you want to do with this code now

?>

I hope it solves the issue for someone! If you need my help or service to fix your code, you can reach me on nabtron.com or contact me at the email mentioned with this comment.
ingjetel at gmail dot com 13-May-2015 11:54
Easy function for basic output of XML file via DOM parsing

<?php
$dom = new DomDocument();
$dom->load("./file.xml") or die("error");
$start = $dom->documentElement;
fc($start);

function fc($node) {
  $child = $node->childNodes;
  foreach($child as $item) {
    if ($item->nodeType == XML_TEXT_NODE) {
      if (strlen(trim($item->nodeValue))) echo trim($item->nodeValue)."<br/>";
    }
    else if ($item->nodeType == XML_ELEMENT_NODE) fc($item);
  }
}
?>
qrworld.net 11-Nov-2014 04:35
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
danny dot nunez15 at gmail dot com 28-Oct-2013 02:54
A simple function to grab all links in a page.

    function get_links($url) {

        // Create a new DOM Document to hold our webpage structure
        $xml = new DOMDocument();

        // Load the url's contents into the DOM

        $xml->loadHTMLFile($url);

        // Empty array to hold all links to return
        $links = array();

        //Loop through each <a> tag in the dom and add it to the link array
        foreach ($xml->getElementsByTagName('a') as $link) {
            $url = $link->getAttribute('href');
            if (!empty($url)) {
                $links[] = $link->getAttribute('href');
            }
        }

        //Return the links
        return $links;
    }
sites.sitesbr.net 22-Jan-2013 12:37
How to objetify a DomDocument with hierarchy like:
<root>
    <item>
          <prop1>info1</prop1>
          <prop2>info2</prop2>
          <prop3>info3</prop3>
     </item>
    <item>
          <prop1>info1</prop1>
          <prop2>info2</prop2>
          <prop3>info3</prop3>
     </item>
</root>

It's possible to use in object style to retrieve information, as:

<?php
     $theNodeValue = $aitem->prop1;
?>

Here is the code: one Class and 2 functions.

<?php
 class ArrayNode{
       public $nodeName, $nodeValue;
 }

 function getChildNodeElements( $domNode ){
     $nodes = array();
     for( $i=0; $i < $domNode->childNodes->length; $i++){
       $cn = $domNode->childNodes->item($i);
       if( $cn->nodeType == 1){
           $nodes[] = $cn;
           }
     }
    return $nodes;
 }

 function getArrayNodes( $domDoc ){
     $res = array();

       for( $i=0; $i < $domDoc->childNodes->length; $i++){
       $cn = $domDoc->childNodes->item($i);
       # The first is the root tag...
          if( $cn->nodeType == 1){
               # But we want it's childNodes.
                $sub_cn = getChildNodeElements( $cn);
                # Found the tagName:
                $baseItemTagName = $sub_cn[0]->nodeName;
                break;
            }
        }

       $dnl = $domDoc->getElementsByTagName( $baseItemTagName);

       for( $i=0; $i< $dnl->length; $i++){
          $arrayNode = new ArrayNode();

      # Summary
      $arrayNode->nodeName = $dnl->item($i)->nodeName;
      $arrayNode->nodeValue = $dnl->item($i)->nodeValue;

      # Child Nodes
      $cn = $dnl->item($i)->childNodes;
      for( $k=0; $k<$cn->length; $k++){
           if( $cn->item($k)->nodeName == "#text" && trim($cn->item($k)->nodeValue) == "") continue;
           $arrayNode->{$cn->item($k)->nodeName} = $cn->item($k)->nodeValue;
      }

      # Attributes
      $attr = $dnl->item($i)->attributes;
      for( $k=0; $k < $attr->length; $k++){
           if(! is_null($attr)){
            if( $attr->item($k)->nodeName == "#text" && trim($attr->item($k)->nodeValue) == "") continue;
            $arrayNode->{$attr->item($k)->nodeName} = $attr->item($k)->nodeValue;
           }
      }

      $res[] = $arrayNode;

       }

     return $res;
 }
?>

To use it:

<?php

  # First you load a XML in a DomDocument variable.

   $url = "/path/to/yourxmlfile.xml";
   $domSrc = file_get_contents($url);
   $dom = new DomDocument();
   $dom->loadXML( $domSrc );

  # Then, you get the ArrayNodes from the DomDocument.

    $ans = getArrayNodes( $dom );

    for( $i=0; $i < count( $ans ) ; $i++){

    $cn =  $ans[ $i];

    $info1 =  $cn->prop1;
    $info2 =  $cn->prop2;
    $info3 =  $cn->prop3;

         // ...

   }

?>
Nick M 01-Jun-2011 10:16
You may need to save all or part of a DOMDocument as an XHTML-friendly string, something compliant with both XML and HTML 4. Here's the DOMDocument class extended with a saveXHTML method:

<?php

/**
 * XHTML Document
 *
 * Represents an entire XHTML DOM document; serves as the root of the document tree.
 */
class XHTMLDocument extends DOMDocument {

  /**
   * These tags must always self-terminate. Anything else must never self-terminate.
   *
   * @var array
   */
  public $selfTerminate = array(
      'area','base','basefont','br','col','frame','hr','img','input','link','meta','param'
  );

  /**
   * saveXHTML
   *
   * Dumps the internal XML tree back into an XHTML-friendly string.
   *
   * @param DOMNode $node
   *         Use this parameter to output only a specific node rather than the entire document.
   */
  public function saveXHTML(DOMNode $node=null) {

    if (!$node) $node = $this->firstChild;

    $doc = new DOMDocument('1.0');
    $clone = $doc->importNode($node->cloneNode(false), true);
    $term = in_array(strtolower($clone->nodeName), $this->selfTerminate);
    $inner='';

    if (!$term) {
      $clone->appendChild(new DOMText(''));
      if ($node->childNodes) foreach ($node->childNodes as $child) {
        $inner .= $this->saveXHTML($child);
      }
    }

    $doc->appendChild($clone);
    $out = $doc->saveXML($clone);

    return $term ? substr($out, 0, -2) . ' />' : str_replace('><', ">$inner<", $out);

  }

}

?>

This hasn't been benchmarked, but is probably significantly slower than saveXML or saveHTML and should be used sparingly.
evert at er dot nl 20-Nov-2010 02:17
A nice and simple node 2 array I wrote, worth a try ;)

<?php
function getArray($node)
{
    $array = false;

    if ($node->hasAttributes())
    {
        foreach ($node->attributes as $attr)
        {
            $array[$attr->nodeName] = $attr->nodeValue;
        }
    }

    if ($node->hasChildNodes())
    {
        if ($node->childNodes->length == 1)
        {
            $array[$node->firstChild->nodeName] = $node->firstChild->nodeValue;
        }
        else
        {
            foreach ($node->childNodes as $childNode)
            {
                if ($childNode->nodeType != XML_TEXT_NODE)
                {
                    $array[$childNode->nodeName][] = $this->getArray($childNode);
                }
            }
        }
    }

    return $array;
}
?>
admin at beerpla dot net 12-Mar-2010 02:12
After seeing many complaints about certain DOMDocument shortcomings, such as bad handling of encodings and always saving HTML fragments with <html>, <head>, and DOCTYPE, I decided that a better solution is needed.

So here it is: SmartDOMDocument. You can find it at http://beerpla.net/projects/smartdomdocument/

Currently, the main highlights are:

- SmartDOMDocument inherits from DOMDocument, so it's very easy to use - just declare an object of type SmartDOMDocument instead of DOMDocument and enjoy the new behavior on top of all existing functionality (see example below).

- saveHTMLExact() - DOMDocument has an extremely badly designed "feature" where if the HTML code you are loading does not contain <html> and <body> tags, it adds them automatically (yup, there are no flags to turn this behavior off).
Thus, when you call $doc->saveHTML(), your newly saved content now has <html><body> and DOCTYPE in it. Not very handy when trying to work with code fragments (XML has a similar problem).
SmartDOMDocument contains a new function called saveHTMLExact() which does exactly what you would want - it saves HTML without adding that extra garbage that DOMDocument does.

- encoding fix - DOMDocument notoriously doesn't handle encoding (at least UTF-8) correctly and garbles the output.
SmartDOMDocument tries to work around this problem by enhancing loadHTML() to deal with encoding correctly. This behavior is transparent to you - just use loadHTML() as you would normally.

- SmartDOMDocument Object As String - you can use a SmartDOMDocument object as a string which will print out its contents.
For example:
<?php
echo "Here is the HTML: $smart_dom_doc";
?>

I'm going to maintain this code and try to fix bugs as they come in.

Enjoy.
tloach at gmail dot com 05-Feb-2010 10:01
For anyone else who has been having issues with formatOuput not working, here is a work-around:

rather than just doing something like:

<?php
$outXML = $xml->saveXML();
?>

force it to reload the XML from scratch, then it will format correctly:

<?php
$outXML = $xml->saveXML();
$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML($outXML);
$outXML = $xml->saveXML();
?>
jay at jaygilford dot com 27-Jan-2010 08:46
Here's a small function I wrote to get all page links using the DOMDocument which will hopefully be of use to others

<?php
/**
 * @author Jay Gilford
 */

/**
 * get_links()
 *
 * @param string $url
 * @return array
 */
function get_links($url) {

    // Create a new DOM Document to hold our webpage structure
    $xml = new DOMDocument();

    // Load the url's contents into the DOM
    $xml->loadHTMLFile($url);

    // Empty array to hold all links to return
    $links = array();

    //Loop through each <a> tag in the dom and add it to the link array
    foreach($xml->getElementsByTagName('a') as $link) {
        $links[] = array('url' => $link->getAttribute('href'), 'text' => $link->nodeValue);
    }

    //Return the links
    return $links;
}
?>
fcartegnie 31-Oct-2009 01:30
Be careful with formatOutput().

Creating an empty node like this:
createElement('foo','')
instead of
createElement('foo')
will break formatOutput.
PhilipWayneRollins at gmail dot com 15-Aug-2009 01:32
If you want to use the DOMDocument to create xHTML documents here is a simple class

Note this is designed for creating xHTML documents from scratch but could be easily extended to work with xHTML documents. Also this is for xHTML not XML.

<?php
    class Document
    {
        public $doctype;
        public $head;
        public $title = 'Sensei Ninja';
        public $body;
        private $styles;
        private $metas;
        private $scripts;
        private $document;

        function __construct (  )
        {
            $this->document = new DOMDocument( );
            $this->head = $this->document->createElement( 'head', ' ' );
            $this->body = $this->document->createElement( 'body', ' ' );
        }

        public function addStyleSheet ( $url, $media='all' )
        {
            $element = $this->document->createElement( 'link' );
            $element->setAttribute( 'type', 'text/css' );
            $element->setAttribute( 'href', $url );
            $element->setAttribute( 'media', $media );
            $this->styles[] = $element;
        }

        public function addScript ( $url )
        {
            $element = $this->document->createElement( 'script', ' ' );
            $element->setAttribute( 'type', 'text/javascript' );
            $element->setAttribute( 'src', $url );
            $this->scripts[] = $element;
        }

        public function addMetaTag ( $name, $content )
        {
            $element = $this->document->createElement( 'meta' );
            $element->setAttribute( 'name', $name );
            $element->setAttribute( 'content', $content );
            $this->metas[] = $element;
        }

        public function setDescription ( $dec )
        {
            $this->addMetaTag( 'description', $dec );
        }

        public function setKeywords ( $keywords )
        {
            $this->addMetaTag( 'keywords', $keywords );
        }

        public function createElement ( $nodeName, $nodeValue=null )
        {
          return $this->document->createElement( $nodeName, $nodeValue );
        }

        public function assemble ( )
        {
            // Doctype creation
            $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML TRANSITIONAL 1.0//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';

            // Create the head element
            $title = $this->document->createElement( 'title', $this->title );
            // Add stylesheets if needed
            if ( is_array( $this->styles ))
                foreach ( $this->styles as $element )
                    $this->head->appendChild( $element );
            // Add scripts if needed
            if(  is_array( $this->scripts ))
                foreach ( $this->scripts as $element )
                    $this->head->appendChild( $element );
            // Add meta tags if needed
            if ( is_array( $this->metas ))
                foreach ( $this->metas as $element )
                    $this->head->appendChild( $element );
            $this->head->appendChild( $title );

            // Create the document
            $html = $this->document->createElement( 'html' );
            $html->setAttribute( 'xmlns', 'http://www.w3.org/1999/xhtml' );
            $html->setAttribute( 'xml:lang', 'en' );
            $html->setAttribute( 'lang', 'en' );
            $html->appendChild( $this->head );
            $html->appendChild( $this->body );

            $this->document->appendChild( $html );
            return $doctype . $this->document->saveXML( );
        }

    }

?>

Small example

<?php
        $document = new Document( );
    $document->title = 'Hello';
    $document->addStyleSheet( 'StyleSheets/main.css' );
    $div = $document->createElement( 'div' );
    $div->nodeValue = 'Hello, world!';
    $div->setAttribute( 'style', 'color: red;' );
    $document->body->appendChild( $div );
    printf( '%s', $document->assemble( ) );
?>
cmyk777 at gmail dot com 23-May-2009 12:31
This function may help to debug current dom element:

<?php
function dom_dump($obj) {
    if ($classname = get_class($obj)) {
        $retval = "Instance of $classname, node list: \n";
        switch (true) {
            case ($obj instanceof DOMDocument):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->saveXML($obj);
                break;
            case ($obj instanceof DOMElement):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->ownerDocument->saveXML($obj);
                break;
            case ($obj instanceof DOMAttr):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->ownerDocument->saveXML($obj);
                //$retval .= $obj->ownerDocument->saveXML($obj);
                break;
            case ($obj instanceof DOMNodeList):
                for ($i = 0; $i < $obj->length; $i++) {
                    $retval .= "Item #$i, XPath: {$obj->item($i)->getNodePath()}\n".
"{$obj->item($i)->ownerDocument->saveXML($obj->item($i))}\n";
                }
                break;
            default:
                return "Instance of unknown class";
        }
    } else {
        return 'no elements...';
    }
    return htmlspecialchars($retval);
}
?>

Example usage:

<?php
$dom = new DomDocument();
$dom->load('test.xml');
$body = $dom->documentElement->getElementsByTagName('book');
echo '<pre>'.dom_dump($body).'<pre>';
?>

Output:

Instance of DOMNodeList, node list:
Item #0, XPath: /library/book[1]
<book isbn="0345342968">
<title>Fahrenheit 451</title>
<author>R. Bradbury</author>
<publisher>Del Rey</publisher>
</book>
Item #1, XPath: /library/book[2]
<book isbn="0048231398">
<title>The Silmarillion</title>
<author>J.R.R. Tolkien</author>
<publisher>G. Allen &amp; Unwin</publisher>
</book>
Item #2, XPath: /library/book[3]
<book isbn="0451524934">
<title>1984</title>
<author>G. Orwell</author>
<publisher>Signet</publisher>
</book>
Item #3, XPath: /library/book[4]
<book isbn="031219126X">
<title>Frankenstein</title>
<author>M. Shelley</author>
<publisher>Bedford</publisher>
</book>
Item #4, XPath: /library/book[5]
<book isbn="0312863551">
<title>The Moon Is a Harsh Mistress</title>
<author>R. A. Heinlein</author>
<publisher>Orb</publisher>
</book>
Fernando H 11-Apr-2008 12:48
Showing a quick example of how to use this class, just so that new users can get a quick start without having to figure it all out by themself. ( At the day of posting, this documentation just got added and is lacking examples. )

<?php

// Set the content type to be XML, so that the browser will   recognise it as XML.
header( "content-type: application/xml; charset=ISO-8859-15" );

// "Create" the document.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );

// Create some elements.
$xml_album = $xml->createElement( "Album" );
$xml_track = $xml->createElement( "Track", "The ninth symphony" );

// Set the attributes.
$xml_track->setAttribute( "length", "0:01:15" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );

// Create another element, just to show you can add any (realistic to computer) number of sublevels.
$xml_note = $xml->createElement( "Note", "The last symphony composed by Ludwig van Beethoven." );

// Append the whole bunch.
$xml_track->appendChild( $xml_note );
$xml_album->appendChild( $xml_track );

// Repeat the above with some different values..
$xml_track = $xml->createElement( "Track", "Highway Blues" );

$xml_track->setAttribute( "length", "0:01:33" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );
$xml_album->appendChild( $xml_track );

$xml->appendChild( $xml_album );

// Parse the XML.
print $xml->saveXML();

?>

Output:
<Album>
  <Track length="0:01:15" bitrate="64kb/s" channels="2">
    The ninth symphony
    <Note>
      The last symphony composed by Ludwig van Beethoven.
    </Note>
  </Track>
  <Track length="0:01:33" bitrate="64kb/s" channels="2">Highway Blues</Track>
</Album>

If you want your PHP->DOM code to run under the .xml extension, you should set your webserver up to run the .xml extension with PHP ( Refer to the installation/configuration configuration for PHP on how to do this ).

Note that this:
<?php
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = $xml->createElement( "Album" );
$xml_track = $xml->createElement( "Track" );
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
?>

is NOT the same as this:
<?php
// Will NOT work.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = new DOMElement( "Album" );
$xml_track = new DOMElement( "Track" );
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
?>

although this will work:
<?php
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = new DOMElement( "Album" );
$xml->appendChild( $xml_album );
?>


Transfer a node from another document

  • « DOMDocument
  • DOMDocument::append »
  • PHP Manual
  • DOMDocument
  • Transfer a node from another document

DOMDocument::adoptNode

(PHP >= 8.3)

DOMDocument::adoptNode — Transfer a node from another document

Descripción

public DOMDocument::adoptNode(DOMNode $node): DOMNode|false

Transfer a node from another document into the current document.

Parámetros

node

The node to transfer.

Valores devueltos

The node that was transfered, or false on error.

Errores/Excepciones

DOM_NOT_SUPPORTED_ERR

Raised if the node type is not supported for document transfers.

Ejemplos

Ejemplo #1 DOMDocument::adoptNode() example

Transfers the hello element from the first document to the second one.

<?php
$doc1 = new DOMDocument;
$doc1->loadXML("<container><hello><world/></hello></container>");
$hello = $doc1->documentElement->firstChild;

$doc2 = new DOMDocument;
$doc2->loadXML("<root/>");
$doc2->documentElement->appendChild($doc2->adoptNode($hello));

echo $doc1->saveXML() . PHP_EOL;
echo $doc2->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<container/>

<?xml version="1.0"?>
<root><hello><world/></hello></root>

Ver también

  • DOMDocument::importNode() - Importa un nodo dentro del documento actual

User Contributed Notes

There are no user contributed notes for this page.


Appends nodes after the last child node

  • « DOMDocument::adoptNode
  • DOMDocument::__construct »
  • PHP Manual
  • DOMDocument
  • Appends nodes after the last child node

DOMDocument::append

(PHP 8)

DOMDocument::append — Appends nodes after the last child node

Descripción

public DOMDocument::append(DOMNode|string ...$nodes): void

Appends one or many nodes to the list of children after the last child node.

Ejemplos

Ejemplo #1 DOMDocument::append() example

Adds nodes after the document root.

<?php
$doc = new DOMDocument;
$doc->loadXML("<hello/>");

$doc->append("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<hello/>
beautiful
<world/>

Ver también

  • DOMParentNode::append()
  • DOMDocument::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo objeto DOMDocument

  • « DOMDocument::append
  • DOMDocument::createAttribute »
  • PHP Manual
  • DOMDocument
  • Crea un nuevo objeto DOMDocument

DOMDocument::__construct

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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

info at ensostudio dot ru 14-Dec-2021 07:37
You can use fragments to set inner HTML:
<?php
$dom = new DOMImplementation();
$document = $dom->createDocument(null, 'html', $dom->createDocumentType('html'));

$div = $document->appendChild($document->createElement('div', '<small>test</small> me'));
echo $document->saveHTML($div);
// <div>&lt;small&gt;test&lt;/small&gt; me</div>

$div = $document->appendChild($document->createElement('div'));
$div->nodeValue = '<small>test</small> me';
echo $document->saveHTML($div);
// <div>&lt;small&gt;test&lt;/small&gt; me</div>

$div = $document->appendChild($document->createElement('div'));
$divInner = $document->createDocumentFragment();
$divInner->appendXML('<small>test</small> me');
$div->appendChild($divInner);
echo $document->saveHTML($div);
// <div><small>test</small> me</div>

?>


Crea un nuevo nodo elemento

  • « DOMDocument::createDocumentFragment
  • DOMDocument::createElementNS »
  • PHP Manual
  • DOMDocument
  • Crea un nuevo nodo elemento

DOMDocument::createElement

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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

Raf-sns 11-Nov-2023 06:19
Be carreful with the option "preserveWhiteSpace"

$dom = new DOMDocument;
// false -> this preserve white spaces
// true -> this will put all entries inline
$dom->preserveWhiteSpace = false;  // preserve white space !
sainthyoga2003 at gmail dot com 09-Feb-2012 03:37
in the default example:

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

you must enter the absolute path for book.xml due for get a false result in load function.
sainthyoga2003 at gmail dot com 25-Feb-2011 05:38
i've found the partial solution for xml:id warning,is explained at this address: https://fosswiki.liip.ch/display/BLOG/GetElementById+Pitfalls

there explains that:
The ID does have to be a valid NCName, which for example means, that the first letter can't be a number.

and in my xml:id i had a number. :D
sainthyoga2003 at gmail dot com 16-Feb-2011 09:31
adding an id for a child, when i use abstract mode i get the following warning:

[quote]Warning: DOMDocument::load() [domdocument.load]: xml:id : attribute value xx is not an NCName in /fake/path/to/xmlfile[/quote]
_ michael 01-Jun-2010 08:34
load() will handle non-ASCII characters depending on the details of the XML declaration, but in a somewhat surprising way. One would assume that the declarations '<?xml version="1.0" encoding="UTF-8"?>' and '<?xml version="1.0"?>' are treated in the same way because UTF-8 is the default encoding anyway. But not so.

* If there is an XML declaration defining the encoding *explicitly*, the non-ASCII characters remain unchanged.
* If the XML declaration does not define the encoding explicitly, or if the XML declaration is missing, non-ASCII characters are converted into numeric entities.

So the document

    <?xml version="1.0"?>
    <root><nonascii>ä</nonascii></root>

will be converted to

    <?xml version="1.0"?>
    <root><nonascii>&#xE4;</nonascii></root>

The same happens if there is no XML declaration at all. On the other hand, the document

    <?xml version="1.0" encoding="UTF-8"?>
    <root><nonascii>ä</nonascii></root>

will remain as it is.

This behaviour applies to loadXML() as well.
_ michael 19-Apr-2010 07:50
XHTML and entities: The solution proposed below by zachatwork at gmail dot com didn't work for me. I checked on a number of servers (both LAMPP and WAMPP) - on each of them, calling loadXML() with the LIBXML_DTDLOAD option triggered an external request for the DTD. And that's bad news.

If allow_url_fopen is turned off, the request for the DTD fails with a warning. If it is turned on, the request fails because these w3c URLs return a 503 Service Unavailable.

HTML entities still generate a warning in either case.

The best solution, as far as I can tell, is simply to ignore the warnings and suppress them using '@'. I can't recommend parsing XHTML with loadHTML() instead of loadXML() - yes, you get rid of the entity problem, but loadHTML() changes the source while parsing it (tries to 'fix' it even though there is nothing to fix).
zachatwork at gmail dot com 30-Jun-2009 11:28
You can easily avoid the warning about &nbsp; references by using the LIBXML_DTDLOAD option.

<?php

$html = <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  </head>
  <body>
    <p>&nbsp;</p>
  </body>
</html>
EOF;

// This one works perfectly.
$dom = new DOMDocument();
$dom->loadXML($html, LIBXML_DTDLOAD);
print $dom->saveXML();

// This one produces a warning.
$dom = new DOMDocument();
$dom->loadXML($html);
print $dom->saveXML();

?>

See also: http://www.php.net/manual/en/libxml.constants.php

Note that libxml will detect that your DTD is locally available via /etc/xml/catalog. So there is no worry about this causing your DOM loads to make external network requests.
Jonas Due Vesterheden 09-Jun-2009 08:18
I had a problem with loading documents over HTTP. I would get errors looking like this:

Warning: DOMDocument::load(http://external/document.xml): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error

The document would load fine in browsers and using wget. The problem is that DOMDocument::load() on my systems (both OS X and Linux) didn't send any User-Agent header which for some weird reason made Microsoft-IIS/6.0 respond with the 500 error.

The solution is found on http://php.net/manual/en/function.libxml-set-streams-context.php :

<?php
$opts = array(
    'http' => array(
        'user_agent' => 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');
?>
syntaxiko 04-Apr-2009 10:16
Function will not work if using XML DOM PECL module
darren at viamedia dot co dot za 05-Aug-2008 07:17
If you are loading xml with the intention of validating it against an internal dtd and you have experienced issues with the validation it could be related to missing LIBXML constants.

I found this post by "aidan at php dot net" in root level dom docs and thought it might be more useful here:
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:
<?php
$dom = new DOMDocument;
// Resolve externals
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);
// OR
// Validate against DTD
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
$dom->validate();
?>
the_N_Channel 15-Jul-2008 04:53
NOTE, will not load successfully if there is a comment at the beginning of the file before the <?xml version="1.0" ?> declaration!
hh dot lohmann at yahoo dot de 30-Aug-2007 03:48
BadGuy´s note may be confusing since what he depicts is no special property of the relevant method. PHP works always in and on a local file system which means that if you want to use resources from other systems or - what is, indeed, BadGuy´s problem - need resources that have been dealt with by other programs or processes, you have to state and manage that explicitly in your code. PHP is just a quite normal program in that.

BadGuy´s solution is using the "http wrapper" to get output from another process (see "wrappers" in the PHP manual). Doing this, the appropriate syntax for http calls has to be respected.
admin at tijnema dot tijnema dot info 02-Jun-2007 04:39
In reply to BadGuy [at] BadGuy [dot] nl

When the news.php file is located on the same server, like you said in the first example then http://my.beautiful-website.com/xmlsource/news.php wouldn't work, but you should use http://localhost/xmlsource/news.php or http://127.0.0.1/xmlsource/news.php
BadGuy [at] BadGuy [dot] nl 18-Jan-2007 08:50
Note that this method uses the local file system before doing anything remote. The 'disadvantage' would be that if you would do the following:
<?php
$xml = new DOMDocument;
$xml->load("xmlsource/news.php");
?>

This would not make the method read the actual output of the news.php file --presumably valid xml data--, but the file contents --obviously this would be php code. So this will return an error saying news.php is missing the xml declaration and maybe the xml start-tag

What would work is the following:

<?php
$xml = new DOMDocument;
$xml->load("http://my.beautiful-website.com/xmlsource/news.php");
?>

This will force a http request to be used to get this file instead of just locally reading it and the file just returning code
daevid at daevid dot com 18-Oct-2005 05:08
Suppose you wanted to dynamically load an array from an .XSD file. This method is your guy. just remember to use the actual xs: portion in xpaths and such.

All the other "load" methods will error out.

<?php
$attributes = array();
$xsdstring = "/htdocs/api/xsd/common.xsd";
$XSDDOC = new DOMDocument();
$XSDDOC->preserveWhiteSpace = false;
if ($XSDDOC->load($xsdstring))
{
    $xsdpath = new DOMXPath($XSDDOC);
    $attributeNodes =
              $xsdpath->
              query('//xs:simpleType[@name="attributeType"]')
              ->item(0);
    foreach ($attributeNodes->childNodes as $attr)
    {
        $attributes[ $attr->getAttribute('value') ] = $attr->getAttribute('name');
    }
    unset($xsdpath);
}
print_r($attributes);
?>


Cargar HTML de una cadena

  • « DOMDocument::load
  • DOMDocument::loadHTMLFile »
  • PHP Manual
  • DOMDocument
  • Cargar HTML de una cadena

DOMDocument::loadHTML

(PHP 5, PHP 7, PHP 8)

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

Anonymous 19-May-2022 04:05
loadHTML() & loadHTMLFile() may always generate warnings if the html include some tags such as "nav, section, footer, etc" adopted as of HTML5 (in PHP 8.1.6).

Try to run below.

<?php

$file_name = 'PHP Runtime Configuration - Manual.html'; // Download this file from "https://www.php.net/manual/en/session.configuration.php" in advance.

$doc = new DOMDocument();
$doc->loadHTMLFile($file_name); // if set "LIBXML_NOERROR" as 2nd arg, no error
echo $doc->saveHTML();

// Warning: DOMDocument::loadHTMLFile(): Tag nav invalid in PHP Runtime Configuration - Manual.html, line: 63 in D:\xampp\htdocs\test\xml(dom)\loadHTML\index.php on line 6

?>
obayed dot opu at gmail dot com 10-Dec-2021 09:58
To support HTML5 you have to disable xml error handling by add `LIBXML_NOERROR` as an option of loadHTML method.

Example:

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br><section>I'M UNSUPPORTED</section></body></html>", LIBXML_NOERROR);
echo $doc->saveHTML();
?>
deepakrajpal dot com at gmail dot com 20-Nov-2020 06:16
If we are loading html5 tags such as <section>, <svg> there is following error:

DOMDocument::loadHTML(): Tag section invalid in Entity

We can disable standard libxml errors (and enable user error handling) using libxml_use_internal_errors(true); before loadHTML();

This is quite useful in phpunit custom assertions as given in following example (if using phpunit test cases):

// Create a DOMDocument
$dom = new DOMDocument();

// fix html5/svg errors
libxml_use_internal_errors(true);

// Load html
$dom->loadHTML("<section></section>");
$htmlNodes = $dom->getElementsByTagName('section');

if ($htmlNodes->length == 0) {
    $this->assertFalse(TRUE);
} else {
    $this->assertTrue(TRUE);
}
divinity76+spam at gmail dot com 14-Sep-2020 09:25
if you want to get rid of all the "DOMText elements containing ONLY whitespace", maybe try

<?php

function loadHTML_noemptywhitespace(string $html, int $extra_flags = 0, int $exclude_flags = 0): DOMDocument
{
    $flags = LIBXML_HTML_NODEFDTD | LIBXML_NOBLANKS | LIBXML_NONET;
    $flags = ($flags | $extra_flags) & ~ $exclude_flags;

    $domd = new DOMDocument();
    $domd->preserveWhiteSpace = false;
    @$domd->loadHTML('<?xml encoding="UTF-8">' . $html, $flags);
    $removeAnnoyingWhitespaceTextNodes = function (\DOMNode $node) use (&$removeAnnoyingWhitespaceTextNodes): void {
        if ($node->hasChildNodes()) {
            // Warning: it's important to do it backwards; if you do it forwards, the index for DOMNodeList might become invalidated;
            // that's why i don't use foreach() - don't change it (unless you know what you're doing, ofc)
            for ($i = $node->childNodes->length - 1; $i >= 0; --$i) {
                $removeAnnoyingWhitespaceTextNodes($node->childNodes->item($i));
            }
        }
        if ($node->nodeType === XML_TEXT_NODE && !$node->hasChildNodes() && !$node->hasAttributes() && empty(trim($node->textContent))) {
            //echo "Removing annoying POS";
            // var_dump($node);
            $node->parentNode->removeChild($node);
        } //elseif ($node instanceof DOMText) { echo "not removed"; var_dump($node, $node->hasChildNodes(), $node->hasAttributes(), trim($node->textContent)); }
    };
    $removeAnnoyingWhitespaceTextNodes($domd);
    return $domd;
}
BychkovVV at mail dot ru 03-Apr-2020 08:30
If you are loading html content from any website, in "utf-8" encoding, when meta width content-type is not first child of HEAD, it would not be acknowledged by parser (encoding); So you can make this fix:
  function domLoadHTML($html)
           {$testDOM = new DOMDocument('1.0', 'UTF-8');
            $testDOM->loadHTML($html);
            $charset = NULL;
            $searchInElemnt = function(&$item) use (&$searchInElemnt, &$charset)
              {if($item->childNodes)
                 {foreach($item->childNodes as $childItem)
                    {switch($childItem->nodeName)
                       {case 'html':
                        case 'head':
                          $searchInElemnt($childItem);
                          break;
                        case 'meta':
                          $attributes = array();
                          foreach ($childItem->attributes as $attr)
                            {$attributes[mb_strtoupper($attr->localName)] = $attr->nodeValue;
                            }
                          if(array_key_exists('HTTP-EQUIV', $attributes) && (mb_strtoupper($attributes['HTTP-EQUIV']) == 'CONTENT-TYPE') && array_key_exists('CONTENT', $attributes) && preg_match('~[\s]*;[\s]*charset[\s]*=[\s]*([^\s]+)~', $attributes['CONTENT'], $matches))
                            {$charset = preg_replace('~[\s\']~', '', $matches[1]);
                            }
                       }
                    }
                 }
              };
            $searchInElemnt($testDOM);
            if(isset($charset))
              {$dom = new DOMDocument('1.0', $charset);
               $dom->loadHTML('<?xml encoding="'.$charset.'">'.$html);
               foreach ($dom->childNodes as $item)
               if($item->nodeType == XML_PI_NODE)
                 {$dom->removeChild($item);
                 }
               $dom->encoding = $charset;
              }
            else
              {$dom = $testDOM;
              }
            return $dom;
           };
kerim-yagmurcu at gmx dot de 24-Dec-2016 03:13
For those of you who want to get an external URL's class element, I have 2 usefull functions. In this example we get the '<h3 class="r">'
 elements back (search result headers) from google search:

1. Check the URL (if it is reachable, existing)
<?php
# URL Check
function url_check($url) {
    $headers = @get_headers($url);
    return is_array($headers) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$headers[0]) : false;
};
?>

2. Clean the element you want to get (remove all tags, tabs, new-lines etc.)
<?php
# Function to clean a string
function clean($text){
    $clean = html_entity_decode(trim(str_replace(';','-',preg_replace('/\s+/S', " ", strip_tags($text)))));// remove everything
    return $clean;
    echo '\n';// throw a new line
}
?>

After doing that, we can output the search result headers with following method:
<?php
$searchstring = 'djceejay';
$url = 'http://www.google.de/webhp#q='.$searchstring;
if(url_check($url)){
    $doc = new DomDocument;
    $doc->validateOnParse = true;
    $doc->loadHtml(file_get_contents($url));
    $output = clean($doc->getElementByClass('r')->textContent);
    echo $output . '<br>';
}else{
    echo 'URL not reachable!';// Throw message when URL not be called
}
?>
fr at felix-riesterer dot de 13-Feb-2016 01:43
Remember: If you use an HTML5 doctype and a meta element like so

<meta CHARSET=Windows-1252">

your HTML code will get interpreted as ISO-8859-something and non-ASCII chars will get converted into HTML entities. However the HTML4-like version will work (as has been pointed out 10 years ago by "bigtree at 29a"):

<meta http-equiv="Content-Type" content="text/html; CHARSET=Windows-1252">
finkenb2 at mail dot lib dot msu dot edu 05-Oct-2015 04:03
Warning:  This does not function well with HTML5 elements such as SVG.  Most of the advice on the Web is to turn off errors in order to have it work with HTML5.
cake at brothercake dot com 16-Dec-2012 05:57
Be aware that this function doesn't actually understand HTML -- it fixes tag-soup input using the general rules of SGML, so it creates well-formed markup, but has no idea which element contexts are allowed.

For example, with input like this where the first element isn't closed:

    <span>hello <div>world</div>

loadHTML will change it to this, which is well-formed but invalid:

    <span>hello <div>world</div></span>
Alex 10-Apr-2010 08:45
Beware of the "gotcha" (works as designed but not as expected): if you use loadHTML, you cannot validate the document. Validation is only for XML. Details here: http://bugs.php.net/bug.php?id=43771&edit=1
Shane Harter 04-Jan-2010 08:42
DOMDocument is very good at dealing with imperfect markup, but it throws warnings all over the place when it does.

This isn't well documented here. The solution to this is to implement a separate aparatus for dealing with just these errors.

Set libxml_use_internal_errors(true) before calling loadHTML. This will prevent errors from bubbling up to your default error handler. And you can then get at them (if you desire) using other libxml error functions.

You can find more info here http://www.php.net/manual/en/ref.libxml.php
mdmitry at gmail dot com 21-Dec-2009 09:02
You can also load HTML as UTF-8 using this simple hack:

<?php

$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="UTF-8">' . $html);

// dirty fix
foreach ($doc->childNodes as $item)
    if ($item->nodeType == XML_PI_NODE)
        $doc->removeChild($item); // remove hack
$doc->encoding = 'UTF-8'; // insert proper

?>
piopier 14-Jun-2009 08:29
Here is a function I wrote to capitalize the previous remarks about charset problems (UTF-8...) when using loadHTML and then DOM functions.
It adds the charset meta tag just after <head> to improve automatic encoding detection, converts any specific character to an html entity, thus PHP DOM functions/attributes will return correct values.

<?php
mb_detect_order("ASCII,UTF-8,ISO-8859-1,windows-1252,iso-8859-15");
function loadNprepare($url,$encod='') {
        $content        = file_get_contents($url);
        if (!empty($content)) {
                if (empty($encod))
                        $encod  = mb_detect_encoding($content);
                $headpos        = mb_strpos($content,'<head>');
                if (FALSE=== $headpos)
                        $headpos= mb_strpos($content,'<HEAD>');
                if (FALSE!== $headpos) {
                        $headpos+=6;
                        $content = mb_substr($content,0,$headpos) . '<meta http-equiv="Content-Type" content="text/html; charset='.$encod.'">' .mb_substr($content,$headpos);
                }
                $content=mb_convert_encoding($content, 'HTML-ENTITIES', $encod);
        }
        $dom = new DomDocument;
        $res = $dom->loadHTML($content);
        if (!$res) return FALSE;
        return $dom;
}
?>

NB: it uses mb_strpos/mb_substr instead of mb_ereg_replace because that seemed more efficient with huge html pages.
Errol 11-Feb-2009 08:05
It should be noted that when any text is provided within the body tag
outside of a containing element, the DOMDocument will encapsulate that
text into a paragraph tag (<p>).

For example:
<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br><div>Text</div></body></html>");
echo $doc->saveHTML();
?>

will yield:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>Test<br></p>
<div>Text</div>
</body></html>

while:
<?php
$doc = new DOMDocument();
$doc->loadHTML(
    "<html><body><i>Test</i><br><div>Text</div></body></html>");
echo $doc->saveHTML();
?>

will yield:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<i>Test</i><br><div>Text</div>
</body></html>
jamesedwardcooke+php at gmail dot com 19-Oct-2008 11:37
Using loadHTML() automagically sets the doctype property of your DOMDocument instance(to the doctype in the html, or defaults to 4.0 Transitional). If you set the doctype with DOMImplementation it will be overridden.

I assumed it was possible to set it and then load html with the doctype I defined(in order to decide the doctype at runtime), and ran into a huge headache trying to find out where my doctype was going. Hopefully this helps someone else.
xuanbn at yahoo dot com 04-Oct-2007 01:38
If you use loadHTML() to process utf HTML string (eg in Vietnamese), you may experience result in garbage text, while some files were OK. Even your HTML already have meta charset  like

  <meta http-equiv="content-type" content="text/html; CHARSET=Windows-1252">

I have discovered that, to help loadHTML() process utf file correctly, the meta tag should come first, before any utf string appear. For example, this HTML file

<html>
 <head>
    <meta http-equiv="content-type" content="text/html; CHARSET=Windows-1252">
    <title> Vietnamese - Ti?ng Vi?t</title>
  </head>
<body></body>
</html>

will be OK with loadHTML() when <meta> tag appear <title> tag.

But the file below will not regcornize by loadHTML() because <title> tag contains utf string appear before <meta> tag.

<html>
 <head>
    <title> Vietnamese - Ti?ng Vi?t</title>
    <meta http-equiv="content-type" content="text/html; CHARSET=Windows-1252">
  </head>
<body></body>
</html>
hanhvansu at yahoo dot com 26-Apr-2007 08:50
When using loadHTML() to process UTF-8 pages, you may meet the problem that the output of dom functions are not like the input. For example, if you want to get "C?nh tranh", you will receive "Cáº¡nh tranh".  I suggest we use mb_convert_encoding before load UTF-8 page :
<?php
    $pageDom = new DomDocument();
    $searchPage = mb_convert_encoding($htmlUTF8Page, 'HTML-ENTITIES', "UTF-8");
    @$pageDom->loadHTML($searchPage);

?>
romain dot lalaut at laposte dot net 15-Feb-2007 08:31
Note that the elements of such document will have no namespace even with <html xmlns="http://www.w3.org/1999/xhtml">
bigtree at DONTSPAM dot 29a dot nl 26-Apr-2005 02:15
Pay attention when loading html that has a different charset than iso-8859-1. Since this method does not actively try to figure out what the html you are trying to load is encoded in (like most browsers do), you have to specify it in the html head. If, for instance, your html is in utf-8, make sure you have a meta tag in the html's head section:

<head>
<meta http-equiv="Content-Type" content="text/html; CHARSET=Windows-1252"/>
</head>

If you do not specify the charset like this, all high-ascii bytes will be html-encoded. It is not enough to set the dom document you are loading the html in to UTF-8.


Cargar HTML desde un fichero

  • « DOMDocument::loadHTML
  • DOMDocument::loadXML »
  • PHP Manual
  • DOMDocument
  • Cargar HTML desde un fichero

DOMDocument::loadHTMLFile

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

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::prepend »
  • PHP Manual
  • DOMDocument
  • Normaliza el documento

DOMDocument::normalizeDocument

(PHP 5, PHP 7, PHP 8)

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.


Prepends nodes before the first child node

  • « DOMDocument::normalizeDocument
  • DOMDocument::registerNodeClass »
  • PHP Manual
  • DOMDocument
  • Prepends nodes before the first child node

DOMDocument::prepend

(PHP 8)

DOMDocument::prepend — Prepends nodes before the first child node

Descripción

public DOMDocument::prepend(DOMNode|string ...$nodes): void

Prepends one or many nodes to the list of children before the first child node.

Ejemplos

Ejemplo #1 DOMDocument::prepend() example

Adds nodes before the document root.

<?php
$doc = new DOMDocument;
$doc->loadXML("<world/>");

$doc->prepend($doc->createElement("hello"), "beautiful");

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<hello/>
beautiful
<world/>

Ver también

  • DOMParentNode::prepend()
  • DOMDocument::append() - Appends nodes after the last child node

User Contributed Notes

There are no user contributed notes for this page.


Registra una clase extendida usada para crear tipos de nodos base

  • « DOMDocument::prepend
  • 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, PHP 8)

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, PHP 8)

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!


Realiza una validación relaxNG del documento

  • « DOMDocument::relaxNGValidate
  • DOMDocument::replaceChildren »
  • PHP Manual
  • DOMDocument
  • Realiza una validación relaxNG del documento

DOMDocument::relaxNGValidateSource

(PHP 5, PHP 7, PHP 8)

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.


Replace children in document

  • « DOMDocument::relaxNGValidateSource
  • DOMDocument::save »
  • PHP Manual
  • DOMDocument
  • Replace children in document

DOMDocument::replaceChildren

(PHP 8 >= 8.3.0)

DOMDocument::replaceChildren — Replace children in document

Descripción

public DOMDocument::replaceChildren(DOMNode|string ...$nodes): void

Replaces the children in the document with new nodes.

Ejemplos

Ejemplo #1 DOMDocument::replaceChildren() example

Replaces the children with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");

$doc->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
beautiful
<world/>

Ver también

  • DOMParentNode::replaceChildren()
  • DOMDocument::append() - Appends nodes after the last child node
  • DOMDocument::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Copia el árbol XML interno a un archivo

  • « DOMDocument::replaceChildren
  • DOMDocument::saveHTML »
  • PHP Manual
  • DOMDocument
  • Copia el árbol XML interno a un archivo

DOMDocument::save

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

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.
qrworld.net 11-Nov-2014 04:34
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
Anonymous 09-Feb-2010 07:52
If you want a simpler way to get around the <script> tag problem try:

<?php

  $script = $doc->createElement ('script');\
  // Creating an empty text node forces <script></script>
  $script->appendChild ($doc->createTextNode (''));
  $head->appendChild ($script);

?>
Anonymous 12-May-2009 07:35
To avoid script tags from being output as <script />, you can use the DOMDocumentFragment class:

<?php

$doc = new DOMDocument();
$doc -> loadXML($xmlstring);
$fragment = $doc->createDocumentFragment();
/* Append the script element to the fragment using raw XML strings (will be preserved in their raw form) and if succesful proceed to insert it in the DOM tree */
if($fragment->appendXML("<script type='text/javascript' src='$source'></script>") {
  $xpath = new DOMXpath($doc);
  $resultlist = $xpath->query("//*[local-name() = 'html']/*[local-name() = 'head']"); /* namespace-safe method to find all head elements which are childs of the html element, should only return 1 match */
  foreach($resultlist as $headnode)  // insert the script tag
     $headnode->appendChild($fragment);
}
$doc->saveXML(); /* and our script tags will still be <script></script> */

?>
Anonymous 25-Apr-2008 08:15
<?php
function getDOMString($retNode) {
  if (!$retNode) return null;
  $retval = strtr($retNode-->ownerDocument->saveXML($retNode),
  array(
    '></area>' => ' />',
    '></base>' => ' />',
    '></basefont>' => ' />',
    '></br>' => ' />',
    '></col>' => ' />',
    '></frame>' => ' />',
    '></hr>' => ' />',
    '></img>' => ' />',
    '></input>' => ' />',
    '></isindex>' => ' />',
    '></link>' => ' />',
    '></meta>' => ' />',
    '></param>' => ' />',
    'default:' => '',
    // sometimes, you have to decode entities too...
    '&quot;' => '&#34;',
    '&amp;' =>  '&#38;',
    '&apos;' => '&#39;',
    '&lt;' =>   '&#60;',
    '&gt;' =>   '&#62;',
    '&nbsp;' => '&#160;',
    '&copy;' => '&#169;',
    '&laquo;' => '&#171;',
    '&reg;' =>   '&#174;',
    '&raquo;' => '&#187;',
    '&trade;' => '&#8482;'
  ));
  return $retval;
}
?>
archanglmr at yahoo dot com 27-Nov-2007 03:28
If created your DOMDocument object using loadHTML() (where the source is from another site) and want to pass your changes back to the browser you should make sure the HTTP Content-Type header matches your meta content-type tags value because modern browsers seem to ignore the meta tag and trust just the HTTP header. For example if you're reading an ISO-8859-1 document and your web server is claiming UTF-8 you need to correct it using the header() function.

<?php
header('Content-Type: text/html; charset=iso-8859-1');
?>
xoplqox 20-Nov-2007 11:07
XHTML:

If the output is XHTML use the function saveXML().

Output example for saveHTML:

<select name="pet" size="3" multiple>
    <option selected>mouse</option>
    <option>bird</option>
    <option>cat</option>
</select>

XHTML conform output using saveXML:

<select name="pet" size="3" multiple="multiple">
    <option selected="selected">mouse</option>
    <option>bird</option>
    <option>cat</option>
</select>
tyson at clugg dot net 21-Apr-2005 05:44
<?php
// Using DOM to fix sloppy HTML.
// An example by Tyson Clugg <tyson@clugg.net>
//
// vim: syntax=php expandtab tabstop=2

function tidyHTML($buffer)
{
  // load our document into a DOM object
  $dom = @DOMDocument::loadHTML($buffer);
  // we want nice output
  $dom->formatOutput = true;
  return($dom->saveHTML());
}

// start output buffering, using our nice
// callback funtion to format the output.
ob_start("tidyHTML");

?>
<html>
<p>It's like comparing apples to oranges.
</html>
<?php

// this will be called implicitly, but we'll
// call it manually to illustrate the point.
ob_end_flush();

?>

The above code takes out sloppy HTML:
 <html>
 <p>It's like comparing apples to oranges.
 </html>

And cleans it up to the following:
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
 <html><body><p>It's like comparing apples to oranges.
 </p></body></html>


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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

Sinopsis de la Clase

class 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 append(DOMNode|string ...$nodes): void
public appendXML(string $data): bool
public prepend(DOMNode|string ...$nodes): void
public replaceChildren(DOMNode|string ...$nodes): 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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::append — Appends nodes after the last child node
  • DOMDocumentFragment::appendXML — Añade información XML sin formato
  • DOMDocumentFragment::__construct — Constructs a DOMDocumentFragment object
  • DOMDocumentFragment::prepend — Prepends nodes before the first child node
  • DOMDocumentFragment::replaceChildren — Replace children in fragment

User Contributed Notes

peter at softcoded dot com 03-May-2017 03:31
DOMDocumentFragment makes it easy to add (or replace)
nodes. Individually creating nodes using DOM methods can
be tedious. Instead, do something like this:

/**
* Create fragment of colgroup
* @param DOMDocument $doc The DOMDocument
* @return DOMDocumentFragment
*/
function makeFragment($d){
  $chunk = <<<HTML
  <colgroup>
    <col class="c1"/>
    <col class="c2"/>
    <col class="c3"/>
    <col class="c4"/>
  </colgroup>
HTML;
  $fragment = $d->createDocumentFragment();
  $fragment->appendXML($chunk);
  return $fragment;
}
Ricki 29-Mar-2011 06:00
DOMDocumentFragment only appears useful if created from a parent DOMDocument eg.

1. $dom = new DOMDocument("1.0","UTF-8");
2. $docFrag = $dom->createDocumentFragment();
3. Now append items to $docFrag
4. Graft $docFrag contents back onto $dom at the desired location

Conversely taking this approach:
1. $dom = new DOMDocument("1.0","UTF-8");
2. $docFrag = new DOMDocumentFragment();
3. Now append items to $docFrag

...will fail on step 3 with a "read only" error as $docFrag is not created as a child of  DOMDocument.

I'm not sure of the reason for this: on the web people have cited security, and others have cited poor design however whatever the reason, it is really limiting when wanting to encapsulating generic independent DocumentFragments into classes for easy grafting to the desired tree. The only workarounds i have seen look expensive from a performance perspective and cumbersome from a coding perspective ie. create a  dummy $dom for temporary use.

(This is valid as of PHP 5.3) I've put this here as i've wasted a lot of time finding it out - I hope this saves others some heartache.

Using new DOMDocumentFramt
matthijs at stdin dot nl 29-Mar-2011 03:06
Note that DOMDocumentFragment is a bit special when it's added to another node. When that happens, not the fragment itself is added as a child, but all of the children of the fragment are moved over to the new parent node.

For example, consider this script:

<?php

/* Create a document and a fragment containing a single node */
$doc = new DOMDocument();
$fragment = $doc->createDocumentFragment();
$fragment->appendChild($doc->createElement('foo'));

/* Now, the foo node is a child of the fragment */
var_dump($fragment->firstChild);

/* After appending the fragment to another node, the children of the
 * fragment will have been transfered to that node (and the fragment is
 * not present in the children list!) */
$doc->appendChild($fragment);
/* So the fragment has no children anymore */
var_dump($fragment->firstChild);
/* But $doc has a single child, which is the foo element, not the
 * fragment */
var_dump($doc->childNodes->length);
var_dump($doc->firstChild);

?>

This produces the following output:

object(DOMElement)#3 (0) {
}
NULL
int(1)
object(DOMElement)#3 (0) {
}


Appends nodes after the last child node

  • « DOMDocumentFragment
  • DOMDocumentFragment::appendXML »
  • PHP Manual
  • DOMDocumentFragment
  • Appends nodes after the last child node

DOMDocumentFragment::append

(PHP 8)

DOMDocumentFragment::append — Appends nodes after the last child node

Descripción

public DOMDocumentFragment::append(DOMNode|string ...$nodes): void

Appends one or many nodes to the list of children after the last child node.

Ejemplos

Ejemplo #1 DOMDocumentFragment::append() example

Appends nodes in the fragment.

<?php
$doc = new DOMDocument;
$fragment = $doc->createDocumentFragment();
$fragment->appendChild($doc->createElement("hello"));

$fragment->append("beautiful", $doc->createElement("world"));

echo $doc->saveXML($fragment);
?>

El resultado del ejemplo sería:

<hello/>beautiful<world/>

Ver también

  • DOMParentNode::append()
  • DOMDocumentFragment::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Añade información XML sin formato

  • « DOMDocumentFragment::append
  • DOMDocumentFragment::__construct »
  • PHP Manual
  • DOMDocumentFragment
  • Añade información XML sin formato

DOMDocumentFragment::appendXML

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

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

Thanks to Christoph. 07-Jun-2022 01:50
Strings such as " ' & < > may need to be escaped in advance.
In that case, you can use htmlspecialchars().
lpetrov(AT)axisvista.com 20-Jul-2007 05:45
Here is (maybe) a better example:
/**
* Helper function for replacing $node (DOMNode)
* with an XML code (string)
*
* @var DOMNode $node
* @var string $xml
*/
public function replaceNodeXML(&$node,$xml) {
 $f = $this->dom->createDocumentFragment();
 $f->appendXML($xml);
 $node->parentNode->replaceChild($f,$node);
}

Copied from the "PHP5 Dom Based Template" article at:
http://blog.axisvista.com/?p=35


Constructs a DOMDocumentFragment object

  • « DOMDocumentFragment::appendXML
  • DOMDocumentFragment::prepend »
  • PHP Manual
  • DOMDocumentFragment
  • Constructs a DOMDocumentFragment object

DOMDocumentFragment::__construct

(PHP 5, PHP 7, PHP 8)

DOMDocumentFragment::__construct — Constructs a DOMDocumentFragment object

Descripción

public DOMDocumentFragment::__construct()

Parámetros

Esta función no tiene parámetros.

User Contributed Notes

There are no user contributed notes for this page.


Prepends nodes before the first child node

  • « DOMDocumentFragment::__construct
  • DOMDocumentFragment::replaceChildren »
  • PHP Manual
  • DOMDocumentFragment
  • Prepends nodes before the first child node

DOMDocumentFragment::prepend

(PHP 8)

DOMDocumentFragment::prepend — Prepends nodes before the first child node

Descripción

public DOMDocumentFragment::prepend(DOMNode|string ...$nodes): void

Prepends one or many nodes to the list of children before the first child node.

Ejemplos

Ejemplo #1 DOMDocumentFragment::prepend() example

Prepends nodes before the fragment root.

<?php
$doc = new DOMDocument;
$fragment = $doc->createDocumentFragment();
$fragment->appendChild($doc->createElement("world"));

$fragment->prepend($doc->createElement("hello"), "beautiful");

echo $doc->saveXML($fragment);
?>

El resultado del ejemplo sería:

<hello/>beautiful<world/>

Ver también

  • DOMParentNode::prepend()
  • DOMDocumentFragment::append() - Appends nodes after the last child node

User Contributed Notes

There are no user contributed notes for this page.


Replace children in fragment

  • « DOMDocumentFragment::prepend
  • DOMDocumentType »
  • PHP Manual
  • DOMDocumentFragment
  • Replace children in fragment

DOMDocumentFragment::replaceChildren

(PHP 8 >= 8.3.0)

DOMDocumentFragment::replaceChildren — Replace children in fragment

Descripción

public DOMDocumentFragment::replaceChildren(DOMNode|string ...$nodes): void

Replaces the children in the document fragment with new nodes.

Ejemplos

Ejemplo #1 DOMDocumentFragment::replaceChildren() example

Replaces the children with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");
$fragment = $doc->createDocumentFragment();
$fragment->append("hello");

$fragment->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML($fragment);
?>

El resultado del ejemplo sería:

beautiful
<world/>

Ver también

  • DOMParentNode::replaceChildren()
  • DOMDocumentFragment::append() - Appends nodes after the last child node
  • DOMDocumentFragment::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMDocumentType

(PHP 5, PHP 7, PHP 8)

Introducción

Cada DOMDocument tiene un atributo doctype cuyo valor es null o un objeto DOMDocumentType.

Sinopsis de la Clase

class 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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, PHP 8)

Sinopsis de la Clase

class DOMElement extends DOMNode {
/* Propiedades */
readonly public bool $schemaTypeInfo;
readonly public string $tagName;
/* Métodos */
public after(DOMNode|string ...$nodes): void
public append(DOMNode|string ...$nodes): void
public before(DOMNode|string ...$nodes): void
public __construct(string $name, string $value = ?, string $namespaceURI = ?)
public getAttribute(string $name): string
public getAttributeNames(): array
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 insertAdjacentElement(string $where, DOMElement $element): ?DOMElement
public insertAdjacentText(string $where, string $data): void
public prepend(DOMNode|string ...$nodes): void
public remove(): void
public removeAttribute(string $name): bool
public removeAttributeNode(DOMAttr $oldnode): bool
public removeAttributeNS(string $namespaceURI, string $localName): bool
public replaceChildren(DOMNode|string ...$nodes): void
public replaceWith(DOMNode|string ...$nodes): void
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
public toggleAttribute(string $qualifiedName, ?bool $force = null): 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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::after — Adds nodes after the element
  • DOMElement::append — Appends nodes after the last child node
  • DOMElement::before — Adds nodes before the element
  • DOMElement::__construct — Crea un nuevo objeto DOMElement
  • DOMElement::getAttribute — Devuelve el valor de un atributo
  • DOMElement::getAttributeNames — Get attribute names
  • 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::insertAdjacentElement — Insert adjacent element
  • DOMElement::insertAdjacentText — Insert adjacent text
  • DOMElement::prepend — Prepends nodes before the first child node
  • DOMElement::remove — Removes the element
  • DOMElement::removeAttribute — Elimina un atributo
  • DOMElement::removeAttributeNode — Elimina un atributo
  • DOMElement::removeAttributeNS — Elimina un atributo
  • DOMElement::replaceChildren — Replace children in element
  • DOMElement::replaceWith — Replaces the element with new nodes
  • 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::toggleAttribute — Toggle attribute

User Contributed Notes

johnny 03-Mar-2014 03:48
Get html of a node
 $html .= $dom->saveHTML($node);
Janne Enberg 07-Nov-2013 11:02
This page doesn't list the inherited properties from DOMNode, e.g. the quite important textContent property. It would be immensely helpful if it would list those as well.
felix dot klee at inka dot de 26-Feb-2013 03:23
How to rename an element and preserve attributes:

<?php

// Changes the name of element $element to $newName.
function renameElement($element, $newName) {
  $newElement = $element->ownerDocument->createElement($newName);
  $parentElement = $element->parentNode;
  $parentElement->insertBefore($newElement, $element);

  $childNodes = $element->childNodes;
  while ($childNodes->length > 0) {
    $newElement->appendChild($childNodes->item(0));
  }

  $attributes = $element->attributes;
  while ($attributes->length > 0) {
    $attribute = $attributes->item(0);
    if (!is_null($attribute->namespaceURI)) {
      $newElement->setAttributeNS('http://www.w3.org/2000/xmlns/',
                                  'xmlns:'.$attribute->prefix,
                                  $attribute->namespaceURI);
    }
    $newElement->setAttributeNode($attribute);
  }

  $parentElement->removeChild($element);
}

function prettyPrint($d) {
  $d->formatOutput = true;
  echo '<pre>'.htmlspecialchars($d->saveXML()).'</pre>';
}

$d = new DOMDocument( '1.0' );
$d->loadXML('<?xml version="1.0"?>
<library>
  <data a:foo="1" x="bar" xmlns:a="http://example.com/a">
    <invite>
      <username>jmansa</username>
      <userid>1</userid>
    </invite>
    <update>1</update>
  </data>
</library>');

$xpath = new DOMXPath($d);
$elements = $xpath->query('/library/data');
if ($elements->length == 1) {
  $element = $elements->item(0);
  renameElement($element, 'invites');
}

prettyPrint($d);

?>
loopduplicate at burningtoken dot com 22-Apr-2011 02:34
This works perfect for me as well:

<?php $xml = $domElement->ownerDocument->saveXML($domElement); ?>
Anonymous 24-Dec-2010 08:22
you can use DOMNode::nodeValue
DOMElement inherits this public property.

$elem->nodeValue
dpetroff ( at ) gmail.com 04-Dec-2010 11:24
Hi!

Combining all th comments, the easiest way to get inner HTML of the node is to use this function:

<?php
function get_inner_html( $node ) {
    $innerHTML= '';
    $children = $node->childNodes;
    foreach ($children as $child) {
        $innerHTML .= $child->ownerDocument->saveXML( $child );
    }

    return $innerHTML;
}
?>
nawaman at gmail dot com 03-Sep-2009 08:08
The following code shows can text-only content be extracted from a document.

<?php
function getTextFromNode($Node, $Text = "") {
    if ($Node->tagName == null)
        return $Text.$Node->textContent;

    $Node = $Node->firstChild;
    if ($Node != null)
        $Text = getTextFromNode($Node, $Text);

    while($Node->nextSibling != null) {
        $Text = getTextFromNode($Node->nextSibling, $Text);
        $Node = $Node->nextSibling;
    }
    return $Text;
}

function getTextFromDocument($DOMDoc) {
    return getTextFromNode($DOMDoc->documentElement);
}

$Doc = new DOMDocument();
$Doc->loadHTMLFile("Test.html");
echo getTextFromDocument($Doc)."\n";
?>
Daniel Morlock 07-May-2009 09:22
It would be nice to have a function which converts a document/node/element into a string.

Anyways, I use the following code snippet to get the innerHTML value of a DOMNode:

<?php
function getInnerHTML($Node)
{
     $Body = $Node->ownerDocument->documentElement->firstChild->firstChild;
     $Document = new DOMDocument();
     $Document->appendChild($Document->importNode($Body,true));
     return $Document->saveHTML();
}
?>
patrick smith 04-Nov-2008 08:14
Although it may be preferable to use the dom to manipulate elements, sometimes it's useful to actually get the innerHTML from a document element (e.g. to load into a client-side editor).

To get the innerHTML of a specific element ($elem_id) in a specific html file ($filepath):

<?php
$innerHTML = '';
$doc = new DOMDocument();
$doc->loadHTMLFile($filepath);
$elem = $doc->getElementById($elem_id);

// loop through all childNodes, getting html
$children = $elem->childNodes;
foreach ($children as $child) {
    $tmp_doc = new DOMDocument();
    $tmp_doc->appendChild($tmp_doc->importNode($child,true));
    $innerHTML .= $tmp_doc->saveHTML();
}
?>
Pinochet 25-Oct-2008 05:33
Hi to get the value of DOMElement just get the nodeValue public parameter (it is inherited from DOMNode):
<?php
echo $domElement->nodeValue;
?>
Everything is obvious if you now about this thing ;-)
j DOT wagner ( AT ) medieninnovation.com 08-Oct-2008 09:11
Caveat!
It took me almost an hour to figure this out, so I hope it saves at least one of you some time.

If you want to debug your DOM tree and try var_dump() or similar you will be fooled into thinking the DOMElement that you are looking at is empty, because var_dump() says: object(DOMElement)#1 (0) { }

After much debugging I found out that all DOM objects are invisible to var_dump() and print_r(), my guess is because they are C objects and not PHP objects. So I tried saveXML(), which works fine on DOMDocument, but is not implemented on DOMElement.

The solution is simple (if you know it):
$xml = $domElement->ownerDocument->saveXML($domElement);

This will give you an XML representation of $domElement.
Severin 14-Sep-2008 06:18
I wanted to find similar Elements - thats why I built an Xpath-String like this - maybe somebody needs it... its not very pretty - but neither is domdocument :)

<?php

$dom->load($xmlFile))

$xpathQuery = '//*';
$xmlNodes = $xpath->query($xpathQuery);

$pathlist = array();
$attrlist = array();
foreach ($xmlNodes as $node) {

  $depth = $this->_getDomDepth($node);   //get Path-Depth (for array key)
  $pathlist[$depth] = $node->tagName;     // tagname

  $attrs = $node->attributes;
  $attr='';
  $a=0;
  foreach ($attrs as $attrName => $attrNode)  // attributes
            {
              if ($attrName !='reg')
              {
                if ($a++!=0) $attr .= ' and ';
                $attr .= '@'.$attrName.'='."'".$attrNode->value."'";
              }
            }

          $attrlist[$depth] = $attr?'['.$attr.']':'';

          $path = ''; for ($i=0;$i<=$depth;$i++) $path .= '/'.$pathlist[$i].$attrlist[$i];  // the xpath of the actual Element

    // ... now you can go on and user $path to find similar elements
    }
  }
}

 private function _getDomDepth(DomNode $node)
   {
     $r = -2;
     while ($node) {
       $r++;
       $node = $node->parentNode;
     }
     return  $r;
   }
?>
ae.fxx 18-Jul-2008 01:49
Hi there.

Remember to append a DOMNode (or any of its descendants) to a DOMDocument __BEFORE__ you try to append a child to it.

I don't know why it has to be this way but it can't be done without it.

bye


Adds nodes after the element

  • « DOMElement
  • DOMElement::append »
  • PHP Manual
  • DOMElement
  • Adds nodes after the element

DOMElement::after

(PHP 8)

DOMElement::after — Adds nodes after the element

Descripción

public DOMElement::after(DOMNode|string ...$nodes): void

Adds the passed nodes after the element.

Ejemplos

Ejemplo #1 DOMElement::after() example

Adds nodes after the hello element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<hello/>");
$container = $doc->documentElement;

$container->after("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<hello/>
beautiful
<world/>

Ver también

  • DOMChildNode::after()
  • DOMElement::before() - Adds nodes before the element

User Contributed Notes

There are no user contributed notes for this page.


Appends nodes after the last child node

  • « DOMElement::after
  • DOMElement::before »
  • PHP Manual
  • DOMElement
  • Appends nodes after the last child node

DOMElement::append

(PHP 8)

DOMElement::append — Appends nodes after the last child node

Descripción

public DOMElement::append(DOMNode|string ...$nodes): void

Appends one or many nodes to the list of children after the last child node.

Ejemplos

Ejemplo #1 DOMElement::append() example

Appends nodes in the container element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container>hello </container>");
$world = $doc->documentElement;

$world->append("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<container>hello beautiful<world/></container>

Ver también

  • DOMParentNode::append()
  • DOMElement::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Adds nodes before the element

  • « DOMElement::append
  • DOMElement::__construct »
  • PHP Manual
  • DOMElement
  • Adds nodes before the element

DOMElement::before

(PHP 8)

DOMElement::before — Adds nodes before the element

Descripción

public DOMElement::before(DOMNode|string ...$nodes): void

Adds the passed nodes before the element.

Ejemplos

Ejemplo #1 DOMElement::before() example

Adds nodes before the hello element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<world/>");
$world = $doc->documentElement;

$world->before("hello", $doc->createElement("beautiful"));

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

hello
<beautiful/>
<world/>

Ver también

  • DOMChildNode::before()
  • DOMElement::after() - Adds nodes after the element

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo objeto DOMElement

  • « DOMElement::before
  • DOMElement::getAttribute »
  • PHP Manual
  • DOMElement
  • Crea un nuevo objeto DOMElement

DOMElement::__construct

(PHP 5, PHP 7, PHP 8)

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

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


Devuelve el valor de un atributo

  • « DOMElement::__construct
  • DOMElement::getAttributeNames »
  • PHP Manual
  • DOMElement
  • Devuelve el valor de un atributo

DOMElement::getAttribute

(PHP 5, PHP 7, PHP 8)

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

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


Get attribute names

  • « DOMElement::getAttribute
  • DOMElement::getAttributeNode »
  • PHP Manual
  • DOMElement
  • Get attribute names

DOMElement::getAttributeNames

(PHP 8 >= 8.3.0)

DOMElement::getAttributeNames — Get attribute names

Descripción

public DOMElement::getAttributeNames(): array

Get attribute names.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Return attribute names.

Ejemplos

Ejemplo #1 DOMElement::getAttributeNames() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<html xmlns:some="some:ns" some:test="a" test2="b"/>');
var_dump($dom->documentElement->getAttributeNames());
?>

El resultado del ejemplo sería:

array(3) {
 [0]=>
 string(10) "xmlns:some"
 [1]=>
 string(9) "some:test"
 [2]=>
 string(5) "test2"
}

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el nodo de un atributo

  • « DOMElement::getAttributeNames
  • DOMElement::getAttributeNodeNS »
  • PHP Manual
  • DOMElement
  • Devuelve el nodo de un atributo

DOMElement::getAttributeNode

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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

There are no user contributed notes for this page.


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, PHP 8)

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, PHP 8)

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::insertAdjacentElement »
  • PHP Manual
  • DOMElement
  • Comprueba si un atributo existe

DOMElement::hasAttributeNS

(PHP 5, PHP 7, PHP 8)

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.


Insert adjacent element

  • « DOMElement::hasAttributeNS
  • DOMElement::insertAdjacentText »
  • PHP Manual
  • DOMElement
  • Insert adjacent element

DOMElement::insertAdjacentElement

(PHP 8 >= 8.3.0)

DOMElement::insertAdjacentElement — Insert adjacent element

Descripción

public DOMElement::insertAdjacentElement(string $where, DOMElement $element): ?DOMElement

Inserts an element at a relative position given by where.

Parámetros

where

  • beforebegin - Insert before the target element.
  • afterbegin - Insert as the first child of the target element.
  • beforeend - Insert as the last child of the target element.
  • afterend - Insert after the target element.

element

The element to insert.

Valores devueltos

Return DOMElement or null on failure.

Ejemplos

Ejemplo #1 DOMElement::insertAdjacentElement() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><container><p>foo</p></container>');
$container = $dom->documentElement;
$p = $container->firstElementChild;

$p->insertAdjacentElement('beforebegin', $dom->createElement('A'));
echo $dom->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<container><A/><p>foo</p></container>

Ver también

  • DOMElement::insertAdjacentText() - Insert adjacent text

User Contributed Notes

There are no user contributed notes for this page.


Insert adjacent text

  • « DOMElement::insertAdjacentElement
  • DOMElement::prepend »
  • PHP Manual
  • DOMElement
  • Insert adjacent text

DOMElement::insertAdjacentText

(PHP 8 >= 8.3.0)

DOMElement::insertAdjacentText — Insert adjacent text

Descripción

public DOMElement::insertAdjacentText(string $where, string $data): void

Inserts text at a relative position given by where.

Parámetros

where

  • beforebegin - Insert before the target element.
  • afterbegin - Insert as the first child of the target element.
  • beforeend - Insert as the last child of the target element.
  • afterend - Insert after the target element.

data

The string to insert.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 DOMElement::insertAdjacentText() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><container><p>H</p></container>');

$container = $dom->documentElement;
$p = $container->firstElementChild;

$p->insertAdjacentText("afterbegin", "P");
$p->insertAdjacentText("beforeend", "P");

echo $dom->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<container><p>PHP</p></container>

Ver también

  • DOMElement::insertAdjacentElement() - Insert adjacent element

User Contributed Notes

There are no user contributed notes for this page.


Prepends nodes before the first child node

  • « DOMElement::insertAdjacentText
  • DOMElement::remove »
  • PHP Manual
  • DOMElement
  • Prepends nodes before the first child node

DOMElement::prepend

(PHP 8)

DOMElement::prepend — Prepends nodes before the first child node

Descripción

public DOMElement::prepend(DOMNode|string ...$nodes): void

Prepends one or many nodes to the list of children before the first child node.

Ejemplos

Ejemplo #1 DOMElement::prepend() example

Prepends nodes in the container element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container> world</container>");
$world = $doc->documentElement;

$world->prepend($doc->createElement("hello"), "beautiful");

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<container><hello/>beautiful world</container>

Ver también

  • DOMParentNode::prepend()
  • DOMElement::append() - Appends nodes after the last child node

User Contributed Notes

There are no user contributed notes for this page.


Removes the element

  • « DOMElement::prepend
  • DOMElement::removeAttribute »
  • PHP Manual
  • DOMElement
  • Removes the element

DOMElement::remove

(PHP 8)

DOMElement::remove — Removes the element

Descripción

public DOMElement::remove(): void

Removes the element.

Ejemplos

Ejemplo #1 DOMElement::remove() example

Removes the element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/><world/></container>");
$hello = $doc->documentElement->firstChild;

$hello->remove();

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<container><world/></container>

Ver también

  • DOMElement::after() - Adds nodes after the element
  • DOMElement::before() - Adds nodes before the element
  • DOMElement::replaceWith() - Replaces the element with new nodes
  • DOMNode::removeChild() - Elimina un hijo de la lista de hijos.

User Contributed Notes

There are no user contributed notes for this page.


Elimina un atributo

  • « DOMElement::remove
  • DOMElement::removeAttributeNode »
  • PHP Manual
  • DOMElement
  • Elimina un atributo

DOMElement::removeAttribute

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

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::replaceChildren »
  • PHP Manual
  • DOMElement
  • Elimina un atributo

DOMElement::removeAttributeNS

(PHP 5, PHP 7, PHP 8)

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

?>


Replace children in element

  • « DOMElement::removeAttributeNS
  • DOMElement::replaceWith »
  • PHP Manual
  • DOMElement
  • Replace children in element

DOMElement::replaceChildren

(PHP 8 >= 8.3.0)

DOMElement::replaceChildren — Replace children in element

Descripción

public DOMElement::replaceChildren(DOMNode|string ...$nodes): void

Replaces the children in the element with new nodes.

Ejemplos

Ejemplo #1 DOMElement::replaceChildren() example

Replaces the children with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");
$container = $doc->documentElement;

$container->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
beautiful
<world/>

Ver también

  • DOMParentNode::replaceChildren()
  • DOMElement::replaceWith() - Replaces the element with new nodes
  • DOMElement::after() - Adds nodes after the element
  • DOMElement::before() - Adds nodes before the element
  • DOMElement::remove() - Removes the element

User Contributed Notes

There are no user contributed notes for this page.


Replaces the element with new nodes

  • « DOMElement::replaceChildren
  • DOMElement::setAttribute »
  • PHP Manual
  • DOMElement
  • Replaces the element with new nodes

DOMElement::replaceWith

(PHP 8)

DOMElement::replaceWith — Replaces the element with new nodes

Descripción

public DOMElement::replaceWith(DOMNode|string ...$nodes): void

Replaces the element with new nodes.

Ejemplos

Ejemplo #1 DOMElement::replaceWith() example

Replaces the element with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

El resultado del ejemplo sería:

<?xml version="1.0"?>
<container>beautiful<world/></container>

Ver también

  • DOMChildNode::replaceWith()
  • DOMElement::replaceChildren() - Replace children in element
  • DOMElement::after() - Adds nodes after the element
  • DOMElement::before() - Adds nodes before the element
  • DOMElement::remove() - Removes the element

User Contributed Notes

There are no user contributed notes for this page.


Añade un nuevo atributo

  • « DOMElement::replaceWith
  • DOMElement::setAttributeNode »
  • PHP Manual
  • DOMElement
  • Añade un nuevo atributo

DOMElement::setAttribute

(PHP 5, PHP 7, PHP 8)

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

info at ensostudio dot ru 02-Dec-2021 06:17
Solution to render HTML 5 tags with attributes with/without value:
<?php
$dom = new DOMImplementation();
$doc = $dom->createDocument(null, 'html', $dom->createDocumentType('html'));

$tag = $doc->appendChild($doc->createElement('input'));
$tag->setAttribute('type', 'text');
$tag->setAttribute('disabled', '');

echo $doc->saveHTML($tag); // <input type="text" disabled="">

$doc->normalize(); // normalize attributes
echo $doc->saveHTML($tag); // <input type="text" disabled>
?>
lehal2@hotmail 06-Jun-2013 09:44
The use of Dom to first remove and then add the width and height to the first img tag from the text.I hope it help you to save your time
<?php
$html = '

            <img src="http://www.example.com/images/header.jpg" width="898" height="223" style="border-bottom:5px solid #cccccc;"/>
        <img src="http://www.example.com/images/header2.jpg" width="898" height="223" style="border-bottom:5px solid #cccccc;"/>
        ';

$doc = DOMDocument::loadHTML($html);
$c =0;
foreach($doc->getElementsByTagName('img') as $image){
    if ($c>0) continue;
    foreach(array('width', 'height') as $attribute_to_remove){
        echo $attribute_to_remove;
        if($image->hasAttribute($attribute_to_remove)){
            $image->removeAttribute($attribute_to_remove);

        }
        if($attribute_to_remove=='height'){
            if(!$image->hasAttribute($attribute_to_remove)){
                $image->setAttribute($attribute_to_remove,'220');

            }}
        if($attribute_to_remove=='width'){
      if(!$image->hasAttribute($attribute_to_remove)){
            $image->setAttribute($attribute_to_remove,'700');

        }}
        $c = $c+1;
    }
}
echo $doc->saveHTML();
Rakesh Verma - rakeshnsony at gmail dot com 10-Nov-2010 11:27
<?php
//Store your html into $html variable.
$html="
<html>
<head>
<title>Untitled Document</title>
</head>

<body>
    <a href='http://example.com'>Example</a><br>
    <a href='http://google.com'>Google</a><br>

    <a href='http://www.yahoo.com'>Yahoo</a><br>
</body>

</html>";

$dom = new DOMDocument();
$dom->loadHTML($html);

//Evaluate Anchor tag in HTML
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');

        //remove and set target attribute
        $href->removeAttribute('target');
        $href->setAttribute("target", "_blank");

        $newURL=$url."/newurl";

        //remove and set href attribute
        $href->removeAttribute('href');
        $href->setAttribute("href", $newURL);
}

// save html
$html=$dom->saveHTML();

echo $html;

?>
address at gmail dot com 03-Jul-2008 07:25
If wanting to set an attribute of an element with unique id of "1"

<?php
$dom = new DomDocument();
$dom->load('test.xml');
$xp = new DomXPath($dom);
$res = $xp->query("//*[@id = '1']");
$res->item(0)->setAttribute('title','2');
$dom->save('test.xml');
?>
Vasil Rangelov 31-Jul-2007 04:44
@karvjorm,
Using this method is not exactly a good practice. Infact, I think it may be a bug.
Names beginning with "xml" are reserved (for namespaces in this case).
setAttribute() should return false in this case I think, but I suppose it doesn't.

Still, the right way to do it is with createElementNS().
It lets you specify the namespace when creating the element node.

So the equivalent to yours ($html added to allow word wrapping) is:

$dom = new DomDocument('1.0','iso-8859-15');
$html = $dom->createElementNS('http://www.w3.org/1999/xhtml', 'html');
$ht_ml = $dom->appendChild($html);
$ht_ml->setAttribute('xml:lang','fi');
$ht_ml->setAttribute('lang','fi');
karvjorm at users.sourceforge.net 02-Mar-2007 03:05
$dom = new DomDocument('1.0','iso-8859-15');

$ht_ml = $dom->appendChild($dom->createElement('html'));
$ht_ml->setAttribute('xmlns','http://www.w3.org/1999/xhtml');
$ht_ml->setAttribute('xml:lang','fi');
$ht_ml->setAttribute('lang','fi');

Result:

<?xml version="1.0" encoding="iso-8859-15"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi" lang="fi">


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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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
  • DOMElement::toggleAttribute »
  • 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, PHP 8)

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.


Toggle attribute

  • « DOMElement::setIdAttributeNS
  • DOMEntity »
  • PHP Manual
  • DOMElement
  • Toggle attribute

DOMElement::toggleAttribute

(PHP 8 >= 8.3.0)

DOMElement::toggleAttribute — Toggle attribute

Descripción

public DOMElement::toggleAttribute(string $qualifiedName, ?bool $force = null): bool

Toggle the attribute.

Parámetros

qualifiedName

The qualified name of the attribute.

force

  • if null, the function will toggle the attribute.
  • if true, the function adds the attribute.
  • if false, the function removes the attribute.

Valores devueltos

Returns true if the attribute is present after finishing the call, false otherwise.

Ejemplos

Ejemplo #1 DOMElement::toggleAttribute() example

<?php

$dom = new DOMDocument();
$dom->loadXML("<?xml version='1.0'?><container selected=\"\"/>");

var_dump($dom->documentElement->toggleAttribute('selected'));
echo $dom->saveXML() . PHP_EOL;

var_dump($dom->documentElement->toggleAttribute('selected'));
echo $dom->saveXML();
?>

El resultado del ejemplo sería:

bool(false)
<?xml version="1.0"?>
<container/>

bool(true)
<?xml version="1.0"?>
<container selected=""/>

User Contributed Notes

There are no user contributed notes for this page.


La clase DOMEntity

(PHP 5, PHP 7, PHP 8)

Introducción

Esta interfaz representa una entidad conocida, analizada o sin analizar, de un documento XML.

Sinopsis de la Clase

class 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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, PHP 8)

Sinopsis de la Clase

class 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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, PHP 8)

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, PHP 8)

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

class 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(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

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, PHP 8)

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

class 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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

Sinopsis de la Clase

class DOMNamedNodeMap implements Traversable {
/* Propiedades */
readonly public int $length;
/* Métodos */
public count(): int
public getIterator(): Iterator
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::getIterator — Retrieve an external iterator
  • 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::getIterator »
  • PHP Manual
  • DOMNamedNodeMap
  • Get number of nodes in the map

DOMNamedNodeMap::count

(PHP 7 >= 7.2.0, PHP 8)

DOMNamedNodeMap::count — Get number of nodes in the map

Descripción

public DOMNamedNodeMap::count(): int

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.


Retrieve an external iterator

  • « DOMNamedNodeMap::count
  • DOMNamedNodeMap::getNamedItem »
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieve an external iterator

DOMNamedNodeMap::getIterator

(PHP 8)

DOMNamedNodeMap::getIterator — Retrieve an external iterator

Descripción

public DOMNamedNodeMap::getIterator(): Iterator

Returns an external iterator for the named node map.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Una instancia de un objeto que implementa Iterator o Traversable

Errores/Excepciones

Lanza una Exception en caso de fallo.

Ver también

  • IteratorAggregate::getIterator() - Recuperar un Iterator externo

User Contributed Notes

There are no user contributed notes for this page.


Recupera un nodo especificado por su nombre

  • « DOMNamedNodeMap::getIterator
  • DOMNamedNodeMap::getNamedItemNS »
  • PHP Manual
  • DOMNamedNodeMap
  • Recupera un nodo especificado por su nombre

DOMNamedNodeMap::getNamedItem

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

Sinopsis de la Clase

class 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 contains(DOMNode|DOMNameSpaceNode|null $other): bool
public getLineNo(): int
public getNodePath(): string
public getRootNode(array $options = null): DOMNode
public hasAttributes(): bool
public hasChildNodes(): bool
public insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public isDefaultNamespace(string $namespaceURI): bool
public isEqualNode(?DOMNode $otherNode): 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::contains — Checks if node contains other node
  • DOMNode::getLineNo — Obtener el número de línea de un nodo
  • DOMNode::getNodePath — Obtener un XPath de un nodo
  • DOMNode::getRootNode — Get root node
  • 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::isEqualNode — Checks that both nodes are equal
  • 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, PHP 8)

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, PHP 8)

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, PHP 8)

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::contains »
  • PHP Manual
  • DOMNode
  • Clona un nodo

DOMNode::cloneNode

(PHP 5, PHP 7, PHP 8)

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

?>


Checks if node contains other node

  • « DOMNode::cloneNode
  • DOMNode::getLineNo »
  • PHP Manual
  • DOMNode
  • Checks if node contains other node

DOMNode::contains

(PHP 8 >= 8.3.0)

DOMNode::contains — Checks if node contains other node

Descripción

public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool

Checks if node contains other node.

Parámetros

other

Node to be checked.

Valores devueltos

Returns true if node contains other node, false otherwise.

Ejemplos

Ejemplo #1 DOMNode::contains() example

<?php

$dom = new DOMDocument();
$dom->loadXML(<<<XML
<!DOCTYPE HTML>
<html>
<body>
<main>
<p>Hello, world!</p>
</main>
</body>
</html>
XML);

$xpath = new DOMXPath($dom);
$main = $xpath->query("//main")[0];

var_dump($dom->documentElement->contains($main));
?>

El resultado del ejemplo sería:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Obtener el número de línea de un nodo

  • « DOMNode::contains
  • DOMNode::getNodePath »
  • PHP Manual
  • DOMNode
  • Obtener el número de línea de un nodo

DOMNode::getLineNo

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

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::getRootNode »
  • PHP Manual
  • DOMNode
  • Obtener un XPath de un nodo

DOMNode::getNodePath

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

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.


Get root node

  • « DOMNode::getNodePath
  • DOMNode::hasAttributes »
  • PHP Manual
  • DOMNode
  • Get root node

DOMNode::getRootNode

(PHP 8 >= 8.3.0)

DOMNode::getRootNode — Get root node

Descripción

public DOMNode::getRootNode(array $options = null): DOMNode

Get root node.

Parámetros

options

This parameter has no effect yet.

Valores devueltos

Returns the root node.

Ejemplos

Ejemplo #1 DOMNode::getRootNode() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><html><body/></html>');

var_dump($dom->documentElement->firstElementChild->getRootNode() === $dom);
?>

El resultado del ejemplo sería:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Comprueba si un nodo tiene atributos

  • « DOMNode::getRootNode
  • DOMNode::hasChildNodes »
  • PHP Manual
  • DOMNode
  • Comprueba si un nodo tiene atributos

DOMNode::hasAttributes

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

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, PHP 8)

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::isEqualNode »
  • PHP Manual
  • DOMNode
  • Comprueba si la URI del espacio de nombres especificada es el espacio de nombres predeterminado

DOMNode::isDefaultNamespace

(PHP 5, PHP 7, PHP 8)

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.


Checks that both nodes are equal

  • « DOMNode::isDefaultNamespace
  • DOMNode::isSameNode »
  • PHP Manual
  • DOMNode
  • Checks that both nodes are equal

DOMNode::isEqualNode

(PHP 8 >= 8.3.0)

DOMNode::isEqualNode — Checks that both nodes are equal

Descripción

public DOMNode::isEqualNode(?DOMNode $otherNode): bool

Checks that both nodes are equal.

Parámetros

otherNode

The node.

Valores devueltos

Returns true if both nodes are equal, false otherwise.

Ejemplos

Ejemplo #1 DOMNode::isEqualNode() example

<?php

$dom1 = (new DOMDocument())->createElement('h1', 'Hello World!');
$dom2 = (new DOMDocument())->createElement('h1', 'Hello World!');

var_dump($dom1->isEqualNode($dom2));
?>

El resultado del ejemplo sería:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Indica si dos nodos son el mismo nodo

  • « DOMNode::isEqualNode
  • DOMNode::isSupported »
  • PHP Manual
  • DOMNode
  • Indica si dos nodos son el mismo nodo

DOMNode::isSameNode

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

Sinopsis de la Clase

class DOMNodeList implements Traversable {
/* Propiedades */
readonly public int $length;
/* Métodos */
public count(): int
public getIterator(): Iterator
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::getIterator — Retrieve an external iterator
  • DOMNodeList::item — Recupera un nodo especificado por un índice

User Contributed Notes

niko at yopmail dot com 03-Apr-2021 03:13
It's worth to mention that DOMNodeList is not an Array,  so you have to convert first to an array before to use for, foreach or array_map, array_filter, array_walk functions.

Use iterator_to_array to make the conversion ( since PHP 5.1.0 ) .

<code>
  /* @ suppress warning var_dump not yet implemented for class */

@array_walk( iterator_to_array( $Some_NodeList ), 'var_dump' ) );

foreach( iterator_to_array( $Some_NodeList ) as $node )
    @var_dump( $node );

</code>

Hope is usefull.
ignitedfirestarter at gmail dot com 04-Jul-2012 10:39
If you want to recurse over a DOM then this might help:
<?php

/**
 * PHP's DOM classes are recursive but don't provide an implementation of
 * RecursiveIterator. This class provides a RecursiveIterator for looping over DOMNodeList
 */
class DOMNodeRecursiveIterator extends ArrayIterator implements RecursiveIterator {

  public function __construct (DOMNodeList $node_list) {

    $nodes = array();
    foreach($node_list as $node) {
      $nodes[] = $node;
    }

    parent::__construct($nodes);

  }

  public function getRecursiveIterator(){
    return new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST);
  }

  public function hasChildren () {
    return $this->current()->hasChildNodes();
  }

  public function getChildren () {
    return new self($this->current()->childNodes);
  }

}
?>
geompse at gmail dot com 19-May-2010 08:39
Note that $length is calculated (php5.3.2).
Iterating over a large NodeList may be time expensive.

Prefer :
$nb = $nodelist->length;
for($pos=0; $pos<$nb; $pos++)

Than:
for($pos=0; $pos<$nodelist->length; $pos++)

I had a hard time figuring that out...
bobvandell at hotmail dot com 26-Aug-2008 09:12
That's actually incorrect. You can use function results as objects. It makes building an API for your database very clean and neat. For example:

Our code:

$articles = Node::screate('tags', 123456)->assets('like:title:test')->articles;

We use the above code to get articles that are linked to assets that are linked to a specific tag in our database.
c dot 1 at smithies dot org 23-May-2008 05:43
You can modify, and even delete, nodes from a DOMNodeList if you iterate backwards:

$els = $document->getElementsByTagName('input');
for ($i = $els->length; --$i >= 0; ) {
  $el = $els->item($i);
  switch ($el->getAttribute('name')) {
    case 'MAX_FILE_SIZE' :
      $el->parentNode->removeChild($el);
    break;
    case 'inputfile' :
      $el->setAttribute('type', 'text');
    //break;
  }
}
drichter at muvicom dot de 14-May-2008 06:11
Addition to my first note:

An traditional for-loop does not allow you to change the DOM-tree while looping - the effects are the nearly the same as with foreach. So you have to collect the nodes in an array and do the tree-altering stuff within a second loop (looping the array this time ...)
drichter at muvicom dot de 14-May-2008 04:56
I have done some testing and have found 2 results:
(My System: Win XP with PHP 5.2.1)

1) Iteration with foreach does function correctly as "james dot j dot hackett at gmail dot com" writes, _if_ you only do readonly stuff with foreach or minor writings of some attributes.

2) foreach does not function, if you are doing some DOM-Operations while iterating. In my situation it was adding the iterated $node as an child to an new node:

$newNode = $dom->createElement('newNode') ;
foreach ($nodeList as $node) {
  echo $node->nodeValue ;
  $newNode->appendChild($node) ;
}

This only gives you the first element ...

I'm interpreting it as an confusing but correct behavior because of the changes within the $dom-object while appending the node at an additional place ...

So, if you want to do something like 2) use for, length and item() :)
james dot j dot hackett at gmail dot com 08-May-2008 09:47
In Response to 'kassah at gmail'

You don't need to convert a DOMNodeList to an array in order iterate through it using 'foreach'.  You can use foreach directly with the DOMNodeList.

$nodeList = $someDomDocument->getElementsbytagname('user');

foreach ($nodeList as $node) {
    echo $node->nodeValue;
}
brack at wjp dot de 21-Apr-2008 02:35
In PHP 5.2.5 (Windows) it is not possible to iterate correctly over the DOMNodeList object returned by DOMNode->childNodes using foreach. Instead I had to use the for loop in conjunction with the item() method of DOMNodeList for iterating over all child nodes correctly.

I don't know whether this is really a bug, but apparently it is.


Obtiene el número de nodos en la lista

  • « DOMNodeList
  • DOMNodeList::getIterator »
  • PHP Manual
  • DOMNodeList
  • Obtiene el número de nodos en la lista

DOMNodeList::count

(PHP 7 >= 7.2.0, PHP 8)

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


Retrieve an external iterator

  • « DOMNodeList::count
  • DOMNodeList::item »
  • PHP Manual
  • DOMNodeList
  • Retrieve an external iterator

DOMNodeList::getIterator

(PHP 8)

DOMNodeList::getIterator — Retrieve an external iterator

Descripción

public DOMNodeList::getIterator(): Iterator

Returns an external iterator for the node list.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Una instancia de un objeto que implementa Iterator o Traversable

Errores/Excepciones

Lanza una Exception en caso de fallo.

Ver también

  • IteratorAggregate::getIterator() - Recuperar un Iterator externo

User Contributed Notes

There are no user contributed notes for this page.


Recupera un nodo especificado por un índice

  • « DOMNodeList::getIterator
  • DOMNotation »
  • PHP Manual
  • DOMNodeList
  • Recupera un nodo especificado por un índice

DOMNodeList::item

(PHP 5, PHP 7, PHP 8)

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, PHP 8)

Sinopsis de la Clase

class 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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, PHP 8)

Sinopsis de la Clase

class 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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, PHP 8)

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, PHP 8)

Introducción

La clase DOMText hereda de DOMCharacterData y representa el contenido textual de un objeto DOMElement o DOMAttr.

Sinopsis de la Clase

class 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::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $newnode, DOMNode $refnode = ?): DOMNode
public DOMNode::isDefaultNamespace(string $namespaceURI): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): 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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

Introducción

Soporta XPath 1.0

Sinopsis de la Clase

class 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.
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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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, PHP 8)

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_external_entity_loader — Get the current external entity loader
    • 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

mansourjabin at gmail dot com 06-Nov-2023 05:35
Critical Note: In PHP 7.4, an issue presents itself when interfacing with libxml version 2.10.2. If you're deploying PHP 7.4 and wish to maintain operational stability, ensure that libxml is aligned to version 2.9.10. This version has been verified to work seamlessly with PHP 7.4, thereby preventing potential conflicts.
KiralyCraft 19-Sep-2022 05:51
Please note that this option does not seem to work for PHP 8.1.10 anymore.


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

Ismael Miguel 07-Jul-2023 10:53
If you want to save without the XML declaration, and LIBXML_NOXMLDECL doesn't work for you, you can just do this:

<?php
$doc = new \DOMDocument('1.0', 'UTF-8');
$doc->loadXML($xml, LIBXML_*);

echo $doc->saveXML($doc->firstElementChild);
?>

This will output the XML without the XML declaration and without using the flag.
You also don't need to do fiddly replacements and pray that it works.
siraic at gmail dot com 24-Mar-2021 12:10
The name of the constant LIBXML_NOENT is very misleading. Adding this flag actually causes the parser to load and insert the external entities. Omitting it leaves the tags untouched, which is probably what you want.
vetalstar at mail dot ru 16-Nov-2017 12:26
LIBXML_DOTTED_VERSION option doesn't work.
libxml version: 2.9.4

<?php

echo LIBXML_DOTTED_VERSION;
$xml = new SimpleXMLElement('<fasa_request id="1234567"/>', LIBXML_NOXMLDECL);

?>
@oneseventeen 05-Feb-2011 11:51
When inserting XML DOM Elements inside existing XML DOM Elements that I loaded from an XML file using the following code, none of my new elements were formatted correctly, they just showed up on one line:

<?php
$dom = DOMDocument::load('file.xml');
$dom->formatOutput = true;
//$dom->add some new elements with child nodes somewhere inside the loaded XML using insertBefore();
$dom->saveXML();
//output: everything looks normal but the new nodes are all on one line.
?>

I found I could pass LIBXML_NOBLANKS to the load method and it would reformat the whole document, including my added stuff:
<?php
$dom = DOMDocument::load('file.xml', LIBXML_NOBLANKS);
$dom->formatOutput = true;
//$dom->add some new elements with child nodes somewhere inside the loaded XML using insertBefore();
$dom->saveXML();
//output: everything looks newly formatted, including new nodes
?>

Hope this helps, took me hours of trial and error to figure this out!
zachatwork at gmail dot com 09-Feb-2010 11:30
Note: The LIBXML_NOXMLDECL constant is defined in this library but is not supported by DOMDocument (yet).

See also: http://bugs.php.net/bug.php?id=47137

<?php

print "PHP_VERSION:      ".PHP_VERSION."\n";
print "LIBXML_VERSION:   ".LIBXML_VERSION."\n";
print "LIBXML_NOXMLDECL: ".LIBXML_NOXMLDECL."\n";

$dom = new DomDocument();
$dom->loadXML("<foo />");

# This should work but doesn't.

print "DOMDocument doesn't honor LIBXML_NOXMLDECL:\n";
print $dom->saveXML(null,LIBXML_NOXMLDECL);

# This works, and will still work after the above is fixed.

print "Forwards compatible workaround:\n";
$lines = explode("\n", $dom->saveXML(null, LIBXML_NOXMLDECL), 2);
if(!preg_match('/^\<\?xml/', $lines[0]))
    print $lines[0];
print $lines[1];

?>

PHP_VERSION:      5.3.1-0.dotdeb.1
LIBXML_VERSION:   20632
LIBXML_NOXMLDECL: 2
DOMDocument doesn't honor LIBXML_NOXMLDECL:
<?xml version="1.0"?>
<foo/>
Forwards compatible workaround:
<foo/>


La 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

class 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_external_entity_loader — Get the current external entity loader
  • 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

editor at geekkb.com 27-Apr-2023 02:46
There is an extra \ should be deleted before PHP_VERSION_ID in the code which suconghou posted 2 years ago.

if (PHP_VERSION_ID < 80000) {
    libxml_disable_entity_loader(true);
}
suconghou at gmail dot com 07-Jan-2021 10:27
In PHP 8.0 and later, PHP uses libxml versions from 2.9.0, libxml_disable_entity_loader is deprecated.
so it is now safe to remove all `libxml_disable_entity_loader` calls on php8

if you want Backwards Compatibility

use this snippet

if (\PHP_VERSION_ID < 80000) {
    libxml_disable_entity_loader(true);
}
vavra at 602 dot cz 04-Jan-2018 09:48
If is called
libxml_disable_entity_loader(true);

, it causes that new SoapClient(.) fails with

SOAP-ERROR: Parsing WSDL: Couldn't load from 'D:\path/dm_operations.wsdl' : failed to load external entity "D:\path/dm_operations.wsdl

because this wsdl imports a xsd as an another external file.
Tested on php 7.1.12, win x64.
brendan at bloodbone dot ws 25-Mar-2014 10:23
This also seems to have an impact on <xsl:import /> statements if this is applied when loading XSLT for the XSLTProcessor class.
phofstetter at sensational dot ch 27-Jan-2014 04:36
Be mindful that this also disables url loading in simplexml_load_file() and likely other libxml based functions that deal with URLs
daschtour at me dot com 25-Dec-2013 11:56
This function was reported to be not thread safe. So this might affect php-scripts on the same server.
simonsimcity 29-Feb-2012 06:23
Using this function you can prevent a vulnerable to Local and Remote File Inclusion attacks.

You'll see it in an example where I load and validate the following string:

<!DOCTYPE scan [<!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource=/etc/passwd">]>
<scan>&test;</scan>

One way to prevent that the file in given back is to set this value to 0.
Please take a closer look at the release of symfony 2.0.11


Recupera un array de errores

  • « libxml_disable_entity_loader
  • libxml_get_external_entity_loader »
  • 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)


Get the current external entity loader

  • « libxml_get_errors
  • libxml_get_last_error »
  • PHP Manual
  • Funciones de libxml
  • Get the current external entity loader

libxml_get_external_entity_loader

(PHP 8 >= 8.2.0)

libxml_get_external_entity_loader — Get the current external entity loader

Descripción

libxml_get_external_entity_loader(): ?callable

Get external entity loader previously installed by libxml_set_external_entity_loader().

Parámetros

Esta función no tiene parámetros.

Valores devueltos

The external entity loader previously installed by libxml_set_external_entity_loader(). If that function was never called, or if it was called with null, null will be returned.

Ver también

  • libxml_set_external_entity_loader() - Cambia el cargador externo por defecto de entidades

User Contributed Notes

There are no user contributed notes for this page.


Recupera el último error de libxml

  • « libxml_get_external_entity_loader
  • 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::current — Returns the current element
    • 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::getChildren — Returns the sub-elements of the current element
    • SimpleXMLElement::hasChildren — Checks whether the current element has sub elements
    • SimpleXMLElement::key — Return current key
    • SimpleXMLElement::next — Move to next element
    • SimpleXMLElement::registerXPathNamespace — Crea un contexto prefijo/ns para la siguiente petición XPath
    • SimpleXMLElement::rewind — Rewind to the first element
    • SimpleXMLElement::saveXML — Alias de SimpleXMLElement::asXML
    • SimpleXMLElement::__toString — Returns the string content
    • SimpleXMLElement::valid — Check whether the current element is valid
    • SimpleXMLElement::xpath — Ejecuta una petición XPath sobre los datos XML
  • SimpleXMLIterator — La clase SimpleXMLIterator
  • 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

reibeltel at gmail dot com 16-Feb-2022 05:53
I rewrite the function to convert xml object to array because my case is more simple:

function xmlObjToArr($obj) {

    $array = [];
    foreach($obj as $item){
        $row = [];
        foreach($item as $key => $val){
            $col = array(
                (string)$key => (string)$val
            );
            array_push($row,$col);

        }
        array_push($array,$row);
    }

    return $array;
}
Anonymous 25-Dec-2019 09:10
<?php
function array_to_xml( $array, $xml = null ) {
  if ( is_array( $array ) ) {
    foreach( $array as $key => $value ) {
      if ( is_int( $key ) ) {
        if ( $key == 0 ) {
          $node = $xml;
        } else {
          $parent = $xml->xpath( ".." )[0];
          $node = $parent->addChild( $xml->getName() );
        }
      } else {
        $node = $xml->addChild( $key );
      }
      array_to_xml( $value, $node );
    }
  } else {
    $xml[0] = $array;
  }
}

$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><root></root>" );

array_to_xml( $array, $xml );
echo $xml->asXML();
?>
charles dot a dot dacosta at gmail dot com 15-Nov-2016 09:49
I had to do the following to catch the fact that my simplexml_load_string call was not working right (it was returning empty objects).

$statistik = simplexml_load_string($record,"SimpleXMLElement",LIBXML_NSCLEAN,$ns,TRUE);

    if (($statistik === FALSE) or ($statistik === NULL) or empty($statistik))
    {
        echo "$ctr) STATISTIK ERROR---\n";
        var_dump($statistik);
        echo "\n\n";
        echo "Failed loading XML\n";
        foreach(libxml_get_errors() as $error)
        {
            echo "\n", $error->message;
        }
        die();
    }

before I put the check for "empty()" I was not catching the error.
oleg at mastak dot fi 30-Mar-2016 09:57
Two lines xml2array:

<?php

$xml = simplexml_load_string($xmlstring);
$array = (array) $xml;

?>
Serge 26-Feb-2015 10:58
XML data values should not contain "&" and that need to be replaced by html-entity "&amp;"

You can use this code to replace lonely "&" to "&amp;":

<?php
$sText = preg_replace('#&(?![a-z]{1,6};)#i', '&amp;', $sText);
?>

This will replace just "&" into "&amp;" but dont touches other html-entities like "&nbsp;", "&lt;" etc and, of course, "&amp;".

P.S. In regexp max length is 6 becouse I found that is the maximum length of possible html entity using this code:
<?php
max(array_map('strlen', array_values(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5)))) - 2
?>
minus two is for first "&" and last ";" in an any html entity.
Tim Adam Perez 23-Jan-2014 08:22
XML to Array in a single line:
$array = (array) simplexml_load_string($xml);

Enjoy!
maikel at yuluma dot com 17-Oct-2013 09:02
In reply to  soloman at textgrid dot com,

2 line XML2Array:

$xml = simplexml_load_string($file);
$array = (array)$xml;
dkrnl at yandex dot ru 30-Sep-2013 02:57
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

Usage example: http://github.com/dkrnl/SimpleXMLReader/blob/master/examples/example1.php

<?php

/**
 * Simple XML Reader
 *
 * @license Public Domain
 * @author Dmitry Pyatkov(aka dkrnl) <dkrnl@yandex.ru>
 * @url http://github.com/dkrnl/SimpleXMLReader
 */
class SimpleXMLReader extends XMLReader
{

    /**
     * Callbacks
     *
     * @var array
     */
    protected $callback = array();

    /**
     * Add node callback
     *
     * @param  string   $name
     * @param  callback $callback
     * @param  integer  $nodeType
     * @return SimpleXMLReader
     */
    public function registerCallback($name, $callback, $nodeType = XMLREADER::ELEMENT)
    {
        if (isset($this->callback[$nodeType][$name])) {
            throw new Exception("Already exists callback $name($nodeType).");
        }
        if (!is_callable($callback)) {
            throw new Exception("Already exists parser callback $name($nodeType).");
        }
        $this->callback[$nodeType][$name] = $callback;
        return $this;
    }

    /**
     * Remove node callback
     *
     * @param  string  $name
     * @param  integer $nodeType
     * @return SimpleXMLReader
     */
    public function unRegisterCallback($name, $nodeType = XMLREADER::ELEMENT)
    {
        if (!isset($this->callback[$nodeType][$name])) {
            throw new Exception("Unknow parser callback $name($nodeType).");
        }
        unset($this->callback[$nodeType][$name]);
        return $this;
    }

    /**
     * Run parser
     *
     * @return void
     */
    public function parse()
    {
        if (empty($this->callback)) {
            throw new Exception("Empty parser callback.");
        }
        $continue = true;
        while ($continue && $this->read()) {
            if (isset($this->callback[$this->nodeType][$this->name])) {
                $continue = call_user_func($this->callback[$this->nodeType][$this->name], $this);
            }
        }
    }

    /**
     * Run XPath query on current node
     *
     * @param  string $path
     * @param  string $version
     * @param  string $encoding
     * @return array(SimpleXMLElement)
     */
    public function expandXpath($path, $version = "1.0", $encoding = "UTF-8")
    {
        return $this->expandSimpleXml($version, $encoding)->xpath($path);
    }

    /**
     * Expand current node to string
     *
     * @param  string $version
     * @param  string $encoding
     * @return SimpleXMLElement
     */
    public function expandString($version = "1.0", $encoding = "UTF-8")
    {
        return $this->expandSimpleXml($version, $encoding)->asXML();
    }

    /**
     * Expand current node to SimpleXMLElement
     *
     * @param  string $version
     * @param  string $encoding
     * @param  string $className
     * @return SimpleXMLElement
     */
    public function expandSimpleXml($version = "1.0", $encoding = "UTF-8", $className = null)
    {
        $element = $this->expand();
        $document = new DomDocument($version, $encoding);
        $node = $document->importNode($element, true);
        $document->appendChild($node);
        return simplexml_import_dom($node, $className);
    }

    /**
     * Expand current node to DomDocument
     *
     * @param  string $version
     * @param  string $encoding
     * @return DomDocument
     */
    public function expandDomDocument($version = "1.0", $encoding = "UTF-8")
    {
        $element = $this->expand();
        $document = new DomDocument($version, $encoding);
        $node = $document->importNode($element, true);
        $document->appendChild($node);
        return $document;
    }

}
?>
whyme 28-Dec-2012 09:55
Simple means simple.  If you know the structure and just want the value of a tag:

<?php
$xml = simplexml_load_file($xmlfile);
print $xml->City->Street->Address->HouseColor;
?>

Warning, numbers can come out as strings, empty elements like <HouseColor></HouseColor> come out as array(0)
Laurent Vervisch 24-Jun-2012 10:57
Here is an example of an easy mapping between xml and classes defined by user.

<?php
class XmlClass extends SimpleXMLElement
{
    /**
     * Returns this object as an instance of the given class.
     */
    public function asInstanceOf($class_name)
    {
        // should check that class_name is valid

        return simplexml_import_dom(dom_import_simplexml($this), $class_name);
    }

    public function __call($name, array $arguments)
    {
        echo "magic __call called for method $name on instance of ".get_class()."\n";

        // class could be mapped according $this->getName()
        $class_name = 'Test';

        $instance = $this->asInstanceOf($class_name);
        return call_user_func_array(array($instance, $name), $arguments);
    }
}

class Test extends XmlClass
{
    public function setValue($string)
    {
        $this->{0} = $string;
    }
}

$xml = new XmlClass('<example><test/></example>');
$test = $xml->test->asInstanceOf('Test');
echo get_class($xml->test), "\n";
echo get_class($test), "\n";

$test->setValue('value set directly by instance of Test');
echo (string)$xml->test, "\n";
echo (string)$test, "\n";

$xml->test->setValue('value set by instance of XmlClass and magic __call');
echo (string)$xml->test, "\n";
echo (string)$test, "\n";
?>

XmlClass
Test
value set directly by instance of Test
value set directly by instance of Test
magic __call called for method setValue on instance of XmlClass
value set by instance of XmlClass and magic __call
value set by instance of XmlClass and magic __call
xaviered at gmail dot com 17-May-2012 07:00
Here is a recursive function that will convert a given SimpleXMLElement object into an array, preserving namespaces and attributes.

<?php
function xmlObjToArr($obj) {
        $namespace = $obj->getDocNamespaces(true);
        $namespace[NULL] = NULL;

        $children = array();
        $attributes = array();
        $name = strtolower((string)$obj->getName());

        $text = trim((string)$obj);
        if( strlen($text) <= 0 ) {
            $text = NULL;
        }

        // get info for all namespaces
        if(is_object($obj)) {
            foreach( $namespace as $ns=>$nsUrl ) {
                // atributes
                $objAttributes = $obj->attributes($ns, true);
                foreach( $objAttributes as $attributeName => $attributeValue ) {
                    $attribName = strtolower(trim((string)$attributeName));
                    $attribVal = trim((string)$attributeValue);
                    if (!empty($ns)) {
                        $attribName = $ns . ':' . $attribName;
                    }
                    $attributes[$attribName] = $attribVal;
                }

                // children
                $objChildren = $obj->children($ns, true);
                foreach( $objChildren as $childName=>$child ) {
                    $childName = strtolower((string)$childName);
                    if( !empty($ns) ) {
                        $childName = $ns.':'.$childName;
                    }
                    $children[$childName][] = xmlObjToArr($child);
                }
            }
        }

        return array(
            'name'=>$name,
            'text'=>$text,
            'attributes'=>$attributes,
            'children'=>$children
        );
    }
?>
thedoc8786 at gmail dot com 23-Mar-2012 07:42
FAIL! This function works better than the one I posted below:

<?php
    function toArray($xml) {
        $array = json_decode(json_encode($xml), TRUE);

        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( empty($value) ) $array[$key] = NULL;
            elseif ( is_array($value) ) $array[$key] = toArray($value);
        }

        return $array;
    }
thedoc8786 at gmail dot com 23-Mar-2012 04:19
I know it is over-done, but the following is a super-short example of a XML to Array conversion function (recursive):

<?php
    function toArray(SimpleXMLElement $xml) {
        $array = (array)$xml;

        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( $value instanceof SimpleXMLElement ) {
                $array[$key] = empty($value) ? NULL : toArray($value);
            }
        }
        return $array;
    }
xananax at yelostudio dot com 07-Sep-2011 06:25
None of the XML2Array functions that I found satisfied me completely; Their results did not always fit the project I was working on, and I found none that would account for repeating XML elements (such as
<fields><field/><field/><field/></fields>)
So I rolled out my own; hope it helps someone.
<?php
/**
 * Converts a simpleXML element into an array. Preserves attributes.<br/>
 * You can choose to get your elements either flattened, or stored in a custom
 * index that you define.<br/>
 * For example, for a given element
 * <code>
 * <field name="someName" type="someType"/>
 * </code>
 * <br>
 * if you choose to flatten attributes, you would get:
 * <code>
 * $array['field']['name'] = 'someName';
 * $array['field']['type'] = 'someType';
 * </code>
 * If you choose not to flatten, you get:
 * <code>
 * $array['field']['@attributes']['name'] = 'someName';
 * </code>
 * <br>__________________________________________________________<br>
 * Repeating fields are stored in indexed arrays. so for a markup such as:
 * <code>
 * <parent>
 *     <child>a</child>
 *     <child>b</child>
 *     <child>c</child>
 * ...
 * </code>
 * you array would be:
 * <code>
 * $array['parent']['child'][0] = 'a';
 * $array['parent']['child'][1] = 'b';
 * ...And so on.
 * </code>
 * @param simpleXMLElement    $xml            the XML to convert
 * @param boolean|string    $attributesKey    if you pass TRUE, all values will be
 *                                            stored under an '@attributes' index.
 *                                            Note that you can also pass a string
 *                                            to change the default index.<br/>
 *                                            defaults to null.
 * @param boolean|string    $childrenKey    if you pass TRUE, all values will be
 *                                            stored under an '@children' index.
 *                                            Note that you can also pass a string
 *                                            to change the default index.<br/>
 *                                            defaults to null.
 * @param boolean|string    $valueKey        if you pass TRUE, all values will be
 *                                            stored under an '@values' index. Note
 *                                            that you can also pass a string to
 *                                            change the default index.<br/>
 *                                            defaults to null.
 * @return array the resulting array.
 */
function simpleXMLToArray(SimpleXMLElement $xml,$attributesKey=null,$childrenKey=null,$valueKey=null){

    if($childrenKey && !is_string($childrenKey)){$childrenKey = '@children';}
    if($attributesKey && !is_string($attributesKey)){$attributesKey = '@attributes';}
    if($valueKey && !is_string($valueKey)){$valueKey = '@values';}

    $return = array();
    $name = $xml->getName();
    $_value = trim((string)$xml);
    if(!strlen($_value)){$_value = null;};

    if($_value!==null){
        if($valueKey){$return[$valueKey] = $_value;}
        else{$return = $_value;}
    }

    $children = array();
    $first = true;
    foreach($xml->children() as $elementName => $child){
        $value = simpleXMLToArray($child,$attributesKey, $childrenKey,$valueKey);
        if(isset($children[$elementName])){
            if(is_array($children[$elementName])){
                if($first){
                    $temp = $children[$elementName];
                    unset($children[$elementName]);
                    $children[$elementName][] = $temp;
                    $first=false;
                }
                $children[$elementName][] = $value;
            }else{
                $children[$elementName] = array($children[$elementName],$value);
            }
        }
        else{
            $children[$elementName] = $value;
        }
    }
    if($children){
        if($childrenKey){$return[$childrenKey] = $children;}
        else{$return = array_merge($return,$children);}
    }

    $attributes = array();
    foreach($xml->attributes() as $name=>$value){
        $attributes[$name] = trim($value);
    }
    if($attributes){
        if($attributesKey){$return[$attributesKey] = $attributes;}
        else{$return = array_merge($return, $attributes);}
    }

    return $return;
}
?>
soloman at textgrid dot com 09-Aug-2011 05:06
Three line xml2array:

<?php

$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

?>

Ta da!
streaver91 at gmail dot com 04-May-2011 08:49
The BIGGEST differece between an XML and a PHP array is that in an XML file, the name of elements can be the same even if they are siblings, eg. "<pa><ch /><ch /><ch /></pa>", while in an PHP array, the key of which must be different.

I think the array structure developed by svdmeer can fit for XML, and fits well.

here is an example array converted from an xml file:
array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@text"=>"some text",
)

or if it has childrens, that can be:

array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@items"=>array(
    0=>array(
        "@tag"=>"name","@text"=>"some text"
    )
)

Also, I wrote a function that can change that array back to XML.

<?php
function array2XML($arr,$root) {
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><{$root}></{$root}>");
$f = create_function('$f,$c,$a','
        foreach($a as $v) {
            if(isset($v["@text"])) {
                $ch = $c->addChild($v["@tag"],$v["@text"]);
            } else {
                $ch = $c->addChild($v["@tag"]);
                if(isset($v["@items"])) {
                    $f($f,$ch,$v["@items"]);
                }
            }
            if(isset($v["@attr"])) {
                foreach($v["@attr"] as $attr => $val) {
                    $ch->addAttribute($attr,$val);
                }
            }
        }');
$f($f,$xml,$arr);
return $xml->asXML();
}
?>
phil at dier dot us 19-Jan-2011 11:37
Here's a function I came up with to convert an associative array to XML.  Works for multidimensional arrays as well.

<?php
function assocArrayToXML($root_element_name,$ar)
{
    $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
    $f = create_function('$f,$c,$a','
            foreach($a as $k=>$v) {
                if(is_array($v)) {
                    $ch=$c->addChild($k);
                    $f($f,$ch,$v);
                } else {
                    $c->addChild($k,$v);
                }
            }');
    $f($f,$xml,$ar);
    return $xml->asXML();
}
?>
philipp at strazny dot com 23-Nov-2010 05:33
Here's a quick way to dump the nodeValues from SimpleXML into an array using the path to each nodeValue as key. The paths are compatible with e.g. DOMXPath. I use this when I need to update values externally (i.e. in code that doesn't know about the underlying xml). Then I use DOMXPath to find the node containing the original value and update it.

<?php
function XMLToArrayFlat($xml, &$return, $path='', $root=false)
{
    $children = array();
    if ($xml instanceof SimpleXMLElement) {
        $children = $xml->children();
        if ($root){ // we're at root
            $path .= '/'.$xml->getName();
        }
    }
    if ( count($children) == 0 ){
        $return[$path] = (string)$xml;
        return;
    }
    $seen=array();
    foreach ($children as $child => $value) {
        $childname = ($child instanceof SimpleXMLElement)?$child->getName():$child;
        if ( !isset($seen[$childname])){
            $seen[$childname]=0;
        }
        $seen[$childname]++;
        XMLToArrayFlat($value, $return, $path.'/'.$child.'['.$seen[$childname].']');
    }
}
?>

Use like this:

<?php
$xml = simplexml_load_string(...some xml string...);
$xmlarray = array(); // this will hold the flattened data
XMLToArrayFlat($xml, $xmlarray, '', true);
?>

You can also pull multiple files in one array:

<?php
foreach($files as $file){
    $xml = simplexml_load_file($file);
    XMLToArrayFlat($xml, $xmlarray, $file.':', true);
}
?>
The respective filename/path is thus prefixed to each key.
kristof at viewranger dot com 18-Nov-2010 05:14
If you tried to load an XML file with this, but the CDATA parts were not loaded for some reason, is because you should do it this way:

$xml = simplexml_load_file($this->filename, 'SimpleXMLElement', LIBXML_NOCDATA);

This converts CDATA to String in the returning object.
sherwinterunez at yahoo dot com 01-Sep-2010 11:15
<?php

// Sherwin R. Terunez
//
// This is my own version of XML Object to Array
//

function amstore_xmlobj2array($obj, $level=0) {

    $items = array();

    if(!is_object($obj)) return $items;

    $child = (array)$obj;

    if(sizeof($child)>1) {
        foreach($child as $aa=>$bb) {
            if(is_array($bb)) {
                foreach($bb as $ee=>$ff) {
                    if(!is_object($ff)) {
                        $items[$aa][$ee] = $ff;
                    } else
                    if(get_class($ff)=='SimpleXMLElement') {
                        $items[$aa][$ee] = amstore_xmlobj2array($ff,$level+1);
                    }
                }
            } else
            if(!is_object($bb)) {
                $items[$aa] = $bb;
            } else
            if(get_class($bb)=='SimpleXMLElement') {
                $items[$aa] = amstore_xmlobj2array($bb,$level+1);
            }
        }
    } else
    if(sizeof($child)>0) {
        foreach($child as $aa=>$bb) {
            if(!is_array($bb)&&!is_object($bb)) {
                $items[$aa] = $bb;
            } else
            if(is_object($bb)) {
                $items[$aa] = amstore_xmlobj2array($bb,$level+1);
            } else {
                foreach($bb as $cc=>$dd) {
                    if(!is_object($dd)) {
                        $items[$obj->getName()][$cc] = $dd;
                    } else
                    if(get_class($dd)=='SimpleXMLElement') {
                        $items[$obj->getName()][$cc] = amstore_xmlobj2array($dd,$level+1);
                    }
                }
            }
        }
    }

    return $items;
}

?>
michael dot allen at emp dot shentel dot com 15-Apr-2010 11:06
Here is a very robust SimpleXML parser.  Can be used to load files, strings, or DOM into SimpleXML, or can be used to perform the reverse when handed SimpleXML.

<?php
/**
 * XMLParser Class File
 *
 * This class loads an XML document into a SimpleXMLElement that can
 * be processed by the calling application.  This accepts xml strings,
 * files, and DOM objects.  It can also perform the reverse, converting
 * an SimpleXMLElement back into a string, file, or DOM object.
 */
class XMLParser {
    /**
     * While parsing, parse the supplied XML document.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML document file.
     *
     * @param string $doc the xml document location path
     * @return object
     */
    public static function loadFile($doc) {
        if (file_exists($doc)) {
            return simplexml_load_file($doc);
        } else {
            throw new Exception ("Unable to load the xml file " .
                                 "using: \"$doc\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML string.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML string.
     *
     * @param string $string the xml document string
     * @return object
     */
    public static function loadString($string) {
        if (isset($string)) {
            return simplexml_load_string($string);
        } else {
            throw new Exception ("Unable to load the xml string " .
                                 "using: \"$string\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML DOM node.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML DOM node.
     *
     * @param object $dom the xml DOM node
     * @return object
     */
    public static function loadDOM($dom) {
        if (isset($dom)) {
            return simplexml_import_dom($dom);
        } else {
            throw new Exception ("Unable to load the xml DOM node " .
                                 "using: \"$dom\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the SimpleXMLElement.
     *
     * Sets up a XML file, string, or DOM object based on success of
     * parsing the XML DOM node.
     *
     * @param object $path the xml document location path
     * @param string $type the return type (string, file, dom)
     * @param object $simplexml the simple xml element
     * @return mixed
     */
    public static function loadSXML($simplexml, $type, $path) {
        if (isset($simplexml) && isset($type)) {
        switch ($type) {
            case 'string':
                return $simplexml->asXML();
            break;
            case 'file':
                if (isset($path)) {
                    return $simplexml->asXML($path);
                } else {
                    throw new Exception ("Unable to create the XML file. Path is missing or" .
                                         "is invalid: \"$path\"", E_USER_ERROR);
                }
            break;
            case 'dom':
                return dom_import_simplexml($simplexml);
            break;
        }
        } else {
            throw new Exception ("Unable to load the simple XML element " .
                                 "using: \"$simplexml\"", E_USER_ERROR);
        }
    }
}
?>
emmanuel 17-Feb-2010 10:21
dynamic sql in php using xml:

test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<sql>
    <statement>
        SELECT * FROM USERS
        <call criteria="byId">WHERE id = %d</call>
        <call criteria="byUsername">WHERE username = "%s"</call>;
    </statement>
</sql>

index.php:
<?php
function callMe($param) {
    $search = array('byUsername' => 'dynsql');

    if (isset($search[$param[1]])) {
        return sprintf($param[2], $search[$param[1]]);
    }

    return "";
}

$xml = simplexml_load_file("test.xml");
$string = $xml->statement->asXML();
$string = preg_replace_callback('/<call criteria="(\w+)">(.*?)<\/call>/', 'callMe', $string);
$node = simplexml_load_string($string);
echo $node;
?>

obviously, this example can be improved [in your own code.]
mahmutta at gmail dot com 20-Jan-2010 12:58
while using simple xml and get double or float int value from xml object for using math operations (+ * - / ) some errors happens on the operation, this is because of simple xml returns everythings to objects.
exmple;

<?php

$name = "somestring";
$size = 11.45;
$xml = '
<xml>
 <name>somestring</name>
 <size>11.45</size>
</xml>';

$xmlget = simplexml_load_string($xml)

echo $xml->size*2;    // 20  its false
// ($xml->size is an object (int)11 and  (45) )

// this is true
echo $size*2;            // 22.90
echo (float)$size*2;   // 22.90
?>
antoine dot rabanes at gmail dot com 16-Oct-2009 07:22
if for some reasons you need the string value instead of the simpleXML Object you can cast the return value as a string.

exemple:

<?php
$all_api_call = simplexml_load_file($url);
$all_api = array();
$all_api = $all_api_call->result;
$list_all_api_name = array();
$i = 0;
foreach ($all_api->children() as $funcky_function)
{
    $string_tmp = (string )$funcky_function->function;
    $list_all_api_name[$i++] = $putain;
}
?>

...
walter 12-Jun-2009 07:58
Working fix for the infamous SimpleXML + memcache bug.

Improves code at http://tinyurl.com/bmoon-simplexml to actually work for arbitrary-depth structures.  (Because neither the function nor the json_decode(json_encode($obj)) hack listed there worked for me.)

There's probably some superfluous code in here that could be improved on -- but it works!

<?php
 # convert a structure that may include objects to a pure
 # array-based structure (that can be stored in memcache)
 #  ... includes support for simplexml!
 # (nb: may have problems with infinite recursive structs)
 function enforce_array($obj) {
  $array = (array)$obj;
  if(empty($array)) {
   $array = '';
  }
  else {
   foreach($array as $key=>$value) {
    if(!is_scalar($value)) {
     if(is_a($value,'SimpleXMLElement')) {
      $tmp = memcache_objects_to_array($value);
      if(!is_array($tmp)) {
       $tmp = ''.$value;
      }
      $array[$key] = $tmp;
     }
     else {
      $array[$key] = enforce_array($value);
     }
    }
    else {
     $array[$key] = $value;
    }
   }
  }
  return $array;
 }
?>
mail at kleineedv dot de 28-Apr-2009 12:37
I had a problem with simplexml reading nodes from an xml file. It always return an SimpleXML-Object but not the text inside the node.

Example:
<?xml version="1.0" encoding="UTF-8"?>
<Test>
    <Id>123</Id>
</Test>

Reading this xml into a variable called $xml and then doing the following
<?php
$myId = $xml->Id;
?>
Did not return 123 in $myId, but instead I got a SimpleXMLElement Object.

The solution is simple, when you know it. Use explicit string conversion.
<?php
$myId = (string)$xml->Id;
?>
oscargodson at gmail dot com 25-Jan-2009 03:05
To add to what others have said, you can't directly put a $_GET or $_POST value into a variable then into an attribute using SimpleXML. You must first convert it to an integer.

This will NOT work

<?php
      $page_id = $_GET['id'];
      echo $xml->page[$page_id]
?>

You will get something like:
Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/mysite/index.php on line 10

However, this WILL work and is much simpler then using (string) or other methods.
<?php
   $page_id = intval($_GET['id']);
   echo $xml->page[$page_id]
?>
bxt at die-optimisten dot net 26-Nov-2008 07:47
Addition to QLeap's post:
SimpleXML will return a reference to an object containing the node value and you can't use references in session variables as there is no feasible way to restore a reference to another variable.

This won't work too:
$val=$this->xml->node->attributes()->name;
echo $array[$val]; // will cause a warning because of the wrong index type.

You have to convert/cast to a String first:
echo $array[(string)$val];

This will work as expected, because converting will call the __toString() method. Therefor echo works too:
echo $val; // will display the name
QLeap 18-Nov-2008 02:27
Storing SimpleXMLElement values in $_SESSION does not work. Saving the results as an object or individual elements of the object will result in the dreaded "Warning: session_start() [function.session-start]: Node no longer exists" error.

For example, this does not work:

    $xml  = new SimpleXMLElement($page);
    $country  = $xml->Response->Placemark->AddressDetails->Country->CountryNameCode;
    $_SESSION['country'] = $country;

This will work:

    $_SESSION['country'] = (string) $country;
gwhitescarver at yahoo dot com 11-Sep-2008 01:02
Moving some code from a PHP 5.2.6 / Windows environment to a 5.2.0 / Linux environment, I somehow lost access to a plain text node within a SimpleXML Object.  On a var_dump of $xml_node, a [0] element was shown as the string '12'.  However, $xml_node[0] was evaluating NULL in 5.2.0.  You can see below the code change I made, pulling my data out of the raw XML with a regular expression.  Hope this is useful to someone.

//In some versions of PHP it seems we cannot access the [0] element of a SimpleXML Object.  Doesn't work in 5.2.0:
//$count = $xml_node[0];
//grab the raw XML:
$count = ($xml_node->asXML());
//pull out the number between the closing and opening brace of the xml:
$count = preg_replace('/.*>(\d*)<.*/', '$1', $count);
charlie at blankcanvasstudios dot com 14-Aug-2008 11:21
Optimizing aalaap at gmail dot com's php

<?php
function is_rss($feedxml) {
    @$feed = simplexml_load_string($feedxml);

    return ($feed->channel->item)?true:false;
}

function is_atom($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);
    ($feed->entry):true:false;
}
?>
aalaap at gmail dot com 30-Jun-2008 06:58
Here are two quick and dirty functions that use SimpleXML to detect if a feed xml is RSS or ATOM:

<?php
function is_rss($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);

    if ($feed->channel->item) {
        return true;
    } else {
        return false;
    }
}

function is_atom($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);

    if ($feed->entry) {
        return true;
    } else {
        return false;
    }
}
?>

The functions take in the full text feed (retrieved via cURL, for example) and return a true or a false based on the result.


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

Josef 01-Sep-2021 06:54
How to find out if a Node exists:

<?xml version='1.0' standalone='yes'?>
<book>
  <author>Josef</author>
  <isbn></isbn>
</book>

empty($xml->isbn) will be true
isset($xml->isbn) will be true

empty($xml->title) will be true
isset($xml->title) will be false
Anonymous 22-Aug-2017 12:35
If your xml string contains booleans encoded with "0" and "1", you will run into problems when you cast the element directly to bool:

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<values>
    <truevalue>1</truevalue>
    <falsevalue>0</falsevalue>
</values>
XML;
$values = new SimpleXMLElement($xmlstr);
$truevalue = (bool)$values->truevalue; // true
$falsevalue = (bool)$values->falsevalue; // also true!!!

Instead you need to cast to string or int first:

$truevalue = (bool)(int)$values->truevalue; // true
$falsevalue = (bool)(int)$values->falsevalue; // false
rowan dot collins at gmail dot com 04-Jun-2015 06:58
There is a common "trick" often proposed to convert a SimpleXML object to an array, by running it through json_encode() and then json_decode(). I'd like to explain why this is a bad idea.

Most simply, because the whole point of SimpleXML is to be easier to use and more powerful than a plain array. For instance, you can write <?php $foo->bar->baz['bing'] ?> and it means the same thing as <?php $foo->bar[0]->baz[0]['bing'] ?>, regardless of how many bar or baz elements there are in the XML; and if you write <?php (string)$foo->bar[0]->baz[0] ?> you get all the string content of that node - including CDATA sections - regardless of whether it also has child elements or attributes. You also have access to namespace information, the ability to make simple edits to the XML, and even the ability to "import" into a DOM object, for much more powerful manipulation. All of this is lost by turning the object into an array rather than reading understanding the examples on this page.

Additionally, because it is not designed for this purpose, the conversion to JSON and back will actually lose information in some situations. For instance, any elements or attributes in a namespace will simply be discarded, and any text content will be discarded if an element also has children or attributes. Sometimes, this won't matter, but if you get in the habit of converting everything to arrays, it's going to sting you eventually.

Of course, you could write a smarter conversion, which didn't have these limitations, but at that point, you are getting no value out of SimpleXML at all, and should just use the lower level XML Parser functions, or the XMLReader class, to create your structure. You still won't have the extra convenience functionality of SimpleXML, but that's your loss.
jishcem at gmail dot com 12-Mar-2013 07:31
For me it was easier to use arrays than objects,

So, I used this code,

$xml = simplexml_load_file('xml_file.xml');

$json_string = json_encode($xml);

$result_array = json_decode($json_string, TRUE);

Hope it would help someone
gkokmdam at zonnet dot nl 23-Feb-2011 01:54
A quick tip on xpath queries and default namespaces. It looks like the XML-system behind SimpleXML has the same workings as I believe the XML-system .NET uses: when one needs to address something in the default namespace, one will have to declare the namespace using registerXPathNamespace and then use its prefix to address the otherwise in the default namespace living element.

<?php
$string = <<<XML
<?xml version='1.0'?>
<document xmlns="http://www.w3.org/2005/Atom">
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);
$xml->registerXPathNamespace("def", "http://www.w3.org/2005/Atom");

$nodes = $xml->xpath("//def:document/def:title");

?>
kdos 31-Jan-2011 05:32
Using stuff like: is_object($xml->module->admin) to check if there actually is a node called "admin", doesn't seem to work as expected, since simplexml always returns an object- in that case an empty one  - even if a particular node does not exist.
For me good old empty() function seems to work just fine in such cases.

Cheers
Max K. 20-Jun-2010 02:38
From the README file:

SimpleXML is meant to be an easy way to access XML data.

SimpleXML objects follow four basic rules:

1) properties denote element iterators
2) numeric indices denote elements
3) non numeric indices denote attributes
4) string conversion allows to access TEXT data

When iterating properties then the extension always iterates over
all nodes with that element name. Thus method children() must be
called to iterate over subnodes. But also doing the following:
foreach ($obj->node_name as $elem) {
  // do something with $elem
}
always results in iteration of 'node_name' elements. So no further
check is needed to distinguish the number of nodes of that type.

When an elements TEXT data is being accessed through a property
then the result does not include the TEXT data of subelements.

Known issues
============

Due to engine problems it is currently not possible to access
a subelement by index 0: $object->property[0].
ie dot raymond at gmail dot com 01-Apr-2010 03:07
If you need to output valid xml in your response, don't forget to set your header content type to xml in addition to echoing out the result of asXML():

<?php

$xml=simplexml_load_file('...');
...
...xml stuff
...

//output xml in your response:
header('Content-Type: text/xml');
echo $xml->asXML();
?>
php at keith tyler dot com 23-Dec-2009 12:57
[Editor's Note: The SimpleXMLIterator class, however, does implement these methods.]

While SimpleXMLElement claims to be iterable, it does not seem to implement the standard Iterator interface functions like ::next and ::reset properly. Therefore while foreach() works, functions like next(), current(), or each() don't seem to work as you would expect -- the pointer never seems to move or keeps getting reset.
radams at circlepix com 24-Apr-2009 10:52
To test whether an element exists:

<?php

    $xml = <<<EOT
<?xml version='1.0' standalone='yes'?>
<root>
    <test1></test1>
    <test2 />
    <test4> </test4>
</root>
EOT;

    $xmlDoc = new SimpleXMLElement($xml);

echo "Test1: \n";
var_dump($xmlDoc->test1);
echo "\n(" . (bool)$xmlDoc->test1 . ")";
echo "\n\n";

echo "Test2: \n";
var_dump($xmlDoc->test2);
echo "\n(" . (bool)$xmlDoc->test2 . ")";
echo "\n\n";

echo "Test3: \n";
var_dump($xmlDoc->test3);
echo "\n(" . (bool)$xmlDoc->test3 . ")";
echo "\n\n";

echo "Test4: \n";
var_dump($xmlDoc->test4);
echo "\n(" . (bool)$xmlDoc->test4 . ")";
echo "\n\n";

?>

The var_dumps for test1, test2, and test3 are identical, but the (bool) test gives a '1' for test1 and test2, and a '' for test3.


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

class SimpleXMLElement {
/* Métodos */
public __construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = 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 current(): SimpleXMLElement
public getDocNamespaces(bool $recursive = false, bool $from_root = true): array
public getName(): string
public getNamespaces(bool $recursive = false): array
public getChildren(): ?SimpleXMLElement
public hasChildren(): bool
public key(): string
public next(): void
public registerXPathNamespace(string $prefix, string $ns): bool
public rewind(): void
public __toString(): string
public valid(): bool
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::current — Returns the current element
  • 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::getChildren — Returns the sub-elements of the current element
  • SimpleXMLElement::hasChildren — Checks whether the current element has sub elements
  • SimpleXMLElement::key — Return current key
  • SimpleXMLElement::next — Move to next element
  • SimpleXMLElement::registerXPathNamespace — Crea un contexto prefijo/ns para la siguiente petición XPath
  • SimpleXMLElement::rewind — Rewind to the first element
  • SimpleXMLElement::saveXML — Alias de SimpleXMLElement::asXML
  • SimpleXMLElement::__toString — Returns the string content
  • SimpleXMLElement::valid — Check whether the current element is valid
  • SimpleXMLElement::xpath — Ejecuta una petición XPath sobre los datos XML

User Contributed Notes

ohcc at 163 dot com 12-Jun-2023 03:28
You can remove SimpleXMLElement nodes using php's unset() language construct.

<?php
    $xml = <<<'EOT'
<users>
    <user>
        <name>orange</name>
        <sex>male</sex>
        <homepage>wuxiancheng.cn</homepage>
    </user>
    <user>
        <name>tangerine</name>
        <sex>male</sex>
        <homepage>51-n.com</homepage>
    </user>
</users>
EOT;
    $sxe = new SimpleXMLElement($xml);
    // This will remove the first user node
    unset($sxe->user[0]);
    // This will remove all user nodes
    unset($sxe->user);
    echo $sxe->asXML();
?>
Patanjali 15-Oct-2020 02:20
Further to rmirabelle's comment, to compare two SimpleXML elements, do the comparison between the objects returned by the dom_import_simplexml function, as per:

<?php
if(dom_import_simplexml($simplexml_element_1)===dom_import_simplexml($simplexml_element_2)){
  ...
 }
?>

You must ensure that both are SimpleXML elements before conversion to DOM objects.
guilhermeasn at yahoo dot com dot br 15-Jan-2020 08:09
Class with a method to transform array or object to XML:

class MakeXML {

    public static function array_obj_to_xml($data, \SimpleXMLElement &$xmlObj) {
        foreach((array) $data as $key => $value) {
            if(is_numeric($key)) {
                $key = "n" . $key;
            }
            if(is_array($value) or is_object($value)) {
                $subnode = $xmlObj->addChild($key);
                self::array_obj_to_xml($value, $subnode);
            } else {
                $xmlObj->addChild($key, htmlspecialchars($value));
            }
        }
    }

}

Example:

$object = new \stdClass();
$object->example = "Try this class";

$objxml = new \SimpleXMLElement('<API/>');
MakeXML::array_obj_to_xml($objxml, $objxml);
echo $objxml->asXML();
Budu 13-May-2018 07:17
public function crearXml(){
        $pruebaXml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<Root></Root>
XML;
$example = new SimpleXMLElement($pruebaXml); //Crea un nuevo objeto SimpleXMLElement
        $example->addAttribute('id', '1');//Añade un elemento hijo al nodo XML

        while( $nodo = $this->iteraciones->iterate()){
            $nodos = $example->addChild('Nodo');
            $nodos->addAttribute('id',$nodo->getId());
            $acierto = $nodos->addChild('nuevoHijo', $nodo->getX());
        }
        $miFichero = $example->asXML();//Retorna un string XML correcto basado en un elemento SimpleXML
        $miArchivo = fopen("xml/example.xml", "w+");//Abre un fichero o un URL
        fwrite($miArchivo, $miFichero);//Escritura archivo
    }
CameronXie 11-Dec-2017 10:48
Map xml to array (with attributes)

<?php declare(strict_types=1);

/**
 * @param SimpleXMLElement $xml
 * @return array
 */
function xmlToArray(SimpleXMLElement $xml): array
{
    $parser = function (SimpleXMLElement $xml, array $collection = []) use (&$parser) {
        $nodes = $xml->children();
        $attributes = $xml->attributes();

        if (0 !== count($attributes)) {
            foreach ($attributes as $attrName => $attrValue) {
                $collection['attributes'][$attrName] = strval($attrValue);
            }
        }

        if (0 === $nodes->count()) {
            $collection['value'] = strval($xml);
            return $collection;
        }

        foreach ($nodes as $nodeName => $nodeValue) {
            if (count($nodeValue->xpath('../' . $nodeName)) < 2) {
                $collection[$nodeName] = $parser($nodeValue);
                continue;
            }

            $collection[$nodeName][] = $parser($nodeValue);
        }

        return $collection;
    };

    return [
        $xml->getName() => $parser($xml)
    ];
}
kurtbr at gmail dot com 31-May-2017 02:58
Here is a helper class to convert a PHP array to XML
You would call it doing the following:

<?php
$xml = new Xml();
$xml-> generateXmlFromArray($array, 'entities', 'entity');
?>

<?php
class Xml
{
    public function getXmlFromArray($value, \SimpleXMLElement &$xmlElement, $entity, $starting = null)
    {

        $handleValue = function($value){
            if(is_string($value)){
                $value = htmlspecialchars($value);
            }
            return $value;
        };
        $addChild = function($name, $value, &$subNode = null)use(&$xmlElement, $handleValue, $entity){
            if(is_array($value)){
                if(!$subNode instanceof \SimpleXMLElement){
                    $currentKey = key($value);
                    $initialValue = null;
                    if(is_numeric($currentKey)){
                        if(!is_array($value[$currentKey])){
                            $initialValue = $value[$currentKey];
                            unset($value[$currentKey]);
                        }
                    }
                    $subNode = $xmlElement->addChild($name, $initialValue);
                }
                $this->getXmlFromArray($handleValue($value), $subNode, $name);
            } else {
                $xmlElement->addChild($name, $handleValue($value));
            }
        };

        if(is_array($value))
        {
            if(is_numeric(key($value))){
                $setSubNodePrimitiveValue = function($value)use(&$xmlElement, $entity, $handleValue){
                    $value = $handleValue($value);
                    $children = $xmlElement->children();
                    $children[] = $value;
                };
                foreach ($value as $item)
                {
                    if(!is_array($item)){
                        $setSubNodePrimitiveValue($item);
                    } else {
                        if($starting === true){
                            $addChild($entity, $item);
                        } else {
                            $addChild($entity, $item, $xmlElement);
                        }
                    }
                }
            } else {
                foreach ($value as $subEntity => $subEntityItem)
                {
                    $addChild($subEntity, $subEntityItem);
                }
            }
        } else {
            $xmlElement->addChild($entity, $handleValue($value));
        }
    }

    /**
     * @param array $array
     * @param string $openingTag
     * @param string $entity
     * @param string $nameSpace
     * @param bool $isPrefixed
     * @return \SimpleXMLElement
     */
    public function generateXmlFromArray(array $array, string $openingTag, string $entity, $nameSpace = '', $isPrefixed = false)
    {
        $xmlString = '<'.$openingTag.'></'.$openingTag.'>';
        $xml = new \SimpleXMLElement($xmlString, LIBXML_NOERROR, false, $nameSpace, $isPrefixed);
        $this->getXmlFromArray($array, $xml, $entity, true);
        return $xml;
    }

    /**
     * @param string $xml
     * @return bool
     */
    public function validateXml(string $xml)
    {
        $dom = new \DOMDocument();
        $dom->loadXML($xml);
        return $dom->validate();
    }

    public function loadXmlPathAsArray(string $xmlPath)
    {
        $xml   = simplexml_load_file($xmlPath);
        $array = json_decode(json_encode($xml), TRUE);
        return (array)$array;
    }

    /**
     * @param string $xmlString
     * @return array
     */
    public function loadXmlStringAsArray(string $xmlString)
    {
        $array = (array) @simplexml_load_string($xmlString);
        if(!$array){
            $array = (array) @json_decode($xmlString, true);
        } else{
            $array = (array)@json_decode(json_encode($array), true);
        }
        return $array;
    }

    /**
     * @param string $xmlString
     * @return \SimpleXMLElement
     */
    public function loadXmlString(string $xmlString)
    {
        return @simplexml_load_string($xmlString);
    }
}
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:54
See previous two parts to get better understanding of how these tricks works. Example shown here refers to part two. (Sorry, length limitation)

3. Tricks
<?php
        // The real profit is in combination of property and array accesses and unset($someNode->{0}) trick -
        // it allows you to remove whatever node you want:
        unset($rootNode->{'div'}[2]);   // remove node with * mark (text*)

        // Another trick is removing child node using child node object
        $newChildNode = $rootNode->addChild('div','text**');    // Create
        unset($newChildNode->{0});      // Remove, node removed from parent object too!

        echo "--2--\n".$rootNode->asXML();
        /*
        <xml_root>complex node
                <type_one>renewed node 1</type_one>
                <type_two>node 3</type_two>
                <type_one>node 2</type_one>
                <div>text</div>
                <div>text</div>
                <div>text</div>
        </xml_root>
        */
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:48
How to view, edit and remove elements.
Speaking in terms of CRUD style, there is no methods to read, edit and remove nodes. But it is possible.

2. How child nodes works (understanding)
<?php
        echo "Exercise 2 \n";

        $rootNode = new SimpleXMLElement('<xml_root>complex node</xml_root>');  // Create root node
        $childNode1 = $rootNode->addChild('type_one','node 1');                 // Create child node 1 with name 'type_one'
        $childNode2 = new SimpleXMLElement('<type_one>node 2</type_one>');      // Create child node 2 with name 'type_one'
        $childNode3 = new SimpleXMLElement('<type_two>node 3</type_two>');      // Create child node 3 with name 'type_two' (different!)
        // Now $rootNode has only one children because other child nodes was created separately
        // Lets paste child node to root node
        echo $childNode1;

        $rootNode->{'type_one'} = $childNode2;      // Note that the property name is 'type_one'
        $rootNode->{'type_two'} = $childNode3;      // Note that the property name is 'type_two'
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            string(6) "node 2"
            ["type_two"]=>
            string(6) "node 3"
        }
        */
        // We see that "node 1" disappeared, that's because assigning one node to some property of another in not a magic.
        // To be clear, the real calls looks like:
        $rootNode->{'type_one'}[0] = (string) $childNode2;
        $rootNode->{'type_two'}[0] = (string) $childNode3;
        // Explanation:
        // A: (string)
        // It means that you can't assign node itself, only its string representation because assigned node will be casted to string anyway.
        // It also means that tag name of assigned node doesn't matter - its name will be whatever name you specified in {} braces.
        // B: [0]
        // The array access operator ([0]) means that each tag name (type_one and type_two) has its own collection with integer indexes.
        // If you want to add another tag with same name, you should increment index:
        $rootNode->{'type_one'}[1] = $childNode2;
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            array(2) {
                [0]=>
                string(6) "node 2"
                [1]=>
                string(6) "node 2"
            }
            ["type_two"]=>
            string(6) "node 3"
        }
        */

        // Note 1. The value of $childNode1 has been changed to "node 1" - that's because the child node, returned from addChild() method
        // is referenced with parent node. If you change its content in one side - it changes in other side too:
        $childNode1->{0} = 'renewed node 1';
        // But it won't happen with $childNode2 - it is single and has no reference with parent node:
        $childNode2->{0} = 'renewed node 2';
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            array(2) {
                [0]=>
                string(14) "renewed node 1"
                [1]=>
                string(6) "node 2"
            }
            ["type_two"]=>
            string(6) "node 3"
        }
        */

        // Note 2. When you added child nodes, the parent node's string content is still alive, var_dump doesn't show it,
        // but you can see through echoing XML:
        echo "--1--\n".$rootNode->asXML();
        /*
        <xml_root>complex node <--------- here!
                <type_one>renewed node 1</type_one>
                <type_two>node 3</type_two>
                <type_one>node 2</type_one>
        </xml_root>
        */
        // See 'complex node'? Bad news that you can't change string content anymore, if we try to call `$rootNode->{0} = 'something'` -
        // it overrides all content - both string and child nodes! I don't know how to write to string content only in that case.
        // But still you can read string content and remove entire node as described above.

        // So the following statements gives same result, except $result variable value:
        $someNode = new SimpleXMLElement('<div>text</div>');
        $result = $rootNode->addChild('div','text');                    // $result is SimpleXMLElement
        $result = $rootNode->addChild($someNode->getName(),$someNode);  // $result is SimpleXMLElement
        $result = $rootNode->{'div'}[] = 'text*';                       // $result is string 'text*'
        $result = $rootNode->{$someNode->getName()}[] = $someNode;      // $result is string 'text'
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:45
How to view, edit and remove elements.
Speaking in terms of CRUD style, there is no methods to read, edit and remove nodes. But it is possible.

1. How to work with single node and its value (basics)
<?php
        echo "Exercise 1 \n";
        // Create
        $someNode = new SimpleXMLElement('<xml_root>simple node</xml_root>');
        // Read
        echo $someNode->{0} ."\n";      // Echoes "simple node"
        echo $someNode ."\n";           // Echoes "simple node", might be used for read case too
        // Edit
        $someNode->{0} = 'new value';
        echo $someNode->{0} ."\n";      // Echoes "new value", value is changed!
        // Remove
        unset($someNode->{0});

        // Don't touch this node anymore otherwise it will throw a warning:
        // "Warning:  SimpleXMLElement::asXML(): Node no longer exists in <...> on line <...>"
        // echo $someNode ."\n";      // Throws the warning

        // Recap: property access to zero property ($someNode->{0}) is the way to read and edit string content of the node AND
        // to remove the node itself
?>
frame at dynamiccreated dot de 14-Jun-2013 01:36
Important note I miss here in the documentation:

SimpleXML supports Array/Iteration-Methods. Therefore it is possible to

add attributes
edit attributes
remove attributes

add nodes
edit nodes
remove nodes

This is the reason why SimpleXML provides only add-methods not deleting- or editing-methods. We also need this methods because SimpleXML acts as a normal class and
new member will not converted to a new node.

Deleting a node seems not to be possible within a foreach-loop. The reason is simple. To do that we need a valid key, but the Iterator only gives us a "understandable feedback" on which node we are working on: the tag name.

So this will not work:

<?php
foreach($doc->seg as $key => $seg)
{
    if((string)$seg['id'] === 'whatever')
    {
        unset($seg); // only clears local copy
        unset($seg[$key]); // wrong index "seg"
    }
}
?>

But this, eg. will work:
<?php
unset($doc->seg[2]);
?>

In case of doubt always do a print_r/var_dump(). It nicely shows the real linked indexes.
Yukull 15-Feb-2013 01:59
xml to object conversion function :
<?php
/**
    @param:
        $xml: SimpleXMLElement
        $force: set to true to always create 'text', 'attribute', and 'children' even if empty
    @return
        object with attributs:
            (string) name: XML tag name
            (string) text: text content of the attribut name
            (array) attributes: array witch keys are attribute key and values are attribute value
            (array) children: array of objects made with xml2obj() on each child
**/
function xml2obj($xml,$force = false){

    $obj = new StdClass();

    $obj->name = $xml->getName();

    $text = trim((string)$xml);
    $attributes = array();
    $children = array();

    foreach($xml->attributes() as $k => $v){
        $attributes[$k]  = (string)$v;
    }

    foreach($xml->children() as $k => $v){
        $children[] = xml2obj($v,$force);
    }

    if($force or $text !== '')
        $obj->text = $text;

    if($force or count($attributes) > 0)
        $obj->attributes = $attributes;

    if($force or count($children) > 0)
        $obj->children = $children;

    return $obj;
}
?>
heaver 31-May-2012 07:33
XML to JSON conversion without '@attributes'
<?php
function XML2JSON($xml) {

        function normalizeSimpleXML($obj, &$result) {
            $data = $obj;
            if (is_object($data)) {
                $data = get_object_vars($data);
            }
            if (is_array($data)) {
                foreach ($data as $key => $value) {
                    $res = null;
                    normalizeSimpleXML($value, $res);
                    if (($key == '@attributes') && ($key)) {
                        $result = $res;
                    } else {
                        $result[$key] = $res;
                    }
                }
            } else {
                $result = $data;
            }
        }
        normalizeSimpleXML(simplexml_load_string($xml), $result);
        return json_encode($result);
    }
?>
demian dot katz at villanova dot edu 29-Mar-2012 05:50
Here is a more namespace-aware version of the earlier function for attaching one SimpleXMLElement to another.  I'm sure it could still be further improved (right now it generates some redundant xmlns definitions), but it seems to be working well enough for my purposes so far.

function SimpleXMLElement_append($parent, $child)
{
    // get all namespaces for document
    $namespaces = $child->getNamespaces(true);

    // check if there is a default namespace for the current node
    $currentNs = $child->getNamespaces();
    $defaultNs = count($currentNs) > 0 ? current($currentNs) : null;
    $prefix = (count($currentNs) > 0) ? current(array_keys($currentNs)) : '';
    $childName = strlen($prefix) > 1
        ? $prefix . ':' . $child->getName() : $child->getName();

    // check if the value is string value / data
    if (trim((string) $child) == '') {
        $element = $parent->addChild($childName, null, $defaultNs);
    } else {
        $element = $parent->addChild(
            $childName, htmlspecialchars((string)$child), $defaultNs
        );
    }

    foreach ($child->attributes() as $attKey => $attValue) {
        $element->addAttribute($attKey, $attValue);
    }
    foreach ($namespaces as $nskey => $nsurl) {
        foreach ($child->attributes($nsurl) as $attKey => $attValue) {
            $element->addAttribute($nskey . ':' . $attKey, $attValue, $nsurl);
        }
    }

    // add children -- try with namespaces first, but default to all children
    // if no namespaced children are found.
    $children = 0;
    foreach ($namespaces as $nskey => $nsurl) {
        foreach ($child->children($nsurl) as $currChild) {
            SimpleXMLElement_append($element, $currChild);
            $children++;
        }
    }
    if ($children == 0) {
        foreach ($child->children() as $currChild) {
            SimpleXMLElement_append($element, $currChild);
        }
    }
}
saganmarketing.com 12-Mar-2012 12:27
Parsing an invalid XML string through SimpleXML causes the script to crash completely (usually) therefore it is best to make sure the XML is valid before parsing with something like this:

// Must be tested with ===, as in if(isXML($xml) === true){}
// Returns the error message on improper XML
function isXML($xml){
    libxml_use_internal_errors(true);

    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->loadXML($xml);

    $errors = libxml_get_errors();

    if(empty($errors)){
        return true;
    }

    $error = $errors[0];
    if($error->level < 3){
        return true;
    }

    $explodedxml = explode("r", $xml);
    $badxml = $explodedxml[($error->line)-1];

    $message = $error->message . ' at line ' . $error->line . '. Bad XML: ' . htmlentities($badxml);
    return $message;
}
Anonymous 14-Nov-2011 12:34
Warning to anyone trying to parse XML with a key name that includes a hyphen ie.)
<subscribe>
    <callback-url>example url</callback-url>
</subscribe>

In order to access the callback-url you will need to do something like the following:
<?php
$xml = simplexml_load_string($input);
$callback = $xml->{"callback-url"};
?>
If you attempt to do it without the curly braces and quotes you will find out that you are returned a 0 instead of what you want.
juanfhj at gmail dot spam dot me dot not dot com 13-Aug-2011 11:01
To access the underlying element as a string, it's necessary to make the cast $x = (string)$my_xml_element.
dans at dansheps dot com 22-Apr-2011 12:06
I created a little function to parse the simple XML into a structure which is easier to iterate(I believe anyways) than the simpleXML node structure.

<?php
function parseSimpleXML($xmldata)
    {
        $childNames = array();
        $children = array();

        if( $xmldata->count() !== 0 )
        {
            foreach( $xmldata->children() AS $child )
            {
                $name = $child->getName();

                if( !isset($childNames[$name]) )
                {
                    $childNames[$name] = 0;
                }

                $childNames[$name]++;
                $children[$name][] = $this->parseSimpleXML($child);
            }
        }

        $returndata = new XMLNode();
        if( $xmldata->attributes()->count() > 0 )
        {
            $returndata->{'@attributes'} = new XMLAttribute();
            foreach( $xmldata->attributes() AS $name => $attrib )
            {
                $returndata->{'@attributes'}->{$name} = (string)$attrib;
            }
        }

        if( count($childNames) > 0 )
        {
            foreach( $childNames AS $name => $count )
            {
                if( $count === 1 )
                {
                    $returndata->{$name} = $children[$name][0];
                }
                else
                {
                    $returndata->{$name} = new XMLMultiNode();
                    $counter = 0;
                    foreach( $children[$name] AS $data )
                    {
                        $returndata->{$name}->{$counter} = $data;
                        $counter++;
                    }
                }
            }
        }
        else
        {
            if( (string)$xmldata !== '' )
            {
                $returndata->{'@innerXML'} = (string)$xmldata;
            }
        }
        return $returndata;
    }
?>
ms dot n at 163 dot com 11-Feb-2011 10:50
Adds a new function for SimpleXMLElement class, in order to output HTML code.

<?php
class CeiXML extends SimpleXMLElement{
public function asHTML(){
$ele=dom_import_simplexml($this);
$dom = new DOMDocument('1.0', 'utf-8');
$element=$dom->importNode($ele,true);
$dom->appendChild($element);
return $dom->saveHTML();
}
}
?>
Pavel Musil pavel dot musil at gmail dot com 10-Feb-2011 03:18
Simple recursive function to append XML object into SimpleXMLElement node:

<?php
// root: parent element - SimpleXMLElement instance
// append: XML object from simplexml_load_string

function xml_join($root, $append) {
    if ($append) {
        if (strlen(trim((string) $append))==0) {
            $xml = $root->addChild($append->getName());
            foreach($append->children() as $child) {
                xml_join($xml, $child);
            }
        } else {
            $xml = $root->addChild($append->getName(), (string) $append);
        }
        foreach($append->attributes() as $n => $v) {
            $xml->addAttribute($n, $v);
        }
    }
}

$xml_append = simplexml_load_string('<data><items><item id="1">value</item></items></data>');
$xml_root = new SimpleXMLElement('<result></result>');

$cxml = $xml_root->addChild('clone');
xml_join($cxml, $xml_append->items->item[0]);

print $xml_root->asXML();
?>

Result:
<?xml version="1.0"?>
<result>
    <clone>
        <item id="1">
            value
        </item>
    </clone>
</result>
rmirabelle 08-Nov-2010 09:42
To further previous comments and drive the point home:

What makes SimpleXMLElement tricky to work with is that it feels and behaves like an object, but is actually a system RESOURCE,  (specifically a libxml resource).

That's why you can't store a SimpleXMLElement to $_SESSION or perform straight comparison operations on node values without first casting them to some type of object.  $_SESSION expects to store 'an object' and comparison operators expect to compare 2 'objects' and SimpleXMLElements are not objects.

When you echo or print a node's value, PHP converts the value (a resource) into a string object for you.  It's a time saver for sure, but can fool you into thinking that your SimpleXMLElement is an object.

Hope this helps clarify
joshduck at gmail dot com 28-Sep-2010 05:00
You should cast elements to a float (or even string) if you plan on using them in addition, multiplication, etc. If you don't then PHP will incorrectly treat the node values as an integer.

<?php
$obj = new SimpleXMLElement('<root>
    <a>1.9</a>
    <b>1.9</b>
</root>');

var_dump($obj->a + $obj->b);
var_dump((float)$obj->a + (float)$obj->b);
var_dump((string)$obj->a + (string)$obj->b);
?>

The first line gives: int(2)
The second and third give the expected result: float(3.8)
francs at seznam dot cz 23-Sep-2010 05:28
Be aware when you trying to cast some attribute to boolean.

(boolean)$xml->attributes()->someAtt;

returns TRUE if attribute is array([0] => 0);

use (boolean)(int) instead.
kweij at lsg dot nl 26-Jul-2010 04:47
I'm using SimpleXML for, ofcourse, it's simplicity, however I did wanted to manipulate the xml and combining one SimpleXMLElement with any other, so I wrote this function to add a SimpleXMLElement-child.

<?php
function SimpleXMLElement_append($key, $value) {
    // check class
    if ((get_class($key) == 'SimpleXMLElement') && (get_class($value) == 'SimpleXMLElement')) {
        // check if the value is string value / data
        if (trim((string) $value) == '') {
            // add element and attributes
            $element = $key->addChild($value->getName());
            foreach ($value->attributes() as $attKey => $attValue) {
                $element->addAttribute($attKey, $attValue);
            }
            // add children
            foreach ($value->children() as $child) {
                SimpleXMLElement_append($element, $child);
            }
        } else {
            // set the value of this item
            $element = $key->addChild($value->getName(), trim((string) $value));
        }
    } else {
        // throw an error
        throw new Exception('Wrong type of input parameters, expected SimpleXMLElement');
    }
}
?>

I'd recommend SimpleXMLElement to extend it's addChild() function with the functionalitity above.
cherubangel at gmail dot com 02-Jul-2010 04:28
Note that changing attributes from within a foreach loop, especially namespaced attributes, can be very tricky.

For example, when trying to change the value of an existing xlink:href attribute:
<?php
foreach($xmlelement -> attributes('xlink', true) as $attribute => $attribvalue){
    $attribvalue[0] = 'value'; // Throws an error
    $attribvalue = 'value'; // Does not change your XML
    $xmlelement -> addAttribute($attribute, 'value', 'http://www.w3.org/1999/xlink'); // Adds an attribute, does not change existing one.
    $xmlelement[$attribute] = 'value'; // Adds an attribute, does not change existing one.
}
?>

Instead, you should access the array returned by the attributes() function directly, like this:
<?php
    $xmlelement -> attributes('xlink', true) -> href = 'value'; // Works!
?>
php at keith tyler dot com 19-Feb-2010 06:23
The root node element of your input XML string is not retrievable as a property.

<?php
$xml="<foo>bar</foo>";
$sxe=new SimpleXMLElement($xml);
print $sxe->foo;
?>

prints nothing. You can only get to the root element via the array index method ($sxe[0]).

Also, you may not have two (or more) root elements -- that is apparently not well-formed XML.

<?php
$xml="<foo/><bar/>";
$sxe=new SimpleXMLElement($xml);
?>

throws an exception. A Q&D is to append an arbitraty root node structure to both ends of the input:

<?php
$xml="<foo/><bar/>";
$sxe=new SimpleXMLElement("<z>".$xml."</z>");
?>

Doing this also solves the above problem of root node property accessibility. (It may not work if your XML string includes a declaration.)
triplepoint at gmail dot com 19-Dec-2009 04:19
It's occasionally useful to add an XML processing instruction to a SimpleXMLElement (treating it as if it were a full document).
<?php
class SimpleXMLElement_Plus extends SimpleXMLElement {

    public function addProcessingInstruction( $name, $value )
    {
        // Create a DomElement from this simpleXML object
        $dom_sxe = dom_import_simplexml($this);

        // Create a handle to the owner doc of this xml
        $dom_parent = $dom_sxe->ownerDocument;

        // Find the topmost element of the domDocument
        $xpath = new DOMXPath($dom_parent);
        $first_element = $xpath->evaluate('/*[1]')->item(0);

        // Add the processing instruction before the topmost element
        $pi = $dom_parent->createProcessingInstruction($name, $value);
        $dom_parent->insertBefore($pi, $first_element);
    }
}
?>

For example, if you had a simpleXMLElement_Plus object made out of the xml fragment:
<xml><content /></xml>

And you needed the output to be:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="xsl/xsl.xsl"?>
<xml><content/></xml>

you could do (using the class above):
<?php
$xml = new SimpleXMLElement_Plus('<xml><content /></xml>');
$xml->addProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="xsl/xsl.xsl"');
echo $xml->asXML();
?>
ivandosreisandrade at gmail dot com 19-Nov-2009 06:55
Hello,

here goes my contribution for those whom are struggling to understand how SimpleXMLElement works.

After some time trying to figure out how this works, I've came up to this small example:

<?php
    $xmlstr = "<?xml version='1.0' ?>\n".
              // optionally you can specify a xml-stylesheet for presenting the results. just uncoment the following line and change the stylesheet name.
              /* "<?xml-stylesheet type='text/xsl' href='xml_style.xsl' ?>\n". */
              "<book></book>";

    // create the SimpleXMLElement object with an empty <book> element
    $xml = new SimpleXMLElement($xmlstr);

    // add some child nodes
    $xml->addChild("title", "Title of my book");
    $xml->addChild("abstract", "My book is about learning to work with SimpleXMLElement");

    // add some more child nodes
    $chapter1 = $xml->addChild("chapter_1");
    // add an attribute to child chapter_1
    $chapter1->addAttribute("chapter_title", "Introduction to my book");

    $chapter2 = $xml->addChild("chapter_2");
    $chapter2->addAttribute("chapter_title", "Development of my book");

    $chapter3 = $xml->addChild("chapter_3");
    $chapter3->addAttribute("chapter_title", "Another chapter of my book");

    $conclusion = $xml->addChild("conclusion", "The ending of my book");

    // insert the header to tell the browser how to read the document
    header("Content-type: text/xml");
    // print the SimpleXMLElement as a XML well-formed string
    echo $xml->asXML();
?>

With this script you can just copy-paste and try to understand how it works.
I hope it can help somebody :)
brett at brettbrewer dot com 27-Oct-2009 04:53
Figuring out how to access the properties of a SimpleXmlElement object was a little tricky for me. In particular, it took a while to discover that I needed to cast my SimpleXmlElement properties to be of type "string" to print them or do comparisons on them. For instance, assuming you already have a string of xml in $xmlstr...

<?php
$sxml= new SimpleXmlElement($xmlstr);

if ((string) $sxml->property== "somevalue") {
    echo (string) $sxml->property;
}
?>
The properties of a SimpleXmlElement object are objects themselves, so you need to put "(string)" before them, which casts their values to a string instead of an object. I assume if you were doing a numeric comparison you'd want to cast to an (int) or something numeric instead.


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

caffeinatedbits 09-Dec-2022 10:50
Just found another gem. Need to remove an attribute? That's simple too!

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

unset($animals->Dog['breed']);

echo $animals->Dog->asXML();
// <Dog/>

?>
caffeinatedbits 09-Dec-2022 10:26
I needed a way to update an attribute, but I could not find any documented way to do this.

After much experimentation, here's my findings of what works - the answer was so simple it took me 8 tries to figure it out :-)

Given the following example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog/>

?>

Test #6 - maybe directly modifying the attributes() Iterator like an array will secretly call __set() magic method?

TL;DR: yep

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
//   array(1) {
//     ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #7 - maybe I don't even need to call attributes() at all?

TL;DR: I sure don't!

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #8 - Maybe I never needed to call addAttribute() in the first place?

TL;DR: nope, I can skip that altogether!

<?php

...

$animals->Dog['breed'] = "chihuahua";
// works!

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

FYI: I also submitted another separate note with what does NOT work just in case you, like me, are curious and tempted to try another way.
caffeinatedbits 09-Dec-2022 10:25
I needed a way to update an attribute, but I could not find any documented way to do this.

TL;DR: It's not only possible, but unbelievably simple. See the other note I submitted for what actually works (sorry, I could not fit it all in a single note due to the 4095 character limit).

After much experimentation, here's my findings of what does NOT work; hopefully, it saves you the time and frustration it cost me.

Given the following example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog/>

?>

Test #1 - attempt to call addAttribute() twice

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

?>

Test #2 - attempt to iterate attributes() (an Iterator) by reference

TL;DR: An iterator cannot be used with foreach by reference

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

try {
    foreach ($animals->Dog->attributes() as $attr => &$value) {
        if ("breed" === $attr) {
            $value = "poodle";
        }
    }
} catch (Throwable $e) {
    echo $e->getMessage();
    // An iterator cannot be used with foreach by reference
}

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #3 - attempt to re-parse child element and then call addAttribute() on the newly parsed element, as suggested in a note I found here

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog = new SimpleXMLElement($animals->asXML());

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #4 - attempt to modify @attributes array element

TL;DR: PHP Notice:  Indirect modification of overloaded element of SimpleXMLElement has no effect

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
//   array(1) {
//     ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['@attributes']['breed'] = "poodle";
// PHP Notice:  Indirect modification of overloaded element of SimpleXMLElement has no effect

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #5 - cast attributes() to array and set value of 'breed' element

TL;DR: does not update value in original object

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = (array) $animals->Dog->attributes();
// array(1) {
//     ["@attributes"]=>
//   array(1) {
//         ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['@attributes']['breed'] = "poodle";

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>
Patanjali 10-Apr-2016 10:37
You cannot use this to update an existing attribute's value.

Instead, get a DOM version of the SimpleXMLElement and use setAttribute, as per:

$XML = '<element a="aa">Text</element>';
$snode = new simple_xml_element($XML);

$dnode = dom_import_simplexml($snode);
$dnode->setAttribute('a', 'bb');

Resulting XML for the node is:
<element a="bb">Text</element>
p.servus 18-Nov-2011 05:42
If you need an Namespace, you must write a Prefix of the Namespace + the Name of the Attribute ("prefix:name") as the first parameter AND the uri as the third one. (I don't know why?!)

Example code:
<?php
$xml = new SimpleXMLElement("<packagedElement></packagedElement>");
$xml->addAttribute("xmi:type", "uml:Class", "http://schema.omg.org/spec/XMI/2.1");
echo $xml->asXml();
?>

Output:
<packagedElement xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmi:type="uml:Class"></packagedElement>
sarlak 07-May-2011 07:49
You can access a node child with his name this way :

<?php
$root = new SimpleXMLElement($filePath);
echo $root->nodeName->attributes;

// It works recursivly so this will work too
echo $root->nodeName->subNodeName->attributes();
?>

But if you want to ADD an attribute to a children you MUST use the children() method to access and modfiy it or it will modify the parent's attributes.

<?php
// Add a subnode
$element->nodeName->addChild('subNodeName', "whatever you want");

// Get the pos in the childrens of the parent node
$lastNodePos = $element->nodeName->count()-1;

// Get the parents node childrens
$nodeChildrens = $element->nodeName->children();

// Add an attribute to the last created
$nodeChildrens[$lastNodePos]->addAttribute('attributeName', "The attribute value);
?>
booleer at yahoo dot it 16-Dec-2010 09:44
If the attribute already exists, addAttribute does nothing.

example:
<?php
$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>
XML;

$xml = simplexml_load_string($xml_string);
$xml->item->addAttribute('id', 'bar');
echo $xml->asXML();
?>

The above examples will output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>


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

fluxlicious at gmail dot com 23-Jan-2023 11:18
The class below allows you to write CDATA and to add additional attributes.

<?php
class SimpleXMLElementExtended extends \SimpleXMLElement
{
    public function addChildWithCData($name, $value)
    {
        $child = parent::addChild($name);
        $element = dom_import_simplexml($child);
        $docOwner = $element->ownerDocument;
        $element->appendChild($docOwner->createCDATASection($value));
        return $child;
    }
}
?>

Example:
<?php
        $xml = new SimpleXMLElementExtended('<xml></xml>');
        $content = $xml->addChildWithCData('content', 'Title of the page');
        $content->addAttribute('id', 1);
        $content->addAttribute('enabled', 'true');

        // Output:
        // <xml>
        //   <content id="1" enabled="true"><![CDATA[Title of the page]]></content>
        // </xml>
?>
caffeinatedbits 09-Dec-2022 11:31
Just in case anyone else, like me, was trying to figure out a way to remove child elements...

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
    <Dog breed="poodle"/>
    <Dog breed="invalid"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

unset($animals->Dog[2]);

echo $animals->asXML();

// <?xml version="1.0" encoding="utf-8"?>
// <Animals>
//         <Dog breed="chihuahua"/>
//         <Dog breed="poodle"/>
//
// </Animals>

?>

Note: you cannot remove elements while iterating children, otherwise it will break the Iterator. Example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
    <Dog breed="poodle"/>
    <Dog breed="invalid"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

$allowed_breeds = [
    'chihuahua',
    'poodle'
];

try {
    $index = 0;
    foreach ($animals->Dog as $dog) {
        if (!in_array($dog['breed'], $allowed_breeds)) {
            unset($animals->Dog[$index]);
        }
        $index++;
    }
} catch (Throwable $e) {
    echo $e->getMessage();
    // SimpleXMLElement is not properly initialized
}

?>
carlos dot eduardo dot debiasi at gmail dot com 22-Apr-2021 01:23
I create this function so you can through and array build the XML, this allows multiple keys with the same value.
The structure must follow

[
    'key' => 'nameOfTheKey',
    'attributes' => ['id' => '1'],
    'fields' => [
        ['key' => 'fieldSamName', 'value' => '1'],
        ['key' => 'fieldSamName', 'value' => '1'],
        ['key' => 'fieldSamName', 'value' => '2'],
        ['key' => 'fieldWithChild', 'fields' => [
            ['key' => 'car', 'value' => '2'],
            ['key' => 'human', 'value' => '3'],
        ]],
    ]
];

Function:
 function toXml(\SimpleXMLElement $node, array $data)
    {
        foreach ($data as $key => $value) {
            $key = $value['key'];
            if (isset($value['value'])) {
                    $newNode = $node->addChild($key, $value['value']);
                if (isset($value['attributes'])) {
                    foreach ($value['attributes'] as $keyAttr => $valueAttr) {
                        $newNode->addAttribute($keyAttr, $valueAttr);
                    }
                }
            } else {
                $newNode = $node->addChild($key);
                if (isset($value['attributes'])) {
                    foreach ($value['attributes'] as $keyAttr => $valueAttr) {
                        $newNode->addAttribute($keyAttr, $valueAttr);
                    }
                }
            }
            if (isset($value['fields'])) {
                foreach ($value['fields'] as $keyField => $valueField) {
                    $this->toXml($newNode, [$keyField => $valueField]);
                }
            }
        }
    }
nwarap 07-Nov-2017 02:46
Want to continue the ampersand (&) chain problem.

Sometimes, you would want to assign  (=) addChild.
This trick will helps you to do this.

<?php
$webOrders = new SimpleXMLElement('<?xml version="1.0"?><WebOrders></WebOrders>');
$webOrder = $webOrders->addChild('WebOrder');
$product = $webOrder->addChild('Product');
$product[0] = 'T&M';
$product->addAttribute('price', 19.99);
$product->addAttribute('qty', 2);
var_dump($webOrders->asXML());
?>

OUTPUT would be:

<?xml version="1.0" encoding="UTF-8"?>
<WebOrders>
    <WebOrder>
        <Product price="19.99" qty="2">T&amp;M</Product>
    </WebOrder>
</WebOrders>
johninen at gmail dot com 14-Sep-2015 01:27
In the docs for google sitemaps it is required an element for mobile sitemaps that looks like this: <mobile:mobile/>

I used some time to figure out how to make it, but it is quite simple when understood.

$mobile_schema = 'http://www.google.com/schemas/sitemap-mobile/1.0';

//Create root element
$xml_mobile = new SimpleXMLElement('
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="'.$mobile_schema.'"></urlset>
');

//Add required children
$url_mobile = $xml_b_list_mobile->addChild('url');
$url_mobile->addChild('loc', 'your-mobile-site-url');
$url_mobile->addChild('mobile:mobile', null, $mobile_schema);

For this to work properly the attribute xmlns:mobile must be set in the root node, and then used as namespace(third argument) when creating the mobile:mobile child with null as value.
thallisphp at gmail dot com 07-May-2014 07:35
<?php
class MySimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     *
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string)$append)) == 0) {
                $xml = $this->addChild($append->getName());
            } else {
                $xml = $this->addChild($append->getName(), (string)$append);
            }

            foreach ($append->children() as $child) {
                $xml->appendXML($child);
            }

            foreach ($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
frosty dot z at freesbee dot fr 16-May-2013 02:31
To complete Volker Grabsch's comment, stating :
"Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&"."

To work around that problem, you can use direct property assignment such as :

<?php
$xmlelement->value = 'my value < > &';
// results in <value>my value &lt; &gt; &amp;</value>
?>

instead of doing :

<?php
$xmlelement->addChild('value', 'my value < > &');
// results in <value>my value &lt; &gt; &</value> (invalid XML)
?>

See also: http://stackoverflow.com/questions/552957 (Rationale behind SimpleXMLElement's handling of text values in addChild and addAttribute)

HTH
passerbyxp at gmail dot com 27-Mar-2013 03:59
Be aware that simply because you can <?php $dom->addChild();?> doesn't mean your XML is valid under simple XML itself:

<?php
$dom=simplexml_load_string("<test></test>");
$dom->addChild("3D","1,2,3");
$xml=$dom->asXML();
echo $xml;
/* echos:
<?xml version="1.0"?>
<test><3D>1,2,3</3D></test>
*/

$dom=simplexml_load_string($xml);
/*
generates a whole lots of warnings,
and refuses to create an object.
*/
?>

Same in PHP 5.3 and 5.4
ivan dot kakurov at gmail dot com 13-Jan-2013 04:09
Here's my solution for creating XML from Multidimensional Array.
<?php
//DATA
        $xmlDAta = array(
            array(
                "name"  => "nameVal",
                "value" => "valVal",
                "css"   => "cssVal"
            ),
            array(
                "name"  => "name1Val",
                "value" => "val1Val",
                "css"   => "css1Val"
            ),
            "tname" => array(
                array(
                    "iTname"   => "iTname",
                    "iTname2"  => "iTname1",
                    "iTname2"  => "iTname2",
                    "iTbname3" => array(
                        "iiTbname"  => "tbName",
                        "iiTbname1" => "tbName1",
                    ),
                ),
            ),
            "tdata" => "otheerDAta"
        );

   /**
     * Create XML using string or array
     *
     * @param mixed $data input data
     * @param SimpleXMLElement $xml
     * @param string $child name of first level child
     *
     * @return adding Xml formated data into SimpleXmlElement
     */

function data2XML(array $data, SimpleXMLElement $xml, $child = "items")
    {

        foreach($data as $key => $val) {
            if(is_array($val)) {

                if(is_numeric($key)) {
                    $node  = $xml->addChild($child);
                    $nodes = $node->getName($child);
                } else {

                    $node  = $xml->addChild($key);
                    $nodes = $node->getName($key);
                }

                $node->addChild($nodes, self::data2Xml($val, $node));
            } else {
                $xml->addChild($key, $val);
            }
        }

    }

//Use

        $xml    = new SimpleXMLElement("<root/>");
        Util::data2XML($xmlDAta, $xml, "Items");

?>
jerikojerk 31-Jul-2011 07:32
If you're looking for a way to append children you may be interested in this:

<?php
$x = new SimpleXMLElement('<root name="toplevel"></root>');
$f1 = new SimpleXMLElement('<child pos="1">alpha</child>');
$f2 = new SimpleXMLElement('<child pos="2">beta</child>');
$f3 = new SimpleXMLElement('<child pos="3">gamma</child>');

$x->{$f1->getName()} = $f1;
$x->{$f2->getName()}[] = $f2;
$x->{$f3->getName()}[] = $f3;

echo 'count child=',$x->count(),"\n";
echo $x->asXML();

foreach ( $x->children() as $foo )
{
    var_dump($foo);
}

?>
alex dot feraud at gmail dot com 16-Jun-2011 02:52
Here is a class with more functions for SimpleXMLElement :

<?php
/**
 *
 * Extension for SimpleXMLElement
 * @author Alexandre FERAUD
 *
 */
class ExSimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add CDATA text in a node
     * @param string $cdata_text The CDATA value  to add
     */
  private function addCData($cdata_text)
  {
   $node= dom_import_simplexml($this);
   $no = $node->ownerDocument;
   $node->appendChild($no->createCDATASection($cdata_text));
  }

  /**
   * Create a child with CDATA value
   * @param string $name The name of the child element to add.
   * @param string $cdata_text The CDATA value of the child element.
   */
    public function addChildCData($name,$cdata_text)
    {
        $child = $this->addChild($name);
        $child->addCData($cdata_text);
    }

    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string) $append))==0) {
                $xml = $this->addChild($append->getName());
                foreach($append->children() as $child) {
                    $xml->appendXML($child);
                }
            } else {
                $xml = $this->addChild($append->getName(), (string) $append);
            }
            foreach($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
Volker Grabsch 21-Apr-2011 06:17
Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&".

So addChild() is unsuited to handle user-defined input!

Instead, you will have to replace all "&" with "&amp;" before calling addChild().

Or, use htmlspecialchars() which also replaces other characters, but won't do any harm as addChild() won't replace those again.
felipenmoura at gmail dot com 11-Apr-2011 06:06
This method returns a reference to the specific SimpleXMLElement.
If you use:
<?php
    $xml= new SimpleXMLElement('<root></root>');
    $xml->father['name']= 'Fathers name'; // creates automatically a father tag with attribute name
    $son= $xml->father->addChild('son'); // uses the first father tag
    $son['name']= 'first son';
    $otherSon= $xml->father->addChild('son'); // uses the first father tag but now, in a second son tag
    $otherSon['name']= 'second son';

    echo htmlentities($xml->asXML());
?>

The result will be
<root>
    <father>
        <son name='first son' />
        <son name='second son' />
    </father>
</root>

So, once you change something to the just added child, you are actually accessing the element inside the SimpleXMLElement as a reference.


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


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

public SimpleXMLElement::__construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = 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

info at ensostudio dot ru 20-Aug-2021 04:22
Extended SimpleXMLElement:
<?php
class XmlElement extends \SimpleXMLElement
{
    public static function factory(string $root): self
    {
        return new static('<?xml version="1.0" encoding="UTF-8"?><'.$root.'/>', LIBXML_BIGLINES | LIBXML_COMPACT);
    }

    /**
      * @param iterable $attributes An array of element attributes as name/value pairs
      * @return $this
      */
    public function addAttributes(iterable $attributes)
    {
        foreach ($attributes as $name => $value) {
            $this->addAttribute($name, $value);
        }

        return $this;
    }

    /**
      * @param string $name The sub-element name
      * @param string|array|null $valueOrAttributes The sub-element value or an array of attributes
      * @param string|null $namespace The sub-element namespace
      * @return static|null
      */
    public function addChild($name, $valueOrAttributes = null, $namespace = null)
    {
        if (is_array($valueOrAttributes)) {
            $child = parent::addChild($name, null, $namespace);
            foreach ($valueOrAttributes as $name => $value) {
                $child->addAttribute($name, $value);
            }
        } else {
            $child = parent::addChild($name, $valueOrAttributes, $namespace);
        }

        return $child;
    }

    /**
      * @param iterable $childs An array of sub-elements as name/value(or attributes) pairs
      * @return $this
      */
    public function addChilds(iterable $childs)
    {
        foreach ($childs as $name => $value) {
            $this->addChild($name, $value);
        }

        return $this;
    }
}
?>
rowan dot collins at gmail dot com 22-Apr-2017 03:23
The manual doesn't really explain what the $ns argument (and the accompanying $is_prefix) are for.

What they do is similar to the ->children() method: they set the context of the returned object to that namespace, so that access via ->elementName and ['attributeName'] refer to elements and attributes in that namespace.

In particular, they do *not* change the namespaces which exist on the document.

See this example:

<?php
// This XML contains two elements called <child>
// One is in the namespace http://example.com, with local prefix 'ws'
// The other has no namespace (no prefix, and no default namespace declared)
$xml = '<ws:example xmlns:ws="http://example.com"><child>Not in namespace</child><ws:child>In example namespace</ws:child></ws:example>';

$sx0 = new SimpleXMLElement($xml, 0, false);
$sx1 = new SimpleXMLElement($xml, 0, false, 'http://example.com');
$sx2 = new SimpleXMLElement($xml, 0, false, 'ws', true);

echo "
    Without: {$sx0->child}
    By namespace: {$sx1->child}
    By prefix: {$sx2->child}
";
?>

Output:

 Without: Not in namespace
 By namespace: In example namespace
 By prefix: In example namespace
ahmad dot mayahi at gmail dot com 07-Jun-2016 09:36
You won't be able to load an XML file without root element:

//This will throw an exception
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>', null, false);

//Here is the solution
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>', null, false);
Phil Cross 01-Sep-2014 11:39
It's worth noting, that you need to typecast dynamic property names to string in order to retrieve there value, for example:

<?php
    $xml = new SimpleXMLElement('records.xml', 0, true);

    // This will work as expected because its a hard coded property value
    foreach($xml as $record){
        echo $record->id;    // Will output the ID fine
    }

    // Dynamic properties require typecasting to string
    $xml_field = 'id';
    foreach($xml as $record){

        // This will dump a SimpleXMLElement object
        var_dump($record->$xml_field);

        // This will output the value as expected
        echo (string)$record->$xml_field;
    }
?>
bertolini dot cedric at me dot com 16-Jun-2014 11:07
It's worth noting that the behavior of SimpleXmlElement::__construct is not exactly the same as simplexml_load_string, regarding libxml_use_internal_errors().

In my case,

<?php
libxml_use_internal_errors(true);
new \SimpleXmlElement($data);
?>

was still throwing error. But as soon as I switched to

<?php
libxml_use_internal_errors(true);
simplexml_load_string($data);
?>

everything worked fine and I stopped getting an error.
kumarldh at gmail dot com 22-Mar-2011 10:50
Using libxml_use_internal_errors() may suppress errors but Exception still requires decent handling. I used following code snippet.

<?php
libxml_use_internal_errors(true);
try{
    $xmlToObject = new SimpleXMLElement($notSoWellFormedXML);
} catch (Exception $e){
    echo 'Please try again later...';
    exit();
}
?>
uramihsayibok, gmail, com 16-Aug-2009 06:52
As I was filling out a bug report, I realized why (speculation here) the constructor is final: so that functions like simplexml_load_file and simplexml_load_string can work. I imagine the PHP-ized code looks something like

<?php

function simplexml_load_file($filename, $class_name = "SimpleXMLElement", $options = 0, $ns = "", $is_prefix = false) {
    return new $class_name($filename, $options, true, $ns, $is_prefix);
}

?>

If we were to use a different $class_name and change the constructor's definition these functions wouldn't work.

There's no easy, sensible solution that keeps simplexml_load_file and simplexml_load_string.
tudor at culise dot net 20-Nov-2007 03:35
This class is extendable, but it's too bad that its constructor cannot be overriden (PHP says it's a final method). Thus the class should be wrapped using the delegation principle rather that extended.


Cuenta los hijos de un elemento

  • « SimpleXMLElement::__construct
  • SimpleXMLElement::current »
  • 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
?>


Returns the current element

  • « SimpleXMLElement::count
  • SimpleXMLElement::getDocNamespaces »
  • PHP Manual
  • SimpleXMLElement
  • Returns the current element

SimpleXMLElement::current

(No hay información de versión disponible, podría estar únicamente en Git)

SimpleXMLElement::current — Returns the current element

Descripción

public SimpleXMLElement::current(): SimpleXMLElement
Advertencia

Prior to PHP 8.0, SimpleXMLElement::current() was only declared on the subclass SimpleXMLIterator.

This method returns the current element as a SimpleXMLElement object.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the current element as a SimpleXMLElement object.

Errores/Excepciones

Throws an Error on failure.

Historial de cambios

Versión | Descripción
8.1.0 | An Error is now thrown if SimpleXMLElement::current() is called on an invalid iterator. Previously, null was returned.

Ejemplos

Ejemplo #1 Return the current element

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP basics</book><book>XML basics</book></books>');

$xmlElement->rewind(); // rewind to first element, otherwise current() won't work
var_dump($xmlElement->current());
?>

El resultado del ejemplo sería:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP basics"
}

Ver también

  • SimpleXMLElement::key() - Return current key
  • SimpleXMLElement::next() - Move to next element
  • SimpleXMLElement::rewind() - Rewind to the first element
  • SimpleXMLElement::valid() - Check whether the current element is valid
  • SimpleXMLElement

User Contributed Notes

There are no user contributed notes for this page.


Devuelve los espacios de nombre declarados en el documento

  • « SimpleXMLElement::current
  • 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::getChildren »
  • 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;
}

?>


Returns the sub-elements of the current element

  • « SimpleXMLElement::getNamespaces
  • SimpleXMLElement::hasChildren »
  • PHP Manual
  • SimpleXMLElement
  • Returns the sub-elements of the current element

SimpleXMLElement::getChildren

(No hay información de versión disponible, podría estar únicamente en Git)

SimpleXMLElement::getChildren — Returns the sub-elements of the current element

Descripción

public SimpleXMLElement::getChildren(): ?SimpleXMLElement
Advertencia

Prior to PHP 8.0, SimpleXMLElement::getChildren() was only declared on the subclass SimpleXMLIterator.

This method returns a SimpleXMLElement object containing sub-elements of the current SimpleXMLElement element.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns a SimpleXMLElement object containing the sub-elements of the current element.

Ejemplos

Ejemplo #1 Return the sub-elements of the current element

<?php
$xml = <<<XML
<books>
<book>
<title>PHP Basics</title>
<author>Jim Smith</author>
</book>
<book>XML basics</book>
</books>
XML;

$xmlElement = new SimpleXMLElement($xml);
for ($xmlElement->rewind(); $xmlElement->valid(); $xmlElement->next()) {
foreach($xmlElement->getChildren() as $name => $data) {
echo "The $name is '$data' from the class " . get_class($data) . "\n";
}
}
?>

El resultado del ejemplo sería:

The title is 'PHP Basics' from the class SimpleXMLElement
The author is 'Jim Smith' from the class SimpleXMLElement

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the current element has sub elements

  • « SimpleXMLElement::getChildren
  • SimpleXMLElement::key »
  • PHP Manual
  • SimpleXMLElement
  • Checks whether the current element has sub elements

SimpleXMLElement::hasChildren

(No hay información de versión disponible, podría estar únicamente en Git)

SimpleXMLElement::hasChildren — Checks whether the current element has sub elements

Descripción

public SimpleXMLElement::hasChildren(): bool
Advertencia

Prior to PHP 8.0, SimpleXMLElement::hasChildren() was only declared on the subclass SimpleXMLIterator.

This method checks whether the current SimpleXMLElement element has sub-elements.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

true if the current element has sub-elements, otherwise false

Ejemplos

Ejemplo #1 Check whether the current element has sub-elements

<?php
$xml = <<<XML
<books>
<book>
<title>PHP Basics</title>
<author>Jim Smith</author>
</book>
<book>XML basics</book>
</books>
XML;

$xmlElement = new SimpleXMLElement($xml);
for ($xmlElement->rewind(); $xmlElement->valid(); $xmlElement->next()) {
if ($xmlElement->hasChildren()) {
var_dump($xmlElement->current());
}
}
?>

El resultado del ejemplo sería:

object(SimpleXMLElement)#2 (2) {
  ["title"]=>
  string(10) "PHP Basics"
  ["author"]=>
  string(9) "Jim Smith"
}

User Contributed Notes

There are no user contributed notes for this page.


Return current key

  • « SimpleXMLElement::hasChildren
  • SimpleXMLElement::next »
  • PHP Manual
  • SimpleXMLElement
  • Return current key

SimpleXMLElement::key

(No hay información de versión disponible, podría estar únicamente en Git)

SimpleXMLElement::key — Return current key

Descripción

public SimpleXMLElement::key(): string
Advertencia

Prior to PHP 8.0, SimpleXMLElement::key() was only declared on the subclass SimpleXMLIterator.

This method gets the XML tag name of the current element.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns the XML tag name of the element referenced by the current SimpleXMLElement object.

Errores/Excepciones

Throws an Error on failure.

Historial de cambios

Versión | Descripción
8.1.0 | An Error is now thrown if SimpleXMLElement::key() is called on an invalid iterator. Previously, false was returned.

Ejemplos

Ejemplo #1 Get the current XML tag key

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP basics</book><book>XML basics</book></books>');

echo var_dump($xmlElement->key());
$xmlElement->rewind(); // rewind to the first element
echo var_dump($xmlElement->key());

?>

El resultado del ejemplo sería:

bool(false)
string(4) "book"

User Contributed Notes

There are no user contributed notes for this page.


Move to next element

  • « SimpleXMLElement::key
  • SimpleXMLElement::registerXPathNamespace »
  • PHP Manual
  • SimpleXMLElement
  • Move to next element

SimpleXMLElement::next

(No hay información de versión disponible, podría estar únicamente en Git)

SimpleXMLElement::next — Move to next element

Descripción

public SimpleXMLElement::next(): void
Advertencia

Prior to PHP 8.0, SimpleXMLElement::next() was only declared on the subclass SimpleXMLIterator.

This method moves the SimpleXMLElement to the next element.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Move to the next element

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP Basics</book><book>XML basics</book></books>');
$xmlElement->rewind(); // rewind to the first element
$xmlElement->next();

var_dump($xmlElement->current());
?>

El resultado del ejemplo sería:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "XML basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Crea un contexto prefijo/ns para la siguiente petición XPath

  • « SimpleXMLElement::next
  • SimpleXMLElement::rewind »
  • 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');
?>


Rewind to the first element

  • « SimpleXMLElement::registerXPathNamespace
  • SimpleXMLElement::saveXML »
  • PHP Manual
  • SimpleXMLElement
  • Rewind to the first element

SimpleXMLElement::rewind

(No hay información de versión disponible, podría estar únicamente en Git)

SimpleXMLElement::rewind — Rewind to the first element

Descripción

public SimpleXMLElement::rewind(): void
Advertencia

Prior to PHP 8.0, SimpleXMLElement::rewind() was only declared on the subclass SimpleXMLIterator.

This method rewinds the SimpleXMLElement to the first element.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Ejemplo #1 Rewind to the first element

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP Basics</book><book>XML Basics</book></books>');
$xmlElement->rewind();

var_dump($xmlElement->current());
?>

El resultado del ejemplo sería:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP Basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Alias de SimpleXMLElement::asXML

  • « SimpleXMLElement::rewind
  • SimpleXMLElement::__toString »
  • PHP Manual
  • SimpleXMLElement
  • Alias de SimpleXMLElement::asXML

SimpleXMLElement::saveXML

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

SimpleXMLElement::saveXML — Alias de SimpleXMLElement::asXML()

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::valid »
  • 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.


Check whether the current element is valid

  • « SimpleXMLElement::__toString
  • SimpleXMLElement::xpath »
  • PHP Manual
  • SimpleXMLElement
  • Check whether the current element is valid

SimpleXMLElement::valid

(No hay información de versión disponible, podría estar únicamente en Git)

SimpleXMLElement::valid — Check whether the current element is valid

Descripción

public SimpleXMLElement::valid(): bool
Advertencia

Prior to PHP 8.0, SimpleXMLElement::valid() was only declared on the subclass SimpleXMLIterator.

This method checks if the current element is valid after calls to SimpleXMLElement::rewind() or SimpleXMLElement::next().

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Returns true if the current element is valid, otherwise false

Ejemplos

Ejemplo #1 Check whether the current element is valid

<?php
$xmlElement = new SimpleXMLElement('<books><book>SQL Basics</book></books>');

$xmlElement->rewind(); // rewind to the first element
echo var_dump($xmlElement->valid()); // bool(true)

$xmlElement->next(); // advance to the next element
echo var_dump($xmlElement->valid()); // bool(false) because there is only one element
?>

User Contributed Notes

There are no user contributed notes for this page.


Ejecuta una petición XPath sobre los datos XML

  • « SimpleXMLElement::valid
  • 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

Filippo Vicari 28-Sep-2022 09:56
You can also search for siblings with a condition. For example immagine to need the title for a desidered language which with the two siblings tags in this XML file

<?xml version="1.0" encoding="UTF-8"?>
<IDOC BEGIN="1">
...
<PRODUCT SEGMENT="1">
    <PRODUCTCODE>005</PRODUCTCODE>
    <LANG>E</LANG>
    <TITLE>Name</TITLE>
    <LANG_ISO>EN</LANG_ISO>
</PRODUCT>
<PRODUCT SEGMENT="1">
    <PRODUCTCODE>005</PRODUCTCODE>
    <LANG>I</LANG>
    <TITLE>Name I</TITLE>
    <LANG_ISO>IT</LANG_ISO>
</PRODUCT>
...
</IDOC>

Let's break it down
<?php
"//PRODUCT" // find product tag
"//PRODUCT/LANG[.='E']" // whithin it find lang == "E"
"//PRODUCT/LANG[.='E']/../"  // go up one step
"//PRODUCT/LANG[.='E']/../TITLE" // get the title Tag content

// Combined search and find siblings ----------------------------
$xml = simplexml_load_file("fname.xml");

// Search for the TITLE field which sibling is == "E" ----------
$title_E_array = $xml->xpath("//PRODUCT/LANG[.='E']/../TITLE"); // By default gives back an array of  SimpleXmlElement
$title = (string) $xml->xpath("//PRODUCT/LANG[.='E']/../TITLE")[0]; // in this way saves only the value as a string
?>
awoerl at contentserv dot com 31-Jan-2017 12:43
I tried to use string functions in the xpath statements I'm passing, like

$oXml->xpath('substring(/foo/bar/text(), 0, 4)');

But no matter which syntax I'm trying I never the string functions to work.

Is it possible, that the xpath method does not support function calls?
Alexis Peters 11-Oct-2016 09:11
If you want this behavior for an multidimensional array you can use this:

<?php
function apath(&$a, $path, $value = NULL) {
    $pathes = explode('/',$path);

    if(count($pathes) > 1) {
        $firstPart = array_shift($pathes);
        if(!isset($a[$firstPart])) {
            $a[$firstPart] = array();
        }
        return apath($a[$firstPart], implode('/', $pathes), $value);
    } else {
        if($value){
            $a[$path] = $value;
        } else {
            return $a[$path];
        }
    }
}

apath($a, 'user/name', array('prename' => 'foo', 'lastname' => 'bar'));

$a = array();
var_dump($a);
var_dump(apath($a, 'user/name/lastname'));

?>
Gives you this:

array(1) {
  ["user"]=>
  array(1) {
    ["name"]=>
    array(2) {
      ["prename"]=>
      string(5) "foo"
      ["lastname"]=>
      string(8) "bar"
    }
  }
}
string(8) "bar"
Anonymous 30-Jan-2015 05:30
As mentioned already xpath will fail is the default namespace 'xmlns' is used like in:

<?php

$xmlstring = $string = <<<XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <fileVersion appName="xl" />
</workbook>
XML;
?>

xpath cannot search through the xml without explicitly specifying a namespace.
There are 2 options :
1. rename the 'xmlns' into something else to trick xpath into believing that no default namespace is defined.
2. register a string as the default namespace and use that string in all your queries. Unfortunatly, an empty space will not work.
No other option currently exist until XPath2.0 becomes the default library.
leonjanzen at gmail dot com 19-Oct-2014 07:48
To run an xpath query on an XML document that has a namespace, the namespace must be registered with SimpleXMLElement::registerXPathNamespace() before running the query. If the XML document namespace does not include a prefix, you must make up an arbitrary one, and then use it in your query.

<?php
$strXml= <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<mydoc xmlns="http://www.url.com/myns">
    <message>Test message</message>
</mydoc>
XML;

$xmlDoc=new \SimpleXMLElement($strXml);

foreach($xmlDoc->getDocNamespaces() as $strPrefix => $strNamespace) {
    if(strlen($strPrefix)==0) {
        $strPrefix="a"; //Assign an arbitrary namespace prefix.
    }
    $xmlDoc->registerXPathNamespace($strPrefix,$strNamespace);
}

print($xmlDoc->xpath("//a:message")[0]); //Use the arbitrary namespace prefix in the query.
?>

This will output:

Test message
BenjaminBeck at gmx dot de 13-Sep-2014 01:36
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $v = $row->xpath('./country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
yetihehe at yetihehe dot com 12-Jan-2011 02:21
Xpath actually knows which element is root regardless of element on which you execute it. Example:

<?php

$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <b>
  <c>code</c>
 </b>
</a>
XML;

header('content-type: text/plain');

$xml = new SimpleXMLElement($string);

//relative to root
$b0=$xml->b[0]->xpath('//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: //c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: //c: ',$node,"\n";
}

echo "\n";

//relative to current element
$b0=$xml->b[0]->xpath('.//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: .//c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('.//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: .//c: ',$node,"\n";
}

?>

Will return:
b[0]: //c: text
b[0]: //c: stuff
b[0]: //c: code
b[1]: //c: text
b[1]: //c: stuff
b[1]: //c: code

b[0]: .//c: text
b[0]: .//c: stuff
b[1]: .//c: code
stefan at efectos dot nl 09-Nov-2010 02:33
Having problems selecting information through xpath when there are namespaces in the XML?

Try this quick and dirty solution, but it works:

<?php
$objImageXml = new SimpleXMLElement($objImageXml->asXML());
?>
grummfy at gmail dot com 11-Feb-2010 04:08
On a xml that have namespace you need to do this before your xpath request (or empty array will be return) :

<?php
$string = str_replace('xmlns=', 'ns=', $string); //$string is a string that contains xml...
?>
DrupalFocus at earthlink dot net 02-Dec-2009 12:27
Looks like the relative path is relative to the SimpleXMLElement object that you call the Xpath() method on.  Basically chopping off the root element.

<?php
$string = <<<XML
<foo>
  <bar>
    <a>
     <b>
      <c>text</c>
      <c>stuff</c>
     </b>
     <d>
      <c>code</c>
     </d>
    </a>
  </bar>
</foo>
XML;

$xml = new SimpleXMLElement($string);
/* Search for children using 2nds level relative <bar><a><b><c> */
$result = $xml->xpath('a/b/c');
if ($result)
foreach($result as $node) {
    drupal_set_message(t('a/b/c: @node.', array('@node' => $node)));
}
else
  drupal_set_message(t('a/b/c: failed.'));

/* it relative to the SimpleXMLElement Search for 2nds level relative <bar><a><b><c> but where is foo */
$bar = $xml->bar;
$result = $bar->xpath('a/b/c');
foreach($result as $node) {
    drupal_set_message(t('bar->a/b/c: @node.', array('@node' => $node)));
}
?>

results in :
#
# a/b/c: failed.
# bar->a/b/c: text.
# bar->a/b/c: stuff.
behnam@zwnj 24-Sep-2009 01:34
Seems like this function cannot return the result of XPath string() [1] function.  For example if you query xpath("string(a/@b)") you will get bool(false) although the node "a" may have the attribute "b" set to a non-empty string.

[1] http://www.w3.org/TR/xpath#section-String-Functions
Anti Veeranna 17-Jun-2009 03:50
Whether it returns a false or empty array for a non-existing path seems to depend on libxml version.

I tried the following code:

<?php
$data = '<foo><bar></bar></foo>';
$xml = simplexml_load_string($data);
print gettype($xml->xpath('/first/second'));
?>

On a machine with libxml 2.6.16 and PHP 5.2.8 I got back boolean. On a different machine with libxml 2.7.3 and PHP 5.2.8/5.2.9 I got back empty array.

You can check the libxml version from command line by executing: php --ri libxml

or simply look at phpinfo() output
arealzone-czernobyl at yahoo dot de 11-Jun-2009 03:23
The simplest way to count nodes in a XML doc:

<?php
$xml = new SimpleXMLElement($xmlstr);

$xmlNode = $xml->xpath('root/yourNodeName');
$nodeCount = count($xmlNode);

echo $nodeCount;
?>
anemik 02-Jul-2008 03:46
If you want to find easly all records satisfying some condition in XML data like

....
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
   </book>
...

try example below

<?php

$xmlStr = file_get_contents('data/books.xml');
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find all book records with price higher than 40$
$res = $xml->xpath("book/price[.>'40']/parent::*");
print_r($res);

?>

You will see response like:
Array (
[0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => bk101
                )

            [author] => Gambardella, Matthew
            [title] => XML Developer's Guide
            [genre] => Computer
            [price] => 44.95
            [publish_date] => 2000-10-01
            [description] => An in-depth look at creating applications
      with XML.
        )
...
paul at pmtlogic dot com 18-Jun-2008 12:17
xpath doesn't seem to be able to handle single quotes embedded in the query itself. For instance, I want to find geo coordinates in an xml file based on country name.

xml snippet:

<zones>
<zone country="Cote d'Ivoire" fullName="Yamoussoukro" geo="6.82,-5.28" id="1050"><url prefix="1001" value="fiji.html" /><url prefix="1002" value="C" /></zone>
</zones>

The following code does not work:

<?php
$xml = simplexml_load_file("my.xml");
$result = $xml->xpath("//zone[@country='Cote d\'Ivoire']");

foreach ( $result[0]->attributes() as $key => $val ) {
    print "<div class='coords'>$key: $val</div>\n";
}
?>

I have tried many variations on the embedded single quote (i.e. escape codes) but with no result. W3C offers no explanation either.

In addition, there doesn't seem to be any way of embedding wildcards in the attribute value (you can embed wildcards in the attribute name). Otherwise the following might be a reasonable substitute in this context:

<?php $result = $xml->xpath("//zone[@country='Cote d*Ivoire']"); ?>
canuemail at gmail dot com 05-May-2008 05:05
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $row = simplexml_load_string($item->asXML());
    $v = $row->xpath('//country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
Hugh 18-Dec-2005 03:23
Note that this function does not ALWAYS return an array. It seems that if the specified path is not found in the document, it will return false. You need to check for the false value before using foreach, if you wish to avoid a warning (and often to handle errors or control program flow in this situation).
drewish at katherinehouse dot com 10-Jul-2005 06:16
xpath() can also be used to select elements by their attributes. For a good XPath reference check out: http://www.w3schools.com/xpath/xpath_syntax.asp

<?php
$string = <<<XML
<sizes>
    <size label="Square" width="75" height="75" />
    <size label="Thumbnail" width="100" height="62" />
    <size label="Small" width="112" height="69" />
    <size label="Large" width="112" height="69" />
</sizes>
XML;

$xml = simplexml_load_string($string);
$result = $xml->xpath("//size[@label='Large']");

// print the first (and only) member of the array
echo $result[0]->asXml();
?>

The script would print:
<size label="Large" width="112" height="69"/>


La 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

class SimpleXMLIterator extends SimpleXMLElement {
/* Métodos heredados */
public SimpleXMLElement::__construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)
public SimpleXMLElement::current(): SimpleXMLElement
public SimpleXMLElement::getChildren(): ?SimpleXMLElement
public SimpleXMLElement::hasChildren(): bool
public SimpleXMLElement::key(): string
public SimpleXMLElement::next(): void
public SimpleXMLElement::rewind(): void
public SimpleXMLElement::__toString(): string
public SimpleXMLElement::valid(): bool
}

Historial de cambios

Versión | Descripción
8.0.0 | Métodos de iterador (SimpleXMLIterator::hasChildren(), SimpleXMLIterator::getChildren(), SimpleXMLIterator::current(), SimpleXMLIterator::key(), SimpleXMLIterator::next(),SimpleXMLIterator::rewind(), SimpleXMLIterator::valid()) se han transferido a SimpleXMLElement.
8.0.0 | SimpleXMLIterator implementa Stringable ahora.

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


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

paul dot allsopp at digital-pig dot com 06-Jun-2023 12:07
Why not just:
simplexml_import_dom(dom_import_simplexml($SimpleXmlNode))
shirkaen at gmail dot com 10-Nov-2016 06:58
/*If tags in DOM have text and some part of this text is surrounded by other tag, simple_import_dom object doesn't contain position of child tag, so rendering it back to html/xml can be a problem. Printing such a node is also peculiar. Eg.*/

//////////////////////
$text = "<body><p>Some text before <em>italic </em>and after text.</p></body>";
$dom = new DOMDocument;
$dom->loadHTML($text);
$result = simplexml_import_dom($dom);
echo $result->p;

//////////////////////
//Prints :
//Some text before and after text.

print_r($result->p);
//Prints:
//SimpleXMLElement Object ( [em] => italic )

print_r($result->p->em)
//does more or less the same:
//SimpleXMLElement Object ( [0] => italic )

var_dump($result->p);
//Prints:
//object(SimpleXMLElement)#8 (1) { ["em"]=> string(7) "italic " }

var_dump($result->p->em)
//object(SimpleXMLElement)#9 (1) { [0]=> string(7) "italic " }

//but
echo $result->p->em;
//prints:
//italic
brandonkirsch at perceptionilluminates dot com 14-Aug-2013 03:38
simplexml_import_dom() will accept DOMNodes or other SimpleXMLElements.  This has a useful purpose if you are extending the SimpleXMLElement class and would prefer the xpath() method to return your class extension instead of basic SimpleXMLElements.  For example:

class MySimpleXML extends SimpleXMLElement{
    public function xpath($xpath){
        $return = array();
        $simpleXmls = parent::xpath($xpath); // run SimpleXMLElement xpath, returning an array of SimpleXMLElements
        foreach($simpleXmls as $xml){
            $return[] = simplexml_import_dom($xml,'MySimpleXML'); // copy SimpleXMLElement, returning as MySimpleXML instance
        }
        return $return;
    }
}

Now I can create an instance of MySimpleXML, run an xpath, and get my results back as an array of MySimpleXML elements instead of the native SimpleXMLElement:

$mySimpleXml = new mySimpleXml('<root><node/></root>');

$array = $mySimpleXml->xpath('/root/node'); // returns array with a single MySimpleXml object


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

siraic at gmail dot com 20-Jun-2023 08:47
LibXML typically uses ten times the file size in memory to read a file, and this memory usage falls largely outside the memory limit guarded by PHP.
tg at debian dot org 20-Feb-2022 09:36
This function does not accept all pathnames, in spite of its documentation.

$ php -r 'print_r( simplexml_load_file("%25.xml"));'
PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "%25.xml" in Command line code on line 1
visualmind at nospam dot php dot net 18-Jan-2022 02:49
This may sometimes get missed, but if your xml nodes are in the format:
<prefix:element />

You need to make sure to set the [namespace or prefix] argument and the [isPrefix] argument to true. Also when recalling elements you need to avoid adding the prefix if that is already set, so in the above example "prefix:element" should be added as "element" but when saved the prefix will be added automatically.

If prefix is not set during load or object construction, load will fail to get the nodes correctly and you will not be able to recall elements directly so $xml->{'prefix:element'} will not work either.
sirgrayjn at gmail dot com 22-Sep-2016 09:51
// Be carefull if you migrate or use local machine
// for test/development.

// Windows directory separators: "\" and "/"
// You may mix separators "C:\somedir\www/img/bg.jpg".

// Mixed separators path work fine in other functions
// But simplexml_load_file() failed with mixed separators.

// Examples:
include("C:\dir\my.php");    // work (windows)
include("C:\dir/my.php");    // work (windows) with mixed
include("C:/dir/my.php");    // work (windows, linux)
simplexml_load_file("C:\dir\my.php");    // work
simplexml_load_file("C:\dir/my.php");    // failed with mixed
simplexml_load_file("C:/dir/my.php");    // work
rex111 at bigmir dot net 08-Sep-2016 03:02
Get all tags and their values. (recursive)

<?php
$xml = simplexml_load_file('settings.xml');

function all_tag($xml){
    $i=0; $name = "";
    foreach ($xml as $k){
        $tag = $k->getName();
        $tag_value = $xml->$tag;
        if ($name == $tag){ $i++;    }
                $name = $tag;
            echo $tag .' '.$tag_value[$i].'<br />';
        // recursive
           all_tag($xml->$tag->children());
    }
}

all_tag($xml);
?>
Rich 24-Nov-2015 02:51
I stumbled on this: a single element with a simple string in it becomes a string, but a single element with a *space* in it becomes an Array, with one element, the string space.

I'm sure to XML mystics this is wise and wonderful but it really confused me,  and I thought it might confuse others.

<?php
$parsed = simplexml_load_string('<container><space> </space><blank></blank><string>hello</string></container>');
$content = json_decode(json_encode($parsed),TRUE);
var_dump($content);
/* Output is:
array(3) {
  'space' => array(1) {           ? did NOT expect this!
    [0] => string(1) " "
  }
  'blank' => array(0) { }
  'string' => string(5) "hello"
}
 */
tuxedobob 30-Jun-2015 01:25
Occasionally you may try to load a file and have it complain about an entity and throw a parser error.

If this is the case, check to make sure that the file in question does not contain an ampersand (&) without a corresponding entity reference.

If it does, or if you want to err on the side of caution, then instead of using simplexml_load_file, try this:

$file = file_get_contents('stuff.xml');
$temp = preg_replace('/&(?!(quot|amp|pos|lt|gt);)/', '&amp;', $file);
$xml = simplexml_load_string($temp) or die("xml not loading");

Read the file into a string, add 'amp;' after any '&' that is not part of a character entity, then parse the string as xml.
kannan at 99deals dot in 04-Sep-2012 06:27
If you have some nodes which are having special characters, it would not load properly

for an instance see the nodes below
<node:number>1538-7445</node:number>
<node:coverDisplayDate>Sep  1 2012 12:00:00:000AM</node:coverDisplayDate>

either you have to change the : to other special characters like '-' in order to convert it properly

Correct Node
<node-number>1538-7445</node-number>
<node-coverDisplayDate>Sep  1 2012 12:00:00:000AM</node-coverDisplayDate>

I have wasted my precious time while debugging this. Please aware about this. ?
ricardo at ricardomartins dot info 21-Aug-2012 05:49
Sometimes we have xml's with hyphens nodes, like

<my_xml>
 <some-node>value</some-node>
</my_xml>

You'll need to use
<?php
$simpleXmlObj->{'some-node'}
?>

instead of
<?php
$simpleXmlObj->some-node;
?>
fusionstream at gmail dot com 05-Apr-2012 04:15
If you are loading many files, this may slow down your page load time.

To set a timeout, use file_get_context and then simplexml_load_string

<?php

$fp = fopen('http://www.example.com/rss', false, stream_create_context(array('http' => array('timeout', '1.5'))));

if ($fp) {
    print_r( simplexml_load_string($fp) );
} else {
    echo "The request timed out";
}
?>
sean at aliencreations dot com 17-Mar-2011 10:59
If you find that you are receiving 500 errors with simplexml_load_file() but you can access the xml/rss feed manually through a browser, your script is probably being blocked by a user agent sniffer.

Add this code before your xml call to remedy this issue

<?php

ini_set("user_agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
ini_set("max_execution_time", 0);
ini_set("memory_limit", "10000M");

$rss = simplexml_load_file($feed_url);

?>
Nanuit at ossi dot at 08-Feb-2011 01:51
A little function very helpfull in using simplexml_load_file behind a proxy

<?php
function getXMLfromURL($url) {
      $Proxy = getenv("HTTP_PROXY");

      if (strlen($Proxy) > 1) {
        $r_default_context = stream_context_get_default ( array
                    ('http' => array(
                        'proxy' => $Proxy,
                        'request_fulluri' => True,
                    ),
                )
            );
        libxml_set_streams_context($r_default_context);
      }
      $daten = simplexml_load_file($url);
      return ($daten);
    }
?>

where HTTP_PROXY is set to e.g.: tcp://proxy:8080
guego dot ol at ig dot com dot br 12-Nov-2010 03:26
Analyze fully XML.

<?php
$xml = simplexml_load_file('file.xml');

foreach($xml as $key0 => $value){
echo "..1..[$key0] => $value";
foreach($value->attributes() as $attributeskey0 => $attributesvalue1){
echo "________[$attributeskey0] = $attributesvalue1";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value as $key => $value2){
echo "....2.....[$key] => $value2";
foreach($value2->attributes() as $attributeskey => $attributesvalue2){
echo "________[$attributeskey] = $attributesvalue2";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value2 as $key2 => $value3){
echo ".........3..........[$key2] => $value3";
foreach($value3->attributes() as $attributeskey2 => $attributesvalue3){
echo "________[$attributeskey2] = $attributesvalue3";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value3 as $key3 => $value4){
echo "...................4....................[$key3] => $value4";
foreach($value4->attributes() as $attributeskey3 => $attributesvalue4){
echo "________[$attributeskey3] = $attributesvalue4";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value4 as $key4 => $value5){
echo ".....................5......................[$key4] => $value5";
foreach($value5->attributes() as $attributeskey4 => $attributesvalue5){
echo "________[$attributeskey4] = $attributesvalue5";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value5 as $key5 => $value6){
echo "......................6.......................[$key5] => $value6";
foreach($value6->attributes() as $attributeskey5 => $attributesvalue6){
echo "________[$attributeskey5] = $attributesvalue6";
}
echo '<br />';
}}}}}
echo '<br />';
}
?>
raduispas at gmail dot com 21-Oct-2010 06:12
if you want to check when this function fails,make sure to compare the return value with ===  instead of == :

<?php
$url = 'http://www.example.com';
$xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);
if($xml ===  FALSE)
{
   //deal with error
}
else { //do stuff }
?>

Otherwise you may end up with FALSE all the time even if the document is ok. Hope this helps someone ;)
jamie at splooshmedia dot co dot uk 31-Mar-2010 06:17
A wrapper around simplexml_load_file to circumvent nasty error messages when the xml server times out or gives a 500 error etc.

<?php
function loadXML2($domain, $path, $timeout = 30) {

    /*
        Usage:

        $xml = loadXML2("127.0.0.1", "/path/to/xml/server.php?code=do_something");
        if($xml) {
            // xml doc loaded
        } else {
            // failed. show friendly error message.
        }
    */

    $fp = fsockopen($domain, 80, $errno, $errstr, $timeout);
    if($fp) {
        // make request
        $out = "GET $path HTTP/1.1\r\n";
        $out .= "Host: $domain\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);

        // get response
        $resp = "";
        while (!feof($fp)) {
            $resp .= fgets($fp, 128);
        }
        fclose($fp);
        // check status is 200
        $status_regex = "/HTTP\/1\.\d\s(\d+)/";
        if(preg_match($status_regex, $resp, $matches) && $matches[1] == 200) {
            // load xml as object
            $parts = explode("\r\n\r\n", $resp);
            return simplexml_load_string($parts[1]);
        }
    }
    return false;

}
?>
Smokey 14-Mar-2010 10:16
for nested and same name values i'v made up this little bit for getting and displaying multiable values from google's geocode when a exact match is not found it returns all close matches in the following format(this is an abriged version of there output)

<Response>
  <Placemark id="1">
    <address> New York 24, NY, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.5850086,40.7207442,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="2">
    <address>New York 27, NY, USA</address>
    <AddressDetails>
      ...................
    </AddressDetails>
    <Point>
      <coordinates>-72.8987835,40.8003588,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="3">
    <address>Cedar Place School, 20 Cedar Pl, Yonkers, NY 10705, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.8966320,40.9256520,0</coordinates>
    </Point>
  </Placemark>
</Response>

<?php
// get and breakdown the results then store them in $var's
$Address = "99999 parkplace, new york, NY";
$urladdress = urlencode($Address);
$Base_url = "http://maps.google.com/maps/geo?q=";
$urlParts = "&output=xml";
$urlrequest = $Base_url . $urladdress . $urlParts;
$xml = simplexml_load_file($urlrequest);
$num = "0";
foreach ($xml->Response->Placemark as $value){
    $num++;
    $GeoFindAdd{$num} = $value->address;
    $GeoFindCords{$num} = $value->Point->coordinates;
}

// a simple display for the results
echo "Found ",$num," Possable Geo Data Sets <br>";
$CountNumResults = "0";
for ( ; $num > 0; $num--){
    $CountNumResults++;
    echo $countnum,"<br> Address = ",$GeoFindAdd{$num},"<br> Coordinates = ",$GeoFindCords{$num},"<br>";
}
echo "END";
?>
knl at bitflop dot com 11-Sep-2009 12:02
If you need to parse the data from SimpleXML into a session variable remember to define the data as a string first.

If you don't you will get warnings of "Node no longer exists" pointing to your session_start() function.

This will work:

<?php

    $new_version = simplexml_load_file('http://example.com/version.xml');
    $_SESSION['current_version'] = (string)$new_version->version;

?>
neil art neilanddeb dort com 17-Aug-2009 06:00
Because the encoding of my XML file is UTF-8 and the
encoding of my web page is iso-8859-1 I was getting strange characters such as â€™ instead of a right single quote.

The solution to this turned out to be hard to find, but really easy to implement.

http://uk3.php.net/manual/en/function.iconv.php

Using the iconv() function you can convert from one encodign to another, the TRANSLIT option seems to work best for what I needed.  Here's my example:

<?php
// convert string from utf-8 to iso8859-1
$horoscope = iconv( "UTF-8", "ISO-8859-1//TRANSLIT", $horoscope );
?>

I found the solution on this page...
http://tinyurl.com/lm39xc
Hope this helps
cryonyx at cerebrate dot ru 21-Oct-2008 03:34
In case you have a XML file with a series of equally named elements on one level simplexml incorrectly processes them and doesn't allow to walk through the array using foreach(). As far as I'm concerned, it is the problem caused by PHP xml_parser (see: http://ru2.php.net/manual/ru/function.xml-parser-create.php#53188).

To avoid this, just use count() and walk through the array using for().

Example:

<params>
  <param>
    <name>version.shell</name>
    <value>1.0</value>
  </param>
  <param>
      <name>version.core</name>
      <value>1.0</value>
  </param>
  <param>
      <name>file.lang</name>
      <value>vc.lang</value>
  </param>
  ...
</params>

<?php
$filename = '...';
$xml = simplexml_load_file($filename);
$p_cnt = count($xml->param);
for($i = 0; $i < $p_cnt; $i++) {
  $param = $xml->param[$i];
  ...;
}
?>
mario 02-Sep-2008 02:08
If you want CDATA in your object you should use LIBXML_NOCDATA

<?php
$xml = simplexml_load_file($file_xml, 'SimpleXMLElement',LIBXML_NOCDATA);

    print_r($xml);
?>
l [DOT] anzinger [AT] gmail [DOT] com 26-Mar-2008 09:03
If you don't want that the CDATA values get escaped, just load the XML with LIBXML_NOCDATA as an 3rd argument.

Note: A PHP version >= 5.1.0 is required for this to work.

Example:

<?php simplexml_load_file('xmldatei.xml', null, LIBXML_NOCDATA); ?>
php at werner dash ott dot de 29-Mar-2007 01:13
Making SimpleXMLElement objects session save.

Besides the effect of not surviving sessions, the SimpleXMLElement object may even crash the session_start() function when trying to re-enter the session!

To come up with a solution for this, I used a pattern as follows. The core idea is to transform the SimpleXMLElement between session calls to and from a string representation which of course is session save.

<?php
  //
  // session save handling of SimpleXMLElement objects
  // (applies to/ tested with PHP 5.1.5 and PHP 5.2.1)
  // The myClass pattern allows for conveniently accessing
  // XML structures while being session save
  //
  class myClass
  {
    private $o_XMLconfig = null;
    private $s_XMLconfig = '';

    public function __construct($args_configfile)
    {
      $this->o_XMLconfig = simplexml_load_file($args_configfile);
      $this->s_XMLconfig = $this->o_XMLconfig->asXML();
    } // __construct()

    public function __destruct()
    {
      $this->s_XMLconfig = $this->o_XMLconfig->asXML();
      unset($this->o_XMLconfig); // this object would otherwise crash
                                 // the subsequent call of
                                 // session_start()!
    } // __destruct()

    public function __wakeup()
    {
      $this->o_XMLconfig = simplexml_load_string($this->s_XMLconfig);
    } // __wakeup()

  } // class myClass
?>
wouter at code-b dot nl 20-Feb-2007 02:08
To correctly extract a value from a CDATA just make sure you cast the SimpleXML Element to a string value by using the cast operator:

<?php
$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<rss>
    <channel>
        <item>
            <title><![CDATA[Tom & Jerry]]></title>
        </item>
    </channel>
</rss>';

$xml = simplexml_load_string($xml);

// echo does the casting for you
echo $xml->channel->item->title;

// but vardump (or print_r) not!
var_dump($xml->channel->item->title);

// so cast the SimpleXML Element to 'string' solve this issue
var_dump((string) $xml->channel->item->title);
?>

Above will output:

Tom & Jerry

object(SimpleXMLElement)#4 (0) {}

string(11) "Tom & Jerry"
Kyle 10-Dec-2006 02:35
In regards to Anonymous on 7th April 2006

There is a way to get back HTML tags. For example:

<?xml version="1.0"?>
<intro>
    Welcome to <b>Example.com</b>!
</intro>

<?php
// I use @ so that it doesn't spit out content of my XML in an error message if the load fails. The content could be passwords so this is just to be safe.
$xml = @simplexml_load_file('content_intro.xml');
if ($xml) {
    // asXML() will keep the HTML tags but it will also keep the parent tag <intro> so I strip them out with a str_replace. You could obviously also use a preg_replace if you have lots of tags.
    $intro = str_replace(array('<intro>', '</intro>'), '', $xml->asXML());
} else {
    $error = "Could not load intro XML file.";
}
?>

With this method someone can change the intro in content_intro.xml and ensure that the HTML is well formed and not ruin the whole site design.
Anonymous 06-Apr-2006 09:21
What has been found when using the script is that simplexml_load_file() will remove any HTML formating inside the XML file, and will also only load so many layers deep. If your XML file is to deap, it will return a boolean false.
fdouteaud at gmail dot com 09-Mar-2006 05:21
Be careful if you are using simplexml data directly to feed your MySQL database using MYSQLi and bind parameters.

The data coming from simplexml are Objects and the bind parameters functions of MySQLi do NOT like that! (it causes some memory leak and can crash Apache/PHP)

In order to do this properly you MUST cast your values to the right type (string, integer...) before passing them to the binding methods of MySQLi.
I did not find that in the documentation and it caused me a lot of headache.
info at evasion dot cc 06-Feb-2006 08:26
Sorry there's a mistake in the previous function :
<?php
   function &getXMLnode($object, $param) {
       foreach($object as $key => $value) {
           if(isset($object->$key->$param)) {
               return $object->$key->$param;
           }
           if(is_object($object->$key)&&!empty($object->$key)) {
               $new_obj = $object->$key;
               // Must use getXMLnode function there (recursive)
               $ret = getXMLnode($new_obj, $param);

           }
       }
       if($ret) return (string) $ret;
       return false;
   }
?>
skutter at imprecision dot net 03-Feb-2006 09:11
So it seems SimpleXML doesn't support CDATA... I bashed together this little regex function to sort out the CDATA before trying to parse XML with the likes of simplexml_load_file / simplexml_load_string. Hope it might help somebody and would be very interested to hear of better solutions. (Other than *not* using SimpleXML of course! ;)

It looks for any <![CDATA [Text and HTML etc in here]]> elements, htmlspecialchar()'s the encapsulated data and then strips the "<![CDATA [" and "]]>" tags out.

<?php
function simplexml_unCDATAise($xml) {
    $new_xml = NULL;
    preg_match_all("/\<\!\[CDATA \[(.*)\]\]\>/U", $xml, $args);

    if (is_array($args)) {
        if (isset($args[0]) && isset($args[1])) {
            $new_xml = $xml;
            for ($i=0; $i<count($args[0]); $i++) {
                $old_text = $args[0][$i];
                $new_text = htmlspecialchars($args[1][$i]);
                $new_xml = str_replace($old_text, $new_text, $new_xml);
            }
        }
    }

    return $new_xml;
}

//Usage:
$xml = 'Your XML with CDATA...';
$xml = simplexml_unCDATAise($xml);
$xml_object = simplexml_load_string($xml);
?>
info at evasion dot cc 03-Feb-2006 03:37
Suppose you have loaded a XML file into $simpleXML_obj.
The structure is like below :

SimpleXMLElement Object
(

    [node1] => SimpleXMLElement Object
        (
            [subnode1] => value1
            [subnode2] => value2
            [subnode3] => value3
        )

    [node2] => SimpleXMLElement Object
        (
            [subnode4] => value4
            [subnode5] => value5
            [subnode6] => value6
        )

)

When searching a specific node in the object, you may use this function :

<?php

    function &getXMLnode($object, $param) {
        foreach($object as $key => $value) {
            if(isset($object->$key->$param)) {
                return $object->$key->$param;
            }
            if(is_object($object->$key)&&!empty($object->$key)) {
                $new_obj = $object->$key;
                $ret = getCfgParam($new_obj, $param);
            }
        }
        if($ret) return (string) $ret;
        return false;
    }
?>

So if you want to get subnode4 value you may use this function like this :

<?php
$result = getXMLnode($simpleXML_obj, 'subnode4');
echo $result;
?>

It display "value4"
genialbrainmachine at NOSPAM dot tiscali dot it 30-Sep-2005 08:52
Micro$oft Word uses non-standard characters and they create problems in using simplexml_load_file.
Many systems include non-standard Word character in their implementation of ISO-8859-1. So an XML document containing that characters can appear well-formed (i.e.) to many browsers. But if you try to load this kind of documents with simplexml_load_file you'll have a little bunch of troubles..
I believe that this is exactly the same question discussed in htmlentites. Following notes to htmlentitles are interesting here too (given in the reverse order, to grant the history):
http://it.php.net/manual/en/function.htmlentities.php#26379
http://it.php.net/manual/en/function.htmlentities.php#41152
http://it.php.net/manual/en/function.htmlentities.php#42126
http://it.php.net/manual/en/function.htmlentities.php#42511
mark 12-Sep-2005 11:06
If the property of an object is empty the array is not created. Here is a version object2array that transfers properly.

<?php
function object2array($object)
{
    $return = NULL;

    if(is_array($object))
    {
        foreach($object as $key => $value)
            $return[$key] = object2array($value);
    }
    else
    {
        $var = get_object_vars($object);

        if($var)
        {
            foreach($var as $key => $value)
                $return[$key] = ($key && !$value) ? NULL : object2array($value);
        }
        else return $object;
    }

    return $return;
}
?>


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
    • wddx examples
  • WDDX Funciones
    • wddx_add_vars — Add variables to a WDDX packet with the specified ID
    • wddx_deserialize — Unserializes a WDDX packet
    • wddx_packet_end — Ends a WDDX packet with the specified ID
    • wddx_packet_start — Starts a new WDDX packet with structure inside it
    • wddx_serialize_value — Serialize a single value into a WDDX packet
    • wddx_serialize_vars — Serialize variables into a WDDX packet

User Contributed Notes

There are no user contributed notes for this page.


Introducción

Advertencia

This extension is DEPRECATED and UNBUNDLED as of PHP 7.4.0.

These functions are intended for work with » WDDX.

Advertencia

Do not pass untrusted user input to wddx_deserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

User Contributed Notes

alvaro at demogracia dot com 29-Sep-2008 08:49
From OpenWDDX.Org:

"The Web Distributed Data Exchange, or WDDX, is a free, open XML-based technology that allows Web applications created with any platform to easily exchange data with one another over the Web."

"WDDX is an XML-based technology that enables the exchange of complex data between Web programming languages, creating what some refer to as 'Web syndicate networks'. WDDX consists of a language-independent representation of data based on an XML 1.0 DTD, and a set of modules for a wide variety of languages that use WDDX. WDDX can be used with HTTP, SMTP, POP, FTP and other Internet protocols that support transferring textual data."


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.

In order to use WDDX, you will need to install the expat library (which comes with Apache 1.3.7 or higher).

User Contributed Notes

There are no user contributed notes for this page.


Instalación

PHP 7.4

Esta extensión se ha movido al repositorio de » PECL y ya no se distribuye con PHP a partir de PHP 7.4.0

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/wddx.

PHP < 7.4

After installing the required expat library, compile PHP with --enable-wddx, and use --with-libexpat-dir for 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

This extension defines a WDDX packet identifier returned by wddx_packet_start().

User Contributed Notes

There are no user contributed notes for this page.


Ejemplos

Tabla de contenidos

  • wddx examples

User Contributed Notes

dormilich at netscape dot net 27-Nov-2008 06:37
If you want to use the WDDX 1.0 DTD for validation (http://www.openwddx.org/downloads/dtd/wddx_dtd_10.txt) check that you define the comment as element, not as attribute.

<?xml version="1.0" encoding="iso-8859-1" ?>
<wddxPacket version='1.0'>
    <header>
        <comment>PHP</comment>
    </header>
    <data><!-- WDDX serialized data --></data>
</wddxPacket>


wddx examples

All the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.

Ejemplo #1 Serializing a single value with WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Ejemplo #2 Using incremental packets with WDDX

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo $packet;
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP'/><data><struct>
<var name='pi'><number>3.1415926</number></var><var name='cities'>
<array length='3'><string>Austin</string><string>Novato</string>
<string>Seattle</string></array></var></struct></data></wddxPacket>

Nota:

Strings should be encoded in UTF-8; to handle other encodings, convert the string first using mb_convert_encoding(), UConverter::transcode(), or iconv().

User Contributed Notes

There are no user contributed notes for this page.


WDDX Funciones

Tabla de contenidos

  • wddx_add_vars — Add variables to a WDDX packet with the specified ID
  • wddx_deserialize — Unserializes a WDDX packet
  • wddx_packet_end — Ends a WDDX packet with the specified ID
  • wddx_packet_start — Starts a new WDDX packet with structure inside it
  • wddx_serialize_value — Serialize a single value into a WDDX packet
  • wddx_serialize_vars — Serialize variables into a WDDX packet

User Contributed Notes

iGEL 14-Mar-2008 02:03
As of version 5.2.5, this is wrong:

> Note: If you want to serialize non-ASCII characters you
> have to convert your data to UTF-8 first (see utf8_encode()
> and iconv()).

Serializing a string with WDDX will always convert it from ISO-8859-1 to UTF-8, no matter what the original encoding is. So if your data already are UTF-8, you get just gibberish.

You can restore the original encoding by using utf8_decode on the serialized wddx data, even though your original data may use chars not included in ISO-8859-1:

<?php
header("Content-Type: text/xml;encoding=utf-8");
echo utf8_decode(wddx_serialize_value("?? ???"));
?>

(This is why I dislike PHP, sorry)
egbert teeselink 23-Feb-2008 10:49
If your PHP doesn't have wddx support installed, and you need it, and you don't want to install PEAR just for wddx, try this short piece of code, based on SimpleXML:

//can read any wddx file generated from php arrays. assumes var elements are only inside struct elements and that only one packet exists.
function wddx_read_node($node, $type)
{
    switch($type)
    {
    case "boolean":
        return (string)$node;
    case "number":
    case "binary":
    case "string":
        return (string)$node;
    case "null":
        return null;
    case "array":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            $a[] = wddx_read_node($subnode, $subtype);
        }
        return $a;
    case "struct":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            list($key, $value) = wddx_read_node($subnode, $subtype); //must be a var element
            $a[$key] = $value;
        }
        return $a;
    case "var":
        list($subnode, $subtype) = getchild($node);
        return array((string)$node["name"], wddx_read_node($subnode, $subtype));
    case "data":
        list($subnode, $subtype) = getchild($node);
        return wddx_read_node($subnode, $subtype);
    }
}

function wddx_read($string)
{
    $xml = simplexml_load_string($string);
    $d = wddx_read_node($xml->data, "data");
    return $d;
}

important notice: this one may not work with all wddx input. multiple packets or variables outside a "struct" are not supported. basically, you always get a PHP (associative) array, never something else. feel free to make additions.
no at spam dot thx 12-Aug-2007 02:09
To bradburn at kiwi dot de:

PHP is only capable of serializing properly variables which match one of its native (scalar) types (See http://php.net/types). Which means that only variables of type booleans, integers, floating point numbers, string and NULL will be serialized properly.

I think there are two exceptions though:
- arrays are serialized by processing them recursively, so if its only composed of the above mentioned types, you should be fine.
- floating point numbers and integers may use the same representation while serialized in WDDX (I don't know much about WDDX, so I'm not 100% sure about this statement).

An interesting case would be whether objects can be serialized or not...
Jimmy Wimenta 15-Jul-2004 05:53
PHP's WDDX is useful only for exchanging data between PHP applications, but definetly not for exchanging data between different languages (which actually defeats the purpose of WDDX).

For example:

$hash1 = array ("2" => "Two", "4" => "Four", "5" => "Five");
$hash2 = array ("0" => "Zero", "1" => "One", "2" => "Two");

$hash1 will be serialized as hash, but
$hash2 will be serialized as array/list, because the key happen to be a sequence starting from 0.

Unless the library provide a way for users to specify the type, it can never be used for cross-platform data exchange.
Q1tum at hotmail dot com 21-Nov-2003 05:08
To insert arrays into a wddx variable here is a fine way to do it:

<?php

$sql = 'SELECT * FROM example';
$query = mysql_query($sql, $db) or die(mysql_error());

while($result = mysql_fetch_array($query)) {
    $id[] = $result[ 'id'];
    $name[] = $result['name'];
    $description[] = $result[$prefix . 'description'];
}

mysql_free_result($query);

wddx_add_vars($packet_id, "id");
wddx_add_vars($packet_id, "name");
wddx_add_vars($packet_id, "description");

$wddxSerializeValue = wddx_packet_end($packet_id);

?>
bradburn at kiwi dot de 30-Jul-2002 07:02
With ref to the above comment about typing, I have found that -- oddly enough -- PHP's WDDX supports the following WDDX types: null, boolean (true/false), number and string, *but* not date-time.

as an example, use the following values in an array that you then serialize:

$number = 5,
$null = NULL,
$bool = true,
$string = 'this is a string'.

they will all serialize correctly, e.g. the third entry comes out as:

<var name='bool'><boolean value='true'/></var>

i have tried with the 'official' format for WDDX 'datetime', e.g. '1998-9-15T09:05:32+4:0' (from the DTD @ http://www.openwddx.org/downloads/dtd/wddx_dtd_10.txt)  but have only succeeded in getting this encoded as a 'string' type.

if anyone else has any more information on this, it would be welcome. i would like to store the variables in 'appropriate' fields in a database, and the fact that only datetime is not supported is slightly irritating -- otherwise it would be a very useful function.
djm at web dot us dot uu dot net 18-Oct-1999 08:45
Since there aren't any examples of reversing the process, here's one. If you had the packet produced by the above example (without the htmlentities() call), you could retrieve the values like this:

<?php
$value = wddx_deserialize($packet);
print "pi is:<br>" . $value["pi"] . "<p>\n";
print "cities is:<br>\n";
while (list($key, $val) = each($value["cities"])) {
    print "$key => $val<br>\n";
}
?>

which outputs:

<pre>
pi is:
3.1415926

cities is:
0 => Austin
1 => Novato
2 => Seattle
</pre>


Add variables to a WDDX packet with the specified ID

  • « WDDX Funciones
  • wddx_deserialize »
  • PHP Manual
  • WDDX Funciones
  • Add variables to a WDDX packet with the specified ID

wddx_add_vars

(PHP 4, PHP 5, PHP 7)

wddx_add_vars — Add variables to a WDDX packet with the specified ID

Advertencia

This function was REMOVED in PHP 7.4.0.

Descripción

wddx_add_vars(resource $packet_id, mixed $var_name, mixed ...$var_names): bool

Serializes the passed variables and add the result to the given packet.

Parámetros

This function takes a variable number of parameters.

packet_id

A WDDX packet, returned by wddx_packet_start().

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

var_names

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 !


Unserializes a WDDX packet

  • « wddx_add_vars
  • wddx_packet_end »
  • PHP Manual
  • WDDX Funciones
  • Unserializes a WDDX packet

wddx_deserialize

(PHP 4, PHP 5, PHP 7)

wddx_deserialize — Unserializes a WDDX packet

Advertencia

This function was REMOVED in PHP 7.4.0.

Descripción

wddx_deserialize(string $packet): mixed

Unserializes a WDDX packet.

Advertencia

Do not pass untrusted user input to wddx_deserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

Parámetros

packet

A WDDX packet, as a string or stream.

Valores devueltos

Returns the deserialized value which can be a string, a number or an array. Note that structures are deserialized into associative arrays.

User Contributed Notes

valer underscore crisan at yahoo 01-Apr-2009 02:03
In PHP 5.2.9, we noticed that wddx serialize and deserialize seems to use UTF-8 encoding for XML input and the output data. There are some posts below that talk about fixing the input XML data so deserialize would work fine on special chars in ISO-8859-1 encoding, but none of the posts talks about the output encoding.

Consider this test:
$text = "Jür";
$packet = wddx_serialize_value($text);
$header = '<?xml version="1.0" encoding="iso-8859-1"?>';
$newText = wddx_deserialize($header . $packet);
echo "WDDX Packet: $packet\n";
echo "Deserialized Object: $newText\n";

The output is:

WDDX Packet: <wddxPacket version='1.0'><header/><data><string>Jür</string></data></wddxPacket>
Deserialized Object: JÃ¼r

The deserialized string is not in ISO-8859-1 encoding. It is in UTF-8 encoding. So we need to run utf8_decode() on the deserialized data to convert it back to ISO-8859-1 encoding which is what our application expects.

Hope this helps.
Magnus Deininger, dma05 at web dot de 12-Feb-2009 05:57
When writing your wddx file manually with an UTF-8 aware editor and saving it in utf-8, if your data gets its special characters mysteriously scrambled, try to add an xml header that marks the output as iso-8859-1, like this one:

<?xml version="1.1" encoding="iso-8859-1" ?>

This makes the wddx decode function treat the input as iso-8859-1, so it will not try to treat it as utf-8 and do an implicit decode to iso-8859-1. You will then have read all string data in the wddx packet in their original utf-8 encoding, so that 'echo' and other output functions will produce the intended result if you have set the output encoding to utf-8.

(Bugs reports on this behaviour seem to be treated as bogus, so it would seem in order to point out this incorrect and highly confusing side-effect.)
dormilich at netscape dot net 28-Nov-2008 05:13
When deserializing objects make sure you have the class definition loaded. wddx_deserialize() doesn't call the class itself, so you will receive a fatal error.
Nevertheless you can look for the class manually and delegate it to __autoload().

<?php
// $wddx_string needs to be valid XML to be loaded by SimpleXML.
// class_exists() will call the __autoload() function. if you don't
// want to use __autoloload(), use require_once()

function loadClassesFromWDDX($wddx_string)
{
    $xml = new SimpleXMLElement($wddx_string);

    foreach ($xml->xpath('//var') as $var)
    {
        if ($var['name'] == 'php_class_name')
        {
            if (!class_exists($var->string))
            {
                throw new Exception('Class '" . $var->string . "'not available.');
                // trigger_error('Class '" . $var->string . "'not available.', E_USER_ERROR);
            }
        }
    }
}
?>
dave at codexweb dot co dot za 21-Jan-2006 04:40
Here's a handy wddx_deserialize clone I wrote a while back. It uses PHP5 SimpleXML and recursion to do pretty much the same task as wddx_deserialize. Hope it comes in handy for someone.

<?php

if (!function_exists('wddx_deserialize'))
{
    /**
     * Clone implementation of wddx_deserialize
     */
    function wddx_deserialize($xmlpacket)
    {
        if ($xmlpacket instanceof SimpleXMLElement)
        {
            if (!empty($xmlpacket->struct))
            {
                $struct = array();
                foreach ($xmlpacket->xpath("struct/var") as $var)
                {
                    if (!empty($var["name"]))
                    {
                        $key = (string) $var["name"];
                        $struct[$key] = wddx_deserialize($var);
                    }
                }
                return $struct;
            }
            else if (!empty($xmlpacket->array))
            {
                $array = array();
                foreach ($xmlpacket->xpath("array/*") as $var)
                {
                    array_push($array, wddx_deserialize($var));
                }
                return $array;
            }
            else if (!empty($xmlpacket->string))
            {
                return (string) $xmlpacket->string;
            }
            else if (!empty($xmlpacket->number))
            {
                return (int) $xmlpacket->number;
            }
            else
            {
                if (is_numeric((string) $xmlpacket))
                {
                    return (int) $xmlpacket;
                }
                else
                {
                    return (string) $xmlpacket;
                }
            }
        }
        else
        {
            $sxe = simplexml_load_string($xmlpacket);
            $datanode = $sxe->xpath("/wddxPacket[@version='1.0']/data");
            return wddx_deserialize($datanode[0]);
        }
    }
}

?>
php dot net at werner-ott dot de 24-Nov-2005 12:20
On migrating wddx_deserialize() from PHP 4.x to PHP 5.1 (5.1.0RC6):

While

  $buffer = wddx_serialize_vars($some_array);
  $some_array = wddx_deserialize($buffer);

worked fine with PHP 4.x, the deserialization failed with PHP 5.1. In the above example $some_array will just be an empty string under 5.1

While wddx_serialize_vars() seems to behave identical in 4.x and 5.1, wddx_deserialize() does NOT.

Prepending XML encoding information to the buffer turned out to be at least a workaround. So, the following works with PHP 5.1:

  $buffer = wddx_serialize_vars($some_array);
  $buffer = '<?xml version="1.0"
          encoding="ISO-8859-1"?>'.
          $buffer;
  $some_array = wddx_deserialize($buffer);

NB: It may well be, that the behavioural difference between 4.x and 5.1 described above can only be observed if the array contains certain characters, i.e. german Umlaute (??????). So this workaround may not be necessary in each and every case.
mail_fidel at yahoo dot com 19-Nov-2004 12:11
To properly deserialize a wddx file it was to be utf8_encoded.

The following code will NOT work (PHP5.0.2 FreeBSD):

<?php
   $data = wddx_serialize_value(array("xyz???","abcd"));
   print $data;
   print_r(wddx_deserialize($data));

?>

Even thought the serialization is done right, the deserialization will not work unless you encode the text using utf8.

This code WILL work:

<?php
   $data = wddx_serialize_value(array(utf8_encode("xyz???"),"abcd"));
   print $data;
   print_r(wddx_deserialize($data));

?>
xavier at c-est-simple dot com 19-May-2004 04:09
JavaScript/PHP interroperability:

If you want to exchange wddx packets between a JavaScript application using the JS wddx library from openwddx (http://www.openwddx.org/downloads/), and a PHP script using wddx functions, be aware that the encoding of the classes of objects serialized in the wddx packet is not made the same way in both implementations.

The JS lib uses a 'type' attribute in the 'struct' tab and gives it the name of the class of the object serialized in the 'struct' element, while PHP uses a 'php_class_name' tag within the 'struct'.
NB : to get the type attribute with JS serialisation, you need to set the 'wddxSerializationType' member in your classes

Example with an object of class 'exemple' containing 2 members _attr1 and _attr2.
(NB : in french, 'example' is spelled 'exemple', okay ? :-)

JS serialization :
<wddxPacket version='1.0'>
 <header/>
 <data>
  <struct type="exemple">
   <var name='_attr1'>
    <string>foo</string>
   </var>
   <var name='_attr2'>
    <string>bar</string>
   </var>
  </struct>
 </data>
</wddxPacket>

php serialization:
<wddxPacket version='1.0'>
 <header/>
 <data>
  <struct>
   <var name='php_class_name'>
    <string>exemple</string>
   </var>
   <var name='_attr1'>
    <string>foo</string>
   </var>
   <var name='_attr2'>
    <string>bar</string>
   </var>
  </struct>
 </data>
</wddxPacket>

I like the JS approach better.
So if you need the compatibility, the workaround is quite simple:
- add a 'php_class_name' member in your JS objects, giving it the name of the class for value, and the JS generated packet will be correctly deserialized with PHP in classed objects.

- use a regexp on a PHP generated packet to add the 'type' attribute so that the JS deserialization instanciates objects of the right class:
      $pat = "/<struct><var name='php_class_name'><string>(\w+)<\/string>/" ;
      $rep = "<struct type='\$1'><var name='php_class_name'><string>\$1</string>" ;
      $serialised = preg_replace($pat, $rep, $serialised );
NB : this only works because the 'php_class_name' tag is just next to the 'struct' tag.
Who knows if this is going to be true in future releases... ?

This way, you can exchange JS and PHP objects (provided you define your JS and PHP classes the same way) smoothly...

It's worth saying that both implementations, as well as my interroperability workaround, handle correctly objects with members that are also objects.

NB : NB means Nota Bene.
xavier at c-est-simple.com 18-May-2004 10:19
Beware, although the deserialized objects are instanciated class objects (if the php_class_name tag is amongst the children of the struct tag and its text content is the name of a loaded class), the constructor of the class has not been called at all.
You can use the members and call the methods of the object all right, but any initialisation action that the constructor might be in charge of is missing.
php at mike2k dot com 10-Sep-2001 06:06
if you have WDDX data coming from a third party source and it isnt being parsed correctly in your php, try translating their WDDX. we have a third party sending us WDDX from cold fusion, and it uses a <recordset> element, which PHP seems to ignore (looking around the web we found some other people having trouble) so the (hopefully temporary) solution we found was to translate the WDDX midstream and then we were able to parse it:

$url = "http://somedomain.com/blah.wddx";
$fp = fopen($url,"r");
$page = fread($fp,10000);
fclose($fp);
$page = str_replace("<recordset","<struct",$page);
$page = str_replace("</recordset","</struct",$page);
$page = str_replace("<field","<var",$page);
$page = str_replace("</field","</var",$page);
$values = wddx_deserialize($page);
while(list($key,$val) = each($values)) {
        print "$key => $val<BR>";
}

this works for us. it's a hack, and hopefully php will support this in the future or something.
medvitz at medvitz dot net 14-Oct-2000 05:29
You can also serialize instantiated class objects with the wddx functions.
ie.

<?php
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "objvar");
$packet = wddx_packet_end($packet_id);

$a =  wddx_deserialize($packet);
$obj = $a[objvar];
?>

now $obj is a useable object, that looks like the original.

Note that with this method, you need to know what the variable name of the original object was.  You can use one of the array functions to get the object in the event that the original object's variable name was unknown.

*** only verified on linux with 4.0.2
djm at web dot us dot uu dot net 18-Oct-1999 09:58
The packet string you pass to this function doesn't have to be sanitized first; it searches for a WDDX packet within the string.  So the string can contain HTML markup and random text outside of the packet, and that is all ignored.
This means you can get a packet from another web page like this:
<?php
$fhandle = fopen("http://myserver.com/packet.php", "r");
if ($fhandle) {
        $page = fread($fhandle,10000);
        fclose($fhandle);
        $value = wddx_deserialize($page);
        print "pi is:<br>" . $value["pi"] . "<p>\n";
} else {
        print "could not get packet.php<p>";
}
?>


Ends a WDDX packet with the specified ID

  • « wddx_deserialize
  • wddx_packet_start »
  • PHP Manual
  • WDDX Funciones
  • Ends a WDDX packet with the specified ID

wddx_packet_end

(PHP 4, PHP 5, PHP 7)

wddx_packet_end — Ends a WDDX packet with the specified ID

Advertencia

This function was REMOVED in PHP 7.4.0.

Descripción

wddx_packet_end(resource $packet_id): string

Ends and returns the given WDDX packet.

Parámetros

packet_id

A WDDX packet, returned by wddx_packet_start().

Valores devueltos

Returns the string containing the WDDX packet.

User Contributed Notes

There are no user contributed notes for this page.


Starts a new WDDX packet with structure inside it

  • « wddx_packet_end
  • wddx_serialize_value »
  • PHP Manual
  • WDDX Funciones
  • Starts a new WDDX packet with structure inside it

wddx_packet_start

(PHP 4, PHP 5, PHP 7)

wddx_packet_start — Starts a new WDDX packet with structure inside it

Advertencia

This function was REMOVED in PHP 7.4.0.

Descripción

wddx_packet_start(string $comment = ?): resource

Start a new WDDX packet for incremental addition of variables. It automatically creates a structure definition inside the packet to contain the variables.

Parámetros

comment

An optional comment string.

Valores devueltos

Returns a packet ID for use in later functions, or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Serialize a single value into a WDDX packet

  • « wddx_packet_start
  • wddx_serialize_vars »
  • PHP Manual
  • WDDX Funciones
  • Serialize a single value into a WDDX packet

wddx_serialize_value

(PHP 4, PHP 5, PHP 7)

wddx_serialize_value — Serialize a single value into a WDDX packet

Advertencia

This function was REMOVED in PHP 7.4.0.

Descripción

wddx_serialize_value(mixed $var, string $comment = ?): string

Creates a WDDX packet from a single given value.

Parámetros

var

The value to be serialized

comment

An optional comment string that appears in the packet header.

Valores devueltos

Returns the WDDX packet, or false on error.

User Contributed Notes

chris at digitalbase dot com 04-Jan-2002 04:36
When serializing JavaScript objects to interact with PHP objects, you should make the JavaScript object's first entry a php_class_name.

PHP:
class myclass {
    var $name;
    var $age;
    var $ssn;
    ...

    function myclass() {
        $this->name = "";
        $this->age = "";
        $this->ssn = "";
        ...
    }
}

JavaScript:
// serialization example code is from the
// WDDX SDK http://www.openwddx.org
function SerializeMsg(name, age, ssn, ...) {
    var MyObj = new Object;

    // the following line is necessary in order
    // to deserialize back to a PHP object
    MyObj.php_class_name = "myclass";

    MyObj.name = name;
    MyObj.age = age;
    MyObj.ssn = ssn;
    ...

    // Create a new serializer "object" to do our work for us
    MySer = new WddxSerializer;

    // Serialize the Message variable into a WDDX Packet
    MyWDDXPacket = MySer.serialize(MyObj);

    // Output WDDX Packet so we can see what it looks like
    return MyWDDXPacket;
}

Now you can use this in a page which is its own form action:
<?php
// don't forget to include the class definition from above!
if (!isSet($wddx_packet))
    $MyObj = new myclass();
else
    $MyObj = wddx_deserialize($wddx_packet);
?>

<html>
<head>
<script language="JavaScript">
<!--
function Init() {
    // sets the form's text-elements
    tmp = document.MyForm;

    tmp.name.value = "<? echo $MyObj->name ?>";
    tmp.age.value = "<? echo $MyObj->age ?>";
    tmp.ssn.value = "<? echo $MyObj->ssn ?>";
    ...
}

function SerializeMsg(name, age, ssn, ...) {
// see above!
}

function SubmitForm() {
    // sumbits the form
    tmp = document.MyForm;

    tmp.wddx_packet.value =
    SerializeMsg(tmp.name.value, tmp.age.value, tmp.ssn.value,...);
    document.submit();
}
// -->
</script>
</head>
<body>
...
<form name="MyForm"
action="<? echo $PHP_SELF ?>" method="post">
<input name="wddx_packet" type="hidden">
<input name="name" type="text">
<input name="age" type="text">
<input name="ssn" type="text">
...
<input name="SubmitBtn" type="button" onclick="SumbitForm()">
</form>
</body>
</html>

---------------------------------
If you don't provide that first 'php_class_name' in the JavaScript function, then when PHP deserializes it will deserialize into an associative array and not an object instance.

Note that this provides a way to maintain state without
using sessions or cookies - just good old HTML!

Hope this helps!
--
Chris Hansen


Serialize variables into a WDDX packet

  • « wddx_serialize_value
  • XMLDiff »
  • PHP Manual
  • WDDX Funciones
  • Serialize variables into a WDDX packet

wddx_serialize_vars

(PHP 4, PHP 5, PHP 7)

wddx_serialize_vars — Serialize variables into a WDDX packet

Advertencia

This function was REMOVED in PHP 7.4.0.

Descripción

wddx_serialize_vars(mixed $var_name, mixed ...$var_names): string

Creates a WDDX packet with a structure that contains the serialized representation of the passed variables.

Parámetros

This function takes a variable number of parameters.

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

var_names

Valores devueltos

Returns the WDDX packet, or false on error.

Ejemplos

Ejemplo #1 wddx_serialize_vars() example

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>

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

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

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

class XMLDiff\DOM extends XMLDiff\Base {
/* Métodos */
public diff(DOMDocument $from, DOMDocument $to): DOMDocument
public merge(DOMDocument $src, DOMDocument $diff): DOMDocument
/* Métodos heredados */
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

class XMLDiff\Memory extends XMLDiff\Base {
/* Métodos */
public diff(string $from, string $to): string
public merge(string $src, string $diff): string
/* Métodos heredados */
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

class XMLDiff\File extends XMLDiff\Base {
/* Métodos */
public diff(string $from, string $to): string
public merge(string $src, string $diff): string
/* Métodos heredados */
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
    • 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

Joachim Kruyswijk 27-Jun-2022 02:08
If you use strict_types=1, you'll get the warning "Notice: Resource ID#... used as offset, casting to integer".

Use

<?php $depth[(int) $parser]  ?>

instead of

<?php $depth[$parser]  ?>
Sample at hotmail dot com 04-Jul-2013 10:32
<?php

public static function xml2array($element, $arr = array())
    {
        if(is_string($element))
        {
            $element = (strlen($element) > 5 && substr($element, -4) === '.xml')
                            ? simplexml_load_file(DATAPATH.$element)
                            : simplexml_load_string($element);
        }
         $iter = 0;
        foreach($element->children() as $b)
        {
            $a = $b->getName();
            if(!$b->children()){
                    $arr[$a] = trim($b[0]);
            }
            else{
                    $arr[$a][$iter] = array();
                    $arr[$a][$iter] = self::xml2array($b,$arr[$a][$iter]);
            }
                $iter++;
        }
        return $arr;
    }
}

?>
roan at horning dot us 30-Oct-2009 09:07
The following example will echo back an xml file using the basic event based parser.  Currently, (at least in the version of PHP5 I'm using) it will skip The XML declaration and the Doctype declaration--they don't seem to be captured by the default handler.

<?php
echo "<pre>";

$file = "test.xml";
echo $file."\n";
global $inTag;

$inTag = "";
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);
xml_set_processing_instruction_handler($xml_parser, "pi_handler");
xml_set_default_handler($xml_parser, "parseDEFAULT");
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "contents");

if (!($fp = fopen($file, "r"))) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
       die( sprintf("XML error: %s at line %d",
                            xml_error_string(xml_get_error_code($xml_parser)),
                            xml_get_current_line_number($xml_parser)));
    }
}
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
       die( sprintf("XML error: %s at line %d",
                            xml_error_string(xml_get_error_code($xml_parser)),
                            xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);

function startElement($parser, $name, $attrs) {

    global $inTag;
    global $depth;

    $padTag = str_repeat(str_pad(" ", 3), $depth);

    if (!($inTag == "")) {
        echo "&gt;";
    }
    echo "\n$padTag&lt;$name";
    foreach ($attrs as $key => $value) {
        echo "\n$padTag".str_pad(" ", 3);
        echo " $key=\"$value\"";
    }
    $inTag = $name;
    $depth++;
}

function endElement($parser, $name) {

    global $depth;
   global $inTag;
    global $closeTag;

    $depth--;

   if ($closeTag == TRUE) {
       echo "&lt/$name&gt;";
       $inTag = "";
   } elseif ($inTag == $name) {
       echo " /&gt;";
       $inTag = "";
   } else {
         $padTag = str_repeat(str_pad(" ", 3), $depth);
       echo "\n$padTag&lt/$name&gt;";
    }
}

function contents($parser, $data) {

    global $closeTag;

    $data = preg_replace("/^\s+/", "", $data);
    $data = preg_replace("/\s+$/", "", $data);

    if (!($data == ""))  {
        echo "&gt;$data";
        $closeTag = TRUE;
    } else {
        $closeTag = FALSE;
     }
}

function parseDEFAULT($parser, $data) {

    $data = preg_replace("/</", "&lt;", $data);
    $data = preg_replace("/>/", "&gt;", $data);
    echo $data;
}

function pi_handler($parser, $target, $data) {

    echo "&lt;?$target $data?&gt;\n";
}
echo "</pre>";
?>


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

  • 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

biuro at dso dot biz dot pl 11-Jan-2022 08:40
A class proposition that can handle very large XML files

use
<?php
$domObj = new BigXMLToArray($fileData, true);
?>

<?php
class BigXMLToArray
{
    public $array;

    public function __construct($xml, $getRoot = false) {
        $use_errors = libxml_use_internal_errors(true);
        $xmlData = simplexml_load_string($xml);
        if (false === $xmlData) {
            $message = "Failed loading XML\r\n";

            foreach(libxml_get_errors() as $error) {
                $message = "\t" . $error->message . "\r\n";
            }
            // Do something about this error message , e.g.
            // DsoMultiImporterLog::setError(['message' => $message, 'xml' => $xml], 'GLOBAL', __METHOD__);
        } else {
            $this->array = $this->xml2array($xmlData, $getRoot);
        }
        libxml_clear_errors();
        libxml_use_internal_errors($use_errors);
    }

    private function getAttributesList($xmlObject, $out = [])
    {
        if (count($xmlObject) > 1) {
            foreach ($xmlObject as $index => $node) {
                if (is_object($node)) {
                    $out[$index] = $this->getAttributesList($xmlObject);
                } else {
                    $out[$index] = $node;
                }
            }
        } else {
            foreach ($xmlObject as $index => $node) {
                if (is_object($node)) {
                    $out = $this->getAttributesList($xmlObject);
                } else {
                    $out = $node;
                }
            }
        }

        return $out;
    }

    private function xml2array($xmlObject, $isRoot = false, $out = [])
    {
        if ($isRoot) {
            $out[$xmlObject->getName()] = $this->xml2array($xmlObject, false);
        } elseif (is_array($xmlObject) || (is_object($xmlObject) && $xmlObject->count() > 0)) {
            foreach ($xmlObject->children() as $index => $node) {
                $tmp = [];
                if (is_object($node)) {
                    foreach($node->attributes() as $a => $b) {
                        if (is_object($b) ||is_array($b)) {
                            $tmp['attrib'][$a] = $this->getAttributesList((array)$b);
                        } else {
                            $tmp['attrib'][$a] = $b;
                        }
                    }
                }

                if (empty($tmp['attrib'])) {
                    $tmp = $this->xml2array($node, false);
                } else {
                    $tmp['value'] = $this->xml2array($node, false);
                }

                if (!empty($out[$index])) {
                    if (is_string($out[$index])
                        || is_numeric($out[$index])
                        || (is_array($out[$index]) && $out[$index] !== array_values($out[$index]))
                    ) {
                        $out[$index] = [$out[$index]];
                    }

                    $out[$index][] = $tmp;
                } else {
                    $out[$index] = $tmp;
                }
            }
        }
        else{
            $out = json_decode($xmlObject);

            if ($out === null and !empty((string) $xmlObject)) {
                $out = (string) $xmlObject;
            }
        }
        return $out;
    }
}
?>
filip dot rydlo at gmail dot com 18-Apr-2017 09:28
// Fix for xmlToArrayParser  .......... hope this helps somebody. :-)

// FIXED the "MULTIPLE-CALLS to callback for one string" issue of 'cdata' in  xmlToArrayParser written by:
// Glen at ITIStudios dot ca  (2012)

  private function cdata($parser, $cdata) {
    if(isset($this->pointer['cdata'])) {      // This FIXes the issue with "INCOMPLETE STRINGS" containing html-entities
      $this->pointer['cdata'] .= $cdata;
    } else {
      $this->pointer['cdata'] = $cdata;
    }
  }
anrdaemon at freemail dot ru 10-Feb-2016 06:06
You must not, never ever use utf8_encode() and utf8_decode().
If you need multibyte conversion utility, use iconv() instead. At the very least, you will get a notification, if your string can not be converted.
utf8_* crap, like other crap of this nature, is ONLY SUPPORTING ONE CONVERSION. ISO-8859-1 <=> UTF-8.
Glen at ITIStudios dot ca 15-Aug-2013 06:42
Update: concatenate element contents in function cdata()
<?php
/**
 *  XML to Associative Array Class
 *
 *  Usage:
 *     $domObj = new xmlToArrayParser($xml);
 *     $domArr = $domObj->array;
 *
 *     if($domObj->parse_error) echo $domObj->get_xml_error();
 *     else print_r($domArr);
 *
 *     On Success:
 *     eg. $domArr['top']['element2']['attrib']['var2'] => val2
 *
 *     On Error:
 *     eg. Error Code [76] "Mismatched tag", at char 58 on line 3
 */

/**
 * Convert an xml file or string to an associative array (including the tag attributes):
 * $domObj = new xmlToArrayParser($xml);
 * $elemVal = $domObj->array['element']
 * Or:  $domArr=$domObj->array;  $elemVal = $domArr['element'].
 *
 * @version  3.0
 * @param Str $xml file/string.
 */
class xmlToArrayParser {
  /** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
  public  $array = array();
  public  $parse_error = false;
  private $parser;
  private $pointer;

  /** Constructor: $domObj = new xmlToArrayParser($xml); */
  public function __construct($xml) {
    $this->pointer =& $this->array;
    $this->parser = xml_parser_create("UTF-8");
    xml_set_object($this->parser, $this);
    xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
    xml_set_element_handler($this->parser, "tag_open", "tag_close");
    xml_set_character_data_handler($this->parser, "cdata");
    $this->parse_error = xml_parse($this->parser, ltrim($xml))? false : true;
  }

  /** Free the parser. */
  public function __destruct() { xml_parser_free($this->parser);}

  /** Get the xml error if an an error in the xml file occured during parsing. */
  public function get_xml_error() {
    if($this->parse_error) {
      $errCode = xml_get_error_code ($this->parser);
      $thisError =  "Error Code [". $errCode ."] \"<strong style='color:red;'>" . xml_error_string($errCode)."</strong>\",
                            at char ".xml_get_current_column_number($this->parser) . "
                            on line ".xml_get_current_line_number($this->parser)."";
    }else $thisError = $this->parse_error;
    return $thisError;
  }

  private function tag_open($parser, $tag, $attributes) {
    $this->convert_to_array($tag, 'attrib');
    $idx=$this->convert_to_array($tag, 'cdata');
    if(isset($idx)) {
      $this->pointer[$tag][$idx] = Array('@idx' => $idx,'@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag][$idx];
    }else {
      $this->pointer[$tag] = Array('@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag];
    }
    if (!empty($attributes)) { $this->pointer['attrib'] = $attributes; }
  }

  /** Adds the current elements content to the current pointer[cdata] array. */
  private function cdata($parser, $cdata){
    if (isset($this->pointer['cdata'])) { $this->pointer['cdata'] .= $cdata;}
    else { $this->pointer['cdata'] = $cdata; }
  }

  private function tag_close($parser, $tag) {
    $current = & $this->pointer;
    if(isset($this->pointer['@idx'])) {unset($current['@idx']);}
    $this->pointer = & $this->pointer['@parent'];
    unset($current['@parent']);
    if(isset($current['cdata']) && count($current) == 1) { $current = $current['cdata'];}
    else if(empty($current['cdata'])) {unset($current['cdata']);}
  }

  /** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
  private function convert_to_array($tag, $item) {
    if(isset($this->pointer[$tag]) && !is_array($this->pointer[$tag])){
      $content = $this->pointer[$tag];
      $this->pointer[$tag] = array((0) => $content);
      $idx = 1;
    }else if (isset($this->pointer[$tag])) {
      $idx = count($this->pointer[$tag]);
      if(!isset($this->pointer[$tag][0])) {
        foreach ($this->pointer[$tag] as $key => $value) {
            unset($this->pointer[$tag][$key]);
            $this->pointer[$tag][0][$key] = $value;
    }}}else $idx = null;
    return $idx;
  }
}
?>
Glen at ITIStudios dot ca 05-Apr-2013 07:38
Update: corrected isset() in convert_to_array() function
<?php
/**
 *  XML to Associative Array Class
 *
 *  Usage:
 *     $domObj = new xmlToArrayParser($xml);
 *     $domArr = $domObj->array;
 *
 *     if($domObj->parse_error) echo $domObj->get_xml_error();
 *     else print_r($domArr);
 *
 *     On Success:
 *     eg. $domArr['top']['element2']['attrib']['var2'] => val2
 *
 *     On Error:
 *     eg. Error Code [76] "Mismatched tag", at char 58 on line 3
 */

/**
 * Convert an xml file or string to an associative array (including the tag attributes):
 * $domObj = new xmlToArrayParser($xml);
 * $elemVal = $domObj->array['element']
 * Or:  $domArr=$domObj->array;  $elemVal = $domArr['element'].
 *
 * @version  2.0
 * @param Str $xml file/string.
 */
class xmlToArrayParser {
  /** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
  public  $array = array();
  public  $parse_error = false;
  private $parser;
  private $pointer;

  /** Constructor: $domObj = new xmlToArrayParser($xml); */
  public function __construct($xml) {
    $this->pointer =& $this->array;
    $this->parser = xml_parser_create("UTF-8");
    xml_set_object($this->parser, $this);
    xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
    xml_set_element_handler($this->parser, "tag_open", "tag_close");
    xml_set_character_data_handler($this->parser, "cdata");
    $this->parse_error = xml_parse($this->parser, ltrim($xml))? false : true;
  }

  /** Free the parser. */
  public function __destruct() { xml_parser_free($this->parser);}

  /** Get the xml error if an an error in the xml file occured during parsing. */
  public function get_xml_error() {
    if($this->parse_error) {
      $errCode = xml_get_error_code ($this->parser);
      $thisError =  "Error Code [". $errCode ."] \"<strong style='color:red;'>" . xml_error_string($errCode)."</strong>\",
                            at char ".xml_get_current_column_number($this->parser) . "
                            on line ".xml_get_current_line_number($this->parser)."";
    }else $thisError = $this->parse_error;
    return $thisError;
  }

  private function tag_open($parser, $tag, $attributes) {
    $this->convert_to_array($tag, 'attrib');
    $idx=$this->convert_to_array($tag, 'cdata');
    if(isset($idx)) {
      $this->pointer[$tag][$idx] = Array('@idx' => $idx,'@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag][$idx];
    }else {
      $this->pointer[$tag] = Array('@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag];
    }
    if (!empty($attributes)) { $this->pointer['attrib'] = $attributes; }
  }

  /** Adds the current elements content to the current pointer[cdata] array. */
  private function cdata($parser, $cdata) { $this->pointer['cdata'] = trim($cdata); }

  private function tag_close($parser, $tag) {
    $current = & $this->pointer;
    if(isset($this->pointer['@idx'])) {unset($current['@idx']);}

    $this->pointer = & $this->pointer['@parent'];
    unset($current['@parent']);

    if(isset($current['cdata']) && count($current) == 1) { $current = $current['cdata'];}
    else if(empty($current['cdata'])) {unset($current['cdata']);}
  }

  /** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
  private function convert_to_array($tag, $item) {
    if(isset($this->pointer[$tag]) && !is_array($this->pointer[$tag])){
      $content = $this->pointer[$tag];
      $this->pointer[$tag] = array((0) => $content);
      $idx = 1;
    }else if (isset($this->pointer[$tag])) {
      $idx = count($this->pointer[$tag]);
      if(!isset($this->pointer[$tag][0])) {
        foreach ($this->pointer[$tag] as $key => $value) {
            unset($this->pointer[$tag][$key]);
            $this->pointer[$tag][0][$key] = $value;
    }}}else $idx = null;
    return $idx;
  }
}
?>
Glen at ITIStudios dot ca 02-Dec-2011 03:37
<?php
/**
 *  XML to Associative Array Class
 *
 *  Usage:
 *     $domObj = new xmlToArrayParser($xml);
 *     $domArr = $domObj->array;
 *
 *     if($domObj->parse_error) echo $domObj->get_xml_error();
 *     else print_r($domArr);
 *
 *     On Success:
 *     eg. $domArr['top']['element2']['attrib']['var2'] => val2
 *
 *     On Error:
 *     eg. Error Code [76] "Mismatched tag", at char 58 on line 3
 */

/**
 * Convert an xml file or string to an associative array (including the tag attributes):
 * $domObj = new xmlToArrayParser($xml);
 * $elemVal = $domObj->array['element']
 * Or:  $domArr=$domObj->array;  $elemVal = $domArr['element'].
 *
 * @version  2.0
 * @param Str $xml file/string.
 */
class xmlToArrayParser {
  /** The array created by the parser can be assigned to any variable: $anyVarArr = $domObj->array.*/
  public  $array = array();
  public  $parse_error = false;
  private $parser;
  private $pointer;

  /** Constructor: $domObj = new xmlToArrayParser($xml); */
  public function __construct($xml) {
    $this->pointer =& $this->array;
    $this->parser = xml_parser_create("UTF-8");
    xml_set_object($this->parser, $this);
    xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
    xml_set_element_handler($this->parser, "tag_open", "tag_close");
    xml_set_character_data_handler($this->parser, "cdata");
    $this->parse_error = xml_parse($this->parser, ltrim($xml))? false : true;
  }

  /** Free the parser. */
  public function __destruct() { xml_parser_free($this->parser);}

  /** Get the xml error if an an error in the xml file occured during parsing. */
  public function get_xml_error() {
    if($this->parse_error) {
      $errCode = xml_get_error_code ($this->parser);
      $thisError =  "Error Code [". $errCode ."] \"<strong style='color:red;'>" . xml_error_string($errCode)."</strong>\",
                            at char ".xml_get_current_column_number($this->parser) . "
                            on line ".xml_get_current_line_number($this->parser)."";
    }else $thisError = $this->parse_error;
    return $thisError;
  }

  private function tag_open($parser, $tag, $attributes) {
    $this->convert_to_array($tag, 'attrib');
    $idx=$this->convert_to_array($tag, 'cdata');
    if(isset($idx)) {
      $this->pointer[$tag][$idx] = Array('@idx' => $idx,'@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag][$idx];
    }else {
      $this->pointer[$tag] = Array('@parent' => &$this->pointer);
      $this->pointer =& $this->pointer[$tag];
    }
    if (!empty($attributes)) { $this->pointer['attrib'] = $attributes; }
  }

  /** Adds the current elements content to the current pointer[cdata] array. */
  private function cdata($parser, $cdata) { $this->pointer['cdata'] = trim($cdata); }

  private function tag_close($parser, $tag) {
    $current = & $this->pointer;
    if(isset($this->pointer['@idx'])) {unset($current['@idx']);}

    $this->pointer = & $this->pointer['@parent'];
    unset($current['@parent']);

    if(isset($current['cdata']) && count($current) == 1) { $current = $current['cdata'];}
    else if(empty($current['cdata'])) {unset($current['cdata']);}
  }

  /** Converts a single element item into array(element[0]) if a second element of the same name is encountered. */
  private function convert_to_array($tag, $item) {
    if(isset($this->pointer[$tag][$item])) {
      $content = $this->pointer[$tag];
      $this->pointer[$tag] = array((0) => $content);
      $idx = 1;
    }else if (isset($this->pointer[$tag])) {
      $idx = count($this->pointer[$tag]);
      if(!isset($this->pointer[$tag][0])) {
        foreach ($this->pointer[$tag] as $key => $value) {
            unset($this->pointer[$tag][$key]);
            $this->pointer[$tag][0][$key] = $value;
    }}}else $idx = null;
    return $idx;
  }
}
?>

This is supplimental information for the "class xmlToArrayParser".
This is a fully functional error free, extensively tested php class unlike the posts that follow it.

Key phrase: Fully functional, fully tested, error free XML To Array parser.

<?php
/**
 * class xmlToArrayParser
 *
  Notes:
  1. 'attrib' and 'cdata' are keys added to the array when the element contains both attributes and content.
  2. Ignores content that is not in between it's own set of tags.
  3. Don't know if it recognizes processing instructions nor do I know about processing instructions.
     <\?some_pi some_attr="some_value"?>  This is the same as a document declaration.
  4. Empty elements are not included unless they have attributes.
  5. Version 2.0, Dec. 2, 2011, added xml error reporting.

  Usage:
    $domObj = new xmlToArrayParser($xml);
    $elemVal = $domObj->array['element']
    Or assign the entire array to its own variable:
    $domArr = $domObj->array;
    $elemVal = $domArr['element']

  Example:
    $xml = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <top>
      <element1>element content 1</element1>
      <element2 var2="val2" />
      <element3 var3="val3" var4="val4">element content 3</element3>
      <element3 var5="val5">element content 4</element3>
      <element3 var6="val6" />
      <element3>element content 7</element3>
    </top>';

    $domObj = new xmlToArrayParser($xml);
    $domArr = $domObj->array;

    if($domObj->parse_error) echo $domObj->get_xml_error();
    else print_r($domArr);

    On Success:
    $domArr['top']['element1'] => element content 1
    $domArr['top']['element2']['attrib']['var2'] => val2
    $domArr['top']['element3']['0']['attrib']['var3'] => val3
    $domArr['top']['element3']['0']['attrib']['var4'] => val4
    $domArr['top']['element3']['0']['cdata'] => element content 3
    $domArr['top']['element3']['1']['attrib']['var5'] => val5
    $domArr['top']['element3']['1']['cdata'] => element content 4
    $domArr['top']['element3']['2']['attrib']['var6'] => val6
    $domArr['top']['element3']['3'] => element content 7

    On Error:
    Error Code [76] "Mismatched tag", at char 58 on line 3
 *
 */
?>
wolfon.AT-DoG.inbox.ru 28-Jul-2008 03:09
Finally a simple xml => array class.
Functioning like SimpleXML library.

<?php
class xml  {
    private $parser;
    private $pointer;
    public $dom;

    public function __construct($data) {
        $this->pointer =& $this->dom;
        $this->parser = xml_parser_create();
        xml_set_object($this->parser, $this);
        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
        xml_parse($this->parser, $data);
    }

    private function tag_open($parser, $tag, $attributes) {
        if (isset($this->pointer[$tag]['@attributes'])) {
            $content = $this->pointer[$tag];
            $this->pointer[$tag] = array(0 => $content);
            $idx = 1;
        } else if (isset($this->pointer[$tag]))
            $idx = count($this->pointer[$tag]);

        if (isset($idx)) {
            $this->pointer[$tag][$idx] = Array(
                '@idx' => $idx,
                '@parent' => &$this->pointer);
               $this->pointer =& $this->pointer[$tag][$idx];
        } else {
            $this->pointer[$tag] = Array(
                '@parent' => &$this->pointer);
            $this->pointer =& $this->pointer[$tag];
        }
        if (!empty($attributes))
            $this->pointer['@attributes'] = $attributes;
    }

    private function cdata($parser, $cdata) {
           $this->pointer['@data'] = $cdata;
    }

    private function tag_close($parser, $tag) {
        $current = & $this->pointer;
        if (isset($this->pointer['@idx']))
            unset($current['@idx']);

        $this->pointer = & $this->pointer['@parent'];

          unset($current['@parent']);
           if (isset($current['@data']) && count($current) == 1)
               $current = $current['@data'];
           else if (empty($current['@data'])||$current['@data']==0)
               unset($current['@data']);
    }
}
?>

maybe I'll do some explanations on habr
geoff at spacevs dot com 07-Nov-2007 09:13
Reading xml into a class:

<?PHP
        class XmlData {}
        $elements = array();
        $elements[] =& new XmlData();
        function startElement($parser, $name, $attrs) {
                global $elements;
                $element =& new XMLData();
                $elements[count($elements)-1]->$name =& $element;
                $elements[] =& $element;
        }
        function endElement($parser, $name) {
                global $elements;
                array_pop($elements);
        }
        function characterData($parser, $data) {
                global $elements;
                $elements[count($elements)-1]->data = $data;
        }
        $xml_parser     = xml_parser_create();
        xml_set_element_handler($xml_parser, "startElement", "endElement");
        xml_set_character_data_handler($xml_parser, "characterData");
        xml_parse($xml_parser, $xml, true);
        xml_parser_free($xml_parser);
        $request =& array_pop($elements);

        echo $request->LOGIN->USER->data;
?>
demonpants at gmail dot com 22-Oct-2007 08:59
I wanted to access the ISBN database, and was previously parsing the HTML string generated from their main page, that is until I discovered they have an API that returns XML.

So, if anyone wants to get some information from the ISBN database, all you need to do is the following.

<?php
//Search the ISBN database for the book.
            $url = "http://www.isbndb.com/api/books.xml? access_key=KEY&index1=isbn&value1=$_GET[ISBN]";
            $p = xml_parser_create();
            xml_parse_into_struct($p,file_get_contents($url),$results,$index);
            xml_parser_free($p);

            $title = $results[$index[TITLELONG][0]][value];
            $author = $results[$index[AUTHORSTEXT][0]][value];
            $publisher = $results[$index[PUBLISHERTEXT][0]][value];
?>

You will need to get an access key from isbndb.com, but it takes two seconds and is free. When you get it, replace KEY in the URL with your own key. Also, my code above will search for the book that fits the ISBN number stored in the GET variable ISBN - you can search by other parameters and return more than one result, but my example is  for a simple ISBN search.
Zvjezdan Patz 09-Sep-2007 08:22
The problem I had was I needed to generate xml on the screen for users to actually see and copy to a file.

I'm generating the xml manually from a php file and the browser kept interpreting the xml...not very helpful.

This is how you get around it:

<?php

$file  = file_get_contents("http://example.com/xml.php?whatever=$whatever");
print nl2br(htmlentities($file));

?>

Prints all my xml quite nicely.
v9 at fakehalo dot us 13-Jul-2007 08:04
I needed this for work/personal use.  Sometimes you'll have a XML string generated as one long string and no line breaks...nusoap in the case of today/work, but there are any other number of possible things that will generate these.  Anyways, this simply takes a long XML string and returns an indented/line-breaked version of the string for display/readability.

<?php
function xmlIndent($str){
    $ret = "";
    $indent = 0;
    $indentInc = 3;
    $noIndent = false;
    while(($l = strpos($str,"<",$i))!==false){
        if($l!=$r && $indent>0){ $ret .= "\n" . str_repeat(" ",$indent) . substr($str,$r,($l-$r)); }
        $i = $l+1;
        $r = strpos($str,">",$i)+1;
        $t = substr($str,$l,($r-$l));
        if(strpos($t,"/")==1){
            $indent -= $indentInc;
            $noIndent = true;
        }
        else if(($r-$l-strpos($t,"/"))==2 || substr($t,0,2)=="<?"){ $noIndent = true; }
        if($indent<0){ $indent = 0; }
        if($ret){ $ret .= "\n"; }
        $ret .= str_repeat(" ",$indent);
        $ret .= $t;
        if(!$noIndent){ $indent += $indentInc; }
        $noIndent = false;
    }
    $ret .= "\n";
    return($ret);
}
?>

(...this was only tested for what i needed at work, could POSSIBLY need additions)
geoffers [at] gmail [dot] com 30-Dec-2006 03:27
Time to add my attempt at a very simple script that parses XML into a structure:

<?php

class Simple_Parser
{
    var $parser;
    var $error_code;
    var $error_string;
    var $current_line;
    var $current_column;
    var $data = array();
    var $datas = array();

    function parse($data)
    {
        $this->parser = xml_parser_create('UTF-8');
        xml_set_object($this->parser, $this);
        xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
        xml_set_element_handler($this->parser, 'tag_open', 'tag_close');
        xml_set_character_data_handler($this->parser, 'cdata');
        if (!xml_parse($this->parser, $data))
        {
            $this->data = array();
            $this->error_code = xml_get_error_code($this->parser);
            $this->error_string = xml_error_string($this->error_code);
            $this->current_line = xml_get_current_line_number($this->parser);
            $this->current_column = xml_get_current_column_number($this->parser);
        }
        else
        {
            $this->data = $this->data['child'];
        }
        xml_parser_free($this->parser);
    }

    function tag_open($parser, $tag, $attribs)
    {
        $this->data['child'][$tag][] = array('data' => '', 'attribs' => $attribs, 'child' => array());
        $this->datas[] =& $this->data;
        $this->data =& $this->data['child'][$tag][count($this->data['child'][$tag])-1];
    }

    function cdata($parser, $cdata)
    {
        $this->data['data'] .= $cdata;
    }

    function tag_close($parser, $tag)
    {
        $this->data =& $this->datas[count($this->datas)-1];
        array_pop($this->datas);
    }
}

$xml_parser = new Simple_Parser;
$xml_parser->parse('<foo><bar>test</bar></foo>');

?>
Didier: dlvb ** free * fr 24-Dec-2006 09:53
Hi !

After parsing the XML and modifying it, I just add a method to rebuild the XML form the internal structure (xmlp->document).
The method xmlp->toXML writes into xmlp->XML attributes. Then, you just have to output it.
I hope it helps.

<?php
class XMLParser {

var $parser;
var $filePath;
var $document;
var $currTag;
var $tagStack;
var $XML;
var $_tag_to_close = false;
var $TAG_ATTRIBUT = 'attr';
var $TAG_DATA = 'data';

function XMLParser($path) {
    $this->parser = xml_parser_create();
    $this->filePath = $path;
    $this->document = array();
    $this->currTag =& $this->document;
    $this->tagStack = array();
    $this->XML = "";
}

function parse() {
    xml_set_object($this->parser, $this);
    xml_set_character_data_handler($this->parser, 'dataHandler');
    xml_set_element_handler($this->parser, 'startHandler', 'endHandler');

   if(!($fp = fopen($this->filePath, "r"))) {
       die("Cannot open XML data file: $this->filePath");
       return false;
     }

    while($data = fread($fp, 4096)) {
        if(!xml_parse($this->parser, $data, feof($fp))) {
            die(sprintf("XML error: %s at line %d",
                xml_error_string(xml_get_error_code($this->parser)),
             xml_get_current_line_number($this->parser)));
      }
    }

    fclose($fp);
    xml_parser_free($this->parser);

    return true;
}

function startHandler($parser, $name, $attribs) {
     if(!isset($this->currTag[$name]))
          $this->currTag[$name] = array();

     $newTag = array();
     if(!empty($attribs))
          $newTag[$this->TAG_ATTRIBUT] = $attribs;
     array_push($this->currTag[$name], $newTag);

     $t =& $this->currTag[$name];
     $this->currTag =& $t[count($t)-1];
     array_push($this->tagStack, $name);
}

function dataHandler($parser, $data) {
    $data = trim($data);

    if(!empty($data)) {
      if(isset($this->currTag[$this->TAG_DATA]))
            $this->currTag[$this->TAG_DATA] .= $data;
      else
            $this->currTag[$this->TAG_DATA] = $data;
    }
}

function endHandler($parser, $name) {
     $this->currTag =& $this->document;
     array_pop($this->tagStack);

     for($i = 0; $i < count($this->tagStack); $i++) {
          $t =& $this->currTag[$this->tagStack[$i]];
          $this->currTag =& $t[count($t)-1];
     }
}

function clearOutput () {
    $this->XML = "";
}

function openTag ($tag) {
    $this->XML.="<".strtolower ($tag);
    $this->_tag_to_close = true;
}

function closeTag () {
    if ($this->_tag_to_close) {
        $this->XML.=">";
        $this->_tag_to_close = false;
    }
}

function closingTag ($tag) {
    $this->XML.="</".strtolower ($tag).">";
}

function output_attributes ($contenu_fils) {
    foreach ($contenu_fils[$this->TAG_ATTRIBUT] as $nomAttribut => $valeur) {
        $this->XML.= " ".strtolower($nomAttribut)."=\"".$valeur."\"";
    }
}

function addData ($texte) {
// to be completed
    $ca  = array ("é", "è", "ê", "à");
    $par = array ("&eacute;", "&egrave;", "&ecirc;", "agrave;");
    return htmlspecialchars(str_replace ($ca, $par, $texte), ENT_NOQUOTES);
}

function toXML ($tags="") {
    if ($tags=="") {
        $tags = $this->document;
      $this->clearOutput ();
    }

    foreach ($tags as $tag => $contenu) {
        $this->process ($tag, $contenu);
    }
}

function process ($tag, $contenu) {
     // Pour tous les TAGs
    foreach ($contenu as $indice => $contenu_fils) {
         $this->openTag ($tag);

         // Pour tous les fils (non attribut et non data)
         foreach ($contenu_fils as $tagFils => $fils) {
             switch ($tagFils) {
                 case $this->TAG_ATTRIBUT:
                         $this->output_attributes ($contenu_fils);
                        $this->closeTag ();
                         break;
                 case $this->TAG_DATA:
                        $this->closeTag ();
                         $this->XML.= $this->addData ($contenu_fils [$this->TAG_DATA]);
                         break;
                 default:
                         $this->closeTag ();
                         $this->process ($tagFils, $fils);
                         break;
             }
         }

        $this->closingTag ($tag);
    }
}

}
?>
forquan 28-Jan-2006 03:45
Here's code that will create an associative array from an xml file.  Keys are the tag data and subarrays are formed from attributes and child tags

<?php
$p =& new xmlParser();
$p->parse('/*xml file*/');
print_r($p->output);
?>

<?php
class xmlParser{
   var $xml_obj = null;
   var $output = array();
   var $attrs;

   function xmlParser(){
       $this->xml_obj = xml_parser_create();
       xml_set_object($this->xml_obj,$this);
       xml_set_character_data_handler($this->xml_obj, 'dataHandler');
       xml_set_element_handler($this->xml_obj, "startHandler", "endHandler");
   }

   function parse($path){
       if (!($fp = fopen($path, "r"))) {
           die("Cannot open XML data file: $path");
           return false;
       }

       while ($data = fread($fp, 4096)) {
           if (!xml_parse($this->xml_obj, $data, feof($fp))) {
               die(sprintf("XML error: %s at line %d",
               xml_error_string(xml_get_error_code($this->xml_obj)),
               xml_get_current_line_number($this->xml_obj)));
               xml_parser_free($this->xml_obj);
           }
       }

       return true;
   }

   function startHandler($parser, $name, $attribs){
       $_content = array();
       if(!empty($attribs))
         $_content['attrs'] = $attribs;
       array_push($this->output, $_content);
   }

   function dataHandler($parser, $data){
       if(!empty($data) && $data!="\n") {
           $_output_idx = count($this->output) - 1;
           $this->output[$_output_idx]['content'] .= $data;
       }
   }

   function endHandler($parser, $name){
       if(count($this->output) > 1) {
           $_data = array_pop($this->output);
           $_output_idx = count($this->output) - 1;
           $add = array();
           if ($_data['attrs'])
                $add['attrs'] = $_data['attrs'];
           if ($_data['child'])
                $add['child'] = $_data['child'];
           $this->output[$_output_idx]['child'][$_data['content']] = $add;
       }
   }
}
?>
Greg S 17-Nov-2005 08:56
If you need utf8_encode support and configure PHP with --disable-all you will have some trouble. Unfortunately the configure options aren't completely documented. If you need utf8 functions and have everything disabled just recompile PHP with --enable-xml and you should be good to go.
compu_global_hyper_mega_net_2 at yahoo dot com 19-Sep-2004 01:35
The documentation regarding white space was never complete I think.

The XML_OPTION_SKIP_WHITE doesn't appear to do anything.  I want to preserve the newlines in a cdata section.  Setting XML_OPTION_SKIP_WHITE to 0 or false doesn't appear to help.  My character_data_handler is getting called once for each line.  This obviously should be reflected in the documentation as well.  When/how often does the handler get called exactly?  Having to build separate test cases is very time consuming.

Inserting newlines myself in my cdata handler is no good either.  For non actual CDATA sections that cause my handler to get called, long lines are split up in multiple calls.  My handler would not be able to tell the difference whether or not the subsequent calls would be due to the fact that the data is coming from the next line or the fact that some internal buffer is long enough for it to 'flush' out and call the handler.
This behaviour also needs to be properly documented.
odders 18-Mar-2004 10:36
I wrote a simple xml parser mainly to deal with rss version 2. I found lots of examples on the net, but they were all masive and bloated and hard to manipulate.

Output is sent to an array, which holds arrays containg data for each item.

Obviously, you will have to make modifications to the code to suit your needs, but there isnt a lot of code there, so that shouldnt be a problem.

<?php

   $currentElements = array();
   $newsArray = array();

   readXml("./news.xml");

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

   // Reads XML file into formatted html
   function readXML($xmlFile)
   {

      $xmlParser = xml_parser_create();

      xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, false);
      xml_set_element_handler($xmlParser, startElement, endElement);
      xml_set_character_data_handler($xmlParser, characterData);

      $fp = fopen($xmlFile, "r");

      while($data = fread($fp, filesize($xmlFile))){
         xml_parse($xmlParser, $data, feof($fp));}

      xml_parser_free($xmlParser);

   }

   // Sets the current XML element, and pushes itself onto the element hierarchy
   function startElement($parser, $name, $attrs)
   {

      global $currentElements, $itemCount;

      array_push($currentElements, $name);

      if($name == "item"){$itemCount += 1;}

   }

   // Prints XML data; finds highlights and links
   function characterData($parser, $data)
   {

      global $currentElements, $newsArray, $itemCount;

      $currentCount = count($currentElements);
      $parentElement = $currentElements[$currentCount-2];
      $thisElement = $currentElements[$currentCount-1];

      if($parentElement == "item"){
         $newsArray[$itemCount-1][$thisElement] = $data;}
      else{
         switch($name){
            case "title":
               break;
            case "link":
               break;
            case "description":
               break;
            case "language":
               break;
            case "item":
               break;}}

   }

   // If the XML element has ended, it is poped off the hierarchy
   function endElement($parser, $name)
   {

      global $currentElements;

      $currentCount = count($currentElements);
      if($currentElements[$currentCount-1] == $name){
         array_pop($currentElements);}

   }

?>
software at serv-a-com dot com 22-Jan-2003 02:08
use:

<?php
while ($data = str_replace("\n","",fread($fp, 4096))){
 // ...
}
?>

instead of:

<?php
while ($data = fread($fp, 4096)) {
  // ...
}
?>

[UPDATE 17-FEB-2003: This post] resulted in some of the visitors e-mailg me on the carriage return stripping issue with questions. I'll try to make the following mumble as brief and easy to understand as possible.

1. Overview of the 4096 fragmentation issue
As you know the following freads the file 4096 bytes at a time (that is 4KB) this is perhaps ok for testing expat and figuring out how things work, but it it rather dangerous in the production environment. Data may not be fully understandable due to fread fragmentation and improperly formatted due to numerous sources(formats) of data contained within (i.e. end of line delimited CDATA).

<?php
while ($data = fread($fp, 4096)) {
  if (!xml_parse($xml_parser, $data, feof($fp))) {
    // ...
  }
}
?>

Sometimes to save time one may want to load it all up into a one big variable and leave all the worries to expat. I think anything under 500 KB is ok (as long as nobody knows about it). Some may argue that larger variables are acceptable or even necessary because of the magic that take place while parsing using xml_parse. Our XML parser(expat) works and can be successfully implemented only when we know what type of XML data we are dealing with, it's average size and structure of general layout and data contained within tags. For example if the tags are followed by a line delimiter like a new line we can read it with fgets in and with minimal effort make sure that no data will be sent to the function that does not end with a end tag. But this require a fair knowledge of the file's preference for storing XML data and tags (and a bit of code between reading data and xml_parse'ing it).
It will save you a headache.

2. Pre Parser Strings and New Line Delimited Data
One important thing to note at this point is that the xml_parse function requires a string variable. You can manipulate the content of any string variable easily as we all know.

A better approach to removing newlines than:

<?php
while ($data = fread($fp, 4096)) {
$data = preg_replace("/\n|\r/","",$data); //flarp
if (!xml_parse($xml_parser, $data, feof($fp))) {...
?>

Above works across all 3 line-delimited text files  (\n, \r, \r\n). But this could potentially (or will most likely) damage or scramble data contained in for example CDATA areas. As far as I am concerned end of line characters should not be used _within_ XML tags. What seems to be the ultimate solution is to pre-parse the loaded data this would require checking the position within the XML document and adding or subtracting (using a in-between fread temporary variable) data based on conditions like: "Is within tag", "Is within CDATA" etc. before fedding it to the parser. This of course opens up a new can of worms (as in parse data for the parser...). (above procedure would take place between fread and xml_parser calls this method would be compatible with the general usage examples on top of the page)

3. The Answer to parsing arbitrary XML and Preprocessor Revisited
You can't just feed any XML document to the parser you constructed and assuming that it will work! You have to know what kind of methods for storing data are used, for example is there a end of line delimited data in the  file ?, Are there any carriage returns in the tags etc... XML files come formatted in different ways some are just a one long string of characters with out any end of line markers others have newlines, carriage returns or both (Microsloth Windows). May or may not contain space and other whitespace between tags. For this reason it is important to what I call Normalize the data before feeding it to the parser. You can perform this with regular expressions or plain old str_replace and concatenation. In many cases this can be done to the file it self sometimes to string data on the fly( as shown in the example above). But I feel it is important to normalize the data before even calling the function to call xml_parse. If you have the ability to access all data before that call you can convert it to what you fell the data should have been in the first place and omit many surprises and expensive regular expression substitution (in a tight spot) while fread'ing the data.
guy at bhaktiandvedanta dot com 27-Sep-2002 12:01
For a simple XML parser you can use this function. It doesn't require any extensions to run.

<?php
// Extracts content from XML tag

function GetElementByName ($xml, $start, $end) {

    global $pos;
    $startpos = strpos($xml, $start);
    if ($startpos === false) {
        return false;
    }
    $endpos = strpos($xml, $end);
    $endpos = $endpos+strlen($end);
    $pos = $endpos;
    $endpos = $endpos-$startpos;
    $endpos = $endpos - strlen($end);
    $tag = substr ($xml, $startpos, $endpos);
    $tag = substr ($tag, strlen($start));

    return $tag;

}

// Open and read xml file. You can replace this with your xml data.

$file = "data.xml";
$pos = 0;
$Nodes = array();

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}
while ($getline = fread($fp, 4096)) {
    $data = $data . $getline;
}

$count = 0;
$pos = 0;

// Goes throw XML file and creates an array of all <XML_TAG> tags.
while ($node = GetElementByName($data, "<XML_TAG>", "</XML_TAG>")) {
    $Nodes[$count] = $node;
    $count++;
    $data = substr($data, $pos);
}

// Gets infomation from tag siblings.
for ($i=0; $i<$count; $i++) {
$code = GetElementByName($Nodes[$i], "<Code>", "</Code>");
$desc = GetElementByName($Nodes[$i], "<Description>", "</Description>");
$price = GetElementByName($Nodes[$i], "<BasePrice>", "</BasePrice>");
}
?>

Hope this helps! :)
Guy Laor
dmarsh dot NO dot SPAM dot PLEASE at spscc dot ctc dot edu 18-Sep-2002 12:27
Some reference code I am working on as "XML Library" of which I am folding it info an object. Notice the use of the DEFINE:

Mainly Example 1 and parts of 2 & 3 re-written as an object:
--- MyXMLWalk.lib.php ---
<?php

if (!defined("PHPXMLWalk")) {
define("PHPXMLWalk",TRUE);

class XMLWalk {
 var $p; //short for xml parser;
 var $e; //short for element stack/array

  function prl($x,$i=0) {
    ob_start();
    print_r($x);
    $buf=ob_get_contents();
    ob_end_clean();
    return join("\n".str_repeat(" ",$i),split("\n",$buf));
  }

 function XMLWalk() {
  $this->p = xml_parser_create();
  $this->e = array();
  xml_parser_set_option($this->p, XML_OPTION_CASE_FOLDING, true);
  xml_set_element_handler($this->p, array(&$this, "startElement"), array(&$this, "endElement"));
  xml_set_character_data_handler($this->p, array(&$this, "dataElement"));
  register_shutdown_function(array(&$this, "free")); // make a destructor
  }

  function startElement($parser, $name, $attrs) {
    if (count($attrs)>=1) {
      $x = $this->prl($attrs, $this->e[$parser]+6);
    } else {
      $x = "";
    }

    print str_repeat(" ",$this->e[$parser]+0). "$name $x\n";
    $this->e[$parser]++;
    $this->e[$parser]++;
  }

  function dataElement($parser, $data) {
    print str_repeat(" ",$this->e[$parser]+0). htmlspecialchars($data, ENT_QUOTES) ."\n";
  }

  function endElement($parser, $name) {
    $this->e[$parser]--;
    $this->e[$parser]--;
  }
  function parse($data, $fp) {
    if (!xml_parse($this->p, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($this->p)),
                    xml_get_current_line_number($this->p)));
    }
  }

  function free() {
    xml_parser_free($this->p);
  }

} // end of class

} // end of define

?>

--- end of file ---

Calling code:
<?php

...

require("MyXMLWalk.lib.php");

$file = "x.xml";

$xme = new XMLWalk;

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
  $xme->parse($data, $fp);
}

...
?>
jon at gettys dot org 14-Aug-2002 01:59
[Editor's note: see also xml_parse_into_struct().]

Very simple routine to convert an XML file into a PHP structure. $obj->xml contains the resulting PHP structure. I would be interested if someone could suggest a cleaner method than the evals I am using.

<?php
$filename = 'sample.xml';
$obj->tree = '$obj->xml';
$obj->xml = '';

function startElement($parser, $name, $attrs) {
    global $obj;

    // If var already defined, make array
    eval('$test=isset('.$obj->tree.'->'.$name.');');
    if ($test) {
      eval('$tmp='.$obj->tree.'->'.$name.';');
      eval('$arr=is_array('.$obj->tree.'->'.$name.');');
      if (!$arr) {
        eval('unset('.$obj->tree.'->'.$name.');');
        eval($obj->tree.'->'.$name.'[0]=$tmp;');
        $cnt = 1;
      }
      else {
        eval('$cnt=count('.$obj->tree.'->'.$name.');');
      }

      $obj->tree .= '->'.$name."[$cnt]";
    }
    else {
      $obj->tree .= '->'.$name;
    }
    if (count($attrs)) {
        eval($obj->tree.'->attr=$attrs;');
    }
}

function endElement($parser, $name) {
    global $obj;
    // Strip off last ->
    for($a=strlen($obj->tree);$a>0;$a--) {
        if (substr($obj->tree, $a, 2) == '->') {
            $obj->tree = substr($obj->tree, 0, $a);
            break;
        }
    }
}

function characterData($parser, $data) {
    global $obj;

    eval($obj->tree.'->data=\''.$data.'\';');
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($filename, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
print_r($obj->xml);
return 0;

?>
hans dot schneider at bbdo-interone dot de 24-Jan-2002 08:43
I had to TRIM the data when I passed one large String containig a wellformed XML-File to xml_parse. The String was read by CURL, which aparently put a BLANK at the end of the String. This BLANK produced a "XML not wellformed"-Error in xml_parse!
sam at cwa dot co dot nz 28-Sep-2000 07:39
I've discovered some unusual behaviour in this API when ampersand entities are parsed in cdata; for some reason the parser breaks up the section around the entities, and calls the handler repeated times for each of the sections. If you don't allow for this oddity and you are trying to put the cdata into a variable, only the last part will be stored.

You can get around this with a line like:

$foo .= $cdata;

If the handler is called several times from the same tag, it will append them, rather than rewriting the variable each time. If the entire cdata section is returned, it doesn't matter.

May happen for other entities, but I haven't investigated.

Took me a while to figure out what was happening; hope this saves someone else the trouble.
Daniel dot Rendall at btinternet dot com 07-Jul-1999 10:21
When using the XML parser, make sure you're not using the magic quotes option (e.g. use set_magic_quotes_runtime(0) if it's not the compiled default), otherwise you'll get 'not well-formed' errors when dealing with tags with attributes set in them.


Obtiene la cadena de un error dado en un intérprete XML

  • « Funciones del Intérprete XML
  • 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(XMLParser $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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(XMLParser $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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(XMLParser $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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
Elad Elrom 12-Sep-2006 02:14
This is a quick fix for parsing XML from remote URL, some of the example above will work when trying to parse on your local server without "http://" but not when trying to parse from remote server using "http://www.URL"...

<?
$file="http://www.URL.com/file.XML";

$xml_parser = xml_parser_create();

$handle = fopen($file, "rb");
$contents = '';
while (!feof($handle)) {
  $data .= fread($handle, 8192);
}
fclose($handle);

xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
   if (array_key_exists('attributes',$xml_elem)) {
     list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
   } else {
     $level[$xml_elem['level']] = $xml_elem['tag'];
   }
  }
  if ($xml_elem['type'] == 'complete') {
   $start_level = 1;
   $php_stmt = '$params';
   while($start_level < $xml_elem['level']) {
     $php_stmt .= '[$level['.$start_level.']]';
     $start_level++;
   }
   $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
   eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";
?>
efredricksen at gmail dot com 24-May-2006 12:55
Perhaps the one true parser:? I modified xademax's fine code to tidy it up, codewise and style wise, rationalize some minor crazyness, and make names fit nomenclature from the XML spec. (There are no uses of eval, and shame on you people who do.)

<?php
class XmlElement {
  var $name;
  var $attributes;
  var $content;
  var $children;
};

function xml_to_object($xml) {
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $xml, $tags);
  xml_parser_free($parser);

  $elements = array();  // the currently filling [child] XmlElement array
  $stack = array();
  foreach ($tags as $tag) {
    $index = count($elements);
    if ($tag['type'] == "complete" || $tag['type'] == "open") {
      $elements[$index] = new XmlElement;
      $elements[$index]->name = $tag['tag'];
      $elements[$index]->attributes = $tag['attributes'];
      $elements[$index]->content = $tag['value'];
      if ($tag['type'] == "open") {  // push
        $elements[$index]->children = array();
        $stack[count($stack)] = &$elements;
        $elements = &$elements[$index]->children;
      }
    }
    if ($tag['type'] == "close") {  // pop
      $elements = &$stack[count($stack) - 1];
      unset($stack[count($stack) - 1]);
    }
  }
  return $elements[0];  // the single top-level element
}

// For example:
$xml = '
<parser>
   <name language="en-us">Fred Parser</name>
   <category>
       <name>Nomenclature</name>
       <note>Noteworthy</note>
   </category>
</parser>
';
print_r(xml_to_object($xml));
?>

will give:

xmlelement Object
(
    [name] => parser
    [attributes] =>
    [content] =>
    [children] => Array
        (
            [0] => xmlelement Object
                (
                    [name] => name
                    [attributes] => Array
                        (
                            [language] => en-us
                        )

                    [content] => Fred Parser
                    [children] =>
                )

            [1] => xmlelement Object
                (
                    [name] => category
                    [attributes] =>
                    [content] =>
                    [children] => Array
                        (
                            [0] => xmlelement Object
                                (
                                    [name] => name
                                    [attributes] =>
                                    [content] => Nomenclature
                                    [children] =>
                                )

                            [1] => xmlelement Object
                                (
                                    [name] => note
                                    [attributes] =>
                                    [content] => Noteworthy
                                    [children] =>
                                )

                        )

                )

        )

)
Stuart 23-May-2006 03:26
This is a great little function for a lot of XML work, but note that this function does not handle XML entities properly.

The basic XML entities &lt; &gt; &amp; &quot; are fine, just anything else will not work:

If the entity is defined in the XML header, the parser will drop it completely from the struct it creates.

If the entity is not defined in the XML then the parser will crash out with an undefined entity error.

You should be able to work around this limitation by using a preg_replace on your XML string before passing it to the parser.

(Further details in Bug #35271; this is just a warning to those thinking of using this function for parsing real XML documents not just trivial XML examples)
xademax at gmail dot com 08-Jan-2006 12:15
This is just another simple xml parser :)

<?php

class Xml
{
    var $tag;
    var $value;
    var $attributes;
    var $next;
}

function xml2array($xml_string)
{
    $Parser = xml_parser_create();
    xml_parser_set_option($Parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($Parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($Parser, $xml_string, $Xml_Values);
    xml_parser_free($Parser);
    $XmlClass = array();
    $LastObj = array();
    $NowObj = &$XmlClass;

    foreach($Xml_Values as $Xml_Key => $Xml_Value)
    {
        $Index = count($NowObj);
        if($Xml_Value["type"] == "complete")
        {
            $NowObj[$Index] = new Xml;
            $NowObj[$Index]->tag = $Xml_Value["tag"];
            $NowObj[$Index]->value = $Xml_Value["value"];
            $NowObj[$Index]->attributes = $Xml_Value["attributes"];
        }
        elseif($Xml_Value["type"] == "open")
        {
            $NowObj[$Index] = new Xml;
            $NowObj[$Index]->tag = $Xml_Value["tag"];
            $NowObj[$Index]->value = $Xml_Value["value"];
            $NowObj[$Index]->attributes = $Xml_Value["attributes"];
            $NowObj[$Index]->next = array();
            $LastObj[count($LastObj)] = &$NowObj;
            $NowObj = &$NowObj[$Index]->next;
        }
        elseif($Xml_Value["type"] == "close")
        {
            $NowObj = &$LastObj[count($LastObj) - 1];
            unset($LastObj[count($LastObj) - 1]);
        }

    }

    return $XmlClass;
}

$String = "
<parser>
    <parseur_name>MyParser</parseur_name>
    <category>
        <name>Name 1</name>
        <note>A note 1</note>
    </category>
</parser>
";
$Xml = xml2array($String);

print_r($Xml);
?>

This exemple will show :
Array
(
    [0] => Xml Object
        (
            [tag] => parser
            [value] =>
            [attributes] =>
            [next] => Array
                (
                    [0] => Xml Object
                        (
                            [tag] => parseur_name
                            [value] => MyParser
                            [attributes] =>
                            [next] =>
                        )

                    [1] => Xml Object
                        (
                            [tag] => category
                            [value] =>
                            [attributes] =>
                            [next] => Array
                                (
                                    [0] => Xml Object
                                        (
                                            [tag] => name
                                            [value] => Name 1
                                            [attributes] =>
                                            [next] =>
                                        )

                                    [1] => Xml Object
                                        (
                                            [tag] => note
                                            [value] => A note 1
                                            [attributes] =>
                                            [next] =>
                                        )

                                )

                        )

                )

        )

)
mbirth at webwriters dot de 08-Nov-2005 03:48
Searching for a nice and working way to get a RSS feed into an array-structure, I found the solution posted by kieran but disliked those several eval()s. So I wrote my own using references/pointers.

<?php

class RSSParser {

  var $struct = array();  // holds final structure
  var $curptr;  // current branch on $struct
  var $parents = array();  // parent branches of current branch

  function RSSParser($url) {
    $this->curptr =& $this->struct;  // set ref to base
    $xmlparser = xml_parser_create();
    xml_set_object($xmlparser, $this);
    xml_set_element_handler($xmlparser, 'tag_open', 'tag_close');
    xml_set_character_data_handler($xmlparser, 'cdata');
    $fp = fopen($url, 'r');

    while ($data = fread($fp, 4096))
      xml_parse($xmlparser, $data, feof($fp))
      || die(sprintf("XML error: %s at line %d",
         xml_error_string(xml_get_error_code($xmlparser)),
         xml_get_current_line_number($xmlparser)));

    fclose($fp);
    xml_parser_free($xmlparser);
  }

  function tag_open($parser, $tag, $attr) {
    $i = count($this->curptr['children']);
    $j = count($this->parents);
    $this->curptr['children'][$i]=array();  // add new child element
    $this->parents[$j] =& $this->curptr;  // store current position as parent
    $this->curptr =& $this->curptr['children'][$i];  // submerge to newly created child element
    $this->curptr['name'] = $tag;
    if (count($attr)>0) $this->curptr['attr'] = $attr;
  }

  function tag_close($parser, $tag) {
    $i = count($this->parents);
    if ($i>0) $this->curptr =& $this->parents[$i-1];  // return to parent element
    unset($this->parents[$i-1]);  // clear from list of parents
  }

  function cdata($parser, $data) {
    $data = trim($data);
    if (!empty($data)) {
      $this->curptr['value'] .= $data;
    }
  }

}

$myparser = new RSSParser('getitems.xml');
$anotherparser = new RSSParser('http://johndoe:secret@myfeeds.com/getfeed.xml');

print_r($myparser->struct);
print_r($anotherparser->struct);

?>
kieran at kieran dot ca 20-Oct-2005 09:20
<?
/*
|
| _xml2array - another abstraction layer on xml_parse_into_struct
|              that returns a nice nested array.
|
|      @param: $xml is a string containing a full xml document
|
|     returns: a nested php array that looks like this:
|
|              array
|              (
|                  [_name] => the name of the tag
|                  [_attributes] => an array of 'attribute'=>'value' combos
|                  [_value] => the text contents of the node
|                  [_children] => an array of these arrays, one for each node.
|              )
|
|       notes: thanks to 'jeffg at activestate dot com' who inspired
|              me to essentially re-write his example code from php.net
|
|           me: Kieran Huggins < kieran[at]kieran[dot]ca >
|
*/
function _xml2array($xml){
    global $keys;
    global $level;
    if(!is_array($xml)){ // init on first run
        $raw_xml = $xml;
        $p = xml_parser_create();
        xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($p, $raw_xml, $xml, $idx);
        xml_parser_free($p);
    }
    for($i=0;$i<count($xml,1);$i++){
        // set the current level
        $level = $xml[$i]['level'];

        if($level<1)break;

        // mark this level's tag in the array
        $keys[$level] = '['.$i.']';

        // if we've come down a level, sort output and destroy the upper level
        if(count($keys)>$level) unset($keys[count($keys)]);

        // ignore close tags, they're useless
        if($xml[$i]['type']=="open" || $xml[$i]['type']=="complete"){

            // build the evalstring
            $e = '$output'.implode('[\'_children\']',$keys);

            // set the tag name
            eval($e.'[\'_name\'] = $xml[$i][\'tag\'];');

            // set the attributes
            if($xml[$i]['attributes']){
                eval($e.'[\'_attributes\'] = $xml[$i][\'attributes\'];');
            }

            // set the value
            if($xml[$i]['value']){
                eval($e.'[\'_value\'] = trim($xml[$i][\'value\']);');
            }

        }

    }

    return $output;
}
?>
Chris Hester 28-Jul-2005 05:06
The array generated from XML stores not only the elements but also any spaces and linebreaks between the tags. This results in a much longer array. (I had 24 array fields instead of 10!) To cure this use the following code when creating the parser:

<?php
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE,1);
?>
PhF at madmac dot fr 23-Jun-2005 01:11
The code previously posted by noob at noobsrule dot com doesn't work when the same tag name is used at different levels.
(but perhaps "$php_used_prefix" was intended for that ?)
For example:
<RatedShipment>
  <TransportationCharges>
    ...
  </TransportationCharges>
  <RatedPackage>
    <TransportationCharges>
      ...
    </TransportationCharges>
  </RatedPackage>
</RatedShipment>
<?php
    $p = xml_parser_create();
    xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($p, $UPSxml, $values, $idx);
    xml_parser_free($p);

    // tracking used keys
    $usedKeys = array();
    $deepLevel = -1;

    // start a php array string (evaluated later)
    $forEvalPrefix = '$xml_array';

    // loop throught the value array
    foreach ($values as $key => $val) {
        $tagName = $val['tag']; // pass the key tag into a more friendly looking variable
        $level = $val['level']; // idem
        if($val['type'] == 'open') {
            $deepLevel++; // increase deep level
            $forEvalPrefix .= '[\''. $tagName .'\']';

            // begin used keys checks to allow multidimensionatity under the same tag
            (isset($usedKeys[$level][$tagName])) ? $usedKeys[$level][$tagName]++ : $usedKeys[$level][$tagName] = 0;
            $forEvalPrefix .= '['. $usedKeys[$level][$tagName] .']';
        }
        if($val['type'] == 'complete') {
            ($level > $deepLevel) ? $deepLevel++ : ''; // increase $deepLevel only if current level is bigger
            $tagValue = addslashes($val['value'] ); // format the value for evaluation as a string
            $forEvalSuffix = '[\''. $tagName .'\'] = \''. $tagValue .'\';'; // create a string to append to the current prefix
            $forEval = $forEvalPrefix . $forEvalSuffix; // (without "$php_used_prefix"...)
            eval($forEval); // write the string to the array structure
        }
        if($val['type'] == 'close') {
            unset($usedKeys[$deepLevel]); // Suppress tagname's keys useless
            $deepLevel--;
            $forEvalPrefix = substr($forEvalPrefix, 0, strrpos($forEvalPrefix, '[')); // cut off the used keys node
            $forEvalPrefix = substr($forEvalPrefix, 0, strrpos($forEvalPrefix, '[')); // cut off the end level of the array string prefix
        }
    }
echo '<pre>';
print_r ($xml_array);
echo '</pre>';
?>

MADmac ;-)
peter at elemental dot org 15-Jun-2005 08:46
Quick addendum to my post below... The code does *not* handle cases where multiple elements are used without attribute IDs, as is the case with the moldb example.  (It is probably worth noting that some of the other code below doesn't do this either, and is still more complex.)

It is not difficult to add that functionality, but I have yet to find an elegant way to integrate that feature, and since I don't need that functionality at the moment, I'm going leave that as an exercise to the reader.  ;-)

-p.
peter at elemental dot org 14-Jun-2005 04:09
Some of the code posted previously seemed absurdly complex, so I thought I'd see if I could simplify things a bit. Here's what I came up with.  (I'm still a PHP newbie, so perhaps I simplified too much.  ;-)  Untested for speed, but it *should* be pretty quick since it uses references instead of lookups or (gack) evals.

Enjoy!

/*
 *  Convert a string containing XML into a nested array
 *
 *  Takes a raw XML string as input
 *  Returns a nested array
 */

function xml2array ($xml_data)
{
    // parse the XML datastring
    $xml_parser = xml_parser_create ();
    xml_parse_into_struct ($xml_parser, $xml_data, $vals, $index);
    xml_parser_free ($xml_parser);

    // convert the parsed data into a PHP datatype
    $params = array();
    $ptrs[0] = & $params;
    foreach ($vals as $xml_elem) {
        $level = $xml_elem['level'] - 1;
        switch ($xml_elem['type']) {
        case 'open':
            $tag_or_id = (array_key_exists ('attributes', $xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
            $ptrs[$level][$tag_or_id] = array ();
            $ptrs[$level+1] = & $ptrs[$level][$tag_or_id];
            break;
        case 'complete':
            $ptrs[$level][$xml_elem['tag']] = (isset ($xml_elem['value'])) ? $xml_elem['value'] : '';
            break;
        }
    }

    return ($params);

}
noob at noobsrule dot com 24-Jan-2005 10:59
This is my first time contributing but I found all the examples either didn't work or were beyond my comprehension.  I also wanted to maintain the XML multi-dimensionality so I could do loops based on keys I was expecting rather than numbers or some other whatnot.  This script is probably way inefficient, but should give you a multidimensional array with a depth that will match the XML source.  Great for situations when you aren't sure what you'll be getting back.  Its also only based on the values array of xml_parse_into_str() using the 3 tag types (open, complete, and close) -- hopefully it will make more sense to other noobs.

Basically it just constructs a string ($php_prefix) that is tweaked if it hits an "open" or "close" tag and evaluated if it hits a "complete" tag.

Thanks.

<?php

# initiate curl session...
$ch = curl_init( "http://yourtargethost" ) or die ( "could not initialize curl" );

# set curl options...
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $request_str );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 0 );
curl_setopt( $ch, CURLOPT_REFERER, https://foobar.com" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );

# execute curl commands...
$curl_result = curl_exec( $ch ) or die ( "could not execute the post" );
curl_close( $ch ); // close curl session

# pass the XML result into 2 arrays ( index and values )...
$p = xml_parser_create();
xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($p, $curl_result, $vals, $index);
xml_parser_free($p);

# create an empty used key tracker...
$used_keys = array();

# start a php array string (evaluated later)...
$php_prefix = "$"."my_array";

# loop through the values array...
foreach ($vals as $key => $val) {
    if( $val['type'] == "open" ) {
        $my_tag = $val['tag']; // pass the key tag into a more friendly looking variable...
        $php_prefix .= "['".$my_tag."']"; # add a new level to the array string...

        # begin used key checks to allow multidimensionality under the same tag, adds a number to the prefix if necessary...
        if( ! array_key_exists( $my_tag, $used_keys ) ) {
            $used_keys[$my_tag] = 0;
            $php_prefix .= "[".$used_keys[$my_tag]."]";
        }else {
            $used_keys[$my_tag]++; // increment the key tracker to avoid overwriting existing key...
            $php_prefix .= "[".$used_keys[$my_tag]."]";
        }
    } elseif( $val['type'] == "complete" ) {
        $my_value = addslashes( $val['value'] ); # format the value for evaluation as a string...
        $php_suffix = "['".$val['tag']."'] = \"".$my_value."\";"; # create a string with the tag and value to append to the current prefix (just used here)...
        $php_str = $php_prefix.$php_used_prefix.$php_suffix;
        eval( $php_str ); # write the string to the array structure...
    }
    if( $val['type'] == "close" ) {
        $php_prefix = substr( $php_prefix, 0, strrpos( $php_prefix, "[" ) ); # cut off the used keys node...
        $php_prefix = substr( $php_prefix, 0, strrpos( $php_prefix, "[" ) ); # cut off the end level of the array string prefix...
    }
}

echo "<pre>";
//print_r ($index);
//echo "<br><br><br>";
//print_r ($vals);
//echo "<br><br><br>";
print_r ($my_array);
echo "</pre>";

?>
dudus at onet dot pl 18-Jan-2005 06:33
This function return array from XML. Included attributes and tags in same level.
I wrote this function based on mmustafa code.

enjoy!
dUDA

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

<?
function XMLtoArray($XML)
{
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $XML, $vals);
    xml_parser_free($xml_parser);
    // wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
    $_tmp='';
    foreach ($vals as $xml_elem)
    {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_level!=1 && $x_type == 'close')
        {
            if (isset($multi_key[$x_tag][$x_level]))
                $multi_key[$x_tag][$x_level]=1;
            else
                $multi_key[$x_tag][$x_level]=0;
        }
        if ($x_level!=1 && $x_type == 'complete')
        {
            if ($_tmp==$x_tag)
                $multi_key[$x_tag][$x_level]=1;
            $_tmp=$x_tag;
        }
    }
    // jedziemy po tablicy
    foreach ($vals as $xml_elem)
    {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_type == 'open')
            $level[$x_level] = $x_tag;
        $start_level = 1;
        $php_stmt = '$xml_array';
        if ($x_type=='close' && $x_level!=1)
            $multi_key[$x_tag][$x_level]++;
        while($start_level < $x_level)
        {
              $php_stmt .= '[$level['.$start_level.']]';
              if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
                  $php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
              $start_level++;
        }
        $add='';
        if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete'))
        {
            if (!isset($multi_key2[$x_tag][$x_level]))
                $multi_key2[$x_tag][$x_level]=0;
            else
                $multi_key2[$x_tag][$x_level]++;
             $add='['.$multi_key2[$x_tag][$x_level].']';
        }
        if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes',$xml_elem))
        {
            if ($x_type == 'open')
                $php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
            else
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
            eval($php_stmt_main);
        }
        if (array_key_exists('attributes',$xml_elem))
        {
            if (isset($xml_elem['value']))
            {
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
                eval($php_stmt_main);
            }
            foreach ($xml_elem['attributes'] as $key=>$value)
            {
                $php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
                eval($php_stmt_att);
            }
        }
    }
     return $xml_array;
}    // END XMLtoArray
?>
happyseb at free dot fr 24-Aug-2004 08:51
I would just add something about the solution proposed by "gordon at kanazawa dot ac dot jp".

Something went wrong about the fact that "cdata" are treated the same way as "complete" in the xml_get_children first and in the xml_get_child then.

When ?
with this method, something like this :
<tagA>
  <tagB>valueB</tagB>
  valueA
  <tagC>valueC</tagC>
</tagA>
is considered as the same thing as
<tagA>
  <tagB>valueB</tagB>
  <tagA>valueA</tagA>
  <tagC>valueC</tagC>
</tagA>

The algorithm is nomore bijective.

Even if it might not be perfect :-) i propose a little modification of the xml_get_child function :

function xml_get_child(&$v, $children=NULL) {
      $c = array(); // the "child"
      if (isset($v['tag']) && $v['type'] != 'cdata') $c['tag'] = $v['tag'];
      if (isset($v['value'])) $c['value'] = $v['value'];
      if (isset($v['attributes'])) $c['attributes'] = $v['attributes'];
      if (is_array($children)) $c['children'] = $children;
      return $c;
}

moreover, the following function will take the tree (made from the xml_get_tree function) as a parameter and build the xml content back

    /*
    // setTree
    // set xml Tree from a well-formed array
    // manage indentation
    // Parameters are :
    // $1 (needed) : Tree to transform
    // $2 (optional) : Indentation type (default is one tabulation)
    // $3 (optional) : First indent (default is empty string)
    */

    function setTree($Atree, $indentType = '    ', $Sindent = '')
    {
      if (! isset ($Atree['tag']) && isset ($Atree['value'])) return ($Sindent.trim($Atree['value'])."\r\n") ;
      else {
        $Stemp = $Sindent.'<'.$Atree['tag'].' ' ;
        if (isset ($Atree['attributes']) && is_array ($Atree['attributes'])) {
          foreach ($Atree['attributes'] as $Aattribute => $Svalue) $Stemp .= $Aattribute.'="'.$Svalue.'" ' ;
        }
        if (! isset ($Atree['children']) && ! isset ($Atree['value'])) $Stemp .= '/>'."\r\n" ;
        else {
          $Stemp .= '>'."\r\n" ;
          if (isset ($Atree['value'])) $Stemp .= $Sindent.$indentType.trim($Atree['value'])."\r\n" ;
          if (isset ($Atree['children']) && is_array ($Atree['children']))
            foreach ($Atree['children'] as $Achild) $Stemp .= $this->setTree($Achild, $indentType, $Sindent.$indentType) ;
          $Stemp .= $Sindent.'</'.$Atree['tag'].'>'."\r\n" ;
        }
        return ($Stemp) ;
      }
    }
sdh33 at cornell dot edu 13-Jun-2004 10:12
(The previous post I wrote was incorrect.  I fix that herein)
I used the algorithm from stephane for writing back to a file, but ran into the following problem.  My original XML looks like

<ENTRY id="1"> ... </ENTRY><ENTRY id="2"> ... </ENTRY>

This got saved back as

<1> ... </1><2> ... </2>,

which expat doesn't like.  So I propose the following modification:

function writeXmlToFile($data, $f, $niv = 0) {
  foreach($data as $name => $elem) {
    if (preg_match("/\A[0-9]/",$name)) {
      $open = "ENTRY id=\"$name\""; $name = "ENTRY";
    } else {
      $open = $name;
    }
    if(is_array($elem)) {
      fwrite($f, str_repeat("  ", $niv)."<".$open.">"."\n");
      writeXmlToFile($elem, $f, $niv + 1);
      fwrite($f, str_repeat("  ", $niv)."</".$name.">"."\n");
    } else {
      fwrite($f, str_repeat("  ", $niv)."<".$open.">".$elem."</".$name.">"."\n");
    }
  }
}
stephane dot dekeyzer at noemail dot com 08-Apr-2004 11:54
for writing the array of mmustafa back to a xml file, use this code:

function writeXmlFile($fileName, $struct){
  $f = fopen($fileName, "w");
  writeXmlToFile($struct, $f);
  fclose($f);
}

function writeXmlToFile($data, $f, $niv = 0){
  foreach($data as $name => $elem){
    if(is_array($elem)){
      fwrite($f, str_repeat("  ", $niv)."<".$name.">"."\n");
      writeXmlToFile($elem, $f, $niv + 1);
      fwrite($f, str_repeat("  ", $niv)."</".$name.">"."\n");
    }
    else{
      fwrite($f, str_repeat("  ", $niv)."<".$name.">".$elem."</".$name.">"."\n");
    }
  }
}
mmustafa at vsnl dot com 06-Jan-2004 12:19
A small and simple php code to convert the raw array returned by xml_parse_into_struct into a proper data structure ..

<?php
$file = "data.xml";
$xml_parser = xml_parser_create();

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

$data = fread($fp, filesize($file));
fclose($fp);
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
    if (array_key_exists('attributes',$xml_elem)) {
      list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
    } else {
      $level[$xml_elem['level']] = $xml_elem['tag'];
    }
  }
  if ($xml_elem['type'] == 'complete') {
    $start_level = 1;
    $php_stmt = '$params';
    while($start_level < $xml_elem['level']) {
      $php_stmt .= '[$level['.$start_level.']]';
      $start_level++;
    }
    $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
    eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";
?>

Converts an XML document like ..

<country id="ZZ">
<name>My Land</name>
<location>15E</location>
<area>40000</area>
<state1>
<name>Hi State</name>
<area>1000</area>
<population>2000</population>
<city1>
<location>13E</location>
<population>500</population>
<area>500</area>
</city1>
<city2>
<location>13E</location>
<population>500</population>
<area>5000</area>
</city2>
</state1>
<state2>
<name>Low State</name>
<area>3000</area>
<population>20000</population>
<city1>
<location>15E</location>
<population>5000</population>
<area>1500</area>
</city1>
</state2>
</country>

To a php datastructure like ..

Array
(
    [ZZ] => Array
        (
            [NAME] => My Land
            [LOCATION] => 15E
            [AREA] => 40000
            [STATE1] => Array
                (
                    [NAME] => Hi State
                    [AREA] => 1000
                    [POPULATION] => 2000
                    [CITY1] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 500
                        )

                    [CITY2] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 5000
                        )

                )

            [STATE2] => Array
                (
                    [NAME] => Low State
                    [AREA] => 3000
                    [POPULATION] => 20000
                    [CITY1] => Array
                        (
                            [LOCATION] => 15E
                            [POPULATION] => 5000
                            [AREA] => 1500
                        )

                )

        )

)
bisqwit at iki dot fi dot not dot for dot ads dot invalid 20-Nov-2002 08:33
I made my own xml2tree()-function.
The difference to the previously suggested ones on this manual page is that this creates a tree where the tags are keys.

Example input:

<tree>
 <leaf name="gruu"> pl?? </leaf>
 <animal type="cat" />
</tree>

Example output:

Array
( 'tree' => Array
     ( 0 => Array
          ( 'children' => Array
               ( 'leaf' => Array
                    ( 0 => Array
                         ( 'attrs' => Array('name' => 'gruu'),
                           'values' => Array(0 => ' pl?? ')
                    )    ),
                 'animal' => Array
                    ( 0 => Array
                         ( 'attrs' => Array('type' => 'cat')
)    )   )    )    )   )

function xml2tree2($string)
{
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $string, $vals, $index);
  xml_parser_free($parser);

  $stack = array( array() );
  $stacktop = 0;
  $parent = array();
  foreach($vals as $val)
  {
    $type = $val['type'];
    if($type=='open' || $type=='complete')
    {
      // open tag
      $stack[$stacktop++] = $tagi;
      $tagi = array('tag' => $val['tag']);

      if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
      if(isset($val['value']))
        $tagi['values'][] = $val['value'];
    }
    if($type=='complete' || $type=='close')
    {
      // finish tag
      $tags[] = $oldtagi = $tagi;
      $tagi = $stack[--$stacktop];
      $oldtag = $oldtagi['tag'];
      unset($oldtagi['tag']);
      $tagi['children'][$oldtag][] = $oldtagi;
      $parent = $tagi;
    }
    if($type=='cdata')
    {
      $tagi['values'][] = $val['value'];
    }
  }
  return $parent['children'];
}

Ps: Note that the xml parsing for some reason chokes if the values contain <> (even inside ""). You need to escape them as &lt; and &gt;.
Same for & (for obvious reasons). Escape it as &amp;.
For example "&nbsp;" should be written as "&amp;nbsp;".
09-Aug-2002 01:20
This is based on a comment above by mh@mainlab.de.  This version makes more sense to me and I included a few comments that might make it more usefull for specific purposes.

// Look through $vals and $index,
// generated by parse_xml_data(),
// for $location.  $location resembles a unix path.
// E.g. "my/xml/path/to/my/data".
// Note: This is NOT a full-feature xml utility.
// Your path must be unique in the xml data
// and the tags must not contain slashes.
//
// returns: cdata from last element of $location
//          or NULL.
function get_xml_values($vals, $index, $location) {
  $location = explode('/', $location);
  $location_level = count($location);
  for ($n=0; $n<$location_level; ++$n) {
    $val_indexes=$index[$location[$n]];
    $good=0;
    for ($i=0; $i<count($val_indexes); ++$i) {
      $v = $vals[$val_indexes[$i]];
      // level is 1 based, n is 0 based:
      if ($v['level']-1 == $n) {
        if ($v['type'] == 'open') {
          // We found an open tag at the correct level.
          $good=1;
          break; // Remove break to avoid 'open' hiding
                 // 'complete' at last $n. (Speed Vs. Robustness:
                 // For now, I'm going with speed).
        }
        if ($v['type'] == 'complete') {
          // We found it, after finding all the prior elements:
          // You may want to change this to
          // return $v
          // so you can call $v['value'] and $v['attributes']
          return $v['value'];
        }
      }
    }
    if (!$good) {
      return NULL;
    }
  }
}
farinspace-at-hotmail-dot-com 20-Jul-2002 06:41
Wow, took a while to consume all of this. I am a noobie at XML, in fact i just really started working with it today. I went ahead and added to the above code by gdemartini@bol.com.br. I also added the update by nyk@cowham.net.

Added 'value' => $vals[$i]['value'] to the open case, as some nodes have both cdata as well as a children node. In previous versions of the functions the cdata of a node(a) that also had children would get stored in the children's array of the parent node(a). Now only children values are in the children array and the cdata is in the value key of the parent node(a).

Added 'value' => $vals[$i]['value'] to tree array as the vals array produced by PHP includes a value to the top most node if no children exist (for completeness).

Also, using xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE,1) will strip all white space from both around the XML tags as well as inside the cdata. I added a piece of code by waldo@wh-e.com to take care of this. All SPACE characters are now only stripped from around the XML tags and cdata spacing is retained.

CODE:
***************************************

function GetChildren($vals, &$i) {

    $children = array();

    while (++$i < sizeof($vals)) {

        // compair type
        switch ($vals[$i]['type']) {

            case 'cdata':
                $children[] = $vals[$i]['value'];
                break;
            case 'complete':
                $children[] = array(
                    'tag' => $vals[$i]['tag'],
                    'attributes' => $vals[$i]['attributes'],
                    'value' => $vals[$i]['value']
                );
                break;
            case 'open':
                $children[] = array(
                    'tag' => $vals[$i]['tag'],
                    'attributes' => $vals[$i]['attributes'],
                    'value' => $vals[$i]['value'],
                    'children' => GetChildren($vals, $i)
                );
                break;
            case 'close':
                return $children;
        }
    }
}

function GetXMLTree($file) {

    $data = implode('', file($file));

    // by: waldo@wh-e.com - trim space around tags not within
    $data = eregi_replace(">"."[[:space:]]+"."<","><",$data);

    // XML functions
    $p = xml_parser_create();

    // by: anony@mous.com - meets XML 1.0 specification
    xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
    xml_parse_into_struct($p, $data, &$vals, &$index);
    xml_parser_free($p);

    $i = 0;
    $tree = array();
    $tree[] = array(
        'tag' => $vals[$i]['tag'],
        'attributes' => $vals[$i]['attributes'],
        'value' => $vals[$i]['value'],
        'children' => GetChildren($vals, $i)
    );

    return $tree;
}

***************************************
dave at ovumdesign dot com 03-Apr-2002 03:32
Here is another variation on gdemartini@bol.com.br's nice tree algorithm. I have included nyk@cowham.net's "cdata" suggestion. I made a few changes to suppress unitialized variable warnings with error_reporting(E_ALL), and made a few stylistic changes.

There are two functional modifications as well. The first is the added option to expat to turn off "case folding", since XML is technically a case-sensitive language. The second is the returned tree - instead of returning a single-element list (an array with index 0 pointing to the top node) like the original algorithm, it returns the top node itself. This saves you an unnecessary level of indirection.

function xml_get_children($vals, &$i) {
    $children = array();
    if (isset($vals[$i]['value'])) $children[] = $vals[$i]['value'];

    while (++$i < count($vals)) {
        switch ($vals[$i]['type']) {
        case 'cdata':
            $children[] = $vals[$i]['value'];
            break;

        case 'complete':
            $children[] = array(
                'tag'        => $vals[$i]['tag'],
                'attributes' => isset($vals[$i]['attributes'])?
                                $vals[$i]['attributes'] : null,
                'value'      => $vals[$i]['value'],
            );
            break;

        case 'open':
            $children[] = array(
                'tag'        => $vals[$i]['tag'],
                'attributes' => isset($vals[$i]['attributes'])?
                                $vals[$i]['attributes'] : null,
                'children'   => xml_get_children($vals, $i),
            );
            break;

        case 'close':
            return $children;
        }
    }
}

function xml_get_tree($file) {
    $data = join('', file($file));

    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE,   1);
    xml_parse_into_struct($parser, $data, $vals, $index);
    xml_parser_free($parser);

    return array(
        'tag'        => $vals[0]['tag'],
        'attributes' => isset($vals[0]['attributes'])?
                        $vals[0]['attributes'] : null,
        'children'   => xml_get_children($vals, $i = 0),
    );
}

This function takes a tree returned by xml_get_tree() and simplifies it similarly to voncken@mailandnews.com and oknapp@soly.de's suggestions. It finds any nodes that expat considered "complete" (childless) and contain no attributes, and it moves the tag name (as the key) and value into an element in the parent node's "values" array.

For example:
$tree = xml_get_tree('moldb.xml');
$tree = xml_condense_tree($tree);
echo $tree['children'][1]['values']['name'];

Outputs:
Lysine

function xml_condense_tree($tree) {
    foreach ($tree['children'] as $index => $node) {
        if (isset($node['children'])) {
            $tree['children'][$index] = xml_condense_tree($node);

        } elseif (isset($node['value']) and !$node['attributes']) {
            $tree['values'][$node['tag']] = $node['value'];
            unset($tree['children'][$index]);
        }
    }

    if (!$tree['children']) unset($tree['children']);
    return $tree;
}

Enjoy,
Dave


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(XMLParser $parser, int $option, string|int $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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(XMLParser $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(XMLParser $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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(XMLParser $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(XMLParser $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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(XMLParser $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.

Precaución

Este evento no es compatible con libXML, por lo que no se llamaría a un controlador registrado.

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(XMLParser $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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(XMLParser $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(
XMLParser $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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(XMLParser $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

Ejemplos

Ejemplo #1 Ejemplo xml_set_object()

<?php
class XMLParser
{
private $parser;

function __construct()
{
$this->parser = xml_parser_create();

xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, "tag_open", "tag_close");
xml_set_character_data_handler($this->parser, "cdata");
}

function __destruct()
{
xml_parser_free($this->parser);
unset($this->parser);
}

function parse($data)
{
xml_parse($this->parser, $data);
}

function tag_open($parser, $tag, $attributes)
{
var_dump($tag, $attributes);
}

function cdata($parser, $cdata)
{
var_dump($cdata);
}

function tag_close($parser, $tag)
{
var_dump($tag);
}
}

$xml_parser = new XMLParser();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
?>

El resultado del ejemplo sería:

string(1) "A"
array(1) {
  ["ID"]=>
  string(5) "hallo"
}
string(3) "PHP"
string(1) "A"

User Contributed Notes

joey at gimo dot co dot uk 10-Aug-2016 10:32
This function seems to be of very limited use when [$object_instance, "method_name"] is a callable.
wake dot shinigami at gmail dot com 23-Nov-2005 08:28
I finally managed to get xml_set_object() to work, after much documentation searching.  As the solution I found has been hinted at, the focus has been wrong.

There have been many problems getting class contained XML parsers to make changes to the members of an instance.  This is because, from what I'm guessing, the functions are using a either a new annonymous instance of the class or an uninstanced version of the class.

What we want to make sure it does it that the parser is accessing its handlers as member methods of a particular instance of a class.  This can be done using the array method for passing a callback, setting the object as a reference to this instance.  This way, you know that the parser is going to call the function properly.

Ex:
<?php
class Parser {

 private $parser;
 private $data;

 public function __construct() {
  $this->parser = NULL;
  $this->data = '';
 }

 private function ParseElementStart($parser, $name, $attrs) {
  // Code
 }
 private function ParseElementEnd($parser, $name) {
  // Code
 }

 public function Parse($XMLdata) {
  $this->parser = xml_parser_create();
  xml_set_object($this->parser, $this);
  xml_set_element_handler($this->parser,
                          array(&$this, 'ParseElementStart'),
                          array(&$this, 'ParseElementEnd'));
  xml_parse($this->parser, $XMLdata);
  xml_parser_free($this->parser);
 }
}
?>

With this, when you call the Parse method, the data in that instance can be modified.  I'm not sure if xml_set_object becomes unneccissary when using the array callbacks, but I leave it in just to make sure that the xml_parse function knows it's in the object.

As above, I'd recommend for memory sake, that the XML parser be created, used, and freed all in the same function, to ensure that everything is cleaned up correctly.
bettmenn at gmx dot de 16-Oct-2004 02:03
Adding to 'lmfe at mega dot ist dot utl dot pt' contribution below, I have to say that this behaviour is very usual for PHP if MemberVars of an Object arent initialized from the constructor.
What worked best for me so far was something like this:
<?php
class foo {
  var $bar
  // the constructor
  function foo() {
    unset($this->bar);  // with every instanciation, the variable is cleared for the object
  }
}
?>
lmfe at mega dot ist dot utl dot pt 29-Sep-2004 10:51
Using PHP 4.3.0, I got this strange behaviour:

<?php
class xml  {

     /* (as specified in the documentation above) */

} // end of class xml

/* This code works */
$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo'>PHP</A>");

/* This code works */
$xml_parser2 = new xml();
$xml_parser2->parse("<A ID='hallo2'>PHP2</A>");

/* This code DON'T work */
$xml_parser = new xml();
$xml_parser->parse("<A ID='hallo3'>PHP3</A>");
?>

In the third block of code, php complains it can't find the handlers it needs.
It seems this problem only happens if the variable is used more than once.
Calling xml_parser_free doesn't help
hwheinzen at t-online dot de 14-Aug-2004 03:38
(Adding to zitan's note)
It seems easy enough to provide output functions for callback handler classes too.

Example:

<?php
class CallBack {
    var $name = 'Callback';
    var $info = 'Information!';
    function toString() {
        return $this->name.': '.$this->info;
    }
}
class Main {
    var $name = 'Main';
    var $callBackObject;
    function setCallBack(&$cBIn) { $this->callBackObject = $cBIn; }
    function toString() {
        return $this->name.': '.$this->callBackObject->toString();
    }
}

$cb = & new CallBack;
$m = & new Main;
$m->setCallBack(&$cb);
echo $cb->toString();
echo $m->toString();
?>

So, after collecting information during the parse operation within the callback handler class, e.g. in tag_close(), retrieving them is possible.
zitan at mediasculpt dot net 01-Sep-2003 09:05
Just a note about creating abstract "call back handlers" as mentioned in some of the other notes.  In this case I recommend extending the base XML class and overwritting the handler methods.  The reason I wanted to do this, is that if you have a separate callback method class it causes problems, for example if you want to collect information out of the XML file and store it in an array.  You can get around it with global variables, but I prefer to use them only when required ;)

Example:

<?php
class xml_output extends xml{

  var $output = array();

   function xml_output(){
    $this->xml();
   }

    //overwrite base methods
    function tag_open($parser, $tag, $attributes)
    {
        array_push($this->output, "<$tag, attributes>");
    }

    function cdata($parser, $cdata)
    {
         array_push($this->output, "$cdata");
    }

    function tag_close($parser, $tag)
    {
         array_push($this->output, "</$tag>");
    }

}

$xml_parser = & new xml_output();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
echo("$xml_parser->output");
?>
sbeam at syxyz dot net 12-Nov-2002 09:34
passing the object as a call-time ref (&$this) as in the example will create a warning in php 4.1+. Pass xml_set_object($xp,$this); instead. This does not seem to break anything - but I dont know for sure.
chiefgeek at ecodedesign.com 04-Aug-2002 10:37
Just adding a little note about my above written example.  It needs some improvements.

Because PHP passes by VALUE by default, when you pass an array like this:
array($callback_handler, 'handler_method')
PHP makes a copy of the callback_handler object and uses the handler_method in the copy.

This is not an ideal situation for many reasons...which I will not get into here...but you should have an idea by now.

The best way to fix this is to change a few things. In the function declaration change the parameter from $callback_handler to &$callback_handler. So now your declaration should look like this

function set_callback_handler(&$callback_handler)
{
  ...
}

Now each time you reference $callback_handler change it to &$callback_handler.  For example:

xml_set_element_handler(
          $this->xml_parser,
          array(&$callback_handler, 'start_element'),
          array(&$callback_handler, 'close_Element' ));

This ensures that PHP will always use the same object.
chiefgeek at ecodedesign.com 03-Aug-2002 08:25
xml_set_object is great, if you want to hard code your start_element, end_element, etc functions within your xml class.

But what if you want to increase the modularity of your application?

Solution, create one generic XMLParser class that handles everything *except* the callback funtions.  Then create an abstract XMLCallbackHandler class which you can extend to provide any customization you want.

So how do you tell the php's xml_parser that you want to use this other class to handle the callback functions.

xml_set_object?  This only works if the functions are *within* the object you called this method from.

The solution lies in the xml_set_element_handler() function.
Take a look at this sample source...

class XMLParser
{

  ...

  function set_callback_handler($callback_handler)
  {
    // Assign the startElement endElement functions
    xml_set_element_handler(
          $this->xml_parser,
          array($callback_handler, 'start_element'),
          array($callback_handler, 'close_Element' ));

    /* By passing an array with this ($object, 'function_name') structure
       to the 2nd and 3rd parameters.  We are able to tell the parser to
       look in another object for these callback functions.
    */

    // Assign the character data function
    xml_set_character_data_handler(
          $this->xml_parser,
          array($callback_handler, 'character_data'));
    }
}

class myCallBackHandler
{
  function start_element(...)
  {
    //code goes here
  }

  function end_element(...)
  {
    //code goes here
  }

  function character_data(...)
  {
    //code goes here
  }
}

Now all thats left to do is use these classes..

$parser = new XMLParser();
$parser->set_callback_handler(new myCallbackHandler());
dfoesch at cs dot nmsu dot edu 12-Apr-2002 05:38
English explaination of why you do: $xml = & new xml();

Ok, when PHP executes "new xml()" it creates an anonymous variable (one that you can't reference with any name) which it then runs the constructor function on.  Ok, now once that's done, it then assigns by VALUE in the example above.  This means that that lovely pointer to your parser is pointing to the anonymous instance of your class, and not the used instance of your class... thus making a "shadow" of all your variables, where assignments inside the parser access different variables than outside the parser.  What PHP _SHOULD_ be doing (similar to C++) is have this statement execute such that the assignment is done by REFERENCE, so that you assign the new name to the class that actually got constructed, and not just a copy of the class that you constructed.

If they did it right, this code wouldn't be broken.
14-Feb-2002 11:10
Call-time pass-by-reference has been deprecated, so the example is buggy as was already mentionned. However since 4.04 (I think) "new" can return objects by reference. So the clean way to have both the parser initialised in the constructor, and to save the result in your object is to do

$xml_parser = & new xml();

see http://www.php.net/manual/en/language.oop.newref.php

Ivan
pete dot nelson at serverSXPYAZMsolved dot com 27-Aug-2001 10:15
<p>in reply to jon9mm's question, I have found the same problem (function 'startElement' does not exist).  I finally found the way around this, by re-reading this doc for xml_set_object.  You HAVE to use the xml_set_object($this->parser, &$this) within your parser function.</p> <p>When that function is called, your object temporarily becomes the parser object and shares scope (so it can see 'startElement', etc).   Once that function is done, the xml_set_object(...) call goes out of scope, and your object is no longer bound to the parser.  So the simplist solution is to call xml_set_object(...), do any parsing, and then call xml_parser_free(...) all within the same function.</p>
<p>And remember, don't call xml_set_object(...) in your object's constructor - your object will be forever bound to the parser object and you'll loose all access to your object's member functions.</p>
<p>This is all explained in the examples above, but it took me reading it a couple of times to grok how it all works.</p>
nick at category4 dot com 14-May-2001 01:45
If you're using the XML parser within an object, be careful not to accidentally call any methods that don't exist within the object. Instead of complaining that the missing method doesn't exist, PHP will say it's not able to find the handler routines, even if you've indicated them correctly. (PHP version 4.0.5 on FreeBSD).
williams at cse dot unl dot edu 06-Dec-2000 12:42
If xml_set_object is not called in the constructor of an object, the values that the parser modifies will be saved. Else, the values do not seem to be saved as stated by "i_sofer" above.
--- Start Example Code ---
class foo {
var xmlparser;
function foo() { \\the constructor
$this->xmlparser=xmlparser_create();
}
function parse() {
xml_set_object($this->xmlparser,&$this);
\\also include data handler
\\and element handlers here
}
}
--- End Example Code ---
i_sofer at yahoo dot com 18-Nov-2000 04:15
Using xml parser in objects seem to have a problem that values modified(even of the object itself) get lost as soon as parsing ends...
malcontent at msgto dot com 20-Aug-2000 12:11
The example will generate a warning unless allow_call_time_pass_reference is set to true in your INI file. It also will not accept a call by value.
robert at webmotion dot com 18-Apr-2000 10:58
While true that there is no automatic destructor for PHP class objects, it is quite simple to create a method called destroy and perform the destruction manually. In the example above it may not be necessary to free the xml parser immediately... it would appear from the example that the object is re-useable.


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(XMLParser $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(XMLParser $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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(XMLParser $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(XMLParser $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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(XMLParser $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(
XMLParser $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.

Historial de cambios

Versión | Descripción
8.0.0 | parser expects an XMLParser instance now; previously, a valid xml resource was expected.

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 — La clase XMLReader
    • 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

There are no user contributed notes for this page.


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 viene con el código fuente PHP.

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.


La clase XMLReader

(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

class XMLReader {
/* Constantes */
public const int NONE;
public const int ELEMENT;
public const int ATTRIBUTE;
public const int TEXT;
public const int CDATA;
public const int ENTITY_REF;
public const int ENTITY;
public const int PI;
public const int COMMENT;
public const int DOC;
public const int DOC_TYPE;
public const int DOC_FRAGMENT;
public const int NOTATION;
public const int WHITESPACE;
public const int SIGNIFICANT_WHITESPACE;
public const int END_ELEMENT;
public const int END_ENTITY;
public const int XML_DECLARATION;
public const int LOADDTD;
public const int DEFAULTATTRS;
public const int VALIDATE;
public const int SUBST_ENTITIES;
/* Propiedades */
public int $attributeCount;
public string $baseURI;
public int $depth;
public bool $hasAttributes;
public bool $hasValue;
public bool $isDefault;
public bool $isEmptyElement;
public string $localName;
public string $name;
public string $namespaceURI;
public int $nodeType;
public string $prefix;
public string $value;
public string $xmlLang;
/* Métodos */
public close(): true
public expand(?DOMNode $baseNode = null): DOMNode|false
public getAttribute(string $name): ?string
public getAttributeNo(int $index): ?string
public getAttributeNs(string $name, string $namespace): ?string
public getParserProperty(int $property): bool
public isValid(): bool
public lookupNamespace(string $prefix): ?string
public moveToAttribute(string $name): bool
public moveToAttributeNo(int $index): bool
public moveToAttributeNs(string $name, string $namespace): bool
public moveToElement(): bool
public moveToFirstAttribute(): bool
public moveToNextAttribute(): bool
public next(?string $name = null): bool
public static open(string $uri, ?string $encoding = null, int $flags = 0): bool|XMLReader
public read(): bool
public readInnerXml(): string
public readOuterXml(): string
public readString(): string
public setParserProperty(int $property, bool $value): bool
public setRelaxNGSchema(?string $filename): bool
public setRelaxNGSchemaSource(?string $source): bool
public setSchema(?string $filename): bool
public static XML(string $source, ?string $encoding = null, int $flags = 0): bool|XMLReader
}

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(): true

Cierra la entrada del objeto XMLReader que es actualmente análizado.

Parámetros

Esta función no tiene parámetros.

Valores devueltos

Siempre devuelve true.

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 = null): DOMNode|false

Éste metodo copia el nodo actual y devuelve el apropiado objeto DOM.

Parámetros

baseNode

A DOMNode defining the target DOMDocument for the created DOM object.

Valores devueltos

El resultante DOMNode o false en caso de error.

User Contributed Notes

Sbastien 02-Jan-2022 01:29
XMLReader::expand() expands the current subtree to DOM. SimpleXML is good too. To avoid a warning like "Imported Node must have associated Document" when using simplexml_import_dom(), we can do :

<?php

// Huge XML compressed file
$xml = XMLReader::open('compress.zlib:///path/to/my-data.xml.gz');

// Targeting a tiny subtree
while ($xml->name !== 'my-targeted-element') {
    $xml->read();
}

// The trick is here...
// Subtree is expanded in an empty document...
$dom = $xml->expand(new DOMDocument());

// ... which can be imported by SimpleXML
$sx = simplexml_import_dom($dom);

// We can now process our tiny subtree with SimpleXML $sx


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
8.0.0 | Esta función ya no puede devolver false.

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

sven at e7o dot de 08-Nov-2023 02:44
To get all attributes and their names, use something like this:

<?php
function getAttributes($reader)
{
    $attributes = [];
    for ($i = 0; $i < $reader->attributeCount; $i++) {
        $reader->moveToAttributeNo($i);
        $attributes[$reader->name] = $reader->value;
    }
    return $attributes;
}
?>
Anonymous 16-Feb-2011 09:02
Or use XMLReader::ELEMENT and XMLReader::END_ELEMENT rather than the numbers 1 and 15.
Gabi 02-Jul-2007 08:15
might be obvious, but not to everyone ;-) ... when reading attributes from a node that has sub-nodes (and creating an output from this node), the output will be issued twice, once on the <ELEMENT> tag and once on the end tag </ELEMENT>. To avoid this, you can test on which part of the node you are using the property nodeType.
It'll be 1 for the element, 15 for the end element.


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 null 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 $name, string $namespace): ?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

name

El nombre local.

namespace

El URI del namespace.

Valores devueltos

The value of the attribute, or null if no attribute with the given name and namespace is found or not positioned of element.

Historial de cambios

Versión | Descripción
8.0.0 | This function can no longer return false.

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.

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

me at lubu dot ch 31-May-2022 09:54
Be aware that $xml->isValid() will return validity only for currently active node, so you have to loop trough the nodes.

Here is a example how to validate a entire XML file against a XSD schema:

<?php

$xmlReader = new \XMLReader();
$xmlReader->open('./example.xml');
$xmlReader->setParserProperty(\XMLReader::VALIDATE, true);
$xmlReader->setSchema('./schema.xsd');

\libxml_use_internal_errors(true);

$msgs = [];

while ($xmlReader->read()) {
    if (!$xmlReader->isValid()) {
        $err = \libxml_get_last_error();
        if ($err && $err instanceof \libXMLError) {
            $msgs[] = \trim($err->message) . ' on line ' . $err->line;
        }
    }
}

if ($msgs) {
    throw new \Exception("XML schema validation errors:\n - " . implode("\n - ", array_unique($msgs)));
}
?>
zubin at trattonuovo dot com 20-Jan-2010 03:00
I encountered some problems to use isValid method with xml2assoc function.
I use this way to validate the entire xml file and put it into an associative array.

$xml = new XMLReader();
if (!$xml->xml($xml_string, NULL, LIBXML_DTDVALID)) {
  echo "XML not valid: load error";
  exit();
}

libxml_use_internal_errors(TRUE);

$xml_array = xml2assoc($xml);

$arErrors = libxml_get_errors();
$xml_errors = "";
foreach ($arErrors AS $xmlError) $xml_errors .= $xmlError->message;
if ($xml_errors != "") {
  echo "XML not valid: ".$xml_errors;
  exit();
}

//all ok
remy dot damour at laposte dot net 31-Dec-2008 03:27
1. If you validate against relax-ng, no need to call $xml->setParserProperty(XMLReader::VALIDATE, true);

2. Be aware that $xml->isValid() will return validity for currently active node (ie. node currently positioned using $xml->read()). It won't check validity of your entire tree at once, but rather on a step by step basis
anzenews at volja dot net 22-Jan-2008 10:50
This comment is only partially correct:
"isValid() always returns false unless you enable checking for validity by $reader->setParserProperty(XMLReader::VALIDATE, true);"
This enables DTD checking, but you can also check by using RelaxNG (see setRelaxNGSchema() and setRelaxNGSchemaSource()).

And also, this is NOT correct:
"If you just need to check if XML file is well formed, successful loading into XMLReader object is usually enough."
It is not enough. Pull parsers operate on stream and if you have a large enough file they will not know it is well formed until it is read to the end. If you need to know if it is well formed or/and valid, read it till the end or validation error (you can use next() for fast reading if you don't care about contents).


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

Busca el ámbito del namespace para un prefijo dado.

Parámetros

prefix

La cadena conteniendo el prefijo.

Valores devueltos

The value of the namespace, or null if no namespace exists.

Historial de cambios

Versión | Descripción
8.0.0 | This function can no longer return false.

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 $name, string $namespace): bool

Posiciona el cursor en el atributo dado en el espacio de nombres especificado.

Parámetros

name

El nombre local.

namespace

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.

Parámetros

Esta función no tiene parámetros.

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.

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

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

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

  • 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 $name = null): bool

Posiciona el cursor al siguiente nodo saltandose todos los subárboles. Si no existe tal nodo, el cursor se desplaza al final del documento.

Parámetros

name

El nodo del siguiente nodoa mover el cursor.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
8.0.0 | name ahora es anulable.

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 static XMLReader::open(string $uri, ?string $encoding = null, int $flags = 0): bool|XMLReader

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.

flags

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

This method may be called statically, but prior to PHP 8.0.0, will issue an E_DEPRECATED error in this case.

Historial de cambios

Versión | Descripción
8.0.0 | XMLReader::open() is now declared as static method, but can still be called on an XMLReader instance.

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.

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

  • 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

There are no user contributed notes for this page.


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 static XMLReader::XML(string $source, ?string $encoding = null, int $flags = 0): bool|XMLReader

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.

flags

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

This method may be called statically, but prior to PHP 8.0.0, will issue an E_DEPRECATED error in this case.

Historial de cambios

Versión | Descripción
8.0.0 | XMLReader::XML() is now declared as static method, but can still be called on an XMLReader instance.

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 — Fin del atributo
    • XMLWriter::endCData — Fin del actual CDATA
    • XMLWriter::endComment — Crea un comentario final
    • XMLWriter::endDocument — Finaliza el actual documento
    • XMLWriter::endDtd — Finaliza la actual DTD
    • XMLWriter::endDtdAttlist — Finaliza la actual attList DTD
    • XMLWriter::endDtdElement — Finaliza el actual elemento DTD
    • XMLWriter::endDtdEntity — Finaliza el actual ente DTD
    • XMLWriter::endElement — Finaliza el actual elemento
    • XMLWriter::endPi — Finaliza el actual IP
    • XMLWriter::flush — Vacía el búfer actual
    • XMLWriter::fullEndElement — Fin del elemento actual
    • XMLWriter::openMemory — Crea un nuevo xmlwriter usando memoria para el string de salida
    • XMLWriter::openUri — Crea un nuevo xmlwriter usando una fuente uri para la salida
    • XMLWriter::outputMemory — Devuelve el actual buffer
    • XMLWriter::setIndent — Cambia la sangria de encendida/apagada
    • XMLWriter::setIndentString — Establece una cadena usada para la identidad
    • XMLWriter::startAttribute — Crea un atributo inicial
    • XMLWriter::startAttributeNs — Crea el atributo de inicio del namespaced
    • XMLWriter::startCdata — Crea la etiqueta de inicio de CDATA
    • XMLWriter::startComment — Crea un comentario inicial
    • XMLWriter::startDocument — Crea un etiqueta del documento
    • XMLWriter::startDtd — Crea la etiqueta DTD inicial
    • XMLWriter::startDtdAttlist — Crea el DTD AttList inicial
    • XMLWriter::startDtdElement — Crea un elemento DTD inicial
    • XMLWriter::startDtdEntity — Crea un ente DTD inicial
    • XMLWriter::startElement — Crea la etiqueta del elemento inicial
    • XMLWriter::startElementNs — Crea la etiqueta del elemento de espacio de nombres inicial
    • XMLWriter::startPi — Crea la etiqueta PI inicial
    • XMLWriter::text — Escribe el texto
    • XMLWriter::writeAttribute — Escribe un atributo completo
    • XMLWriter::writeAttributeNs — Escribe un atributo full de namespaced
    • XMLWriter::writeCdata — Escribe una etiqueta completa del CDATA
    • XMLWriter::writeComment — EScribe la etiqueta del comentario completa
    • XMLWriter::writeDtd — Escribe una etiqueta completa del DTD
    • XMLWriter::writeDtdAttlist — Escribe la etiqueta completa del DTD AttList
    • XMLWriter::writeDtdElement — Escribe la etiqueta completa de un elemento DTD
    • XMLWriter::writeDtdEntity — Escribe una etiqueta completa de un ente DTD
    • XMLWriter::writeElement — Escribe una etiqueta completa del elemento
    • XMLWriter::writeElementNs — Escribe una etiqueta completa del elemento
    • XMLWriter::writePi — Escribe un IP
    • XMLWriter::writeRaw — Escribe un texto sin formato del XML

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

class XMLWriter {
/* Métodos */
endAttribute(): bool
xmlwriter_end_attribute(resource $xmlwriter): bool
endCdata(): bool
xmlwriter_end_cdata(resource $xmlwriter): bool
endComment(): bool
xmlwriter_end_comment(resource $xmlwriter): bool
endDocument(): bool
xmlwriter_end_document(resource $xmlwriter): bool
endDtd(): bool
xmlwriter_end_dtd(resource $xmlwriter): bool
endDtdAttlist(): bool
xmlwriter_end_dtd_attlist(resource $xmlwriter): bool
endDtdElement(): bool
xmlwriter_end_dtd_element(resource $xmlwriter): bool
endDtdEntity(): bool
xmlwriter_end_dtd_entity(resource $xmlwriter): bool
endElement(): bool
xmlwriter_end_element(resource $xmlwriter): bool
endPi(): bool
xmlwriter_end_pi(resource $xmlwriter): bool
flush(bool $empty = true): mixed
xmlwriter_flush(resource $xmlwriter, bool $empty = true): mixed
fullEndElement(): bool
xmlwriter_full_end_element(resource $xmlwriter): bool
openMemory(): bool
xmlwriter_open_memory(): resource
openUri(string $uri): bool
xmlwriter_open_uri(string $uri): resource
outputMemory(bool $flush = true): string
xmlwriter_output_memory(resource $xmlwriter, bool $flush = true): string
setIndent(bool $indent): bool
xmlwriter_set_indent(resource $xmlwriter, bool $indent): bool
setIndentString(string $indentString): bool
xmlwriter_set_indent_string(resource $xmlwriter, string $indentString): bool
startAttribute(string $name): bool
xmlwriter_start_attribute(resource $xmlwriter, string $name): bool
startAttributeNs(string $prefix, string $name, string $uri): bool
xmlwriter_start_attribute_ns(
resource $xmlwriter,
string $prefix,
string $name,
string $uri
): bool
startCdata(): bool
xmlwriter_start_cdata(resource $xmlwriter): bool
startComment(): bool
xmlwriter_start_comment(resource $xmlwriter): bool
startDocument(string $version = 1.0, string $encoding = null, string $standalone = ?): bool
xmlwriter_start_document(
resource $xmlwriter,
string $version = 1.0,
string $encoding = null,
string $standalone = ?
): bool
startDtd(string $qualifiedName, string $publicId = ?, string $systemId = ?): bool
xmlwriter_start_dtd(
resource $xmlwriter,
string $qualifiedName,
string $publicId = ?,
string $systemId = ?
): bool
startDtdAttlist(string $name): bool
xmlwriter_start_dtd_attlist(resource $xmlwriter, string $name): bool
startDtdElement(string $qualifiedName): bool
xmlwriter_start_dtd_element(resource $xmlwriter, string $qualifiedName): bool
startDtdEntity(string $name, bool $isparam): bool
xmlwriter_start_dtd_entity(resource $xmlwriter, string $name, bool $isparam): bool
startElement(string $name): bool
xmlwriter_start_element(resource $xmlwriter, string $name): bool
startElementNs(string $prefix, string $name, string $uri): bool
xmlwriter_start_element_ns(
resource $xmlwriter,
string $prefix,
string $name,
string $uri
): bool
startPi(string $target): bool
xmlwriter_start_pi(resource $xmlwriter, string $target): bool
text(string $content): bool
xmlwriter_text(resource $xmlwriter, string $content): bool
writeAttribute(string $name, string $value): bool
xmlwriter_write_attribute(resource $xmlwriter, string $name, string $value): bool
writeAttributeNs(
string $prefix,
string $name,
string $uri,
string $content
): bool
xmlwriter_write_attribute_ns(
resource $xmlwriter,
string $prefix,
string $name,
string $uri,
string $content
): bool
writeCdata(string $content): bool
xmlwriter_write_cdata(resource $xmlwriter, string $content): bool
writeComment(string $content): bool
xmlwriter_write_comment(resource $xmlwriter, string $content): bool
writeDtd(
string $name,
string $publicId = ?,
string $systemId = ?,
string $subset = ?
): bool
xmlwriter_write_dtd(
resource $xmlwriter,
string $name,
string $publicId = ?,
string $systemId = ?,
string $subset = ?
): bool
writeDtdAttlist(string $name, string $content): bool
xmlwriter_write_dtd_attlist(resource $xmlwriter, string $name, string $content): bool
writeDtdElement(string $name, string $content): bool
xmlwriter_write_dtd_element(resource $xmlwriter, string $name, string $content): bool
writeDtdEntity(
string $name,
string $content,
bool $pe,
string $pubid,
string $sysid,
string $ndataid
): bool
xmlwriter_write_dtd_entity(
resource $xmlwriter,
string $name,
string $content,
bool $pe,
string $pubid,
string $sysid,
string $ndataid
): bool
writeElement(string $name, string $content = ?): bool
xmlwriter_write_element(resource $xmlwriter, string $name, string $content = ?): bool
writeElementNs(
string $prefix,
string $name,
string $uri,
string $content = ?
): bool
xmlwriter_write_element_ns(
resource $xmlwriter,
string $prefix,
string $name,
string $uri,
string $content = ?
): bool
writePi(string $target, string $content): bool
xmlwriter_write_pi(resource $xmlwriter, string $target, string $content): bool
writeRaw(string $content): bool
xmlwriter_write_raw(resource $xmlwriter, string $content): bool
}

Tabla de contenidos

  • XMLWriter::endAttribute — Fin del atributo
  • XMLWriter::endCData — Fin del actual CDATA
  • XMLWriter::endComment — Crea un comentario final
  • XMLWriter::endDocument — Finaliza el actual documento
  • XMLWriter::endDtd — Finaliza la actual DTD
  • XMLWriter::endDtdAttlist — Finaliza la actual attList DTD
  • XMLWriter::endDtdElement — Finaliza el actual elemento DTD
  • XMLWriter::endDtdEntity — Finaliza el actual ente DTD
  • XMLWriter::endElement — Finaliza el actual elemento
  • XMLWriter::endPi — Finaliza el actual IP
  • XMLWriter::flush — Vacía el búfer actual
  • XMLWriter::fullEndElement — Fin del elemento actual
  • XMLWriter::openMemory — Crea un nuevo xmlwriter usando memoria para el string de salida
  • XMLWriter::openUri — Crea un nuevo xmlwriter usando una fuente uri para la salida
  • XMLWriter::outputMemory — Devuelve el actual buffer
  • XMLWriter::setIndent — Cambia la sangria de encendida/apagada
  • XMLWriter::setIndentString — Establece una cadena usada para la identidad
  • XMLWriter::startAttribute — Crea un atributo inicial
  • XMLWriter::startAttributeNs — Crea el atributo de inicio del namespaced
  • XMLWriter::startCdata — Crea la etiqueta de inicio de CDATA
  • XMLWriter::startComment — Crea un comentario inicial
  • XMLWriter::startDocument — Crea un etiqueta del documento
  • XMLWriter::startDtd — Crea la etiqueta DTD inicial
  • XMLWriter::startDtdAttlist — Crea el DTD AttList inicial
  • XMLWriter::startDtdElement — Crea un elemento DTD inicial
  • XMLWriter::startDtdEntity — Crea un ente DTD inicial
  • XMLWriter::startElement — Crea la etiqueta del elemento inicial
  • XMLWriter::startElementNs — Crea la etiqueta del elemento de espacio de nombres inicial
  • XMLWriter::startPi — Crea la etiqueta PI inicial
  • XMLWriter::text — Escribe el texto
  • XMLWriter::writeAttribute — Escribe un atributo completo
  • XMLWriter::writeAttributeNs — Escribe un atributo full de namespaced
  • XMLWriter::writeCdata — Escribe una etiqueta completa del CDATA
  • XMLWriter::writeComment — EScribe la etiqueta del comentario completa
  • XMLWriter::writeDtd — Escribe una etiqueta completa del DTD
  • XMLWriter::writeDtdAttlist — Escribe la etiqueta completa del DTD AttList
  • XMLWriter::writeDtdElement — Escribe la etiqueta completa de un elemento DTD
  • XMLWriter::writeDtdEntity — Escribe una etiqueta completa de un ente DTD
  • XMLWriter::writeElement — Escribe una etiqueta completa del elemento
  • XMLWriter::writeElementNs — Escribe una etiqueta completa del elemento
  • XMLWriter::writePi — Escribe un IP
  • XMLWriter::writeRaw — Escribe un texto sin formato del XML

User Contributed Notes

There are no user contributed notes for this page.


Fin del atributo

  • « XMLWriter
  • XMLWriter::endCData »
  • PHP Manual
  • XMLWriter
  • Fin del atributo

XMLWriter::endAttribute

xmlwriter_end_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endAttribute -- xmlwriter_end_attribute — Fin del atributo

Descripción

Estilo orientado a objetos

XMLWriter::endAttribute(): bool

Estilo por procedimientos

xmlwriter_end_attribute(resource $xmlwriter): bool

Finaliza el atributo actual.

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.

Ver también

  • XMLWriter::startAttribute() - Crea un atributo inicial
  • XMLWriter::startAttributeNs() - Crea el atributo de inicio del namespaced
  • XMLWriter::writeAttribute() - Escribe un atributo completo
  • XMLWriter::writeAttributeNs() - Escribe un atributo full de namespaced

User Contributed Notes

There are no user contributed notes for this page.


Fin del actual CDATA

  • « XMLWriter::endAttribute
  • XMLWriter::endComment »
  • PHP Manual
  • XMLWriter
  • Fin del actual 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 — Fin del actual CDATA

Descripción

Estilo orientado a objetos

XMLWriter::endCdata(): bool

Estilo por procedimientos

xmlwriter_end_cdata(resource $xmlwriter): bool

Finaliza la actual sección 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.

Ver también

  • XMLWriter::startCdata() - Crea la etiqueta de inicio de CDATA
  • XMLWriter::writeCdata() - Escribe una etiqueta completa del CDATA

User Contributed Notes

There are no user contributed notes for this page.


Crea un comentario final

  • « XMLWriter::endCData
  • XMLWriter::endDocument »
  • PHP Manual
  • XMLWriter
  • Crea un comentario final

XMLWriter::endComment

xmlwriter_end_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::endComment -- xmlwriter_end_comment — Crea un comentario final

Descripción

Estilo orientado a objetos

XMLWriter::endComment(): bool

Estilo por procedimientos

xmlwriter_end_comment(resource $xmlwriter): bool

Crea un comentario final.

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.

Ver también

  • XMLWriter::startComment() - Crea un comentario inicial
  • XMLWriter::writeComment() - EScribe la etiqueta del comentario completa

User Contributed Notes

There are no user contributed notes for this page.


Finaliza el actual documento

  • « XMLWriter::endComment
  • XMLWriter::endDtd »
  • PHP Manual
  • XMLWriter
  • Finaliza el actual documento

XMLWriter::endDocument

xmlwriter_end_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDocument -- xmlwriter_end_document — Finaliza el actual documento

Descripción

Estilo orientado a objetos

XMLWriter::endDocument(): bool

Estilo por procedimientos

xmlwriter_end_document(resource $xmlwriter): bool

Finaliza el actual documento.

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.

Ver también

  • XMLWriter::startDocument() - Crea un etiqueta del documento

User Contributed Notes

There are no user contributed notes for this page.


Finaliza la actual DTD

  • « XMLWriter::endDocument
  • XMLWriter::endDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Finaliza la actual 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 — Finaliza la actual DTD

Descripción

Estilo orientado a objetos

XMLWriter::endDtd(): bool

Estilo por procedimientos

xmlwriter_end_dtd(resource $xmlwriter): bool

Finaliza la actual DTD del documento.

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.

Ver también

  • XMLWriter::startDtd() - Crea la etiqueta DTD inicial
  • XMLWriter::writeDtd() - Escribe una etiqueta completa del DTD

User Contributed Notes

There are no user contributed notes for this page.


Finaliza la actual attList DTD

  • « XMLWriter::endDtd
  • XMLWriter::endDtdElement »
  • PHP Manual
  • XMLWriter
  • Finaliza la actual attList DTD

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 — Finaliza la actual attList DTD

Descripción

Estilo orientado a objetos

XMLWriter::endDtdAttlist(): bool

Estilo por procedimientos

xmlwriter_end_dtd_attlist(resource $xmlwriter): bool

Finaliza la actual attList 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().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startDtdAttlist() - Crea el DTD AttList inicial
  • XMLWriter::writeDtdAttlist() - Escribe la etiqueta completa del DTD AttList

User Contributed Notes

There are no user contributed notes for this page.


Finaliza el actual elemento DTD

  • « XMLWriter::endDtdAttlist
  • XMLWriter::endDtdEntity »
  • PHP Manual
  • XMLWriter
  • Finaliza el actual elemento DTD

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 — Finaliza el actual elemento DTD

Descripción

Estilo orientado a objetos

XMLWriter::endDtdElement(): bool

Estilo por procedimientos

xmlwriter_end_dtd_element(resource $xmlwriter): bool

Finaliza el actual elemento 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().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startDtdElement() - Crea un elemento DTD inicial
  • XMLWriter::writeDtdElement() - Escribe la etiqueta completa de un elemento DTD

User Contributed Notes

There are no user contributed notes for this page.


Finaliza el actual ente DTD

  • « XMLWriter::endDtdElement
  • XMLWriter::endElement »
  • PHP Manual
  • XMLWriter
  • Finaliza el actual ente DTD

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 — Finaliza el actual ente DTD

Descripción

Estilo orientado a objetos

XMLWriter::endDtdEntity(): bool

Estilo por procedimientos

xmlwriter_end_dtd_entity(resource $xmlwriter): bool

Finaliza el actual ente 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().

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startDtdEntity() - Crea un ente DTD inicial
  • XMLWriter::writeDtdEntity() - Escribe una etiqueta completa de un ente DTD

User Contributed Notes

There are no user contributed notes for this page.


Finaliza el actual elemento

  • « XMLWriter::endDtdEntity
  • XMLWriter::endPi »
  • PHP Manual
  • XMLWriter
  • Finaliza el actual elemento

XMLWriter::endElement

xmlwriter_end_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endElement -- xmlwriter_end_element — Finaliza el actual elemento

Descripción

Estilo orientado a objetos

XMLWriter::endElement(): bool

Estilo por procedimientos

xmlwriter_end_element(resource $xmlwriter): bool

Finaliza el actual elemento.

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.

Ver también

  • XMLWriter::startElement() - Crea la etiqueta del elemento inicial
  • XMLWriter::writeElement() - Escribe una etiqueta completa del elemento

User Contributed Notes

There are no user contributed notes for this page.


Finaliza el actual IP

  • « XMLWriter::endElement
  • XMLWriter::flush »
  • PHP Manual
  • XMLWriter
  • Finaliza el actual IP

XMLWriter::endPi

xmlwriter_end_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endPi -- xmlwriter_end_pi — Finaliza el actual IP

Descripción

Estilo orientado a objetos

XMLWriter::endPi(): bool

Estilo por procedimientos

xmlwriter_end_pi(resource $xmlwriter): bool

Finaliza la actual instrucción de procesamiento.

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.

Ver también

  • XMLWriter::startPi() - Crea la etiqueta PI inicial
  • XMLWriter::writePi() - Escribe un IP

User Contributed Notes

There are no user contributed notes for this page.


Vacía el búfer actual

  • « XMLWriter::endPi
  • XMLWriter::fullEndElement »
  • PHP Manual
  • XMLWriter
  • Vacía el búfer actual

XMLWriter::flush

xmlwriter_flush

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::flush -- xmlwriter_flush — Vacía el búfer actual

Descripción

Estilo orientado a objetos

XMLWriter::flush(bool $empty = true): mixed

Estilo por procedimientos

xmlwriter_flush(resource $xmlwriter, bool $empty = true): mixed

Vacía el buffer actual.

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

Cuando vaciar el buffer o no. Por omisión es true.

Valores devueltos

Si se abrió el documento en memoria, ésta función devolverá el buffer XML generado, Además, si se usa URI, esta función va a escribir el buffer y devolver el número de bytes escritos.

User Contributed Notes

There are no user contributed notes for this page.


Fin del elemento actual

  • « XMLWriter::flush
  • XMLWriter::openMemory »
  • PHP Manual
  • XMLWriter
  • Fin del elemento actual

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 — Fin del elemento actual

Descripción

Estilo orientado a objetos

XMLWriter::fullEndElement(): bool

Estilo por procedimientos

xmlwriter_full_end_element(resource $xmlwriter): bool

Fin del elemento XML actual. Escribe una etiqueta final aun si el elemento está vacío.

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.

Ver también

  • XMLWriter::endElement() - Finaliza el actual elemento

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo xmlwriter usando memoria para el string de salida

  • « XMLWriter::fullEndElement
  • XMLWriter::openUri »
  • PHP Manual
  • XMLWriter
  • Crea un nuevo xmlwriter usando memoria para el string de salida

XMLWriter::openMemory

xmlwriter_open_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openMemory -- xmlwriter_open_memory — Crea un nuevo xmlwriter usando memoria para el string de salida

Descripción

Estilo orientado a objetos

XMLWriter::openMemory(): bool

Estilo por procedimientos

xmlwriter_open_memory(): resource

Crea un nuevo XMLWriter usando memoria para el string de salida.

Parámetros

Valores devueltos

Estilo orientado a objetos: Devuelve true en caso de éxito o false en caso de error.

Estilo por procedimientos: Devuelve un nuevo recurso xmlwriter para luego usarlo con las funciones de xmlwriter en caso de éxito, y false en caso de error.

Ver también

  • XMLWriter::openUri() - Crea un nuevo xmlwriter usando una fuente uri para la salida

User Contributed Notes

There are no user contributed notes for this page.


Crea un nuevo xmlwriter usando una fuente uri para la salida

  • « XMLWriter::openMemory
  • XMLWriter::outputMemory »
  • PHP Manual
  • XMLWriter
  • Crea un nuevo xmlwriter usando una fuente uri para la salida

XMLWriter::openUri

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openUri -- xmlwriter_open_uri — Crea un nuevo xmlwriter usando una fuente uri para la salida

Descripción

Estilo orientado a objetos

XMLWriter::openUri(string $uri): bool

Estilo por procedimientos

xmlwriter_open_uri(string $uri): resource

Crea un nuevo XMLWriter usando uri para la salida.

Parámetros

uri

El recurso de URI para la salida.

Valores devueltos

Estilo orientado a objetos: Devuelve true en caso de éxito o false en caso de error.

Estilo por procedimientos: Devuelve un nuevo xmlwriter recurso para usarlo después con las funciones xmlwriter en caso de éxito, false en caso de error.

Ver también

  • XMLWriter::openMemory() - Crea un nuevo xmlwriter usando memoria para el string de salida

User Contributed Notes

There are no user contributed notes for this page.


Devuelve el actual buffer

  • « XMLWriter::openUri
  • XMLWriter::setIndent »
  • PHP Manual
  • XMLWriter
  • Devuelve el actual 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 — Devuelve el actual buffer

Descripción

Estilo orientado a objetos

XMLWriter::outputMemory(bool $flush = true): string

Estilo por procedimientos

xmlwriter_output_memory(resource $xmlwriter, bool $flush = true): string

Devuelve el buffer actual.

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

Si se mantiene la salida del buffer o no. Por omisión es true.

Valores devueltos

Devuelve el buffer actual como un string.

Ver también

  • XMLWriter::flush() - Vacía el búfer actual

User Contributed Notes

There are no user contributed notes for this page.


Cambia la sangria de encendida/apagada

  • « XMLWriter::outputMemory
  • XMLWriter::setIndentString »
  • PHP Manual
  • XMLWriter
  • Cambia la sangria de encendida/apagada

XMLWriter::setIndent

xmlwriter_set_indent

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndent -- xmlwriter_set_indent — Cambia la sangria de encendida/apagada

Descripción

Estilo orientado a objetos

XMLWriter::setIndent(bool $indent): bool

Estilo por procedimientos

xmlwriter_set_indent(resource $xmlwriter, bool $indent): bool

Cambia la sangría a encendida o apagada

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().

indent

Si la sangría está activada.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::setIndentString() - Establece una cadena usada para la identidad

User Contributed Notes

There are no user contributed notes for this page.


Establece una cadena usada para la identidad

  • « XMLWriter::setIndent
  • XMLWriter::startAttribute »
  • PHP Manual
  • XMLWriter
  • Establece una cadena usada para la identidad

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 — Establece una cadena usada para la identidad

Descripción

Estilo orientado a objetos

XMLWriter::setIndentString(string $indentString): bool

Estilo por procedimientos

xmlwriter_set_indent_string(resource $xmlwriter, string $indentString): bool

Establece el string el cual va a ser usado para sangrar cada elemento/atributo del resultado 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().

indentString

El string de sangría.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::setIndent() - Cambia la sangria de encendida/apagada

User Contributed Notes

There are no user contributed notes for this page.


Crea un atributo inicial

  • « XMLWriter::setIndentString
  • XMLWriter::startAttributeNs »
  • PHP Manual
  • XMLWriter
  • Crea un atributo inicial

XMLWriter::startAttribute

xmlwriter_start_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttribute -- xmlwriter_start_attribute — Crea un atributo inicial

Descripción

Estilo orientado a objetos

XMLWriter::startAttribute(string $name): bool

Estilo por procedimientos

xmlwriter_start_attribute(resource $xmlwriter, string $name): bool

Inicia un atributo.

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

El nombre del atributo.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startAttributeNs() - Crea el atributo de inicio del namespaced
  • XMLWriter::endAttribute() - Fin del atributo
  • XMLWriter::writeAttribute() - Escribe un atributo completo
  • XMLWriter::writeAttributeNs() - Escribe un atributo full de namespaced

User Contributed Notes

There are no user contributed notes for this page.


Crea el atributo de inicio del namespaced

  • « XMLWriter::startAttribute
  • XMLWriter::startCdata »
  • PHP Manual
  • XMLWriter
  • Crea el atributo de inicio del namespaced

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 — Crea el atributo de inicio del namespaced

Descripción

Estilo orientado a objetos

XMLWriter::startAttributeNs(string $prefix, string $name, string $uri): bool

Estilo por procedimientos

xmlwriter_start_attribute_ns(
resource $xmlwriter,
string $prefix,
string $name,
string $uri
): bool

Inicia un atributo de namespaced.

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

El prefijo del namespace.

name

El atributo del nombre.

uri

El URI del namespaced.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startAttribute() - Crea un atributo inicial
  • XMLWriter::endAttribute() - Fin del atributo
  • XMLWriter::writeAttribute() - Escribe un atributo completo
  • XMLWriter::writeAttributeNs() - Escribe un atributo full de namespaced

User Contributed Notes

There are no user contributed notes for this page.


Crea la etiqueta de inicio de CDATA

  • « XMLWriter::startAttributeNs
  • XMLWriter::startComment »
  • PHP Manual
  • XMLWriter
  • Crea la etiqueta de inicio de CDATA

XMLWriter::startCdata

xmlwriter_start_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startCdata -- xmlwriter_start_cdata — Crea la etiqueta de inicio de CDATA

Descripción

Estilo orientado a objetos

XMLWriter::startCdata(): bool

Estilo por procedimientos

xmlwriter_start_cdata(resource $xmlwriter): bool

Inicia un 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.

Ver también

  • XMLWriter::endCdata() - Fin del actual CDATA
  • XMLWriter::writeCdata() - Escribe una etiqueta completa del CDATA

User Contributed Notes

There are no user contributed notes for this page.


Crea un comentario inicial

  • « XMLWriter::startCdata
  • XMLWriter::startDocument »
  • PHP Manual
  • XMLWriter
  • Crea un comentario inicial

XMLWriter::startComment

xmlwriter_start_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::startComment -- xmlwriter_start_comment — Crea un comentario inicial

Descripción

Estilo orientado a objetos

XMLWriter::startComment(): bool

Estilo por procedimientos

xmlwriter_start_comment(resource $xmlwriter): bool

Inicia un comentario.

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.

Ver también

  • XMLWriter::endComment() - Crea un comentario final
  • XMLWriter::writeComment() - EScribe la etiqueta del comentario completa

User Contributed Notes

There are no user contributed notes for this page.


Crea un etiqueta del documento

  • « XMLWriter::startComment
  • XMLWriter::startDtd »
  • PHP Manual
  • XMLWriter
  • Crea un etiqueta del documento

XMLWriter::startDocument

xmlwriter_start_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDocument -- xmlwriter_start_document — Crea un etiqueta del documento

Descripción

Estilo orientado a objetos

XMLWriter::startDocument(string $version = 1.0, string $encoding = null, string $standalone = ?): bool

Estilo por procedimientos

xmlwriter_start_document(
resource $xmlwriter,
string $version = 1.0,
string $encoding = null,
string $standalone = ?
): bool

Inicia un documento.

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

La versión numerica del documento como parte de la declaración XML.

encoding

La codificación del documento como parte de la declaración XML.

standalone

yes o no.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::endDocument() - Finaliza el actual documento

User Contributed Notes

There are no user contributed notes for this page.


Crea la etiqueta DTD inicial

  • « XMLWriter::startDocument
  • XMLWriter::startDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Crea la etiqueta DTD inicial

XMLWriter::startDtd

xmlwriter_start_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtd -- xmlwriter_start_dtd — Crea la etiqueta DTD inicial

Descripción

Estilo orientado a objetos

XMLWriter::startDtd(string $qualifiedName, string $publicId = ?, string $systemId = ?): bool

Estilo por procedimientos

xmlwriter_start_dtd(
resource $xmlwriter,
string $qualifiedName,
string $publicId = ?,
string $systemId = ?
): bool

Inicia un 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

El nombre calificado del tipo de documento a crear.

publicId

El identificador externo del subconjunto publico.

systemId

El identificador externo del subconjunto del sistema.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::endDtd() - Finaliza la actual DTD
  • XMLWriter::writeDtd() - Escribe una etiqueta completa del DTD

User Contributed Notes

There are no user contributed notes for this page.


Crea el DTD AttList inicial

  • « XMLWriter::startDtd
  • XMLWriter::startDtdElement »
  • PHP Manual
  • XMLWriter
  • Crea el DTD AttList inicial

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 — Crea el DTD AttList inicial

Descripción

Estilo orientado a objetos

XMLWriter::startDtdAttlist(string $name): bool

Estilo por procedimientos

xmlwriter_start_dtd_attlist(resource $xmlwriter, string $name): bool

Inicia una lista de atributo 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

El nombre de la lista de atributos.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::endDtdAttlist() - Finaliza la actual attList DTD
  • XMLWriter::writeDtdAttlist() - Escribe la etiqueta completa del DTD AttList

User Contributed Notes

There are no user contributed notes for this page.


Crea un elemento DTD inicial

  • « XMLWriter::startDtdAttlist
  • XMLWriter::startDtdEntity »
  • PHP Manual
  • XMLWriter
  • Crea un elemento DTD inicial

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 — Crea un elemento DTD inicial

Descripción

Estilo orientado a objetos

XMLWriter::startDtdElement(string $qualifiedName): bool

Estilo por procedimientos

xmlwriter_start_dtd_element(resource $xmlwriter, string $qualifiedName): bool

Inicia un elemento 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

El nombre calificado del tipo de documento a crear.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::endDtdElement() - Finaliza el actual elemento DTD
  • XMLWriter::writeDtdElement() - Escribe la etiqueta completa de un elemento DTD

User Contributed Notes

There are no user contributed notes for this page.


Crea un ente DTD inicial

  • « XMLWriter::startDtdElement
  • XMLWriter::startElement »
  • PHP Manual
  • XMLWriter
  • Crea un ente DTD inicial

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 — Crea un ente DTD inicial

Descripción

Estilo orientado a objetos

XMLWriter::startDtdEntity(string $name, bool $isparam): bool

Estilo por procedimientos

xmlwriter_start_dtd_entity(resource $xmlwriter, string $name, bool $isparam): bool

Inicia un ente 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

El nombre de la entidad.

isparam

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::endDtdEntity() - Finaliza el actual ente DTD
  • XMLWriter::writeDtdEntity() - Escribe una etiqueta completa de un ente DTD

User Contributed Notes

There are no user contributed notes for this page.


Crea la etiqueta del elemento inicial

  • « XMLWriter::startDtdEntity
  • XMLWriter::startElementNs »
  • PHP Manual
  • XMLWriter
  • Crea la etiqueta del elemento inicial

XMLWriter::startElement

xmlwriter_start_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startElement -- xmlwriter_start_element — Crea la etiqueta del elemento inicial

Descripción

Estilo orientado a objetos

XMLWriter::startElement(string $name): bool

Estilo por procedimientos

xmlwriter_start_element(resource $xmlwriter, string $name): bool

Inicia un elemento.

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

El nombre del elemento.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::endElement() - Finaliza el actual elemento
  • XMLWriter::writeElement() - Escribe una etiqueta completa del elemento

User Contributed Notes

There are no user contributed notes for this page.


Crea la etiqueta del elemento de espacio de nombres inicial

  • « XMLWriter::startElement
  • XMLWriter::startPi »
  • PHP Manual
  • XMLWriter
  • Crea la etiqueta del elemento de espacio de nombres inicial

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 — Crea la etiqueta del elemento de espacio de nombres inicial

Descripción

Estilo orientado a objetos

XMLWriter::startElementNs(string $prefix, string $name, string $uri): bool

Estilo por procedimientos

xmlwriter_start_element_ns(
resource $xmlwriter,
string $prefix,
string $name,
string $uri
): bool

Inicia un elemento de espacio de nombres.

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

El prefijo del namespace.

name

El elemento del nombre.

uri

El namespace de URI.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::endElement() - Finaliza el actual elemento
  • XMLWriter::writeElementNs() - Escribe una etiqueta completa del elemento

User Contributed Notes

There are no user contributed notes for this page.


Crea la etiqueta PI inicial

  • « XMLWriter::startElementNs
  • XMLWriter::text »
  • PHP Manual
  • XMLWriter
  • Crea la etiqueta PI inicial

XMLWriter::startPi

xmlwriter_start_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startPi -- xmlwriter_start_pi — Crea la etiqueta PI inicial

Descripción

Estilo orientado a objetos

XMLWriter::startPi(string $target): bool

Estilo por procedimientos

xmlwriter_start_pi(resource $xmlwriter, string $target): bool

Inicia una etiqueta para la instrucción de procesamiento.

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

El objetivo de la instrucción de procesamiento.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::endPi() - Finaliza el actual IP
  • XMLWriter::writePi() - Escribe un IP

User Contributed Notes

There are no user contributed notes for this page.


Escribe el texto

  • « XMLWriter::startPi
  • XMLWriter::writeAttribute »
  • PHP Manual
  • XMLWriter
  • Escribe el texto

XMLWriter::text

xmlwriter_text

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::text -- xmlwriter_text — Escribe el texto

Descripción

Estilo orientado a objetos

XMLWriter::text(string $content): bool

Estilo por procedimientos

xmlwriter_text(resource $xmlwriter, string $content): bool

Escribe el texto.

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

El contenido del texto.

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.


Escribe un atributo completo

  • « XMLWriter::text
  • XMLWriter::writeAttributeNs »
  • PHP Manual
  • XMLWriter
  • Escribe un atributo completo

XMLWriter::writeAttribute

xmlwriter_write_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttribute -- xmlwriter_write_attribute — Escribe un atributo completo

Descripción

Estilo orientado a objetos

XMLWriter::writeAttribute(string $name, string $value): bool

Estilo por procedimientos

xmlwriter_write_attribute(resource $xmlwriter, string $name, string $value): bool

Escribe un atributo completo.

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

El nombre del atributo.

value

El valor del atributo.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::writeAttributeNs() - Escribe un atributo full de namespaced
  • XMLWriter::startAttribute() - Crea un atributo inicial
  • XMLWriter::startAttributeNs() - Crea el atributo de inicio del namespaced
  • XMLWriter::endAttribute() - Fin del atributo

User Contributed Notes

There are no user contributed notes for this page.


Escribe un atributo full de namespaced

  • « XMLWriter::writeAttribute
  • XMLWriter::writeCdata »
  • PHP Manual
  • XMLWriter
  • Escribe un atributo full de namespaced

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 — Escribe un atributo full de namespaced

Descripción

Estilo orientado a objetos

XMLWriter::writeAttributeNs(
string $prefix,
string $name,
string $uri,
string $content
): bool

Estilo por procedimientos

xmlwriter_write_attribute_ns(
resource $xmlwriter,
string $prefix,
string $name,
string $uri,
string $content
): bool

Escribe un atributo de espacio de nombres completo.

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

el prefijo del namespace.

name

El nombre del atributo.

uri

El namespace de URI.

content

El valor del atributo.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::writeAttribute() - Escribe un atributo completo
  • XMLWriter::startAttribute() - Crea un atributo inicial
  • XMLWriter::startAttributeNs() - Crea el atributo de inicio del namespaced
  • XMLWriter::endAttribute() - Fin del atributo

User Contributed Notes

There are no user contributed notes for this page.


Escribe una etiqueta completa del CDATA

  • « XMLWriter::writeAttributeNs
  • XMLWriter::writeComment »
  • PHP Manual
  • XMLWriter
  • Escribe una etiqueta completa del CDATA

XMLWriter::writeCdata

xmlwriter_write_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeCdata -- xmlwriter_write_cdata — Escribe una etiqueta completa del CDATA

Descripción

Estilo orientado a objetos

XMLWriter::writeCdata(string $content): bool

Estilo por procedimientos

xmlwriter_write_cdata(resource $xmlwriter, string $content): bool

Escribe un CDATA completo.

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

El contenido del CDATA.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startCdata() - Crea la etiqueta de inicio de CDATA
  • XMLWriter::endCdata() - Fin del actual CDATA

User Contributed Notes

There are no user contributed notes for this page.


EScribe la etiqueta del comentario completa

  • « XMLWriter::writeCdata
  • XMLWriter::writeDtd »
  • PHP Manual
  • XMLWriter
  • EScribe la etiqueta del comentario completa

XMLWriter::writeComment

xmlwriter_write_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeComment -- xmlwriter_write_comment — EScribe la etiqueta del comentario completa

Descripción

Estilo orientado a objetos

XMLWriter::writeComment(string $content): bool

Estilo por procedimientos

xmlwriter_write_comment(resource $xmlwriter, string $content): bool

Escribe un comentario completo.

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

El contenido del comentario.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startComment() - Crea un comentario inicial
  • XMLWriter::endComment() - Crea un comentario final

User Contributed Notes

There are no user contributed notes for this page.


Escribe una etiqueta completa del DTD

  • « XMLWriter::writeComment
  • XMLWriter::writeDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Escribe una etiqueta completa del DTD

XMLWriter::writeDtd

xmlwriter_write_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtd -- xmlwriter_write_dtd — Escribe una etiqueta completa del DTD

Descripción

Estilo orientado a objetos

XMLWriter::writeDtd(
string $name,
string $publicId = ?,
string $systemId = ?,
string $subset = ?
): bool

Estilo por procedimientos

xmlwriter_write_dtd(
resource $xmlwriter,
string $name,
string $publicId = ?,
string $systemId = ?,
string $subset = ?
): bool

Escribe un completo 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

El nombre del DTD.

publicId

El identificador del subcojunto externo publico.

systemId

El identificador externo del subconjunto del sistema.

subset

El contenido del DTD.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startDtd() - Crea la etiqueta DTD inicial
  • XMLWriter::endDtd() - Finaliza la actual DTD

User Contributed Notes

There are no user contributed notes for this page.


Escribe la etiqueta completa del DTD AttList

  • « XMLWriter::writeDtd
  • XMLWriter::writeDtdElement »
  • PHP Manual
  • XMLWriter
  • Escribe la etiqueta completa del DTD AttList

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 — Escribe la etiqueta completa del DTD AttList

Descripción

Estilo orientado a objetos

XMLWriter::writeDtdAttlist(string $name, string $content): bool

Estilo por procedimientos

xmlwriter_write_dtd_attlist(resource $xmlwriter, string $name, string $content): bool

Escribe una lista del 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

El nombre de la lista del atributo del DTD.

content

El contenido de la lista del atributo del DTD.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startDtdAttlist() - Crea el DTD AttList inicial
  • XMLWriter::endDtdAttlist() - Finaliza la actual attList DTD

User Contributed Notes

There are no user contributed notes for this page.


Escribe la etiqueta completa de un elemento DTD

  • « XMLWriter::writeDtdAttlist
  • XMLWriter::writeDtdEntity »
  • PHP Manual
  • XMLWriter
  • Escribe la etiqueta completa de un elemento DTD

XMLWriter::writeDtdElement

xmlwriter_write_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdElement -- xmlwriter_write_dtd_element — Escribe la etiqueta completa de un elemento DTD

Descripción

Estilo orientado a objetos

XMLWriter::writeDtdElement(string $name, string $content): bool

Estilo por procedimientos

xmlwriter_write_dtd_element(resource $xmlwriter, string $name, string $content): bool

Escribe un elemento completo 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

El nombre del elemento DTD.

content

El contenido del elemento.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startDtdElement() - Crea un elemento DTD inicial
  • XMLWriter::endDtdElement() - Finaliza el actual elemento DTD

User Contributed Notes

There are no user contributed notes for this page.


Escribe una etiqueta completa de un ente DTD

  • « XMLWriter::writeDtdElement
  • XMLWriter::writeElement »
  • PHP Manual
  • XMLWriter
  • Escribe una etiqueta completa de un ente DTD

XMLWriter::writeDtdEntity

xmlwriter_write_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdEntity -- xmlwriter_write_dtd_entity — Escribe una etiqueta completa de un ente DTD

Descripción

Estilo orientado a objetos

XMLWriter::writeDtdEntity(
string $name,
string $content,
bool $pe,
string $pubid,
string $sysid,
string $ndataid
): bool

Estilo por procedimientos

xmlwriter_write_dtd_entity(
resource $xmlwriter,
string $name,
string $content,
bool $pe,
string $pubid,
string $sysid,
string $ndataid
): bool

Escribe un ente completo 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

El nombre del ente.

content

El contenido del ente.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startDtdEntity() - Crea un ente DTD inicial
  • XMLWriter::endDtdEntity() - Finaliza el actual ente DTD

User Contributed Notes

There are no user contributed notes for this page.


Escribe una etiqueta completa del elemento

  • « XMLWriter::writeDtdEntity
  • XMLWriter::writeElementNs »
  • PHP Manual
  • XMLWriter
  • Escribe una etiqueta completa del elemento

XMLWriter::writeElement

xmlwriter_write_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElement -- xmlwriter_write_element — Escribe una etiqueta completa del elemento

Descripción

Estilo orientado a objetos

XMLWriter::writeElement(string $name, string $content = ?): bool

Estilo por procedimientos

xmlwriter_write_element(resource $xmlwriter, string $name, string $content = ?): bool

Escribe una etiqueta completa del elemento.

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

El nombre del elemento.

content

Los contenidos del elemento.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
5.2.3 | El parámetro content se convierte en opcional.

Ver también

  • XMLWriter::startElement() - Crea la etiqueta del elemento inicial
  • XMLWriter::endElement() - Finaliza el actual elemento
  • XMLWriter::writeElementNs() - Escribe una etiqueta completa del elemento

User Contributed Notes

There are no user contributed notes for this page.


Escribe una etiqueta completa del elemento

  • « XMLWriter::writeElement
  • XMLWriter::writePi »
  • PHP Manual
  • XMLWriter
  • Escribe una etiqueta completa del elemento

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 — Escribe una etiqueta completa del elemento

Descripción

Estilo orientado a objetos

XMLWriter::writeElementNs(
string $prefix,
string $name,
string $uri,
string $content = ?
): bool

Estilo por procedimientos

xmlwriter_write_element_ns(
resource $xmlwriter,
string $prefix,
string $name,
string $uri,
string $content = ?
): bool

Escribe una etiqueta completa del elemento.

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

El nombre del prefijo.

name

El nombre del elemento.

uri

El URI del namespace.

content

Los contenidos del elemento.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Historial de cambios

Versión | Descripción
5.2.3 | El parámetro content se convierte en opcional.

Ver también

  • XMLWriter::startElementNs() - Crea la etiqueta del elemento de espacio de nombres inicial
  • XMLWriter::endElement() - Finaliza el actual elemento
  • XMLWriter::writeElement() - Escribe una etiqueta completa del elemento

User Contributed Notes

There are no user contributed notes for this page.


Escribe un IP

  • « XMLWriter::writeElementNs
  • XMLWriter::writeRaw »
  • PHP Manual
  • XMLWriter
  • Escribe un IP

XMLWriter::writePi

xmlwriter_write_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writePi -- xmlwriter_write_pi — Escribe un IP

Descripción

Estilo orientado a objetos

XMLWriter::writePi(string $target, string $content): bool

Estilo por procedimientos

xmlwriter_write_pi(resource $xmlwriter, string $target, string $content): bool

Escribe una instrucción de procesamiento.

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

El objetivo de la instrucción de procesamiento.

content

El contenido de la instrucción de procesamiento.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::startPi() - Crea la etiqueta PI inicial
  • XMLWriter::endPi() - Finaliza el actual IP

User Contributed Notes

There are no user contributed notes for this page.


Escribe un texto sin formato del XML

  • « XMLWriter::writePi
  • XSL »
  • PHP Manual
  • XMLWriter
  • Escribe un texto sin formato del XML

XMLWriter::writeRaw

xmlwriter_write_raw

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4)

XMLWriter::writeRaw -- xmlwriter_write_raw — Escribe un texto sin formato del XML

Descripción

Estilo orientado a objetos

XMLWriter::writeRaw(string $content): bool

Estilo por procedimientos

xmlwriter_write_raw(resource $xmlwriter, string $content): bool

Escribe un texto sin formato del 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().

content

El string a escribir.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Ver también

  • XMLWriter::text() - Escribe el texto

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

class 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 dimensions (width, height)
    • UI\Window — Window
    • UI\Control — Control
    • UI\Menu — Menu
    • UI\MenuItem — Menu Item
    • UI\Area — Area
    • UI\Executor — Execution Scheduler
    • UI\Controls\Tab — Tab Control
    • UI\Controls\Check — Check Control
    • UI\Controls\Button — Button Control
    • UI\Controls\ColorButton — ColorButton Control
    • UI\Controls\Label — Label Control
    • UI\Controls\Entry — Entry Control
    • UI\Controls\MultilineEntry — MultilineEntry Control
    • UI\Controls\Spin — Spin Control
    • UI\Controls\Slider — Slider Control
    • UI\Controls\Progress — Progress Control
    • UI\Controls\Separator — Control Separator
    • UI\Controls\Combo — Combo Control
    • UI\Controls\EditableCombo — EdiableCombo Control
    • UI\Controls\Radio — Radio Control
    • UI\Controls\Picker — Picker Control
    • UI\Controls\Form — Control Form (Arrangement)
    • UI\Controls\Grid — Control Grid (Arrangement)
    • UI\Controls\Group — Control Group (Arrangement)
    • UI\Controls\Box — Control Box (Arrangement)
    • UI\Draw\Pen — Draw Pen
    • UI\Draw\Path — Draw Path
    • UI\Draw\Matrix — Draw Matrix
    • UI\Draw\Color — Color Representation
    • UI\Draw\Stroke — Draw Stroke
    • UI\Draw\Brush — Brushes
    • UI\Draw\Brush\Gradient — Gradient Brushes
    • UI\Draw\Brush\LinearGradient — Linear Gradient
    • UI\Draw\Brush\RadialGradient — Radial Gradient
    • UI\Draw\Text\Layout — Represents Text Layout
    • UI\Draw\Text\Font — Represents a Font
    • UI\Draw\Text\Font\Descriptor — Font Descriptor
    • UI 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 dimensions (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 class 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 dimensions (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 class 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

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

class 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

class 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

class UI\Area extends UI\Control {
/* Constantes */
const int Ctrl;
const int Alt;
const int Shift;
const int Super;
const int Down;
const int Up;
/* Mé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 class 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

class 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

class 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

class 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

class 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

class 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

class UI\Controls\Entry extends UI\Control {
/* Constantes */
const int Normal;
const int Password;
const int Search;
/* Constructor */
public __construct(int $type = UI\Controls\Entry::Normal)
/* Mé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

class UI\Controls\MultilineEntry extends UI\Control {
/* Constantes */
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

class 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

class 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

class 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

class UI\Controls\Separator extends UI\Control {
/* Constantes */
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

class 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

class 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

class 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

class UI\Controls\Picker extends UI\Control {
/* Constantes */
const int Date;
const int Time;
const int DateTime;
/* Constructor */
public __construct(int $type = UI\Controls\Picker::Date)
/* Mé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

class 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

class UI\Controls\Grid extends UI\Control {
/* Constantes */
const int Fill;
const int Start;
const int Center;
const int End;
const int Leading;
const int Top;
const int Trailing;
const int Bottom;
/* 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

class 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

class UI\Controls\Box extends UI\Control {
/* Constantes */
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 class 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

class UI\Draw\Path {
/* Constantes */
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

class 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

class UI\Draw\Color {
/* Constantes */
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

class UI\Draw\Stroke {
/* Constructor */
public __construct(
int $cap = UI\Draw\Line\Cap::Flat,
int $join = UI\Draw\Line\Join::Miter,
float $thickness = 1,
float $miterLimit = 10
)
/* Mé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

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

class 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

class 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

class 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

class 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

class UI\Draw\Text\Font\Descriptor {
/* Constructor */
public __construct(
string $family,
float $size,
int $weight = UI\Draw\Text\Font\Weight::Normal,
int $italic = UI\Draw\Text\Font\Italic::Normal,
int $stretch = UI\Draw\Text\Font\Stretch::Normal
)
/* Mé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 class UI\Draw\Text\Font\Weight {
/* Constantes */
const int Thin;
const int UltraLight;
const int Light;
const int Book;
const int Normal;
const int Medium;
const int SemiBold;
const int Bold;
const int UltraBold;
const int Heavy;
const int UltraHeavy;
}

User Contributed Notes

There are no user contributed notes for this page.


Italic Font Settings

(UI 0.9.9)

Introducción

Sinopsis de la Clase

final class UI\Draw\Text\Font\Italic {
/* Constantes */
const int Normal = 0;
const int Oblique = 1;
const int Italic = 2;
}

User Contributed Notes

There are no user contributed notes for this page.


Font Stretch Settings

(UI 0.9.9)

Introducción

Sinopsis de la Clase

final class UI\Draw\Text\Font\Stretch {
/* Constantes */
const int UltraCondensed = 0;
const int ExtraCondensed = 1;
const int Condensed = 2;
const int SemiCondensed = 3;
const int Normal = 4;
const int SemiExpanded = 5;
const int Expanded = 6;
const int ExtraExpanded = 7;
const int UltraExpanded = 8;
}

User Contributed Notes

There are no user contributed notes for this page.


Line Cap Settings

(UI 0.9.9)

Introducción

Sinopsis de la Clase

final class UI\Draw\Line\Cap {
/* Constantes */
const int Flat;
const int Round;
const int Square;
}

User Contributed Notes

There are no user contributed notes for this page.


Line Join Settings

(UI 0.9.9)

Introducción

Sinopsis de la Clase

final class UI\Draw\Line\Join {
/* Constantes */
const int Miter;
const int Round;
const int Bevel;
}

User Contributed Notes

There are no user contributed notes for this page.


Key Identifiers

(UI 1.0.0)

Introducción

Sinopsis de la Clase

final class UI\Key {
/* Constantes */
const int Escape;
const int Insert;
const int Delete;
const int Home;
const int End;
const int PageUp;
const int PageDown;
const int Up;
const int Down;
const int Left;
const int Right;
const int F1;
const int F2;
const int F3;
const int F4;
const int F5;
const int F6;
const int F7;
const int F8;
const int F9;
const int F10;
const int F11;
const int F12;
const int N0;
const int N1;
const int N2;
const int N3;
const int N4;
const int N5;
const int N6;
const int N7;
const int N8;
const int N9;
const int NDot;
const int NEnter;
const int NAdd;
const int NSubtract;
const int NMultiply;
const int NDivide;
}

User Contributed Notes

There are no user contributed notes for this page.


InvalidArgumentException

(UI 1.0.3)

Introducción

Sinopsis de la Clase

class UI\Exception\InvalidArgumentException extends InvalidArgumentException implements Throwable {
/* Propiedades heredadas */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Métodos heredados */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


RuntimeException

(UI 1.0.3)

Introducción

Sinopsis de la Clase

class UI\Exception\RuntimeException extends RuntimeException implements Throwable {
/* Propiedades heredadas */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Métodos heredados */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


FAQ: 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 8 es la generación actual de PHP, la cual emplea el Motor Zend 4 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://github.com/php/php-src/issues.

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

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://github.com/php/php-src/issues

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:

  • 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

Nota: Asegúrese de reiniciar tras seguir los pasos anteriores para garantizar que se apliquen los cambios a PATH.

¿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, 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

¿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. 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.
  10. 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?
  11. 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.
  12. Cuando intento compilar PHP usando --with-apxs obtengo mensajes de error extraños.
  13. Durante el make, obtengo errores sobre microtime, y muchas cosas de RUSAGE_.
  14. 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?
  15. Si deseo actualizar mi PHP. ¿Donde puedo encontrar la línea ./configure que fue usada para compilar mi instalación actual de PHP?
  16. Cuando compilo PHP con la librería GD, también da errores raros de compilación o segfaults en la ejecución.
  17. 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.

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

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

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

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

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

Otra opción es la función crypt(), la cual tiene soporte para varios algoritmos hash. 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

tamas at microwizard dot com 22-Sep-2021 08:23
While I am reading the comments some old math lessons came into my mind and started thinking. Using constants in a mathematical algorythms do not change the complexity of the algorythm itself.

The reason of salting is to avoid using rainbow tables (sorry guys this is the only reason) because it speeds up (shortcuts) the "actual" processing power.
(((Longer stored hashes AND longer password increases complexity of cracking NOT adding salt ALONE.)))

PHP salting functions returns all the needed information for checking passwords, therfore this information should be treated as constant from farther point of view. It is also a target for rainbow tables (sure: for much-much larger ones).

What is the solution?
The solution is to store password hash and salt on different places.
The implementation is yours. Every two different places will be good enough.

Yes, it will make problems for hackers. He/she needs to understand your system. No speed up for password cracking will work for him/her without reimplementing your whole system.

This is my two cent.
swardx at gmail dot com 29-Jun-2016 09:36
A great read..

https://nakedsecurity.sophos.com/2013/11/20/serious-security-how-to-store-your-users-passwords-safely/

Serious Security: How to store your users’ passwords safely

In summary, here is our minimum recommendation for safe storage of your users’ passwords:

    Use a strong random number generator to create a salt of 16 bytes or longer.
    Feed the salt and the password into the PBKDF2 algorithm.
    Use HMAC-SHA-256 as the core hash inside PBKDF2.
    Perform 20,000 iterations or more. (June 2016.)
    Take 32 bytes (256 bits) of output from PBKDF2 as the final password hash.
    Store the iteration count, the salt and the final hash in your password database.
    Increase your iteration count regularly to keep up with faster cracking tools.

Whatever you do, don’t try to knit your own password storage algorithm.
alf dot henrik at ascdevel dot com 12-Mar-2014 07:58
I feel like I should comment some of the clams being posted as replies here.

For starters, speed IS an issue with MD5 in particular and also SHA1. I've written my own MD5 bruteforce application just for the fun of it, and using only my CPU I can easily check a hash against about 200mill. hash per second. The main reason for this speed is that you for most attempts can bypass 19 out of 64 steps in the algorithm. For longer input (> 16 characters) it won't apply, but I'm sure there's some ways around it.

If you search online you'll see people claiming to be able to check against billions of hashes per second using GPUs. I wouldn't be surprised if it's possible to reach 100 billion per second on a single computer alone these days, and it's only going to get worse. It would require a watt monster with 4 dual high-end GPUs or something, but still possible.

Here's why 100 billion per second is an issue:
Assume most passwords contain a selection of 96 characters. A password with 8 characters would then have 96^8 = 7,21389578984e+15 combinations.
With 100 billion per second it would then take 7,21389578984e+15 / 3600 = ~20 hours to figure out what it actually says. Keep in mind that you'll need to add the numbers for 1-7 characters as well. 20 hours is not a lot if you want to target a single user.

So on essence:
There's a reason why newer hash algorithms are specifically designed not to be easily implemented on GPUs.

Oh, and I can see there's someone mentioning MD5 and rainbow tables. If you read the numbers here, I hope you realize how incredibly stupid and useless rainbow tables have become in terms of MD5. Unless the input to MD5 is really huge, you're just not going to be able to compete with GPUs here. By the time a storage media is able to produce far beyond 3TB/s, the CPUs and GPUs will have reached much higher speeds.

As for SHA1, my belief is that it's about a third slower than MD5. I can't verify this myself, but it seems to be the case judging the numbers presented for MD5 and SHA1. The issue with speeds is basically very much the same here as well.

The moral here:
Please do as told. Don't every use MD5 and SHA1 for hasing passwords ever again. We all know passwords aren't going to be that long for most people, and that's a major disadvantage. Adding long salts will help for sure, but unless you want to add some hundred bytes of salt, there's going to be fast bruteforce applications out there ready to reverse engineer your passwords or your users' passwords.
fluffy at beesbuzz dot biz 11-Jun-2012 11:33
The security issue with simple hashing (md5 et al) isn't really the speed, so much as the fact that it's idempotent; two different people with the same password will have the same hash, and so if one person's hash is brute-forced, the other one will as well.  This facilitates rainbow attacks.  Simply slowing the hash down isn't a very useful tactic for improving security.  It doesn't matter how slow and cumbersome your hash algorithm is - as soon as someone has a weak password that's in a dictionary, EVERYONE with that weak password is vulnerable.

Also, hash algorithms such as md5 are for the purpose of generating a digest and checking if two things are probably the same as each other; they are not intended to be impossible to generate a collision for.  Even if an underlying password itself requires a lot of brute forcing to determine, that doesn't mean it will be impossible to find some other bit pattern that generates the same hash in a trivial amount of time.

As such: please, please, PLEASE only use salted hashes for password storage.  There is no reason to implement your own salted hash mechanism, either, as crypt() already does an excellent job of this.


PHP 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

There are no user contributed notes for this page.


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

There are no user contributed notes for this page.


Apéndices

  • Historia de PHP y Proyectos Relacionados
    • Historia de PHP
    • Historia de los proyectos relacionados con PHP
    • Libros sobre PHP
    • Publicaciones sobre PHP
  • Migrating from PHP 8.2.x to PHP 8.3.x
    • New Features
    • New Classes and Interfaces
    • New Functions
    • New Global Constants
    • Backward Incompatible Changes
    • Deprecated Features
    • Other Changes
    • Windows Support
  • Migrating from PHP 8.1.x to PHP 8.2.x
    • New Features
    • New Functions
    • Nuevas constantes globales
    • Backward Incompatible Changes
    • Características obsoletas
    • Other Changes
    • Windows Support
  • Migración de PHP 8.0.x a PHP 8.1.x
    • New Features
    • New Classes and Interfaces
    • New Functions
    • New Global Constants
    • Cambios incompatibles con versiones anteriores
    • Deprecated Features
    • Other Changes
  • Migración de PHP 7.4.x a PHP 8.0.x
    • Nuevas características
    • Cambios incompatibles hacia atrás
    • Características obsoletas
    • Otros cambios
  • Migración de PHP 7.3.x a PHP 7.4.x
    • Nuevas características
    • Nuevas clases e interfaces
    • Nuevas funciones
    • Nuevas constantes globales
    • Cambios incompatibles hacia atrás
    • Características obsoletas
    • Extensiones eliminadas
    • Other Changes
    • Soporte para Windows
  • 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

okhalelawrence at gmail dot com 07-Aug-2021 06:12
The Birth of PHP 6;

After Version 5: PHP received mixed reviews due to lacking native Unicode support at the core language level. In 2005, a project headed by Andrei Zmievski was initiated to bring native Unicode support throughout PHP, by embedding the International Components for Unicode (ICU) library, and representing text strings as UTF-16 internally. Since this would cause major changes both to the internals of the language and to user code, it was planned to release this as version 6.0 of the language, along with other major features then in development.

The Birth of PHP 7;

During 2014 and 2015, a new major PHP version was developed, PHP 7. The numbering of this version involved some debate among internal developers.While the PHP 6 Unicode experiment had never been released, several articles and book titles referenced the PHP 6 name, which might have caused confusion if a new release were to reuse the name. After a vote, the name PHP 7 was chosen.

The foundation of PHP 7 is a PHP branch that was originally dubbed PHP next generation (phpng). It was authored by Dmitry Stogov, Xinchen Hui and Nikita Popov, and aimed to optimize PHP performance by refactoring the Zend Engine while retaining near-complete language compatibility. By 14 July 2014, WordPress-based benchmarks, which served as the main benchmark suite for the phpng project, showed an almost 100% increase in performance. Changes from phpng make it easier to improve performance in future versions, as more compact data structures and other changes are seen as better suited for a successful migration to a just-in-time (JIT) compiler. Because of the significant changes, the reworked Zend Engine was called Zend Engine 3, succeeding Zend Engine 2 used in PHP 5.

Because of the major internal changes in phpng, it must receive a new major version number of PHP, rather than a minor PHP 5 release, according to PHP's release process. Major versions of PHP are allowed to break backward-compatibility of code and therefore PHP 7 presented an opportunity for other improvements beyond phpng that require backward-compatibility breaks.

The Birth of PHP 8;

PHP 8 was released on November 26, 2020. PHP 8 is a major version and has breaking changes from previous versions.New features and notable changes include:
Just-in-time compilation
Just-in-time compilation is supported in PHP 8.
PHP 8's JIT compiler can provide substantial performance improvements for some use cases.PHP developer Nikita Popov has stated that the performance improvements for most websites will be less substantial than the upgrade from PHP 5 to PHP 7.Performance improvements due to the addition of the JIT compiler are expected to be more substantial for mathematical-type operations than for common web-development use cases.Additionally, the JIT compiler provides future potential to move some code from C to PHP, due to the performance improvements for some use cases.
Addition of the match expression
Main article: PHP syntax and semantics § Match
PHP 8 introduced the match expression.The match expression is conceptually similar to a switch statement and is more compact for some use cases.Because match is an expression, its result can be caught into a variable or returned from a function.
Type changes and additions
PHP 8 introduced union types, a new static return type, and a new mixed type.
"Attributes", often referred to as "annotations" in other programming languages, were added in PHP 8, which allow metadata to be added to classes.
throw was changed from being a statement to being an expression. This allows exceptions to be thrown in places that were not previously possible. Sorce: wikipedia


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.


Migrating from PHP 8.2.x to PHP 8.3.x

Tabla de contenidos

  • New Features
  • New Classes and Interfaces
  • New Functions
  • New Global Constants
  • Backward Incompatible Changes
  • Deprecated Features
  • Other Changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

Véanse también las guías de migración para versiones de PHP 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x, 8.2.x.

User Contributed Notes

There are no user contributed notes for this page.


New Features

PHP Core

Readonly Amendments

Anonymous classes may now be marked as readonly.

Readonly properties can now be reinitialized during cloning.

Typed Class Constants

Class, interface, trait, and enum constants now support type declarations.

Closures created from magic methods

Closures created from magic methods can now accept named arguments.

The final modifier with a method from a trait

The final modifier may now be used when using a method from a trait.

Override Attribute

Added the #[\Override] attribute to check that a method exists in a parent class or implemented interface.

Fetch class constant dynamically syntax

Class constants can now be accessed dynamically using the C::{$name} syntax.

Static variable Initializers

Static variable initializers can now contain arbitrary expressions.

Fallback value syntax for ini variables

php.ini now supports fallback/default value syntax.

<?php
/*
On /path/to/user.ini contains the following settings:

listen = localhost:${DRUPAL_FPM_PORT:-9000}
*/

$user_ini = parse_ini_file('/path/to/user.ini');
echo $user_ini['listen']; // localhost:9000

CLI

It is now possible to lint multiple files.

DOM

Added properties DOMElement::$className and DOMElement::$id. These are not binary-safe at the moment because of underlying limitations of libxml2. This means that the property values will be cut off at a NUL byte.

Added properties DOMNode::$isConnected and DOMNameSpaceNode::$isConnected.

Added properties DOMNode::$parentElement and DOMNameSpaceNode::$parentElement.

FFI

It is now possible to assign FFI\CData to other FFI\CData. Meaning CData can now be assigned to structs and fields.

Opcache

opcache_get_status()['scripts'][n]['revalidate'] now contains a Unix timestamp of when the next revalidation of the scripts timestamp is due, dictated by the opcache.revalidate_freq INI directive.

POSIX

posix_getrlimit() now takes an optional $res parameter to allow fetching a single resource limit.

posix_isatty() now raises type warnings for integers following the usual ZPP semantics.

posix_ttyname() now raises type warnings for integers following the usual ZPP semantics and value warnings for invalid file descriptor integers.

Streams

Streams can now emit the STREAM_NOTIFY_COMPLETED notification. This was previously not implemented.

User Contributed Notes

There are no user contributed notes for this page.


New Classes and Interfaces

Date

  • DateError
  • DateObjectError
  • DateRangeError
  • DateException
  • DateInvalidOperationException
  • DateInvalidTimeZoneException
  • DateMalformedIntervalStringException
  • DateMalformedPeriodStringException
  • DateMalformedStringException

Random

  • Random\IntervalBoundary

User Contributed Notes

There are no user contributed notes for this page.


New Functions

Date

  • DatePeriod::createFromISO8601String()

DOM

  • DOMElement::getAttributeNames()
  • DOMElement::insertAdjacentElement()
  • DOMElement::insertAdjacentText()
  • DOMElement::toggleAttribute()
  • DOMNode::contains()
  • DOMNode::getRootNode()
  • DOMNode::isEqualNode()
  • DOMNameSpaceNode::contains()
  • DOMParentNode::replaceChildren()

Intl

  • IntlCalendar::setDate()
  • IntlCalendar::setDateTime()
  • IntlGregorianCalendar::createFromDate()
  • IntlGregorianCalendar::createFromDateTime()

JSON

  • json_validate()

LDAP

  • ldap_connect_wallet()
  • ldap_exop_sync()

MBString

  • mb_str_pad()

Posix

  • posix_sysconf()
  • posix_pathconf()
  • posix_fpathconf()
  • posix_eaccess()

PostgreSQL

  • pg_set_error_context_visibility() (libpq >= 9.6)

Random

  • Random\Randomizer::getBytesFromString()
  • Random\Randomizer::nextFloat()
  • Random\Randomizer::getFloat()

Reflection

  • ReflectionMethod::createFromMethodName()

Sockets

  • socket_atmark()

Standard

  • str_increment()
  • str_decrement()
  • stream_context_set_options()

Zip

  • ZipArchive::getArchiveFlag()

User Contributed Notes

There are no user contributed notes for this page.


New Global Constants

cURL

  • CURLINFO_CAPATH (libcurl >= 7.84.0)
  • CURLINFO_CAINFO (libcurl >= 7.84.0)
  • CURLOPT_MIME_OPTIONS (libcurl >= 7.81.0)
  • CURLMIMEOPT_FORMESCAPE (libcurl >= 7.81.0)
  • CURLOPT_WS_OPTIONS (libcurl >= 7.86.0)
  • CURLWS_RAW_MODE (libcurl >= 7.86.0)
  • CURLOPT_SSH_HOSTKEYFUNCTION (libcurl >= 7.84.0)
  • CURLOPT_PROTOCOLS_STR (libcurl >= 7.85.0)
  • CURLOPT_REDIR_PROTOCOLS_STR (libcurl >= 7.85.0)
  • CURLOPT_CA_CACHE_TIMEOUT (libcurl >= 7.87.0)
  • CURLOPT_QUICK_EXIT (libcurl >= 7.87.0)
  • CURLKHMATCH_OK (libcurl >= 7.19.6)
  • CURLKHMATCH_MISMATCH (libcurl >= 7.19.6)
  • CURLKHMATCH_MISSING (libcurl >= 7.19.6)
  • CURLKHMATCH_LAST (libcurl >= 7.19.6)

Intl

  • MIXED_NUMBERS (Spoofchecker)
  • HIDDEN_OVERLAY (Spoofchecker)

OpenSSL

  • OPENSSL_CMS_OLDMIMETYPE
  • PKCS7_NOOLDMIMETYPE

PCNTL

  • SIGINFO

PDO_ODBC

  • PDO_ODBC_TYPE

Posix

  • POSIX_SC_ARG_MAX
  • POSIX_SC_PAGESIZE
  • POSIX_SC_NPROCESSORS_CONF
  • POSIX_SC_NPROCESSORS_ONLN
  • POSIX_PC_LINK_MAX
  • POSIX_PC_MAX_CANON
  • POSIX_PC_MAX_INPUT
  • POSIX_PC_NAME_MAX
  • POSIX_PC_PATH_MAX
  • POSIX_PC_PIPE_BUF
  • POSIX_PC_CHOWN_RESTRICTED
  • POSIX_PC_NO_TRUNC
  • POSIX_PC_ALLOC_SIZE_MIN
  • POSIX_PC_SYMLINK_MAX

Sockets

The following socket options are now defined if they are supported:

  • SO_ATTACH_REUSEPORT_CBPF (Linux)
  • SO_DETACH_BPF (Linux)
  • SO_DETACH_FILTER (Linux)
  • TCP_QUICKACK (Linux)
  • IP_DONTFRAG (FreeBSD)
  • IP_MTU_DISCOVER (Linux)
  • IP_PMTUDISC_DO (Linux)
  • IP_PMTUDISC_DONT (Linux)
  • IP_PMTUDISC_WANT (Linux)
  • IP_PMTUDISC_PROBE (Linux)
  • IP_PMTUDISC_INTERFACE (Linux)
  • IP_PMTUDISC_OMIT (Linux)
  • AF_DIVERT (FreeBSD)
  • SOL_UDPLITE
  • UDPLITE_RECV_CSCOV
  • UDPLITE_SEND_CSCOV
  • SO_RERROR (NetBSD)
  • SO_ZEROIZE (OpenBSD)
  • SO_SPLICE (OpenBSD)
  • TCP_REPAIR (Linux)
  • SO_REUSEPORT_LB (FreeBSD)
  • IP_BIND_ADDRESS_NO_PORT (Linux)

Zip

  • ZipArchive::ER_DATA_LENGTH (libzip >= 1.10)
  • ZipArchive::ER_NOT_ALLOWED (libzip >= 1.10)
  • ZipArchive::AFL_RDONLY (libzip >= 1.10)
  • ZipArchive::AFL_IS_TORRENTZIP (libzip >= 1.10)
  • ZipArchive::AFL_WANT_TORRENTZIP (libzip >= 1.10)
  • ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE (libzip >= 1.10)
  • ZipArchive::FL_OPEN_FILE_NOW
  • ZipArchive::LENGTH_TO_END as default value for
ZipArchive::addFile() and
ZipArchive::replaceFile()
  • ZipArchive::LENGTH_UNCHECKED (libzip >= 1.10)

User Contributed Notes

There are no user contributed notes for this page.


Backward Incompatible Changes

PHP Core

Programs that were very close to overflowing the call stack

Programs that were very close to overflowing the call stack may now throw an Error when using more than zend.max_allowed_stack_size-zend.reserved_stack_size bytes of stack (fiber.stack_size-zend.reserved_stack_size for fibers).

Executing proc_get_status() multiple times

Executing proc_get_status() multiple times will now always return the right value on POSIX systems. Previously, only the first call of the function returned the right value. Executing proc_close() after proc_get_status() will now also return the right exit code. Previously this would return -1. Internally, this works by caching the result on POSIX systems. If the previous behaviour is required, it is possible to check the "cached" key in the array returned by proc_get_status() to check whether the result was cached.

Zend Max Execution Timers

Zend Max Execution Timers is now enabled by default for ZTS builds on Linux.

Uses of traits with static properties

Uses of traits with static properties will now redeclare static properties inherited from the parent class. This will create a separate static property storage for the current class. This is analogous to adding the static property to the class directly without traits.

Assigning a negative index to an empty array

Assigning a negative index $n to an empty array will now make sure that the next index is $n+1 instead of 0.

Class constant visibility variance check

Class constant visibility variance is now correctly checked when inherited from interfaces.

WeakMap entries whose key maps to itself

WeakMap entries whose key maps to itself (possibly transitively) may now be removed during cycle collection if the key is not reachable except by iterating over the WeakMap (reachability via iteration is considered weak). Previously, such entries would never be automatically removed.

Date

The DateTime extension has introduced Date extension specific exceptions and errors under the DateError and DateException hierarchies, instead of warnings and generic exceptions. This improves error handling, at the expense of having to check for errors and exceptions.

DOM

Calling DOMChildNode::after(),
DOMChildNode::before(),
DOMChildNode::replaceWith()
on a node that has no parent is now a no-op instead of a hierarchy
exception, which is the behaviour demanded by the DOM specification.

Using the DOMParentNode and DOMChildNode methods without a document now works instead of throwing a DOM_HIERARCHY_REQUEST_ERR DOMException. This is in line with the behaviour demanded by the DOM specification.

Calling DOMDocument::createAttributeNS() without specifying a prefix would incorrectly create a default namespace, placing the element inside the namespace instead of the attribute. This bug is now fixed.

DOMDocument::createAttributeNS() would previously incorrectly throw a DOM_NAMESPACE_ERRNAMESPACE_ERR DOMException when the prefix was already used for a different URI. It now correctly chooses a different prefix when there's a prefix name conflict.

New methods and properties were added to some DOM classes. If a userland class inherits from these classes and declare a method or property with the same name, the declarations must be compatible. Otherwise, a typical compile error about incompatible declarations will be thrown. See the list of new features and new functions for a list of the newly implemented methods and properties.

FFI

C functions that have a return type of void now return null instead of returning the following object object(FFI\CData:void) { }

Opcache

The opcache.consistency_checks INI directive was removed. This feature was broken with the tracing JIT, as well as with inheritance cache, and has been disabled without a way to enable it since PHP 8.1.18 and PHP 8.2.5. Both the tracing JIT and inheritance cache may modify shm after the script has been persisted by invalidating its checksum. The attempted fix skipped over the modifiable pointers but was rejected due to complexity. For this reason, it was decided to remove the feature instead.

Phar

The type of Phar class constants are now declared.

Standard

The range() function has had various changes:

  • A TypeError is now thrown when passing objects, resources, or arrays as the boundary inputs.
  • A more descriptive ValueError is thrown when passing 0 for $step.
  • A ValueError is now thrown when using a negative $step for increasing ranges.
  • If $step is a float that can be interpreted as an int, it is now done so.
  • A ValueError is now thrown if any argument is infinity or NAN.
  • An E_WARNING is now emitted if $start or $end is the empty string. The value continues to be cast to the value 0.
  • An E_WARNING is now emitted if $start or $end has more than one byte, only if it is a non-numeric string.
  • An E_WARNING is now emitted if $start or $end is cast to an integer because the other boundary input is a number. (e.g. range(5, 'z');).
  • An E_WARNING is now emitted if $step is a float when trying to generate a range of characters, except if both boundary inputs are numeric strings (e.g. range('5', '9', 0.5); does not produce a warning).
  • range() now produce a list of characters if one of the boundary inputs is a string digit instead of casting the other input to int (e.g. range('9', 'A');).
<?php
range('9', 'A'); // ["9", ":", ";", "<", "=", ">", "?", "@", "A"], as of PHP 8.3.0
range('9', 'A'); // [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], prior to PHP 8.3.0
?>

The file() flags error check now catches all invalid flags. Notably FILE_APPEND was previously silently accepted.

SNMP

The type of SNMP class constants are now declared.

User Contributed Notes

There are no user contributed notes for this page.


Deprecated Features

PHP Core

Saner Increment/Decrement operators

Using the increment operator (++) on empty, non-numeric, or non-alphanumeric strings is now deprecated. Moreover, incrementing non-numeric strings is soft deprecated. That means no E_DEPRECATED diagnostic is emitted, but this feature should not be used when producing new code. The new str_increment() function should be used instead.

Using the decrement operator (--) on empty or non-numeric strings is now deprecated.

get_class()/get_parent_class() call without arguments

Calling get_class() and get_parent_class() without arguments is now deprecated.

DBA

Calling dba_fetch() with $dba as the 3rd argument is now deprecated.

FFI

Calling FFI::cast(), FFI::new(), and FFI::type() statically is now deprecated.

Intl

The U_MULTIPLE_DECIMAL_SEP*E*RATORS constant had been deprecated, using the U_MULTIPLE_DECIMAL_SEP*A*RATORS constant instead is recommended.

The NumberFormatter::TYPE_CURRENCY constant has been deprecated.

LDAP

Calling ldap_connect() with separate $hostname and $port is deprecated.

MBString

Passing a negative $width to mb_strimwidth() is now deprecated.

Phar

Calling Phar::setStub() with a resource and a $length is now deprecated. Such calls should be replaced by: $phar->setStub(stream_get_contents($resource));

Random

The MT_RAND_PHP Mt19937 variant is deprecated.

Reflection

Calling ReflectionProperty::setValue() with only one parameter is deprecated. To set static properties, pass null as the first parameter.

Standard

The assert_options() function is now deprecated.

The ASSERT_ACTIVE, ASSERT_BAIL, ASSERT_CALLBACK, ASSERT_EXCEPTION, and ASSERT_WARNING constants have been deprecated.

The assert.* INI settings have been deprecated. See the Changes to INI File Handling page for further details.

SQLite3

Using exceptions is now preferred, warnings will be removed in the future. Calling SQLite3::enableExceptions(false) will trigger a deprecation warning in this version.

Zip

The ZipArchive::FL_RECOMPRESS constant is deprecated and will be removed in a future version of libzip.

User Contributed Notes

There are no user contributed notes for this page.


Other Changes

Core changes

FFI

FFI::load() is now allowed during preloading when opcache.preload_user is the current system user. Previously, calling FFI::load() was not possible during preloading if the opcache.preload_user directive was set.

FPM

FPM CLI test now fails if the socket path is longer than supported by OS.

Opcache

In the CLI and phpdbg SAPIs, preloading does not require the opcache.preload_user directive to be set anymore when running as root. In other SAPIs, this directive is required when running as root because preloading is done before the SAPI switches to an unprivileged user.

Streams

Blocking fread() on socket connection returns immediately if there are any buffered data instead of waiting for more data.

Memory stream no longer fails if seek offset is past the end. Instead the memory is increase on the next write and date between the old end and offset is filled with zero bytes in the same way how it works for files.

stat() access operations like file_exists() and similar will now use real path instead of the actual stream path. This is consistent with stream opening.

Changes in SAPI Modules

CLI

The STDOUT, STDERR and STDIN streams are no longer closed on resource destruction which is mostly when the CLI finishes. It is however still possible to explicitly close those streams using fclose() and similar.

Changed Functions

Core

gc_status() has added the following 8 fields:

  • "running" => bool
  • "protected" => bool
  • "full" => bool
  • "buffer_size" => int
  • "application_time" => float: Total application time, in seconds (including collector_time)
  • "collector_time" => float: Time spent collecting cycles, in seconds (including destructor_time and free_time)
  • "destructor_time" => float: Time spent executing destructors during cycle collection, in seconds
  • "free_time" => float: Time spent freeing values during cycle collection, in seconds

class_alias() now supports creating an alias of an internal class.

Setting open_basedir at runtime using ini_set('open_basedir', ...); no longer accepts paths containing the parent directory (..). Previously, only paths starting with .. were disallowed. This could easily be circumvented by prepending ./ to the path.

User exception handlers now catch exceptions during shutdown.

The resultant HTML of highlight_string() and highlight_file() has changed. Whitespace between outer HTML tags is removed. Newlines and spaces are no longer converted to HTML entities. The whole HTML is now wrapped in a <pre> tag. The outer <span> tag has been merged with the <code> tag.

Calendar

easter_date() now supports years from 1970 to 2,000,000,000 on 64-bit systems, previously it only supported years in the range from 1970 to 2037.

Curl

curl_getinfo() now supports two new constants: CURLINFO_CAPATH and CURLINFO_CAINFO. If option is null, the following two additional keys are present: "capath" and "cainfo".

DOM

Changed DOMCharacterData::appendData() tentative return type to true.

DOMDocument::loadHTML(), DOMDocument::loadHTMLFile(), and DOMDocument::loadXML() now have a tentative return type of bool. Previously, this was documented as having a return type of DOMDocument|bool, but, as of PHP 8.0.0, DOMDocument cannot be returned as it is no longer statically callable.

Gd

The signature of imagerotate() has changed. The $ignore_transparent parameter has been removed, as it was ignored since PHP 5.5.0.

Intl

datefmt_set_timezone() (and its alias IntlDateformatter::setTimeZone()) now returns true on success, previously null was returned.

IntlBreakiterator::setText() now returns false on failure, previously null was returned. It now returns true on success, previously null was returned.

IntlChar::enumCharNames() is now returning a boolean. Previously it returned null on success and false on failure.

IntlDateFormatter::__construct() throws an U_ILLEGAL_ARGUMENT_ERROR exception when an invalid locale had been set.

MBString

mb_strtolower() and mb_convert_case() implement conditional casing rules for the Greek letter sigma. For mb_convert_case(), conditional casing only applies to MB_CASE_LOWER and MB_CASE_TITLE modes, not to MB_CASE_LOWER_SIMPLE and MB_CASE_TITLE_SIMPLE.

mb_decode_mimeheader() interprets underscores in QPrint-encoded MIME encoded words as required by RFC 2047; they are converted to spaces. Underscores must be encoded as "=5F" in such MIME encoded words.

In rare cases, mb_encode_mimeheader() will transfer-encode its input string where it would pass it through as raw ASCII in PHP 8.2.

mb_encode_mimeheader() no longer drops NUL (zero) bytes when QPrint-encoding the input string. This previously caused strings in certain text encodings, especially UTF-16 and UTF-32, to be corrupted by mb_encode_mimeheader.

mb_detect_encoding()'s "non-strict" mode now behaves as described in the documentation. Previously, it would return false if the same byte (for example, the first byte) of the input string was invalid in all candidate encodings. More generally, it would eliminate candidate encodings from consideration when an invalid byte was seen, and if the same input byte eliminated all remaining encodings still under consideration, it would return false. On the other hand, if all candidate encodings but one were eliminated from consideration, it would return the last remaining one without regard for how many encoding errors might be encountered later in the string. This is different from the behavior described in the documentation, which says: "If strict is set to false, the closest matching encoding will be returned."

mysqli

mysqli_fetch_object() now raises a ValueError instead of an Exception when the $constructor_args argument is non empty with the class not having constructor.

mysqli_poll() now raises a ValueError when neither the $read nor the $error arguments are passed.

mysqli_field_seek() and mysqli_result::field_seek() now specify the return type as true instead of bool.

ODBC

odbc_autocommit() now accepts null for the $enable parameter. Passing null has the same behaviour as passing only 1 parameter, namely indicating if the autocommit feature is enabled or not.

PGSQL

pg_fetch_object() now raises a ValueError instead of an Exception when the $constructor_args argument is non empty with the class not having constructor.

pg_insert() now raises a ValueError instead of a E_WARNING when the table specified is invalid.

pg_insert() and pg_convert() raises a ValueError or a TypeError instead of a E_WARNING when the value/type of a field does not match properly with a PostgreSQL's type.

The $row parameter of
pg_fetch_result(),
pg_field_prtlen(), and
pg_field_is_null() is now nullable.

Random

Changed mt_srand() and srand() to not check the number of arguments to determine whether a random seed should be used. Passing null will generate a random seed, 0 will use zero as the seed. The functions are now consistent with Random\Engine\Mt19937::__construct().

Reflection

Return type of ReflectionClass::getStaticProperties() is no longer nullable.

Standard

E_NOTICEs emitted by unserialize() have been promoted to E_WARNING.

unserialize() now emits a new E_WARNING if the input contains unconsumed bytes.

array_pad() is now only limited by the maximum number of elements an array can have. Before, it was only possible to add at most 1048576 elements at a time.

strtok() raises an E_WARNING in the case token is not provided when starting tokenization.

password_hash() will now chain the underlying Random\RandomException as the ValueError's $previous Exception when salt generation fails.

If using an array as the $command for proc_open(), it must now have at least one non empty element. Otherwise a ValueError is thrown.

proc_open() returns false if $command array is invalid command instead of resource object that produces warning later. This was already the case for Windows but it is now also the case if posix_spawn implementation is in use (most Linux, BSD and MacOS platforms). There are still some old platforms where this behavior is not changed as posix_spawn is not supported there.

array_sum() and array_product() now warn when values in the array cannot be converted to int/float. Previously arrays and objects where ignored whilst every other value was cast to int. Moreover, objects that define a numeric cast (e.g. GMP) are now casted instead of ignored.

The $decimal of number_format() now properly handles negative integers. Rounding with a negative value for $decimal means that $num is rounded to $decimals significant digits before the decimal point. Previously negative $decimals were silently ignored and the number got rounded to zero decimal places.

A new $before_needle argument has been added to strrchr(). It behaves like its counterpart in the strstr() or stristr() functions.

str_getcsv() and fgetcsv() now return an empty string instead of a string with a single null byte for the last field which only contains an unterminated enclosure.

Other Changes to Extensions

Core

Using the increment/decrement operators (++/--) on values of type bool now emit warnings. This is because it currently has no effect, but will behave like $bool += 1 in the future.

Using the decrement operator (--) on values of type null now emit warnings. This is because it currently has no effect, but will behave like $null -= 1 in the future.

Internal objects that implement an _IS_NUMBER cast but not a do_operator handler that overrides addition and subtraction now can be incremented and decrement as if one would do $o += 1 or $o -= 1

DOM

The DOM lifetime mechanism has been reworked such that implicitly removed nodes can still be fetched. Previously this resulted in an exception.

SQLite3

The SQLite3 class now throws SQLite3Exception (extends Exception) instead of Exception.

The SQLite error code is now passed in the exception error code instead of being included in the error message.

Changes to INI File Handling

  • The assert.* INI settings have been deprecated. This comprises the following INI settings:

    • assert.active
    • assert.bail
    • assert.callback
    • assert.exception
    • assert.warning
    If the value of the setting is equal to the default value, no deprecation notice is emitted. The zend.assertions INI setting should be used instead.

  • zend.max_allowed_stack_size is a new INI directive to set the maximum allowed stack size. Possible values are 0 (detect the process or thread maximum stack size), -1 (no limit), or a positive number of bytes. The default is 0. When it is not possible to detect the process or thread maximum stack size, a known system default is used. Setting this value too high has the same effect as disabling the stack size limit. Fibers use fiber.stack_size as maximum allowed stack size. An Error is thrown when the process call stack exceeds zend.max_allowed_stack_size-zend.reserved_stack_size bytes, to prevent stack-overflow-induced segmentation faults, with the goal of making debugging easier. The stack size increases during uncontrolled recursions involving internal functions or the magic methods __toString(), __clone(), __sleep(), __destruct(). This is not related to stack buffer overflows, and is not a security feature.

  • zend.reserved_stack_size is a new INI directive to set the reserved stack size, in bytes. This is subtracted from the max allowed stack size, as a buffer, when checking the stack size.

Performance

DOM

Looping over a DOMNodeList now uses caching. Therefore requesting items no longer takes quadratic time by default.

Getting text content from nodes now avoids an allocation, resulting in a performance gain.

DOMChildNode::remove() now runs in O(1) performance.

Standard

The file() flags error check is now about 7% faster.

SPL

RecursiveDirectoryIterator now performs less I/O when looping over a directory.

User Contributed Notes

There are no user contributed notes for this page.


Windows Support

Core

Minimum supported Windows version has been bumped to Windows 8 or Windows Server 2012.

User Contributed Notes

There are no user contributed notes for this page.


Migrating from PHP 8.1.x to PHP 8.2.x

Tabla de contenidos

  • New Features
  • New Functions
  • Nuevas constantes globales
  • Backward Incompatible Changes
  • Características obsoletas
  • Other Changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

Véanse también las guías de migración para versiones de PHP 7.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x, 8.1.x.

User Contributed Notes

Anonymous 03-Mar-2023 01:02
that’s incredible version of PHP,The performance is really nicer than older version.


New Features

PHP Core

SensitiveParameter Attribute

Added the #[\SensitiveParameter] attribute to redact sensitive data in backtraces.

error_log_mode INI directive

The error_log_mode INI directive has been added which allows setting the permissions for the error log file.

Enumerations properties in constant expressions

It is now possible to fetch properties of Enumerations in constant expressions.

Type System Improvements

It is now possible to use null and false as stand-alone types.

The true type has been added.

It is now possible to combine intersection and union types. The type needs to be written in DNF.

Constants in Traits

It is now possible to define constants in traits.

Readonly Classes

Support for readonly on classes has been added.

cURL

Added the CURLINFO_EFFECTIVE_METHOD option, which returns the effective HTTP method in the return value of curl_getinfo().

Exposed multiple new constants from libcurl 7.62 to 7.80.

Added the curl_upkeep() function to perform any connection upkeep checks.

DBA

The LMDB Driver now accepts the DBA_LMDB_USE_SUB_DIR or DBA_LMDB_NO_SUB_DIR flags to determine if it should create a subdirectory or not when creating a database file.

OCI8

Added the oci8.prefetch_lob_size INI directive and oci_set_prefetch_lob() function to tune LOB query performance by reducing the number of round-trips between PHP and Oracle Databases when fetching LOBS. This is usable with Oracle Database 12.2 or later.

OpenSSL

Added AEAD support for the chacha20-poly1305 algorithm.

ODBC

Added the odbc_connection_string_is_quoted(), odbc_connection_string_should_quote(), and odbc_connection_string_quote() functions. These are primarily used behind the scenes in the ODBC and PDO_ODBC extensions, but are exposed to userland for easier unit testing, and for user applications and libraries to perform quoting themselves.

PCRE

Added support for the n (NO_AUTO_CAPTURE) modifier, which makes simple (xyz) groups non-capturing. Only named groups like (?<name>xyz) are capturing. This only affects which groups are capturing, it is still possible to use numbered subpattern references, and the matches array will still contain numbered results.

Random

This is a new extension which organises and consolidates existing implementations related to random number generators. New and better RNGs are available with scope issues eliminated.

User Contributed Notes

There are no user contributed notes for this page.


New Functions

cURL

  • curl_upkeep()

IMAP

  • imap_is_open() (as of PHP 8.2.1)

MySQLi

  • mysqli_execute_query()

ODBC

  • odbc_connection_string_is_quoted()
  • odbc_connection_string_should_quote()
  • odbc_connection_string_quote()

OpenSSL

  • openssl_cipher_key_length()

Reflection

  • ReflectionFunction::isAnonymous()
  • ReflectionMethod::hasPrototype()

Sodium

XChaCha20

  • sodium_crypto_stream_xchacha20_xor_ic()

Standard

  • memory_reset_peak_usage()
  • ini_parse_quantity()

XML

  • libxml_get_external_entity_loader()

User Contributed Notes

There are no user contributed notes for this page.


Nuevas constantes globales

COM

  • DISP_E_PARAMNOTFOUND
  • LOCALE_NEUTRAL

cURL

  • CURLALTSVC_H1 (libcurl >= 7.64.1)
  • CURLALTSVC_H2 (libcurl >= 7.64.1)
  • CURLALTSVC_H3 (libcurl >= 7.64.1)
  • CURLALTSVC_READONLYFILE (libcurl >= 7.64.1)
  • CURLAUTH_AWS_SIGV4 (libcurl >= 7.75.0)
  • CURLE_PROXY (libcurl >= 7.73.0)
  • CURLFTPMETHOD_DEFAULT
  • CURLHSTS_ENABLE (libcurl >= 7.74.0)
  • CURLHSTS_READONLYFILE (libcurl >= 7.74.0)
  • CURLINFO_PROXY_ERROR (libcurl >= 7.73.0)
  • CURLINFO_REFERER (libcurl >= 7.76.0)
  • CURLINFO_RETRY_AFTER (libcurl >= 7.66.0)
  • CURLMOPT_MAX_CONCURRENT_STREAMS (libcurl >= 7.67.0)
  • CURLOPT_ALTSVC_CTRL (libcurl >= 7.64.1)
  • CURLOPT_ALTSVC (libcurl >= 7.64.1)
  • CURLOPT_AWS_SIGV4 (libcurl >= 7.75.0)
  • CURLOPT_CAINFO_BLOB (libcurl >= 7.77.0)
  • CURLOPT_DOH_SSL_VERIFYHOST (libcurl >= 7.76.0)
  • CURLOPT_DOH_SSL_VERIFYPEER (libcurl >= 7.76.0)
  • CURLOPT_DOH_SSL_VERIFYSTATUS (libcurl >= 7.76.0)
  • CURLOPT_HSTS_CTRL (libcurl >= 7.74.0)
  • CURLOPT_HSTS (libcurl >= 7.74.0)
  • CURLOPT_MAIL_RCPT_ALLLOWFAILS (libcurl >= 7.69.0)
  • CURLOPT_MAXAGE_CONN (libcurl >= 7.65.0)
  • CURLOPT_MAXFILESIZE_LARGE
  • CURLOPT_MAXLIFETIME_CONN (libcurl >= 7.80.0)
  • CURLOPT_PROXY_CAINFO_BLOB (libcurl >= 7.77.0)
  • CURLOPT_SASL_AUTHZID (libcurl >= 7.66.0)
  • CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 (libcurl >= 7.80.0)
  • CURLOPT_SSL_EC_CURVES (libcurl >= 7.73.0)
  • CURLOPT_UPKEEP_INTERVAL_MS (libcurl >= 7.62.0)
  • CURLOPT_UPLOAD_BUFFERSIZE (libcurl >= 7.62.0)
  • CURLOPT_XFERINFOFUNCTION (libcurl >= 7.32.0)
  • CURLPROTO_MQTT (libcurl >= 7.71.0)
  • CURLPX_BAD_ADDRESS_TYPE (libcurl >= 7.73.0)
  • CURLPX_BAD_VERSION (libcurl >= 7.73.0)
  • CURLPX_CLOSED (libcurl >= 7.73.0)
  • CURLPX_GSSAPI (libcurl >= 7.73.0)
  • CURLPX_GSSAPI_PERMSG (libcurl >= 7.73.0)
  • CURLPX_GSSAPI_PROTECTION (libcurl >= 7.73.0)
  • CURLPX_IDENTD_DIFFER (libcurl >= 7.73.0)
  • CURLPX_IDENTD (libcurl >= 7.73.0)
  • CURLPX_LONG_HOSTNAME (libcurl >= 7.73.0)
  • CURLPX_LONG_PASSWD (libcurl >= 7.73.0)
  • CURLPX_LONG_USER (libcurl >= 7.73.0)
  • CURLPX_NO_AUTH (libcurl >= 7.73.0)
  • CURLPX_OK (libcurl >= 7.73.0)
  • CURLPX_RECV_ADDRESS (libcurl >= 7.73.0)
  • CURLPX_RECV_AUTH (libcurl >= 7.73.0)
  • CURLPX_RECV_CONNECT (libcurl >= 7.73.0)
  • CURLPX_RECV_REQACK (libcurl >= 7.73.0)
  • CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED (libcurl >= 7.73.0)
  • CURLPX_REPLY_COMMAND_NOT_SUPPORTED (libcurl >= 7.73.0)
  • CURLPX_REPLY_CONNECTION_REFUSED (libcurl >= 7.73.0)
  • CURLPX_REPLY_GENERAL_SERVER_FAILURE (libcurl >= 7.73.0)
  • CURLPX_REPLY_HOST_UNREACHABLE (libcurl >= 7.73.0)
  • CURLPX_REPLY_NETWORK_UNREACHABLE (libcurl >= 7.73.0)
  • CURLPX_REPLY_NOT_ALLOWED (libcurl >= 7.73.0)
  • CURLPX_REPLY_TTL_EXPIRED (libcurl >= 7.73.0)
  • CURLPX_REPLY_UNASSIGNED (libcurl >= 7.73.0)
  • CURLPX_REQUEST_FAILED (libcurl >= 7.73.0)
  • CURLPX_RESOLVE_HOST (libcurl >= 7.73.0)
  • CURLPX_SEND_AUTH (libcurl >= 7.73.0)
  • CURLPX_SEND_CONNECT (libcurl >= 7.73.0)
  • CURLPX_SEND_REQUEST (libcurl >= 7.73.0)
  • CURLPX_UNKNOWN_FAIL (libcurl >= 7.73.0)
  • CURLPX_UNKNOWN_MODE (libcurl >= 7.73.0)
  • CURLPX_USER_REJECTED (libcurl >= 7.73.0)
  • CURLSSLOPT_AUTO_CLIENT_CERT (libcurl >= 7.77.0)
  • CURLSSLOPT_NATIVE_CA (libcurl >= 7.71.0)
  • CURLSSLOPT_NO_PARTIALCHAIN (libcurl >= 7.68.0)
  • CURLSSLOPT_REVOKE_BEST_EFFORT (libcurl >= 7.70.0)
  • CURL_VERSION_GSASL (libcurl >= 7.76.0)
  • CURL_VERSION_HSTS (libcurl >= 7.74.0)
  • CURL_VERSION_HTTP3 (libcurl >= 7.66.0)
  • CURL_VERSION_UNICODE (libcurl >= 7.72.0)
  • CURL_VERSION_ZSTD (libcurl >= 7.72.0)

DBA

  • DBA_LMDB_USE_SUB_DIR
  • DBA_LMDB_NO_SUB_DIR

Filter

  • FILTER_FLAG_GLOBAL_RANGE

Sockets

Ahora se definen las siguientes opciones de socket si son compatibles:

  • SO_INCOMING_CPU
  • SO_MEMINFO
  • SO_RTABLE (OpenBSD)
  • TCP_KEEPALIVE (MacOS)
  • TCP_KEEPCNT (Linux, others)
  • TCP_KEEPIDLE (Linux, others)
  • TCP_KEEPINTVL (Linux, others)
  • TCP_NOTSENT_LOWAT
  • LOCAL_CREDS_PERSISTENT (FreeBSD)
  • SCM_CREDS2 (FreeBSD)
  • LOCAL_CREDS (NetBSD)
  • SO_BPF_EXTENSIONS
  • SO_SETFIB
  • TCP_CONGESTION (Linux, FreeBSD)
  • SO_ZEROCOPY (Linux)
  • MSG_ZEROCOPY (Linux)

User Contributed Notes

There are no user contributed notes for this page.


Backward Incompatible Changes

Date

DateTime::createFromImmutable() now has a tentative return type of static, previously it was DateTime.

DateTimeImmutable::createFromMutable() now has a tentative return type of static, previously it was DateTimeImmutable.

number symbols in relative formats no longer accept multiple signs, e.g. +-2.

ODBC

The ODBC extension now escapes the username and password for the case when both a connection string and username/password are passed, and the string must be appended to. Before, user values containing values needing escaping could have created a malformed connection string, or injected values from user-provided data. The escaping rules should be identical to the .NET BCL DbConnectionOptions behaviour.

PDO_ODBC

The PDO_ODBC extension also escapes the username and password when a connection string is passed. See the change to the ODBC extension for further details.

Standard

glob() now returns an empty array if all paths are restricted by open_basedir. Previously it returned false. Moreover, a warning is now emitted even if only some paths are restricted by open_basedir.

FilesystemIterator::__construct(): prior to PHP 8.2.0, FilesystemIterator::SKIP_DOTS constant was always set and couldn't be disabled. In order to maintain the previous behaviour the constant must be explicitly set when using the flags parameter. The default value from flags parameter has not been modified.

strtolower(),
strtoupper(),
stristr(),
stripos(),
strripos(),
lcfirst(),
ucfirst(),
ucwords(),
and str_ireplace() are no longer locale-sensitive.
They now perform ASCII case conversion, as if the locale were "C".
Localized versions of these functions are available in the MBString extension.
Moreover, array_change_key_case(), and sorting with
SORT_FLAG_CASE now also use ASCII case conversion.

str_split() returns an empty array for an empty string now. Previously it returned an array with a single empty string entry. mb_str_split() is not affected by this change as it was already behaving like that.

ksort() and krsort() now do numeric string comparison under SORT_REGULAR using the standard PHP 8 rules now.

var_export() no longer omits the leading backslash for exported classes, i.e. these are now fully qualified.

Standard PHP Library (SPL)

The following methods now enforce their signature:

  • SplFileInfo::_bad_state_ex()
  • SplFileObject::getCsvControl()
  • SplFileObject::fflush()
  • SplFileObject::ftell()
  • SplFileObject::fgetc()
  • SplFileObject::fpassthru()

SplFileObject::hasChildren() now has a tentative return type of false, previously it was bool.

SplFileObject::getChildren() now has a tentative return type of null, previously it was ?RecursiveIterator.

GlobIterator now returns an empty array if all paths are restricted by open_basedir. Previously it returned false. Moreover, a warning is now emitted even if only some paths are restricted by open_basedir.

User Contributed Notes

There are no user contributed notes for this page.


Características obsoletas

Núcleo PHP

Uso de las propiedades dinámicas

La creación de propiedades dinámicas está obsoleta, a menos que la clase opte por utilizar el atributo #[\AllowDynamicProperties]. La clase stdClass permite propiedades dinámicas. El uso de los métodos mágicos como __get()/__set() no se ven afectados por este cambio. Un aviso de obsolescencia de uso de propiedades dinámicas puede ser abordado por:

  • Declaring the property (preferred).
  • Adding the #[\AllowDynamicProperties] attribute to the class (which also applies to all child classes).
  • Using a WeakMap if additional data needs to be associated with an object which one does not own.

Relative callables

Callables that are not accepted by the $callable() syntax (but are accepted by call_user_func()) are deprecated. In particular:

  • "self::method"
  • "parent::method"
  • "static::method"
  • ["self", "method"]
  • ["parent", "method"]
  • ["static", "method"]
  • ["Foo", "Bar::method"]
  • [new Foo, "Bar::method"]
This does not affect normal method callables such as "A::method" or ["A", "method"].

"${var}" and "${expr}" style interpolation

The "${var}" and "${expr}" style of string interpolation is deprecated. Use "$var"/"{$var}" and "{${expr}}", respectively.

MBString

Usage of the QPrint, Base64, Uuencode, and HTML-ENTITIES 'text encodings' is deprecated for all MBString functions. Unlike all the other text encodings supported by MBString, these do not encode a sequence of Unicode codepoints, but rather a sequence of raw bytes. It is not clear what the correct return values for most MBString functions should be when one of these non-encodings is specified. Moreover, PHP has separate, built-in implementations of all of them; for example, UUencoded data can be handled using convert_uuencode()/convert_uudecode().

SPL

The internal SplFileInfo::_bad_state_ex() method has been deprecated.

Standard

utf8_encode() and utf8_decode() have been deprecated.

User Contributed Notes

tabflo at gmx dot at 13-Jul-2023 01:43
a have a baseclass for all databasemodels and handle my dynamic property setter and getter this way:

    public array $dynamicProperties = [];

    public function __set(string $name, mixed $value) {
        if(property_exists($this, $name))
            $this->{$name} = $value;
        else
            $this->dynamicProperties[$name] = $value;
    }

    public function __get(string $name) {
        if(property_exists($this, $name))
            return $this->$name;
        else
            return $this->dynamicProperties[$name];
    }

just put the content into a class and extend from it. enjoy :)


Other Changes

Core changes

The iterable type is now a built-in compile time alias for array|Traversable. Error messages relating to iterable will therefore now use array|Traversable. Type Reflection is preserved for single iterable (and ?iterable) to produce a ReflectionNamedType with name iterable, however usage of iterable in union types will be converted to array|Traversable.

The date format of sent cookies is now 'D, d M Y H:i:s \G\M\T'; previously it was 'D, d-M-Y H:i:s T'.

Changes in SAPI Modules

CLI

The STDOUT, STDERR and STDIN streams are no longer closed on resource destruction which is mostly when the CLI finishes. It is however still possible to explicitly close those streams using fclose() and similar.

Changed Functions

Core

The strcmp(), strcasecmp(),
strncmp(), strncasecmp(), and
substr_compare() functions, using binary safe string
comparison now return -1, 0 and 1.

DBA

dba_open() and dba_popen() now have the following enforced signature:

dba_open(
string $path,
string $mode,
?string $handler = null,
int $permission = 0644,
int $map_size = 0,
?int $flags = null
): resource|false

dba_fetch()'s optional skip argument is now at the end in line with PHP userland semantics. Its signature is now:

dba_fetch(string|array $key, resource $handle, int $skip): string|false
The overloaded signature:
dba_fetch(string|array $key, int $skip, resource $handle): string|false
is still accepted, but it is recommended to use the new standard variant.

Random

random_bytes() and random_int() now throw a \Random\RandomException on CSPRNG failures. Previously a plain \Exception was thrown instead.

SPL

The iterator parameter of iterator_to_array() and iterator_count() is widened to iterable from Iterator, allowing arrays to be passed.

Other Changes to Extensions

Date

The properties of DatePeriod are now properly declared.

Intl

Instances of IntlBreakIterator, IntlRuleBasedBreakIterator, IntlCodePointBreakIterator, IntlPartsIterator, IntlCalendar, Collator, IntlIterator, UConverter, IntlDateFormatter, IntlDatePatternGenerator, MessageFormatter, ResourceBundle, Spoofchecker, IntlTimeZone, and Transliterator are no longer serializable. Previously, they could be serialized, but unserialization yielded unusable objects or failed.

MySQLi

The support for libmysql has been removed and it is no longer possible to compile mysqli with libmysql. From now on, the mysqli extension can be compiled only with mysqlnd. All libmysql features unavailable in mysqlnd have been removed:

  • The reconnect property of mysqli_driver
  • The mysqli.reconnect INI directive
  • The MYSQLI_IS_MARIADB constant has been deprecated

OCI8

The minimum Oracle Client library version required is now 11.2.

PCRE

NUL characters (\0) in pattern strings are now supported.

Session

Trying to change the session.cookie_samesite INI directive while the session is active or output has already been sent will now fail and emit a warning. This aligns the behaviour with all other session INI settings.

SQLite3

sqlite3.defensive is now PHP_INI_USER.

Standard

getimagesize() now reports the actual image dimensions, bits and channels of AVIF images. Previously, the dimensions have been reported as 0x0, and bits and channels have not been reported at all.

Tidy

The properties of the tidy class are now properly declared. And those of the tidyNode class are now properly declared as readonly.

Zip

The Zip extension has been updated to version 1.20.0, which adds the following methods:

  • ZipArchive::clearError()
  • ZipArchive::getStreamName()
  • ZipArchive::getStreamIndex()

Changes to INI File Handling

Support for binary (0b/0B) and octal (0o/0O) prefixes has been added to integer INI settings. Integer INI settings that start with a zero (0) continue to be interpreted as an octal integer.

Parsing of some ill-formatted values will now trigger a warning when this was silently ignored before. For backwards compatibility, interpretation of these values has not changed. This affects the following settings:

  • bcmath.scale
  • com.code_page
  • default_socket_timeout
  • fiber.stack_size
  • hard_timeout
  • intl.error_level
  • ldap.max_links
  • max_input_nesting_level
  • max_input_vars
  • mbstring.regex_retry_limit
  • mbstring.regex_stack_limit
  • mysqli.allow_local_infile
  • mysqli.allow_persistent
  • mysqli.default_port
  • mysqli.max_links
  • mysqli.max_persistent
  • mysqli.rollback_on_cached_plink
  • mysqlnd.log_mask
  • mysqlnd.mempool_default_size
  • mysqlnd.net_read_buffer_size
  • mysqlnd.net_read_timeout
  • oci8.default_prefetch
  • oci8.max_persistent
  • oci8.persistent_timeout
  • oci8.ping_interval
  • oci8.prefetch_lob_size
  • oci8.privileged_connect
  • oci8.statement_cache_size
  • odbc.allow_persistent
  • odbc.check_persistent
  • odbc.max_persistent
  • odbc.max_links
  • odbc.defaultbinmode
  • odbc.default_cursortype
  • odbc.defaultlrl
  • opcache.consistency_checks
  • opcache.file_update_protection
  • opcache.force_restart_timeout
  • opcache.interned_strings_buffer
  • opcache.jit_bisect_limit
  • opcache.jit_blacklist_root_trace
  • opcache.jit_blacklist_side_trace
  • opcache.jit_debug
  • opcache.jit_hot_func
  • opcache.jit_hot_loop
  • opcache.jit_hot_return
  • opcache.jit_hot_side_exit
  • opcache.jit_max_exit_counters
  • opcache.jit_max_loop_unrolls
  • opcache.jit_max_polymorphic_calls
  • opcache.jit_max_recursive_calls
  • opcache.jit_max_recursive_returns
  • opcache.jit_max_root_traces
  • opcache.jit_max_side_traces
  • opcache.log_verbosity_level
  • opcache.max_file_size
  • opcache.opt_debug_level
  • opcache.optimization_level
  • opcache.revalidate_freq
  • output_buffering
  • pcre.backtrack_limit
  • pcre.recursion_limit
  • pgsql.max_links
  • pgsql.max_persistent
  • post_max_size
  • realpath_cache_size
  • realpath_cache_ttl
  • session.cache_expire
  • session.cookie_lifetime
  • session.gc_divisor
  • session.gc_maxlifetime
  • session.gc_probability
  • soap.wsdl_cache_limit
  • soap.wsdl_cache_ttl
  • unserialize_max_depth
  • upload_max_filesize
  • user_ini.cache_ttl
  • xmlrpc_error_number
  • zend.assertions
  • zlib.output_compression_level

User Contributed Notes

There are no user contributed notes for this page.


Windows Support

Core

Windows specific error messages are no longer localized, but instead always displayed in English to better match PHP error messages.

Preliminary and highly experimental support for building on ARM64 has been added.

OCI8

Because building against Oracle Client 10g is no longer supported anyway, the configuration option --with-oci8 has been dropped. The --with-oci8-11g, --with-oci8-12c and --with-oci8-19 configuration options are still supported.

Zip

The Zip extension is upgraded to version 1.21.0, and is now built as shared library (DLL) by default.

User Contributed Notes

There are no user contributed notes for this page.


Migración de PHP 8.0.x a PHP 8.1.x

Tabla de contenidos

  • New Features
  • New Classes and Interfaces
  • New Functions
  • New Global Constants
  • Cambios incompatibles con versiones anteriores
  • Deprecated Features
  • Other Changes

Esta nueva versión menor trae consigo una serie de nuevas características y algunas incompatibilidades que deben probarse 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.1.x, 7.2.x, 7.3.x, 7.4.x, 8.0.x.

User Contributed Notes

There are no user contributed notes for this page.


New Features

PHP Core

Integer Octal Literal Prefix

Octal integers can now use an explicit 0o/0O prefix in integer literals, similarly to binary and hexadecimal integer literals.

<?php
014; // Non-prefix octal literal
0o14; // Prefixed octal literal
?>

Array Unpacking with String Keys

Added support for array unpacking with strings keys.

<?php
$arr1 = [1, 'a' => 'b'];
$arr2 = [...$arr1, 'c' => 'd']; //[1, 'a' => 'b', 'c' => 'd']
?>

Named Argument After Argument Unpacking

It is now possible to specify named arguments after an argument unpack. e.g. foo(...$args, named: $arg).

full-path Key for File Uploads

File uploads now provide an additional full_path key, which contains the full path (rather than just the basename) of the uploaded file. This is intended for use in conjunction with "upload webkitdirectory".

Enumerations

Support for Enumerations has been added.

Fibers

Support for Fibers has been added.

First Class Callable Syntax

Closures for callables can now be created using the syntax myFunc(...), which is identical to Closure::fromCallable('myFunc').

Nota: The ... is part of the syntax, and not an omission.

Intersection Types

Support for intersection types has been added.

Precaución

Intersection types cannot be used together with union types

Never type

A new return only type never has been added. This indicates that a function either exit(), throws an exception, or doesn't terminate.

new in Initializers

It is now possible to use new ClassName() expressions as the default value of a parameter, static variable, global constant initializers, and as attribute arguments. Objects can also be passed to define() now.

Readonly properties

Support for readonly has been added.

Final class constants

Added support for the final modifier for class constants. Also, interface constants become overridable by default.

CURL

Added the CURLOPT_DOH_URL option.

Added options for blob certificate when libcurl >= 7.71.0:

  • CURLOPT_ISSUERCERT_BLOB
  • CURLOPT_PROXY_ISSUERCERT
  • CURLOPT_PROXY_ISSUERCERT_BLOB
  • CURLOPT_PROXY_SSLCERT_BLOB
  • CURLOPT_PROXY_SSLKEY_BLOB
  • CURLOPT_SSLCERT_BLOB
  • CURLOPT_SSLKEY_BLOB

Added CURLStringFile, which can be used to post a file from a string rather than a file:

<?php
$file = new CURLStringFile($data, 'filename.txt', 'text/plain');
curl_setopt($curl, CURLOPT_POSTFIELDS, ['file' => $file]);
?>

FPM

Added openmetrics status format. It can be used by Prometheus to fetch FPM metrics.

Added new pool option for the dynamic process manager called pm.max_spawn_rate. It allows to start a number of children at a faster rate when dynamic pm is selected. The default value is 32 which was the previous hard coded value.

GD

Avif support is now available through imagecreatefromavif() and imageavif(), if libgd has been built with Avif support.

Hash

The following functions hash(), hash_file(), and hash_init() now support an additional optional options argument, which can be used to pass algorithm specific data.

MurmurHash3

Added support for MurmurHash3 with streaming support. The following variants are implemented:

  • murmur3a, 32-bit hash
  • murmur3c, 128-bit hash for x86
  • murmur3f, 128-bit hash for x64

The initial hash state can be passed through the seed key in the options array, for example:

<?php
$h = hash("murmur3f", $data, options: ["seed" => 42]);
echo $h, "\n";
?>
A valid seed value is within the range from 0 to the platform defined UINT_MAX, usually 4294967295.

xxHash

Added support for xxHash. The following variants are implemented:

  • xxh32, 32-bit hash
  • xxh64, 64-bit hash
  • xxh3, 64-bit hash
  • xxh128, 128-bit hash

The initial hash state can be passed through the seed key in the options array, for example:

<?php
$h = hash("xxh3", $data, options: ["seed" => 42]);
echo $h, "\n";
?>
Secret usage is supported through passing the secret key in the options array, too:
<?php
$h = hash("xxh3", $data, options: ["secret" => "at least 136 bytes long secret here"]);
echo $h, "\n";
?>
The quality of the custom secret is crucial for the quality of the resulting hash. It is highly recommended for the secret to use the best possible entropy.

MySQLi

New INI directive mysqli.local_infile_directory

The mysqli.local_infile_directory INI directive has been added, which can be used to specify a directory from which files are allowed to be loaded. It is only meaningful if mysqli.allow_local_infile is not enabled, as all directories are allowed in that case.

Binding parameters in execute

It is now possible to bind parameters by passing them as an array to mysqli_stmt::execute(). All values will be bound as strings. Only list arrays are allowed. This new feature is not available when MySQLi is compiled with libmysqlclient.

<?php
$stmt = $mysqli->prepare('INSERT INTO users(id, name) VALUES(?,?)');
$stmt->execute([1, $username]);
?>

New method mysqli_result::fetch_column()

mysqli_result::fetch_column() has been added to allow fetching a single scalar value from the result set. The new method accepts an optional 0-based column parameter of type int specifying which column to fetch from.

<?php
$result = $mysqli->query('SELECT username FROM users WHERE id = 123');
echo $result->fetch_column();
?>

PDO

The PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY attribute has been added, which can be used to specify a directory from which files are allowed to be loaded. It is only meaningful if PDO::MYSQL_ATTR_LOCAL_INFILE is not enabled, as all directories are allowed in that case.

PDO_SQLite

SQLite's "file:" DSN syntax is now supported, which allows specifying additional flags. This feature is not available if open_basedir is set.

<?php
new PDO('sqlite:file:path/to/sqlite.db?mode=ro')
?>

POSIX

Added POSIX_RLIMIT_KQUEUES and POSIX_RLIMIT_NPTS. These rlimits are only available on FreeBSD.

Standard

fputcsv() now accepts a new eol argument which allows to define a custom End of Line sequence, the default remains the same and is "\n".

SPL

SplFileObject::fputcsv() now accepts a new eol argument which allows to define a custom End of Line sequence, the default remains the same and is "\n".

User Contributed Notes

There are no user contributed notes for this page.


New Classes and Interfaces

cURL

  • CURLStringFile

Intl

  • IntlDatePatternGenerator

Reflection

  • ReflectionFiber

User Contributed Notes

There are no user contributed notes for this page.


New Functions

PHP Core

  • array_is_list()

GD

  • imagecreatefromavif()
  • imageavif()

MySQLi

  • mysqli_result::fetch_column()
  • mysqli_fetch_column()

Process Control

  • pcntl_rfork()

Reflection

  • ReflectionFunctionAbstract::getClosureUsedVariables()

Standard

  • fsync()
  • fdatasync()

Sodium

XChaCha20

  • sodium_crypto_stream_xchacha20()
  • sodium_crypto_stream_xchacha20_keygen()
  • sodium_crypto_stream_xchacha20_xor()

Ristretto255

Ristretto255 functions are available as of libsodium 1.0.18.

  • sodium_crypto_core_ristretto255_add()
  • sodium_crypto_core_ristretto255_from_hash()
  • sodium_crypto_core_ristretto255_is_valid_point()
  • sodium_crypto_core_ristretto255_random()
  • sodium_crypto_core_ristretto255_scalar_add()
  • sodium_crypto_core_ristretto255_scalar_complement()
  • sodium_crypto_core_ristretto255_scalar_invert()
  • sodium_crypto_core_ristretto255_scalar_mul()
  • sodium_crypto_core_ristretto255_scalar_negate()
  • sodium_crypto_core_ristretto255_scalar_random()
  • sodium_crypto_core_ristretto255_scalar_reduce()
  • sodium_crypto_core_ristretto255_scalar_sub()
  • sodium_crypto_core_ristretto255_sub()
  • sodium_crypto_scalarmult_ristretto255()
  • sodium_crypto_scalarmult_ristretto255_base()

User Contributed Notes

There are no user contributed notes for this page.


New Global Constants

cURL

  • CURLOPT_DOH_URL
  • CURLOPT_ISSUERCERT_BLOB
  • CURLOPT_PROXY_ISSUERCERT
  • CURLOPT_PROXY_ISSUERCERT_BLOB
  • CURLOPT_PROXY_SSLCERT_BLOB
  • CURLOPT_PROXY_SSLKEY_BLOB
  • CURLOPT_SSLCERT_BLOB
  • CURLOPT_SSLKEY_BLOB

GD

  • IMG_AVIF
  • IMG_WEBP_LOSSLESS

MySQLi

  • MYSQLI_REFRESH_REPLICA

    This constant has been added as a replacement for MYSQLI_REFRESH_SLAVE, in line with an upstream change in MySQL. The old constant is still available for backwards-compatibility reasons, but may be deprecated/removed in the future.

PCNTL

  • PRIO_DARWIN_BG
  • PRIO_DARWIN_THREAD

POSIX

  • POSIX_RLIMIT_KQUEUES
  • POSIX_RLIMIT_NPTS

Sockets

The following socket options are now defined if they are supported:

  • SO_ACCEPTFILTER
  • SO_DONTTRUNC
  • SO_WANTMORE
  • SO_MARK
  • TCP_DEFER_ACCEPT

Sodium

  • SODIUM_CRYPTO_STREAM_XCHACHA20_NONCEBYTES
  • SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES
  • SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_BYTES
  • SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_BYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_HASHBYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES
  • SODIUM_CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES

Tokenizer

  • T_READONLY

User Contributed Notes

There are no user contributed notes for this page.


Cambios incompatibles con versiones anteriores

PHP Core

$GLOBALS Access Restrictions

Access to the $GLOBALS array is now subject to a number of restrictions. Read and write access to individual array elements like $GLOBALS['var'] continues to work as-is. Read-only access to the entire $GLOBALS array also continues to be supported. However, write access to the entire $GLOBALS array is no longer supported. For example, array_pop($GLOBALS) will result in an error.

Usage of static Variables in Inherited Methods

When a method using static variables is inherited (but not overridden), the inherited method will now share static variables with the parent method.

<?php
class A {
public static function counter() {
static $counter = 0;
$counter++;
return $counter;
}
}
class B extends A {}
var_dump(A::counter()); // int(1)
var_dump(A::counter()); // int(2)
var_dump(B::counter()); // int(3), previously int(1)
var_dump(B::counter()); // int(4), previously int(2)
?>
This means that static variables in methods now behave the same way as static properties.

Return Type Compatibility with Internal Classes

Most non-final internal methods now require overriding methods to declare a compatible return type, otherwise a deprecated notice is emitted during inheritance validation. In case the return type cannot be declared for an overriding method due to PHP cross-version compatibility concerns, a #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Resource to Object Migration

Several recursos have been migrated to objects. Return value checks using is_resource() should be replaced with checks for false.

  • The FileInfo functions now accept and return, respectively, finfo objects instead of fileinfo recursos.

  • The FTP functions now accept and return, respectively, FTP\Connection objects instead of ftp recursos.

  • The IMAP functions now accept and return, respectively, IMAP\Connection objects instead of imap recursos.

  • The LDAP functions now accept and return, respectively, LDAP\Connection objects instead of ldap link recursos.

  • The LDAP functions now accept and return, respectively, LDAP\Result objects instead of ldap result recursos.

  • The LDAP functions now accept and return, respectively, LDAP\ResultEntry objects instead of ldap result entry recursos.

  • The PgSQL functions now accept and return, respectively, PgSql\Connection objects instead of pgsql link recursos.

  • The PgSQL functions now accept and return, respectively, PgSql\Result objects instead of pgsql result recursos.

  • The PgSQL functions now accept and return, respectively, PgSql\Lob objects instead of pgsql large object recursos.

  • The PSpell functions now accept and return, respectively, PSpell\Dictionary objects instead of pspell recursos.

  • The PSpell functions now accept and return, respectively, PSpell\Config objects instead of pspell config recursos.

MySQLi

mysqli_fetch_fields(), and mysqli_fetch_field_direct() will now always return 0 for the max_length. This information can be computed by iterating over the result set, and taking the maximum length. This is what PHP was doing internally previously.

The MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH option no longer has any effect.

The MYSQLI_STORE_RESULT_COPY_DATA option no longer has any effect. Passing any value to the mode parameter of mysqli::store_result() no longer has any effect.

mysqli::connect() now returns true instead of null on success.

The default error handling mode has been changed from "silent" to "exceptions" See the MySQLi reporting mode page for more details on what this entails, and how to explicitly set this attribute. To restore the previous behaviour use: mysqli_report(MYSQLI_REPORT_OFF);

Classes extending mysqli_stmt::execute() are now required to specify the additional mandatory parameter.

MySQLnd

The mysqlnd.fetch_data_copy INI directive has been removed. This should not result in user-visible behavior changes.

OpenSSL

EC private keys will now be exported in PKCS#8 format rather than traditional format, just like all other keys.

openssl_pkcs7_encrypt() and openssl_cms_encrypt() will now to default using AES-128-CBC rather than RC2-40. The RC2-40 cipher is considered insecure and not enabled by default by OpenSSL 3.

PHP Data Objects

PDO::ATTR_STRINGIFY_FETCHES now stringifies values of type bool to "0" or "1". Previously bools were not stringified.

Calling PDOStatement::bindColumn() with PDO::PARAM_LOB will now constantly bind a stream result when PDO::ATTR_STRINGIFY_FETCHES is not enabled. Previously, the result would either be a stream or a string depending on the used database driver and the time the binding is performed.

MySQL Driver

Integers and floats in result sets will now be returned using native PHP types instead of strings when using emulated prepared statements. This matches the behavior of native prepared statements. The previous behaviour can be restored by enabling the PDO::ATTR_STRINGIFY_FETCHES option.

SQLite Driver

Integers and floats in results sets will now be returned using native PHP types. The previous behaviour can be restored by enabling the PDO::ATTR_STRINGIFY_FETCHES option.

Phar

To comply with the ArrayAccess interface, Phar::offsetUnset() and PharData::offsetUnset() no longer return a bool.

Standard

version_compare() no longer accepts undocumented operator abbreviations.

htmlspecialchars(), htmlentities(), htmlspecialchars_decode(), html_entity_decode(), and get_html_translation_table() now use ENT_QUOTES | ENT_SUBSTITUTE rather than ENT_COMPAT by default. This means that ' is escaped to &#039; while previously nothing was done. Additionally, malformed UTF-8 will be replaced by a Unicode substitution character, instead of resulting in an empty string.

debug_zval_dump() now prints the refcount of a reference wrappers with their refcount, instead of only prepending & to the value. This more accurately models reference representation since PHP 7.0.

debug_zval_dump() now prints interned instead of a dummy refcount for interned strings and immutable arrays.

Standard PHP Library (SPL)

SplFixedArray, will now be JSON encoded like an array

User Contributed Notes

There are no user contributed notes for this page.


Deprecated Features

PHP Core

Implementing Serializable without __serialize() and __unserialize()

Either only the new methods should be implemented, if no support for PHP prior to version 7.4 is provided, or both should be implemented.

Passing null to non-nullable parameters of built-in functions

Scalar types for built-in functions are nullable by default. This behaviour is deprecated to align with the behaviour of user-defined functions, where scalar types need to be marked as nullable explicitly.

<?php
var_dump(str_contains("foobar", null));
// Deprecated: Passing null to parameter #2 ($needle) of type string
// is deprecated
?>

Implicit incompatible float to int conversions

The implicit conversion of float to int which leads to a loss in precision is now deprecated. This affects array keys, int type declarations in coercive mode, and operators working on ints.

<?php
$a = [];
$a[15.5]; // deprecated, as key value loses the 0.5 component
$a[15.0]; // ok, as 15.0 == 15
?>

Calling a static element on a trait

Calling a static method, or accessing a static property directly on a trait is deprecated. Static methods and properties should only be accessed on a class using the trait.

Returning a non-array from __sleep()

Returning a value which is not an array from __sleep() now generates a diagnostic.

Returning by reference from a void function

<?php
function &test(): void {}
?>
Such a function is contradictory, and already emits the following E_NOTICE when called: Only variable references should be returned by reference.

Autovivification from false

Autovivification is the process of creating a new array when appending to a value. Autovivification is prohibited from scalar values, false however was an exception. This is now deprecated.

<?php
$arr = false;
$arr[] = 2; // deprecated
?>

Nota:

Autovivification from null and undefined values is still allowed:

<?php
// From undefined
$arr[] = 'some value';
$arr['doesNotExist'][] = 2;
// From null
$arr = null;
$arr[] = 2;
?>

ctype

Verifying non-string arguments

Passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to string or an explicit call to chr() should be made. All ctype_*() functions are affected.

Date

date_sunrise() and date_sunset() have been deprecated in favor of date_sun_info().

strptime() has been deprecated.
Use date_parse_from_format() instead (for locale-independent parsing),
or IntlDateFormatter::parse() (for locale-dependent parsing).

strftime() and gmstrftime() have been deprecated.
Use date() instead (for locale-independent formatting),
or IntlDateFormatter::format() (for locale-dependent formatting).

Filter

The FILTER_SANITIZE_STRING and FILTER_SANITIZE_STRIPPED filters are deprecated.

The filter.default INI directive is deprecated.

GD

The num_points of imagepolygon(), imageopenpolygon() and imagefilledpolygon() has been deprecated.

Hash

The mhash(),
mhash_keygen_s2k(),
mhash_count(),
mhash_get_block_size(),
and mhash_get_hash_name() have been deprecated.
Use the hash_*() functions instead.

IMAP

The NIL constant has been deprecated. Use 0 instead.

Intl

Calling IntlCalendar::roll() with a bool argument is deprecated. Use 1 and -1 instead of true and false respectively.

Multibyte String

Calling mb_check_encoding() without any arguments is deprecated.

MySQLi

The mysqli_driver::$driver_version property has been deprecated. It was meaningless and outdated, use PHP_VERSION_ID instead.

Calling mysqli::get_client_info() or mysqli_get_client_info() with the mysqli argument has been deprecated. Call mysqli_get_client_info() without any arguments to obtain the version information of the client library.

The mysqli::init() method has been deprecated.
Replace calls to parent::init() with
parent::__construct().

OCI8

The oci8.old_oci_close_semantics INI directive is deprecated.

ODBC

odbc_result_all() has been deprecated.

PDO

The PDO::FETCH_SERIALIZE fetch mode has been deprecated.

PgSQL

Not passing the connection argument to all pgsql_*() functions has been deprecated.

SOAP

The ssl_method option of SoapClient::__construct() has been deprecated in favor of SSL stream context options.

Standard

Calling key(), current(), next(), prev(), reset(), or end() on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead.

The auto_detect_line_endings INI directive is deprecated. If necessary, handle "\r" line breaks manually instead.

The FILE_BINARY and FILE_TEXT constants have been deprecated. They never had any effect.

User Contributed Notes

There are no user contributed notes for this page.


Other Changes

Changes in SAPI Modules

CLI

Using -a without the readline extension will now result in an error. Previously, -a without readline had the same behavior as calling php without any arguments, apart from printing an additional "Interactive mode enabled" message. This mode was not interactive.

PHPDBG

Remote functionality from phpdbg has been removed.

Changed Functions

Core

The order of properties used in foreach, var_dump(), serialize(), object comparison, etc. was changed. Properties are now ordered naturally according to their declaration and inheritance. Properties declared in a base class are going to be before the child properties.

This order is consistent with internal layout of properties in zend_object structure and repeats the order in default_properties_table[] and properties_info_table[]. The old order was not documented and was caused by class inheritance implementation details.

Filter

The FILTER_FLAG_ALLOW_OCTAL flag of the FILTER_VALIDATE_INT filter now accept octal string with the leading octal prefix ("0o"/"0O").

GMP

All GMP functions now accept octal string with the leading octal prefix ("0o"/"0O").

PDO ODBC

PDO::getAttribute() with
PDO::ATTR_SERVER_INFO and
PDO::ATTR_SERVER_VERSION
now return values instead of throwing PDOException.

Reflection

ReflectionProperty::setAccessible() and ReflectionMethod::setAccessible() no longer have an effect. Properties and methods are now always considered accessible via Reflection.

Standard

syslog() is now binary safe.

Other Changes to Extensions

GD

imagewebp() can now do lossless WebP encoding by passing IMG_WEBP_LOSSLESS as the quality.

This constant is only defined, if the used libgd supports lossless WebP encoding.

MySQLi

mysqli_stmt::next_result() and mysqli::fetch_all() are now available when linking against libmysqlclient.

OpenSSL

  • The OpenSSL extension now requires at least OpenSSL version 1.0.2.

  • OpenSSL 3.0 is now supported. Be aware that many ciphers are no longer enabled by default (part of the legacy provider), and that parameter validation (e.g. minimum key sizes) is stricter now.

Phar

  • SHA256 is now used by default for signatures.

  • Added support for OpenSSL_SHA256 and OpenSSL_SHA512 signatures.

SNMP

  • Added support for SHA256 and SHA512 for the security protocol.

Standard

--with-password-argon2 now uses pkg-config to detect libargon2. As such, an alternative libargon2 location should now be specified using PKG_CONFIG_PATH.

Changes to INI File Handling

  • The log_errors_max_len INI directive has been removed. It no longer had an effect since PHP 8.0.0.

  • A leading dollar in a quoted string can now be escaped: "\${" will now be interpreted as a string with contents ${.

  • Backslashes in double quoted strings are now more consistently treated as escape characters. Previously, "foo\\" followed by something other than a newline was not considered as a terminated string. It is now interpreted as a string with contents foo\. However, as an exception, the string "foo\" followed by a newline will continue to be treated as a valid string with contents foo\ rather than an unterminated string. This exception exists to support naive uses of Windows file paths such as "C:\foo\".

User Contributed Notes

There are no user contributed notes for this page.


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
  • Otros cambios

Esta nueva versión mayor trae consigo una serie de nuevas características y algunas incompatibilidades que deben probarse 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, 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

aphpguy at galaxy dot za dot net 06-Jul-2023 12:33
If you have older projects that break with PHP7 to 8 migration due to the loose comparison issue:

i.e. if ($a == 0) different behaviour between PHP 7 and PHP 8
(for case like $a = "" or $a = "123foo" and other cases listed at top)

replace in old code:

if ($a == 0) { .. }

with

if (cmp_eq($a, $b)) { .. }

Tested with a wide range of scenarios, even against arrays, booleans, file handles, pipe handles, objects, scalars and numbers.

So old code still behave like before.
Then both PHP8.x and older PHP up to ver 7.x will give the exact same boolean true or false output for loose comparisons.

function cmp_eq($a, $b) {
// If both $a and $b are of type strings, compare them as strings
if (is_string($a) && is_string($b)) { return $a == $b; } // may not be === because php says '42' equals '042' true yet '42' === '042' is false.

// If both $a and $b are numeric strings, compare them as numbers
if (is_numeric($a) && is_numeric($b)) { return $a == $b; }

// If $a is an empty string and $b is 0, or vice versa, return true
if (($a === '' && $b === 0) || ($a === 0 && $b === '')) { return true; }

// If $a is a non-numeric string and $b is 0, or vice versa, return true
if ((is_string($a) && ($a !== '') && ($b === 0)) || (($a === 0) && is_string($b) && ($b !== ''))) {
return true;
}
// special case '123abc' == 123 .. php 7 casts 123abc to 123, then 123 == 123 results in true. lets mimic that.
if ((is_string($a) && ($a !== '') && (is_numeric($b)) && ((bool)$b))) {
$number = filter_var($a, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); //"-234.56xyz"
return $number == $b;
}
if (is_numeric($a) && ((bool)$a) && is_string($b) && ($b !== '')) {
$number = filter_var($b, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); //"-234.56xyz"
return $a == $number;
}

// If $a is a number and $b is a non-numeric string, cast $a to string and compare
if (is_numeric($a) && is_string($b)) { return strval($a) == $b; }

// If $b is a number and $a is a non-numeric string, cast $b to string and compare
if (is_string($a) && is_numeric($b)) { return $a == strval($b); }

// If $a and $b are both non-numeric strings, compare them directly, we should return true if they are the same
return $a == $b;
} // end func cmp_eq

Note: the better way would be to port code to PHP 8, use strict variable typing and rather make use of the === and !== operators.

But in some cases having lots of old code to quickly patch, this might help.
1035041238 at qq dot com 15-Nov-2022 02:41
In PHP 8, an empty string is less than any number, an English letter is always bigger than any number.

More interesting are the punctuation marks and non-word characters, some bigger than numbers, some smaller than numbers

$string = '`~!@#$%^&*()-_=+[]{};:\'"\\|,.<>/?';

$number = 999999999999;

$str_len = strlen($string);

$bigger = $smaller = $equal = [];
for ( $i = 0; $i < $str_len; ++$i ) {
    if ( $string[$i] > $number ) {
        $bigger[] = $string[$i];
    } elseif ( $string[$i] < $number ) {
        $smaller[] = $string[$i];
    } else {
        $equal[] = $string[$i];
    }
}

var_dump( $bigger ); //['`', '~', '@', '^', '_', '=', '[', ']', '{', '}', ';', ':', '\', '|', '<', '>', '?']
var_dump( $smaller); //['!', '#', '$', '%', '&', '*', '(', ')', '-', '+', ''', '"', ',', '.', '/']
var_dump( $equal); //[]
retry, abort, fail 25-Feb-2022 11:57
The change in string to int comparison mentioned above (e.g. '' == 0 now equates to false) has some other nasty consequences:

$a = '';

// php 8

if ( $a < 0 ) echo 'true'; // echos true
if ( $a < -1) echo 'true'; // echos true
if ( $a < -100 ) echo 'true'; // echos true

// php 7

if ( $a < 0 ) echo 'true'; // no output
if ( $a < -1) echo 'true'; // no output
if ( $a < -100 ) echo 'true'; // no output

So in a situation where you may have a web form input and expected an empty value to equate to 0, watch out not only for == 0, != 0, and <= 0 comparisons, but ALL < or <= comparisons to negative integers.


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

dominique dot vienne at ik dot me 21-Jun-2021 01:23
If you try to get all methods / functions assigning an optional argument before a mandatory one, try this regex (single line)

<?php
function\s+[a-z][a-zA-Z0-9_]*\((?:\$[a-z][a-zA-Z0-9]*\s*,\s*)*
(?:\$[a-z][A-Za-z0-9_]*\s*=[^\$\)]+)+\$[a-z][a-zA-Z0-9_]*\)
?>

for
<?php
public function test($a, $b) {
$a = [];
$b = [$abc => $ss[],
];
}

private function too($c, $a = true, $b) {
}

protected function bar($a = []) {
}

public function foo($a, $b = true) {
}

public function fooBar32($a=true, $b = [], $c) {
}

private function oo_bAr($a = []) {
}
?>
it will match too() and fooBar32()

Have a nice migration! ;)


Otros cambios

Cambios en los módulos SAPI

Apache2Handler

El módulo PHP ha sido renombrado de php7_module a php_module.

Fucniones Cambiadas

Reflection

Los resultados de ReflectionClass::getConstants() y ReflectionClass::getReflectionConstants() pueden ser filtrados a través de un nuevo parámetro filter. Tres nuevas constantes han sido añadidas para ser usadas junto a la clase:

  • ReflectionClassConstant::IS_PUBLIC
  • ReflectionClassConstant::IS_PROTECTED
  • ReflectionClassConstant::IS_PRIVATE

Zip

  • Los métodos ZipArchive::addGlob() y ZipArchive::addPattern() aceptan más valores en el options argumento de array:

    • 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() ahora restaura el tiempo de modificación del archivo.

Otros cambios a las extensiones

CURL

  • La extensión CURL ahora requiere al menos libcurl 7.29.0.

  • El parámetro obsoleto version de curl_version() ha sido eliminado.

Fecha y Tiempo

DatePeriod ahora implementa IteratorAggregate (instead of Traversable).

DOM

DOMNamedNodeMap y DOMNodeList ahora implementan IteratorAggregate (instead of Traversable).

Intl

IntlBreakIterator y ResourceBundle ahora implementan IteratorAggregate (instead of Traversable).

Enchant

La extensión enchant ahora usa libenchant-2 por defecto cuando esté disponible. libenchant versión 1 sigue siendo soportado pero está obsoleto y podría ser borrado en el futuro.

GD

  • El num_points párametro de imagepolygon(), imageopenpolygon() y imagefilledpolygon() es ahora opcional, p.e. esas funciones pueden ser llamadas con 3 o 4 argumentos. Si el argumento está omitido, está calculado como count($points)/2.

  • La función imagegetinterpolation() para obtener la interpolación actual ha sido añadida.

JSON

La extensión JSON no puede ser deshabilitada y siempre será una parte integral de cualquier build PHP. De manera similar a la extensión de fecha.

MBString

La tabla unicode ha sido actualizada a la versión 13.0.0.

PDO

PDOStatement ahora implementa IteratorAggregate (instead of Traversable).

LibXML

La versión mínima requerida es 2.9.0. Esto significa que la carga externa está garantizada de ser deshabilitada por defecto y no habrá pasos extras para protegerse frente a los ataques XXE

MySQLi / PDO MySQL

  • Cuando mysqlnd no sea usado (que es la opción recomendada y por defecto), la versión libmysqlclient mínima soportada es ahora 5.5.

  • mysqli_result ahora implementa IteratorAggregate (instead of Traversable).

PGSQL / PDO PGSQL

Las extensiones PGQSQL y PDO PGSQL ahora requieren al menos libpq 9.1.

Readline

Llamar a readline_completion_function() antes de que un prompt interactivo comience (e.g. in auto_prepend_file) ahora sobreescribirá default interactive prompt completion function. Previamente readline_completion_function() solo trabajaba cuando se le llamaba antes de comenzar el prompt interactivo.

SimpleXML

SimpleXMLElement ahora implementa RecursiveIterator y absorve la funcionalidad de SimpleXMLIterator. SimpleXMLIterator es una extensión vacía de SimpleXMLElement.

Cambios al INI File Handling

  • com.dotnet_version es una nueva directiva INI para elegir la versión del framework .NET a usar en los objetos dotnet .

  • zend.exception_string_param_max_len es una nueva directiva INI para establecer la longitud máxima del string de una stringified stack strace.

EBCDIC

Los objetivos EBCDIC no estarán más soportadas, aunque es poco probable que todavía estuvieran trabajando en el primer lugar.

Rendimiento

  • Un compilador Just-In-Time (JIT) ha sido añadido a la extensión opcache

  • array_slice() de un array sin gaps no escaneará más el array completo para encontrar el offset del comienzo. Esto puede ser significante al reducir el runtime de la función con offsets más largos y tamaños más pequeños.

  • strtolower() ahora usa una implementación SIMD cuando se usa "C" LC_CTYPE locale (que es la opción por defecto).

User Contributed Notes

barry dot nelson at amobiledevice dot com 16-Jan-2023 12:18
If loading the PHP8 apache module on SuSe Linux, the configuration scripts incorrectly try to load it with automatically generated load statement of:
LoadModule php8_module                     /usr/lib64/apache2/mod_php8.so
This does not work, the patch below fixes the conf file generator...

--- /usr/share/apache2/get_module_list    2023-01-14 22:41:49.586825349 -0500
+++ /usr/share/apache2/get_module_list    2023-01-14 22:42:02.171600410 -0500
@@ -91,4 +91,8 @@
     esac

+    if [ "$module_id" = "php8_module" ]; then
+        module_id="php_module"
+    fi
+
     if [[ -f $module_path ]]; then
         printf "LoadModule %-30s %s\n" $module_id $module_path >&3


Migración de PHP 7.3.x a PHP 7.4.x

Tabla de contenidos

  • Nuevas características
  • Nuevas clases e interfaces
  • Nuevas funciones
  • Nuevas constantes globales
  • Cambios incompatibles hacia atrás
  • Características obsoletas
  • Extensiones eliminadas
  • Other Changes
  • Soporte para Windows

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.


Nuevas características

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 características
  • Nuevas funciones »
  • PHP Manual
  • Migración de PHP 7.3.x a PHP 7.4.x
  • Nuevas clases e interfaces

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

There are no user contributed notes for this page.


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.


Cambios incompatibles hacia atrás

PHP Core

Array-style access of non-arrays

Intentar usar valores de tipo null, bool, int, float o un resource como un array (como $null["key"]) ahora generará un aviso.

Función get_declared_classes()

La función get_declared_classes() ya no devuelve las clases anónimas que aún no han sido instanciadas.

fn keyword

fn es ahora una palabra clave reservada. En particular, ya no puede utilizarse como nombre de función o de clase. Todavía se puede utilizar como nombre de método o constante de clase.

Etiqueta <?php al final del fichero

<?php al final del fichero (sin la nueva línea final) se interpretará ahora como una etiqueta de apertura de PHP. Anteriormente se interpretaba como una etiqueta de apertura corta seguida de php y resultaba un error de sintaxis (con short_open_tag=1) o se interpretaba como un string <?php (con 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.

Función htmlentities()

htmlentities() will now raise a notice (instead of a strict standards warning) if it is used with an encoding for which only basic entity substitution is supported, in which case it is equivalent to htmlspecialchars().

Funciones fread() y fwrite()

fread() y fwrite() ahora devolverán false si la operación ha fallado. Anteriormente se devolvía un string vacío o un 0. EAGAIN/EWOULDBLOCK no se consideran fallos.

Estas funciones ahora también lanzan un aviso en caso de fallo, como cuando se intenta escribir en un recurso de archivo de sólo lectura.

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 password_needs_rehash() 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.


Soporte para Windows

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

There are no user contributed notes for this page.


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

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, with the supported filter types - all, no-ctrl and ascii. Starting with PHP 7.3.8, raw is also available, restoring the way syslog behaved in previous PHP versions. This filter will also affect calls to syslog().
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

antonfedonyuk at gmail dot com 21-Apr-2021 12:27
Note: "omitted" = "removed":
<?php
declare(strict_types=1);

interface ITest
{
    public function run(array $input);
}

class Test implements ITest
{
    public function run($input) {
       return $input;
   }
}

echo (new Test())->run('foo'); // display foo, no error
?>
info at ensostudio dot ru 11-Sep-2020 07:28
Note: you cant change parameter type for abstract method defined in interface.
<?php
abstract class AbstractAssocArray imlements ArrayAccess
{
    abstract public function offsetSet($offset, $value): void;
    ...
}
abstract class AbstractAssocArray2 extends AbstractAssocArray
{
    abstract public function offsetSet(string $offset, $value): void;
}
class AssocArray extends AbstractAssocArray2
{
    public function offsetSet(string $offset, $value): void
    {
         $this->{$offset} = $value;
    }
}
?>
It's throw fatal error: Declaration of AbstractAssocArray::offsetSet(string $offset, $value): void must be compatible with AbstractAssocArrayAccess::offsetSet($offset, $value).


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

There are no user contributed notes for this page.


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 bool 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 01:52
In php 7.0 it's possible to curry functions in a way that's similar to JavaScript.

<?php

// A curried function
function add($a) {
  return function($b) use ($a) {
    return $a + $b;
  };
}

// Invoking curried function in PHP 7
$result = add(10)(15);

var_dump($result); // int 25

?>

Currying in this way is not possible in php 5.6.
Adrian Wiik 16-Jan-2020 01:52
A good rule of thumb for remembering what the spaceship operator expression returns is to replace the spaceship operator with a minus sign (-). If the result is negative, 0 or positive, the expression will return -1, 0 or 1 respectively.

Example:
<?php
echo 5 <=> 8; // 5 - 8 = -3, prints -1
echo 2 <=> 2; // 2 - 2 = 0, prints 0
echo 4 <=> 2; // 4 - 2 = 2, prints 1


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

There are no user contributed notes for this page.


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

There are no user contributed notes for this page.


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

There are no user contributed notes for this page.


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

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!


Sobre la depuración en PHP

PHP viene con el depurador interactivo phpdbg. Se pueden 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

There are no user contributed notes for this page.


Opciones de configuración

Tabla de contenidos

  • Listado de opciones de configuración del núcleo

User Contributed Notes

There are no user contributed notes for this page.


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 |
arg_separator.input | "&" | PHP_INI_PERDIR |
arg_separator.output | "&" | PHP_INI_ALL |
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.exception | "0" | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
auto_append_file | NULL | PHP_INI_PERDIR |
auto_detect_line_endings | "0" | PHP_INI_ALL |
auto_globals_jit | "1" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
bcmath.scale | "0" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM |
cgi.discard_path | "0" | PHP_INI_SYSTEM |
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM |
cgi.force_redirect | "1" | PHP_INI_SYSTEM |
cgi.nph | "0" | PHP_INI_ALL |
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM |
cgi.rfc2616_headers | "0" | PHP_INI_ALL |
child_terminate | "0" | PHP_INI_ALL |
cli.pager | "" | PHP_INI_ALL |
cli.prompt | "\\b \\> " | PHP_INI_ALL |
cli_server.color | "0" | PHP_INI_ALL | Disponible desde PHP 5.4.0.
com.allow_dcom | "0" | PHP_INI_SYSTEM |
com.autoregister_typelib | "0" | PHP_INI_ALL |
com.autoregister_verbose | "0" | PHP_INI_ALL |
com.autoregister_casesensitive | "1" | PHP_INI_ALL |
com.code_page | "" | PHP_INI_ALL |
com.dotnet_version | "" | PHP_INI_SYSTEM | Disponible desde PHP 8.0.0
com.typelib_file | "" | PHP_INI_SYSTEM |
curl.cainfo | NULL | PHP_INI_SYSTEM |
date.default_latitude | "31.7667" | PHP_INI_ALL |
date.default_longitude | "35.2333" | PHP_INI_ALL |
date.sunrise_zenith | "90.583333" | PHP_INI_ALL |
date.sunset_zenith | "90.583333" | PHP_INI_ALL |
date.timezone | "" | PHP_INI_ALL |
dba.default_handler | DBA_DEFAULT | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL | Por omisión a "UTF-8".
default_mimetype | "text/html" | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
disable_classes | "" | Solamente en php.ini |
disable_functions | "" | Solamente en php.ini |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL |
docref_ext | "" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
doc_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM | 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_log_mode | 0o644 | PHP_INI_ALL | Disponible a partir de PHP 8.2.0
error_prepend_string | NULL | PHP_INI_ALL |
error_reporting | NULL | PHP_INI_ALL |
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL |
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL |
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL |
exif.encode_jis | "" | PHP_INI_ALL |
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL |
exit_on_timeout | "" | PHP_INI_ALL |
expect.timeout | "10" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.logfile | "" | PHP_INI_ALL |
expect.match_max | "" | PHP_INI_ALL |
expose_php | "1" | Solamente en php.ini |
extension | NULL | Solamente en php.ini |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM |
fastcgi.logging | "1" | PHP_INI_SYSTEM |
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM |
fbsql.autocommit | "1" | PHP_INI_SYSTEM |
fbsql.batchSize | "1000" | PHP_INI_SYSTEM |
fbsql.batchsize | "1000" | PHP_INI_ALL |
fbsql.default_database | "" | PHP_INI_SYSTEM |
fbsql.default_database_password | "" | PHP_INI_SYSTEM |
fbsql.default_host | NULL | PHP_INI_SYSTEM |
fbsql.default_password | "" | PHP_INI_SYSTEM |
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM |
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM |
fbsql.max_connections | "128" | PHP_INI_SYSTEM |
fbsql.max_links | "128" | PHP_INI_SYSTEM |
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM |
fbsql.max_results | "128" | PHP_INI_SYSTEM |
fbsql.show_timestamp_decimals | "0" | PHP_INI_SYSTEM |
file_uploads | "1" | PHP_INI_SYSTEM |
filter.default | "unsafe_raw" | PHP_INI_PERDIR |
filter.default_flags | NULL | PHP_INI_PERDIR |
from | "" | PHP_INI_ALL |
gd.jpeg_ignore_warning | "1" | PHP_INI_ALL |
geoip.custom_directory | "" | PHP_INI_ALL |
hard_timeout | "2" | PHP_INI_SYSTEM | Disponible desde PHP 7.1.0.
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.default | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL |
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.default_db | NULL | PHP_INI_SYSTEM | Disponible desde PHP 5.0.0.
ibase.default_user | NULL | PHP_INI_ALL |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL | Disponible desde PHP 5.0.0.
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_all_pconnect | "0" | PHP_INI_SYSTEM | Disponible 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.
iconv.input_encoding | "ISO-8859-1" | PHP_INI_ALL | Obsoleta desde PHP 5.6.0.
iconv.output_encoding | "ISO-8859-1" | PHP_INI_ALL | Obsoleta desde PHP 5.6.0.
iconv.internal_encoding | "ISO-8859-1" | PHP_INI_ALL | Obsoleta desde PHP 5.6.0.
ignore_repeated_errors | "0" | PHP_INI_ALL |
ignore_repeated_source | "0" | PHP_INI_ALL |
ignore_user_abort | "0" | PHP_INI_ALL |
implicit_flush | "0" | PHP_INI_ALL |
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
intl.default_locale |  | PHP_INI_ALL |
intl.error_level | 0 | PHP_INI_ALL |
intl.use_exceptions | 0 | PHP_INI_ALL | Disponible desde PECL 3.0.0a1
last_modified | "0" | PHP_INI_ALL |
ldap.max_links | "-1" | PHP_INI_SYSTEM |
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL |
mail.add_x_header | "0" | PHP_INI_PERDIR |
mail.force_extra_parameters | NULL | Solamente en php.ini |
mail.log | "" | PHP_INI_PERDIR |
max_execution_time | "30" | PHP_INI_ALL |
max_input_nesting_level | "64" | PHP_INI_PERDIR |
max_input_vars | 1000 | PHP_INI_PERDIR |
max_input_time | "-1" | PHP_INI_PERDIR |
mbstring.language | "neutral" | PHP_INI_ALL |
mbstring.detect_order | NULL | PHP_INI_ALL |
mbstring.http_input | "pass" | PHP_INI_ALL | Obsoleta
mbstring.http_output | "pass" | PHP_INI_ALL | Obsoleta
mbstring.internal_encoding | NULL | PHP_INI_ALL | Obsoleta
mbstring.substitute_character | NULL | PHP_INI_ALL |
mbstring.func_overload | "0" | PHP_INI_SYSTEM | Obsoleta desde PHP 7.2.0; eliminada desde PHP 8.0.0.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR |
mbstring.http_output_conv_mimetypes | "^(text/|application/xhtml\+xml)" | PHP_INI_ALL |
mbstring.strict_detection | "0" | PHP_INI_ALL |
mbstring.regex_retry_limit | "1000000" | PHP_INI_ALL | Disponible a partir de PHP 7.4.0.
mbstring.regex_stack_limit | "100000" | PHP_INI_ALL | Disponible a partir de PHP 7.3.5.
mcrypt.algorithms_dir | null | PHP_INI_ALL |
mcrypt.modes_dir | null | PHP_INI_ALL |
memcache.allow_failover | "1" | PHP_INI_ALL | Disponible desde memcache 2.0.2.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Disponible desde memcache 2.1.0.
memcache.chunk_size | "8192" | PHP_INI_ALL | Disponible desde memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Disponible desde memcache 2.0.2.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Disponible desde memcache 2.2.0.
memcache.hash_function | "crc32" | PHP_INI_ALL | Disponible desde memcache 2.2.0.
session.save_handler | "files" | PHP_INI_ALL | Soportado desde memcache 2.1.2
session.save_path | "" | PHP_INI_ALL | Soportado desde memcache 2.1.2
memcache.protocol | ascii | >PHP_INI_ALL | Soportado desde memcache 3.0.0
memcache.redundancy | 1 | >PHP_INI_ALL | Soportado desde memcache 3.0.0
memcache.session_redundancy | 2 | >PHP_INI_ALL | Soportado desde memcache 3.0.0
memcache.compress_threshold | 20000 | >PHP_INI_ALL | Soportado desde memcache 3.0.3
memcache.lock_timeout | 15 | >PHP_INI_ALL | Soportado desde memcache 3.0.4
memory_limit | "128M" | PHP_INI_ALL |
mysql.allow_local_infile | "1" | PHP_INI_SYSTEM |
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL |
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.connect_timeout | "60" | PHP_INI_ALL |
mysqli.allow_local_infile | "1" | PHP_INI_SYSTEM | Antes de PHP 7.2.16 y 7.3.3 por omisión era "1"
mysqli.local_infile_directory |  | PHP_INI_SYSTEM |
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.collect_statistics | "1" | PHP_INI_SYSTEM |
mysqlnd.collect_memory_statistics | "0" | PHP_INI_SYSTEM |
mysqlnd.debug | "" | PHP_INI_SYSTEM |
mysqlnd.log_mask | 0 | PHP_INI_ALL |
mysqlnd.mempool_default_size | 16000 | PHP_INI_ALL |
mysqlnd.net_read_timeout | "86400" | PHP_INI_SYSTEM | Antes de PHP 7.2.0 el valor predeterminado era "31536000" y la capacidad de cambio era PHP_INI_SYSTEM
mysqlnd.net_cmd_buffer_size | "4096" | PHP_INI_SYSTEM |
mysqlnd.net_read_buffer_size | "32768" | PHP_INI_SYSTEM |
mysqlnd.sha256_server_public_key | "" | PHP_INI_PERDIR |
mysqlnd.trace_alloc | "" | PHP_INI_SYSTEM |
mysqlnd.fetch_data_copy | 0 | PHP_INI_ALL |
oci8.connection_class | "" | PHP_INI_ALL | Disponible desde PECL OCI8 1.3.
oci8.default_prefetch | "100" | PHP_INI_SYSTEM | Disponible desde PECL OCI8 1.1.
oci8.events | Off | PHP_INI_SYSTEM | Disponible desde PECL OCI8 1.3.
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Disponible desde PECL OCI8 1.1.
oci8.old_oci_close_semantics | Off | PHP_INI_SYSTEM | Disponible desde PECL OCI8 1.1.
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Disponible desde PECL OCI8 1.1.
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Disponible desde PECL OCI8 1.1.
oci8.prefetch_lob_size | "0" | PHP_INI_SYSTEM | Disponible desde PECL OCI8 3.2.
oci8.privileged_connect | Off | PHP_INI_SYSTEM | Disponible desde PECL OCI8 1.1.
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Disponible desde PECL OCI8 1.1.
odbc.default_db * | NULL | PHP_INI_ALL |
odbc.default_user * | NULL | PHP_INI_ALL |
odbc.default_pw * | NULL | PHP_INI_ALL |
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
odbc.default_cursortype | "3" | PHP_INI_ALL | Disponible a partir de PHP 5.3.0
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 |
opcache.interned_strings_buffer | "8" | PHP_INI_SYSTEM |
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.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.record_warnings | "0" | PHP_INI_SYSTEM | Disponible a partir de PHP 8.0.0
opcache.preferred_memory_model | "" | PHP_INI_SYSTEM |
opcache.protect_memory | "0" | PHP_INI_SYSTEM |
opcache.mmap_base | null | PHP_INI_SYSTEM |
opcache.restrict_api | "" | PHP_INI_SYSTEM |
opcache.file_update_protection | "2" | PHP_INI_ALL |
opcache.huge_code_pages | "0" | PHP_INI_SYSTEM |
opcache.lockfile_path | "/tmp" | PHP_INI_SYSTEM |
opcache.opt_debug_level | "0" | PHP_INI_SYSTEM | Disponible a partir de PHP 7.1.0
opcache.file_cache | NULL | PHP_INI_SYSTEM |
opcache.file_cache_only | "0" | PHP_INI_SYSTEM |
opcache.file_cache_consistency_checks | "1" | PHP_INI_SYSTEM |
opcache.file_cache_fallback | "1" | PHP_INI_SYSTEM | Solo Windows.
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
opcache.cache_id | "" | PHP_INI_SYSTEM | Solo Windows. Disponible a partir de PHP 7.4.0
opcache.jit | "tracing" | PHP_INI_ALL | Disponible a partir de PHP 8.0.0
opcache.jit_buffer_size | "0" | PHP_INI_SYSTEM | Disponible a partir de PHP 8.0.0
opcache.jit_debug | "0" | PHP_INI_ALL | Disponible a partir de PHP 8.0.0
opcache.jit_bisect_limit | "0" | PHP_INI_ALL | Disponible a partir de PHP 8.0.0
opcache.jit_prof_threshold | "0.005" | PHP_INI_ALL | Disponible a partir de PHP 8.0.0
opcache.jit_max_root_traces | "1024" | PHP_INI_SYSTEM | Disponible a partir PHP 8.0.0
opcache.jit_max_side_traces | "128" | PHP_INI_SYSTEM | Disponible a partir de PHP 8.0.0
opcache.jit_max_exit_counters | "8192" | PHP_INI_SYSTEM | Disponible a partir de PHP 8.0.0
opcache.jit_hot_loop | "64" | PHP_INI_SYSTEM | Disponible a partir de PHP 8.0.0
opcache.jit_hot_func | "127" | PHP_INI_SYSTEM | Disponible a partir de PHP 8.0.0
opcache.jit_hot_return | "8" | PHP_INI_SYSTEM | Disponible a partir de PHP 8.0.0
opcache.jit_hot_side_exit | "8" | PHP_INI_SYSTEM | Disponible a partir de PHP 8.0.0
opcache.jit_blacklist_root_trace | "16" | PHP_INI_ALL | Disponible a partir de PHP 8.0.0
opcache.jit_blacklist_side_trace | "8" | PHP_INI_ALL | Disponible a partir de PHP 8.0.0
opcache.jit_max_loop_unrolls | "8" | PHP_INI_ALL | Disponible a partir de PHP 8.0.0
opcache.jit_max_recursive_calls | "2" | PHP_INI_ALL | Disponible a partir de PHP 8.0.0
opcache.jit_max_recursive_returns | "2" | PHP_INI_ALL | Disponible a partir de PHP 8.0.0
opcache.jit_max_polymorphic_calls | "2" | PHP_INI_ALL | Disponible a partir de PHP 8.0.0
open_basedir | NULL | PHP_INI_ALL |
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR |
pcre.backtrack_limit | "1000000" | PHP_INI_ALL |
pcre.recursion_limit | "100000" | PHP_INI_ALL |
pcre.jit | "1" | PHP_INI_ALL |
pdo.dsn.* |  | Solamente php.ini |
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL |
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Esta característica obsoleta será eliminada con certeza en el futuro.
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM |
pgsql.ignore_notice | "0" | PHP_INI_ALL |
pgsql.log_notice | "0" | PHP_INI_ALL |
phar.readonly | "1" | PHP_INI_ALL |
phar.require_hash | "1" | PHP_INI_ALL |
phar.cache_list | "" | PHP_INI_SYSTEM |
post_max_size | "8M" | PHP_INI_PERDIR |
precision | "14" | PHP_INI_ALL |
realpath_cache_size | "16K" | PHP_INI_SYSTEM |
realpath_cache_ttl | "120" | PHP_INI_SYSTEM |
register_argc_argv | "1" | PHP_INI_PERDIR |
report_memleaks | "1" | PHP_INI_ALL |
report_zend_debug | "1" | PHP_INI_ALL |
request_order | "" | PHP_INI_PERDIR |
runkit.superglobal | "" | PHP_INI_PERDIR |
runkit.internal_override | "0" | PHP_INI_SYSTEM |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | "/usr/sbin/sendmail -t -i" | PHP_INI_SYSTEM |
serialize_precision | "-1" | PHP_INI_ALL | Hasta PHP 7.1.0, el valor por omisión era 17.
session.save_path | "" | PHP_INI_ALL |
session.name | "PHPSESSID" | PHP_INI_ALL |
session.save_handler | "files" | PHP_INI_ALL |
session.auto_start | "0" | PHP_INI_PERDIR |
session.gc_probability | "1" | PHP_INI_ALL |
session.gc_divisor | "100" | PHP_INI_ALL |
session.gc_maxlifetime | "1440" | PHP_INI_ALL |
session.serialize_handler | "php" | PHP_INI_ALL |
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_domain | "" | PHP_INI_ALL |
session.cookie_secure | "" | PHP_INI_ALL |
session.cookie_httponly | "" | PHP_INI_ALL |
session.cookie_samesite | "" | PHP_INI_ALL | Disponible desde PHP 7.3.0.
session.use_strict_mode | "0" | PHP_INI_ALL |
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL |
session.referer_check | "" | PHP_INI_ALL |
session.cache_limiter | "nocache" | PHP_INI_ALL |
session.cache_expire | "180" | PHP_INI_ALL |
session.use_trans_sid | "0" | PHP_INI_ALL |
session.trans_sid_tags | "a=href,area=href,frame=src,form=" | PHP_INI_ALL | Disponible desde PHP 7.1.0.
session.trans_sid_hosts | $_SERVER['HTTP_HOST'] | PHP_INI_ALL | Disponible desde PHP 7.1.0.
session.sid_length | "32" | PHP_INI_ALL | Disponible desde PHP 7.1.0.
session.sid_bits_per_character | "5" | PHP_INI_ALL | Disponible desde PHP 7.1.0.
session.upload_progress.enabled | "1" | PHP_INI_PERDIR |
session.upload_progress.cleanup | "1" | PHP_INI_PERDIR |
session.upload_progress.prefix | "upload_progress_" | PHP_INI_PERDIR |
session.upload_progress.name | "PHP_SESSION_UPLOAD_PROGRESS" | PHP_INI_PERDIR |
session.upload_progress.freq | "1%" | PHP_INI_PERDIR |
session.upload_progress.min_freq | "1" | PHP_INI_PERDIR |
session.lazy_write | "1" | PHP_INI_ALL |
session.hash_function | "0" | PHP_INI_ALL | Eliminado en PHP 7.1.0
session.hash_bits_per_character | "4" | PHP_INI_ALL | Eliminado en PHP 7.1.0
session.entropy_file | "" | PHP_INI_ALL | Eliminado en PHP 7.1.0.
session.entropy_length | "0" | PHP_INI_ALL | Eliminado en PHP 7.1.0.
short_open_tag | "1" | PHP_INI_PERDIR |
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL |
soap.wsdl_cache_enabled | 1 | PHP_INI_ALL |
soap.wsdl_cache_dir | /tmp | PHP_INI_ALL |
soap.wsdl_cache_ttl | 86400 | PHP_INI_ALL |
soap.wsdl_cache | 1 | PHP_INI_ALL |
soap.wsdl_cache_limit | 5 | PHP_INI_ALL |
sql.safe_mode | "0" | PHP_INI_SYSTEM |
sqlite3.extension_dir | NULL | PHP_INI_SYSTEM |
sqlite3.defensive | 1 | PHP_INI_SYSTEM | Disponible desde PHP 7.2.17 y 7.3.4 para libsqlite = 3.26.0.
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 |
sysvshm.init_mem | 10000 | PHP_INI_SYSTEM |
tidy.default_config | "" | PHP_INI_SYSTEM |
tidy.clean_output | "0" | PHP_INI_USER |
track_errors | "0" | PHP_INI_ALL | Obsoleta desde PHP 7.2.0, eliminada en PHP 8.0.0
unserialize_callback_func | NULL | PHP_INI_ALL |
uploadprogress.file.filename_template | "/tmp/upt_%s.txt" | PHP_INI_ALL |
upload_max_filesize | "2M" | PHP_INI_PERDIR |
max_file_uploads | 20 | PHP_INI_SYSTEM |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL |
user_agent | NULL | PHP_INI_ALL |
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM |
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM |
uopz.disable | "0" | PHP_INI_SYSTEM | Available as of uopz 5.0.2
uopz.exit | "0" | PHP_INI_SYSTEM | Available as of uopz 6.0.1
uopz.overloads | "1" | PHP_INI_SYSTEM | Available as of uopz 2.0.2. Removed as of uopz 5.0.0.
variables_order | "EGPCS" | PHP_INI_PERDIR |
vld.active | "0" | PHP_INI_SYSTEM |
vld.execute | "1" | PHP_INI_SYSTEM | 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 |
zlib.output_compression | "0" | PHP_INI_ALL |
zlib.output_compression_level | "-1" | PHP_INI_ALL |
zlib.output_handler | "" | PHP_INI_ALL |

User Contributed Notes

There are no user contributed notes for this page.


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 |
[PATH=] | PHP_INI_SYSTEM |

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 |
precision | "14" | PHP_INI_ALL |
serialize_precision | "-1" | PHP_INI_ALL | Antes de PHP 7.1.0, el valor predeterminado era 17.
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 |
zend.script_encoding | NULL | PHP_INI_ALL |
zend.detect-unicode | NULL | PHP_INI_ALL |
zend.signal_check | "0" | PHP_INI_SYSTEM |
zend.assertions | "1" | PHP_INI_ALL con restricciones |

He aquí una breve explicación de las directivas de configuración.

short_open_tag bool

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 no afecta a la abreviatura <?=, siempre está disponible.

precision int
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 int
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.
expose_php bool

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

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

Cuando se alcanza el tiempo de espera establecido en max_execution_time, PHP en tiempo de ejecución reducirá los recursos fluidamente. Si algo se atasca mientras esto sucede, el duro tiempo de espera se marca durante la cantidad establecida en segundos. Cuando se alcanza el duro tiempo de espera, PHP terminará absolutamente todo. Cuando se establece a 0, el duro tiempo de espera nunca se activará.

Cuando PHP se detenga desde el duro tiempo de espera, se verá así:

Fatal error: Maximum execution time of 30+2 seconds exceeded (terminated) in Unknown on line 0

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 bool

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 bool

Para verficar gestores de señales reemplazados en el apagado.

exit_on_timeout bool

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 |

He aquí una breve explicación de las directivas de configuración.

memory_limit int

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.

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 | Antes de PHP 7.0.16 y 7.1.2, el valor predeterminado era "16K"
realpath_cache_ttl | "120" | PHP_INI_SYSTEM |

Nota:

El uso de open_basedir deshabilitará la caché de realpath.

He aquí una breve explicación de las directivas de configuración.

realpath_cache_size int

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 int

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 |
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 |
enable_post_data_reading | "1" | PHP_INI_PERDIR |
post_max_size | "8M" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
auto_append_file | NULL | PHP_INI_PERDIR |
default_mimetype | "text/html" | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL |
input_encoding | "" | PHP_INI_ALL |
output_encoding | "" | PHP_INI_ALL |

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

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 bool
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.
enable_post_data_reading bool
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 int
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 omisión, 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

"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

Este ajuste se usa para módulos multibyte comos mbstring e iconv. El valor predeterminado es vacío.

output_encoding string

Este ajuste se usa para módulos multibyte comos mbstring e iconv. El valor predeterminado es vacío.

internal_encoding string

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 |
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 |
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 |
cgi.force_redirect | "1" | PHP_INI_SYSTEM |
cgi.nph | "0" | PHP_INI_SYSTEM |
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM |
cgi.rfc2616_headers | "0" | PHP_INI_ALL |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM |
fastcgi.logging | "1" | PHP_INI_SYSTEM |

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, no un prefijo.

El valor predeterminado permite abrir cualquier fichero.

Nota:

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.

Nota:

El uso de open_basedir establece realpath_cache_size en 0 y por lo tanto deshabilita la caché de realpath.

Precaución

open_basedir es solo una red de seguridad adicional, que de ninguna manera es exhaustiva y, por lo tanto, no se puede confiar en ella cuando se necesita seguridad.

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.

cgi.check_shebang_line bool

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 bool

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 bool

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 bool

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 bool

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 bool

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 |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
max_input_nesting_level | 64 | PHP_INI_PERDIR |
max_input_vars | 1000 | PHP_INI_PERDIR |
upload_max_filesize | "2M" | PHP_INI_PERDIR |
max_file_uploads | 20 | PHP_INI_SYSTEM |

He aquí una breve explicación de las directivas de configuración.

file_uploads bool

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 int

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 int

El número máximo de ficheros a subir permitidos de forma simultánea. 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 | Eliminado en PHP 7.2.0

He aquí una breve explicación de las directivas de configuración.

sql.safe_mode bool

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.

Advertencia

Esta característica ha sido ELIMINADA en PHP 7.2.0.

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 |

He aquí una breve explicación de las directivas de configuración.

windows_show_crt_warning bool

Esta directiva muestra las advertencias CRT de Windows cuando está establecida.

User Contributed Notes

andre dot wetter at myelco dot ch 23-Mar-2021 09:55
If you use Microsoft IIS Windows and want to use open_basedir restrictions with multiple dirs you have to set them into single quotes in the main config xml file of IIS (C:\Windows\System32\inetsrv\config\applicationHost.config). Works fine in IIS 10.

Multiple files with single quotes and ; for windows:
"C:\php\php-cgi.exe|-d open_basedir='C:\Windows\Temp\;D:\mywebsite1\'"

Only one dir works fine without single quotes:
"C:\php\php-cgi.exe|-d open_basedir=D:\mywebsite1\"

In my main config xml file of IIS there are 2 nodes to set per website and the definitions have to be equal:
configuration\Location\system.webServer\handlers\add
configuration\system.webServer\fastCgi
Simone Pellegatta 19-Jan-2021 12:08
Be careful while using auto_prepend_file.

When the custom exception handler, set by set_exception_handler(), handles an uncaught exception, it interrupts the execution of every script.

If the script with the unhandled exception has been automatically prepended or included by an automatically prepended script, however, the main script will continue running anyway.

This could cause several issues: when we think that throwing an exception would automatically interrupt the current application, a whole chunk of code is going to run anyway.
Anton Bannikov 22-Apr-2020 02:40
I had a problem with 'open_basedir =' string in php.ini. This string was writtren in VirtualHost Directory directive of Apache2 and successfully rewrote the same php.ini setting! It happened with VestaCP, but I think, it's a common way. Goog luck!
luisdev 03-Mar-2020 02:59
https://haydenjames.io/understanding-php-memory_limit/ explains the memory_limit setting nicely.
diamondeagle at webmail dot co dot za 15-Aug-2019 11:14
Note regarding the upload_tmp_dir setting and UNC Paths:

When using PHP on Windows OS and IIS FastCGI, if you need to use a UNC path to a folder on a network drive for the upload_tmp_dir setting then you must use three \ characters at the front of the UNC path.

Windows and PHP use the first slash as an escape character, so if you only use two slashes then it passes a UNC path with just one backslash. That is not valid for UNC paths and you many experience problems when uploading files, such as errors saying that "PHP is missing a temporary folder".

Correct:
upload_tmp_dir = "\\\path\to\your\folder"

Incorrect:
upload_tmp_dir = "\\path\to\your\folder"
fernandobasso dot br at gmail dot com 17-Oct-2016 08:06
This might help in case someone happens to maintain old applications with a charset other than utf-8.

According to the docs, you can override the default charset if you use `header()`.

Suppose php.ini sets the default_charset to "UTF-8", but you need a legacy charset, like ISO-8859-1.

Still,

<?php header('Content-Type: text/html; Charset=ISO-8859-1'); ?>

would not override the charset, just add it as well and the result
was a response header like (note the two charsets):

    Content-Type:"text/html; Charset=ISO-8859-1;CHARSET=Windows-1252"

I found it strange the default one as `charset` with a lowercase `c`
as opposed to my custom charset with an uppercase `C`.

What solved was to _override_ the charset using all lowercase letters
as well for the word “charset”:

<?php header('content-type: text/html; charset=ISO-8859-1'); ?>

Then, the double charset from the response headers disappeared, and only the single, custom charset remained.
dougal at gunters dot org 03-Mar-2016 05:11
It appears that if you use both the 'include_path' directives and 'open_basedir', that file searches will hit the include path *first*, before local files. But if 'open_basedir' is not in use, then local files are found first. For example, suppose you have code in '/var/www/myfile.php' which does:

<?php
  require_once('config.php');
?>

Further, assume that there is a local file '/var/www/config.php', and there is also a file '/var/local/php/config.php'.

Next, if your php.ini has:

  include_path = /var/local/php/

Normally, this would look for '/var/www/config.php' first, and if not found, then it would try '/var/local/php/config.php'.

But if you also have this in php.ini:

  open_basedir = /var/www/:/var/local/php/

Then the require would reverse the order of the search, and load '/var/local/php/config.php', even when the local 'config.php' file exists.

Furthermore, if include_path contains directories not in open_basedir, you can end up with a fatal error. For example, change the directive to:

  open_basedir = /var/www/:/var/local/includes/php/

Now the require will first find '/var/local/php/config.php' from the include_path, try to include it, but be unable to because of the open_basedir restrictions.
leo at korfu dot cz 29-May-2006 03:45
"If the size of post data is greater than post_max_size..."

It seems that a more elegant way is comparison between post_max_size and $_SERVER['CONTENT_LENGTH']. Please note that the latter includes not only size of uploaded file plus post data but also multipart sequences. Leo


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
  • Clases/Objetos
  • CommonMark
  • COM
  • Componere
  • Ctype
  • CUBRID
  • cURL
  • Fecha/Hora
  • DBA
  • dBase
  • Direct IO
  • Directorios
  • DOM
  • Data Structures
  • Eio
  • Enchant
  • Manejo de errores
  • Ev
  • Event
  • Ejecución de programas
  • Exif
  • Expect
  • FANN
  • FDF
  • FFI
  • Fileinfo
  • Sistema de Ficheros
  • Filter
  • Gestor de procesos FastCGI
  • FTP
  • Manejo de Funciones
  • Gearman
  • Gender
  • GeoIP
  • Gettext
  • Gmagick
  • GMP
  • GnuPG
  • Hash
  • HRTime
  • Firebird/InterBase
  • IBM DB2
  • iconv
  • Igbinary
  • GD
  • ImageMagick
  • IMAP
  • Opciones/Info de PHP
  • Inotify
  • intl
  • JSON
  • LDAP
  • libxml
  • Lua
  • LuaSandbox
  • LZF
  • Mail
  • Mailparse
  • Math
  • Cadenas de caracteres multibyte
  • Mcrypt
  • Memcache
  • Memcached
  • Mhash
  • Misc.
  • mqseries
  • MySQL (Original)
  • Mysql_xdevapi
  • MySQLi
  • Mysqlnd
  • Network
  • OAuth
  • OCI8
  • OPcache
  • OpenAL
  • OpenSSL
  • Control de la salida
  • parallel
  • 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
  • phpdbg
  • POSIX
  • PS
  • Pspell
  • pthreads
  • Quickhash
  • Radius
  • Random
  • Rar
  • Readline
  • Recode
  • Reflection
  • Rnp
  • RpmInfo
  • RRD
  • runkit
  • ScoutAPM
  • Seaslog
  • Semaphore
  • Sesiones
  • Memoria compartida
  • Simdjson
  • SimpleXML
  • SNMP
  • SOAP
  • Sockets
  • Sodium
  • Solr
  • SPL
  • SQLite3
  • SQLSRV
  • ssdeep
  • SSH2
  • Statistics
  • Stomp
  • Flujos
  • Strings
  • SVM
  • SVN
  • Swoole
  • Sync
  • Taint
  • TCP
  • Tidy
  • Tokenizer
  • Trader
  • UI
  • ODBC
  • uopz
  • URLs
  • V8js
  • Manejo de variables
  • var_representation
  • Varnish
  • WDDX
  • win32service
  • WinCache
  • wkhtmltox
  • xattr
  • xdiff
  • Xhprof
  • XLSWriter
  • Analizador XML
  • XMLDiff
  • XMLReader
  • XML-RPC
  • XMLWriter
  • XSL
  • Yac
  • 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

  • Fecha/Hora

  • Directorios

  • Manejo de errores

  • Ejecución de programas

  • Sistema de Ficheros

  • Gestor de procesos FastCGI

  • Manejo de Funciones

  • Hash

  • Opciones/Info de PHP

  • JSON

  • Mail

  • Math

  • Misc.

  • Network

  • OPcache

  • Control de la salida

  • Hash de contraseñas

  • PCRE

  • Random

  • Reflection

  • SPL

  • Flujos

  • Strings

  • URLs

  • Manejo de variables

Bundled

Extensiones incorporadas en PHP.

  • Apache

  • BC Math

  • Calendario

  • COM

  • Ctype

  • DBA

  • Exif

  • FFI

  • Fileinfo

  • Filter

  • FTP

  • HRTime

  • iconv

  • GD

  • intl

  • Cadenas de caracteres multibyte

  • Mhash

  • PCNTL

  • PDO

  • Phar

  • phpdbg

  • POSIX

  • Semaphore

  • Sesiones

  • Memoria compartida

  • Sockets

  • SQLite3

  • Tokenizer

  • Zlib

Extensiones externas

Estas extensiones vienen con PHP, pero para poder compilarlas, se requieren bibliotecas externas.

  • Bzip2

  • cURL

  • DOM

  • Enchant

  • Gettext

  • GMP

  • IMAP

  • LDAP

  • libxml

  • 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

  • SimpleXML

  • SNMP

  • SOAP

  • Sodium

  • Tidy

  • ODBC

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

  • APCu

  • CommonMark

  • Componere

  • CUBRID

  • dBase

  • Direct IO

  • Data Structures

  • Eio

  • Ev

  • Event

  • Expect

  • FANN

  • FDF

  • Gearman

  • Gender

  • GeoIP

  • Gmagick

  • GnuPG

  • Firebird/InterBase

  • IBM DB2

  • Igbinary

  • ImageMagick

  • Inotify

  • Lua

  • LuaSandbox

  • LZF

  • Mailparse

  • Mcrypt

  • Memcache

  • Memcached

  • mqseries

  • MySQL (Original)

  • Mysql_xdevapi

  • OAuth

  • OpenAL

  • parallel

  • Parle

  • CUBRID (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MS SQL Server (PDO)

  • PS

  • pthreads

  • Quickhash

  • Radius

  • Rar

  • Recode

  • Rnp

  • RpmInfo

  • RRD

  • runkit

  • ScoutAPM

  • Seaslog

  • Simdjson

  • Solr

  • SQLSRV

  • ssdeep

  • SSH2

  • Statistics

  • Stomp

  • SVM

  • SVN

  • Swoole

  • Sync

  • Taint

  • TCP

  • Trader

  • UI

  • uopz

  • V8js

  • var_representation

  • Varnish

  • WDDX

  • win32service

  • WinCache

  • wkhtmltox

  • xattr

  • xdiff

  • Xhprof

  • XLSWriter

  • XMLDiff

  • XML-RPC

  • Yac

  • Yaconf

  • Yaf

  • Yaml

  • Yar

  • YAZ

  • Mensajería de 0MQ

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

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.

  • ImageMagick

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • Oracle (PDO)

  • PS

  • Rnp

  • XML-RPC

User Contributed Notes

There are no user contributed notes for this page.


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
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 | OCICollection::assignElem | OCI8
ocibindbyname | oci_bind_by_name() | OCI8
ocicancel | oci_cancel() | OCI8
ocicloselob | OCILob::close | OCI8
ocicollappend | OCICollection::append | OCI8
ocicollassign | OCICollection::assign | OCI8
ocicollmax | OCICollection::max | OCI8
ocicollsize | OCICollection::size | OCI8
ocicolltrim | OCICollection::trim | OCI8
ocicolumnisnull | oci_field_is_null() | OCI8
ocicolumnname | oci_field_name() | OCI8
ocicolumnprecision | oci_field_precision() | OCI8
ocicolumnscale | oci_field_scale() | OCI8
ocicolumnsize | oci_field_size() | OCI8
ocicolumntype | oci_field_type() | OCI8
ocicolumntyperaw | oci_field_type_raw() | OCI8
ocicommit | oci_commit() | OCI8
ocidefinebyname | oci_define_by_name() | OCI8
ocierror | oci_error() | OCI8
ociexecute | oci_execute() | OCI8
ocifetch | oci_fetch() | OCI8
ocifetchinto | oci_fetch_array(), oci_fetch_row(), oci_fetch_assoc(), oci_fetch_object() | OCI8
ocifetchstatement | oci_fetch_all() | OCI8
ocifreecollection | OCICollection::free | OCI8
ocifreecursor | oci_free_statement() | OCI8
ocifreedesc | oci_free_descriptor() | OCI8
ocifreestatement | oci_free_statement() | OCI8
ocigetelem | OCICollection::getElem | OCI8
ociinternaldebug | oci_internal_debug() | OCI8
ociloadlob | OCILob::load | OCI8
ocilogon | oci_connect() | OCI8
ocinewcollection | oci_new_collection() | OCI8
ocinewcursor | oci_new_cursor() | OCI8
ocinewdescriptor | oci_new_descriptor() | OCI8
ocinlogon | oci_new_connect() | OCI8
ocinumcols | oci_num_fields() | OCI8
ociparse | oci_parse() | OCI8
ocipasswordchange | oci_password_change() | OCI8
ociplogon | oci_pconnect() | OCI8
ociresult | oci_result() | OCI8
ocirollback | oci_rollback() | OCI8
ocisavelob | OCILob::save | OCI8
ocisavelobfile | OCILob::import | OCI8
ociserverversion | oci_server_version() | OCI8
ocisetprefetch | oci_set_prefetch() | OCI8
ocistatementtype | oci_statement_type() | OCI8
ociwritelobtofile | OCILob::export | OCI8
ociwritetemporarylob | OCILob::writeTemporary | OCI8
odbc_do | odbc_exec() | ODBC
odbc_field_precision | odbc_field_len() | ODBC
pg_clientencoding | pg_client_encoding() | PostgreSQL
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL
pos | current() | 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. Las siguientes palabras no pueden utilizarse 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. Sin embargo, se permiten como propiedades, constantes y métodos de clases, interfaces y traits, excepto que la clase no se pueda usar como nombre de constante.

Palabras reservadas de PHP
__halt_compiler() | abstract | and | array() | as
break | callable | case | catch | class
clone | const | continue | declare | default
die() | do | echo | else | elseif
empty() | enddeclare | endfor | endforeach | endif
endswitch | endwhile | eval() | exit() | extends
final | finally | fn (a partir de PHP 7.4) | for | foreach
function | global | goto | if | implements
include | include_once | instanceof | insteadof | interface
isset() | list() | match (a partir de PHP 8.0) | namespace | new
or | print | private | protected | public
require | require_once | return | static | switch
throw | trait | try | unset() | use
var | while | xor | yield | yield from
Constantes en tiempo de compilación
__CLASS__ | __DIR__ | __FILE__ | __FUNCTION__ | __LINE__ | __METHOD__
__NAMESPACE__ | __TRAIT__ |  |  |  |

User Contributed Notes

Johnny D. 22-May-2020 06:37
const FORBIDDEN_TYPES = [
    'null',

    'bool',
    'false',
    'true',

    'int',
    'float',

    'string',
];
Thomas Hansen 15-Aug-2016 10:08
Please note that reserved words are still not allowed to be used as namespace or as part of it:

<?php
namespace MyNameSpace\List;

class Test
{
}
?>

This will fail with a Parse error:  syntax error, unexpected 'List' (T_LIST), expecting identifier (T_STRING)
martindilling at gmail dot com 15-Apr-2013 10:20
RegEx to find all the keywords:

\b(
(a(bstract|nd|rray|s))|
(c(a(llable|se|tch)|l(ass|one)|on(st|tinue)))|
(d(e(clare|fault)|ie|o))|
(e(cho|lse(if)?|mpty|nd(declare|for(each)?|if|switch|while)|val|x(it|tends)))|
(f(inal|or(each)?|unction))|
(g(lobal|oto))|
(i(f|mplements|n(clude(_once)?|st(anceof|eadof)|terface)|sset))|
(n(amespace|ew))|
(p(r(i(nt|vate)|otected)|ublic))|
(re(quire(_once)?|turn))|
(s(tatic|witch))|
(t(hrow|r(ait|y)))|
(u(nset|se))|
(__halt_compiler|break|list|(x)?or|var|while)
)\b
Chris 04-Oct-2012 04:33
Here they are as arrays:

<?php
$keywords = array('__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor');

$predefined_constants = array('__CLASS__', '__DIR__', '__FILE__', '__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__', '__TRAIT__');
?>

Along with get_defined_functions() and get_defined_constants(), this can be useful for checking eval() statements.


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().
Exception
ErrorException
php_user_filter
Closure
La clase final predefinida Closure se usa para representar funciones anónimas.
Generator
La clase final predefinida Generator se usa para representar generadores.
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 (int)
La versión "mayor" actual de PHP como valor integer (p.ej., int(5) en la versión "5.2.7-extra").
PHP_MINOR_VERSION (int)
La versión "menor" actual de PHP como valor integer (p.ej, int(2) en la versión "5.2.7-extra").
PHP_RELEASE_VERSION (int)
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").
PHP_VERSION_ID (int)
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").
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.
PHP_ZTS (int)
PHP_DEBUG (int)
PHP_MAXPATHLEN (int)
La longitud máxima de los nombres de ficheros (incluyendo directorios) admitida por la compilación de PHP.
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.
PHP_INT_MAX (int)
El número entero más grande admitido en esta compilación de PHP. Normalmente int(2147483647) en sistemas de 32 bits y int(9223372036854775807) en sistemas de 64 bits.
PHP_INT_MIN (int)
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. Usualmente, PHP_INT_MIN === ~PHP_INT_MAX.
PHP_INT_SIZE (int)
El tamaño de un número entero en bytes en esta compilación de PHP.
PHP_FLOAT_DIG (int)
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 positivo de punto flotante representable. Si necesita el menor número de punto flotante negative representable, use - PHP_FLOAT_MAX. 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)
El directorio por defecto donde buscar las extensiones cargables dinámicamente (a menos que sea sobreescrito por extension_dir). Por defecto es PHP_PREFIX (o PHP_PREFIX . "\\ext" en Windows).
PHP_PREFIX (string)
El valor de "--prefix" usado en la configuración. En Windows, es el valor --with-prefix que se estableció en la configuración.
PHP_BINDIR (string)
El valor --bindir se estableció en la configuración. En Windows, es el valor --with-prefix que se estableció en la configuración.
PHP_BINARY (string)
Especifica la ruta de los binarios de PHP durante la ejecución del script.
PHP_MANDIR (string)
Especifica dónde están instalados los manuales.
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 (int)
Constante de informe de error
E_WARNING (int)
Constante de informe de error
E_PARSE (int)
Constante de informe de error
E_NOTICE (int)
Constante de informe de error
E_CORE_ERROR (int)
Constante de informe de error
E_CORE_WARNING (int)
Constante de informe de error
E_COMPILE_ERROR (int)
Constante de informe de error
E_COMPILE_WARNING (int)
Constante de informe de error
E_USER_ERROR (int)
Constante de informe de error
E_USER_WARNING (int)
Constante de informe de error
E_USER_NOTICE (int)
E_RECOVERABLE_ERROR (int)
Constante de informe de error.
E_DEPRECATED (int)
Constante de informe de error.
E_USER_DEPRECATED (int)
Constante de informe de error.
E_ALL (int)
Constante de informe de error.
E_STRICT (int)
Constante de informe de error.
__COMPILER_HALT_OFFSET__ (int)
true (bool)
Ver también Booleans.
false (bool)
Ver también Booleans.
null (null)
Ver también Null.
PHP_WINDOWS_EVENT_CTRL_C (int)
El evento CTRL+C en Windows. Disponible a partir de PHP 7.4.0 (sólo para Windows).
PHP_WINDOWS_EVENT_CTRL_BREAK (int)
El evento CTRL+BREAK en Windows. Disponible a partir de PHP 7.4.0 (sólo para Windows).

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

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 | float | bool | string
true | false | null | 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 mixed numeric

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
AddressInfo | socket_addrinfo_lookup() | socket_addrinfo_bind(), socket_addrinfo_connect(), socket_addrinfo_explain(), | None | AddressInfo (extensión sockets)
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() | Manejar cURL
curl_multi | curl_multi_init() | curl_multi_errno(), curl_multi_exec(), curl_multi_info_read(), curl_multi_remove_handle(), curl_multi_select(), curl_multi_setopt() | curl_multi_close() | cURL multi handle
curl_share | curl_share_init() | curl_share_errno(), curl_share_setopt() | curl_share_close() | cURL share handle
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | 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
enchant_broker | enchant_broker_init() | enchant_broker_describe(), enchant_broker_dict_exists(), enchant_broker_get_dict_path(), enchant_broker_get_error(), enchant_broker_list_dicts(), enchant_broker_set_dict_path(), enchant_broker_set_ordering() | enchant_broker_free() | Enchant broker (a partir de PHP 8.0.0)
enchant_dict | enchant_broker_request_dict() enchant_broker_request_pwl_dict() | enchant_dict_add_to_personal(), enchant_dict_add_to_session(), enchant_dict_check(), enchant_dict_describe(), enchant_dict_get_error(), enchant_dict_is_in_session(), enchant_dict_store_replacement(), enchant_dict_suggest() | enchant_broker_free_dict() | Enchant dictionary (a partir de PHP 8.0.0)
fdf | fdf_open() | fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() | fdf_close() | 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(), 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
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
interbase blob | ibase_blob_create(), ibase_blob_import(), ibase_blob_open() | ibase_blob_add(), ibase_blob_cancel(), ibase_blob_echo(), ibase_blob_get(), ibase_blob_info() | ibase_blob_close()
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | 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
mailparse_mail_structure | mailparse_msg_create() mailparse_msg_parse_file() | mailparse_msg_extract_part_file() mailparse_msg_extract_part() mailparse_msg_extract_whole_part_file() mailparse_msg_get_part_data() mailparse_msg_get_part() mailparse_msg_get_structure() mailparse_msg_parse() | mailparse_msg_free()
mysql link | mysql_connect() | mysql_affected_rows(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Enlace a una base de datos MySQL
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | 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() | OCICollection::append(), OCICollection::assign(), OCICollection::assignElem(), OCICollection::getElem(), OCICollection::max(), OCICollection::size(), OCICollection::trim() | OCICollection::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() | OCILob::append(), OCILob::close(), OCILob::eof(), OCILob::erase(), OCILob::export(), OCILob::flush(), OCILob::getBuffering(), OCILob::import(), OCILob::load(), OCILob::read(), OCILob::rewind(), OCILob::save(), OCILob::saveFile(), OCILob::seek(), OCILob::setBuffering(), OCILob::size(), OCILob::tell(), OCILob::truncate(), OCILob::write(), OCILob::writeTemporary(), OCILob::writeToFile(), oci_lob_copy(), oci_lob_is_equal() | OCILob::free() | 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 | Enlace a la base de datos Birdstep (a partir de PHP 7.3.0)
birdstep result | Birdstep resultado (a partir de PHP 7.3.0)
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
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_meta_data(), 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_meta_data(), 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
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 8.0.0)
Socket | socket_accept(), socket_addrinfo_bind(), socket_addrinfo_connect(), socket_create(), socket_create_listen(), socket_import_stream(), socket_wsaprotocol_info_import() | socket_accept(), socket_bind(), socket_clear_error(), socket_connect(), socket_get_option(), socket_getpeername(), socket_getsockname(), socket_last_error(), socket_listen(), socket_read(), socket_recv(), socket_recvfrom(), socket_recvmsg(), socket_select(), socket_send(), socket_sendmsg(), socket_sendto(), socket_set_block(), socket_set_nonblock(), socket_set_option(), socket_shutdown(), socket_write(), socket_wsaprotocol_info_export(), socket_wsaprotocol_info_release() | socket_close() | Socket (sockets extension)
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
SSH2 Session | ssh2_connect() | ssh2_disconnect()
SSH2 Listener | ssh2_forward_listen()
SSH2 SFTP | ssh2_sftp()
SSH2 Publickey Subsystem | ssh2_publickey_init()
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() inflate_get_read_len(), inflate_get_status() | None | contexto de inflación incremental (a partir de PHP 8.0.0)

User Contributed Notes

Anonymous 28-Jul-2023 12:19
Resource of type "process" is returned by proc_open() and used by proc_close()


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(). La 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

marcus at synchromedia dot co dot uk 10-May-2022 09:50
It's not quite obvious what all the available parameters are for convert.quoted-printable-encode. If you want the stream filter to act the same way as the quoted_printable_encode function, you need these extra params, for example:

stream_filter_append(
    STDOUT,
    'convert.quoted-printable-encode',
    STREAM_FILTER_WRITE,
    [
        'line-break-chars' => PHP_EOL,
        'line-length' => 75,
    ]
);
echo stream_copy_to_stream(STDIN, STDOUT);

Without these extra params set, you may get no wrapping at all, or wrapping using the wrong line break sequence.


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 si eaaqyhfgrtl soporte de zlib se encuentra habilitado.

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 si el soporte de bz2 se encuentra habilitado.

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

TingSong 20-Feb-2023 03:43
To decompress a gzipped stream:

<?php
$stream = fopen('https://example.com/some/file.txt.gz', 'rb');
stream_filter_append($stream, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 15+16]);

// read the decompressed line directly
$line = fgets($stream);

// process the lines
?>

As the doc of zlib https://www.zlib.net/manual.html#Advanced

The 'window' parameter between 8 and 15 specified the window size from 28 to 2¹5 bytes. It can be added by 16 for wrapping with gzip header and trailer instead of zlib wrapper.

And, window could be -8..-15 for unwrapping RAW deflate data.
Anonymous 10-Feb-2021 06:37
To use the zlib.inflate filter with data originally written using gzcompress() or zlib.deflate, set the window option to 15 as outlined here: https://bugs.php.net/bug.php?id=68556

<?php
$fh = fopen(file_name, 'rb');
stream_filter_append($fh, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 15]);
$contents = stream_get_contents($fh);
fclose($fh);
bohwaz 08-Jul-2018 01:39
Please note that there is currently a bug in this feature. ftell(), fseek() and fstat() functions cannot be used. Writing to a stream after using this function will not change the stream position as it should.

See bug: https://bugs.php.net/bug.php?id=49874

Also the zlib filters don't work with php://temp, php://memory and php://input streams, nothing is outputted to those streams.
Anonymous 21-Aug-2015 06:12
To read a gzip encoded stream from http
<?php
$opts = [
    "http" => [
        "method" => "GET",
        "header" => [ "Accept-Encoding: gzip" ],
    ]
];
$ctx = stream_context_create($opts);
$f = fopen("http://php.net", "r", false, $ctx);
// check  stream_get_meta_data($f)["wrapper_data"] has "Content-Encoding: gzip"
stream_filter_append($f, "zlib.inflate", STREAM_FILTER_READ, ["window" => 30]);
echo stream_get_contents($f); // any stream processing
fclose($f);


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

alefinvest at outlook dot com 06-Aug-2021 06:47
That was hard to fetch this page mentioned in note by other user long time ago.
I intended to read Appendix P to find some code examples.
Wondering how to implement custom transport extension for php on our server tto be used with some nowadays technologies research.
https://www.php.net/manual/ru/function.stream-context-create.php#75211


Dominio de Internet: TCP, UDP, SSL, y TLS

ssl://, tls://, sslv2:// & sslv3://.

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.

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://.

  • 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 portno debe ser definido como 0.

Nota: Los sockets de dominio Unix no son compatibles en Windows.

User Contributed Notes

Matthew Fortune 16-Feb-2007 03:03
It appears that fsockopen prior to php5 did not need the unix:// qualifier when opening a unix domain socket:

php4: fsockopen("/tmp/mysocket"......);

php5: fsockopen("unix:///tmp/mysocket"......);

This caught me out when upgrading.


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 int. false es un bool 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() | bool : 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; | bool | true | false | true | false
$x = true; | bool | false | false | true | true
$x = 1; | int | false | false | true | true
$x = 42; | int | false | false | true | true
$x = 0; | int | true | false | true | false
$x = -1; | int | 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

Jeroen 14-Jul-2023 04:26
Be aware of the difference between checking the *value* of an array item, and checking the *existence* of an array item:
<?php
$arr = [
  'x' => 0,
  'y' => null,
];

isset($arr['x']); // true, same as isset(0)
isset($arr['y']); // false, same as isset(null)

array_key_exists('y', $arr); // true, though the value is null
array_key_exists('z', $arr); // false
ray dot paseur at SometimesUsesGmail dot com 14-Feb-2023 11:37
A colorized version of the loose comparison table is here (no copyright, nor attribution required)
https://iconoun.com/php_type_comparisons.php
Anonymous 17-Nov-2020 02:24
I noticed that some "magic" also happens when comparing strings with leading zeros with only two equal signs:

<?php
var_dump('1' == '01');
var_dump('01' == '000001');
?>

Output:
bool(true)
bool(true)

If the string contains only numbers all leading zeroes seem to be ignored.
TrickyFoxy 02-Jan-2020 08:25
<?php
echo md5('240610708') == md5('QNKCDZO') ? "equal" : "not equal"; // prints equal!!!
php at ckls dot net 20-Aug-2018 02:50
regarding the editors note in php at richardneill dot org note:
[Editor's note: As of PHP 5.4.4 this is no longer true. Integral strings that overflow into floating point numbers will no longer be considered equal.]

While this is true, there is still the following behaviour:
<?php
$x = "1";
$y = "+1";
var_dump($x == $x);
?>
outputs "bool(true)".
So still be wary of string-comparison where both strings might be interpreted as numbers.
mark at theanti dot social 29-Mar-2018 08:59
There is also 0.0 which is not identical to 0.

  $x = 0.0;
  gettype($x); // double
  empty($x); // true
  is_null($x); //false
  isset($x); // true
  is_numeric($x); // true
  $x ? true : false; // false
  $x == 0; // true
  $x == "0"; // true
  $x == "0.0"; // true
  $x == false; // true
  $x == null; // true
  $x === 0; // false
  $x === false; // false
  $x === null; // false
  $x === "0"; // false
  $x === "0.0"; // false
alt dot jl-3gi8b7l at binich dot com 10-Mar-2018 03:41
Here's how PHP handles loose and strict comparisons of default parameters in functions:

Very unintuitive:

<?php
function f($x='surprise')
    {
    if ($x == 'surprise')
        return $x; // returns 0 !!
    }

echo f(0);
?>

Here some further tests:

<?php
function f($x='surprise')
    {
    if ($x == 'surprise')
        return 'A:'.$x;
    if ($x === 'surprise')
        return 'B:'.$x;
    return 'C:'.$x;
    }

echo "\n".f(0); // A:0 !!
echo "\n".f(0.0); // A:0 !!
echo "\n".f(NULL); // C: !!
echo "\n".f(FALSE); // C:
echo "\n".f(); // A:surprise
echo "\n".f(''); // C:
echo "\n".f((integer)0); // A:0
echo "\n".f((string)0); // C:0
echo "\n".f('0'); // C:0
echo "\n".f(0.1); // C:0.1
echo "\n".f(array()); // C:Array
echo "\n".f('surprise'); // A:surprise
?>
biziclop at vipmail dot hu 12-Aug-2017 08:57
Want to strictly compare integers that may or may not be converted to floats (via PHPExcel import/export, etc.)? You are out of luck:

var_dump(   (int)1 ===   (int)1 ); // bool(true)
var_dump( (float)1 === (float)1 ); // bool(true)
var_dump( (float)1 ===   (int)1 ); // bool(false)
var_dump(   (int)1 === (float)1 ); // bool(false)

This slightly complicated function might help you:

function equal_numbers( $a, $b ){
  if( $a === $b )  return true;
  if(   is_int( $a ) && is_float( $b ))  return (float)$a === $b && $a ===   (int)$b;
  if( is_float( $a ) &&   is_int( $b ))  return   (int)$a === $b && $a === (float)$b;
  return false;
}

Here are some tests:

test(100, 100.0 ); // int(100) float(100) bool(true)
test(  0,  -0   ); // int(0)   int(0)     bool(true)
test( -0,  -0.0 ); // int(0)   float(-0)  bool(true)
test(  0, 1/0   ); // int(0)   float(INF) bool(false)
test(  0, acos(2));// int(0)   float(NAN) bool(false)
test(       PHP_INT_MAX * 10, 0 );             //float(92233720368547758080) int(0) bool(false)
test((float)PHP_INT_MAX,     PHP_INT_MAX     );//float(9223372036854775808)  int(9223372036854775807) bool(false)
test((float)PHP_INT_MAX / 2, PHP_INT_MAX / 2 );//float(4611686018427387904)  float(4611686018427387904) bool(true)

function test( $a, $b ){
  var_dump( $a, $b, equal_numbers( $a, $b ));
}
engineer dot morozov at gmail dot com 07-Feb-2016 03:23
If you want to calculate how much more/less items by the criterion

Example:

in loop:
$counter += intval($item->isValid()) <=> 0.5;

if $counter >= 0 - valid items are more then invalid on $counter
if $counter  < 0 - valid items are less then invalid on $counter
trexx68 25-Apr-2015 05:11
If you want to view the truth tables colorized, just:

1. Save a local copy of this page as an .html file,
2. View the page source with any text editor.
3. Replace the opening <head> tag so it will include this:

<head>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

4. Replace the closing </body> tag with this:

  <script>
    $( "td:contains('FALSE')" ).css("color", "red");
    $( "td:contains('TRUE')" ).css("color", "green");
  </script>
</body>

5. Save the file, and view it on your browser.  Enjoy.
aravind dot a dot padmanabhan at gmail dot com 22-Apr-2015 02:31
please note that

$x = 0.0 ;
print empty($x); // returns 1 (true)

$x = "0.0";
print empty($x); // returns blank (false);
Anonymous 16-Oct-2014 06:19
The loose comparison chart is missing a few things.

array(1)==true returns true.

also:

(int)array(1) === 1 returns true

This is symmetric:

array(1) === (array)1 returns true

but the loose comparison

array(1)==1 still returns false.
blue dot hirano at gmail dot com 07-Sep-2014 02:29
The truth tables really ought to be colorized; they're very hard to read as they are right now (just big arrays of TRUE and FALSE).

Also, something to consider: clustering the values which compare similarly (like is done on qntm.org/equality) would make the table easier to read as well. (This can be done simply by hand by rearranging the order of headings to bring related values closer together).
Anonymous 21-Nov-2013 01:43
I'm running PHP 5.5.3.

This is a correction to one of the previous posts.

<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //false
?>

Output is:

true, false, false
crazy888s at hotmail dot com 14-Dec-2012 06:14
PHP's loose comparisons can be a huge convenience when used properly! It's extremely helpful to just remember the following are always FALSE:

null, false, "", 0, "0", array()

If your application never depends on a particular "empty/false/null/0/not set" value type, you won't have to worry about 99% of the other weird cases listed here. You won't need empty() or isset(). And ALL variable types will always work as expected for statements like:

if(boolean && !string){...}
if(array){...}
if(!null || int){...}

Consider the same when working with your database values.
php at richardneill dot org 12-Apr-2012 07:45
[Editor's note: As of PHP 5.4.4 this is no longer true. Integral strings that overflow into floating point numbers will no longer be considered equal.]

Be wary of string-comparison where both strings might be interpreted as numbers.  Eg:

$x="123456789012345678901234567890"; $y="123456789012345678900000000000";
echo  ($x==$y)?"equal":"not_equal";   #Prints equal !!

Both strings are getting converted to floats, then losing precision, then becoming equal :-(

Using "===" or making either of the strings non-numeric will prevent this.
[This is on a 32-bit machine, on a 64-bit, you will have to make the strings longer to see the effect]
Jouriy LYSENKO 17-Jun-2011 02:18
If $var not declared.

In php 5.2 :
<?php if($var) ?> - work

in php 5.3 :
<?php if($var) ?> - dont work and generate error E_NOTICE
php at benizi dot com 15-Feb-2010 10:31
It's interesting to note that 'empty()' and 'boolean : if($x)'
are paired as logical opposites, as are 'is_null()' and 'isset()'.
edgar at goodforall dot eu 15-Dec-2009 06:55
Some function to write out your own comparisson table in tsv format. Can be easily modified to add more testcases and/or binary functions. It will test all comparables against each other with all functions.

<?php
$funcs = array(
        /* Testing equality */
        'eq' => '==',
        'ne' => '!=',
        'gt' => '>',
        'lt' => '<',
        'ne2' => '<>',
        'lte' => '<=',
        'gte' => '>=',
        /* Testing identity */
        'id' => '===',
        'nid' => '!=='
);
class Test {
        protected $a;
        public $b;
        public function __construct($a,$b){
                $this->a = $a;
                $this->b = $b;
        }
        public function getab(){
                return $this->a.",". $this->b;
        }

}
$tst1 = new Test(1,2);
$tst2 = new Test(1,2);
$tst3 = new Test(2,2);
$tst4 = new Test(1,1);

$arr1 = array(1,2,3);
$arr2 = array(2,3,4);
$arr3 = array('a','b','c','d');
$arr4 = array('a','b','c');
$arr5 = array();

$comp1 = array(
        'ints' => array(-1,0,1,2),
        'floats' => array(-1.1,0.0,1.1,2.0),
        'string' => array('str', 'str1', '', '1'),
        'bools' => array(true, false),
        'null' => array(null),
        'objects' => array($tst1,$tst2,$tst3,$tst4),
        'arrays' => array($arr1, $arr2, $arr3, $arr4, $arr5)
);
$fbody = array();

foreach($funcs as $name => $op){
        $fbody[$name] = create_function('$a,$b', 'return $a ' . $op . ' $b;');
}

$table = array(array('function', 'comp1', 'comp2', 'f comp1 comp2', 'type'));
/* Do comparisons */
$comp2  = array();
foreach($comp1 as $type => $val){
        $comp2[$type] = $val;
}

foreach($comp1 as $key1 => $val1){
        foreach($comp2 as $key2 => $val2){
                addTableEntry($key1, $key2, $val1, $val2);
        }
}
$out = '';
foreach($table as $row){
        $out .= sprintf("%-20s\t%-20s\t%-20s\t%-20s\t%-20s\n", $row[0], $row[1], $row[2], $row[3], $row[4]);
}

print $out;
exit;

function addTableEntry($n1, $n2, $comp1, $comp2){
        global $table, $fbody;
        foreach($fbody as $fname => $func){
                        foreach($comp1 as $val1){
  foreach($comp2 as $val2){
                                        $val = $func($val1,$val2);
                                                $table[] = array($fname, gettype($val1) . ' => ' . sprintval($val1), gettype($val2) .' => ' . sprintval($val2), gettype($val) . ' => ' . sprintval($val), gettype($val1) . "-" . gettype($val2) . '-' . $fname);
                                        }
                        }
        }
}

function sprintval($val){
        if(is_object($val)){
                return 'object-' . $val->getab();
        }
        if(is_array($val)){
                return implode(',', $val);
        }
        if(is_bool($val)){
                if($val){
                        return 'true';
                }
                return 'false';
        }
        return strval($val);
}

?>
info at shaelf dot ru 06-Jan-2008 01:51
Compare object
<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //true
?>
frank 14-Aug-2007 03:06
A comparison table for <=,<,=>,> would be nice...
Following are TRUE (tested PHP4&5):
NULL <= -1
NULL <= 0
NULL <= 1
!(NULL >= -1)
NULL >= 0
!(NULL >= 1)
That was a surprise for me (and it is not like SQL, I would like to have the option to have SQL semantics with NULL...).
Jan 29-Dec-2005 11:23
Note that php comparison is not transitive:

"php" == 0 => true
0 == null => true
null == "php" => false
jerryschwartz at comfortable dot com 26-Jul-2005 01:04
In some languages, a boolean is promoted to an integer (with a value of 1 or -1, typically) if used in an expression with an integer. I found that PHP has it both ways:

If you add a boolean with a value of true to an integer with a value of 3, the result will be 4 (because the boolean is cast as an integer).

On the other hand, if you test a boolean with a value of true for equality with an integer with a value of three, the result will be true (because the integer is cast as a boolean).

Surprisingly, at first glance, if you use either < or > as the comparison operator the result is always false (again, because the integer as cast as a boolean, and true is neither greater nor less than true).
tom 17-Jun-2005 02:27
<?php
if (strlen($_POST['var']) > 0) {
    // form value is ok
}
?>

When working with HTML forms this a good way to:

(A) let "0" post values through like select or radio values that correspond to array keys or checkbox booleans that would return FALSE with empty(), and;
(B) screen out $x = "" values, that would return TRUE with isset()!

Because HTML forms post values as strings, this is a good way to test variables!

[[Editor Note: This will create a PHP Error of level E_NOTICE if the checked variable (in this case $_POST['var']) is undefined. It may be used after (in conjuection with) isset() to prevent this.]]
aidan at php dot net 24-Jan-2005 07:00
The way PHP handles comparisons when multiple types are concerned is quite confusing.

For example:
"php" == 0

This is true, because the string is casted interally to an integer. Any string (that does not start with a number), when casted to an integer, will be 0.


Lista de componentes léxicos del analizador

Varias partes del lenguaje PHP son representadas internamente por tokens. Un fragmento de código que contenga una secuencia no válida de tokens puede dar lugar a errores como Parse error: syntax error, unexpected token "==", expecting "(" in script.php on line 10." donde el token == está representado internamente por T_IS_EQUAL.

La siguiente tabla enumera todas los tokens. También están disponibles como constantes PHP.

Nota: Uso de las constantes T_*

Los valores de las constantes T_* se generan automáticamente basándose en la infraestructura del analizador subyacente de PHP. Esto significa que el valor concreto de un token puede cambiar entre dos versiones de PHP. 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.

Para hacer uso de las constantes T_* a través de múltiples versiones de PHP, las constantes indefinidas pueden ser definidas por el usuario (usando números grandes como 10000) y una estrategia apropiada que funcione tanto con las versiones de PHP como con los valores T_*.

<?php
// Antes de PHP 7.4.0, T_FN no está definido.
defined('T_FN') || define('T_FN', 10001);

Componente léxico
Elemento | Sintaxis | Referencia
T_ABSTRACT | abstract | Abstracción de clases
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_ATTRIBUTE | #[ | attributes (disponible a partir de PHP 8.0.0)
T_BAD_CHARACTER |  | todo lo que haya por debajo de ASCII 32 excepto \t (0x09), \n (0x0a) y \r (0x0d) (disponible a partir de PHP 7.4.0)
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
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_COALESCE | ?? | operadores de comparación
T_COALESCE_EQUAL | ??= | operadores de asignación (disponible a partir de PHP 7.4.0)
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
T_DIV_EQUAL | /= | operadores de asignación
T_DNUMBER | 0.12, etc. | números de punto flotante
T_DO | do | do..while
T_DOC_COMMENT | /** */ | comentarios tipo PHPDoc
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
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
T_FN | fn | funciones flecha (disponible a partir de PHP 7.4.0)
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function | funciones
T_FUNC_C | __FUNCTION__ | constantes mágicas
T_GLOBAL | global | ámbito de las variables
T_GOTO | goto | control-structures.goto.html
T_HALT_COMPILER | __halt_compiler() | __halt_compiler
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)
T_INTERFACE | interface | Interfaces de objetos
T_INT_CAST | (int) o (integer) | type-casting
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_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
T_NEW | new | clases y objetos
T_NS_C | __NAMESPACE__ | espacios de nombres
T_NS_SEPARATOR | \ | espacios de nombres
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_NULLSAFE_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
T_POW_EQUAL | **= | operadores de asignación
T_PRINT | print() | print
T_PRIVATE | private | clases y objetos
T_PROTECTED | protected | clases y objetos
T_PUBLIC | public | 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_SPACESHIP | <=> | operadores de comparació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)
T_TRAIT_C | __TRAIT__ | __TRAIT__
T_TRY | try | Excepciones
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | conversión de tipos
T_USE | use | espacios de nombres
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
T_YIELD_FROM | yield from | generadores

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, PHP 7)
strlen -- Obtiene longitud de un string

Descripción
strlen ( string $string ) : int

Devuelve la longitud del string dado.

Explicación de la definición de una función
Parte | Descripción
strlen | El nombre de la función.
(PHP 4, PHP 5, PHP 7) | strlen() está disponible en todas las versiones de PHP 4, PHP 5 y 7
( 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.
int | Tipo de valor devuelto por esta función, en este caso un int (ejemplo: la longitud de un int se mide en números).

Podríamos escribir la definición de esta función de un modo genérico:

      nombre función ( tipo de parámetro   nombre parámetro ) : tipo de retorno

Muchas funciones tiene múltiples parametros, por ejemplo in_array(). Su prototipo sería:

      in_array ( mixed $needle, array $haystack , bool $strict = false ) : bool

¿Qué significa? in_array() devuelve un valor boolean, true si termina con éxito (Si la needle fue encontrada en el haystack) o false en caso de error (si la needle no fue encontrada en el haystack). El primer parámetro se llama needle y puede ser de muchos tipos, así que lo llamamos "mixed". Este mixed needle (que es lo que estamos buscando) bien puede ser un valor escalar (string, integer, o float), o un array. El haystack (el array en el que buscamos) es el segundo parámetro. El tercero es un parámetro opcional y lo llamamos strict. 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:

       preg_match ( string $pattern , string $subject , array &$matches = null,
       int $flags = 0 , int $offset = 0 ) : int|false

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, PHP 7)

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 7.3.1 como ejemplo, entonces el 7 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://github.com/php/php-src/issues. 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
    • AllowDynamicProperties::__construct - Construct a new AllowDynamicProperties attribute instance
    • 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::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_is_list - Checks whether a given array is a list
    • 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
    • Attribute::__construct - Construct a new Attribute instance
  • b
    • BackedEnum::from - Maps a scalar to an enum instance
    • BackedEnum::tryFrom - Maps a scalar to an enum instance or null
    • 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
    • BaseResult::getWarnings - Fetch warnings from last operation
    • BaseResult::getWarningsCount - Fetch warning count from last operation
    • 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 u obtiene la ruta de un 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
    • 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::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
    • 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
    • Client::getClient - Get client session
    • Client::__construct - Client constructor
    • cli_get_process_title - Returns the current process title
    • cli_set_process_title - Sets the process title
    • closedir - 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
    • Collection::add - Add collection document
    • Collection::addOrReplaceOne - Add or replace collection document
    • Collection::count - Get document count
    • Collection::createIndex - Create collection index
    • Collection::dropIndex - Drop collection index
    • Collection::existsInDatabase - Check if collection exists in database
    • Collection::find - Search for document
    • Collection::getName - Get collection name
    • Collection::getOne - Get one document
    • Collection::getSchema - Get schema object
    • Collection::getSession - Get session object
    • Collection::modify - Modify collection documents
    • Collection::remove - Remove collection documents
    • Collection::removeOne - Remove one collection document
    • Collection::replaceOne - Replace one collection document
    • Collection::__construct - Collection constructor
    • CollectionAdd::execute - Execute the statement
    • CollectionAdd::__construct - CollectionAdd constructor
    • CollectionFind::bind - Bind value to query placeholder
    • CollectionFind::execute - Execute the statement
    • CollectionFind::fields - Set document field filter
    • CollectionFind::groupBy - Set grouping criteria
    • CollectionFind::having - Set condition for aggregate functions
    • CollectionFind::limit - Limit number of returned documents
    • CollectionFind::lockExclusive - Execute operation with EXCLUSIVE LOCK
    • CollectionFind::lockShared - Execute operation with SHARED LOCK
    • CollectionFind::offset - Skip given number of elements to be returned
    • CollectionFind::sort - Set the sorting criteria
    • CollectionFind::__construct - CollectionFind constructor
    • CollectionModify::arrayAppend - Append element to an array field
    • CollectionModify::arrayInsert - Insert element into an array field
    • CollectionModify::bind - Bind value to query placeholder
    • CollectionModify::execute - Execute modify operation
    • CollectionModify::limit - Limit number of modified documents
    • CollectionModify::patch - Patch document
    • CollectionModify::replace - Replace document field
    • CollectionModify::set - Set document attribute
    • CollectionModify::skip - Skip elements
    • CollectionModify::sort - Set the sorting criteria
    • CollectionModify::unset - Unset the value of document fields
    • CollectionModify::__construct - CollectionModify constructor
    • CollectionRemove::bind - Bind value to placeholder
    • CollectionRemove::execute - Execute remove operation
    • CollectionRemove::limit - Limit number of documents to remove
    • CollectionRemove::sort - Set the sorting criteria
    • CollectionRemove::__construct - CollectionRemove constructor
    • ColumnResult::getCharacterSetName - Get character set
    • ColumnResult::getCollationName - Get collation name
    • ColumnResult::getColumnLabel - Get column label
    • ColumnResult::getColumnName - Get column name
    • ColumnResult::getFractionalDigits - Get fractional digit length
    • ColumnResult::getLength - Get column field length
    • ColumnResult::getSchemaName - Get schema name
    • ColumnResult::getTableLabel - Get table label
    • ColumnResult::getTableName - Get table name
    • ColumnResult::getType - Get column type
    • ColumnResult::isNumberSigned - Check if signed type
    • ColumnResult::isPadded - Check if padded
    • ColumnResult::__construct - ColumnResult constructor
    • CommonMark\CQL::__construct - CQL Construction
    • CommonMark\CQL::__invoke - CQL Execution
    • CommonMark\Interfaces\IVisitable::accept - Visitation
    • CommonMark\Interfaces\IVisitor::enter - Visitation
    • CommonMark\Interfaces\IVisitor::leave - Visitation
    • CommonMark\Node::accept - Visitation
    • CommonMark\Node::appendChild - AST Manipulation
    • CommonMark\Node::insertAfter - AST Manipulation
    • CommonMark\Node::insertBefore - AST Manipulation
    • CommonMark\Node::prependChild - AST Manipulation
    • CommonMark\Node::replace - AST Manipulation
    • CommonMark\Node::unlink - AST Manipulation
    • CommonMark\Node\BulletList::__construct - BulletList Construction
    • CommonMark\Node\CodeBlock::__construct - CodeBlock Construction
    • CommonMark\Node\Heading::__construct - Heading Construction
    • CommonMark\Node\Image::__construct - Image Construction
    • CommonMark\Node\Link::__construct - Link Construction
    • CommonMark\Node\OrderedList::__construct - Constructor OrderedList
    • CommonMark\Node\Text::__construct - Text Construction
    • CommonMark\Parse - Parsing
    • CommonMark\Parser::finish - Parsing
    • CommonMark\Parser::parse - Parsing
    • CommonMark\Parser::__construct - Parsing
    • CommonMark\Render - Rendering
    • CommonMark\Render\HTML - Rendering
    • CommonMark\Render\Latex - Rendering
    • CommonMark\Render\Man - Rendering
    • CommonMark\Render\XML - Rendering
    • compact - 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
    • 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)
    • CrudOperationBindable::bind - Bind value to placeholder
    • CrudOperationLimitable::limit - Set result limit
    • CrudOperationSkippable::skip - Number of operations to skip
    • CrudOperationSortable::sort - Sort results
    • 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_upkeep - Performs any connection upkeep checks
    • 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)
    • DatabaseObject::existsInDatabase - Check if object exists in database
    • DatabaseObject::getName - Get object name
    • DatabaseObject::getSession - Get session name
    • 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::createFromISO8601String - Creates a new DatePeriod object from an ISO8601 string
    • 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 instance 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
    • 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::getBasename - Obtener el nombre base del elemento actual DirectoryIterator
    • DirectoryIterator::getExtension - Obtiene la extensión de un fichero
    • DirectoryIterator::getFilename - Devuelve el nombre del fichero del elemento actual DirectoryIterator
    • DirectoryIterator::isDot - Determina si el elemento actual DirectoryIterator es '.' o '..'
    • 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
    • DocResult::fetchAll - Get all rows
    • DocResult::fetchOne - Get one row
    • DocResult::getWarnings - Get warnings from last operation
    • DocResult::getWarningsCount - Get warning count from last operation
    • DocResult::__construct - DocResult constructor
    • DOMAttr::isId - Verifica si un atributo es un ID definido.
    • DOMAttr::__construct - Crea un nuevo objeto DOMAttr
    • DOMCdataSection::__construct - Construye un nuevo objeto DOMCdataSection
    • DOMCharacterData::after - Adds nodes after the character data
    • DOMCharacterData::appendData - Añade el string de caracteres al final de los datos de carácter del nodo.
    • DOMCharacterData::before - Adds nodes before the node
    • DOMCharacterData::deleteData - Eliminar una serie de caracteres del nodo
    • DOMCharacterData::insertData - Inserta un string en la posición de 16-bit especificada
    • DOMCharacterData::remove - Removes the character data
    • DOMCharacterData::replaceData - Reemplaza un substring dentro de un nodo DOMCharacterData
    • DOMCharacterData::replaceWith - Replaces the character data with new nodes
    • DOMCharacterData::substringData - Extrae una serie de datos del nodo
    • DOMComment::__construct - Crea un nuevo objeto DOMComment
    • DOMDocument::adoptNode - Transfer a node from another document
    • DOMDocument::append - Appends nodes after the last child node
    • 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::prepend - Prepends nodes before the first child node
    • 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::replaceChildren - Replace children in document
    • 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::append - Appends nodes after the last child node
    • DOMDocumentFragment::appendXML - Añade información XML sin formato
    • DOMDocumentFragment::prepend - Prepends nodes before the first child node
    • DOMDocumentFragment::replaceChildren - Replace children in fragment
    • DOMDocumentFragment::__construct - Constructs a DOMDocumentFragment object
    • DOMElement::after - Adds nodes after the element
    • DOMElement::append - Appends nodes after the last child node
    • DOMElement::before - Adds nodes before the element
    • DOMElement::getAttribute - Devuelve el valor de un atributo
    • DOMElement::getAttributeNames - Get attribute names
    • 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::insertAdjacentElement - Insert adjacent element
    • DOMElement::insertAdjacentText - Insert adjacent text
    • DOMElement::prepend - Prepends nodes before the first child node
    • DOMElement::remove - Removes the element
    • DOMElement::removeAttribute - Elimina un atributo
    • DOMElement::removeAttributeNode - Elimina un atributo
    • DOMElement::removeAttributeNS - Elimina un atributo
    • DOMElement::replaceChildren - Replace children in element
    • DOMElement::replaceWith - Replaces the element with new nodes
    • 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::toggleAttribute - Toggle attribute
    • 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::getIterator - Retrieve an external iterator
    • 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::contains - Checks if node contains other node
    • DOMNode::getLineNo - Obtener el número de línea de un nodo
    • DOMNode::getNodePath - Obtener un XPath de un nodo
    • DOMNode::getRootNode - Get root node
    • 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::isEqualNode - Checks that both nodes are equal
    • 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::getIterator - Retrieve an external iterator
    • 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
    • enum_exists - Checks if the enum has been defined
    • 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 - Alias de Event::add
    • Event::addTimer - Alias de Event::add
    • Event::del - Makes event non-pending
    • Event::delSignal - Alias de Event::del
    • Event::delTimer - Alias de Event::del
    • 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 - Recursos ddisponibles asignados para esta base de eventos
    • 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::setFlags - Sets one or more flags to configure the eventual EventBase will be initialized
    • 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 Throwable 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
    • Executable::execute - Execute statement
    • ExecutionStatus::__construct - ExecutionStatus constructor
    • 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.
    • expression - Bind prepared statement variables as parameters
    • Expression::__construct - Expression constructor
    • 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 - Descarga todos los datos de la respuesta al cliente
    • 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
    • fclose - Cierra un puntero a un archivo abierto
    • fdatasync - Synchronizes data (but not meta-data) to the file
    • 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
    • FFI\CType::getAlignment - Description
    • FFI\CType::getArrayElementType - Description
    • FFI\CType::getArrayLength - Description
    • FFI\CType::getAttributes - Description
    • FFI\CType::getEnumKind - Description
    • FFI\CType::getFuncABI - Description
    • FFI\CType::getFuncParameterCount - Description
    • FFI\CType::getFuncParameterType - Description
    • FFI\CType::getFuncReturnType - Description
    • FFI\CType::getKind - Description
    • FFI\CType::getName - Description
    • FFI\CType::getPointerType - Description
    • FFI\CType::getSize - Description
    • FFI\CType::getStructFieldNames - Description
    • FFI\CType::getStructFieldOffset - Description
    • FFI\CType::getStructFieldType - Description
    • fflush - 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
    • Fiber::getCurrent - Gets the currently executing Fiber instance
    • Fiber::getReturn - Gets the value returned by the Fiber
    • Fiber::isRunning - Determines if the fiber is running
    • Fiber::isStarted - Determines if the fiber has started
    • Fiber::isSuspended - Determines if the fiber is suspended
    • Fiber::isTerminated - Determines if the fiber has terminated
    • Fiber::resume - Resumes execution of the fiber with a value
    • Fiber::start - Start execution of the fiber
    • Fiber::suspend - Suspends execution of the current fiber
    • Fiber::throw - Resumes execution of the fiber with an exception
    • Fiber::__construct - Creates a new Fiber instance
    • FiberError::__construct - Constructor to disallow direct instantiation
    • 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
    • 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::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
    • fpm_get_status - Devuelve el estado actual del pool de FPM
    • 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
    • fsync - Synchronizes changes to the file (including meta-data)
    • 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 - Get the Autonomous System Numbers (ASN)
    • geoip_continent_code_by_name - Get the two letter continent code
    • geoip_country_code3_by_name - Get the three letter country code
    • geoip_country_code_by_name - Get the two letter country code
    • geoip_country_name_by_name - Get the full country name
    • geoip_database_info - Get GeoIP Database information
    • geoip_db_avail - Determine if GeoIP Database is available
    • geoip_db_filename - Returns the filename of the corresponding GeoIP Database
    • geoip_db_get_all_info - Returns detailed information about all GeoIP database types
    • geoip_domain_by_name - Get the second level domain name
    • geoip_id_by_name - Get the Internet connection type
    • geoip_isp_by_name - Get the Internet Service Provider (ISP) name
    • geoip_netspeedcell_by_name - Get the Internet connection speed
    • geoip_org_by_name - Get the organization name
    • geoip_record_by_name - Returns the detailed City information found in the GeoIP Database
    • geoip_region_by_name - Get the country code and region
    • geoip_region_name_by_code - Returns the region name for some country and region code combo
    • geoip_setup_custom_directory - Set a custom directory for the GeoIP database
    • geoip_time_zone_by_country_and_region - Returns the time zone for some country and region code combo
    • 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 - Show largest possible random value
    • 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
    • getSession - Connect to a MySQL server
    • 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 static 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_debug_type - Gets the type name of a variable in a way that is suitable for debugging
    • 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_mangled_object_vars - Returns an array of mangled object properties
    • 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 - Random number
    • gmp_random_range - Get a uniformly selected integer
    • 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_deletekey - Delete a key from the keyring
    • gnupg_encrypt - Encripta el texto dado
    • gnupg_encryptsign - Encripta y firma un texto dado
    • gnupg_export - Exporta una llave
    • gnupg_getengineinfo - Returns the engine info
    • gnupg_geterror - Retorna el texto de error si una función falla
    • gnupg_geterrorinfo - Returns the error info
    • gnupg_getprotocol - Retorna el protocolo activo actualmente para todas las operaciones
    • gnupg_gettrustlist - Search the trust items
    • 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_listsignatures - List key signatures
    • 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 o 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
    • igbinary_serialize - Generates a compact, storable binary representation of a value
    • igbinary_unserialize - Creates a PHP value from a stored representation from igbinary_serialize
    • 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
    • imageavif - Exportar la imagen al navegador o a un fichero
    • 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
    • imagecreatefromavif - Crea una nueva imagen a partir de un fichero o de una URL
    • 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
    • imagecreatefromtga - Crea una nueva imagen a partir de un fichero o de una URL
    • 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 - Adjusts the levels of a particular image channel
    • 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 - Mutes the colors of the image
    • Imagick::blurImage - Añade un filtro de borrosidad a la imagen
    • Imagick::borderImage - Rodea la imagen con un borde
    • Imagick::brightnessContrastImage - Change the brightness and/or contrast of an image
    • 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 - Clips along the named paths from the 8BIM profile, if present
    • 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 - Apply color transformation to an image
    • 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 - Deletes an image property
    • 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 - Applies a custom convolution kernel to the image
    • 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 - Implements the discrete Fourier transform (DFT)
    • 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 - Returns a named attribute
    • 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 - Returns the image mime-type
    • 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 - Returns the ImageMagick quantum range
    • Imagick::getQuantumDepth - Obtiene la profundidad de la cuantía
    • Imagick::getQuantumRange - Devuelve el rango de cuantía de Imagick
    • Imagick::getRegistry - Get a StringRegistry entry
    • 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 - Formats a string with image details
    • 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 - Implements the inverse discrete Fourier transform (DFT)
    • 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 - Applies a user supplied kernel to the image according to the given morphology method.
    • 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 - Reads image from an array of filenames
    • 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 - Rotational blurs an image
    • 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 - Sets the image bias
    • 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_is_open - Check if the IMAP stream is still valid
    • 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
    • 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_parse_quantity - Get interpreted size from ini shorthand syntax
    • 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
    • InternalIterator::current - Return the current element
    • InternalIterator::key - Return the key of the current element
    • InternalIterator::next - Move forward to next element
    • InternalIterator::rewind - Rewind the Iterator to the first element
    • InternalIterator::valid - Check if current position is valid
    • InternalIterator::__construct - Private constructor to disallow direct instantiation
    • 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::setDate - Set a date fields
    • IntlCalendar::setDateTime - Set a date and time fields
    • 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
    • IntlTimeZone::__construct - Private constructor to disallow direct instantiation
    • 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()
    • json_validate - Checks if a string contains valid JSON
    • 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 - Combined linear congruential generator
    • 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_connect_wallet - Connect to an LDAP server
    • 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_count_references - Counts the number of references in a search result
    • 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_sync - Performs an extended operation
    • 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_external_entity_loader - Get the current external entity loader
    • 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::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
    • 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
    • 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 - Return character by Unicode code point value
    • 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 Unicode 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 - Replace ill-formed byte sequences with the substitute character
    • 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_pad - Pad a multibyte string to a certain length with another multibyte 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_create_iv - Creates an initialization vector (IV) from a random source
    • mcrypt_decrypt - Decrypts crypttext with given parameters
    • mcrypt_encrypt - Encrypts plaintext with given parameters
    • mcrypt_enc_get_algorithms_name - Returns the name of the opened algorithm
    • mcrypt_enc_get_block_size - Returns the blocksize of the opened algorithm
    • mcrypt_enc_get_iv_size - Returns the size of the IV of the opened algorithm
    • mcrypt_enc_get_key_size - Returns the maximum supported keysize of the opened mode
    • mcrypt_enc_get_modes_name - Returns the name of the opened mode
    • mcrypt_enc_get_supported_key_sizes - Returns an array with the supported keysizes of the opened algorithm
    • mcrypt_enc_is_block_algorithm - Checks whether the algorithm of the opened mode is a block algorithm
    • mcrypt_enc_is_block_algorithm_mode - Checks whether the encryption of the opened mode works on blocks
    • mcrypt_enc_is_block_mode - Checks whether the opened mode outputs blocks
    • mcrypt_enc_self_test - Runs a self test on the opened module
    • mcrypt_generic - This function encrypts data
    • mcrypt_generic_deinit - This function deinitializes an encryption module
    • mcrypt_generic_init - This function initializes all buffers needed for encryption
    • mcrypt_get_block_size - Gets the block size of the specified cipher
    • mcrypt_get_cipher_name - Gets the name of the specified cipher
    • mcrypt_get_iv_size - Returns the size of the IV belonging to a specific cipher/mode combination
    • mcrypt_get_key_size - Gets the key size of the specified cipher
    • mcrypt_list_algorithms - Gets an array of all supported ciphers
    • mcrypt_list_modes - Gets an array of all supported modes
    • mcrypt_module_close - Closes the mcrypt module
    • mcrypt_module_get_algo_block_size - Returns the blocksize of the specified algorithm
    • mcrypt_module_get_algo_key_size - Returns the maximum supported keysize of the opened mode
    • mcrypt_module_get_supported_key_sizes - Returns an array with the supported keysizes of the opened algorithm
    • mcrypt_module_is_block_algorithm - This function checks whether the specified algorithm is a block algorithm
    • mcrypt_module_is_block_algorithm_mode - Returns if the specified module is a block algorithm or not
    • mcrypt_module_is_block_mode - Returns if the specified mode outputs blocks or not
    • mcrypt_module_open - Opens the module of the algorithm and the mode to be used
    • mcrypt_module_self_test - This function runs a self test on the specified module
    • md5 - Calcula el 'hash' md5 de un string
    • md5_file - Calcula el resumen criptográfico md5 de un archivo dado
    • mdecrypt_generic - Decrypts data
    • 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
    • memory_reset_peak_usage - Reset the peak memory usage
    • 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 - Computes hash
    • mhash_count - Gets the highest available hash ID
    • mhash_get_block_size - Gets the block size of the specified hash
    • mhash_get_hash_name - Gets the name of the specified hash
    • mhash_keygen_s2k - Generates a key
    • microtime - 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
    • MongoDB\BSON\Binary::getData - Returns the Binary's data
    • MongoDB\BSON\Binary::getType - Returns the Binary's type
    • MongoDB\BSON\Binary::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Binary::serialize - Serialize a Binary
    • MongoDB\BSON\Binary::unserialize - Unserialize a Binary
    • MongoDB\BSON\Binary::__construct - Construct a new Binary
    • MongoDB\BSON\Binary::__toString - Returns the Binary's data
    • MongoDB\BSON\BinaryInterface::getData - Returns the BinaryInterface's data
    • MongoDB\BSON\BinaryInterface::getType - Returns the BinaryInterface's type
    • MongoDB\BSON\BinaryInterface::__toString - Returns the BinaryInterface's data
    • MongoDB\BSON\DBPointer::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\DBPointer::serialize - Serialize a DBPointer
    • MongoDB\BSON\DBPointer::unserialize - Unserialize a DBPointer
    • MongoDB\BSON\DBPointer::__construct - Construct a new DBPointer (unused)
    • MongoDB\BSON\DBPointer::__toString - Returns an empty string
    • MongoDB\BSON\Decimal128::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Decimal128::serialize - Serialize a Decimal128
    • MongoDB\BSON\Decimal128::unserialize - Unserialize a Decimal128
    • MongoDB\BSON\Decimal128::__construct - Construct a new Decimal128
    • MongoDB\BSON\Decimal128::__toString - Returns the string representation of this Decimal128
    • MongoDB\BSON\Decimal128Interface::__toString - Returns the string representation of this Decimal128Interface
    • MongoDB\BSON\fromJSON - Returns the BSON representation of a JSON value
    • MongoDB\BSON\fromPHP - Returns the BSON representation of a PHP value
    • MongoDB\BSON\Int64::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Int64::serialize - Serialize an Int64
    • MongoDB\BSON\Int64::unserialize - Unserialize an Int64
    • MongoDB\BSON\Int64::__construct - Construct a new Int64
    • MongoDB\BSON\Int64::__toString - Returns the string representation of this Int64
    • MongoDB\BSON\Javascript::getCode - Returns the Javascript's code
    • MongoDB\BSON\Javascript::getScope - Returns the Javascript's scope document
    • MongoDB\BSON\Javascript::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Javascript::serialize - Serialize a Javascript
    • MongoDB\BSON\Javascript::unserialize - Unserialize a Javascript
    • MongoDB\BSON\Javascript::__construct - Construct a new Javascript
    • MongoDB\BSON\Javascript::__toString - Returns the Javascript's code
    • MongoDB\BSON\JavascriptInterface::getCode - Returns the JavascriptInterface's code
    • MongoDB\BSON\JavascriptInterface::getScope - Returns the JavascriptInterface's scope document
    • MongoDB\BSON\JavascriptInterface::__toString - Returns the JavascriptInterface's code
    • MongoDB\BSON\MaxKey::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\MaxKey::serialize - Serialize a MaxKey
    • MongoDB\BSON\MaxKey::unserialize - Unserialize a MaxKey
    • MongoDB\BSON\MaxKey::__construct - Construct a new MaxKey
    • MongoDB\BSON\MinKey::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\MinKey::serialize - Serialize a MinKey
    • MongoDB\BSON\MinKey::unserialize - Unserialize a MinKey
    • MongoDB\BSON\MinKey::__construct - Construct a new MinKey
    • MongoDB\BSON\ObjectId::getTimestamp - Returns the timestamp component of this ObjectId
    • MongoDB\BSON\ObjectId::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\ObjectId::serialize - Serialize an ObjectId
    • MongoDB\BSON\ObjectId::unserialize - Unserialize an ObjectId
    • MongoDB\BSON\ObjectId::__construct - Construct a new ObjectId
    • MongoDB\BSON\ObjectId::__toString - Returns the hexidecimal representation of this ObjectId
    • MongoDB\BSON\ObjectIdInterface::getTimestamp - Returns the timestamp component of this ObjectIdInterface
    • MongoDB\BSON\ObjectIdInterface::__toString - Returns the hexidecimal representation of this ObjectIdInterface
    • MongoDB\BSON\Regex::getFlags - Returns the Regex's flags
    • MongoDB\BSON\Regex::getPattern - Returns the Regex's pattern
    • MongoDB\BSON\Regex::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Regex::serialize - Serialize a Regex
    • MongoDB\BSON\Regex::unserialize - Unserialize a Regex
    • MongoDB\BSON\Regex::__construct - Construct a new Regex
    • MongoDB\BSON\Regex::__toString - Returns the string representation of this Regex
    • MongoDB\BSON\RegexInterface::getFlags - Returns the RegexInterface's flags
    • MongoDB\BSON\RegexInterface::getPattern - Returns the RegexInterface's pattern
    • MongoDB\BSON\RegexInterface::__toString - Returns the string representation of this RegexInterface
    • MongoDB\BSON\Serializable::bsonSerialize - Provides an array or document to serialize as BSON
    • MongoDB\BSON\Symbol::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Symbol::serialize - Serialize a Symbol
    • MongoDB\BSON\Symbol::unserialize - Unserialize a Symbol
    • MongoDB\BSON\Symbol::__construct - Construct a new Symbol (unused)
    • MongoDB\BSON\Symbol::__toString - Returns the Symbol as a string
    • MongoDB\BSON\Timestamp::getIncrement - Returns the increment component of this Timestamp
    • MongoDB\BSON\Timestamp::getTimestamp - Returns the timestamp component of this Timestamp
    • MongoDB\BSON\Timestamp::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Timestamp::serialize - Serialize a Timestamp
    • MongoDB\BSON\Timestamp::unserialize - Unserialize a Timestamp
    • MongoDB\BSON\Timestamp::__construct - Construct a new Timestamp
    • MongoDB\BSON\Timestamp::__toString - Returns the string representation of this Timestamp
    • MongoDB\BSON\TimestampInterface::getIncrement - Returns the increment component of this TimestampInterface
    • MongoDB\BSON\TimestampInterface::getTimestamp - Returns the timestamp component of this TimestampInterface
    • MongoDB\BSON\TimestampInterface::__toString - Returns the string representation of this TimestampInterface
    • MongoDB\BSON\toCanonicalExtendedJSON - Returns the Canonical Extended JSON representation of a BSON value
    • MongoDB\BSON\toJSON - Returns the Legacy Extended JSON representation of a BSON value
    • MongoDB\BSON\toPHP - Returns the PHP representation of a BSON value
    • MongoDB\BSON\toRelaxedExtendedJSON - Returns the Relaxed Extended JSON representation of a BSON value
    • MongoDB\BSON\Undefined::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Undefined::serialize - Serialize a Undefined
    • MongoDB\BSON\Undefined::unserialize - Unserialize a Undefined
    • MongoDB\BSON\Undefined::__construct - Construct a new Undefined (unused)
    • MongoDB\BSON\Undefined::__toString - Returns an empty string
    • MongoDB\BSON\Unserializable::bsonUnserialize - Constructs the object from a BSON array or document
    • MongoDB\BSON\UTCDateTime::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\UTCDateTime::serialize - Serialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::toDateTime - Returns the DateTime representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTime::unserialize - Unserialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::__construct - Construct a new UTCDateTime
    • MongoDB\BSON\UTCDateTime::__toString - Returns the string representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTimeInterface::toDateTime - Returns the DateTime representation of this UTCDateTimeInterface
    • MongoDB\BSON\UTCDateTimeInterface::__toString - Returns the string representation of this UTCDateTimeInterface
    • MongoDB\Driver\BulkWrite::count - Count number of write operations in the bulk
    • MongoDB\Driver\BulkWrite::delete - Add a delete operation to the bulk
    • MongoDB\Driver\BulkWrite::insert - Add an insert operation to the bulk
    • MongoDB\Driver\BulkWrite::update - Add an update operation to the bulk
    • MongoDB\Driver\BulkWrite::__construct - Create a new BulkWrite
    • MongoDB\Driver\ClientEncryption::addKeyAltName - Adds an alternate name to a key document
    • MongoDB\Driver\ClientEncryption::createDataKey - Creates a key document
    • MongoDB\Driver\ClientEncryption::decrypt - Decrypt a value
    • MongoDB\Driver\ClientEncryption::deleteKey - Deletes a key document
    • MongoDB\Driver\ClientEncryption::encrypt - Encrypt a value
    • MongoDB\Driver\ClientEncryption::encryptExpression - Encrypts a match or aggregate expression
    • MongoDB\Driver\ClientEncryption::getKey - Gets a key document
    • MongoDB\Driver\ClientEncryption::getKeyByAltName - Gets a key document by an alternate name
    • MongoDB\Driver\ClientEncryption::getKeys - Gets all key documents
    • MongoDB\Driver\ClientEncryption::removeKeyAltName - Removes an alternate name from a key document
    • MongoDB\Driver\ClientEncryption::rewrapManyDataKey - Rewraps data keys
    • MongoDB\Driver\ClientEncryption::__construct - Create a new ClientEncryption object
    • MongoDB\Driver\Command::__construct - 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\CursorInterface::getId - Returns the ID for this cursor
    • MongoDB\Driver\CursorInterface::getServer - Returns the server associated with this cursor
    • MongoDB\Driver\CursorInterface::isDead - Checks if the cursor may have additional results
    • MongoDB\Driver\CursorInterface::setTypeMap - Sets a type map to use for BSON unserialization
    • MongoDB\Driver\CursorInterface::toArray - Returns an array containing all results for this cursor
    • MongoDB\Driver\Exception\CommandException::getResultDocument - Returns the result document for the failed command
    • 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::addSubscriber - Registers a monitoring event subscriber with this Manager
    • MongoDB\Driver\Manager::createClientEncryption - Create a new ClientEncryption object
    • MongoDB\Driver\Manager::executeBulkWrite - Execute one or more write operations
    • MongoDB\Driver\Manager::executeCommand - Execute a database command
    • MongoDB\Driver\Manager::executeQuery - Execute a database query
    • MongoDB\Driver\Manager::executeReadCommand - Execute a database command that reads
    • MongoDB\Driver\Manager::executeReadWriteCommand - Execute a database command that reads and writes
    • MongoDB\Driver\Manager::executeWriteCommand - Execute a database command that writes
    • MongoDB\Driver\Manager::getEncryptedFieldsMap - Return the encryptedFieldsMap auto encryption option for the Manager
    • MongoDB\Driver\Manager::getReadConcern - Return the ReadConcern for the Manager
    • MongoDB\Driver\Manager::getReadPreference - Return the ReadPreference for the Manager
    • MongoDB\Driver\Manager::getServers - Return the servers to which this manager is connected
    • MongoDB\Driver\Manager::getWriteConcern - Return the WriteConcern for the Manager
    • MongoDB\Driver\Manager::removeSubscriber - Unregisters a monitoring event subscriber with this Manager
    • MongoDB\Driver\Manager::selectServer - Select a server matching a read preference
    • MongoDB\Driver\Manager::startSession - Start a new client session for use with this client
    • MongoDB\Driver\Manager::__construct - Create new MongoDB Manager
    • MongoDB\Driver\Monitoring\addSubscriber - Registers a monitoring event subscriber globally
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName - Returns the command name
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros - Returns the command's duration in microseconds
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getError - Returns the Exception associated with the failed command
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId - Returns the command's operation ID
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getReply - Returns the command reply document
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId - Returns the command's request ID
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getServer - Returns the Server on which the command was executed
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId - Returns the server connection ID for the command
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId - Returns the load balancer service ID for the command
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand - Returns the command document
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName - Returns the command name
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName - Returns the database on which the command was executed
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId - Returns the command's operation ID
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId - Returns the command's request ID
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getServer - Returns the Server on which the command was executed
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId - Returns the server connection ID for the command
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId - Returns the load balancer service ID for the command
    • MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed - Notification method for a failed command
    • MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted - Notification method for a started command
    • MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded - Notification method for a successful command
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName - Returns the command name
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros - Returns the command's duration in microseconds
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId - Returns the command's operation ID
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply - Returns the command reply document
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId - Returns the command's request ID
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer - Returns the Server on which the command was executed
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId - Returns the server connection ID for the command
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId - Returns the load balancer service ID for the command
    • MongoDB\Driver\Monitoring\removeSubscriber - Unregisters a monitoring event subscriber globally
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged - Notification method for a server description change
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed - Notification method for closing a server
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed - Notification method for a failed server heartbeat
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted - Notification method for a started server heartbeat
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded - Notification method for a successful server heartbeat
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening - Notification method for opening a server
    • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged - Notification method for a topology description change
    • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed - Notification method for closing the topology
    • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening - Notification method for opening the topology
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription - Returns the new description for the server
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription - Returns the previous description for the server
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId - Returns the topology ID associated with this server
    • MongoDB\Driver\Monitoring\ServerClosedEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerClosedEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId - Returns the topology ID associated with this server
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros - Returns the heartbeat's duration in microseconds
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError - Returns the Exception associated with the failed heartbeat
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited - Returns whether the heartbeat used a streaming protocol
    • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited - Returns whether the heartbeat used a streaming protocol
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros - Returns the heartbeat's duration in microseconds
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply - Returns the heartbeat reply document
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited - Returns whether the heartbeat used a streaming protocol
    • MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost - Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId - Returns the topology ID associated with this server
    • MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription - Returns the new description for the topology
    • MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription - Returns the previous description for the topology
    • MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId - Returns the topology ID
    • MongoDB\Driver\Monitoring\TopologyClosedEvent::getTopologyId - Returns the topology ID
    • MongoDB\Driver\Monitoring\TopologyOpeningEvent::getTopologyId - Returns the topology ID
    • MongoDB\Driver\Query::__construct - Create a new Query
    • MongoDB\Driver\ReadConcern::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\ReadConcern::getLevel - Returns the ReadConcern's "level" option
    • MongoDB\Driver\ReadConcern::isDefault - Checks if this is the default read concern
    • MongoDB\Driver\ReadConcern::serialize - Serialize a ReadConcern
    • MongoDB\Driver\ReadConcern::unserialize - Unserialize a ReadConcern
    • MongoDB\Driver\ReadConcern::__construct - Create a new ReadConcern
    • MongoDB\Driver\ReadPreference::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\ReadPreference::getHedge - Returns the ReadPreference's "hedge" option
    • MongoDB\Driver\ReadPreference::getMaxStalenessSeconds - Returns the ReadPreference's "maxStalenessSeconds" option
    • MongoDB\Driver\ReadPreference::getMode - Returns the ReadPreference's "mode" option
    • MongoDB\Driver\ReadPreference::getModeString - Returns the ReadPreference's "mode" option as a string
    • MongoDB\Driver\ReadPreference::getTagSets - Returns the ReadPreference's "tagSets" option
    • MongoDB\Driver\ReadPreference::serialize - Serialize a ReadPreference
    • MongoDB\Driver\ReadPreference::unserialize - Unserialize a ReadPreference
    • MongoDB\Driver\ReadPreference::__construct - 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 describing this server
    • MongoDB\Driver\Server::getLatency - Returns the latency of this server in milliseconds
    • MongoDB\Driver\Server::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\Server::getServerDescription - Returns a ServerDescription for this server
    • MongoDB\Driver\Server::getTags - Returns an array of tags describing this server in a replica set
    • MongoDB\Driver\Server::getType - 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\ServerApi::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\ServerApi::serialize - Serialize a ServerApi
    • MongoDB\Driver\ServerApi::unserialize - Unserialize a ServerApi
    • MongoDB\Driver\ServerApi::__construct - Create a new ServerApi instance
    • MongoDB\Driver\ServerDescription::getHelloResponse - Returns the server's most recent "hello" response
    • MongoDB\Driver\ServerDescription::getHost - Returns the hostname of this server
    • MongoDB\Driver\ServerDescription::getLastUpdateTime - Returns the server's last update time in microseconds
    • MongoDB\Driver\ServerDescription::getPort - Returns the port on which this server is listening
    • MongoDB\Driver\ServerDescription::getRoundTripTime - Returns the server's round trip time in milliseconds
    • MongoDB\Driver\ServerDescription::getType - Returns a string denoting the type of this server
    • MongoDB\Driver\Session::abortTransaction - Aborts a transaction
    • MongoDB\Driver\Session::advanceClusterTime - Advances the cluster time for this session
    • MongoDB\Driver\Session::advanceOperationTime - Advances the operation time for this session
    • MongoDB\Driver\Session::commitTransaction - Commits a transaction
    • MongoDB\Driver\Session::endSession - Terminates a session
    • MongoDB\Driver\Session::getClusterTime - Returns the cluster time for this session
    • MongoDB\Driver\Session::getLogicalSessionId - Returns the logical session ID for this session
    • MongoDB\Driver\Session::getOperationTime - Returns the operation time for this session
    • MongoDB\Driver\Session::getServer - Returns the server to which this session is pinned
    • MongoDB\Driver\Session::getTransactionOptions - Returns options for the currently running transaction
    • MongoDB\Driver\Session::getTransactionState - Returns the current transaction state for this session
    • MongoDB\Driver\Session::isDirty - Returns whether the session has been marked as dirty
    • MongoDB\Driver\Session::isInTransaction - Returns whether a multi-document transaction is in progress
    • MongoDB\Driver\Session::startTransaction - Starts a transaction
    • MongoDB\Driver\Session::__construct - Create a new Session (not used)
    • MongoDB\Driver\TopologyDescription::getServers - Returns the servers in the topology
    • MongoDB\Driver\TopologyDescription::getType - Returns a string denoting the type of this topology
    • MongoDB\Driver\TopologyDescription::hasReadableServer - Returns whether the topology has a readable server
    • MongoDB\Driver\TopologyDescription::hasWritableServer - Returns whether the topology has a writable server
    • MongoDB\Driver\WriteConcern::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\WriteConcern::getJournal - Returns the WriteConcern's "journal" option
    • MongoDB\Driver\WriteConcern::getW - Returns the WriteConcern's "w" option
    • MongoDB\Driver\WriteConcern::getWtimeout - Returns the WriteConcern's "wtimeout" option
    • MongoDB\Driver\WriteConcern::isDefault - Checks if this is the default write concern
    • MongoDB\Driver\WriteConcern::serialize - Serialize a WriteConcern
    • MongoDB\Driver\WriteConcern::unserialize - Unserialize a WriteConcern
    • MongoDB\Driver\WriteConcern::__construct - 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
    • 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 - Show largest possible random value
    • mt_rand - Generate a random value via the Mersenne Twister Random Number Generator
    • mt_srand - Seeds the Mersenne Twister Random Number Generator
    • 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
    • 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::execute_query - Prepares, binds parameters, and executes SQL statement
    • 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_column - Fetch a single column from the next row of a result set
    • 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_result::getIterator - Retrieve an external iterator
    • mysqli_result::__construct - Constructs a mysqli_result object
    • 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
    • mysqli_warning::__construct - Private constructor to disallow direct instantiation
    • 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
    • mysql_xdevapi\Client::close - Close client
  • 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"
    • net_get_interfaces - Get network interfaces
    • 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::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
    • ocibindbyname - Alias de oci_bind_by_name
    • ocicancel - Alias de oci_cancel
    • ocicloselob - Alias de OCILob::close
    • ocicollappend - Alias de OCICollection::append
    • ocicollassign - Alias de OCICollection::assign
    • ocicollassignelem - Alias de OCICollection::assignElem
    • OCICollection::append - Añade un elemento a la colección
    • OCICollection::assign - Asigna un valor a la colección desde otra colección existente
    • OCICollection::assignElem - Asigna un valor a un elemento de la colección
    • OCICollection::free - Libera los recursos asociados con el objeto colección
    • OCICollection::getElem - Devuelve el valor de un elemento
    • OCICollection::max - Devuelve el número máximo de elementos de la colección
    • OCICollection::size - Devuelve el tamaño de la colección
    • OCICollection::trim - Elimina elementos del final de la colección
    • ocicollgetelem - Alias de OCICollection::getElem
    • ocicollmax - Alias de OCICollection::max
    • ocicollsize - Alias de OCICollection::size
    • ocicolltrim - Alias de OCICollection::trim
    • ocicolumnisnull - Alias de oci_field_is_null
    • ocicolumnname - Alias de oci_field_name
    • ocicolumnprecision - Alias de oci_field_precision
    • ocicolumnscale - Alias de oci_field_scale
    • ocicolumnsize - Alias de oci_field_size
    • ocicolumntype - Alias de oci_field_type
    • ocicolumntyperaw - Alias de oci_field_type_raw
    • ocicommit - Alias de oci_commit
    • ocidefinebyname - Alias de oci_define_by_name
    • ocierror - Alias de oci_error
    • ociexecute - Alias de oci_execute
    • ocifetch - Alias de oci_fetch
    • ocifetchinto - Variante obsoleta de oci_fetch_array, oci_fetch_object, oci_fetch_assoc y oci_fetch_row
    • ocifetchstatement - Alias de oci_fetch_all
    • ocifreecollection - Alias de OCICollection::free
    • ocifreecursor - Alias de oci_free_statement
    • ocifreedesc - Alias de OCILob::free
    • ocifreestatement - Alias de oci_free_statement
    • ociinternaldebug - Alias de oci_internal_debug
    • ociloadlob - Alias de OCILob::load
    • OCILob::append - Añade datos a un objeto grande (LOB) desde otro
    • OCILob::close - Cierra un descriptor de LOB
    • OCILob::eof - Comprueba la marca de final de fichero en un descriptor de objetos grandes
    • OCILob::erase - Borra la porción especificada de los datos internos de un LOB
    • OCILob::export - Exporta el contenido de un LOB a un fichero
    • OCILob::flush - Vacía/escribe el búfer de un LOB al servidor
    • OCILob::free - Libera los recursos asociados con el descriptor del LOB
    • OCILob::getBuffering - Devuelve el estado actual del uso del búfer para un objeto grande
    • OCILob::import - Importa datos de un fichero a un LOB
    • OCILob::load - Devuelve el contenido de un objeto grande
    • OCILob::read - Lee parte del objeto grande
    • OCILob::rewind - Mueve el puntero interno al comienzo de un objeto grande
    • OCILob::save - Guarda datos en un objeto grande
    • OCILob::saveFile - Alias de OCILob::import
    • OCILob::seek - Ubica el puntero interno de un objeto grande
    • OCILob::setBuffering - Cambia el estado actual del uso del búfer para objetos grandes
    • OCILob::size - Devuelve el tamaño de un objeto grande
    • OCILob::tell - Devuelve la posición actual del puntero interno de un objeto grande
    • OCILob::truncate - Trunca un objeto grande
    • OCILob::write - Escribe datos en un objeto grande
    • OCILob::writeTemporary - Escribe un objeto grande temporal
    • OCILob::writeToFile - Alias de OCILob::export
    • ocilogoff - Alias de oci_close
    • ocilogon - Alias de oci_connect
    • ocinewcollection - Alias de oci_new_collection
    • ocinewcursor - Alias de oci_new_cursor
    • ocinewdescriptor - Alias de oci_new_descriptor
    • ocinlogon - Alias de oci_new_connect
    • ocinumcols - Alias de oci_num_fields
    • ociparse - Alias de oci_parse
    • ociplogon - Alias de oci_pconnect
    • ociresult - Alias de oci_result
    • ocirollback - Alias de oci_rollback
    • ocirowcount - Alias de oci_num_rows
    • ocisavelob - Alias de OCILob::save
    • ocisavelobfile - Alias de OCILob::import
    • ociserverversion - Alias de oci_server_version
    • ocisetprefetch - Alias de oci_set_prefetch
    • ocistatementtype - Alias de oci_statement_type
    • ociwritelobtofile - Alias de OCILob::export
    • ociwritetemporarylob - Alias de OCILob::writeTemporary
    • oci_bind_array_by_name - 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 - Establece un tiempo de espera de milisegundos para las llamadas a la base de datos
    • oci_set_client_identifier - Establece el identificador del cliente
    • oci_set_client_info - Establece la información del cliente
    • oci_set_db_operation - Establece la operación de base de datos
    • 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_set_prefetch_lob - Establece la cantidad de datos precargados para cada CLOB o BLOB.
    • oci_statement_type - Devuelve el tipo de una sentencia
    • oci_unregister_taf_callback - Anular el registro de una función callback definida para 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_connection_string_is_quoted - Determines if an ODBC connection string value is quoted
    • odbc_connection_string_quote - Quotes an ODBC connection string value
    • odbc_connection_string_should_quote - Determines if an ODBC connection string value should be quoted
    • odbc_cursor - 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 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_cipher_key_length - Gets the cipher key length
    • openssl_cms_decrypt - Decrypt a CMS message
    • openssl_cms_encrypt - Encrypt a CMS message
    • openssl_cms_read - Export the CMS file to an array of PEM certificates
    • openssl_cms_sign - Sign a file
    • openssl_cms_verify - Verify a CMS signature
    • openssl_csr_export - 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::sigilCount - Number of elements in matched rule
    • Parle\Parser::sigilName - Retrieve a rule or token name
    • Parle\Parser::token - Declare a token
    • Parle\Parser::tokenId - Get token id
    • Parle\Parser::trace - Trace the parser operation
    • Parle\Parser::validate - Validate input
    • Parle\RLexer::advance - Process next lexer rule
    • Parle\RLexer::build - Finalize the lexer rule set
    • Parle\RLexer::callout - Define token callback
    • Parle\RLexer::consume - Pass the data for processing
    • Parle\RLexer::dump - Dump the state machine
    • Parle\RLexer::getToken - Retrieve the current token
    • Parle\RLexer::insertMacro - Insert regex macro
    • Parle\RLexer::push - Add a lexer rule
    • Parle\RLexer::pushState - Push a new start state
    • Parle\RLexer::reset - Reset lexer
    • Parle\RParser::advance - Process next parser rule
    • Parle\RParser::build - Finalize the grammar rules
    • Parle\RParser::consume - Consume the data for processing
    • Parle\RParser::dump - Dump the grammar
    • Parle\RParser::errorInfo - Retrieve the error information
    • Parle\RParser::left - Declare a token with left-associativity
    • Parle\RParser::nonassoc - Declare a token with no associativity
    • Parle\RParser::precedence - Declare a precedence rule
    • Parle\RParser::push - Add a grammar rule
    • Parle\RParser::reset - Reset parser state
    • Parle\RParser::right - Declare a token with right-associativity
    • Parle\RParser::sigil - Retrieve a matching part of a rule
    • Parle\RParser::sigilCount - Number of elements in matched rule
    • Parle\RParser::sigilName - Retrieve a rule or token name
    • Parle\RParser::token - Declare a token
    • Parle\RParser::tokenId - Get token id
    • Parle\RParser::trace - Trace the parser operation
    • Parle\RParser::validate - Validate input
    • Parle\Stack::pop - Pop an item from the stack
    • Parle\Stack::push - Push an item into the stack
    • parse_ini_file - 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_rfork - Manipulates process resources
    • 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_unshare - Dissociates parts of the process execution context
    • 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::getIterator - Gets result set iterator
    • 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 instance
    • 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 instance
    • 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_context_visibility - Determines the visibility of the context's error messages returned by pg_last_error and pg_result_error
    • 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
    • Phar::__destruct - Destructs a Phar archive object
    • 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
    • PharData::__destruct - Destructs a non-executable tar or zip archive object
    • 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
    • PharFileInfo::__destruct - Destructs a Phar entry object
    • 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
    • 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_eaccess - Determine accessibility of a file
    • posix_errno - Alias de posix_get_last_error
    • posix_fpathconf - Returns the value of a configurable limit
    • posix_getcwd - 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_pathconf - Returns the value of a configurable limit
    • 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_sysconf - Returns system runtime information
    • 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
  • q
    • QuickHashIntHash::add - This method adds a new entry to the hash
    • QuickHashIntHash::delete - This method deletes an entry from the hash
    • QuickHashIntHash::exists - This method checks whether a key is part of the hash
    • QuickHashIntHash::get - This method retrieves a value from the hash by its key
    • QuickHashIntHash::getSize - Returns the number of elements in the hash
    • QuickHashIntHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashIntHash::loadFromString - This factory method creates a hash from a string
    • QuickHashIntHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashIntHash::saveToString - This method returns a serialized version of the hash
    • QuickHashIntHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntHash::update - This method updates an entry in the hash with a new value
    • QuickHashIntHash::__construct - Creates a new QuickHashIntHash object
    • QuickHashIntSet::add - This method adds a new entry to the set
    • QuickHashIntSet::delete - This method deletes an entry from the set
    • QuickHashIntSet::exists - This method checks whether a key is part of the set
    • QuickHashIntSet::getSize - Returns the number of elements in the set
    • QuickHashIntSet::loadFromFile - This factory method creates a set from a file
    • QuickHashIntSet::loadFromString - This factory method creates a set from a string
    • QuickHashIntSet::saveToFile - This method stores an in-memory set to disk
    • QuickHashIntSet::saveToString - This method returns a serialized version of the set
    • QuickHashIntSet::__construct - Creates a new QuickHashIntSet object
    • QuickHashIntStringHash::add - This method adds a new entry to the hash
    • QuickHashIntStringHash::delete - This method deletes an entry from the hash
    • QuickHashIntStringHash::exists - This method checks whether a key is part of the hash
    • QuickHashIntStringHash::get - This method retrieves a value from the hash by its key
    • QuickHashIntStringHash::getSize - Returns the number of elements in the hash
    • QuickHashIntStringHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashIntStringHash::loadFromString - This factory method creates a hash from a string
    • QuickHashIntStringHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashIntStringHash::saveToString - This method returns a serialized version of the hash
    • QuickHashIntStringHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntStringHash::update - This method updates an entry in the hash with a new value
    • QuickHashIntStringHash::__construct - Creates a new QuickHashIntStringHash object
    • QuickHashStringIntHash::add - This method adds a new entry to the hash
    • QuickHashStringIntHash::delete - This method deletes an entry from the hash
    • QuickHashStringIntHash::exists - This method checks whether a key is part of the hash
    • QuickHashStringIntHash::get - This method retrieves a value from the hash by its key
    • QuickHashStringIntHash::getSize - Returns the number of elements in the hash
    • QuickHashStringIntHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashStringIntHash::loadFromString - This factory method creates a hash from a string
    • QuickHashStringIntHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashStringIntHash::saveToString - This method returns a serialized version of the hash
    • QuickHashStringIntHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashStringIntHash::update - This method updates an entry in the hash with a new value
    • QuickHashStringIntHash::__construct - Creates a new QuickHashStringIntHash object
    • quoted_printable_decode - 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 - Generate a random integer
    • Random\Engine::generate - Generates randomness
    • Random\Engine\Mt19937::generate - Generate 32 bits of randomness
    • Random\Engine\Mt19937::__construct - Constructs a new Mt19937 engine
    • Random\Engine\Mt19937::__debugInfo - Returns the internal state of the engine
    • Random\Engine\Mt19937::__serialize - Serializes the Mt19937 object
    • Random\Engine\Mt19937::__unserialize - Deserializes the data parameter into a Mt19937 object
    • Random\Engine\PcgOneseq128XslRr64::generate - Generate 64 bits of randomness
    • Random\Engine\PcgOneseq128XslRr64::jump - Efficiently move the engine ahead multiple steps
    • Random\Engine\PcgOneseq128XslRr64::__construct - Constructs a new PCG Oneseq 128 XSL RR 64 engine
    • Random\Engine\PcgOneseq128XslRr64::__debugInfo - Returns the internal state of the engine
    • Random\Engine\PcgOneseq128XslRr64::__serialize - Serializes the PcgOneseq128XslRr64 object
    • Random\Engine\PcgOneseq128XslRr64::__unserialize - Deserializes the data parameter into a PcgOneseq128XslRr64 object
    • Random\Engine\Secure::generate - Generate cryptographically secure randomness
    • Random\Engine\Xoshiro256StarStar::generate - Generate 64 bits of randomness
    • Random\Engine\Xoshiro256StarStar::jump - Efficiently move the engine ahead by 2^128 steps
    • Random\Engine\Xoshiro256StarStar::jumpLong - Efficiently move the engine ahead by 2^192 steps
    • Random\Engine\Xoshiro256StarStar::__construct - Constructs a new xoshiro256** engine
    • Random\Engine\Xoshiro256StarStar::__debugInfo - Returns the internal state of the engine
    • Random\Engine\Xoshiro256StarStar::__serialize - Serializes the Xoshiro256StarStar object
    • Random\Engine\Xoshiro256StarStar::__unserialize - Deserializes the data parameter into a Xoshiro256StarStar object
    • Random\Randomizer::getBytes - Get random bytes
    • Random\Randomizer::getBytesFromString - Get random bytes from a source string
    • Random\Randomizer::getFloat - Get a uniformly selected float
    • Random\Randomizer::getInt - Get a uniformly selected integer
    • Random\Randomizer::nextFloat - Get a float from the right-open interval [0.0, 1.0)
    • Random\Randomizer::nextInt - Get a positive integer
    • Random\Randomizer::pickArrayKeys - Select random array keys
    • Random\Randomizer::shuffleArray - Get a permutation of an array
    • Random\Randomizer::shuffleBytes - Get a byte-wise permutation of a string
    • Random\Randomizer::__construct - Constructs a new Randomizer
    • Random\Randomizer::__serialize - Serializes the Randomizer object
    • Random\Randomizer::__unserialize - Deserializes the data parameter into a Randomizer object
    • random_bytes - Get cryptographically secure random bytes
    • random_int - Get a cryptographically secure, uniformly selected integer
    • 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::getAttributes - Gets Attributes
    • 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::isEnum - Returns whether this is an enum
    • 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::isReadOnly - Checks if class is readonly
    • 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::getAttributes - Gets Attributes
    • 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::isEnumCase - Checks if class constant is an Enum case
    • ReflectionClassConstant::isFinal - Checks if class constant is final
    • 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::isAnonymous - Checks if a function is anonymous
    • ReflectionFunction::isDisabled - Comprueba si una función está desactivada
    • ReflectionFunction::__construct - Contruye un objeto de tipo ReflectionFunction
    • ReflectionFunction::__toString - Convertir a string
    • ReflectionFunctionAbstract::getAttributes - Gets Attributes
    • ReflectionFunctionAbstract::getClosureScopeClass - Devuelve el ámbito asociado al cierre
    • ReflectionFunctionAbstract::getClosureThis - Devuelve una función anónima que apunta a esta función
    • ReflectionFunctionAbstract::getClosureUsedVariables - Returns an array of the used variables in the Closure
    • 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::getTentativeReturnType - Returns the tentative return type associated with the function
    • ReflectionFunctionAbstract::hasReturnType - Checks if the function has a specified return type
    • ReflectionFunctionAbstract::hasTentativeReturnType - Devuelve si la función tiene un tipo de retorno tentativo
    • 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::isStatic - Checks if the function is static
    • 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::createFromMethodName - Creates a new 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::hasPrototype - Returns whether a method has a prototype
    • 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::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 name of the type as a string
    • 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::getAttributes - Gets Attributes
    • 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::getAttributes - Gets Attributes
    • 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::isPromoted - Checks if property is promoted
    • ReflectionProperty::isProtected - Comprueba si la propiedad es protegida
    • ReflectionProperty::isPublic - Comprueba si la propiedad es pública
    • ReflectionProperty::isReadOnly - Checks if property is readonly
    • 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
    • ReflectionReference::__construct - Private constructor to disallow direct instantiation
    • 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
    • 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
    • Result::getAffectedItemsCount - Get affected row count
    • Result::getAutoIncrementValue - Get autoincremented value
    • Result::getGeneratedIds - Get generated ids
    • Result::getWarnings - Get warnings from last operation
    • Result::getWarningsCount - Get warning count from last operation
    • Result::__construct - Result constructor
    • ReturnTypeWillChange::__construct - Construct a new ReturnTypeWillChange attribute instance
    • rewind - Rebobina la posición de un puntero a un archivo
    • rewinddir - Regresar el gestor de directorio
    • rmdir - Elimina un directorio
    • rnp_backend_string - Return cryptographic backend library name
    • rnp_backend_version - Return cryptographic backend library version
    • rnp_decrypt - Decrypt PGP message
    • rnp_dump_packets - Dump OpenPGP packets stream information in humand-readable format
    • rnp_dump_packets_to_json - Dump OpenPGP packets stream information to the JSON string
    • rnp_ffi_create - Create the top-level object used for interacting with the library
    • rnp_ffi_destroy - Destroy the top-level object used for interacting with the library
    • rnp_ffi_set_pass_provider - Set password provider callback function
    • rnp_import_keys - Import keys from PHP string to the keyring and receive JSON describing new/updated keys
    • rnp_import_signatures - Import standalone signatures to the keyring and receive JSON describing updated keys
    • rnp_key_export - Export a key
    • rnp_key_export_autocrypt - Export minimal key for autocrypt feature (just 5 packets: key, uid, signature, encryption subkey, signature)
    • rnp_key_export_revocation - Generate and export primary key revocation signature
    • rnp_key_get_info - Get information about the key
    • rnp_key_remove - Remove a key from keyring(s)
    • rnp_key_revoke - Revoke a key or subkey by generating and adding revocation signature
    • rnp_list_keys - Enumerate all keys present in a keyring by specified identifer type
    • rnp_load_keys - Load keys from PHP string
    • rnp_load_keys_from_path - Load keys from specified path
    • rnp_locate_key - Search for the key
    • rnp_op_encrypt - Encrypt message
    • rnp_op_generate_key - Generate key
    • rnp_op_sign - Perform signing operation on a binary data, return embedded signature(s)
    • rnp_op_sign_cleartext - Perform signing operation on a textual data, return cleartext signed message
    • rnp_op_sign_detached - Perform signing operation, return detached signature(s)
    • rnp_op_verify - Verify embedded or cleartext signatures
    • rnp_op_verify_detached - Verify detached signatures
    • rnp_save_keys - Save keys to PHP string
    • rnp_save_keys_to_path - Save keys to specified path
    • rnp_supported_features - Get supported features in JSON format
    • rnp_version_string - RNP library version
    • rnp_version_string_full - Full version string of RNP library
    • round - Redondea un float
    • RowResult::fetchAll - Get all rows from result
    • RowResult::fetchOne - Get row from result
    • RowResult::getColumnNames - Get all column names
    • RowResult::getColumns - Get column metadata
    • RowResult::getColumnsCount - Get column count
    • RowResult::getWarnings - Get warnings from last operation
    • RowResult::getWarningsCount - Get warning count from last operation
    • RowResult::__construct - RowResult constructor
    • rpmaddtag - Add tag retrieved in query
    • rpmdbinfo - Get information from installed RPM
    • rpmdbsearch - Search RPM packages
    • rpmgetsymlink - Get target of a symlink
    • rpminfo - Get information from a RPM file
    • rpmvercmp - RPM version comparison
    • RRDCreator::addArchive - 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
    • Schema::createCollection - Add collection to schema
    • Schema::dropCollection - Drop collection from schema
    • Schema::existsInDatabase - Check if exists in database
    • Schema::getCollection - Get collection from schema
    • Schema::getCollectionAsTable - Get collection table object
    • Schema::getCollections - Get all schema collections
    • Schema::getName - Get schema name
    • Schema::getSession - Get schema session
    • Schema::getTable - Get schema table
    • Schema::getTables - Get schema tables
    • Schema::__construct - constructor
    • SchemaObject::getSchema - Get schema object
    • scoutapm_get_calls - Returns a list of instrumented calls that have occurred
    • scoutapm_list_instrumented_functions - List functions scoutapm will instrument.
    • SeasLog::alert - Record alert log information
    • SeasLog::analyzerCount - Get log count by level, log_path and key_word
    • SeasLog::analyzerDetail - Get log detail by level, log_path, key_word, start, limit, order
    • SeasLog::closeLoggerStream - Manually release stream flow from logger
    • SeasLog::critical - Record critical log information
    • SeasLog::debug - Record debug log information
    • SeasLog::emergency - Record emergency log information
    • SeasLog::error - Record error log information
    • SeasLog::flushBuffer - Flush logs buffer, dump to appender file, or send to remote api with tcp/udp
    • SeasLog::getBasePath - Get SeasLog base path.
    • SeasLog::getBuffer - Get the logs buffer in memory as array
    • SeasLog::getBufferEnabled - Determin if buffer enabled
    • SeasLog::getDatetimeFormat - Get SeasLog datetime format style
    • SeasLog::getLastLogger - Get SeasLog last logger path
    • SeasLog::getRequestID - Get SeasLog request_id differentiated requests
    • SeasLog::getRequestVariable - Get SeasLog request variable
    • SeasLog::info - Record info log information
    • SeasLog::log - The Common Record Log Function
    • SeasLog::notice - Record notice log information
    • SeasLog::setBasePath - Set SeasLog base path
    • SeasLog::setDatetimeFormat - Set SeasLog datetime format style
    • SeasLog::setLogger - Set SeasLog logger name
    • SeasLog::setRequestID - Set SeasLog request_id differentiated requests
    • SeasLog::setRequestVariable - Manually set SeasLog request variable
    • SeasLog::warning - Record warning log information
    • SeasLog::__construct - Description
    • SeasLog::__destruct - Description
    • seaslog_get_author - Get SeasLog author.
    • seaslog_get_version - Get SeasLog version.
    • SeekableIterator::seek - 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
    • SensitiveParameter::__construct - Construct a new SensitiveParameter attribute instance
    • SensitiveParameterValue::getValue - Returns the sensitive value
    • SensitiveParameterValue::__construct - Constructs a new SensitiveParameterValue object
    • SensitiveParameterValue::__debugInfo - Protects the sensitive value against accidental exposure
    • 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
    • Session::close - Close session
    • Session::createSchema - Create new schema
    • Session::dropSchema - Drop a schema
    • Session::generateUUID - Get new UUID
    • Session::getDefaultSchema - Get default schema name
    • Session::getSchema - Get a new schema object
    • Session::getSchemas - Get the schemas
    • Session::getServerVersion - Get server version
    • Session::listClients - Get client list
    • Session::quoteName - Add quotes
    • Session::releaseSavepoint - Release set savepoint
    • Session::rollback - Rollback transaction
    • Session::rollbackTo - Rollback transaction to savepoint
    • Session::setSavepoint - Create savepoint
    • Session::sql - Execute SQL query
    • Session::startTransaction - Start transaction
    • Session::__construct - Description constructor
    • SessionHandler::close - 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_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_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
    • setrawcookie - Enviar una cookie sin codificar su valor
    • 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
    • simdjson_decode - Decodes a JSON string
    • simdjson_is_valid - Check if a JSON string is valid
    • simdjson_key_count - Returns the value at a JSON pointer.
    • simdjson_key_exists - Check if the JSON contains the value referred to by a JSON pointer.
    • simdjson_key_value - Decodes the value of a JSON string located at the requested JSON pointer.
    • similar_text - 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::current - Returns the current element
    • SimpleXMLElement::getChildren - Returns the sub-elements of the current element
    • 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::hasChildren - Checks whether the current element has sub elements
    • SimpleXMLElement::key - Return current key
    • SimpleXMLElement::next - Move to next element
    • SimpleXMLElement::registerXPathNamespace - Crea un contexto prefijo/ns para la siguiente petición XPath
    • SimpleXMLElement::rewind - Rewind to the first element
    • SimpleXMLElement::saveXML - Alias de SimpleXMLElement::asXML
    • SimpleXMLElement::valid - Check whether the current element is valid
    • SimpleXMLElement::xpath - Ejecuta una petición XPath sobre los datos XML
    • SimpleXMLElement::__construct - Crea un nuevo objeto SimpleXMLElement
    • SimpleXMLElement::__toString - Returns the string content
    • 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 - Alias de snmp_set_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_atmark - Determines whether socket is at out-of-band mark
    • 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 - Decodes a base64-encoded string into raw binary.
    • sodium_bin2base64 - Encodes a raw binary string with base64.
    • sodium_bin2hex - Encode to hexadecimal
    • sodium_compare - Compare large numbers
    • sodium_crypto_aead_aes256gcm_decrypt - Verify then decrypt a message with AES-256-GCM
    • sodium_crypto_aead_aes256gcm_encrypt - Encrypt then authenticate with AES-256-GCM
    • sodium_crypto_aead_aes256gcm_is_available - Check if hardware supports AES256-GCM
    • sodium_crypto_aead_aes256gcm_keygen - Generate a random AES-256-GCM key
    • sodium_crypto_aead_chacha20poly1305_decrypt - Verify then decrypt with ChaCha20-Poly1305
    • sodium_crypto_aead_chacha20poly1305_encrypt - Encrypt then authenticate with ChaCha20-Poly1305
    • sodium_crypto_aead_chacha20poly1305_ietf_decrypt - Verify that the ciphertext includes a valid tag
    • sodium_crypto_aead_chacha20poly1305_ietf_encrypt - Encrypt a message
    • sodium_crypto_aead_chacha20poly1305_ietf_keygen - Generate a random ChaCha20-Poly1305 (IETF) key.
    • sodium_crypto_aead_chacha20poly1305_keygen - Generate a random ChaCha20-Poly1305 key.
    • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt - (Preferred) Verify then decrypt with XChaCha20-Poly1305
    • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt - (Preferred) Encrypt then authenticate with XChaCha20-Poly1305
    • sodium_crypto_aead_xchacha20poly1305_ietf_keygen - Generate a random XChaCha20-Poly1305 key.
    • sodium_crypto_auth - Compute a tag for the message
    • sodium_crypto_auth_keygen - Generate a random key for sodium_crypto_auth
    • sodium_crypto_auth_verify - Verifies that the tag is valid for the message
    • sodium_crypto_box - Authenticated public-key encryption
    • sodium_crypto_box_keypair - Randomly generate a secret key and a corresponding public key
    • sodium_crypto_box_keypair_from_secretkey_and_publickey - Create a unified keypair string from a secret key and public key
    • sodium_crypto_box_open - Authenticated public-key decryption
    • sodium_crypto_box_publickey - Extract the public key from a crypto_box keypair
    • sodium_crypto_box_publickey_from_secretkey - Calculate the public key from a secret key
    • sodium_crypto_box_seal - Anonymous public-key encryption
    • sodium_crypto_box_seal_open - Anonymous public-key decryption
    • sodium_crypto_box_secretkey - Extracts the secret key from a crypto_box keypair
    • sodium_crypto_box_seed_keypair - Deterministically derive the key pair from a single key
    • sodium_crypto_core_ristretto255_add - Adds an element
    • sodium_crypto_core_ristretto255_from_hash - Maps a vector
    • sodium_crypto_core_ristretto255_is_valid_point - Determines if a point on the ristretto255 curve
    • sodium_crypto_core_ristretto255_random - Generates a random key
    • sodium_crypto_core_ristretto255_scalar_add - Adds a scalar value
    • sodium_crypto_core_ristretto255_scalar_complement - The sodium_crypto_core_ristretto255_scalar_complement purpose
    • sodium_crypto_core_ristretto255_scalar_invert - Inverts a scalar value
    • sodium_crypto_core_ristretto255_scalar_mul - Multiplies a scalar value
    • sodium_crypto_core_ristretto255_scalar_negate - Negates a scalar value
    • sodium_crypto_core_ristretto255_scalar_random - Generates a random key
    • sodium_crypto_core_ristretto255_scalar_reduce - Reduces a scalar value
    • sodium_crypto_core_ristretto255_scalar_sub - Subtracts a scalar value
    • sodium_crypto_core_ristretto255_sub - Subtracts an element
    • sodium_crypto_generichash - Get a hash of the message
    • sodium_crypto_generichash_final - Complete the hash
    • sodium_crypto_generichash_init - Initialize a hash for streaming
    • sodium_crypto_generichash_keygen - Generate a random generichash key
    • sodium_crypto_generichash_update - Add message to a hash
    • sodium_crypto_kdf_derive_from_key - Derive a subkey
    • sodium_crypto_kdf_keygen - Generate a random root key for the KDF interface
    • sodium_crypto_kx_client_session_keys - Calculate the client-side session keys.
    • sodium_crypto_kx_keypair - Creates a new sodium keypair
    • sodium_crypto_kx_publickey - Extract the public key from a crypto_kx keypair
    • sodium_crypto_kx_secretkey - Extract the secret key from a crypto_kx keypair.
    • sodium_crypto_kx_seed_keypair - Description
    • sodium_crypto_kx_server_session_keys - Calculate the server-side session keys.
    • sodium_crypto_pwhash - Derive a key from a password, using Argon2
    • sodium_crypto_pwhash_scryptsalsa208sha256 - Derives a key from a password, using scrypt
    • sodium_crypto_pwhash_scryptsalsa208sha256_str - Get an ASCII encoded hash
    • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify - Verify that the password is a valid password verification string
    • sodium_crypto_pwhash_str - Get an ASCII-encoded hash
    • sodium_crypto_pwhash_str_needs_rehash - Determine whether or not to rehash a password
    • sodium_crypto_pwhash_str_verify - Verifies that a password matches a hash
    • sodium_crypto_scalarmult - Compute a shared secret given a user's secret key and another user's public key
    • sodium_crypto_scalarmult_base - Alias de sodium_crypto_box_publickey_from_secretkey
    • sodium_crypto_scalarmult_ristretto255 - Computes a shared secret
    • sodium_crypto_scalarmult_ristretto255_base - Calculates the public key from a secret key
    • sodium_crypto_secretbox - Authenticated shared-key encryption
    • sodium_crypto_secretbox_keygen - Generate random key for sodium_crypto_secretbox
    • sodium_crypto_secretbox_open - Authenticated shared-key decryption
    • sodium_crypto_secretstream_xchacha20poly1305_init_pull - Initialize a secretstream context for decryption
    • sodium_crypto_secretstream_xchacha20poly1305_init_push - Initialize a secretstream context for encryption
    • sodium_crypto_secretstream_xchacha20poly1305_keygen - Generate a random secretstream key.
    • sodium_crypto_secretstream_xchacha20poly1305_pull - Decrypt a chunk of data from an encrypted stream
    • sodium_crypto_secretstream_xchacha20poly1305_push - Encrypt a chunk of data so that it can safely be decrypted in a streaming API
    • sodium_crypto_secretstream_xchacha20poly1305_rekey - Explicitly rotate the key in the secretstream state
    • sodium_crypto_shorthash - Compute a short hash of a message and key
    • sodium_crypto_shorthash_keygen - Get random bytes for key
    • sodium_crypto_sign - Sign a message
    • sodium_crypto_sign_detached - Sign the message
    • sodium_crypto_sign_ed25519_pk_to_curve25519 - Convert an Ed25519 public key to a Curve25519 public key
    • sodium_crypto_sign_ed25519_sk_to_curve25519 - Convert an Ed25519 secret key to a Curve25519 secret key
    • sodium_crypto_sign_keypair - Randomly generate a secret key and a corresponding public key
    • sodium_crypto_sign_keypair_from_secretkey_and_publickey - Join a secret key and public key together
    • sodium_crypto_sign_open - Check that the signed message has a valid signature
    • sodium_crypto_sign_publickey - Extract the Ed25519 public key from a keypair
    • sodium_crypto_sign_publickey_from_secretkey - Extract the Ed25519 public key from the secret key
    • sodium_crypto_sign_secretkey - Extract the Ed25519 secret key from a keypair
    • sodium_crypto_sign_seed_keypair - Deterministically derive the key pair from a single key
    • sodium_crypto_sign_verify_detached - Verify signature for the message
    • sodium_crypto_stream - Generate a deterministic sequence of bytes from a seed
    • sodium_crypto_stream_keygen - Generate a random sodium_crypto_stream key.
    • sodium_crypto_stream_xchacha20 - Expands the key and nonce into a keystream of pseudorandom bytes
    • sodium_crypto_stream_xchacha20_keygen - Returns a secure random key
    • sodium_crypto_stream_xchacha20_xor - Encrypts a message using a nonce and a secret key (no authentication)
    • sodium_crypto_stream_xchacha20_xor_ic - Encrypts a message using a nonce and a secret key (no authentication)
    • sodium_crypto_stream_xor - Encrypt a message without authentication
    • sodium_hex2bin - Decodes a hexadecimally encoded binary string
    • sodium_increment - Increment large number
    • sodium_memcmp - Test for equality in constant-time
    • sodium_memzero - Overwrite a string with NUL characters
    • sodium_pad - Add padding data
    • sodium_unpad - Remove padding data
    • SolrClient::addDocument - 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
    • 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
    • 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::getIterator - Retrieve the iterator to go through the array
    • SplFixedArray::getSize - Obtiene el tamaño de el array
    • SplFixedArray::jsonSerialize - Returns a representation that can be converted to JSON
    • 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::__serialize - Serializes the SplFixedArray object
    • SplFixedArray::__unserialize - Deserializes the data parameter into an SplFixedArray object
    • 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
    • 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
    • SplQueue::dequeue - Quita un nodo de la cola
    • SplQueue::enqueue - Añade un elemento a la cola
    • 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::setRestrictionLevel - Set the restriction level
    • 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
    • SQLite3Result::__construct - Constructs an SQLite3Result
    • 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
    • SQLite3Stmt::__construct - Constructs an SQLite3Stmt object
    • 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
    • SqlStatement::bind - Bind statement parameters
    • SqlStatement::execute - Execute the operation
    • SqlStatement::getNextResult - Get next result
    • SqlStatement::getResult - Get result
    • SqlStatement::hasMoreResults - Check for more results
    • SqlStatement::__construct - Description constructor
    • SqlStatementResult::fetchAll - Get all rows from result
    • SqlStatementResult::fetchOne - Get single row
    • SqlStatementResult::getAffectedItemsCount - Get affected row count
    • SqlStatementResult::getColumnNames - Get column names
    • SqlStatementResult::getColumns - Get columns
    • SqlStatementResult::getColumnsCount - Get column count
    • SqlStatementResult::getGeneratedIds - Get generated ids
    • SqlStatementResult::getLastInsertId - Get last insert id
    • SqlStatementResult::getWarnings - Get warnings from last operation
    • SqlStatementResult::getWarningsCount - Get warning count from last operation
    • SqlStatementResult::hasData - Check if result has data
    • SqlStatementResult::nextResult - Get next result
    • SqlStatementResult::__construct - Description constructor
    • sqrt - Raíz cuadrada
    • srand - Seed the random number generator
    • 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_send_eof - Send EOF to stream
    • 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
    • Statement::getNextResult - Get next result
    • Statement::getResult - Get result
    • Statement::hasMoreResults - Check if more results
    • Statement::__construct - Description constructor
    • stats_absolute_deviation - Returns the absolute deviation of an array of values
    • stats_cdf_beta - Calculates any one parameter of the beta distribution given values for the others
    • stats_cdf_binomial - Calculates any one parameter of the binomial distribution given values for the others
    • stats_cdf_cauchy - Calculates any one parameter of the Cauchy distribution given values for the others
    • stats_cdf_chisquare - Calculates any one parameter of the chi-square distribution given values for the others
    • stats_cdf_exponential - Calculates any one parameter of the exponential distribution given values for the others
    • stats_cdf_f - Calculates any one parameter of the F distribution given values for the others
    • stats_cdf_gamma - Calculates any one parameter of the gamma distribution given values for the others
    • stats_cdf_laplace - Calculates any one parameter of the Laplace distribution given values for the others
    • stats_cdf_logistic - Calculates any one parameter of the logistic distribution given values for the others
    • stats_cdf_negative_binomial - Calculates any one parameter of the negative binomial distribution given values for the others
    • stats_cdf_noncentral_chisquare - Calculates any one parameter of the non-central chi-square distribution given values for the others
    • stats_cdf_noncentral_f - Calculates any one parameter of the non-central F distribution given values for the others
    • stats_cdf_noncentral_t - Calculates any one parameter of the non-central t-distribution give values for the others
    • stats_cdf_normal - Calculates any one parameter of the normal distribution given values for the others
    • stats_cdf_poisson - Calculates any one parameter of the Poisson distribution given values for the others
    • stats_cdf_t - Calculates any one parameter of the t-distribution given values for the others
    • stats_cdf_uniform - Calculates any one parameter of the uniform distribution given values for the others
    • stats_cdf_weibull - Calculates any one parameter of the Weibull distribution given values for the others
    • stats_covariance - Computes the covariance of two data sets
    • stats_dens_beta - Probability density function of the beta distribution
    • stats_dens_cauchy - Probability density function of the Cauchy distribution
    • stats_dens_chisquare - Probability density function of the chi-square distribution
    • stats_dens_exponential - Probability density function of the exponential distribution
    • stats_dens_f - Probability density function of the F distribution
    • stats_dens_gamma - Probability density function of the gamma distribution
    • stats_dens_laplace - Probability density function of the Laplace distribution
    • stats_dens_logistic - Probability density function of the logistic distribution
    • stats_dens_normal - Probability density function of the normal distribution
    • stats_dens_pmf_binomial - Probability mass function of the binomial distribution
    • stats_dens_pmf_hypergeometric - Probability mass function of the hypergeometric distribution
    • stats_dens_pmf_negative_binomial - Probability mass function of the negative binomial distribution
    • stats_dens_pmf_poisson - Probability mass function of the Poisson distribution
    • stats_dens_t - Probability density function of the t-distribution
    • stats_dens_uniform - Probability density function of the uniform distribution
    • stats_dens_weibull - Probability density function of the Weibull distribution
    • stats_harmonic_mean - Returns the harmonic mean of an array of values
    • stats_kurtosis - Computes the kurtosis of the data in the array
    • stats_rand_gen_beta - Generates a random deviate from the beta distribution
    • stats_rand_gen_chisquare - Generates a random deviate from the chi-square distribution
    • stats_rand_gen_exponential - Generates a random deviate from the exponential distribution
    • stats_rand_gen_f - Generates a random deviate from the F distribution
    • stats_rand_gen_funiform - Generates uniform float between low (exclusive) and high (exclusive)
    • stats_rand_gen_gamma - Generates a random deviate from the gamma distribution
    • stats_rand_gen_ibinomial - Generates a random deviate from the binomial distribution
    • stats_rand_gen_ibinomial_negative - Generates a random deviate from the negative binomial distribution
    • stats_rand_gen_int - Generates random integer between 1 and 2147483562
    • stats_rand_gen_ipoisson - Generates a single random deviate from a Poisson distribution
    • stats_rand_gen_iuniform - Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
    • stats_rand_gen_noncentral_chisquare - Generates a random deviate from the non-central chi-square distribution
    • stats_rand_gen_noncentral_f - Generates a random deviate from the noncentral F distribution
    • stats_rand_gen_noncentral_t - Generates a single random deviate from a non-central t-distribution
    • stats_rand_gen_normal - Generates a single random deviate from a normal distribution
    • stats_rand_gen_t - Generates a single random deviate from a t-distribution
    • stats_rand_get_seeds - Get the seed values of the random number generator
    • stats_rand_phrase_to_seeds - Generate two seeds for the RGN random number generator
    • stats_rand_ranf - Generates a random floating point number between 0 and 1
    • stats_rand_setall - Set seed values to the random generator
    • stats_skew - Computes the skewness of the data in the array
    • stats_standard_deviation - Returns the standard deviation
    • stats_stat_binomial_coef - Returns a binomial coefficient
    • stats_stat_correlation - Returns the Pearson correlation coefficient of two data sets
    • stats_stat_factorial - Returns the factorial of an integer
    • stats_stat_independent_t - Returns the t-value from the independent two-sample t-test
    • stats_stat_innerproduct - Returns the inner product of two vectors
    • stats_stat_paired_t - Returns the t-value of the dependent t-test for paired samples
    • stats_stat_percentile - Returns the percentile value
    • stats_stat_powersum - Returns the power sum of a vector
    • stats_variance - Returns the variance
    • Stomp::abort - 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 los metadatos 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_options - Sets options on the specified context
    • 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
    • Stringable::__toString - Gets a string representation of the object
    • 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_decrement - Decrement an alphanumeric string
    • str_ends_with - Checks if a string ends with a given substring
    • str_getcsv - Convierte un string con formato CSV a un array
    • str_increment - Increment an alphanumeric string
    • 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_clear_error - Clear errors in the socket or on the last error code
    • swoole_client_select - Get the file description which are ready to read/write or error
    • swoole_cpu_num - Get the number of CPU
    • swoole_errno - Get the error code of the latest system call
    • swoole_error_log - Output error messages to the log
    • swoole_event_add - Add new callback functions of a socket into the EventLoop
    • swoole_event_defer - Add callback function to the next event loop
    • swoole_event_del - Remove all event callback functions of a socket
    • swoole_event_exit - Exit the eventloop, only available at the client side
    • swoole_event_set - Update the event callback functions of a socket
    • swoole_event_wait - Start the event loop
    • swoole_event_write - Write data to a socket
    • swoole_get_local_ip - Get the IPv4 IP addresses of each NIC on the machine
    • swoole_last_error - Get the lastest error message
    • swoole_load_module - Load a swoole extension
    • swoole_select - Select the file descriptions which are ready to read/write or error in the eventloop
    • swoole_set_process_name - Set the process name
    • swoole_strerror - Convert the Errno into error messages
    • swoole_timer_after - Trigger a one time callback function in the future
    • swoole_timer_exists - Check if a timer callback function is existed
    • swoole_timer_tick - Trigger a timer tick callback function by time interval
    • swoole_version - Get the version of Swoole
    • symlink - 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
    • Table::count - Get row count
    • Table::delete - Delete rows from table
    • Table::existsInDatabase - Check if table exists in database
    • Table::getName - Get table name
    • Table::getSchema - Get table schema
    • Table::getSession - Get table session
    • Table::insert - Insert table rows
    • Table::isView - Check if table is view
    • Table::select - Select rows from table
    • Table::update - Update rows in table
    • Table::__construct - Table constructor
    • TableDelete::bind - Bind delete query parameters
    • TableDelete::execute - Execute delete query
    • TableDelete::limit - Limit deleted rows
    • TableDelete::orderby - Set delete sort criteria
    • TableDelete::where - Set delete search condition
    • TableDelete::__construct - TableDelete constructor
    • TableInsert::execute - Execute insert query
    • TableInsert::values - Add insert row values
    • TableInsert::__construct - TableInsert constructor
    • TableSelect::bind - Bind select query parameters
    • TableSelect::execute - Execute select statement
    • TableSelect::groupBy - Set select grouping criteria
    • TableSelect::having - Set select having condition
    • TableSelect::limit - Limit selected rows
    • TableSelect::lockExclusive - Execute EXCLUSIVE LOCK
    • TableSelect::lockShared - Execute SHARED LOCK
    • TableSelect::offset - Set limit offset
    • TableSelect::orderby - Set select sort criteria
    • TableSelect::where - Set select search condition
    • TableSelect::__construct - TableSelect constructor
    • TableUpdate::bind - Bind update query parameters
    • TableUpdate::execute - Execute update query
    • TableUpdate::limit - Limit update row count
    • TableUpdate::orderby - Set sorting criteria
    • TableUpdate::set - Add field to be updated
    • TableUpdate::where - Set search filter
    • TableUpdate::__construct - TableUpdate constructor
    • taint - 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::getCreatorId - Identificación
    • Thread::getCurrentThread - Identificación
    • Thread::getCurrentThreadId - Identification
    • Thread::getThreadId - Identification
    • Thread::isJoined - State Detection
    • Thread::isStarted - State Detection
    • Thread::join - Synchronization
    • Thread::start - Execution
    • Threaded::chunk - Manipulation
    • Threaded::count - Manipulation
    • Threaded::extend - Runtime Manipulation
    • Threaded::isRunning - State Detection
    • Threaded::isTerminated - State Detection
    • Threaded::merge - Manipulation
    • Threaded::notify - Synchronization
    • Threaded::notifyOne - Synchronization
    • Threaded::pop - Manipulation
    • Threaded::run - Execution
    • Threaded::shift - Manipulation
    • Threaded::synchronized - 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
    • 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
    • UnitEnum::cases - Generates a list of cases on an enum
    • 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 o más variables especificadas
    • 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 un string desde UTF-8 a ISO-8859-1, sustituyendo los caracteres no válidos o no representables
    • utf8_encode - Convierte una cadena de 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
    • var_representation - Returns a short, readable, parsable string representation of a variable
    • 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
    • Warning::__construct - Warning constructor
    • wddx_add_vars - Add variables to a WDDX packet with the specified ID
    • wddx_deserialize - Unserializes a WDDX packet
    • wddx_packet_end - Ends a WDDX packet with the specified ID
    • wddx_packet_start - Starts a new WDDX packet with structure inside it
    • wddx_serialize_value - Serialize a single value into a WDDX packet
    • wddx_serialize_vars - Serialize variables into a WDDX packet
    • WeakMap::count - Counts the number of live entries in the map
    • WeakMap::getIterator - Retrieve an external iterator
    • WeakMap::offsetExists - Checks whether a certain object is in the map
    • WeakMap::offsetGet - Returns the value pointed to by a certain object
    • WeakMap::offsetSet - Updates the map with a new key-value pair
    • WeakMap::offsetUnset - Removes an entry from the map
    • 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::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 - Fin del atributo
    • XMLWriter::endCData - Fin del actual CDATA
    • XMLWriter::endComment - Crea un comentario final
    • XMLWriter::endDocument - Finaliza el actual documento
    • XMLWriter::endDtd - Finaliza la actual DTD
    • XMLWriter::endDtdAttlist - Finaliza la actual attList DTD
    • XMLWriter::endDtdElement - Finaliza el actual elemento DTD
    • XMLWriter::endDtdEntity - Finaliza el actual ente DTD
    • XMLWriter::endElement - Finaliza el actual elemento
    • XMLWriter::endPi - Finaliza el actual IP
    • XMLWriter::flush - Vacía el búfer actual
    • XMLWriter::fullEndElement - Fin del elemento actual
    • XMLWriter::openMemory - Crea un nuevo xmlwriter usando memoria para el string de salida
    • XMLWriter::openUri - Crea un nuevo xmlwriter usando una fuente uri para la salida
    • XMLWriter::outputMemory - Devuelve el actual buffer
    • XMLWriter::setIndent - Cambia la sangria de encendida/apagada
    • XMLWriter::setIndentString - Establece una cadena usada para la identidad
    • XMLWriter::startAttribute - Crea un atributo inicial
    • XMLWriter::startAttributeNs - Crea el atributo de inicio del namespaced
    • XMLWriter::startCdata - Crea la etiqueta de inicio de CDATA
    • XMLWriter::startComment - Crea un comentario inicial
    • XMLWriter::startDocument - Crea un etiqueta del documento
    • XMLWriter::startDtd - Crea la etiqueta DTD inicial
    • XMLWriter::startDtdAttlist - Crea el DTD AttList inicial
    • XMLWriter::startDtdElement - Crea un elemento DTD inicial
    • XMLWriter::startDtdEntity - Crea un ente DTD inicial
    • XMLWriter::startElement - Crea la etiqueta del elemento inicial
    • XMLWriter::startElementNs - Crea la etiqueta del elemento de espacio de nombres inicial
    • XMLWriter::startPi - Crea la etiqueta PI inicial
    • XMLWriter::text - Escribe el texto
    • XMLWriter::writeAttribute - Escribe un atributo completo
    • XMLWriter::writeAttributeNs - Escribe un atributo full de namespaced
    • XMLWriter::writeCdata - Escribe una etiqueta completa del CDATA
    • XMLWriter::writeComment - EScribe la etiqueta del comentario completa
    • XMLWriter::writeDtd - Escribe una etiqueta completa del DTD
    • XMLWriter::writeDtdAttlist - Escribe la etiqueta completa del DTD AttList
    • XMLWriter::writeDtdElement - Escribe la etiqueta completa de un elemento DTD
    • XMLWriter::writeDtdEntity - Escribe una etiqueta completa de un ente DTD
    • XMLWriter::writeElement - Escribe una etiqueta completa del elemento
    • XMLWriter::writeElementNs - Escribe una etiqueta completa del elemento
    • XMLWriter::writePi - Escribe un IP
    • XMLWriter::writeRaw - Escribe un texto sin formato del XML
    • 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 - Recuperar el tipo de excepción
    • 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::clearError - Clear the status error message, system and/or zip messages
    • 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::getArchiveFlag - Returns the value of a Zip archive global flag
    • 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::getStreamIndex - Get a file handler to the entry defined by its index (read only)
    • ZipArchive::getStreamName - Get a file handler to the entry defined by its name (read only)
    • ZipArchive::isCompressionMethodSupported - Check if a compression method is supported by libzip
    • ZipArchive::isEncryptionMethodSupported - Check if a encryption method is supported by libzip
    • ZipArchive::locateName - 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::setArchiveFlag - Set a global flag of a ZIP archive
    • 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

There are no user contributed notes for this page.


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 -
  • Example#9 -
  • Example#10 -
  • Example#11 -
  • Example#12 -
  • Example#13 -
  • Example#14 -
  • Example#15 -
  • Example#16 -
  • Example#17 -
  • Example#18 -
  • Example#19 -
  • Example#20 -
  • Example#21 - Extracto de lighttpd.conf
  • Example#22 - Lanzando oyentes FastCGI
  • Example#23 - Conexión a instancias de php-fastcgi remotas
  • Example#24 - Ejemplo de instalación de paquete de OpenBSD
  • Example#25 - Ejemplo de Instalación en Debian con Apache 2
  • Example#26 - Deteniendo e iniciando Apache una vez que PHP está instalado
  • Example#27 - Métodos para listar paquetes relacionados con PHP 5
  • Example#28 - Instalar PHP con MySQL, cURL
  • Example#29 - Configuración recomendada de WinCache
  • Example#30 - Configuración recomendada de WinCache
  • Example#31 - Linea de órdenes para configurar IIS y PHP
  • Example#32 - Registro de cambios
  • Example#33 - PHP y Apache 2.x como controlador
  • Example#34 -
  • Example#35 - PHP y Apache 2.x como CGI
  • Example#36 - Configurar Apache para ejecutar PHP como FastCGI
  • Example#37 - Pasando variables de entorno y ajustando las configuraciones de PHP por grupos
  • Example#38 - Establecer ajustes PHP en nginx.conf
  • Example#39 - llamada a phpinfo
  • Example#40 - Variables de entorno de php.ini
  • Example#41 - Ejemplo de php.ini
  • Example#42 - Ejemplo de configuración de Apache
  • Example#43 - Salida avanzada usando condiciones
  • Example#44 - Etiquetas de apertura y de cierre de PHP
  • Example#45 - Literales de números enteros
  • Example#46 - Desbordamiento de enteros en sistemas de 32 bit
  • Example#47 - Desbordamiento de enteros en sistemas de 64 bit
  • Example#48 - Ejemplo no válido
  • Example#49 - Ejemplo de entrecomillado de string en Heredoc
  • Example#50 - Ejemplo de Heredoc en argumentos
  • Example#51 - Usar Heredoc para inicializar valores estáticos
  • Example#52 - Emplear comillas dobles en Heredoc
  • Example#53 - Ejemplo de entrecomillado de string de Nowdoc
  • Example#54 - Ejemplo de datos estáticos
  • Example#55 - Ejemplo de sintaxis simple
  • Example#56 - Algunos ejemplos de string
  • Example#57 - Diferencias entre PHP 5.3 y PHP 5.4
  • Example#58 - Un array simple
  • Example#59 - Ejemplo de amoldamiento de tipo y sobrescritura
  • Example#60 - Claves mixtas integer y string
  • Example#61 - Arrays indexados sin clave
  • Example#62 - Claves no en todos los elementos
  • Example#63 - Acceso a elementos de un array
  • Example#64 - Hacer referencia al resultado array de funciones
  • Example#65 - Simple array unpacking
  • Example#66 - Array unpacking with duplicate key
  • Example#67 - Uso de array()
  • Example#68 - Colección
  • Example#69 - Cambiando elemento en el bucle
  • Example#70 - Índice con base 1
  • Example#71 - Llenado de un array
  • Example#72 - Ordenado de un array
  • Example#73 - Arrays recursivos y multi-dimensionales
  • Example#74 - Ejemplos de funciones de llamadas de retorno
  • Example#75 - Ejemplo de retrollamada utilizando un cierre
  • Example#76 - Ejemplo de de tipo de parámetro iterable
  • Example#77 - Ejemplo de valor predeterminado de un parámetro iterable
  • Example#78 - Ejemplo de tipo de retorno iterable
  • Example#79 - Ejemplo de tipo de retorno de generadro iterable
  • Example#80 - Ejemplo de varianza del tipo iterable
  • Example#81 -
  • Example#82 - Declaración de tipo de clase básica
  • Example#83 - Declaración de tipo de interfaz básica
  • Example#84 - Declaración de tipo de retorno básica
  • Example#85 - Retornando un objeto
  • Example#86 - Declaración de tipo de argumento Nullable
  • Example#87 - Declaración de tipo de retorno Nullable
  • Example#88 - Forma antigua de hacer argumentos nullable por defecto
  • Example#89 - Tipificación estricta para los valores de los argumentos
  • Example#90 - Tipificación coercitiva para valores de los argumentos
  • Example#91 - Tipificación estricta para valores de retorno
  • Example#92 - Ejemplo de tipos siendo forzados a formar parte del tipo Unión
  • Example#93 - Tipificación de parámetros pasados por referencia
  • Example#94 - Capturando TypeError
  • Example#95 - Valores predeterminados en variables sin inicializar
  • Example#96 - Uso de global
  • Example#97 - Uso de $GLOBALS en lugar de global
  • Example#98 - Ejemplo que demuestra las superglobales y el ámbito
  • Example#99 - Ejemplo que demuestra la necesidad de variables estáticas
  • Example#100 - Ejemplo del uso de variables estáticas
  • Example#101 - Variables estáticas con funciones recursivas
  • Example#102 - Declaración de variables estáticas
  • Example#103 - Ejemplo de propiedad variable
  • Example#104 - Un formulario HTML sencillo
  • Example#105 - Acceso a datos de un formulario HTML sencillo con POST
  • Example#106 - Old methods of accessing user input
  • Example#107 - Variables de formulario más complejas
  • Example#108 - Un ejemplo de setcookie
  • Example#109 - Nombres de constantes correctos e incorrectos
  • Example#110 - Definición de constantes
  • Example#111 - Definición de constantes usando el la palabra reservada const
  • Example#112 - Asociatividad
  • Example#113 - Orden de evaluación no definido
  • Example#114 - +, - y . tienen la misma precedencia
  • Example#115 - Asignación por referencia
  • Example#116 - Operaciones AND, OR y XOR bit a bit sobre integers
  • Example#117 - Operaciones XOR bit a bit sobre strings
  • Example#118 - Desplazamiento de bits sobre integers
  • Example#119 - Comparación boolean/null
  • Example#120 - Transcripción de la comparación estándar de arrays
  • Example#121 - Asignación de un valor predeterminado
  • Example#122 - Comportamiento Ternario poco obvio
  • Example#123 - Assigning a default value
  • Example#124 - Nesting null coalescing operator
  • Example#125 - Operaciones aritméticas sobre variables de caracteres
  • Example#126 - Los operadores lógicos ilustrados
  • Example#127 - Comparando arrays
  • Example#128 - Utilizando instanceof con clases
  • Example#129 - Utilizando instanceof con clases heredadas
  • Example#130 - Utilizando instanceof para verificar si un objeto no es una instancia de una clase
  • Example#131 - Utilizando instanceof para la clase
  • Example#132 - Utilizando instanceof con otras variables
  • Example#133 - Usar instanceof para comprobar otras variables
  • Example#134 - Evitando búsquedas del nombre de clase y errores fatales con instanceof en PHP 5.0
  • Example#135 - Estructura switch
  • Example#136 - Estrutura switch permite el uso de strings
  • Example#137 - Estructura de una expresión match
  • Example#138 - Ejemplo de una expresión match no controlada
  • Example#139 - Uso de expresiones match generalizadas para ramificar en rangos de integers
  • Example#140 - Uso de expresiones match generalizadas para ramificar el contenido de strings.
  • Example#141 - Ejemplo de uso del tick
  • Example#142 - Ejemplo de uso de ticks
  • Example#143 - Declarando un encoding para el script
  • Example#144 - Ejemplo básico de include
  • Example#145 - Incluyendo dentro de funciones
  • Example#146 - include por medio de HTTP
  • Example#147 - Comparando el valor de retorno de include
  • Example#148 - include y la sentencia return
  • Example#149 - Usando buffering de salida para incluir un archivo PHP dentro de una cadena
  • Example#150 - Ejemplo de goto
  • Example#151 - Ejemplo de goto en un bucle
  • Example#152 - Esto no funcionará
  • Example#153 - Seudocódigo para demostrar el uso de funciones
  • Example#154 - Funciones condicionales
  • Example#155 - Funciones dentro de funciones
  • Example#156 - Funciones recursivas
  • Example#157 - Pasar arrays a funciones
  • Example#158 - Paso de parámetros de una función por referencia
  • Example#159 - Uso de parámetros predeterminados en funciones
  • Example#160 - Usar tipos no escalares como valores predeterminados
  • Example#161 - Uso incorrecto de argumentos predeterminados en una función
  • Example#162 - Uso correcto de argumentos predeterminados en una función
  • Example#163 -
  • Example#164 - Declaración básica de tipo clase
  • Example#165 - Declaración básica de tipo interfaz
  • Example#166 - Tipos de parámetros pasados por referencia
  • Example#167 - Declaración de tipo nulo
  • Example#168 - Tipificación estricta
  • Example#169 - Tipificación débil
  • Example#170 - Capturar la excepción TypeError
  • Example#171 - Usando ... para acceder a argumentos variables
  • Example#172 - Usar ... para proporcionar argumentos
  • Example#173 - Argumentos variables de declaración de tipo
  • Example#174 - Acceder a argumentos variables en PHP 5.5 y anteriores
  • Example#175 - Named argument syntax
  • Example#176 - Positional arguments versus named arguments
  • Example#177 - Same example as above with a different order of parameters
  • Example#178 - Combining named arguments with positional arguments
  • Example#179 - Error exception when passing the same parameter multiple times
  • Example#180 - Empleo de return
  • Example#181 - Devolver un array para obtener múltiples valores
  • Example#182 - Devolver una referencia desde una función
  • Example#183 - Declaración básica de tipo de devolución
  • Example#184 - El modo estricto en acción
  • Example#185 - Devolver un objeto
  • Example#186 - Declaración de tipo de retorno anulable (a partir de PHP 7.1.0)
  • Example#187 - Ejemplo de función variable
  • Example#188 - Ejemplo de método variable
  • Example#189 - Ejemplo de método variable con propiedades estáticas
  • Example#190 - Llamables complejos
  • Example#191 - Ejemplo de función anónima
  • Example#192 - Ejemplo de asignación de variable de una función anónima
  • Example#193 - Heredar variables de un ámbito padre
  • Example#194 - Cierres y ámbito
  • Example#195 - Vinculación automática de $this
  • Example#196 - Intentar usar $this dentro de una función anónima estática
  • Example#197 - Intentar vincular un objeto a una función anónima estática
  • Example#198 - Las funciones de flecha capturan las variables por valor automáticamente
  • Example#199 - Las funciones de flecha capturan variables por valor automáticamente, incluso cuando están anidadas
  • Example#200 - Ejemplos de funciones de flecha
  • Example#201 - Los valores del alcance exterior no pueden ser modificados por las funciones de flecha
  • Example#202 - Simple first class callable syntax
  • Example#203 - Scope comparison of CallableExpr(...) and traditional callable
  • Example#204 -
  • Example#205 - Definición de una clase sencilla
  • Example#206 - Algunos ejemplos de la pseudovariable $this
  • Example#207 -
  • Example#208 -
  • Example#209 - Creación de una instancia
  • Example#210 - Asignación de objetos
  • Example#211 - Creación de nuevos objetos
  • Example#212 - Acceder a un miembro de un objeto recién creado
  • Example#213 - Acceso a propiedad contra llamada a método
  • Example#214 - Llamar a una función anónima almacenada en una propiedad
  • Example#215 - Herencia de clases sencilla
  • Example#216 - Compatible child methods
  • Example#217 - Fatal error when a child method removes a parameter
  • Example#218 - Fatal error when a child method makes an optional parameter mandatory
  • Example#219 - Error when using named arguments and parameters were renamed in a child class
  • Example#220 - Resolución de nombres de clases
  • Example#221 - Missing class name resolution
  • Example#222 - Object name resolution
  • Example#223 - Nullsafe Operator
  • Example#224 - Declaración de propiedades
  • Example#225 - Ejemplo de propiedades tipadas
  • Example#226 - Acceso a las propiedades
  • Example#227 - Ejemplo de propiedades de solo lectura
  • Example#228 - Inicialización ilegal de propiedades readonly
  • Example#229 -
  • Example#230 -
  • Example#231 -
  • Example#232 - Definición y uso de una constante
  • Example#233 - Ejemplo de datos estáticos
  • Example#234 - Ejemplo de ::class en espacio de nombres
  • Example#235 - Ejemplo de expresión constante
  • Example#236 - Modificadores de visibilidad de constantes de clase
  • Example#237 - Ejemplo de autocarga
  • Example#238 - Otro ejemplo de autocarga
  • Example#239 - Autocarga con manejo de excepciones para 5.3.0+
  • Example#240 - Autocarga con manejo de excepciones para 5.3.0+: Excepción personalizada ausente
  • Example#241 - Utilización de nuevos constructores unificados
  • Example#242 - Using constructor arguments
  • Example#243 - Using constructor property promotion
  • Example#244 - Using static creation methods
  • Example#245 - Ejemplo de Destructor
  • Example#246 - Declaración de propiedades
  • Example#247 - Declaración de métodos
  • Example#248 - Declaración de constantes a partir de PHP 7.1.0
  • Example#249 - Accediendo a miembros private del mismo tipo de objeto
  • Example#250 -
  • Example#251 - Ejemplo de herencia
  • Example#252 - The overriding method does not declare any return type
  • Example#253 - The overriding method declares a wrong return type
  • Example#254 - The overriding method declares a wrong return type without a deprecation notice
  • Example#255 - :: desde el exterior de la definición de la clase
  • Example#256 - :: desde el interior de la definición de la clase
  • Example#257 - Invocando a un método parent
  • Example#258 - Ejemplo de método estático
  • Example#259 - Ejemplo de propiedad estática
  • Example#260 - Ejemplo de clase abstracta
  • Example#261 - Ejemplo de clase abstracta
  • Example#262 - Ejemplo de interfaz
  • Example#263 - Interfaces extensibles
  • Example#264 - Herencia múltiple de interfaces
  • Example#265 - Interfaces con constantes
  • Example#266 - Ejemplo de rasgo
  • Example#267 - Ejemplo de Orden de Precedencia
  • Example#268 - Ejemplo de Orden de Precedencia #2
  • Example#269 - Uso de varios rasgos
  • Example#270 - Resolución de Conflictos
  • Example#271 - Modificar la Visibilidad de un Método
  • Example#272 - Traits compuestos de traits
  • Example#273 - Expresar Resquisitos con Métodos Abstractos
  • Example#274 - Variables estáticas
  • Example#275 - Métodos Estáticos
  • Example#276 - Definir Propiedades
  • Example#277 - Resolución de Conflictos
  • Example#278 - Sobrecarga de propiedades mediante los métodos __get(), __set(), __isset() y __unset()
  • Example#279 - Sobrecarga de métodos mediante los métodos __call() and __callStatic()
  • Example#280 - Iteración simple de un objeto
  • Example#281 - Iteración de un objeto implementando Iterator
  • Example#282 - Iteración de un objeto implementando IteratorAggregate
  • Example#283 - Sleep y wakeup
  • Example#284 - Serialize y unserialize
  • Example#285 - Ejemplo simple
  • Example#286 - Uso de __invoke()
  • Example#287 - Uso de __set_state()
  • Example#288 - Utilizar __debugInfo()
  • Example#289 - Ejemplo de métodos Final
  • Example#290 - Ejemplo de clase Final
  • Example#291 - Ejemplo de constantes finales a partir de PHP 8.1.0
  • Example#292 - Clonación de un objeto
  • Example#293 - Acceder a un miembre del objeto recién clonado
  • Example#294 - Ejemplo de comparación de objetos en PHP 5
  • Example#295 - Uso de self::
  • Example#296 - Uso básico de static::
  • Example#297 - Uso de static:: en un contexto no estático
  • Example#298 - Llamadas que propagan y que no propagan la información de llamada
  • Example#299 - Referencias y Objetos
  • Example#300 - Ejemplo de sintaxis de espacios de nombres
  • Example#301 - Declarar un único espacio de nombres
  • Example#302 - Declarar un único espacio de nombres
  • Example#303 - Declarar un único espacio de nombres con jerarquía
  • Example#304 - Declarar varios espacios de nombres, sintaxis de combinación simple
  • Example#305 - Declarar varios espacios de nombres, sintaxis de llaves
  • Example#306 - Declarar múltiples espacios de nombres y código que no es de espacio de nombres
  • Example#307 - Declarar varios espacios de nombres y código que no es de espacio de nombres
  • Example#308 - Acceder a clases, funciones y constantes globales desde un espacio de nombres
  • Example#309 - Acceder dinámicamente a elementos
  • Example#310 - Acceder dinámicamente a elementos de un espacio de nombres
  • Example#311 - Ejemplo de __NAMESPACE__, código de espacio de nombres
  • Example#312 - Ejemplo de __NAMESPACE__, código global
  • Example#313 - Empleo de __NAMESPACE__ para la construcción dinámica de nombres
  • Example#314 - El operador namespace, dentro de un espacio de nombres
  • Example#315 - El operador namespace, en código global
  • Example#316 - Importar/apodar con el operador use
  • Example#317 - Importar/apodar con el operador use, varias sentencias use combinadas
  • Example#318 - La importación y los nombres dinámicos
  • Example#319 - La importación y los nombres completamente cualificados
  • Example#320 - Regla de importación ilegal
  • Example#321 - Usar la especificación de espacio global
  • Example#322 - Acceder a clases globales dentro de un espacio de nombres
  • Example#323 - Recurrir a funciones/constantes globales dentro de un espacio de nombres
  • Example#324 - Las resoluciones de nombres ilustradas
  • Example#325 - Acceder a clases globales fuera de un espacio de nombres
  • Example#326 - Acceder a clases globales fuera de un espacio de nombres
  • Example#327 - Acceder a clases internas en espacios de nombres
  • Example#328 - Acceder a clases, funciones o constantes internas en un espacio de nombres
  • Example#329 - Nombres completamente cualificados
  • Example#330 - Nombres cualificados
  • Example#331 - Nombres de clases no cualificados
  • Example#332 - Nombres de funciones o constantes no cualificados
  • Example#333 - Peligros de usar nombres de espacios de nombres dentro de una cadena entre comillas dobles
  • Example#334 - Constantes no definidas
  • Example#335 - Constantes no definidas
  • Example#336 - Basic limited values
  • Example#337 - Advanced exclusive values
  • Example#338 - La clase Exception Interna
  • Example#339 - Extender la clase Exception (PHP 5.3.0+)
  • Example#340 - Lanzar una Excepción
  • Example#341 - Manejo de excepciones con un bloque finally
  • Example#342 - Excepciones anidadas
  • Example#343 - Basic usage
  • Example#344 - Implementando range como generador
  • Example#345 - Ejemplo sencillo de facilitar valores con yield
  • Example#346 - Facilitar un par clave-valor
  • Example#347 - Yielding nulls
  • Example#348 - Facilitar valores por referencia
  • Example#349 - yield from con iterator_to_array
  • Example#350 - Uso básico de yield from
  • Example#351 - yield from y valores devueltos
  • Example#352 - Implementing optional methods of an interface with Attributes
  • Example#353 - Attribute Syntax
  • Example#354 - Reading Attributes using Reflection API
  • Example#355 - Reading Specific Attributes using Reflection API
  • Example#356 - Simple Attribute Class
  • Example#357 - Using target specification to restrict where attributes can be used
  • Example#358 - Using IS_REPEATABLE to allow attribute on a declaration multiple times
  • Example#359 - Usar referencias con variables no definidas
  • Example#360 - Refenciar variables globales dentro de funciones
  • Example#361 - Referencias y la sentencia foreach
  • Example#362 - Ejemplo de $GLOBALS
  • Example#363 - Ejemplo de $_SERVER
  • Example#364 - Ejemplo de $_GET
  • Example#365 - Ejemplo de $_POST
  • Example#366 - Ejemplo de $_ENV
  • Example#367 - Ejemplo de $_COOKIE
  • Example#368 - Ejemplo de $php_errormsg
  • Example#369 - Ejemplo de $http_response_header
  • Example#370 - Ejemplo de $argc
  • Example#371 - Ejemplo de $argv
  • Example#372 - Ejemplo de Exception::getMessage
  • Example#373 - Ejemplo de Exception::getPrevious
  • Example#374 - Ejemplo de Exception::getCode
  • Example#375 - Ejemplo de Exception::getFile
  • Example#376 - Ejemplo de Exception::getLine
  • Example#377 - Ejemplo de Exception::getTrace
  • Example#378 - Ejemplo de Exception::getTraceAsString
  • Example#379 - Ejemplo de Exception::__toString
  • Example#380 - Utilizar set_error_handler para convertir mensajes de error en objetos ErrorException.
  • Example#381 - Ejemplo de ErrorException::getSeverity
  • Example#382 - Ejemplo de Error::getMessage
  • Example#383 - Ejemplo de Error::getPrevious
  • Example#384 - Ejemplo de Error::getCode
  • Example#385 - Ejemplo de Error::getFile
  • Example#386 - Ejemplo de Error::getLine
  • Example#387 - Ejemplo de Error::getTrace
  • Example#388 - Ejemplo de Error::getTraceAsString
  • Example#389 - Ejemplo de Error::__toString
  • Example#390 - Uso básico
  • Example#391 - Basic usage
  • Example#392 - Uso básico
  • Example#393 - Ejemplo de ArrayAccess::offsetExists
  • Example#394 - Uso básico
  • Example#395 - Ejemplo de Closure::bind
  • Example#396 - Ejemplo de Closure::bindTo
  • Example#397 - Ejemplo de Closure::call
  • Example#398 - Created as a result of typecasting to object
  • Example#399 - Created as a result of json_decode
  • Example#400 - Declaring dynamic properties
  • Example#401 - Ejemplo de Generator::getReturn
  • Example#402 - Ejemplo de Generator::key
  • Example#403 - Empleo de Generator::send para inyectar valores
  • Example#404 - Lanzar una ecepión dentro de un generador
  • Example#405 - Uso básico de WeakReference
  • Example#406 - Weakmap usage example
  • Example#407 - Basic Stringable Usage
  • Example#408 - Basic usage
  • Example#409 - Basic usage
  • Example#410 - Basic usage
  • Example#411 - Passing a SensitiveParameterValue object to var_dump
  • Example#412 - SensitiveParameterValue::getValue example
  • Example#413 -
  • Example#414 -
  • Example#415 - Ejemplo de uso básico de bindto
  • Example#416 - Obtener una página y enviar datos POST
  • Example#417 - Ignorar las redirecciones, aunque obtener las cabeceras y el contenido
  • Example#418 - Obtener una página y enviar datos POST
  • Example#419 - Ejemplo de uso básico password
  • Example#420 - Detectar la URL en la que se finaliza tras las redirecciones
  • Example#421 - php://temp/maxmemory
  • Example#422 - php://filter/resource=<flujo a filtrar>
  • Example#423 - php://filter/read=<lista de filtros a aplicar a la cadena de lectura>
  • Example#424 - php://filter/write=<lista de filtros a aplicar a la cadena de escritura>
  • Example#425 - php://memory y php://temp no son reutilizables
  • Example#426 - Mostrar contenidos de data://
  • Example#427 - Obtener el Tipo de Medio
  • Example#428 - Uso básico
  • Example#429 - Abriendo un flujo a partir de una conexión activa
  • Example#430 - ¡La variable $session debe permanecer disponible!
  • Example#431 - Recorriendo un archivo RAR
  • Example#432 - Abriendo un fichero encriptado (encriptación de cabeceras)
  • Example#433 - Un control pobre puede llevar a ....
  • Example#434 - ... Un ataque al sistema de archivos
  • Example#435 - Comprobación más segura del nombre de archivo
  • Example#436 - Comprobación más segura del nombre de archivo
  • Example#437 - Script vulnerable a bytes nulos
  • Example#438 - Validando correctamente la entrada
  • Example#439 - Campo de contraseña con hash
  • Example#440 - Dividir el conjunto de resultados en páginas ... y crear superusuarios (PostgreSQL)
  • Example#441 - Enumerar artículos ... y algunas contraseñas (cualquier servidor de bases de datos)
  • Example#442 - Desde restablecer una contraseña ... hasta obtener más privilegios (cualquier servidor de bases de datos)
  • Example#443 - Atacar el sistema operativo del host de la base de datos (MSSQL Server)
  • Example#444 - Evitar la inyección SQL mediante el uso de declaraciones preparadas con PDO
  • Example#445 - Atacando variables con una página HTML personalizada
  • Example#446 - Explotando variables comunes de depuración
  • Example#447 - Buscando variables peligrosas con E_ALL
  • Example#448 - Uso Peligroso de Variables
  • Example#449 - Ocultando PHP como si fuera otro lenguaje
  • Example#450 - Utilizar tipos desconocidos para extensiones de PHP
  • Example#451 - Utilizar tipos HTML para extensiones de PHP
  • Example#452 - Ejemplo de autenticación HTTP 'Basic'
  • Example#453 - Ejemplo de autenticación HTTP 'Digest'
  • Example#454 - Ejemplo de autenticación HTTP forzando un nuevo usuario/contraseña
  • Example#455 - Un formulario simple de búsqueda con XForms
  • Example#456 - Empleo de un Xform para rellenar $_POST
  • Example#457 - Formulario para la subida de ficheros
  • Example#458 - Validación de la subida de ficheros
  • Example#459 - Subir un array de ficheros
  • Example#460 - Subida de varios ficheros
  • Example#461 - Guardar ficheros PUT de HTTP
  • Example#462 - Obtener el título de una página remota
  • Example#463 - Almacenar datos en un servidor remoto
  • Example#464 - Ejemplo que muestra las diferencias respecto a la SAPI CGI:
  • Example#465 -
  • Example#466 - Muestra los módulos PHP y Zend incorporados (y habilitados)
  • Example#467 - Obteniendo un error sintáctico usando comillas dobles
  • Example#468 - Usando comillas simples para prevenir la sustitución de variables de la consola
  • Example#469 - Usando las opciones -B, -R y -E para contar el número de líneas de un proyecto.
  • Example#470 - Al usar -v obtenemos el nombre de la SAPI y la versión de PHP y Zend
  • Example#471 - Ejemplo de --ini
  • Example#472 - Uso básico de --rf
  • Example#473 - Ejemplo de --rc
  • Example#474 - Ejemplo de --re
  • Example#475 - Ejemplo de --ri
  • Example#476 - Ejecutando un script PHP como un script de consola
  • Example#477 - Script destinado a ejecutarse desde la línea de comandos (script.php)
  • Example#478 - Fichero por lotes para ejecutar un script PHP en línea de comandos (script.bat)
  • Example#479 - Ejecutando código desde la consola interactiva
  • Example#480 - Autocompletado con el tabulador
  • Example#481 - Estableciendo configuraciones de php.ini en la shell interactiva
  • Example#482 - Iniciando el servidor web
  • Example#483 - Iniciando con una raíz de documentos específica
  • Example#484 - Utilizando un Script enrutador
  • Example#485 - Revisión del uso de la CLI del servidor web
  • Example#486 - Manejando tipos de ficheros no soportados
  • Example#487 - Accediendo a la CLI del servidor web desde máquinas remotas
  • Example#488 - Creación de un nuevo contenedor zval
  • Example#489 - Mostrar información de zval
  • Example#490 - Incremento de refcount de un zval
  • Example#491 - Decremento de refcount de zval
  • Example#492 - Crear un zval de tipo array
  • Example#493 - Añadir un elemento existente a un array
  • Example#494 - Eliminar un elemento de un array
  • Example#495 - Añadir el propio array como elemento de sí mismo
  • Example#496 - Eliminar $a
  • Example#497 - Ejemplo de uso de memoria
  • Example#498 - Influencia en rendimiento de Recolector de Basuras
  • Example#499 - Ejecutando el script anterior
  • Example#500 - Recompilando PHP para habilitar el análisis del Recolector de Basuras
  • Example#501 - Estadísticas de Recolección de Basuras
  • Example#502 - all_probes.d para monitorizar todos los Sondeos Estáticos en PHP con DTrace
  • Example#503 - all_probes.stp para monitorizar todas los Sondeos Estáticos de PHP con SystemTap
  • Example#504 - A apcu_add example
  • Example#505 - Un ejemplo de apcu_cache_info
  • Example#506 - Ejemplo de apcu_cas
  • Example#507 - Ejemplo de apcu_dec
  • Example#508 - Un ejemplo deapcu_delete
  • Example#509 - An apcu_entry example
  • Example#510 - apcu_exists example
  • Example#511 - A apcu_fetch example
  • Example#512 - apcu_inc example
  • Example#513 - A apcu_key_info example
  • Example#514 - A apcu_sma_info example
  • Example#515 - A apcu_store example
  • Example#516 - Un ejemplo de APCUIterator::__construct
  • Example#517 - Usar el manejo de errores en un script
  • Example#518 - Ejemplo de debug_backtrace
  • Example#519 - Ejemplo de debug_print_backtrace
  • Example#520 - Un ejemplo de error_clear_last
  • Example#521 - Un ejemplo de error_get_last
  • Example#522 - Ejemplos de error_log
  • Example#523 - Ejemplos de error_reporting
  • Example#524 - Ejemplo de restore_error_handler
  • Example#525 - Ejemplo de restore_exception_handler
  • Example#526 - Manejo de errores con set_error_handler y trigger_error
  • Example#527 - Ejemplo de set_exception_handler
  • Example#528 - Ejemplo de trigger_error
  • Example#529 - Calling a function from shared library
  • Example#530 - Calling a function, returning a structure through an argument
  • Example#531 - Accessing existing C variables
  • Example#532 - Creating and Modifying C variables
  • Example#533 - Working with C arrays
  • Example#534 - Working with C enums
  • Example#535 -
  • Example#536 -
  • Example#537 - Ejemplo de control de la salida
  • Example#538 - Ejemplo de ob_end_clean
  • Example#539 - Ejemplo de ob_end_flush
  • Example#540 - Un ejemplo sencillo de ob_get_clean
  • Example#541 - Un ejemplo sencillo de ob_get_contents
  • Example#542 - Ejemplo de ob_get_flush
  • Example#543 - Un ejemplo sencillo de ob_get_length
  • Example#544 - Ejemplo de ob_gzhandler
  • Example#545 - Ejemplo de ob_list_handlers
  • Example#546 - Ejemplo de una función de llamada de retorno definida por el usuario
  • Example#547 - Crear un búfer de salida imborrable de forma compatible con PHP 5.3 y 5.4
  • Example#548 - Ejemplo de output_add_rewrite_var
  • Example#549 - Ejemplo de output_reset_rewrite_vars
  • Example#550 - Ejemplo de assert_options
  • Example#551 - Handle a failed assertion with a custom handler
  • Example#552 - Using a custom handler to print a description
  • Example#553 - Expectations without a custom exception
  • Example#554 - Expectations with a custom exception
  • Example#555 - cli_get_process_title example
  • Example#556 - cli_set_process_title example
  • Example#557 - Ejemplos de dl
  • Example#558 - Ejemplo de extension_loaded
  • Example#559 - Ejemplo de gc_enabled
  • Example#560 - gc_status Usage
  • Example#561 - get_current_user ejemplo
  • Example#562 - Ejemplo de get_defined_constants
  • Example#563 - Imprime las funciones XML
  • Example#564 - Ejemplo de get_include_path
  • Example#565 - Ejemplo de get_included_files
  • Example#566 - get_loaded_extensions
  • Example#567 - get_magic_quotes_runtime ejemplo
  • Example#568 - Unfiltered get_resources
  • Example#569 - Filtered get_resources
  • Example#570 - Ejemplo de getenv
  • Example#571 - Ejemplo de getlastmod
  • Example#572 - Ejemplo de getopt: Lo básico
  • Example#573 - Ejemplo de getopt: Introducir opciones long
  • Example#574 - Ejemplo de getopt: Pasar varias opciones como una
  • Example#575 - getrusage ejemplo
  • Example#576 - ini_get_all ejemplos
  • Example#577 - Disabling details
  • Example#578 - Unos cuantos ejemplos de la función ini_get
  • Example#579 - A few ini_parse_quantity examples
  • Example#580 - ini_restore ejemplo
  • Example#581 - Establece una opción ini
  • Example#582 - A memory_get_usage ejemplo
  • Example#583 - memory_reset_peak_usage example
  • Example#584 - php_ini_loaded_file ejemplo
  • Example#585 - Un ejemplo simple para enumerar los archivos ini devueltos
  • Example#586 - Ejemplo de php_sapi_name
  • Example#587 - Algúnos ejemplos de php_uname
  • Example#588 - Algunos ejemplos de las constantes relacionadas al SO
  • Example#589 - Imprimir los créditos generales
  • Example#590 - Imprimir los desarrolladores principales y el grupo de documentación
  • Example#591 - Imprimir todos los créditos
  • Example#592 - Ejemplo de phpinfo
  • Example#593 - phpversion Ejemplo básico
  • Example#594 - PHP_VERSION_ID Ejemplo y uso
  • Example#595 - Definición de una variable de entorno
  • Example#596 - Ejemplo de restore_include_path
  • Example#597 - Ejemplo de set_include_path
  • Example#598 - Añadir a la ruta de inclusión
  • Example#599 - sys_get_temp_dir example
  • Example#600 - Ejemplos de version_compare
  • Example#601 - Ejemplo de zend_thread_id
  • Example#602 - Ejemplo de zend_version
  • Example#603 - Superglobales personalizadas con runkit.superglobal=_FOO,_BAR en php.ini
  • Example#604 - Un ejemplo de runkit_function_add
  • Example#605 - Un ejemplo de runkit_function_copy
  • Example#606 - Un ejemplo de runkit_function_redefine
  • Example#607 - Ejemplo de runkit_import
  • Example#608 - Ejemplo de runkit_method_add
  • Example#609 - Ejemplo de runkit_method_copy
  • Example#610 - Ejemplo de runkit_method_redefine
  • Example#611 - Ejemplo de runkit_method_remove
  • Example#612 - Ejemplo derunkit_method_rename
  • Example#613 - runkit7_zval_inspect example
  • Example#614 - Basic uopz_add_function Usage
  • Example#615 - uopz_allow_exit example
  • Example#616 - uopz_backup example
  • Example#617 - uopz_compose example
  • Example#618 - uopz_copy example
  • Example#619 - Basic uopz_del_function Usage
  • Example#620 - uopz_delete example
  • Example#621 - uopz_delete class example
  • Example#622 - uopz_extend example
  • Example#623 - uopz_flags example
  • Example#624 - "Unfinalize" a Class
  • Example#625 - uopz_function example
  • Example#626 - uopz_function class example
  • Example#627 - uopz_get_exit_status example
  • Example#628 - Basic uopz_get_hook Usage
  • Example#629 - uopz_get_mock example
  • Example#630 - Basic uopz_get_property Usage
  • Example#631 - uopz_get_return example
  • Example#632 - Basic uopz_get_static Usage
  • Example#633 - uopz_implement example
  • Example#634 - uopz_overload example
  • Example#635 - uopz_redefine example
  • Example#636 - uopz_rename example
  • Example#637 - uopz_rename class example
  • Example#638 - uopz_restore example
  • Example#639 - Basic uopz_set_hook Usage
  • Example#640 - uopz_set_mock example
  • Example#641 - uopz_set_mock example
  • Example#642 - uopz_set_mock and static members
  • Example#643 - Basic uopz_set_property Usage
  • Example#644 - uopz_set_return example
  • Example#645 - uopz_set_return example
  • Example#646 - uopz_set_return class example
  • Example#647 - Basic uopz_set_static Usage
  • Example#648 - uopz_undefine example
  • Example#649 - Basic uopz_unset_hook Usage
  • Example#650 - uopz_unset_mock example
  • Example#651 - uopz_unset_return example
  • Example#652 - Ejemplo de wincache.ignorelist
  • Example#653 - Authentication configuration for wincache.php
  • Example#654 - Enabling WinCache session handler
  • Example#655 - Enabling WinCache functions reroutes
  • Example#656 - Reroute.ini file content
  • Example#657 - A wincache_fcache_fileinfo example
  • Example#658 - Un ejemplo de wincache_fcache_meminfo
  • Example#659 - Empleo de wincache_lock
  • Example#660 - A wincache_ocache_fileinfo example
  • Example#661 - A wincache_ocache_meminfo example
  • Example#662 - A wincache_refresh_if_changed example
  • Example#663 - A wincache_rplist_fileinfo example
  • Example#664 - A wincache_rplist_meminfo example
  • Example#665 - A wincache_scache_info example
  • Example#666 - Ejemplo de wincache_scache_meminfo
  • Example#667 - wincache_ucache_add with key as a string
  • Example#668 - wincache_ucache_add with key as an array
  • Example#669 - Usando wincache_ucache_cas
  • Example#670 - Usando wincache_ucache_clear
  • Example#671 - Usando wincache_ucache_dec
  • Example#672 - Usando wincache_ucache_delete con key como un string
  • Example#673 - Usingwincache_ucache_delete con key como un array
  • Example#674 - Using wincache_ucache_delete con key como un array donde algunos elementos no se pueden eliminar
  • Example#675 - Usando wincache_ucache_exists
  • Example#676 - wincache_ucache_get con key como un string
  • Example#677 - wincache_ucache_get con key como un array
  • Example#678 - Usando wincache_ucache_inc
  • Example#679 - Usar wincache_ucache_info
  • Example#680 - Ejemplo de wincache_ucache_meminfo
  • Example#681 - wincache_ucache_set with key as a string
  • Example#682 - wincache_ucache_set with key as an array
  • Example#683 - Usar wincache_unlock
  • Example#684 - Ejemplo Xhprof con interfaz gráfica de usuario opcional
  • Example#685 - xhprof_disable ejemplo
  • Example#686 - Ejemplos de xhprof_enable
  • Example#687 - Ejemplo de xhprof_sample_disable
  • Example#688 - Asegúrate de que el artículo se almacene
  • Example#689 - Using CHAP passwords
  • Example#690 - radius_acct_open example
  • Example#691 - radius_add_server example
  • Example#692 - Ejemplo de radius_auth_open
  • Example#693 - radius_create_request example
  • Example#694 - radius_cvt_addr example
  • Example#695 - radius_cvt_int example
  • Example#696 - radius_cvt_string example
  • Example#697 - radius_get_attr example
  • Example#698 - radius_get_tagged_attr_data example
  • Example#699 - radius_get_tagged_attr_tag example
  • Example#700 - radius_get_vendor_attr example
  • Example#701 - radius_put_attr example
  • Example#702 - radius_put_int example
  • Example#703 - radius_put_string example
  • Example#704 - radius_put_vendor_attr example
  • Example#705 - Ejemplo de interfaz de llamada readline
  • Example#706 - Ejemplo de readline
  • Example#707 - Pequeño ejemplo de bzip2
  • Example#708 - Comprimiendo datos
  • Example#709 - Descompresión de un String
  • Example#710 - Ejemplo de bzerror
  • Example#711 - Ejemplo de bzopen
  • Example#712 - ejemplo de bzread
  • Example#713 - Ejemplo de bzwrite
  • Example#714 - Utilizar un fichero externo
  • Example#715 - Utilizar un fichero dentro de un archivo phar
  • Example#716 - Convertir un archivo phar, desde phar al formato de fichero tar
  • Example#717 - Ejemplo de uso de phar.cache_list
  • Example#718 - Un ejemplo de Phar::addEmptyDir
  • Example#719 - Un ejemplo de Phar::addFile
  • Example#720 - Un ejemplo de Phar::addFromString
  • Example#721 - Un ejemplo de Phar::apiVersion
  • Example#722 - Un ejemplo de Phar::buildFromDirectory
  • Example#723 - Un ejemplo de Phar::buildFromIterator con SplFileInfo
  • Example#724 - Un ejemplo de Phar::buildFromIterator con otros iteradores
  • Example#725 - Un ejemplo de Phar::canCompress
  • Example#726 - Un ejemplo de Phar::canWrite
  • Example#727 - Un ejemplo de Phar::compress
  • Example#728 - Un ejemplo de Phar::compressFiles
  • Example#729 - Un ejemplo de Phar::__construct
  • Example#730 - Un ejemplo de Phar::convertToData
  • Example#731 - Un ejemplo de Phar::convertToExecutable
  • Example#732 - Un ejemplo de Phar::copy
  • Example#733 - Phar::count ejemplo
  • Example#734 - Un ejemplo de Phar::createDefaultStub
  • Example#735 - Un ejemplo de Phar::decompress
  • Example#736 - Un ejemplo de Phar::decompressFiles
  • Example#737 - Un ejemplo de Phar::delMetaData
  • Example#738 - Un ejemplo de Phar::delete
  • Example#739 - Un ejemplo de Phar::extractTo
  • Example#740 - Un ejemplo de Phar::getMetadata
  • Example#741 - Un ejemplo de Phar::getStub
  • Example#742 - Un ejemplo de Phar::hasMetadata
  • Example#743 - Un ejemplo de Phar::interceptFileFuncs
  • Example#744 - Un ejemplo de Phar::interceptFileFuncs
  • Example#745 - Un ejemplo de Phar::isBuffering
  • Example#746 - Un ejemplo de Phar::isCompressed
  • Example#747 - Un ejemplo de Phar::loadPhar
  • Example#748 - Un ejemplo de Phar::mapPhar
  • Example#749 - Un ejemplo de Phar::mount
  • Example#750 - Un ejemplo de Phar::mungServer
  • Example#751 - Un ejemplo de Phar::offsetExists
  • Example#752 - Ejemplo de Phar::offsetGet
  • Example#753 - Un ejemplo de Phar::offsetSet
  • Example#754 - Un ejemplo de Phar::offsetUnset
  • Example#755 - Un ejemplo de Phar::running
  • Example#756 - Un ejemplo de Phar::setAlias
  • Example#757 - Un ejemplo de Phar::setDefaultStub
  • Example#758 - Un ejemplo de Phar::setMetadata
  • Example#759 - Un ejemplo de Phar::setStub
  • Example#760 - Un ejemplo de Phar::startBuffering
  • Example#761 - Un ejemplo de Phar::stopBuffering
  • Example#762 - Un ejemplo de Phar::unlinkArchive
  • Example#763 - Un ejemplo de Phar::webPhar
  • Example#764 - Un ejemplo de PharData::addEmptyDir
  • Example#765 - Un ejemplo de PharData::addFile
  • Example#766 - Un ejemplo de PharData::addFromString
  • Example#767 - Un ejemplo de PharData::buildFromDirectory
  • Example#768 - Un ejemplo de PharData::buildFromIterator con SplFileInfo
  • Example#769 - Un ejemplo de PharData::buildFromIterator con otros iteradores
  • Example#770 - Un ejemplo de PharData::compress
  • Example#771 - Un ejemplo de PharData::compressFiles
  • Example#772 - Un ejemplo de PharData::__construct
  • Example#773 - Un ejemplo de PharData::convertToData
  • Example#774 - Un ejemplo de PharData::convertToExecutable
  • Example#775 - Un ejemplo de Phar::copy
  • Example#776 - Un ejemplo de PharData::decompress
  • Example#777 - Un ejemplo de PharData::decompressFiles
  • Example#778 - Un ejemplo de PharData::delMetaData
  • Example#779 - Un ejemplo de PharData::delete
  • Example#780 - Un ejemplo de PharData::extractTo
  • Example#781 - Un ejemplo de PharData::offsetSet
  • Example#782 - Un ejemplo de PharData::offsetUnset
  • Example#783 - Un ejemplo de Phar::setMetadata
  • Example#784 - Un ejemplo de PharFileInfo::chmod
  • Example#785 - Un ejemplo de PharFileInfo::compress
  • Example#786 - Un ejemplo de PharFileInfo::__construct
  • Example#787 - Un ejemplo de PharFileInfo::decompress
  • Example#788 - Un ejemplo de PharFileInfo::delMetaData
  • Example#789 - Un ejemplo de PharFileInfo::getCRC32
  • Example#790 - Un ejemplo de PharFileInfo::getCompressedSize
  • Example#791 - Un ejemplo de PharFileInfo::getMetadata
  • Example#792 - Un ejemplo de PharFileInfo::getPharFlags
  • Example#793 - Un ejemplo de PharFileInfo::isCRCChecked
  • Example#794 - Un ejemplo de PharFileInfo::isCompressed
  • Example#795 - Un ejemplo de PharFileInfo::setMetadata
  • Example#796 - Instalación Rar
  • Example#797 - Descompresión "al vuelo"
  • Example#798 - Ejemplo de sistema de extracción de archivos Rar
  • Example#799 - Estilo orientado a objetos
  • Example#800 - Estilo por procedimientos
  • 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 - Volume Callback
  • Example#814 - Estilo orientado a objetos
  • Example#815 - Estilo por procedimientos
  • Example#816 - Ejemplo de RarArchive::__toString
  • Example#817 - Ejemplo de RarEntry::extract
  • Example#818 - ¿Cómo extraer todos los archivos en archivo?:
  • Example#819 - Ejemplo de RarEntry::getAttr
  • Example#820 - Ejemplo de RarEntry::getHostOs (version >= 2.0.0)
  • Example#821 - RarEntry::getHostOs example (version <= 1.0.0)
  • Example#822 - Ejemplo de RarEntry::getMethod
  • Example#823 - Ejemplo de RarEntry::getName
  • Example#824 - Ejemplo de RarEntry::getPackedSize
  • Example#825 - Ejemplo de RarEntry::getStream
  • Example#826 - Ejemplo de RarEntry::getUnpackedSize
  • Example#827 - Ejemplo de RarEntry::getVersion
  • Example#828 - Ejemplo de RarException::isUsingExceptions
  • Example#829 - Ejemplo de RarException::setUsingExceptions
  • Example#830 - Crear un fichero Zip
  • Example#831 - Volcar la información del archivo y listarlos
  • Example#832 - Usando contenedor Zip, leer meta info de OpenOffice
  • Example#833 - Ejemplo del uso de Zip
  • Example#834 - Crea un nuevo directorio en un archivo
  • Example#835 - Abrir y extraer
  • Example#836 - Añade una entrada al nuevo fichero
  • Example#837 - Añade un fichero en un directorio dentro de un archivo
  • Example#838 - Ejemplo con ZipArchive::addGlob
  • Example#839 - Ejemplo con ZipArchive::addPattern
  • Example#840 - Elimina el fichero desde el archivo usando su índice
  • Example#841 - Eliminado un fichero y un directorio desde un archivo, usando nombres
  • Example#842 - Extraer todas las entradas
  • Example#843 - Extraer dos entradas
  • Example#844 - Vuelca el comentario del archivo
  • Example#845 - Test if archive is a torrentzip format
  • Example#846 - Vuelca el comentario de la entrada
  • Example#847 - Vuelca el comentario de la entrada
  • Example#848 - Extraer todas las entradas con permisos Unix
  • Example#849 - Obtener el contenido del fichero
  • Example#850 - Obtener el contenido de los ficheros
  • Example#851 - Convierte una imagen desde una entrada de fichero zip
  • Example#852 - Ejemplo de ZipArchive::getNameIndex
  • Example#853 - Obtiene los contenidos de entrada con fread y lo almacena
  • Example#854 - Lo mismo como el ejemplo anterior pero con fopen y el envoltorio de flujo de zip
  • Example#855 - El flujo de envoltorio y la imagen, también pueden ser utilizados con la función xml
  • Example#856 - Get the entry contents with fread and store it
  • Example#857 - Get the entry contents with fread and store it
  • Example#858 - Crear un archivo y luego utilizarlo con ZipArchive::locateName
  • Example#859 - Abrir y extraer
  • Example#860 - Crear un fichero
  • Example#861 - Crear un fichero temporal
  • Example#862 - Archive a file
  • Example#863 - Archive a file
  • Example#864 - Renombra una entrada
  • Example#865 - Renombra una entrada
  • Example#866 - Abrir y reemplazar
  • Example#867 - Crear un archivo y establecer un comentario
  • Example#868 - Create a torrentzip archive
  • Example#869 - Abrir un archivo y establecer un comentario para una entrada
  • Example#870 - Abrir un archivo y establecer un comentario para una entrada
  • Example#871 - Añadir ficheros con diferentes métodos de compresión a un archivo
  • Example#872 - Añadir ficheros con diferentes métodos de compresión a un archivo
  • Example#873 - Añadir fichero y establecer el método de compresión
  • Example#874 - Archivar y encriptar un archivo
  • Example#875 - Archivar un fichero, con sus permisos Unix
  • Example#876 - Archivar un fichero
  • Example#877 - Archivar un fichero
  • Example#878 - Volcar la información estadística de una entrada
  • Example#879 - Volcar la información estadística de una entrada
  • Example#880 - Pequeño Ejemplo de Zlib
  • Example#881 - Trabajando con la API de compresión y descompresión increemental
  • Example#882 - Ejemplo de gzclose
  • Example#883 - Ejemplo de gzcompress
  • Example#884 - Ejemplo de gzdeflate
  • Example#885 - Creando un archivo gzip
  • Example#886 - Ejemplo de gzeof
  • Example#887 - Ejemplo de gzfile
  • Example#888 - Ejemplo de gzgetc
  • Example#889 - Ejemplo de gzgets
  • Example#890 - Ejemplo de gzgetss
  • Example#891 - Ejemplo de gzinflate
  • Example#892 - Ejemplo de gzopen
  • Example#893 - Ejemplo de gzpassthru
  • Example#894 - Ejemplo de gzread
  • Example#895 - Ejamplo de gzseek
  • Example#896 - Ejemplo de gzuncompress
  • Example#897 - Ejemplo de gzwrite
  • Example#898 - Ejemplo de zlib_encode
  • Example#899 - hash_algos ejemplo
  • Example#900 - Ejemplo de hash_copy
  • Example#901 - Ejemplo hash_equals
  • 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 - mcrypt_create_iv Example
  • Example#914 - mcrypt_enc_get_algorithms_name example
  • Example#915 - mcrypt_enc_get_modes_name example
  • Example#916 - mcrypt_enc_get_supported_key_sizes example
  • Example#917 - mcrypt_encrypt Example
  • Example#918 - mcrypt_get_block_size example
  • Example#919 - mcrypt_get_cipher_name Example
  • Example#920 - mcrypt_get_iv_size Example
  • Example#921 - mcrypt_get_key_size Example
  • Example#922 - mcrypt_list_algorithms Example
  • Example#923 - mcrypt_list_modes Example
  • Example#924 - mcrypt_module_open Examples
  • Example#925 - Using mcrypt_module_open in encryption
  • Example#926 - mcrypt_module_self_test example
  • Example#927 - mdecrypt_generic Example
  • Example#928 - Computes the MD5 digest and hmac and print it out as hex
  • Example#929 - Traversing all hashes
  • Example#930 - mhash_get_block_size Example
  • Example#931 - mhash_get_hash_name Example
  • Example#932 - Ejemplo de openssl_cipher_iv_length
  • Example#933 - openssl_cipher_key_length example
  • Example#934 - openssl_cms_sign example
  • Example#935 - Crear un certificado autofirmado
  • Example#936 - Ejemplo de openssl_csr_sign - firmar una CSR (cómo implementar su propia AC)
  • Example#937 - Ejemplo de openssl_error_string
  • Example#938 - Ejemplo de openssl_get_cert_locations
  • Example#939 - Ejemplo de openssl_get_cipher_methods
  • Example#940 - openssl_get_curve_names example
  • Example#941 - Ejemplo de openssl_get_md_methods
  • Example#942 - Ejemplo de openssl_open
  • Example#943 - Ejemplo de openssl_pkcs12_read
  • Example#944 - Ejemplo de openssl_pkcs7_decrypt
  • Example#945 - Ejemplo de openssl_pkcs7_encrypt
  • Example#946 - Get a PEM array from a P7B file
  • Example#947 - Ejemplo de openssl_pkcs7_sign
  • Example#948 - openssl_pkey_derive example
  • Example#949 - Ejemplo de openssl_random_pseudo_bytes
  • Example#950 - Ejemplo de openssl_seal
  • Example#951 - Ejemplo de openssl_sign
  • Example#952 - Ejemplo de openssl_sign
  • Example#953 - Ejemplo de openssl_spki_export_challenge
  • Example#954 - Ejemplo de openssl_spki_export_challenge desde <keygen>
  • Example#955 - openssl_spki_export example
  • Example#956 - openssl_spki_export example from <keygen>
  • Example#957 - openssl_spki_new example
  • Example#958 - openssl_spki_verify example
  • Example#959 - openssl_spki_verify example from <keygen>
  • Example#960 - Ejemplo de openssl_verify
  • Example#961 - openssl_verify example
  • Example#962 - openssl_x509_verify example
  • Example#963 - Basic password usage
  • Example#964 - Ejemplo de password_hash
  • Example#965 - Ejemplo de password_hash estableciendo el coste manualmente
  • Example#966 - Ejemplo de password_hash estableciendo la sal manualmente
  • Example#967 - Ejemplo de password_hash buscando un buen coste
  • Example#968 - Empleo de password_needs_rehash
  • Example#969 - Ejemplo de password_verify
  • Example#970 - RNP clearsign example
  • Example#971 - simple callback function example
  • Example#972 - sodium_crypto_box_seal_open example
  • Example#973 - sodium_crypto_box_seal example
  • Example#974 - sodium_crypto_core_ristretto255_add example
  • Example#975 - sodium_crypto_core_ristretto255_from_hash example
  • Example#976 - sodium_crypto_core_ristretto255_is_valid_point example
  • Example#977 - sodium_crypto_core_ristretto255_random example
  • Example#978 - sodium_crypto_core_ristretto255_scalar_add example
  • Example#979 - sodium_crypto_core_ristretto255_scalar_invert example
  • Example#980 - sodium_crypto_core_ristretto255_scalar_negate example
  • Example#981 - sodium_crypto_core_ristretto255_scalar_random example
  • Example#982 - sodium_crypto_core_ristretto255_scalar_sub example
  • Example#983 - sodium_crypto_core_ristretto255_sub example
  • Example#984 - sodium_crypto_generichash_final example
  • Example#985 - sodium_crypto_generichash_init example
  • Example#986 - sodium_crypto_generichash_update example
  • Example#987 - sodium_crypto_kx_keypair usage
  • Example#988 - sodium_crypto_pwhash_str example
  • Example#989 - sodium_crypto_pwhash example
  • Example#990 - sodium_crypto_secretbox_keygen example
  • Example#991 - Comparing sodium_crypto_secretbox_keygen with random_bytes
  • Example#992 - sodium_crypto_secretbox_open example
  • Example#993 - sodium_crypto_secretbox example
  • Example#994 - sodium_crypto_secretstream_xchacha20poly1305_init_pull example
  • Example#995 - sodium_crypto_secretstream_xchacha20poly1305_init_push example
  • Example#996 - sodium_crypto_stream_xchacha20_xor_ic example
  • Example#997 - Ejemplo de DBA
  • Example#998 - Atravesar una base de datos
  • Example#999 - Ejemplo de dba_handlers
  • Example#1000 - Conexiones sin DSN
  • Example#1001 - odbc_connection_string_quote example
  • Example#1002 - Ejemplo de odbc_execute y odbc_prepare
  • Example#1003 - Ejemplos de odbc_fetch_into
  • Example#1004 - odbc_next_result
  • Example#1005 - Ejemplo de odbc_execute y odbc_prepare
  • Example#1006 - Ejemplos de odbc_result
  • Example#1007 - Ejemplos de odbc_setoption
  • Example#1008 - Uso de PDO::ATTR_DRIVER_NAME
  • Example#1009 - Conectarse a MySQL
  • Example#1010 - Manejo de errores de conexión
  • Example#1011 - Cerrar una conexión
  • Example#1012 - Conexiones persistentes
  • Example#1013 - Ejecución de un lote en una transacción
  • Example#1014 - Inserciones repetidas utilizando sentencias preparadas
  • Example#1015 - Inserciones repetidas utilizando sentencias preparadas
  • Example#1016 - Obtener datos empleando sentencias preparadas
  • Example#1017 - Llamar a un procedimiento almacenado con un parámetro de salida
  • Example#1018 - Llamar a un procedimiento almacenado con un parámetro de entrada/salida
  • Example#1019 - Uso inválido de un marcador de posición
  • Example#1020 - Crear una instancia de PDO y establecer el modo de error
  • Example#1021 - Crear una instancia de PDO y establecer el modo de error desde el constructor
  • Example#1022 - Mostrar una imagen desde una base de datos
  • Example#1023 - Insertar una imagen en una base de datos
  • Example#1024 - Insertar una imagen en una base de datos: Oracle
  • Example#1025 - Revertir una transacción
  • Example#1026 - Consignar una transacción básica
  • Example#1027 - Consignar una transacción DDL
  • Example#1028 - Crear una instancia PDO a través de una invocación al controlador
  • Example#1029 - Crear una instancia PDO a través de una invocación a la URI
  • Example#1030 - Crear una instancia de PDO usando un alias
  • Example#1031 - Recuperación de un código SQLSTATE
  • Example#1032 - Muestra los campos de errorInfo() para una conexión PDO_ODBC a una base de datos DB2
  • Example#1033 - Ejecutando una sentencia DELETE
  • Example#1034 - Obtiene los atributos de la conexión a la base de datos
  • Example#1035 - Un ejemplo de PDO::getAvailableDrivers
  • Example#1036 - Prepara una sentencia SQL con parámetros de sustitución nombrados
  • Example#1037 - Prepara una sentencia SQL con parámetros de signos de interrogación
  • Example#1038 - Demostración de PDO::query
  • Example#1039 - Entrecomillar una cadena de caracteres normal
  • Example#1040 - Entrecomillar una cadena peligrosa
  • Example#1041 - Entrecomillar una cadena compleja
  • Example#1042 - Revertir una transacción
  • Example#1043 - Vincular la salida de un conjunto de resultados a variables de PHP
  • Example#1044 - Ejecutar una sentencia preparada con parámetros de sustitución con nombre
  • Example#1045 - Ejecutar una sentencia preparada con parámetros de sustitución de signos de interrogación
  • Example#1046 - Llamar a un procedimiento almacenado con un parámetro INOUT
  • Example#1047 - Ejecutar una sentencia preparada con parámetros de sustitución con nombre
  • Example#1048 - Ejecutar una sentencia preparada con parámetros de sustitución de signos de interrogación
  • Example#1049 - Un ejemplo de PDOStatement::closeCursor
  • Example#1050 - Contar columnas
  • Example#1051 - Ejemplo de PDOStatement::debugDumpParams con parámetros con nombre
  • Example#1052 - Ejemplo de PDOStatement::debugDumpParams con parámetros sin nombre
  • Example#1053 - Recuperar un código SQLSTATE
  • Example#1054 - Mostrar los campos de errorInfo() para una conexión PDO_ODBC a una base de datos de DB2
  • Example#1055 - Ejecutar una sentencia preparada con una variable y valor vinculados
  • Example#1056 - Ejecutar una sentencia preparada con un array de valores de inserción (parámetros con nombre)
  • Example#1057 - Ejecutar una sentencia preparada con un array de valores de inserción (parámetros de sustitución)
  • Example#1058 - Ejecutar una sentencia preparada con parámetros de sustitución de signos de interrogación
  • Example#1059 - Ejecutar una sentencia preparada usando un array para la cláusula IN
  • Example#1060 - Obtención de filas usando diferentes tipos de obtención
  • Example#1061 - Obtener filas con un cursor desplazable
  • Example#1062 - Orden de construcción
  • Example#1063 - Obtener todas las filas restantes de un conjunto de resultados
  • Example#1064 - Obtener todos los valores de una única columna de un conjunto de resultados
  • Example#1065 - Agrupar todos los valores según una única columna
  • Example#1066 - Instanciar una clase para cada resultado
  • Example#1067 - Invocar a una función por cada resultado
  • Example#1068 - Devolver la primera columna de la siguiente fila
  • Example#1069 - Recuperar metadatos de una columna
  • Example#1070 - Obtener múltiples conjuntos de filas devueltas por un procedimiento almacenado
  • Example#1071 - Devolver el número de filas eliminadas
  • Example#1072 - Contar las filas devueltas por una sentencia SELECT
  • Example#1073 - Establece el modo de obtención
  • Example#1074 - Insertar LOBs en CUBRID PDO
  • Example#1075 - Obtener LOBs en CUBRID PDO
  • Example#1076 - Insertar un conjunto en CUBRID PDO con el tipo de datos predeterminado.
  • Example#1077 - Especificar un tipo de datos al insertar un conjunto en CUBRID PDO
  • Example#1078 - Ejemplos de DSN de PDO_CUBRID
  • Example#1079 - Un ejemplo de PDO::cubrid_schema
  • Example#1080 - PDO_DBLIB DSN examples
  • Example#1081 - Ejemplo de DSN de PDO_FIREBIRD DSN con ruta
  • Example#1082 - Ejemplo de DSN de PDO_FIREBIRD DSN con puerto y ruta
  • Example#1083 - Ejemplo de DSN de PDO_FIREBIRD con localhost y ruta hacia empleado.fdb en un sistema Debian
  • Example#1084 - Ejemplo de DSN de PDO_IBM DSN usando db2cli.ini
  • Example#1085 - Ejemplo de DSN de PDO_IBM usando una cadena de conexión
  • Example#1086 - Ejemplo de DSN de PDO_INFORMIX usando odbc.ini
  • Example#1087 - Ejemplo de DSN de PDO_INFORMIX usando una cadena de conexión
  • Example#1088 - Forzar consultas para que sean guardadas en el búfer en mysql
  • Example#1089 - Establecer el juego de caracteres de la conexión a UTF-8, antes de PHP 5.3.6
  • Example#1090 - ejemplos PDO_MYSQL DSN
  • Example#1091 - Ejemplos de DSN de PDO_SQLSRV
  • Example#1092 - Ejemplos del DSN de PDO_OCI
  • Example#1093 - Ejemplo de DSN de PDO_ODBC (administrador de controladores de ODBC)
  • Example#1094 - Ejemplo de DSN de PDO_ODBC (conexión no catalogada de IBM DB2)
  • Example#1095 - Ejemplo de DSN de PDO_ODBC (conexión no catalogada de Microsoft Access)
  • Example#1096 - Ejemplos de DSN de PDO_PGSQL
  • Example#1097 - Un ejemplo de PDO::pgsqlLOBCreate
  • Example#1098 - Un ejemplo de PDO::pgsqlLOBOpen
  • Example#1099 - Un ejemplo de PDO::pgsqlLOBUnlink
  • Example#1100 - Ejemplos de PDO_SQLITE DSN
  • Example#1101 - Ejemplo de función acumuladora max_length
  • Example#1102 - Ejemplo de PDO::sqliteCreateCollation
  • Example#1103 - Ejemplo de PDO::sqliteCreateFunction
  • Example#1104 - Ejemplo de Recuperación de Datos
  • Example#1105 - Ejemplo de Inserción de Datos
  • Example#1106 - Ejemplo de cubrid_bind
  • Example#1107 - Ejemplo de BLOB/CLOB de cubrid_bind
  • Example#1108 - Ejemplo de BLOB/CLOB de cubrid_bind
  • Example#1109 - Ejemplo de cubrid_close_prepare
  • Example#1110 - Ejemplo de cubrid_close_request
  • Example#1111 - Ejemplo de cubrid_col_get
  • Example#1112 - Ejemplo de cubrid_col_size
  • Example#1113 - Ejemplo de cubrid_column_names
  • Example#1114 - Ejemplo de cubrid_column_types
  • Example#1115 - Ejemplo de cubrid_commit
  • Example#1116 - Ejemplo de cubrid_connect_with_url, url sin propiedades
  • Example#1117 - Ejemplo de cubrid_connect_with_url, url con propiedades
  • Example#1118 - Ejemplo de cubrid_connect
  • Example#1119 - Ejemplo de cubrid_current_oid
  • Example#1120 - Ejemplo de cubrid_disconnect
  • Example#1121 - Ejemplo de cubrid_drop
  • Example#1122 - Ejemplo de cubrid_error_code_facility
  • Example#1123 - Ejemplo de cubrid_error_code
  • Example#1124 - Ejemplo de cubrid_error_msg
  • Example#1125 - Ejemplo de cubrid_execute
  • Example#1126 - Ejemplo de cubrid_fetch
  • Example#1127 - Ejemplo de cubrid_free_result
  • Example#1128 - Ejemplo de cubrid_get_charset
  • Example#1129 - Ejemplo de cubrid_get_class_name
  • Example#1130 - Ejemplo de cubrid_get_client_info
  • Example#1131 - Ejemplo de cubrid_get_db_parameter
  • Example#1132 - Ejemplo de cubrid_get_query_timeout
  • Example#1133 - Ejemplo de cubrid_get_server_info
  • Example#1134 - Ejemplo de cubrid_get
  • Example#1135 - Ejemplo de cubrid_insert_id
  • Example#1136 - Ejemplo de cubrid_is_instance
  • Example#1137 - Ejemplo de cubrid_lob_close
  • Example#1138 - Ejemplo de cubrid_lob_export
  • Example#1139 - Ejemplo de cubrid_lob_get
  • Example#1140 - Ejemplo de cubrid_lob_send
  • Example#1141 - Ejemplo de cubrid_lob_size
  • Example#1142 - Ejemplo de cubrid_lob2_bind
  • Example#1143 - Ejemplo de cubrid_lob2_export
  • Example#1144 - Ejemplo de cubrid_lob2_export
  • Example#1145 - Ejemplo 1 de cubrid_lob2_read
  • Example#1146 - Ejemplo 2 cubrid_lob2_read
  • Example#1147 - Ejemplo de cubrid_lob2_seek64
  • Example#1148 - Ejemplo de cubrid_lob2_seek
  • Example#1149 - Ejemplo 1 de cubrid_lob2_write
  • Example#1150 - Ejemplo 2 de cubrid_lob2_write
  • Example#1151 - Ejemplo de cubrid_lock_read
  • Example#1152 - Ejemplo de cubrid_lock_write
  • Example#1153 - Ejemplo de cubrid_move_cursor
  • Example#1154 - cubrid_next_result ejemplo
  • Example#1155 - Ejemplo de cubrid_num_cols
  • Example#1156 - Ejemplo de cubrid_num_rows
  • Example#1157 - Ejemplo de url de cubrid_pconnect_with_url sin propiedades
  • Example#1158 - Ejemplo de url de cubrid_pconnect_with_url con propiedades
  • Example#1159 - Ejemplo de cubrid_pconnect
  • Example#1160 - Ejemplo de cubrid_prepare
  • Example#1161 - Ejemplo de cubrid_put
  • Example#1162 - Ejemplo de cubrid_rollback
  • Example#1163 - Ejemplo de cubrid_schema
  • Example#1164 - Ejemplo de cubrid_seq_drop
  • Example#1165 - Ejemplo de cubrid_seq_insert
  • Example#1166 - Ejemplo de cubrid_seq_put
  • Example#1167 - Ejemplo de cubrid_set_add
  • Example#1168 - Ejemplo de cubrid_get_db_parameter
  • Example#1169 - Ejemplo de cubrid_set_drop
  • Example#1170 - Ejemplo de cubrid_version
  • Example#1171 - Ejemplo de cubrid_affected_rows
  • Example#1172 - Ejemplo de cubrid_client_encoding
  • Example#1173 - Ejemplo de cubrid_close
  • Example#1174 - Ejemplo de cubrid_data_seek
  • Example#1175 - Ejemplo de cubrid_db_name
  • Example#1176 - Ejemplo de cubrid_errno
  • Example#1177 - Ejemplo de cubrid_error
  • Example#1178 - Ejemplo de cubrid_fetch_array
  • Example#1179 - Ejemplo de cubrid_fetch_assoc
  • Example#1180 - Ejemplo de cubrid_fetch_field
  • Example#1181 - Ejemplo de cubrid_fetch_lengths
  • Example#1182 - Ejemplo de cubrid_fetch_object
  • Example#1183 - Ejemplo de cubrid_fetch_row
  • Example#1184 - Ejemplo de cubrid_field_flags
  • Example#1185 - Ejemplo de cubrid_field_len
  • Example#1186 - Ejemplo de cubrid_field_name
  • Example#1187 - Ejemplo de cubrid_field_seek
  • Example#1188 - Ejemplo de cubrid_field_table
  • Example#1189 - Ejemplo de cubrid_field_type
  • Example#1190 - Ejemplo de cubrid_list_dbs
  • Example#1191 - Ejemplo de cubrid_num_fields
  • Example#1192 - Ejemplo de cubrid_ping
  • Example#1193 - Consulta No Válida
  • Example#1194 - Consulta Válida
  • Example#1195 - Ejemplo de cubrid_real_escape_string
  • Example#1196 - Ejemplo de cubrid_result
  • Example#1197 - Ejemplo de cubrid_unbuffered_query
  • Example#1198 - Ejemplo de cubrid_load_from_glo
  • Example#1199 - Ejemplo de cubrid_new_glo
  • Example#1200 - Ejemplo de cubrid_save_to_glo
  • Example#1201 - Ejemplo de cubrid_send_glo
  • Example#1202 - Insertar un registro en una base de datos dBase
  • Example#1203 - Cerrar un archivo de base de datos de dBase
  • Example#1204 - Crear un archivo de base de datos dBase
  • Example#1205 - Mostrar la información de cabecera de un archivo de base de datos dBase
  • Example#1206 - Listar todos los miembros registrados en la base de datos
  • Example#1207 - Ejemplo de dbase_numfields
  • Example#1208 - Recorrer todos los registros de la base de datos
  • Example#1209 - Abrir un archivo de base de datos de dBase
  • Example#1210 - Vaciar una base de datos dBase
  • Example#1211 - Actualizar un registro en la base de datos
  • Example#1212 - Ejemplo de ibase_blob_get
  • Example#1213 - Ejemplo de ibase_blob_import
  • Example#1214 - Ejemplo de ibase_connect
  • Example#1215 - Ejemplo de ibase_execute
  • Example#1216 - Ejemplo de ibase_fetch_object
  • Example#1217 - Ejemplo de ibase_field_info
  • Example#1218 - Ejemplo de ibase_name_result
  • Example#1219 - Ejemplo de ibase_num_fields
  • Example#1220 - Ejemplo de ibase_query
  • Example#1221 - Ejemplo de ibase_set_event_handler
  • Example#1222 - Consultando el valor de AUTOCOMMIT de una conexión
  • Example#1223 - Asignando el valor de AUTOCOMMIT en una conexión
  • Example#1224 - Vinculando variables PHP a sentencias preparadas
  • Example#1225 - Llamada a procedimientos almacenados con parámetros de Entrada y Salida
  • Example#1226 - Insertando un objeto extenso binario (BLOB) directamente desde un fichero
  • Example#1227 - Ejemplo de db2_client_info
  • Example#1228 - Cierre de una conexión
  • Example#1229 - Extrayendo el valor SQLSTATE de un intento de conexión fallido
  • Example#1230 - Extrayendo el mensaje de error devuelto por un intento de conexión fallido
  • Example#1231 - Creando una conexión catalogada
  • Example#1232 - Creando una conexión no catalogada
  • Example#1233 - Creando una conexión con confirmaciones automáticas de transacciones deshabilitadas
  • Example#1234 - Optimizando en i5/OS
  • Example#1235 - Usando contexto de confianza
  • Example#1236 - Ejemplo de db2_escape_string
  • Example#1237 - Creando una tabla con db2_exec
  • Example#1238 - Ejecutando una sentencia SELECT con cursor de tipo SCROLLABLE
  • Example#1239 - Devolviendo datos XML como resultado
  • Example#1240 - Ejecutando un JOIN con datos XML
  • Example#1241 - Devolviendo datos SQL como parte de un documento XML extenso
  • Example#1242 - Preparando y ejecutando una sentencia SQL con marcadores de parámetros
  • Example#1243 - Llamando a un procedimiento almacenado con un parámetro OUT
  • Example#1244 - Devolviendo datos XML como resultado SQL
  • Example#1245 - Ejecutando un "JOIN" con datos XML
  • Example#1246 - Devolviendo datos SQL como parte un documento XML más extenso
  • Example#1247 - Iterando a través de un cursor de no-recorrido (sólo hacia adelante)
  • Example#1248 - Extrayendo filas específicas con db2_fetch_array con un cursor de recorrido
  • Example#1249 - Iterando a través de un cursor de no-recorrido (sólo hacia adelante)
  • Example#1250 - Extrayendo filas específicas con db2_fetch_assoc a partir de un cursor de recorrido
  • Example#1251 - Iterando a través de un cursor de no-recorrido (sólo hacia adelante)
  • Example#1252 - Extrayendo filas específicas con db2_fetch_both a partir de un cursor de recorrido
  • Example#1253 - Ejemplo de db2_fetch_object
  • Example#1254 - Iterando a través de un bloque de resultados
  • Example#1255 - Alternativas recomendadas para db2_fetch_row/db2_result en i5/OS
  • Example#1256 - Estableciendo y extrayendo parámetros a través de una conexión
  • Example#1257 - Ejemplo de db2_last_insert_id
  • Example#1258 - Iterando a través de diferentes tipos de datos
  • Example#1259 - Llamando a un procedimiento almacenado que devuelve múltiples resultados
  • Example#1260 - Extrayendo el número de campos de un resultado
  • Example#1261 - Cerrando una conexión persistente
  • Example#1262 - Ejemplo de db2_pconnect
  • Example#1263 - Utilizando contexto de confianza
  • Example#1264 - Preparando y ejecutando un comando SQL con marcadores de parámetros.
  • Example#1265 - Ejemplo de db2_result
  • Example#1266 - Cancelando una sentencia DELETE
  • Example#1267 - A db2_server_info example
  • Example#1268 - Setting one parameter with a connection resource
  • Example#1269 - Setting multiple parameters with a connection resource
  • Example#1270 - Setting multiple parameters with an invalid key
  • Example#1271 - Setting multiple parameters with an invalid value
  • Example#1272 - Setting multiple parameters with a connection resource and the wrong type
  • Example#1273 - Setting multiple parameters with the wrong resource
  • Example#1274 - Putting it all together
  • Example#1275 - i5/OS cursors are read-only
  • Example#1276 - MongoDB\Driver\Manager::__construct basic example
  • Example#1277 - MongoDB\Driver\Manager::__construct basic examples
  • Example#1278 - MongoDB\Driver\Manager::executeBulkWrite example
  • Example#1279 - MongoDB\Driver\Manager::executeCommand with a command returning a single result document
  • Example#1280 - MongoDB\Driver\Manager::executeCommand with a command returning a cursor
  • Example#1281 - Limiting execution time for a command
  • Example#1282 - MongoDB\Driver\Manager::executeQuery example
  • Example#1283 - Limiting execution time for a query
  • Example#1284 - MongoDB\Driver\Manager::getReadConcern example
  • Example#1285 - MongoDB\Driver\Manager::getReadPreference example
  • Example#1286 - MongoDB\Driver\Manager::getServers example
  • Example#1287 - MongoDB\Driver\Manager::getWriteConcern example
  • Example#1288 - Composing MongoDB\Driver\Command to provide a helper to create collections
  • Example#1289 - MongoDB\Driver\Command::__construct example
  • Example#1290 - MongoDB\Driver\Command::__construct example
  • Example#1291 - MongoDB\Driver\Query::__construct example
  • Example#1292 - Mixed write operations are grouped by type
  • Example#1293 - Ordered write operations causing an error
  • Example#1294 - MongoDB\Driver\BulkWrite::__construct example
  • Example#1295 - MongoDB\Driver\BulkWrite::count example
  • Example#1296 - MongoDB\Driver\BulkWrite::delete example
  • Example#1297 - MongoDB\Driver\BulkWrite::insert example
  • Example#1298 - MongoDB\Driver\BulkWrite::update example
  • Example#1299 - Declare an API version on a manager
  • Example#1300 - Declare a strict API version on a manager
  • Example#1301 - MongoDB\Driver\WriteConcern::bsonSerialize with majority write concern
  • Example#1302 - MongoDB\Driver\WriteConcern::bsonSerialize with wtimeout and journal
  • Example#1303 - MongoDB\Driver\WriteConcern::__construct example
  • Example#1304 - MongoDB\Driver\WriteConcern::getJournal example
  • Example#1305 - MongoDB\Driver\WriteConcern::getW example
  • Example#1306 - MongoDB\Driver\WriteConcern::getWtimeout example
  • Example#1307 - MongoDB\Driver\WriteConcern::isDefault example
  • Example#1308 - MongoDB\Driver\ReadPreference::bsonSerialize with primary read preference
  • Example#1309 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and tag sets
  • Example#1310 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and max staleness
  • Example#1311 - MongoDB\Driver\ReadPreference::__construct example
  • Example#1312 - MongoDB\Driver\ReadPreference::getMaxStalenessSeconds example
  • Example#1313 - MongoDB\Driver\ReadPreference::getMode example
  • Example#1314 - MongoDB\Driver\ReadPreference::getModeString example
  • Example#1315 - MongoDB\Driver\ReadPreference::getTagSets example
  • Example#1316 - MongoDB\Driver\ReadConcern::bsonSerialize with empty read concern
  • Example#1317 - MongoDB\Driver\ReadConcern::bsonSerialize with local read concern
  • Example#1318 - MongoDB\Driver\ReadConcern::__construct example
  • Example#1319 - MongoDB\Driver\ReadConcern::getLevel example
  • Example#1320 - MongoDB\Driver\ReadConcern::isDefault example
  • Example#1321 - Reading a result set
  • Example#1322 - Reading a result set for a tailable cursor
  • Example#1323 - MongoDB\Driver\Cursor::getId example
  • Example#1324 - MongoDB\Driver\Cursor::getServer example
  • Example#1325 - MongoDB\Driver\Cursor::isDead example
  • Example#1326 - MongoDB\Driver\Cursor::setTypeMap example
  • Example#1327 - MongoDB\Driver\Cursor::toArray example
  • Example#1328 - MongoDB\Driver\CursorId::__toString example
  • Example#1329 - MongoDB\Driver\Server::getHost example
  • Example#1330 - MongoDB\Driver\Server::getInfo example
  • Example#1331 - MongoDB\Driver\Server::getLatency example
  • Example#1332 - MongoDB\Driver\Server::getPort example
  • Example#1333 - MongoDB\Driver\WriteConcernError::getCode example
  • Example#1334 - MongoDB\Driver\WriteConcernError::getInfo example
  • Example#1335 - MongoDB\Driver\WriteConcernError::getMessage example
  • Example#1336 - MongoDB\Driver\WriteError::getCode example
  • Example#1337 - MongoDB\Driver\WriteError::getIndex example
  • Example#1338 - MongoDB\Driver\WriteError::getMessage example
  • Example#1339 - MongoDB\Driver\WriteResult::getDeletedCount example
  • Example#1340 - MongoDB\Driver\WriteResult::getInsertedCount example
  • Example#1341 - MongoDB\Driver\WriteResult::getMatchedCount example
  • Example#1342 - MongoDB\Driver\WriteResult::getModifiedCount example
  • Example#1343 - MongoDB\Driver\WriteResult::getServer example
  • Example#1344 - MongoDB\Driver\WriteResult::getUpsertedCount example
  • Example#1345 - MongoDB\Driver\WriteResult::getUpsertedIds example
  • Example#1346 - MongoDB\Driver\WriteResult::getWriteConcernError example
  • Example#1347 - MongoDB\Driver\WriteResult::getWriteErrors with a single error
  • Example#1348 - MongoDB\Driver\WriteResult::getWriteErrors with multiple errors
  • Example#1349 - MongoDB\Driver\WriteResult::isAcknowledged with acknowledged write concern
  • Example#1350 - MongoDB\Driver\WriteResult::isAcknowledged with unacknowledged write concern
  • Example#1351 - MongoDB\BSON\fromJSON example
  • Example#1352 - MongoDB\BSON\fromPHP example
  • Example#1353 - MongoDB\BSON\toCanonicalExtendedJSON example
  • Example#1354 - MongoDB\BSON\toJSON example
  • Example#1355 - MongoDB\BSON\toPHP example
  • Example#1356 - MongoDB\BSON\toRelaxedExtendedJSON example
  • Example#1357 - MongoDB\BSON\Binary::__construct example
  • Example#1358 - MongoDB\BSON\Binary::getData example
  • Example#1359 - MongoDB\BSON\Binary::getType example
  • Example#1360 - MongoDB\BSON\Binary::__toString example
  • Example#1361 - MongoDB\BSON\Decimal128::__construct example
  • Example#1362 - MongoDB\BSON\Decimal128::__toString example
  • Example#1363 - MongoDB\BSON\Javascript::__construct example
  • Example#1364 - MongoDB\BSON\Javascript::getCode example
  • Example#1365 - MongoDB\BSON\Javascript::getScope example
  • Example#1366 - MongoDB\BSON\Javascript::__toString example
  • Example#1367 - MongoDB\BSON\MaxKey::__construct example
  • Example#1368 - MongoDB\BSON\MinKey::__construct example
  • Example#1369 - MongoDB\BSON\ObjectId::__construct example
  • Example#1370 - MongoDB\BSON\ObjectId::getTimestamp example
  • Example#1371 - MongoDB\BSON\ObjectId::__toString example
  • Example#1372 - MongoDB\BSON\Regex::__construct example
  • Example#1373 - MongoDB\BSON\Regex::getFlags example
  • Example#1374 - MongoDB\BSON\Regex::getPattern example
  • Example#1375 - MongoDB\BSON\Regex::__toString example
  • Example#1376 - MongoDB\BSON\Timestamp::__construct example
  • Example#1377 - MongoDB\BSON\Timestamp::__toString example
  • Example#1378 - MongoDB\BSON\UTCDateTime::__construct example
  • Example#1379 - MongoDB\BSON\UTCDatetime::toDateTime example
  • Example#1380 - MongoDB\BSON\UTCDateTime::__toString example
  • Example#1381 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for root document
  • Example#1382 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for root document
  • Example#1383 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for document field
  • Example#1384 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for document field
  • Example#1385 - MongoDB\BSON\Unserializable::bsonUnserialize example
  • Example#1386 - MongoDB\BSON\Int64::__toString example
  • Example#1387 - MongoDB\Driver\Exception\WriteException::getWriteResult example
  • Example#1388 - Comparación de las tres API de MySQL
  • Example#1389 - Comandos de configuración para usar mysqlnd o libmysqlclient
  • Example#1390 - Ejemplo de consulta no almacenada en buffer: mysqli
  • Example#1391 - Ejemplo de consulta no almacenada en buffer: pdo_mysql
  • Example#1392 - Ejemplo de consulta no almacenada en buffer: mysql
  • Example#1393 - Problemas al establecer el conjunto de caracteres con SQL
  • Example#1394 - Ejemplo para establecer el conjunto de caracteres: mysqli
  • Example#1395 - Ejemplo para establecer el conjunto de caracteres: pdo_mysql
  • Example#1396 - Ejemplo para establecer el conjunto de caracteres: mysql
  • Example#1397 - Migración sencilla desde la antigua extensión mysql
  • Example#1398 - Interfaz orientada a objetos y procedimental
  • Example#1399 - Estilo de codificación malo
  • Example#1400 - Significado especial de localhost
  • Example#1401 - Configuración predeterminada
  • Example#1402 - Conectando a MySQL
  • Example#1403 - Navegación a través de resultados almacenados en buffer
  • Example#1404 - Navegación a través de resultados no almacenados en buffer
  • Example#1405 - El protocolo de texto devuelve cadenas de manera predeterminado
  • Example#1406 - Tipos de datos nativos con mysqlnd y la opción de conexión
  • Example#1407 - Primera etapa: prepación
  • Example#1408 - Segunda etapa: vincular y ejecutar
  • Example#1409 - INSERT preparada una vez, ejecutada múltiples veces
  • Example#1410 - Menos viajes de ida y vuelta usando SQL multi-INSERT
  • Example#1411 - Tipos de datos nativos
  • Example#1412 - Vinculación de variables de salida
  • Example#1413 - Usar mysqli_result para obtener los resultados
  • Example#1414 - Conjunto de resultados almacenado en buffer para la lectura flexible
  • Example#1415 - Llamar a un procedimiento almacenado
  • Example#1416 - Usar variables de sesión
  • Example#1417 - Obtener los resultados de procedimientos almacenados
  • Example#1418 - Procedimientos Almacenados y Sentencias Preparadas
  • Example#1419 - Procedimientos Almacenados y Sentencias Preparadas usando la API de vinculación
  • Example#1420 - Sentencias múltiples
  • Example#1421 - Inyección SQL
  • Example#1422 - Establecer el modo de autoconsignación con SQL y a través de la API
  • Example#1423 - Consignación y reinicio
  • Example#1424 - Acceder a los metadatos de un conjunto de resultados
  • Example#1425 - Metadatos de sentencias preparadas
  • Example#1426 - Ejemplo de $mysqli->affected_rows
  • Example#1427 - Ejemplo de mysqli::autocommit
  • Example#1428 - Ejemplo de $mysqli->begin_transaction
  • Example#1429 - Ejemplo del método mysqli::change_user
  • Example#1430 - Ejemplo de mysqli::character_set_name
  • Example#1431 - Ejemplo de mysqli::commit
  • Example#1432 - $mysqli->connect_errno example
  • Example#1433 - Ejemplo de $mysqli->connect_error
  • Example#1434 - Ejemplo de mysqli::__construct
  • Example#1435 - Generando un fichero de prueba (traza)
  • Example#1436 - Ejemplo de $mysqli->errno
  • Example#1437 - Ejemplo de $mysqli->error_list
  • Example#1438 - Ejemplo de $mysqli->error
  • Example#1439 - mysqli::execute_query example
  • Example#1440 - Ejemplo de $mysqli->field_count
  • Example#1441 - mysqli::get_charset example
  • Example#1442 - mysqli_get_client_info
  • Example#1443 - mysqli_get_client_version
  • Example#1444 - Un ejemplo de mysqli_get_connection_stats
  • Example#1445 - Ejemplo de $mysqli->host_info
  • Example#1446 - Ejemplo de $mysqli->protocol_version
  • Example#1447 - Ejemplo de $mysqli->server_info
  • Example#1448 - Ejemplo de $mysqli->server_version
  • Example#1449 - Ejemplo de $mysqli->info
  • Example#1450 - Ejemplo de $mysqli->insert_id
  • Example#1451 - Ejemplo de mysqli::kill
  • Example#1452 - Ejemplo de mysqli::multi_query
  • Example#1453 - Ejemplo de mysqli::ping
  • Example#1454 - Un ejemplo de mysqli_poll
  • Example#1455 - Ejemplo de mysqli::prepare
  • Example#1456 - Ejemplo de mysqli::query
  • Example#1457 - Ejemplo de mysqli::real_connect
  • Example#1458 - Ejemplo de mysqli::real_escape_string
  • Example#1459 - Ejemplo de mysqli::rollback
  • Example#1460 - Ejemplo de mysqli::select_db
  • Example#1461 - Ejemplo de mysqli::set_charset
  • Example#1462 - Ejemplo de $mysqli->sqlstate
  • Example#1463 - Ejemplo de mysqli::stat
  • Example#1464 - Ejemplo $mysqli->thread_id
  • Example#1465 - Ejemplo de mysqli::use_result
  • Example#1466 - Ejemplo de $mysqli->warning_count
  • Example#1467 - Estilo orientado a objetos
  • Example#1468 - Estilo por procedimientos
  • Example#1469 - Estilo orientado a objetos
  • Example#1470 - Estilo por procedimientos
  • Example#1471 - Estilo orientado a objetos
  • Example#1472 - Estilo por procedimientos
  • Example#1473 - Estilo orientado a objetos
  • Example#1474 - Estilo por procedimientos
  • Example#1475 - Estilo orientado a objetos
  • Example#1476 - Estilo por procedimientos
  • Example#1477 - Estilo orientado a objetos
  • Example#1478 - Estilo por procedimientos
  • Example#1479 - Estilo orientado a objetos
  • Example#1480 - Estilo por procedimientos
  • Example#1481 - Estilo orientado a objetos
  • Example#1482 - Estilo por procedimientos
  • Example#1483 - Estilo orientado a objetos
  • Example#1484 - Estilo por procedimientos
  • Example#1485 - Estilo orientado a objetos
  • Example#1486 - Estilo por procedimientos
  • Example#1487 - Estilo orientado a objetos
  • Example#1488 - Estilo por procedimientos
  • Example#1489 - Estilo orientado a objetos
  • Example#1490 - Estilo por procedimientos
  • Example#1491 - Estilo orientado a objetos
  • Example#1492 - Estilo por procedimientos
  • Example#1493 - Estilo orientado a objetos
  • Example#1494 - Estilo por procedimientos
  • Example#1495 - Estilo orientado a objetos
  • Example#1496 - Estilo orientado a objetos
  • Example#1497 - Estilo por procedimientos
  • Example#1498 - Estilo orientado a objetos
  • Example#1499 - Estilo por procedimientos
  • Example#1500 - Creation of a mysqli_result object
  • Example#1501 - Estilo orientado a objetos
  • Example#1502 - Estilo por procedimientos
  • Example#1503 - Estilo orientado a objetos
  • Example#1504 - Estilo por procedimientos
  • Example#1505 - Estilo orientado a objetos
  • Example#1506 - Estilo por procedimientos
  • Example#1507 - Estilo orientado a objetos
  • Example#1508 - Estilo por procedimientos
  • Example#1509 - Un ejemplo de mysqli_result comparando el uso de iterator
  • Example#1510 - mysqli_result::fetch_column example
  • Example#1511 - Estilo orientado a objetos
  • Example#1512 - Estilo por procedimientos
  • Example#1513 - Estilo orientado a objetos
  • Example#1514 - Estilo por procedimientos
  • Example#1515 - Estilo orientado a objetos
  • Example#1516 - Estilo por procedimientos
  • Example#1517 - Estilo orientado a objetos
  • Example#1518 - Estilo por procedimientos
  • Example#1519 - Estilo orientado a objetos
  • Example#1520 - Estilo por procedimientos
  • Example#1521 - Estilo orientado a objetos
  • Example#1522 - Estilo por procedimientos
  • Example#1523 - Estilo orientado a objetos
  • Example#1524 - Estilo por procedimientos
  • Example#1525 - Estilo orientado a objetos
  • Example#1526 - Estilo por procedimientos
  • Example#1527 - Estilo orientado a objetos
  • Example#1528 - Estilo por procedimientos
  • Example#1529 - Estilo orientado a objetos
  • Example#1530 - Estilo por procedimientos
  • Example#1531 - Ejemplo de mysqli_connect
  • Example#1532 - A mysqli_get_client_stats example
  • Example#1533 - Connecting to a MySQL Server
  • Example#1534 - Creating a Schema and Collection on the MySQL Server
  • Example#1535 - Storing and Retrieving Data
  • Example#1536 - Fetching and Iterating Multiple Documents
  • Example#1537 - mysql_xdevapi\Expression example
  • Example#1538 - URI examples
  • Example#1539 - mysql_xdevapi\getSession example
  • Example#1540 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1541 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1542 - mysql_xdevapi\Client::__construct example
  • Example#1543 - mysql_xdevapi\Collection::add example
  • Example#1544 - mysql_xdevapi\Collection::addOrReplaceOne example
  • Example#1545 - mysql_xdevapi\Collection::getOne example
  • Example#1546 - mysql_xdevapi\Collection::count example
  • Example#1547 - mysql_xdevapi\Collection::createIndex example
  • Example#1548 - mysql_xdevapi\Collection::dropIndex example
  • Example#1549 - mysql_xdevapi\Collection::existsInDatabase example
  • Example#1550 - mysql_xdevapi\Collection::find example
  • Example#1551 - mysql_xdevapi\Collection::getName example
  • Example#1552 - mysql_xdevapi\Collection::getOne example
  • Example#1553 - mysql_xdevapi\Collection::getSchema example
  • Example#1554 - mysql_xdevapi\Collection::getSession example
  • Example#1555 - mysql_xdevapi\Collection::modify example
  • Example#1556 - mysql_xdevapi\Collection::remove example
  • Example#1557 - mysql_xdevapi\Collection::removeOne example
  • Example#1558 - mysql_xdevapi\Collection::replaceOne example
  • Example#1559 - mysql_xdevapi\CollectionAdd::__construct example
  • Example#1560 - mysql_xdevapi\CollectionAdd::execute example
  • Example#1561 - mysql_xdevapi\CollectionFind::bind example
  • Example#1562 - CollectionFind example
  • Example#1563 - CollectionFind example
  • Example#1564 - mysql_xdevapi\CollectionFind::fields example
  • Example#1565 - mysql_xdevapi\CollectionFind::groupBy example
  • Example#1566 - mysql_xdevapi\CollectionFind::having example
  • Example#1567 - mysql_xdevapi\CollectionFind::limit example
  • Example#1568 - mysql_xdevapi\CollectionFind::lockExclusive example
  • Example#1569 - mysql_xdevapi\CollectionFind::lockShared example
  • Example#1570 - mysql_xdevapi\CollectionFind::offset example
  • Example#1571 - mysql_xdevapi\CollectionFind::sort example
  • Example#1572 - mysql_xdevapi\CollectionModify::arrayAppend example
  • Example#1573 - mysql_xdevapi\CollectionModify::arrayInsert example
  • Example#1574 - mysql_xdevapi\CollectionModify::bind example
  • Example#1575 - mysql_xdevapi\CollectionModify::__construct example
  • Example#1576 - mysql_xdevapi\CollectionModify::execute example
  • Example#1577 - mysql_xdevapi\CollectionModify::limit example
  • Example#1578 - mysql_xdevapi\CollectionModify::patch example
  • Example#1579 - mysql_xdevapi\CollectionModify::replace example
  • Example#1580 - mysql_xdevapi\CollectionModify::set example
  • Example#1581 - mysql_xdevapi\CollectionModify::skip example
  • Example#1582 - mysql_xdevapi\CollectionModify::sort example
  • Example#1583 - mysql_xdevapi\CollectionModify::unset example
  • Example#1584 - mysql_xdevapi\CollectionRemove::bind example
  • Example#1585 - mysql_xdevapi\Collection::remove example
  • Example#1586 - mysql_xdevapi\CollectionRemove::execute example
  • Example#1587 - mysql_xdevapi\CollectionRemove::limit example
  • Example#1588 - mysql_xdevapi\CollectionRemove::sort example
  • Example#1589 - mysql_xdevapi\ColumnResult::__construct example
  • Example#1590 - mysql_xdevapi\ColumnResult::getCharacterSetName example
  • Example#1591 - mysql_xdevapi\ColumnResult::getCollationName example
  • Example#1592 - mysql_xdevapi\ColumnResult::getColumnLabel example
  • Example#1593 - mysql_xdevapi\ColumnResult::getColumnName example
  • Example#1594 - mysql_xdevapi\ColumnResult::getFractionalDigits example
  • Example#1595 - mysql_xdevapi\ColumnResult::getLength example
  • Example#1596 - mysql_xdevapi\ColumnResult::getSchemaName example
  • Example#1597 - mysql_xdevapi\ColumnResult::getTableLabel example
  • Example#1598 - mysql_xdevapi\ColumnResult::getTableName example
  • Example#1599 - mysql_xdevapi\ColumnResult::getType example
  • Example#1600 - mysql_xdevapi\ColumnResult::isNumberSigned example
  • Example#1601 - mysql_xdevapi\ColumnResult::isPadded example
  • Example#1602 - mysql_xdevapi\CrudOperationBindable::bind example
  • Example#1603 - mysql_xdevapi\CrudOperationLimitable::limit example
  • Example#1604 - mysql_xdevapi\CrudOperationSkippable::skip example
  • Example#1605 - mysql_xdevapi\CrudOperationSortable::sort example
  • Example#1606 - mysql_xdevapi\DatabaseObject::existsInDatabase example
  • Example#1607 - mysql_xdevapi\DatabaseObject::getName example
  • Example#1608 - mysql_xdevapi\DatabaseObject::getSession example
  • Example#1609 - A DocResult example
  • Example#1610 - mysql_xdevapi\DocResult::fetchAll example
  • Example#1611 - mysql_xdevapi\DocResult::fetchOne example
  • Example#1612 - mysql_xdevapi\DocResult::getWarnings example
  • Example#1613 - mysql_xdevapi\DocResult::getWarningsCount example
  • Example#1614 - execute() examples
  • Example#1615 - mysql_xdevapi\ExecutionStatus::__construct example
  • Example#1616 - mysql_xdevapi\Expression::__construct example
  • Example#1617 - mysql_xdevapi\Result::__construct example
  • Example#1618 - mysql_xdevapi\Result::getAffectedItemsCount example
  • Example#1619 - mysql_xdevapi\Result::getAutoIncrementValue example
  • Example#1620 - mysql_xdevapi\Result::getGeneratedIds example
  • Example#1621 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1622 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1623 - mysql_xdevapi\RowResult::__construct example
  • Example#1624 - mysql_xdevapi\RowResult::fetchAll example
  • Example#1625 - mysql_xdevapi\RowResult::fetchOne example
  • Example#1626 - mysql_xdevapi\RowResult::getColumnsCount example
  • Example#1627 - mysql_xdevapi\RowResult::getColumnNames example
  • Example#1628 - mysql_xdevapi\RowResult::getColumns example
  • Example#1629 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1630 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1631 - Schema::__construct example
  • Example#1632 - Schema::createCollection example
  • Example#1633 - Schema::createCollection validate parameter example
  • Example#1634 - Schema::dropCollection example
  • Example#1635 - Schema::existsInDatabase example
  • Example#1636 - Schema::getCollection example
  • Example#1637 - Schema::getCollectionAsTable example
  • Example#1638 - mysql_xdevapi\Schema::getCollections example
  • Example#1639 - mysql_xdevapi\Schema::getName example
  • Example#1640 - mysql_xdevapi\Schema::getSession example
  • Example#1641 - mysql_xdevapi\Schema::getTable example
  • Example#1642 - mysql_xdevapi\Schema::getTables example
  • Example#1643 - mysql_xdevapi\Session::getSchema example
  • Example#1644 - mysql_xdevapi\Session::close example
  • Example#1645 - mysql_xdevapi\Session::commit example
  • Example#1646 - mysql_xdevapi\Session::__construct example
  • Example#1647 - mysql_xdevapi\Session::createSchema example
  • Example#1648 - mysql_xdevapi\Session::dropSchema example
  • Example#1649 - mysql_xdevapi\Session::generateUuid example
  • Example#1650 - mysql_xdevapi\Session::getSchema example
  • Example#1651 - mysql_xdevapi\Session::getSchema example
  • Example#1652 - mysql_xdevapi\Session::getSchemas example
  • Example#1653 - mysql_xdevapi\Session::getServerVersion example
  • Example#1654 - mysql_xdevapi\Session::listClients example
  • Example#1655 - mysql_xdevapi\Session::quoteName example
  • Example#1656 - mysql_xdevapi\Session::releaseSavepoint example
  • Example#1657 - mysql_xdevapi\Session::rollback example
  • Example#1658 - mysql_xdevapi\Session::rollbackTo example
  • Example#1659 - mysql_xdevapi\Session::setSavepoint example
  • Example#1660 - mysql_xdevapi\Session::sql example
  • Example#1661 - mysql_xdevapi\Session::startTransaction example
  • Example#1662 - mysql_xdevapi\SqlStatement::bind example
  • Example#1663 - mysql_xdevapi\SqlStatement::__construct example
  • Example#1664 - mysql_xdevapi\SqlStatement::execute example
  • Example#1665 - mysql_xdevapi\SqlStatement::getNextResult example
  • Example#1666 - mysql_xdevapi\SqlStatement::getResult example
  • Example#1667 - mysql_xdevapi\SqlStatement::hasMoreResults example
  • Example#1668 - mysql_xdevapi\SqlStatementResult::__construct example
  • Example#1669 - mysql_xdevapi\SqlStatementResult::fetchAll example
  • Example#1670 - mysql_xdevapi\SqlStatementResult::fetchOne example
  • Example#1671 - mysql_xdevapi\SqlStatementResult::getAffectedItemsCount example
  • Example#1672 - mysql_xdevapi\SqlStatementResult::getColumnsCount example
  • Example#1673 - mysql_xdevapi\SqlStatementResult::getColumnNames example
  • Example#1674 - mysql_xdevapi\SqlStatementResult::getColumns example
  • Example#1675 - mysql_xdevapi\SqlStatementResult::getGeneratedIds example
  • Example#1676 - mysql_xdevapi\SqlStatementResult::getLastInsertId example
  • Example#1677 - mysql_xdevapi\SqlStatementResult::getWarnings example
  • Example#1678 - mysql_xdevapi\SqlStatementResult::getWarningsCount example
  • Example#1679 - mysql_xdevapi\SqlStatementResult::hasData example
  • Example#1680 - mysql_xdevapi\SqlStatementResult::nextResult example
  • Example#1681 - mysql_xdevapi\Statement::__construct example
  • Example#1682 - mysql_xdevapi\Statement::getNextResult example
  • Example#1683 - mysql_xdevapi\Statement::getResult example
  • Example#1684 - mysql_xdevapi\Statement::hasMoreResults example
  • Example#1685 - mysql_xdevapi\Table::__construct example
  • Example#1686 - mysql_xdevapi\Table::count example
  • Example#1687 - mysql_xdevapi\Table::delete example
  • Example#1688 - mysql_xdevapi\Table::existsInDatabase example
  • Example#1689 - mysql_xdevapi\Table::getName example
  • Example#1690 - mysql_xdevapi\Table::getSchema example
  • Example#1691 - mysql_xdevapi\Table::getSession example
  • Example#1692 - mysql_xdevapi\Table::insert example
  • Example#1693 - mysql_xdevapi\Table::isView example
  • Example#1694 - mysql_xdevapi\Table::count example
  • Example#1695 - mysql_xdevapi\Table::update example
  • Example#1696 - mysql_xdevapi\TableDelete::bind example
  • Example#1697 - mysql_xdevapi\TableDelete::__construct example
  • Example#1698 - mysql_xdevapi\TableDelete::execute example
  • Example#1699 - mysql_xdevapi\TableDelete::limit example
  • Example#1700 - mysql_xdevapi\TableDelete::orderBy example
  • Example#1701 - mysql_xdevapi\TableDelete::where example
  • Example#1702 - mysql_xdevapi\TableInsert::__construct example
  • Example#1703 - mysql_xdevapi\TableInsert::execute example
  • Example#1704 - mysql_xdevapi\TableInsert::values example
  • Example#1705 - mysql_xdevapi\TableSelect::bind example
  • Example#1706 - mysql_xdevapi\TableSelect::__construct example
  • Example#1707 - mysql_xdevapi\TableSelect::execute example
  • Example#1708 - mysql_xdevapi\TableSelect::groupBy example
  • Example#1709 - mysql_xdevapi\TableSelect::having example
  • Example#1710 - mysql_xdevapi\TableSelect::limit example
  • Example#1711 - mysql_xdevapi\TableSelect::lockExclusive example
  • Example#1712 - mysql_xdevapi\TableSelect::lockShared example
  • Example#1713 - mysql_xdevapi\TableSelect::offset example
  • Example#1714 - mysql_xdevapi\TableSelect::orderBy example
  • Example#1715 - mysql_xdevapi\TableSelect::where example
  • Example#1716 - mysql_xdevapi\TableUpdate::bind example
  • Example#1717 - mysql_xdevapi\TableUpdate::__construct example
  • Example#1718 - mysql_xdevapi\TableUpdate::execute example
  • Example#1719 - mysql_xdevapi\TableUpdate::limit example
  • Example#1720 - mysql_xdevapi\TableUpdate::orderby example
  • Example#1721 - mysql_xdevapi\TableUpdate::set example
  • Example#1722 - mysql_xdevapi\TableUpdate::where example
  • Example#1723 - mysql_xdevapi\Warning::__construct example
  • Example#1724 - Ejemplo general de la extensión MySQL
  • Example#1725 - Ejemplo de mysql_affected_rows
  • Example#1726 - Ejemplo de mysql_affected_rows al utilizar transacciones
  • Example#1727 - Ejemplo de mysql_client_encoding
  • Example#1728 - Ejemplo de mysql_close
  • Example#1729 - Ejemplo de mysql_connect
  • Example#1730 - Ejemplo de mysql_connect usando la sintaxis nombre_anfitrión:puerto
  • Example#1731 - Ejemplo de mysql_connect usando la sintaxis ":/rota/al/socket"
  • Example#1732 - Ejemplo alternativo de mysql_create_db
  • Example#1733 - Ejemplo de mysql_data_seek
  • Example#1734 - Ejemplo de mysql_db_name
  • Example#1735 - Ejemplo alternativo de mysql_db_query
  • Example#1736 - Ejemplo alternativo de mysql_drop_db
  • Example#1737 - Ejemplo de mysql_errno
  • Example#1738 - Ejemplo de mysql_error
  • Example#1739 - Ejemplo de mysql_escape_string
  • Example#1740 - Consulta con nombres de campos duplicados con alias
  • Example#1741 - mysql_fetch_array con MYSQL_NUM
  • Example#1742 - mysql_fetch_array con MYSQL_ASSOC
  • Example#1743 - mysql_fetch_array con MYSQL_BOTH
  • Example#1744 - Un ejemplo desarrolado de mysql_fetch_assoc
  • Example#1745 - Ejemplo de mysql_fetch_field
  • Example#1746 - Un ejemplo de mysql_fetch_lengths
  • Example#1747 - Ejemplo de mysql_fetch_object
  • Example#1748 - Ejemplo de mysql_fetch_object
  • Example#1749 - Recuperar una fila con mysql_fetch_row
  • Example#1750 - Un ejemplo de mysql_field_flags
  • Example#1751 - Ejemplo de mysql_field_len
  • Example#1752 - Ejemplo de mysql_field_name
  • Example#1753 - Un ejemplo de mysql_field_table
  • Example#1754 - Ejemplo de mysql_field_type
  • Example#1755 - Un ejemplo de mysql_free_result
  • Example#1756 - Ejemplo de mysql_get_client_info
  • Example#1757 - Ejemplo de mysql_get_host_info
  • Example#1758 - Ejemplo de mysql_get_proto_info
  • Example#1759 - Ejemplo de mysql_get_server_info
  • Example#1760 - Sentencias MySQL Relevantes
  • Example#1761 - Ejemplo de mysql_insert_id
  • Example#1762 - Ejemplo de mysql_list_dbs
  • Example#1763 - Alternativa para la obsoleta mysql_list_fields
  • Example#1764 - Ejemplo de mysql_list_processes
  • Example#1765 - Ejemplo alternativo de mysql_list_tables
  • Example#1766 - Un ejemplo de mysql_num_fields
  • Example#1767 - Ejemplo de mysql_num_rows
  • Example#1768 - Un ejemplo de mysql_ping
  • Example#1769 - Consulta inválida
  • Example#1770 - Consulta válida
  • Example#1771 - Ejemplo sencillo de mysql_real_escape_string
  • Example#1772 - mysql_real_escape_string requiere una conexión
  • Example#1773 - Un ejemplo de ataque de inyección de SQL
  • Example#1774 - Ejemplo de mysql_result
  • Example#1775 - Ejemplo mysql_select_db
  • Example#1776 - Ejemplo de mysql_stat
  • Example#1777 - Ejemplo alternativo de mysql_stat
  • Example#1778 - Ejemplo de mysql_tablename
  • Example#1779 - Ejemplo de mysql_thread_id
  • Example#1780 - Consulta básica
  • Example#1781 - Inserción con variables vinculadas
  • Example#1782 - Vincular la cláusula WHERE a una consulta
  • Example#1783 - Insertar datos en una columna CLOB
  • Example#1784 - Usar una función almacenada de PL/SQL
  • Example#1785 - Utilizar un procedimiento almacenado de PL/SQL
  • Example#1786 - Llamar a una función de PL/SQL que devuelve un REF CURSOR
  • Example#1787 -
  • Example#1788 - user_oci8_probes.d para rasrear todos los Sondeos estáticos de OCI8 para PHP al nivel de usuario con DTrace
  • Example#1789 - Ejemplo de oci_bind_array_by_name
  • Example#1790 - Insertar datos con oci_bind_by_name
  • Example#1791 - Vincular una vez para múltiples ejecuciones
  • Example#1792 - Vinculación con un bucle foreach
  • Example#1793 - Vinculación en una cláusula WHERE
  • Example#1794 - Vinculación con una cláusula LIKE
  • Example#1795 - Vinculación con REGEXP_LIKE
  • Example#1796 - Vinculación de múltiples valores en una cláusula IN
  • Example#1797 - Vinculación de un ROWID devuelto por una consulta
  • Example#1798 - Vinculación de un ROWID sobre INSERT
  • Example#1799 - Vinculación para una función almacenada de PL/SQL
  • Example#1800 - Vinculación de parámetros para un procedimiento almacenado de PL/SQL
  • Example#1801 - Vinculación de una columna CLOB
  • Example#1802 - Vincular un BOOLEAN de PL/SQL
  • Example#1803 - Ejemplo de oci_client_version
  • Example#1804 - Cerrar una conexión
  • Example#1805 - Las conexiones a bases de datos no se cierran hasta que todas las referencias sean cerradas
  • Example#1806 - Cerrar una conexión abierta más de una vez
  • Example#1807 - Las conexsiones se cierran cuando las variables salen de su ámbito
  • Example#1808 - Ejemplo de oci_commit
  • Example#1809 - Uso básico de oci_connect utilizando la sintaxis de Easy Connect
  • Example#1810 - Uso básico de oci_connect utilizando un nombre de Network Connect
  • Example#1811 - oci_connect con un conjunto de caracteres explícito
  • Example#1812 - Usar múltiples llamadas a oci_connect
  • Example#1813 - Ejemplo de oci_define_by_name
  • Example#1814 - oci_define_by_name con nombres de columna sensibles al uso de mayúsculas/minúsculas
  • Example#1815 - oci_define_by_name con columnas de tipo LOB
  • Example#1816 - oci_define_by_name con un tipo explícito
  • Example#1817 - Mostrar el mensaje de error de Oracle después de un error de conexión
  • Example#1818 - Mostrar el mensaje de error de Oracle después de un error de análisis
  • Example#1819 - Mostrar el mensaje de error de Oracle, la sentencia problemática, y la posición del problema en un error de ejecución
  • Example#1820 - oci_execute para consultas
  • Example#1821 - Ejemplo de oci_execute sin especificar un modo
  • Example#1822 - Ejemplo de oci_execute con OCI_NO_AUTO_COMMIT
  • Example#1823 - Ejemplo de oci_execute con diferentes modos de consolidación
  • Example#1824 - Ejemplo de oci_execute con OCI_DESCRIBE_ONLY
  • Example#1825 - Ejemplo de oci_fetch_all
  • Example#1826 - Ejemplo de oci_fetch_all con OCI_FETCHSTATEMENT_BY_ROW
  • Example#1827 - oci_fetch_all con OCI_NUM
  • Example#1828 - oci_fetch_array con OCI_BOTH
  • Example#1829 - oci_fetch_array con OCI_NUM
  • Example#1830 - oci_fetch_array con OCI_ASSOC
  • Example#1831 - oci_fetch_array con OCI_RETURN_NULLS
  • Example#1832 - oci_fetch_array con OCI_RETURN_LOBS
  • Example#1833 - oci_fetch_array con nombres de columna sensibles al uso de mayúsculas/minúsculas
  • Example#1834 - oci_fetch_array con columnas que tienen nombres duplicados
  • Example#1835 - oci_fetch_array con columnas DATE
  • Example#1836 - oci_fetch_array con REF CURSOR
  • Example#1837 - Paginación con oci_fetch_array usando una consulta como LIMIT
  • Example#1838 - oci_fetch_array con Conjuntos de Resultados Implícitos de Oracle Database 12c
  • Example#1839 - Ejemplo de oci_fetch_assoc
  • Example#1840 - Ejemplo de oci_fetch_object
  • Example#1841 - oci_fetch_object con nombres de columnas sensibles al uso de mayúsculas/minúsculas
  • Example#1842 - oci_fetch_object con LOBs
  • Example#1843 - Ejemplo de oci_fetch_row
  • Example#1844 - oci_fetch con variables definidas
  • Example#1845 - oci_fetch con oci_result
  • Example#1846 - Ejemplo de oci_field_name
  • Example#1847 - Ejemplo de oci_field_name
  • Example#1848 - Ejemplo de oci_field_precision
  • Example#1849 - oci_field_scale Example
  • Example#1850 - Ejemplo de oci_field_size
  • Example#1851 - oci_field_type_raw Example
  • Example#1852 - Ejemplo de oci_field_type
  • Example#1853 - Obtener Conjuntos de resultados implícitos en un blucle
  • Example#1854 - Obtener gestores de sentencias hijas individualemente
  • Example#1855 - Establecer explícitamente la Cuenta de precarga
  • Example#1856 - Ejemplo de Conjunto de resultados implícitos sin usar oci_get_implicit_resultset
  • Example#1857 - Ejemplo de oci_new_connect
  • Example#1858 - Vincular un REF CURSOR en una llamada a un procedimiento almacenado de Oracle
  • Example#1859 - Ejemplo de oci_new_descriptor
  • Example#1860 - Ejemplo de oci_new_descriptor
  • Example#1861 - Ejemplo de oci_num_fields
  • Example#1862 - Ejemplo de oci_num_rows
  • Example#1863 - Ejemplo de oci_parse para sentencias SQL
  • Example#1864 - Ejemplo de oci_parse para sentencias PL/SQL
  • Example#1865 - Ejemplo de oci_password_change cambiando la contraseña de un usuario ya conectado
  • Example#1866 - Ejemplo de oci_password_change conectando y cambiando la contraseña en un solo paso
  • Example#1867 - Ejemplo básico de oci_pconnect usando la sintaxis de Easy Connect
  • Example#1868 - oci_fetch con oci_result
  • Example#1869 - Ejemplo de oci_rollback
  • Example#1870 - Ejemplo de reversión a un SAVEPOINT
  • Example#1871 - Ejemplo de oci_server_version
  • Example#1872 - Establecer la acción
  • Example#1873 - Ajuste del tiempo de espera
  • Example#1874 - Establecer el identificador del cliente para el usuario de la aplicación
  • Example#1875 - Establecer la información del cliente
  • Example#1876 - Ajuste del DBOP
  • Example#1877 - Dos scripts pueden usar diferentes versiones de myfunc() a la vez
  • Example#1878 - Establecer el nombre del módulo
  • Example#1879 - Cambiando el valor de prefetch de LOB para una consulta
  • Example#1880 - Cambiar el valor de precarga predeterminado para una consulta
  • Example#1881 - Cambiar la precarga predeterminada para la obtención de un REF CURSOR
  • Example#1882 - Establecer el valor de precarga cuando se vuelve a pasar un REF CURSOR a Oracle
  • Example#1883 - Ejemplo de oci_statement_type
  • Example#1884 - Ejemplo resumido de la extensión PostgreSQL
  • Example#1885 - Ejemplo de pg_affected_rows
  • Example#1886 - Ejemplo de pg_cancel_query
  • Example#1887 - Ejemplo de pg_client_encoding
  • Example#1888 - Ejemplo de pg_close
  • Example#1889 - Usando pg_connect
  • Example#1890 - Ejemplo de pg_connection_busy
  • Example#1891 - Ejemplo de pg_connection_reset
  • Example#1892 - Ejemplo de pg_connection_status
  • Example#1893 - Ejemplo de pg_convert
  • Example#1894 - Ejemplo de la función pg_copy_from
  • Example#1895 - Ejemplo de pg_copy_to
  • Example#1896 - Ejemplo de pg_dbname
  • Example#1897 - Ejemplo de la función pg_delete
  • Example#1898 - pg_end_copy example
  • Example#1899 - Ejemplo de pg_escape_bytea
  • Example#1900 - pg_escape_identifier example
  • Example#1901 - pg_escape_literal example
  • Example#1902 - pg_escape_string example
  • Example#1903 - Usando pg_execute
  • Example#1904 - pg_fetch_all_columns example
  • Example#1905 - PostgreSQL fetch all
  • Example#1906 - pg_fetch_array example
  • Example#1907 - pg_fetch_assoc example
  • Example#1908 - pg_fetch_object example
  • Example#1909 - pg_fetch_result example
  • Example#1910 - pg_fetch_row example
  • Example#1911 - pg_field_is_null example
  • Example#1912 - Getting information about fields
  • Example#1913 - Getting information about fields
  • Example#1914 - Getting information about fields
  • Example#1915 - Getting information about fields
  • Example#1916 - Getting table information about a field
  • Example#1917 - Getting information about fields
  • Example#1918 - Obtención de información sobre los campos
  • Example#1919 - pg_free_result example
  • Example#1920 - PostgreSQL NOTIFY message
  • Example#1921 - PostgreSQL backend PID
  • Example#1922 - pg_get_result example
  • Example#1923 - Ejemplo de pg_host
  • Example#1924 - pg_insert example
  • Example#1925 - Ejemplo depg_last_error
  • Example#1926 - Ejemplo de pg_last_notice
  • Example#1927 - pg_last_oid example
  • Example#1928 - pg_lo_close example
  • Example#1929 - pg_lo_create example
  • Example#1930 - pg_lo_export example
  • Example#1931 - pg_lo_import example
  • Example#1932 - pg_lo_open example
  • Example#1933 - pg_lo_read_all example
  • Example#1934 - pg_lo_read example
  • Example#1935 - pg_lo_seek example
  • Example#1936 - pg_lo_tell example
  • Example#1937 - pg_lo_truncate example
  • Example#1938 - pg_lo_unlink example
  • Example#1939 - pg_lo_write example
  • Example#1940 - Getting table metadata
  • Example#1941 - pg_num_fields example
  • Example#1942 - pg_num_rows example
  • Example#1943 - Ejemplo de pg_options
  • Example#1944 - pg_parameter_status example
  • Example#1945 - Usando pg_pconnect
  • Example#1946 - Ejemplo de pg_ping
  • Example#1947 - Ejemplo de pg_port
  • Example#1948 - Usando pg_prepare
  • Example#1949 - pg_put_line example
  • Example#1950 - Using pg_query_params
  • Example#1951 - Ejemplo de pg_query
  • Example#1952 - Uso de pg_query con varias sentencias
  • Example#1953 - pg_result_error_field example
  • Example#1954 - pg_result_error example
  • Example#1955 - pg_result_seek example
  • Example#1956 - pg_result_status example
  • Example#1957 - pg_select example
  • Example#1958 - Using pg_send_execute
  • Example#1959 - Utilizando pg_send_prepare
  • Example#1960 - Using pg_send_query_params
  • Example#1961 - pg_send_query example
  • Example#1962 - pg_set_client_encoding example
  • Example#1963 - pg_set_error_context_visibility example
  • Example#1964 - pg_set_error_verbosity example
  • Example#1965 - pg_trace example
  • Example#1966 - Ejemplo de pg_transaction_status
  • Example#1967 - Ejemplo de pg_tty
  • Example#1968 - pg_unescape_bytea example
  • Example#1969 - Ejemplo de pg_untrace
  • Example#1970 - Ejemplo de pg_update
  • Example#1971 - Ejemplo de pg_version
  • Example#1972 - Backup an existing database
  • Example#1973 - Ejemplo de SQLite3::changes
  • Example#1974 - Ejemplo de SQLite3::close
  • Example#1975 - Ejemplo de SQLite3::__construct
  • Example#1976 - SQLite3::createCollation
  • Example#1977 - Ejemplo de SQLite3::createFunction
  • Example#1978 - SQLite3::enableExceptions example
  • Example#1979 - Ejemplo de SQLite3::exec
  • Example#1980 - Ejemplo de SQLite3::loadExtension
  • Example#1981 - Ejemplo de SQLite3::open
  • Example#1982 - SQLite3::openBlob example
  • Example#1983 - Incrementally writing a BLOB
  • Example#1984 - Ejemplo de SQLite3::prepare
  • Example#1985 - Ejemplo de SQLite3::query
  • Example#1986 - Ejemplo de SQLite3::querySingle
  • Example#1987 - SQLite3::setAuthorizer example
  • Example#1988 - Ejemplo de SQLite3::version
  • Example#1989 - Ejemplo de SQLite3Stmt::bindValue
  • Example#1990 - Inspecting the expanded SQL
  • Example#1991 - Ejemplo de sqlsrv_begin_transaction
  • Example#1992 - Ejemplo de sqlsrv_cancel
  • Example#1993 - Ejemplo de sqlsrv_client_info
  • Example#1994 - Ejemplo de sqlsrv_close
  • Example#1995 - Ejemplo de sqlsrv_commit
  • Example#1996 - Conectar utilizando autenticación Windows.
  • Example#1997 - Conectar especificando nombre de usuario y contraseña.
  • Example#1998 - Conectar a un puerto específico.
  • Example#1999 - ejemplo de functionname
  • Example#2000 - ejemplo de sqlsrv_execute
  • Example#2001 - Devolver un array asociativo.
  • Example#2002 - Devolver un array numérico.
  • Example#2003 - Ejemplo con sqlsrv_fetch_object
  • Example#2004 - Ejemplo con sqlsrv_fetch
  • Example#2005 - Ejemplo con sqlsrv_field_metadata
  • Example#2006 - sqlsrv_free_stmt example
  • Example#2007 - sqlsrv_get_field example
  • Example#2008 - sqlsrv_has_rows example
  • Example#2009 - sqlsrv_next_result example
  • Example#2010 - sqlsrv_num_fields example
  • Example#2011 - sqlsrv_num_rows example
  • Example#2012 - sqlsrv_prepare example
  • Example#2013 - sqlsrv_query example
  • Example#2014 - sqlsrv_rollback example
  • Example#2015 - sqlsrv_rows_affected example
  • Example#2016 - sqlsrv_send_stream_data example
  • Example#2017 - sqlsrv_server_info example
  • Example#2018 - Ejemplo de cal_days_in_month
  • Example#2019 - Ejemplo de cal_from_jd
  • Example#2020 - Ejemplo de cal_info
  • Example#2021 - Ejemplo de easter_date
  • Example#2022 - Ejemplo de easter_days
  • Example#2023 - Funciones de calendario
  • Example#2024 - Ejemplo de jdtojewish
  • Example#2025 - DateTime::add/sub, añadir intervalos que cubren el tiempo transcurrido
  • Example#2026 - DateTime::modify y strtotime, aumentar o disminuir valores de componentes individuales
  • Example#2027 - Añadir o restar horas puede sobrepasar o subpasar fechas
  • Example#2028 - Ejemplo de DateTime::add
  • Example#2029 - Más ejemplos de DateTime::add
  • Example#2030 - Cuidado al añadir meses
  • Example#2031 - Ejemplo de DateTime::__construct
  • Example#2032 - Complejidades de DateTime::__construct
  • Example#2033 - Ejemplo de DateTime::createFromFormat
  • Example#2034 - Complejidades de DateTime::createFromFormat
  • Example#2035 - Cadena de formato con caracteres literales
  • Example#2036 - Creating a mutable date time object
  • Example#2037 - Creating a mutable date time object
  • Example#2038 - Ejemplo de DateTime::getLastErrors
  • Example#2039 - Ejemplo de DateTime::modify
  • Example#2040 - Cuidado al añadir o sustraer meses
  • Example#2041 - Ejemplo de DateTime::setDate
  • Example#2042 - Los valores que exceden rangos son añadidos a sus valores padre
  • Example#2043 - Ejemplo de DateTime::setISODate
  • Example#2044 - Los valores que execen rangos son añadidos a sus valores padre
  • Example#2045 - Buscar el mes en el que se encuentra una semana
  • Example#2046 - Ejemplo de DateTime::setTime
  • Example#2047 - Los valores que exceden rangos son añadidos a sus valores padre
  • Example#2048 - Ejemplo de DateTime::setTimestamp
  • Example#2049 - Alternativa de DateTime::setTimestamp en PHP 5.2
  • Example#2050 - Ejemplo de DateTime::setTimeZone
  • Example#2051 - Ejemplo de DateTime::sub
  • Example#2052 - Más ejemplos de DateTime::sub
  • Example#2053 - Cuidado al sustraer meses
  • Example#2054 - Creating an immutable date time object
  • Example#2055 - Crear un objeto de fecha y hora inmutable
  • Example#2056 - Ejemplo de DateTime::diff
  • Example#2057 - Comparación de objetos DateTime
  • Example#2058 - Ejemplo de DateTime::format
  • Example#2059 - Ejemplo de DateTime::getOffset
  • Example#2060 - Ejemplo de DateTime::getTimestamp
  • Example#2061 - Ejemplo de DateTime::getTimezone
  • Example#2062 - Atrapar errores cuando se instancia un DateTimeZone
  • Example#2063 - Ejemplo de DateTimeZone::getLocation
  • Example#2064 - Ejemplo de DateTimeZone::getOffset
  • Example#2065 - Un ejemplo de timezone_transitions_get
  • Example#2066 - Un ejemplo de timezone_abbreviations_list
  • Example#2067 - Un ejemplo de timezone_identifiers_list
  • Example#2068 - Ejemplo de DateInterval
  • Example#2069 - Analizar intervalos de fechas válidos
  • Example#2070 - Ejemplo de DateInterval
  • Example#2071 - DateInterval y excesos
  • Example#2072 - DateInterval y DateTime::diff con los modificadores %a y %d
  • Example#2073 - Ejemplo de DatePeriod
  • Example#2074 - Ejemplo de DatePeriod con DatePeriod::EXCLUDE_START_DATE
  • Example#2075 - DatePeriod::createFromISO8601String example
  • Example#2076 - Ejemplo de DatePeriod::getDateInterval
  • Example#2077 - Ejemplo de DatePeriod::getEndDate
  • Example#2078 - DatePeriod::getEndDate sin una fecha final
  • Example#2079 - Different values for DatePeriod::getRecurrences
  • Example#2080 - Ejemplo de DatePeriod::getStartDate
  • Example#2081 - Ejemplo de checkdate
  • Example#2082 - Obtener la zona horaria por defecto
  • Example#2083 - Obtener la abreviatura de una zona horaria
  • Example#2084 - Obtener la zona horaria por defecto
  • Example#2085 - Ejemplo de date_parse_from_format
  • Example#2086 - Un ejemplo de date_parse
  • Example#2087 - date_parse con formatos relativos
  • Example#2088 - Un ejemplo de date_sun_info
  • Example#2089 - Ejemplo de date_sunrise
  • Example#2090 - Ejemplo de date_sunset
  • Example#2091 - Ejemplo de date
  • Example#2092 - Escapar caracteres en date
  • Example#2093 - Ejemplo de date y mktime
  • Example#2094 - date Formatting
  • Example#2095 - Ejemplo de getdate
  • Example#2096 - Ejemplo de gettimeofday
  • Example#2097 - Ejemplo de gmdate
  • Example#2098 - Ejemplo básico de gmmktime
  • Example#2099 - Ejemplo de gmstrftime
  • Example#2100 - Ejemplo de idate
  • Example#2101 - Ejemplo de localtime
  • Example#2102 - Ejecución de un script de cronometraje con microtime
  • Example#2103 - Ejecución de un script de cronometraje en PHP 5
  • Example#2104 - microtime y REQUEST_TIME_FLOAT (desde PHP 5.4.0)
  • Example#2105 - Ejemplo básico de mktime
  • Example#2106 - Ejemplo de mktime
  • Example#2107 - El último día del mes
  • Example#2108 - Ejemplos de localismos con strftime
  • Example#2109 - Ejemplo de número de semana del ISO 8601:1988
  • Example#2110 - Ejemplo multiplataforma compatible del modificador %e
  • Example#2111 - Mostrar todos los formatos conocidos y desconocidos.
  • Example#2112 - Ejemplo de strptime
  • Example#2113 - Un ejemplo de strtotime
  • Example#2114 - Comprobar si falla
  • Example#2115 - Ejemplo de time
  • Example#2116 - Un ejemplo de timezone_name_from_abbr
  • Example#2117 - Obtener la versión de timezonedb
  • Example#2118 - Medir la ejecución de varios bloques de código y obtener el total
  • Example#2119 - Cerrando un descriptor de fichero
  • Example#2120 - Bloqueando y desbloqueando
  • Example#2121 - Abrir un descriptor de fichero
  • Example#2122 - Posicionamiento de un fichero
  • Example#2123 - Asignando la tasa de baudios del puerto serie
  • Example#2124 - chdir ejemplo
  • Example#2125 - Ejemplo de chroot
  • Example#2126 - closedir ejemplo
  • Example#2127 - Ejemplo de dir
  • Example#2128 - getcwd ejemplo
  • Example#2129 - opendir ejemplo
  • Example#2130 - Listar todas las entradas de un directorio
  • Example#2131 - Listar todas las entradas del directorio actual y descartar . y ..
  • Example#2132 - Un simple ejemplo de scandir
  • Example#2133 - Ejemplo de finfo_buffer
  • Example#2134 - Un ejemplo de finfo_file
  • Example#2135 - Estilo orientado a objetos
  • Example#2136 - Estilo por procedimientos
  • Example#2137 - Ejemplo mime_content_type
  • Example#2138 - Ejemplo de basename
  • Example#2139 - Cambiar el grupo de un archivo
  • Example#2140 - Uso sencillo de chown
  • Example#2141 - Ejemplo de clearstatcache
  • Example#2142 - Ejemplo de copy
  • Example#2143 - Ejemplo de dirname
  • Example#2144 - Ejemplo de disk_free_space
  • Example#2145 - Ejemplo de disk_total_space
  • Example#2146 - Un ejemplo sencillo de fclose
  • Example#2147 - fdatasync example
  • Example#2148 - Manejar tiempos de espera con feof
  • Example#2149 - Ejemplo de feof con un puntero a un archivo no válido
  • Example#2150 - Ejemplo de escritura de un archivo usando fflush
  • Example#2151 - Un ejemplo de fgetc
  • Example#2152 - Leer e imprimir el contenido completo de un fichero CSV
  • Example#2153 - Leer un fichero línea a línea
  • Example#2154 - Leer un archivo PHP línea a línea
  • Example#2155 - Comprobar si existe un fichero
  • Example#2156 - Obtiene y muestra el código fuente de la página de inicio de un sitio web
  • Example#2157 - Buscar dentro de include_path
  • Example#2158 - Leer una sección de un fichero
  • Example#2159 - Usar contextos de flujo
  • Example#2160 - Ejemplo sencillo de uso
  • Example#2161 - Usar banderas
  • Example#2162 - Ejemplo de file
  • Example#2163 - Ejemplo de fileatime
  • Example#2164 - Un ejemplo de filectime
  • Example#2165 - Encontrar el grupo de un archivo
  • Example#2166 - Comparar el i-nodo de un archivo con el archivo actual
  • Example#2167 - Ejemplo de filemtime
  • Example#2168 - Encontrar el propietario de un archivo
  • Example#2169 - Muestra los permisos como un valor octal
  • Example#2170 - Muestra los permisos completos
  • Example#2171 - Ejemplo de filesize
  • Example#2172 - Ejemplo de filetype
  • Example#2173 - Ejemplo de flock
  • Example#2174 - flock usando la opción LOCK_NB
  • Example#2175 - Comprobar un adjetivo con un patrón comodín tipo shell
  • Example#2176 - Ejemplos de fopen
  • Example#2177 - Usar fpassthru con archivos binarios
  • Example#2178 - Ejemplo de fputcsv
  • Example#2179 - Un ejemplo sencillo de fread
  • Example#2180 - Ejemplo de lectura binaria de fread
  • Example#2181 - Ejemplos de lectura remota con fread
  • Example#2182 - Ejemplo de fscanf
  • Example#2183 - Contenido de usuarios.txt
  • Example#2184 - Ejemplo de fseek
  • Example#2185 - Ejemplo de fstat
  • Example#2186 - fsync example
  • Example#2187 - Ejemplo de ftell
  • Example#2188 - Ejemplo de truncar un archivo
  • Example#2189 - Un ejemplo sencillo de fwrite
  • Example#2190 - Manera conveniente de cómo glob puede remplazar a opendir y similares.
  • Example#2191 - Ejemplo de is_dir
  • Example#2192 - Ejemplo de is_executable
  • Example#2193 - Ejemplo de is_file
  • Example#2194 - Crear y confirmar si un archivo es un enlace simbólico
  • Example#2195 - Ejemplo de is_readable
  • Example#2196 - Ejemplo de is_uploaded_file
  • Example#2197 - Ejemplo de is_writable
  • Example#2198 - Cambiar el grupo de un enlace simbólico
  • Example#2199 - Cambiar el propietario de un enlace simbólico
  • Example#2200 - Crear un simple enlace duro
  • Example#2201 - Ejmeplo de linkinfo
  • Example#2202 - Comparación de stat y lstat
  • Example#2203 - Ejmplo de mkdir
  • Example#2204 - mkdir usando el parámetro recursive
  • Example#2205 - Subida de múltiples archivos
  • Example#2206 - Contenido de ejemplo.ini
  • Example#2207 - Ejemplo de parse_ini_file
  • Example#2208 - parse_ini_file analizando un fichero de php.ini
  • Example#2209 - Ejemplo de pathinfo
  • Example#2210 - Ejemplo de pathinfo mostrando las diferencias entre null y no utilizar extensión
  • Example#2211 - Ejemplo de pathinfo para un fichero que comienza con punto
  • Example#2212 - Ejemplo de pclose
  • Example#2213 - Ejemplo de popen
  • Example#2214 - Ejemplo de popen
  • Example#2215 - Forzar un descarga empleando readfile
  • Example#2216 - Ejemplo de readlink
  • Example#2217 - Ejemplo de realpath_cache_get
  • Example#2218 - Ejemplo de realpath_cache_size
  • Example#2219 - Ejemplo de realpath
  • Example#2220 - realpath en Windows
  • Example#2221 - Ejemplo con rename
  • Example#2222 - Ejemplo de sobrescritura con rewind
  • Example#2223 - Ejemplo de rmdir
  • Example#2224 - Ejemplo de stat
  • Example#2225 - Usar la información de stat junto con touch
  • Example#2226 - Crear un enlace simbólico
  • Example#2227 - Ejemplo de tempnam
  • Example#2228 - Ejemplo de tmpfile
  • Example#2229 - Ejemplo de touch
  • Example#2230 - touch usando el parámetro time
  • Example#2231 - Ejemplo de umask
  • Example#2232 - Uso básico de unlink
  • Example#2233 - Ejemplo de uso de inotify
  • Example#2234 - Comprueba si el administrador del sistema firmó el archivo
  • Example#2235 - Imprime los nombres de todos los atributos extendidos del archivo
  • Example#2236 - Elimina todos los atributos extendidos de un archivo
  • Example#2237 - Establece atributos extendidos en archivo .wav
  • Example#2238 - Ejemplo de xattr_supported
  • Example#2239 - Ejemplo de xdiff_file_bdiff_size
  • Example#2240 - Ejemplo de xdiff_file_bdiff
  • Example#2241 - xdiff_file_bpatch example
  • Example#2242 - Ejemplo de xdiff_file_diff_binary
  • Example#2243 - Ejemplo de xdiff_file_diff
  • Example#2244 - Ejemplo de xdiff_file_merge3
  • Example#2245 - Ejemplo de xdiff_file_patch_binary
  • Example#2246 - Ejemplo de xdiff_file_patch
  • Example#2247 - Ejemplo de parche invertido
  • Example#2248 - Ejemplo de xdiff_file_rabdiff
  • Example#2249 - Ejemplo de xdiff_string_bdiff_size
  • Example#2250 - Ejemplo de xdiff_string_diff
  • Example#2251 - Ejemplo de xdiff_string_patch
  • Example#2252 - Ejemplos de Uso de Enchant
  • Example#2253 - Listar los entornos proporcionados por el agente dado
  • Example#2254 - Un ejemplo de enchant_broker_dict_exists
  • Example#2255 - Listar todos los diccionarios disponibles para un agente
  • Example#2256 - Un ejemplo de enchant_broker_request_dict
  • Example#2257 - Añadir una palabra a un PWL
  • Example#2258 - Adding a word to a PWL
  • Example#2259 - Un ejemplo de enchant_dict_describe
  • Example#2260 - Un ejemplo de enchant_dict_quick_check
  • Example#2261 - Un ejemplo de enchant_dict_suggest
  • Example#2262 - Ejemplo de uso.
  • Example#2263 - Uso de Gender\Gender::country
  • Example#2264 - Ejemplo de bindtextdomain
  • Example#2265 - gettext-check
  • Example#2266 - Ejemplo de ngettext
  • Example#2267 - Ejemplo de iconv_get_encoding
  • Example#2268 - Ejemplo de iconv_mime_decode_headers
  • Example#2269 - Ejemplo de la función iconv_mime_decode
  • Example#2270 - Ejemplo de iconv_mime_encode
  • Example#2271 - Ejemplo de iconv_set_encoding
  • Example#2272 - Ejemplo de iconv
  • Example#2273 - Ejemplo de ob_iconv_handler
  • Example#2274 - Ejemplo usando la API procedimental
  • Example#2275 - Ejemplo usando la API orientada a objetos
  • Example#2276 - Reglas de FRENCH_COLLATION
  • Example#2277 - Reglas de ALTERNATE_HANDLING
  • Example#2278 - Reglas de CASE_FIRST
  • Example#2279 - Reglas de CASE_LEVEL
  • Example#2280 - Ejemplo de collator_asort
  • Example#2281 - Ejemplo de collator_compare
  • Example#2282 - Ejemplo de Collator::__construct
  • Example#2283 - Ejemplo de collator_create
  • Example#2284 - Ejemplo de collator_get_attribute
  • Example#2285 - Ejemplo collator_get_error_code
  • Example#2286 - Ejemplo de collator_get_error_message
  • Example#2287 - Ejemplo collator_get_locale
  • Example#2288 - Ejemplo de collator_get_sort_key
  • Example#2289 - Ejemplo de collator_get_strength
  • Example#2290 - Ejemplo de collator_set_attribute
  • Example#2291 - Ejemplo de collator_set_strength
  • Example#2292 - Ejemplo de collator_sort_with_sort_keys
  • Example#2293 - Ejemplo de collator_sort
  • Example#2294 - Ejemplo de numfmt_create
  • Example#2295 - Ejemplo de NumberFormatter::create
  • Example#2296 - Ejemplo de numfmt_format_currency
  • Example#2297 - Ejemplo orientado a objetos
  • Example#2298 - Ejemplo de numfmt_format
  • Example#2299 - Ejemplo orientado a objetos
  • Example#2300 - Ejemplo de numfmt_get_attribute
  • Example#2301 - Ejemplo orientado a objetos
  • Example#2302 - Ejemplo de numfmt_get_error_code
  • Example#2303 - Ejemplo orientado a objetos
  • Example#2304 - Ejemplo de numfmt_get_error_message
  • Example#2305 - Ejemplo orientado a objetos
  • Example#2306 - Ejemplo de numfmt_get_locale
  • Example#2307 - Ejemplo de numfmt_get_pattern
  • Example#2308 - OO example
  • Example#2309 - Ejemplo de numfmt_get_symbol
  • Example#2310 - OO example
  • Example#2311 - Ejemplo de numfmt_get_text_attribute
  • Example#2312 - OO example
  • Example#2313 - Ejemplo de numfmt_parse_currency
  • Example#2314 - OO example
  • Example#2315 - Ejemplo de numfmt_parse
  • Example#2316 - Ejemplo O.O.
  • Example#2317 - Ejemplo de numfmt_set_attribute
  • Example#2318 - OO example
  • Example#2319 - Ejemplo de numfmt_set_pattern
  • Example#2320 - OO example
  • Example#2321 - Ejemplo de numfmt_set_symbol
  • Example#2322 - OO example
  • Example#2323 - Ejemplo de numfmt_set_text_attribute
  • Example#2324 - OO example
  • Example#2325 - Ejemplo de locale_accept_from_http
  • Example#2326 - Ejemplo orientado a objetos
  • Example#2327 - Ejemplo de locale_compose
  • Example#2328 - Ejemplo orientado a objetos
  • Example#2329 - Ejemplo de locale_filter_matches
  • Example#2330 - Ejemplo orientado a objetos
  • Example#2331 - Ejepmplo de locale_get_all_variants
  • Example#2332 - Ejemplo orientado a objetos
  • Example#2333 - Ejemplo de locale_get_default
  • Example#2334 - Ejemplo orientado a objetos
  • Example#2335 - Ejemplo de locale_get_display_language
  • Example#2336 - Ejemplo orientado a objetos
  • Example#2337 - Ejemplo de locale_get_display_name
  • Example#2338 - Ejemplo orientado a objetos
  • Example#2339 - Ejemplo de locale_get_display_region
  • Example#2340 - Ejemplo orientado a objetos
  • Example#2341 - Ejemplo de locale_get_display_script
  • Example#2342 - Ejemplo orientado a objetos
  • Example#2343 - Ejemplo de locale_get_display_variant
  • Example#2344 - Ejemplo orientado a objetos
  • Example#2345 - Ejemplo de locale_get_keywords
  • Example#2346 - Ejemplo orientado a objetos
  • Example#2347 - Ejemplo de locale_get_primary_language
  • Example#2348 - Ejemplo orientado a objetos
  • Example#2349 - Ejemplo de locale_get_region
  • Example#2350 - Ejemplo orientado a objetos
  • Example#2351 - Ejemplo de locale_get_script
  • Example#2352 - Ejemplo orientado a objetos
  • Example#2353 - Ejemplo de locale_lookup
  • Example#2354 - Ejemplo orientado a objetos
  • Example#2355 - Ejemplo locale_parse
  • Example#2356 - Ejemplo orientado a objetos
  • Example#2357 - Ejemplo de locale_set_default
  • Example#2358 - Ejemplo orientado a objetos
  • Example#2359 - Normalizer::getRawDecomposition example
  • Example#2360 - Ejemplo de normalizer_is_normalized
  • Example#2361 - Ejemplo orientado a objetos
  • Example#2362 - Ejemplo de normalizer_normalize
  • Example#2363 - Ejemplo Orientado a Objetos
  • Example#2364 - Ejemplo de msgfmt_create
  • Example#2365 - Ejemplo orientado a objetos
  • Example#2366 - Ejemplo de msgfmt_format_message
  • Example#2367 - Ejemplo orientado a objetos
  • Example#2368 - Ejemplo de msgfmt_format
  • Example#2369 - Ejemplo orientado a objetos
  • Example#2370 - Ejemplo de msgfmt_get_error_code
  • Example#2371 - Ejemplo orientado a objetos
  • Example#2372 - Ejemplo de msgfmt_get_error_message
  • Example#2373 - Ejemplo orientado a objetos
  • Example#2374 - Ejemplo de msgfmt_get_locale
  • Example#2375 - Ejemplo orientado a objetos
  • Example#2376 - Ejemplo de msgfmt_get_pattern
  • Example#2377 - Ejemplo orientado a objetos
  • Example#2378 - Ejemplo de msgfmt_parse_message
  • Example#2379 - Ejemplo orientado a objetos
  • Example#2380 - Ejemplo de msgfmt_parse
  • Example#2381 - Ejemplo orientado a objetos
  • Example#2382 - Ejemplo de msgfmt_set_pattern
  • Example#2383 - Ejemplo orientado a objetos
  • Example#2384 - IntlCalendar::add
  • Example#2385 - IntlCalendar::after
  • Example#2386 - Ejemplod de IntlCalendar::clear
  • Example#2387 - IntlCalendar::createInstance
  • Example#2388 - IntlCalendar::equals
  • Example#2389 - IntlCalendar::fieldDifference
  • Example#2390 - IntlCalendar::fromDateTime
  • Example#2391 - IntlCalendar::get
  • Example#2392 - IntlCalendar::getActualMaximum
  • Example#2393 - IntlCalendar::getAvailableLocales()
  • Example#2394 - IntlCalendar::getDayOfWeekType
  • Example#2395 - IntlCalendar::getErrorCode y IntlCalendar::getErrorMessage
  • Example#2396 - IntlCalendar::getErrorMessage
  • Example#2397 - IntlCalendar::getFirstDayOfWeek
  • Example#2398 - IntlCalendar::getKeyworkValuesForLocale
  • Example#2399 - Ejemplos de máximos
  • Example#2400 - IntlCalendar::getLocale
  • Example#2401 - IntlCalendar::getMinimalDaysInFirstWeek
  • Example#2402 - IntlCalendar::getNow
  • Example#2403 - IntlCalendar::getRepeatedWallTimeOption
  • Example#2404 - IntlCalendar::getSkippedWallTimeOption
  • Example#2405 - IntlCalendar::getTime
  • Example#2406 - IntlCalendar::getTimeZone
  • Example#2407 - IntlCalendar::getType
  • Example#2408 - IntlCalendar::inDaylightTime
  • Example#2409 - IntlCalendar::isEquivalentTo
  • Example#2410 - IntlCalendar::isLenient
  • Example#2411 - IntlCalendar::isWeekend
  • Example#2412 - IntlCalendar::roll
  • Example#2413 - IntlCalendar::set
  • Example#2414 - IntlCalendar::setDate example
  • Example#2415 - IntlCalendar::setDateTime example
  • Example#2416 - IntlCalendar::setFirstDayOfWeek
  • Example#2417 - IntlCalendar::setTime
  • Example#2418 - IntlCalendar::setTimeZone
  • Example#2419 - IntlCalendar::toDateTime
  • Example#2420 - Ejemplo de datefmt_create
  • Example#2421 - Ejemplo orientado a objetos
  • Example#2422 - Ejemplo de datefmt_format
  • Example#2423 - Ejemplo orientado a objetos
  • Example#2424 - Con un objeto IntlCalendar
  • Example#2425 - Ejemplos de IntlDateFormatter::formatObject
  • Example#2426 - Ejemlo de datefmt_get_calendar
  • Example#2427 - Ejemplo orientado a objetos
  • Example#2428 - Ejemlo de datefmt_get_datetype
  • Example#2429 - Ejemplo orientado a objetos
  • Example#2430 - Ejemplo de datefmt_get_error_code
  • Example#2431 - Ejemplo orientado a objetos
  • Example#2432 - Ejemplo de datefmt_get_error_message
  • Example#2433 - Ejemplo orientado a objetos
  • Example#2434 - Ejemplo de datefmt_get_locale
  • Example#2435 - Ejemplo orientado a objetos
  • Example#2436 - Ejemplo de datefmt_get_pattern
  • Example#2437 - Ejemplo orientado a objetos
  • Example#2438 - Ejemplo de datefmt_get_timetype
  • Example#2439 - Ejemplo orientado a objetos
  • Example#2440 - Ejemplo de datefmt_get_timezone_id
  • Example#2441 - Ejemplo orientado a objetos
  • Example#2442 - Ejemplo IntlDateFormatter::getCalendarObject
  • Example#2443 - Ejemplos de IntlDateFormatter::getTimeZone
  • Example#2444 - Ejmplo de datefmt_is_lenient
  • Example#2445 - Ejemplo orientado a objetos
  • Example#2446 - Ejemplo de datefmt_localtime
  • Example#2447 - Ejemplo orientado a objetos
  • Example#2448 - Ejemplo orientado a objetos
  • Example#2449 - Ejemplo de datefmt_parse
  • Example#2450 - Ejemplo de datefmt_set_calendar
  • Example#2451 - Ejemplo orientado a objetos
  • Example#2452 - Ejemplo con el argumento IntlCalendar
  • Example#2453 - Ejemplo de datefmt_set_lenient
  • Example#2454 - Ejemplo orientado a objetos
  • Example#2455 - Ejemplo de datefmt_set_pattern
  • Example#2456 - Ejemplo orientado a objetos
  • Example#2457 - Ejemplos de IntlDateFormatter::setTimeZone
  • Example#2458 - Ejemplo de resourcebundle_count
  • Example#2459 - Ejemplo orientado a objetos
  • Example#2460 - Ejemplo de resourcebundle_create
  • Example#2461 - Ejemplo de ResourceBundle::create
  • Example#2462 - Ejemplo de resourcebundle_get_error_code
  • Example#2463 - Ejemplo orientado a objetos
  • Example#2464 - Ejemplo de resourcebundle_get_error_message
  • Example#2465 - Ejemplo orientado a objetos
  • Example#2466 - Ejemplo de resourcebundle_get
  • Example#2467 - Ejemplo orientado a objetos
  • Example#2468 - Ejemplo de resourcebundle_locales
  • Example#2469 - Ejemplo orientado a objetos
  • Example#2470 - Converting escaped UTF-16 code units
  • Example#2471 - Ejemplo de grapheme_extract
  • Example#2472 - Ejemplo de grapheme_stripos
  • Example#2473 - Ejemplo de grapheme_stristr
  • Example#2474 - Ejemplo de grapheme_strlen
  • Example#2475 - Ejemplo de grapheme_strpos
  • Example#2476 - Ejemplo de grapheme_strripos
  • Example#2477 - Ejemplo de grapheme_strrpos
  • Example#2478 - Ejemplo de grapheme_strstr
  • Example#2479 - Ejemplo de grapheme_substr
  • Example#2480 - Ejemplo de idn_to_ascii
  • Example#2481 - Ejemplo de idn_to_utf8
  • Example#2482 - Probar diferentes puntos de código
  • Example#2483 - Probar diferentes puntos de código
  • Example#2484 - Probar diferentes puntos de código
  • Example#2485 - Probar diferentes puntos de código
  • Example#2486 - Probar diferentes puntos de código
  • Example#2487 - Probar diferentes puntos de código
  • Example#2488 - Probar diferentes puntos de código
  • Example#2489 - Probar diferentes puntos de código
  • Example#2490 - Probar diferentes puntos de código
  • Example#2491 - Enumeración de un rango de muestra de puntos de código
  • Example#2492 - Enumeración de un rango de muestra de puntos de código
  • Example#2493 - Probar diferentes puntos de código
  • Example#2494 - Probar diferentes puntos de código
  • Example#2495 - Probar diferentes puntos de código
  • Example#2496 - Probar diferentes puntos de código
  • Example#2497 - Probar diferentes puntos de código
  • Example#2498 - Probar diferentes propiedades
  • Example#2499 - Probar diferentes propiedades
  • Example#2500 - Probar diferentes propiedades
  • Example#2501 - Probar diferentes puntos de código
  • Example#2502 - Probar diferentes propiedades
  • Example#2503 - Probar diferentes propiedades
  • Example#2504 - Probar diferentes propiedades
  • Example#2505 - Probar diferentes propiedades
  • Example#2506 - Probar diferentes propiedades
  • Example#2507 - Probar diferentes propiedades
  • Example#2508 - Probar diferentes puntos de código
  • Example#2509 - Probar diferentes puntos de código
  • Example#2510 - Probar diferentes puntos de código
  • Example#2511 - Probar diferentes puntos de código
  • Example#2512 - Probar diferentes puntos de código
  • Example#2513 - Probar diferentes puntos de código
  • Example#2514 - Probar diferentes puntos de código
  • Example#2515 - Probar diferentes puntos de código
  • Example#2516 - Probar diferentes puntos de código
  • Example#2517 - Probar diferentes puntos de código
  • Example#2518 - Probar diferentes puntos de código
  • Example#2519 - Probar diferentes puntos de código
  • Example#2520 - Probar diferentes puntos de código
  • Example#2521 - Probar diferentes puntos de código
  • Example#2522 - Probar diferentes puntos de código
  • Example#2523 - Probar diferentes puntos de código
  • Example#2524 - Probar diferentes puntos de código
  • Example#2525 - Probar diferentes puntos de código
  • Example#2526 - Probar diferentes puntos de código
  • Example#2527 - Probar diferentes puntos de código
  • Example#2528 - Probar diferentes puntos de código
  • Example#2529 - Probar diferentes puntos de código
  • Example#2530 - Probar diferentes puntos de código
  • Example#2531 - Probar diferentes puntos de código
  • Example#2532 - Probar diferentes puntos de código
  • Example#2533 - Probar diferentes puntos de código
  • Example#2534 - Probar diferentes puntos de código
  • Example#2535 - Probar diferentes puntos de código
  • Example#2536 - Probar diferentes puntos de código
  • Example#2537 - Probar diferentes puntos de código
  • Example#2538 - Probar diferentes puntos de código
  • Example#2539 - Probar diferentes puntos de código
  • Example#2540 - intl_error_name ejemplo
  • Example#2541 - intl_get_error_code ejemplo
  • Example#2542 - intl_get_error_message ejemplo
  • Example#2543 - intl_is_failure ejemplo
  • Example#2544 - Ejemplos de ajustes de php.ini
  • Example#2545 - Ajustes de php.ini para usuarios de EUC-JP
  • Example#2546 - Ajustes de php.ini para usuarios de SJIS
  • Example#2547 - Desactivar la conversión de caracteres de la entrada HTTP en php.ini
  • Example#2548 - Ejemplo de configuración de php.ini
  • Example#2549 - Ejemplo de script
  • Example#2550 - Probar diferentes puntos de código
  • Example#2551 - Ejemplo de mb_convert_case
  • Example#2552 - Ejemplo de mb_convert_case con texto no latino en UTF-8
  • Example#2553 - Ejemplo de mb_convert_encoding
  • Example#2554 - Ejemplo de mb_convert_kana
  • Example#2555 - Ejemplo de mb_convert_variables
  • Example#2556 - Ejemplo de convmap
  • Example#2557 - Ejemplo de convmap escapando cadenas de JavaScript
  • Example#2558 - Ejemplo de mb_detect_encoding
  • Example#2559 - Ejemplo de mb_detect_order
  • Example#2560 - Ejemplo mostrando un orden de detección inútil
  • Example#2561 - Ejemplo de mb_encode_mimeheader
  • Example#2562 - Ejemplo de convmap
  • Example#2563 - Ejemplo de mb_encode_numericentity
  • Example#2564 - Ejemplo de mb_encoding_aliases
  • Example#2565 - Ejemplo de mb_ereg_replace_callback
  • Example#2566 - mb_ereg_replace_callback usando una función anónima admitida en PHP 5.3.0 o posterior
  • Example#2567 - Ejemplo de mb_internal_encoding
  • Example#2568 - Ejemplo de mb_list_encodings
  • Example#2569 -
  • Example#2570 - Ejemplo de mb_output_handler
  • Example#2571 - Ejemplo de mb_preferred_mime_name
  • Example#2572 - mb_str_pad example
  • Example#2573 - Ejemplo de mb_strimwidth
  • Example#2574 - Ejemplo de mb_strtolower
  • Example#2575 - Ejemplo de mb_strtolower con texto no latino
  • Example#2576 - Ejemplo de mb_strtoupper
  • Example#2577 - Ejemplo de mb_strtoupper con texto UTF-8 no latino
  • Example#2578 - Ejemplo de mb_substitute_character
  • Example#2579 - Ejemplo de mb_substr_count
  • Example#2580 - pspell_add_to_personal
  • Example#2581 - Ejemplo de pspell_check
  • Example#2582 - Ejemplo de pspell_add_to_personal
  • Example#2583 - pspell_config_create
  • Example#2584 - pspell_config_ignore
  • Example#2585 - Ejemplo de pspell_config_mode
  • Example#2586 - pspell_config_personal
  • Example#2587 - pspell_config_repl
  • Example#2588 - pspell_config_runtogether
  • Example#2589 - pspell_new_config
  • Example#2590 - pspell_new_personal
  • Example#2591 - pspell_new
  • Example#2592 - pspell_add_to_personal
  • Example#2593 - pspell_store_replacement
  • Example#2594 - Ejemplo de pspell_suggest
  • Example#2595 - Ejemplo básico de recode_file
  • Example#2596 - Ejemplo básico de recode_string
  • Example#2597 - Ejemplo de exif_imagetype
  • Example#2598 - Ejemplo de exif_read_data
  • Example#2599 - Ejemplo exif_tagname
  • Example#2600 - Ejemplo de exif_thumbnail
  • Example#2601 - Creación de un PNG con PHP
  • Example#2602 - Añadir marcas de agua a imágenes usando canales alfa
  • Example#2603 - Usar imagecopymerge para crear una marca de agua translúcida
  • Example#2604 - Empleo de gd_info
  • Example#2605 - getimagesize y tipos MIME
  • Example#2606 - Ejemplo degetimagesize
  • Example#2607 - getimagesize (URL)
  • Example#2608 - getimagesize() devolviendo IPTC
  • Example#2609 - Ejemplo de getimagesizefromstring
  • Example#2610 - Ejemplo de image_type_to_extension
  • Example#2611 - Ejemplo de image_type_to_mime_type
  • Example#2612 - Ejemplo de image2wbmp
  • Example#2613 - Ejemplo de uso de imagealphablending
  • Example#2614 - Una comparación de dos líneas, una con antialias activado
  • Example#2615 - Dibujar un círculo con imagearc
  • Example#2616 - Saving a BMP file
  • Example#2617 - Ejemplo de imagechar
  • Example#2618 - Ejemplo de imagecharup
  • Example#2619 - Ejemplo de imagecolorallocate
  • Example#2620 - Ejemplo usando imagecolorallocatealpha
  • Example#2621 - Acceder a los distintos valores RGB
  • Example#2622 - Valores RGB legibles para humanos usando imagecolorsforindex
  • Example#2623 - Buscar un conjunto de colores en una imagen
  • Example#2624 - Buscar un conjunto de colores en una imagen
  • Example#2625 - Ejemplo usando imagecolorclosesthwb
  • Example#2626 - Usar imagecolordeallocate
  • Example#2627 - Obtener colores del logotipo de GD
  • Example#2628 - Obtener colores del logotipo de GD
  • Example#2629 - Ejemplo de imagecolormatch
  • Example#2630 - Usar imagecoloresolve para obtener colores de una imagen
  • Example#2631 - Usar imagecoloresolvealpha para obtener colores de una imagen
  • Example#2632 - Ejemplo de imagecolorset
  • Example#2633 - Ejemplo de imagecolorsforindex
  • Example#2634 - Obtener el número total de colores de una imagen usando imagecolorstotal
  • Example#2635 - Ejemplo de imagecolortransparent
  • Example#2636 - Poner en relieve el logotipo de PHP.net
  • Example#2637 - Borrosidad gaussiana
  • Example#2638 - Recortar el logotipo de PHP.net
  • Example#2639 - Fusionar dos copias del logotipo de PHP.net con 75% de transparencia
  • Example#2640 - Uso de imagecopymergegray
  • Example#2641 - Ejemplo sencillo
  • Example#2642 - Redimensionar una imagen proporcionalmente
  • Example#2643 - Cambiar el tamaño de una imagen
  • Example#2644 - Crear un nuevo flujo de imagen GD e imprimir una imagen.
  • Example#2645 - Convert an BMP image to a PNG image using imagecreatefrombmp
  • Example#2646 - Ejemplo de imagecreatefromgd2
  • Example#2647 - Ejemplo de imagecreatefromgd2part
  • Example#2648 - Ejemplo de imagecreatefromgd
  • Example#2649 - Ejemplo de manejar un error durante la carga de un GIF
  • Example#2650 - Ejemplo de manejar un error durante la carga de un JPEG
  • Example#2651 - Ejemplo de manejar un error durante la carga de un PNG
  • Example#2652 - Ejemplo de imagecreatefromstring
  • Example#2653 - Ejemplo de manejar un error durante la carga de un WBMP
  • Example#2654 - Convertir una image WebP a una imagen jpeg usando imagecreatefromwebp
  • Example#2655 - Convertir una imagen XBM en una imagen png usando imagecreatefromxbm
  • Example#2656 - Crear una instancia de imagen usando imagecreatefromxpm
  • Example#2657 - Crear un nuevo flujo a una imagen GD e imprimir una imagen.
  • Example#2658 - Ejemplo de imagedashedline
  • Example#2659 - Alternativa a imagedashedline
  • Example#2660 - Ejemplo de uso de imagedestroy
  • Example#2661 - Ejemplo de imageellipse
  • Example#2662 - Ejemplo de imagefill
  • Example#2663 - Crear una gráfico de tarta en 3D
  • Example#2664 - Ejemplo de imagefilledellipse
  • Example#2665 - Ejemplo de imagefilledpolygon
  • Example#2666 - Uso de imagefilledrectangle
  • Example#2667 - Rellenar una elipse con un color
  • Example#2668 - Ejemplo de escala de grises con imagefilter
  • Example#2669 - Ejemplo de brillo con imagefilter
  • Example#2670 - Ejemplo de coloración con imagefilter
  • Example#2671 - Ejemplo de inversión de color con imagefilter
  • Example#2672 - Ejemplo de pixelación con imagefilter
  • Example#2673 - Voltea una imagen verticalmente
  • Example#2674 - Voltea la imagen horizontalmente
  • Example#2675 - Usar imagefontheight con fuentes incorporadas
  • Example#2676 - Usar imagefontheight junto con imageloadfont
  • Example#2677 - Usar imagefontwidth con fuentes incorporadas
  • Example#2678 - Usar imagefontwidth junto con imageloadfont
  • Example#2679 - Ejemplo de imageftbbox
  • Example#2680 - Ejemplo de imagefttext
  • Example#2681 - Uso de imagegammacorrect
  • Example#2682 - Imprimir una imagen GD2
  • Example#2683 - Guardar una imagen GD2
  • Example#2684 - Imprimir una imagen GD
  • Example#2685 - Saving a GD image
  • Example#2686 - imagegetclip example
  • Example#2687 - Imprimir una imagen usando imagegif
  • Example#2688 - Convertir una imagen PNG en GIF usando imagegif
  • Example#2689 - Ejemplo de imagegrabscreen
  • Example#2690 - Ejemplo de imagegrabwindow
  • Example#2691 - Activar el entrelazamiento usando imageinterlace
  • Example#2692 - Simple detección de instancias de imagen de color verdadero usando imageistruecolor
  • Example#2693 - Imprimir una imagen JPEG
  • Example#2694 - Guardar una imagen JPEG
  • Example#2695 - Imprimir la imagen al 75% de calidad
  • Example#2696 - Ejemplo de imagelayereffect
  • Example#2697 - Dibujar una línea gruesa
  • Example#2698 - Ejemplo de uso de imageloadfont
  • Example#2699 - imageopenpolygon example
  • Example#2700 - Ejemplo de imagepalettecopy
  • Example#2701 - Convertir cualquier recurso de imagaen a color verdadero
  • Example#2702 - Ejemplo de imagepolygon
  • Example#2703 - Ejemplo sencillo de imagerectangle
  • Example#2704 - Setting and getting the resolution of an image
  • Example#2705 - Rotar una imagen 180 grados
  • Example#2706 - Ejemplo de imagesavealpha
  • Example#2707 - Ejemplo de imagesetbrush
  • Example#2708 - Ejemplo de imagesetinterpolation
  • Example#2709 - Ejemplo de imagesetpixel
  • Example#2710 - Ejemplo de imagesetstyle
  • Example#2711 - Ejemplo de imagesetthickness
  • Example#2712 - Ejemplo de imagesettile
  • Example#2713 - Ejemplo de imagestring
  • Example#2714 - Ejemplo de imagestringup
  • Example#2715 - Usar imagesx
  • Example#2716 - Usar imagesy
  • Example#2717 - Convertir una imagen de color verdadero en una imagen de paleta
  • Example#2718 - Ejemplo de imagettfbbox
  • Example#2719 - Ejemplo de imagettftext
  • Example#2720 - Comprobar el soporte para PNG
  • Example#2721 - Imprimir una imagen WBMP
  • Example#2722 - Guardar una imagen WBMP
  • Example#2723 - Imprimir la imagen con un primer plano diferente
  • Example#2724 - Guardar un fichero WebP
  • Example#2725 - Guardar un fichero XBM
  • Example#2726 - Guardar un fichero XBM con un color de primer plano diferente
  • Example#2727 - Incluir información IPTC a un JPEG
  • Example#2728 - iptcparse() usado junto con getimagesize
  • Example#2729 - Ejemplo de jpeg2wbmp
  • Example#2730 - Ejmplo de png2wbmp
  • Example#2731 - Ejemplo de Gmagick
  • Example#2732 - Ejemplo de Gmagick::despeckleimage
  • Example#2733 - Gmagick::setCompressionQuality
  • Example#2734 - Crear una miniatura con Imagick
  • Example#2735 - Hacer una miniatura de todos los archivos JPG de un directorio
  • Example#2736 - Crear un reflejo de una imagen
  • Example#2737 - Rellenar un texto con un gradiente
  • Example#2738 - Leer una imágen GIF y redimensionar todos los fotogramas
  • Example#2739 - Crear un logo de PHP
  • Example#2740 - Usar Imagick::adaptiveBlurImage:
  • Example#2741 - Usar Imagick::adaptiveResizeImage
  • Example#2742 - Un ejemplo de Imagick::adaptiveSharpenImage
  • Example#2743 - Imagick::adaptiveThresholdImage
  • Example#2744 - Imagick::addNoiseImage
  • Example#2745 - Imagick::affineTransformImage
  • Example#2746 - Usar Imagick::annotateImage:
  • Example#2747 - Ejemplo de Imagick::appendImages
  • Example#2748 - Imagick::autoLevelImage
  • Example#2749 - Imagick::blackThresholdImage
  • Example#2750 - Imagick::blueShiftImage
  • Example#2751 - Usar Imagick::blurImage:
  • Example#2752 - Imagick::borderImage
  • Example#2753 - Imagick::brightnessContrastImage
  • Example#2754 - Imagick::charcoalImage
  • Example#2755 - Usar Imagick::chopImage:
  • Example#2756 - Clonación de un objeto Imagick en diferentes versiones de imagick
  • Example#2757 - Usar Imagick::clutImage:
  • Example#2758 - Imagick::colorizeImage
  • Example#2759 - Imagick::colorMatrixImage
  • Example#2760 - Usar Imagick::commentImage:
  • Example#2761 - Usar Imagick::compareImageLayers
  • Example#2762 - Uso de Imagick::compareImages:
  • Example#2763 - Empleo de Imagick::compositeImage:
  • Example#2764 - Imagick::contrastImage
  • Example#2765 - Imagick::convolveImage
  • Example#2766 - Imagick::cropImage
  • Example#2767 - Imagick::deskewImage
  • Example#2768 - Imagick::despeckleImage
  • Example#2769 - Usar Imagick::distortImage:
  • Example#2770 - Imagick::edgeImage
  • Example#2771 - Imagick::embossImage
  • Example#2772 - Imagick::enhanceImage
  • Example#2773 - Imagick::equalizeImage
  • Example#2774 - Usando Imagick::evaluateImage
  • Example#2775 - Usar Imagick::exportImagePixels
  • Example#2776 - Imagick::filter
  • Example#2777 - Imagick::flipImage
  • Example#2778 - Ejemplo de Imagick::floodfillPaintImage
  • Example#2779 - Imagick::flopImage
  • Example#2780 - Imagick::forwardFourierTransformImage
  • Example#2781 - Imagick::frameImage
  • Example#2782 - Crear un degradado sinusoide
  • Example#2783 - Crear un degradado desde el polinomio (4x^2 - 4x + 1)
  • Example#2784 - Crear un degradao complejo a partir del polinomio (4x^2 - 4x^2 + 1) modulado por un degradao sinusoide
  • Example#2785 - Imagick::fxImage
  • Example#2786 - Imagick::gammaImage
  • Example#2787 - Imagick::gaussianBlurImage
  • Example#2788 - Imagick::getImageGeometry
  • Example#2789 - Generates Imagick::getImageHistogram
  • Example#2790 - Usar Imagick::getImageLength:
  • Example#2791 - Usar Imagick::getImageProperties:
  • Example#2792 - Usando Imagick::getImageProperty:
  • Example#2793 - Usar Imagick::getIteratorIndex:
  • Example#2794 - Imagick::getPixelIterator
  • Example#2795 - Ejemplo de Imagick::getPixelRegionIterator
  • Example#2796 - Imagick::haldClutImage
  • Example#2797 - Imagick::identifyFormat
  • Example#2798 - Ejemplo de formato resultante
  • Example#2799 - Imagick::implodeImage
  • Example#2800 - Ejemplo deImagick::importImagePixels
  • Example#2801 - Imagick::levelImage
  • Example#2802 - Imagick::linearStretchImage
  • Example#2803 - Imagick::magnifyImage
  • Example#2804 - Imagick::medianFilterImage
  • Example#2805 - Imagick::mergeImageLayers
  • Example#2806 - Imagick::modulateImage
  • Example#2807 - Convolve Imagick::morphology
  • Example#2808 - Correlate Imagick::morphology
  • Example#2809 - Erode Imagick::morphology
  • Example#2810 - Erode Intensity Imagick::morphology
  • Example#2811 - Dilate Imagick::morphology
  • Example#2812 - Dilate intensity Imagick::morphology
  • Example#2813 - Distance with Chebyshev kernel Imagick::morphology
  • Example#2814 - Distance with Manhattan kernel Imagick::morphology
  • Example#2815 - Distance with ocatagonal kernel Imagick::morphology
  • Example#2816 - Distance with Euclidean kernel Imagick::morphology
  • Example#2817 - Edge Imagick::morphology
  • Example#2818 - Open Imagick::morphology
  • Example#2819 - Open intensity Imagick::morphology
  • Example#2820 - Close Imagick::morphology
  • Example#2821 - Close Intensity Imagick::morphology
  • Example#2822 - Smooth Imagick::morphology
  • Example#2823 - Edge in Imagick::morphology
  • Example#2824 - Edge out Imagick::morphology
  • Example#2825 - 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#2826 - 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#2827 - Hit and Miss Imagick::morphology
  • Example#2828 - Thinning Imagick::morphology
  • Example#2829 - Thicken Imagick::morphology
  • Example#2830 - Thick to generate a convex hull Imagick::morphology
  • Example#2831 - Iterative morphology Imagick::morphology
  • Example#2832 - Helper function to get an image silhouette Imagick::morphology
  • Example#2833 - Imagick::motionBlurImage
  • Example#2834 - Imagick::negateImage
  • Example#2835 - Usar Imagick::newImage:
  • Example#2836 - Imagick::newPseudoImage
  • Example#2837 - Imagick::normalizeImage
  • Example#2838 - Imagick::oilPaintImage
  • Example#2839 - Usar Imagick::optimizeImageLayers
  • Example#2840 - Imagick::orderedPosterizeImage
  • Example#2841 - Usar Imagick::pingImageBlob
  • Example#2842 - Usar Imagick::pingImageFile
  • Example#2843 - Un ejemplo de Imagick::polaroidImage
  • Example#2844 - Imagick::posterizeImage
  • Example#2845 - Imagick::quantizeImage
  • Example#2846 - Usar Imagick::queryFontMetrics:
  • Example#2847 - Imagick::queryFonts
  • Example#2848 - Imagick::queryFormats
  • Example#2849 - Imagick::radialBlurImage
  • Example#2850 - Imagick::raiseImage
  • Example#2851 - Imagick::randomThresholdImage
  • Example#2852 - Imagick::readImageBlob
  • Example#2853 - Imagick::recolorImage
  • Example#2854 - Imagick::reduceNoiseImage
  • Example#2855 - Imagick::resampleImage
  • Example#2856 - Imagick::resizeImage
  • Example#2857 - Imagick::rollImage
  • Example#2858 - Imagick::rotateImage
  • Example#2859 - Imagick::rotationalBlurImage
  • Example#2860 - Usar Imagick::roundCorners:
  • Example#2861 - Imagick::scaleImage
  • Example#2862 - Imagick::segmentImage
  • Example#2863 - Imagick::selectiveBlurImage
  • Example#2864 - Imagick::separateImageChannel
  • Example#2865 - Imagick::sepiaToneImage
  • Example#2866 - Imagick::setCompressionQuality
  • Example#2867 - Un ejemplo de Imagick::setFont
  • Example#2868 - Un ejemplo de Imagick::setImage
  • Example#2869 - Imagick::setImageArtifact
  • Example#2870 - Imagick::setImageBias
  • Example#2871 - Imagick::setImageClipMask
  • Example#2872 - Imagick::setImageCompressionQuality
  • Example#2873 - Modificar un GIF animado con Imagick::setImageDelay
  • Example#2874 - Uso básido ce Imagick::setImageIterations
  • Example#2875 - Un ejemplo de Imagick::setImageOpacity
  • Example#2876 - Imagick::setImageOrientation
  • Example#2877 - Usar Imagick::setImageProperty:
  • Example#2878 - Imagick::setImageResolution
  • Example#2879 - Modificar un GIF animado con Imagick::setImageTicksPerSecond
  • Example#2880 - Usar Imagick::setIteratorIndex:
  • Example#2881 - Attempt to reach '$extent' sizeImagick::setOption
  • Example#2882 - Imagick::setOption
  • Example#2883 - Imagick::setOption
  • Example#2884 - Un ejemplo de Imagick::setPointSize
  • Example#2885 - Imagick::setProgressMonitor
  • Example#2886 - Imagick::setSamplingFactors
  • Example#2887 - Imagick::shadeImage
  • Example#2888 - Imagick::shadowImage
  • Example#2889 - Imagick::sharpenImage
  • Example#2890 - Imagick::shaveImage
  • Example#2891 - Imagick::shearImage
  • Example#2892 - 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#2893 - Imagick::sketchImage
  • Example#2894 - Imagick::smushImages
  • Example#2895 - Imagick::solarizeImage
  • Example#2896 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#2897 - SPARSECOLORMETHOD_BILINEAR Imagick::sparseColorImage
  • Example#2898 - SPARSECOLORMETHOD_SPEPARDS Imagick::sparseColorImage
  • Example#2899 - SPARSECOLORMETHOD_VORONOI Imagick::sparseColorImage
  • Example#2900 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#2901 - createGradientImage is used by other examples. Imagick::sparseColorImage
  • Example#2902 - Imagick::spliceImage
  • Example#2903 - Imagick::spreadImage
  • Example#2904 - Imagick::statisticImage
  • Example#2905 - Imagick::subImageMatch
  • Example#2906 - Imagick::swirlImage
  • Example#2907 - Imagick::textureImage
  • Example#2908 - Imagick::thresholdImage
  • Example#2909 - Imagick::thumbnailImage
  • Example#2910 - Imagick::tintImage
  • Example#2911 - Usar Imagick::transformImage:
  • Example#2912 - Ejemplo de Imagick::transformImageColorspace
  • Example#2913 - Imagick::transformImageColorspace
  • Example#2914 - Imagick::transparentPaintImage
  • Example#2915 - Imagick::transposeImage
  • Example#2916 - Imagick::transverseImage
  • Example#2917 - Usar Imagick::trimImage:
  • Example#2918 - Imagick::uniqueImageColors
  • Example#2919 - Imagick::unsharpMaskImage
  • Example#2920 - Imagick::vignetteImage
  • Example#2921 - WaveImage can be quite slow Imagick::waveImage
  • Example#2922 - Imagick::whiteThresholdImage
  • Example#2923 - Ejemplo de ImagickDraw::affine
  • Example#2924 - Ejemplo de ImagickDraw::arc
  • Example#2925 - Ejemplo de ImagickDraw::bezier
  • Example#2926 - Ejemplo de ImagickDraw::circle
  • Example#2927 - ImagickDraw::composite
  • Example#2928 - Ejemplo de ImagickDraw::ellipse
  • Example#2929 - Ejemplo de ImagickDraw::line
  • Example#2930 - ImagickDraw::matte
  • Example#2931 - Ejemplo de ImagickDraw::pathCurveToQuadraticBezierAbsolute
  • Example#2932 - Ejemplo de ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
  • Example#2933 - Ejemplo de ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
  • Example#2934 - Ejemplo de ImagickDraw::pathStart
  • Example#2935 - Ejemplo de ImagickDraw::point
  • Example#2936 - Ejemplo de ImagickDraw::polygon
  • Example#2937 - Ejemplo de ImagickDraw::polyline
  • Example#2938 - Ejemplo de ImagickDraw::popDefs
  • Example#2939 - Ejemplo de ImagickDraw::push
  • Example#2940 - Ejemplo de ImagickDraw::pushPattern
  • Example#2941 - Ejemplo de ImagickDraw::rectangle
  • Example#2942 - Ejemplo de ImagickDraw::rotate
  • Example#2943 - Ejemplo de ImagickDraw::roundRectangle
  • Example#2944 - Ejemplo de ImagickDraw::scale
  • Example#2945 - Ejemplo de ImagickDraw::setClipPath
  • Example#2946 - ImagickDraw::setClipRule
  • Example#2947 - Ejemplo de ImagickDraw::setClipUnits
  • Example#2948 - Ejemplo de ImagickDraw::setFillAlpha
  • Example#2949 - ImagickDraw::setFillColor
  • Example#2950 - ImagickDraw::setFillOpacity
  • Example#2951 - ImagickDraw::setFillRule
  • Example#2952 - Ejemplo de ImagickDraw::setFont
  • Example#2953 - Ejemplo de ImagickDraw::setFontFamily
  • Example#2954 - Ejemplo de ImagickDraw::setFontSize
  • Example#2955 - ImagickDraw::setFontStretch
  • Example#2956 - ImagickDraw::setFontStyle
  • Example#2957 - Ejemplo de ImagickDraw::setFontWeight
  • Example#2958 - ImagickDraw::setGravity
  • Example#2959 - Ejemplo de ImagickDraw::setStrokeAlpha
  • Example#2960 - Ejemplo de ImagickDraw::setStrokeAntialias
  • Example#2961 - Ejemplo de ImagickDraw::setStrokeColor
  • Example#2962 - Ejemplo de ImagickDraw::setStrokeDashArray
  • Example#2963 - Ejemplo de ImagickDraw::setStrokeDashOffset
  • Example#2964 - ImagickDraw::setStrokeLineCap
  • Example#2965 - ImagickDraw::setStrokeLineJoin
  • Example#2966 - Ejemplo de ImagickDraw::setStrokeMiterLimit
  • Example#2967 - Ejemplo de ImagickDraw::setStrokeOpacity
  • Example#2968 - Ejemplo de ImagickDraw::setStrokeWidth
  • Example#2969 - ImagickDraw::setTextAlignment
  • Example#2970 - Ejemplo de ImagickDraw::setTextAntialias
  • Example#2971 - ImagickDraw::setTextDecoration
  • Example#2972 - Ejemplo de ImagickDraw::setTextUnderColor
  • Example#2973 - Ejemplo de ImagickDraw::setVectorGraphics
  • Example#2974 - Ejemplo de ImagickDraw::setViewBox
  • Example#2975 - Ejemplo de ImagickDraw::skewX
  • Example#2976 - Ejemplo de ImagickDraw::skewY
  • Example#2977 - Ejemplo de ImagickDraw::translate
  • Example#2978 - ImagickPixel::construct
  • Example#2979 - Uso básico de Imagick::getColor
  • Example#2980 - Uso básico de Imagick::getColorAsString
  • Example#2981 - getColorCount de ImagickPixel
  • Example#2982 - Uso básico de Imagick::getColorValue
  • Example#2983 - ImagickPixel::getColorValueQuantum
  • Example#2984 - Uso básico de Imagick::getHSL
  • Example#2985 - ImagickPixel::isSimilar
  • Example#2986 - ImagickPixel::setColor
  • Example#2987 - Uso básico de Imagick::setColorValue
  • Example#2988 - ImagickPixel::setColorValueQuantum
  • Example#2989 - Usar ImagickPixel::setHSL para modificar un color
  • Example#2990 - ImagickPixelIterator::clear
  • Example#2991 - ImagickPixelIterator::construct
  • Example#2992 - ImagickPixelIterator::getNextIteratorRow
  • Example#2993 - ImagickPixelIterator::resetIterator
  • Example#2994 - ImagickPixelIterator::setIteratorRow
  • Example#2995 - ImagickKernel::addKernel
  • Example#2996 - ImagickKernel::addUnityKernel
  • Example#2997 - ImagickKernel::addUnityKernel
  • Example#2998 - ImagickKernel::fromBuiltin
  • Example#2999 - ImagickKernel::fromMatrix
  • Example#3000 - ImagickKernel::getMatrix
  • Example#3001 - ImagickKernel::scale
  • Example#3002 - ImagickKernel::separate
  • Example#3003 - Ejemplo de imap_append
  • Example#3004 - Ejemplo de imap_check
  • Example#3005 - Ejemplo de imap_createmailbox
  • Example#3006 - Ejemplo de imap_delete
  • Example#3007 - Ejemplo de imap_fetch_overview
  • Example#3008 - Ejemplo de imap_gc
  • Example#3009 - Ejemplo de imap_get_quota
  • Example#3010 - Ejemplo de imap_get_quota 4.3 o superiro
  • Example#3011 - Ejemplo de imap_get_quotaroot
  • Example#3012 - Ejemplo de imap_getacl
  • Example#3013 - Ejemplo de imap_getmailboxes
  • Example#3014 - imap_is_open example
  • Example#3015 - Ejemplo de imap_list
  • Example#3016 - Ejemplo de imap_mail_compose
  • Example#3017 - Ejemplo de imap_mailboxmsginfo
  • Example#3018 - Ejemplo de imap_mime_header_decode
  • Example#3019 - Diferentes usos de imap_open
  • Example#3020 - Ejemplo de imap_open
  • Example#3021 - Ejemplo de imap_ping
  • Example#3022 - Ejemplo de imap_reopen
  • Example#3023 - Ejemplo de imap_rfc822_parse_adrlist
  • Example#3024 - Ejemplo de imap_rfc822_write_address
  • Example#3025 - imap_search example
  • Example#3026 - Ejemplo de imap_set_quota
  • Example#3027 - Ejemplo de imap_setflag_full
  • Example#3028 - Ejemplo de imap_status
  • Example#3029 - Ejemplo de imap_thread
  • Example#3030 - Ejemplo de imap_timeout
  • Example#3031 - Calcular el hash de un usuario suscriptor.
  • Example#3032 - Enviar un correo.
  • Example#3033 - Enviar un correo con cabeceras extra.
  • Example#3034 - Enviar un correo con parámetros de línea de comando adicionales.
  • Example#3035 - Envío de un correo HTML
  • Example#3036 - Ejemplo de mailparse_determine_best_xfer_encoding
  • Example#3037 - Ejemplo de mailparse_rfc822_parse_addresses
  • Example#3038 - Ejemplo de mailparse_stream_encode
  • Example#3039 - Ejemplo de mailparse_uudecode_all
  • Example#3040 - Ejemplo bcadd
  • Example#3041 - Ejemplobccomp
  • Example#3042 - Ejemplo bcdiv
  • Example#3043 - Ejemplo bcmod
  • Example#3044 - Ejemplo bcmul
  • Example#3045 - Ejemplo bcpow
  • Example#3046 - Ejemplo de escalado de bcpow
  • Example#3047 - Ejemplo bcscale
  • Example#3048 - Ejemplo bcsqrt
  • Example#3049 - Ejemplo bcsub
  • Example#3050 - Función factorial usando GMP
  • Example#3051 - Ejemplo de gmp_abs
  • Example#3052 - Ejemplo de gmp_add
  • Example#3053 - Ejemplo de gmp_and
  • Example#3054 - Ejemplo de gmp_clrbit
  • Example#3055 - gmp_cmp example
  • Example#3056 - Ejemplo de gmp_com
  • Example#3057 - Ejemplo de gmp_div_q
  • Example#3058 - División de números GMP
  • Example#3059 - gmp_div_r example
  • Example#3060 - Ejemplo degmp_divexact
  • Example#3061 - Ejemplo de gmp_export
  • Example#3062 - Ejemplo degmp_fact
  • Example#3063 - Ejemplo degmp_gcd
  • Example#3064 - Resolver ecuaciones de diofántica lineal
  • Example#3065 - Ejemplo degmp_hamdist
  • Example#3066 - Ejemplo de gmp_import
  • Example#3067 - Creación de un número GMP
  • Example#3068 - Ejemplo de gmp_intval
  • Example#3069 - Ejemplo de gmp_invert
  • Example#3070 - Ejemplo de gmp_jacobi
  • Example#3071 - Ejemplo de gmp_legendre
  • Example#3072 - Ejemplo de gmp_mod
  • Example#3073 - Ejemplo degmp_mul
  • Example#3074 - Ejemplo degmp_neg
  • Example#3075 - Ejemplo de gmp_nextprime
  • Example#3076 - Ejemplo de gmp_or
  • Example#3077 - Ejemplo de gmp_perfect_square
  • Example#3078 - Ejemplo de gmp_popcount
  • Example#3079 - Ejemplo de gmp_pow
  • Example#3080 - gmp_powm example
  • Example#3081 - Ejemplo de gmp_prob_prime
  • Example#3082 - gmp_random_bits example
  • Example#3083 - gmp_random_range example
  • Example#3084 - Ejemplo de gmp_random_seed
  • Example#3085 - Ejemplo de gmp_random
  • Example#3086 - Ejemplo de gmp_scan0
  • Example#3087 - Ejemplo de gmp_scan1
  • Example#3088 - Ejemplo de gmp_setbit - índice 0
  • Example#3089 - Ejemplo de gmp_setbit - índice 1
  • Example#3090 - Ejemplo de gmp_setbit - limpiar un bit
  • Example#3091 - Ejemplo de gmp_sign
  • Example#3092 - Ejemplo de gmp_sqrt
  • Example#3093 - Ejemplo degmp_sqrtrem
  • Example#3094 - Converting a GMP number to a string
  • Example#3095 - Ejemplo de gmp_sub
  • Example#3096 - Ejemplo degmp_testbit
  • Example#3097 - Ejemplo degmp_xor
  • Example#3098 - Ejemplo de abs
  • Example#3099 - Ejemplo de base_convert
  • Example#3100 - Ejemplo de bindec
  • Example#3101 - bindec interpreta las entradas como enteros sin signo
  • Example#3102 - Ejemplo de ceil
  • Example#3103 - Ejemplo de cos
  • Example#3104 - Ejemplo de decbin
  • Example#3105 - Ejemplo dechex
  • Example#3106 - Ejemplo de dechex con números enteros grandes
  • Example#3107 - Ejemplo de decoct
  • Example#3108 - Ejemplo de deg2rad
  • Example#3109 - Ejemplo de exp
  • Example#3110 - Using fdiv
  • Example#3111 - Ejemplo de floor
  • Example#3112 - Uso de fmod
  • Example#3113 - Ejemplo de hexdec
  • Example#3114 - Ejemplo de intdiv
  • Example#3115 - Ejemplo de is_nan
  • Example#3116 - Ejemplos de uso de max
  • Example#3117 - Ejemplos de uso de min
  • Example#3118 - Ejemplo de octdec
  • Example#3119 - Ejemplo de pi
  • Example#3120 - Algunos ejemplos de pow
  • Example#3121 - Ejemplo de rad2deg
  • Example#3122 - Ejemplos de round
  • Example#3123 - Ejemplos de mode
  • Example#3124 - Ejemplos de mode con precisión
  • Example#3125 - Ejemplo de sin
  • Example#3126 - Ejemplo de sqrt
  • Example#3127 - Ejemplo de tan
  • Example#3128 - Evaluar un documento FDF
  • Example#3129 - Añadiendo código JavaScript a un FDF
  • Example#3130 - Poblar un documento PDF
  • Example#3131 - Guardando un fichero subido por FDF
  • Example#3132 - Detección de todos los nombres de campo en un FDF
  • Example#3133 - Accediendo a los datos de un formulario
  • Example#3134 - Acceso a datos de formulario
  • Example#3135 - Salvando un FDF como string
  • Example#3136 - Paso de datos FDF a un segundo formulario
  • Example#3137 - Ejemplo de firma (clearsign) gnupg mediante funciones
  • Example#3138 - Ejemplo de firma gnupg (clearsign) mediante orientación a objetos
  • Example#3139 - keylistiterator
  • Example#3140 - Ejemplo de gnupg_adddecryptkey mediante funciones
  • Example#3141 - Ejemplo de gnupg_adddecryptkey mediante OO
  • Example#3142 - Ejemplo de gnupg_addencryptkey mediante funciones
  • Example#3143 - Ejemplo de gnupg_addencryptkey mediante OO
  • Example#3144 - Ejemplo de gnupg_addsignkey mediante funciones
  • Example#3145 - Ejemplo de gnupg_addsignkey mediante OO
  • Example#3146 - Ejemplo de gnupg_cleardecryptkeys mediante funciones
  • Example#3147 - Ejemplo de gnupg_cleardecryptkeys mediante OO
  • Example#3148 - Ejemplo de gnupg_clearencryptkeys mediante funciones
  • Example#3149 - Ejemplo de gnupg_clearencryptkeys mediante OO
  • Example#3150 - Ejemplo de gnupg_clearsignkeys mediante funciones
  • Example#3151 - Ejemplo de gnupg_clearsignkeys mediante OO
  • Example#3152 - Ejemplo de gnupg_decrypt mediante funciones
  • Example#3153 - Ejemplo de gnupg_encrypt mediante OO
  • Example#3154 - Ejemplo de gnupg_decryptverify mediante funciones
  • Example#3155 - Ejemplo de gnupg_decryptverify mediante OO
  • Example#3156 - Procedural gnupg_deletekey example
  • Example#3157 - OO gnupg_deletekey example
  • Example#3158 - Ejemplo de gnupg_encrypt mediante funciones
  • Example#3159 - Ejemplo de gnupg_encrypt mediante OO
  • Example#3160 - Ejemplo de gnupg_encryptsign mediante funciones
  • Example#3161 - Ejemplo de gnupg_encryptsign mediante OO
  • Example#3162 - Ejemplo de gnupg_export mediante funciones
  • Example#3163 - Ejemplo de gnupg_export mediante OO
  • Example#3164 - Procedural gnupg_getengineinfo example
  • Example#3165 - OO gnupg_getengineinfo example
  • Example#3166 - Ejemplo de gnupg_geterror mediante funciones
  • Example#3167 - Ejemplo de gnupg_geterror mediante OO
  • Example#3168 - Procedural gnupg_geterrorinfo example
  • Example#3169 - OO gnupg_geterrorinfo example
  • Example#3170 - Ejemplo de gnupg_getprotocol mediante funciones
  • Example#3171 - Ejemplo de gnupg_getprotocol mediante
  • Example#3172 - Procedural gnupg_gettrustlist example
  • Example#3173 - OO gnupg_gettrustlist example
  • Example#3174 - Ejemplo de gnupg_import mediante funciones
  • Example#3175 - Ejemplo de gnupg_import mediante OO
  • Example#3176 - Ejemplo de gnupg_init mediante funciones
  • Example#3177 - Ejemplo del inicializador gnupg mediante OO
  • Example#3178 - Ejemplo de gnupg_keyinfo mediante funciones
  • Example#3179 - Ejemplo de gnupg_keyinfo mediante OO
  • Example#3180 - Procedural gnupg_listsignatures example
  • Example#3181 - OO gnupg_listsignatures example
  • Example#3182 - Ejemplo de gnupg_setarmor mediante funciones
  • Example#3183 - Ejemplo de gnupg_setarmor mediante OO
  • Example#3184 - Pejemplo de gnupg_seterrormode mediante funciones
  • Example#3185 - Ejemplo de gnupg_seterrormode mediante OO
  • Example#3186 - Ejemplo de gnupg_setsignmode mediante funciones
  • Example#3187 - Ejemplo de gnupg_setsignmode mediante OO
  • Example#3188 - Ejemplo de gnupg_sign mediante funciones
  • Example#3189 - Ejemplo de gnupg_sign mediante OO
  • Example#3190 - Ejemplo de gnupg_verify mediante funciones
  • Example#3191 - Ejemplo de gnupg_verify mediante OO
  • Example#3192 - Crear y usar un patrón
  • Example#3193 - Crear y utilizar una plantilla
  • Example#3194 - Particionar silábicamente un texto
  • Example#3195 - Dibujar un rectángulo
  • Example#3196 - Crear y utilizar un color directo
  • Example#3197 - Rotación del sistema de coordenadas
  • Example#3198 - Colocar texto en una posición dada
  • Example#3199 - Dibujar una línea discontinua
  • Example#3200 - Traslación del sistema de coordenadas
  • Example#3201 - A rpmdbinfo example
  • Example#3202 - Searching for the package owning a file
  • Example#3203 - A rpminfo example
  • Example#3204 - ejemplo
  • Example#3205 - ejemplo
  • Example#3206 - ejemplo
  • Example#3207 - ejemplo
  • Example#3208 - ejemplo
  • Example#3209 - ejemplo
  • Example#3210 - ejemplo
  • Example#3211 - ejemplo
  • Example#3212 - ejemplo
  • Example#3213 - ejemplo
  • Example#3214 - ejemplo
  • Example#3215 - ejemplo
  • Example#3216 - ejemplo
  • Example#3217 - ejemplo
  • Example#3218 - ejemplo
  • Example#3219 - ejemplo
  • Example#3220 - ejemplo
  • Example#3221 - ejemplo
  • Example#3222 - ejemplo
  • Example#3223 - Incorrect requests
  • Example#3224 - Llamar a una petición desde una llamada de retorno de petición
  • Example#3225 - Llamar a una petición desde una llamada de retorno de petición
  • Example#3226 - Usar eio con libevent
  • Example#3227 - Cancelar una petición
  • Example#3228 - Llamar a eio_chmod
  • Example#3229 - Realizar una petición personalizada
  • Example#3230 - Agrupar peticiones
  • Example#3231 - Emplear eio con la extensión libevent
  • Example#3232 - Emplear eio con la extensión event
  • Example#3233 - Ejemplo de eio_cancel
  • Example#3234 - Ejemplo de eio_custom
  • Example#3235 - Ejemplo de eio_event_loop
  • Example#3236 - Ejemplo de eio_lstat
  • Example#3237 - Usar eio con libevent
  • Example#3238 - Agrupar peticiones
  • Example#3239 - Ejemplo de eio_grp
  • Example#3240 - Ejemplo de eio_link
  • Example#3241 - Ejemplo de eio_lstat
  • Example#3242 - Ejemplo de eio_mkdir
  • Example#3243 - Ejemplo de eio_mknod
  • Example#3244 - Ejepmlo de eio_nreqs
  • Example#3245 - Ejemplo de eio_open
  • Example#3246 - Ejemplo de eio_poll
  • Example#3247 - Ejemplo de eio_read
  • Example#3248 - eio_readdir example
  • Example#3249 - Ejemplo de eio_readlink
  • Example#3250 - Ejemplo deeio_realpath
  • Example#3251 - Ejemplo de eio_rename
  • Example#3252 - Ejemplo de eio_rmdir
  • Example#3253 - Ejemplo de eio_stat
  • Example#3254 - Ejemplo de eio_statvfs
  • Example#3255 - eio_symlink example
  • Example#3256 - Simple timers
  • Example#3257 - Periodic timer. Tick each 10.5 seconds
  • Example#3258 - Periodic timer. Use reschedule callback
  • Example#3259 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3260 - Wait until STDIN is readable
  • Example#3261 - Use some async I/O to access a socket
  • Example#3262 - Embedding one loop into another
  • Example#3263 - Embedding loop created with kqueue backend into the default loop
  • Example#3264 - Handle SIGTERM signal
  • Example#3265 - Monitor changes of /var/log/messages
  • Example#3266 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3267 - Process status changes
  • Example#3268 - Using reschedule callback
  • Example#3269 - Embedding loop created with kqueue backend into the default loop
  • Example#3270 - Embedding one loop into another
  • Example#3271 - Embedding loop created with kqueue backend into the default loop
  • Example#3272 - Embedding loop created with kqueue backend into the default loop
  • Example#3273 - Periodic timer. Use reschedule callback
  • Example#3274 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3275 - Hourly watcher
  • Example#3276 - Manejar la señal SIGTERM
  • Example#3277 - Monitor changes of /var/log/messages
  • Example#3278 - Monitor changes of /var/log/messages
  • Example#3279 - Simple timers
  • Example#3280 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3281 - Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.
  • Example#3282 - Ejemplo de uso de Expect
  • Example#3283 - Otro ejemplo de uso de Expect
  • Example#3284 - Ejemplo de expect_expectl
  • Example#3285 - Ejemplo de expect_popen
  • Example#3286 - Process Control Example
  • Example#3287 - pcntl_fork example
  • Example#3288 - pcntl_rfork example
  • Example#3289 - pcntl_signal_dispatch example
  • Example#3290 - pcntl_signal_get_handler example
  • Example#3291 - pcntl_signal example
  • Example#3292 - pcntl_sigprocmask example
  • Example#3293 - pcntl_sigwaitinfo example
  • Example#3294 - Ejemplo de posix_access
  • Example#3295 - Ejemplo de posix_ctermid
  • Example#3296 - posix_eaccess example
  • Example#3297 - posix_fpathconf example
  • Example#3298 - Ejemplo de posix_get_last_error
  • Example#3299 - Ejemplo de posix_getcwd
  • Example#3300 - Ejemplo de posix_getegid
  • Example#3301 - Ejemplo de posix_geteuid
  • Example#3302 - Ejemplo de posix_getgid
  • Example#3303 - Ejemplo de uso deposix_getgrgid
  • Example#3304 - Ejemplo de uso de posix_getgrnam
  • Example#3305 - Ejemplo de uso de posix_getgroups
  • Example#3306 - Ejemplo de uso de posix_getlogin
  • Example#3307 - Ejemplo de uso de posix_getpgid
  • Example#3308 - Ejemplo de uso de posix_getpid
  • Example#3309 - Ejemplo de uso de posix_getppid
  • Example#3310 - Ejemplo de uso de posix_getpwnam
  • Example#3311 - Ejemplo de uso de posix_getpwuid
  • Example#3312 - Ejemplo de uso de posix_getrlimit
  • Example#3313 - Ejemplo de uso de posix_getsid
  • Example#3314 - Ejemplo de uso de posix_getuid
  • Example#3315 - Un ejemplo de posix_mknod
  • Example#3316 - posix_pathconf example
  • Example#3317 - Ejemplo de posix_setegid
  • Example#3318 - Ejemplo de posix_setgid
  • Example#3319 - Ejemplo de posix_setuid
  • Example#3320 - Ejemplo de posix_strerror
  • Example#3321 - posix_sysconf example
  • Example#3322 - Ejemplo de uso de posix_times
  • Example#3323 - Ejemplo de uso de posix_uname
  • Example#3324 - Ejemplo de escapeshellarg
  • Example#3325 - Ejemplo de escapeshellcmd
  • Example#3326 - Un ejemplo de exec
  • Example#3327 - Ejemplo de proc_open
  • Example#3328 - Un ejemplo de shell_exec
  • Example#3329 - Ejemplo de system
  • Example#3330 - Example showing Future as return value
  • Example#3331 - Example showing Future as synchronization point
  • Example#3332 - Fetch a chunk of the property table
  • Example#3333 - Counting the properties of an object
  • Example#3334 - Runtime inheritance
  • Example#3335 - Detect the state of the referenced object
  • Example#3336 - Detect the state of the referenced object
  • Example#3337 - Merging into the property table of a threaded object
  • Example#3338 - Notifications and Waiting
  • Example#3339 - Notifications and Waiting
  • Example#3340 - Popping the last item from the property table of a threaded object
  • Example#3341 - Shifting the first item from the property table of a threaded object
  • Example#3342 - Synchronizing
  • Example#3343 - Notifications and Waiting
  • Example#3344 - Devuelve la identificación del hilo o proceso que el hilo referenciado creó.
  • Example#3345 - Devuelve el hilo que se está ejecutando
  • Example#3346 - Return the identity of the currently executing Thread
  • Example#3347 - Return the identity of the referenced Thread
  • Example#3348 - Detect the state of the referenced Thread
  • Example#3349 - Tell if the referenced Thread was started
  • Example#3350 - Join with the referenced Thread
  • Example#3351 - Starting Threads
  • Example#3352 - A basic example of Worker::collect
  • Example#3353 - A basic example of Worker::getStacked
  • Example#3354 - Detect the state of a worker
  • Example#3355 - Shutdown the referenced worker
  • Example#3356 - Stacking a task for execution onto a worker
  • Example#3357 - Removing objects from the stack of Workers
  • Example#3358 - A basic example of Pool::collect
  • Example#3359 - Creating Pools
  • Example#3360 - Shutting down a pool
  • Example#3361 - Submitting Tasks
  • Example#3362 - Submitting tasks to a specific worker
  • Example#3363 - New immutability semantics of Threaded
  • Example#3364 - Volatile use-case
  • Example#3365 -
  • Example#3366 - Resumen de las operaciones con Memoria Compartida
  • Example#3367 - Cerrando segmento de memoria compartida
  • Example#3368 - Borrando segmento de memoria compartida
  • Example#3369 - Crear un nuevo segmento de memoria compartida
  • Example#3370 - Lectura de un segmento de memoria compartida
  • Example#3371 - Obtención del tamaño de un segmento de memoria compartida
  • Example#3372 - Escribiendo en un segmento de memoria compartida
  • Example#3373 - SyncMutex::__construct named mutex with lock timeout example
  • Example#3374 - SyncMutex::__construct unnamed mutex example
  • Example#3375 - SyncMutex::lock example
  • Example#3376 - SyncMutex::unlock example
  • Example#3377 - SyncSemaphore::__construct example
  • Example#3378 - SyncSemaphore::lock example
  • Example#3379 - SyncSemaphore::unlock example
  • Example#3380 - SyncEvent::__construct example
  • Example#3381 - SyncEvent::fire example
  • Example#3382 - SyncEvent::reset example
  • Example#3383 - SyncEvent::wait example
  • Example#3384 - SyncReaderWriter::__construct example
  • Example#3385 - SyncReaderWriter::readlock example
  • Example#3386 - SyncReaderWriter::readunlock example
  • Example#3387 - SyncReaderWriter::writelock example
  • Example#3388 - SyncReaderWriter::writeunlock example
  • Example#3389 - SyncSharedMemory::__construct example
  • Example#3390 - SyncSharedMemory::first example
  • Example#3391 - SyncSharedMemory::__construct example
  • Example#3392 - SyncSharedMemory::size example
  • Example#3393 - SyncSharedMemory::write example
  • Example#3394 - A geoip_asnum_by_name example
  • Example#3395 - A geoip_continent_code_by_name example
  • Example#3396 - A geoip_country_code_by_name example
  • Example#3397 - A geoip_country_code3_by_name example
  • Example#3398 - A geoip_country_name_by_name example
  • Example#3399 - A geoip_database_info example
  • Example#3400 - A geoip_db_avail example
  • Example#3401 - A geoip_db_filename example
  • Example#3402 - A geoip_db_get_all_info example
  • Example#3403 - A geoip_db_get_all_info example
  • Example#3404 - A geoip_domain_by_name example
  • Example#3405 - A geoip_id_by_name example
  • Example#3406 - A geoip_isp_by_name example
  • Example#3407 - A geoip_netspeedcell_by_name example
  • Example#3408 - A geoip_org_by_name example
  • Example#3409 - A geoip_record_by_name example
  • Example#3410 - A geoip_region_by_name example
  • Example#3411 - A geoip_region_name_by_code example using region code for US/Canada
  • Example#3412 - A geoip_region_name_by_code example using FIPS codes
  • Example#3413 - A geoip_setup_custom_directory example
  • Example#3414 - A geoip_time_zone_by_country_and_region example using region code for US/Canada
  • Example#3415 - A geoip_time_zone_by_country_and_region example using FIPS codes
  • Example#3416 - Fichero xor.data
  • Example#3417 - Entrenamiento sencillo
  • Example#3418 - Prueba sencilla
  • Example#3419 - Ejemplo de fann_create_train_from_callback
  • Example#3420 - Ejemplo de fann_read_train_from_file
  • Example#3421 - igbinary_serialize example
  • Example#3422 - Ejemplo de JsonSerializable::jsonSerialize devolviendo un array
  • Example#3423 - Ejemplo de JsonSerializable::jsonSerialize devolviendo un array asociativo
  • Example#3424 - Ejemplo de JsonSerializable::jsonSerialize devolviento un integer
  • Example#3425 - Ejemplo de JsonSerializable::jsonSerialize devolviendo un string
  • Example#3426 - Ejemplos de json_decode
  • Example#3427 - Acceder a propiedades de objeto no válidas
  • Example#3428 - Errores comunes al usar json_decode
  • Example#3429 - Errores con depth
  • Example#3430 - json_decode de enteros grandes
  • Example#3431 - Un ejemplo de json_encode
  • Example#3432 - Un ejemplo de json_encode mostrando algunas de las opciones en acción
  • Example#3433 - Ejemplo de la opción JSON_NUMERIC_CHECK
  • Example#3434 - Ejemplo de array secuencial contra array no secuencial
  • Example#3435 - Ejemplo de la opción JSON_PRESERVE_ZERO_FRACTION
  • Example#3436 - Ejemplo de json_last_error
  • Example#3437 - json_last_error en json_encode
  • Example#3438 - json_validate examples
  • Example#3439 - simdjson_decode examples
  • Example#3440 - Accessing invalid object properties
  • Example#3441 - common mistakes using simdjson_decode
  • Example#3442 - depth errors
  • Example#3443 - simdjson_decode of large integers
  • Example#3444 - simdjson_decode examples
  • Example#3445 - depth errors
  • Example#3446 - Ejemplo de Lua::assign
  • Example#3447 - Ejemplo de la función Lua::call
  • Example#3448 - Ejemplo de la función Lua::eval
  • Example#3449 - Ejemplo de Lua::registerCallback
  • Example#3450 - Ejemplo de LuaClosure::__invoke
  • Example#3451 - Execute some Lua code
  • Example#3452 - Calling a Lua function
  • Example#3453 - Profiling Lua code
  • Example#3454 - Loading code into Lua
  • Example#3455 - Manipulating the usage timer
  • Example#3456 - Registering PHP functions to call from Lua
  • Example#3457 - Calling a Lua function
  • Example#3458 - Calling a Lua function
  • Example#3459 - Ejemplo de constant
  • Example#3460 - Definir Constantes
  • Example#3461 - Comprobar constantes
  • Example#3462 - Ejemplo de eval - fusión de texto sencillo
  • Example#3463 - Ejemplo de exit
  • Example#3464 - Ejemplo de status de exit
  • Example#3465 - Las funciones Shutdown y los destructores se ejecutan igualmente
  • Example#3466 - Listar toda la información sobre el navegador del usuario
  • Example#3467 - Un Ejemplo de __halt_compiler
  • Example#3468 - Ejemplo de highlight_string
  • Example#3469 - hrtime usage
  • Example#3470 - Un ejemplo ignore_user_abort
  • Example#3471 - Ejemplo de pack
  • Example#3472 - Ejemplo de php_strip_whitespace
  • Example#3473 - Basic sapi_windows_generate_ctrl_event Usage
  • Example#3474 - Basic sapi_windows_set_ctrl_handler Usage
  • Example#3475 - sapi_windows_vt100_support default state
  • Example#3476 - sapi_windows_vt100_support changing state
  • Example#3477 - Example usage of VT100 support enabled
  • Example#3478 - Ejemplo de sleep
  • Example#3479 - Ejemplo de sys_getloadavg
  • Example#3480 - Ejemplo de time_nanosleep
  • Example#3481 - Un ejemplo de time_sleep_until
  • Example#3482 - Ejemplo de uniqid
  • Example#3483 - Ejemplo de unpack
  • Example#3484 - Ejemplo de unpack con un repetidor
  • Example#3485 - Ejemplo unpack con claves sin nombre
  • Example#3486 - Ejemplo de usleep
  • Example#3487 - Random Example
  • Example#3488 - mt_rand example
  • Example#3489 - rand example
  • Example#3490 - random_bytes example
  • Example#3491 - random_int example
  • Example#3492 - Random\Randomizer::__construct example
  • Example#3493 - Random\Randomizer::getBytes example
  • Example#3494 - Random\Randomizer::getBytesFromString example
  • Example#3495 - Generate a random code for multi-factor authentication
  • Example#3496 - Select from a string with a non-uniform distribution
  • Example#3497 - Random\Randomizer::getFloat example
  • Example#3498 - Random\Randomizer::getInt example
  • Example#3499 - Random\Randomizer::nextFloat example
  • Example#3500 - Incorrect scaling using an affine transformation
  • Example#3501 - Random\Randomizer::nextInt example
  • Example#3502 - Random\Randomizer::pickArrayKeys example
  • Example#3503 - Picking random values
  • Example#3504 - Random\Randomizer::__serialize example
  • Example#3505 - Random\Randomizer::shuffleArray example
  • Example#3506 - Random\Randomizer::shuffleBytes example
  • Example#3507 - Byte-wise shuffling breaks Unicode characters
  • Example#3508 - Random\Randomizer::__unserialize example
  • Example#3509 - Random\Engine::generate example
  • Example#3510 - Random\Engine\Mt19937::__construct example
  • Example#3511 - Random\Engine\Mt19937::__debugInfo example
  • Example#3512 - Random\Engine\Mt19937::__serialize example
  • Example#3513 - Random\Engine\Mt19937::__unserialize example
  • Example#3514 - Random\Engine\PcgOneseq128XslRr64::__construct example
  • Example#3515 - Deriving a seed from a string
  • Example#3516 - Random\Engine\PcgOneseq128XslRr64::__debugInfo example
  • Example#3517 - Random\Engine\PcgOneseq128XslRr64::jump example
  • Example#3518 - Randomizer methods may call the engine more than once
  • Example#3519 - Random\Engine\PcgOneseq128XslRr64::__serialize example
  • Example#3520 - Random\Engine\PcgOneseq128XslRr64::__unserialize example
  • Example#3521 - Random\Engine\Xoshiro256StarStar::__construct example
  • Example#3522 - Deriving a seed from a string
  • Example#3523 - Random\Engine\Xoshiro256StarStar::__debugInfo example
  • Example#3524 - Random\Engine\Xoshiro256StarStar::jump example
  • Example#3525 - Random\Engine\Xoshiro256StarStar::jumpLong example
  • Example#3526 - Random\Engine\Xoshiro256StarStar::__serialize example
  • Example#3527 - Random\Engine\Xoshiro256StarStar::__unserialize example
  • Example#3528 - Get and set base path
  • Example#3529 - Get and set logger
  • Example#3530 - Fast write log
  • Example#3531 - Fast count some type of log count value
  • Example#3532 - Acquisit some type of log list
  • Example#3533 - seaslog_get_author example
  • Example#3534 - seaslog_get_version example
  • Example#3535 - SeasLog::alert example
  • Example#3536 - SeasLog::analyzerCount example
  • Example#3537 - SeasLog::analyzerDetail example
  • Example#3538 - SeasLog::closeLoggerStream example
  • Example#3539 - SeasLog::__construct example
  • Example#3540 - SeasLog::critical example
  • Example#3541 - SeasLog::debug example
  • Example#3542 - SeasLog::__destruct example
  • Example#3543 - SeasLog::emergency example
  • Example#3544 - SeasLog::error example
  • Example#3545 - SeasLog::flushBuffer example
  • Example#3546 - SeasLog::getBasePath example
  • Example#3547 - SeasLog::getBuffer example
  • Example#3548 - SeasLog::getBufferEnabled example
  • Example#3549 - SeasLog::getDatetimeFormat example
  • Example#3550 - SeasLog::getLastLogger example
  • Example#3551 - SeasLog::getRequestID example
  • Example#3552 - SeasLog::getRequestVariable example
  • Example#3553 - SeasLog::info example
  • Example#3554 - SeasLog::log example
  • Example#3555 - SeasLog::notice example
  • Example#3556 - SeasLog::setBasePath example
  • Example#3557 - SeasLog::setDatetimeFormat example
  • Example#3558 - SeasLog::setLogger example
  • Example#3559 - SeasLog::setRequestID example
  • Example#3560 - SeasLog::setRequestVariable example
  • Example#3561 - SeasLog::warning example
  • Example#3562 - Ejemplo de SplStack
  • Example#3563 - SplQueue ejemplo
  • Example#3564 - Gestión eficiente de tareas con SplQueue
  • Example#3565 - Ejemplo de uso SplFixedArray
  • Example#3566 - Ejemplo de SplFixedArray::__construct
  • Example#3567 - Ejemplo de SplFixedArray::count
  • Example#3568 - Ejemplo de SplFixedArray::fromArray
  • Example#3569 - Ejemplo de SplFixedArray::getSize
  • Example#3570 - Ejemplo de SplFixedArray::setSize
  • Example#3571 - Ejemplo de SplFixedArray::toArray
  • Example#3572 - SplObjectStorage como un conjunto
  • Example#3573 - SplObjectStorage como un mapa
  • Example#3574 - Ejemplo de SplObjectStorage::addAll
  • Example#3575 - Ejemplo de SplObjectStorage::attach
  • Example#3576 - Ejemplo de SplObjectStorage::contains
  • Example#3577 - Ejemplo de SplObjectStorage::count
  • Example#3578 - Ejemplo de SplObjectStorage::current
  • Example#3579 - Ejemplo de SplObjectStorage::detach
  • Example#3580 - Ejemplo de SplObjectStorage::getHash
  • Example#3581 - Ejemplo de SplObjectStorage::getInfo
  • Example#3582 - Ejemplo de SplObjectStorage::key
  • Example#3583 - Ejemplo de SplObjectStorage::next
  • Example#3584 - Ejemplo de SplObjectStorage::offsetExists
  • Example#3585 - Ejemplo de SplObjectStorage::offsetGet
  • Example#3586 - Ejemplo de SplObjectStorage::offsetSet
  • Example#3587 - Ejemplo de SplObjectStorage::offsetUnset
  • Example#3588 - Ejemplo de SplObjectStorage::removeAll
  • Example#3589 - Ejemplo de SplObjectStorage::removeAllExcept
  • Example#3590 - Ejemplo de SplObjectStorage::rewind
  • Example#3591 - Ejemplo de SplObjectStorage::serialize
  • Example#3592 - Ejemplo de SplObjectStorage::setInfo
  • Example#3593 - Ejemplo de SplObjectStorage::unserialize
  • Example#3594 - Ejemplo de SplObjectStorage::valid
  • Example#3595 - Ejemplo de AppendIterator::append
  • Example#3596 - Recorriendo AppendIterator con foreach
  • Example#3597 - Recorriendo AppendIterator con la API de AppendIterator
  • Example#3598 - Ejemplo básico de AppendIterator.getIteratorIndex
  • Example#3599 - Ejemplo básico de AppendIterator::key
  • Example#3600 - Ejemplo de ArrayIterator::current
  • Example#3601 - Ejemplo de ArrayIterator::key
  • Example#3602 - Ejemplo de ArrayIterator::next
  • Example#3603 - Ejemplo de ArrayIterator::rewind
  • Example#3604 - Ejemplo de ArrayIterator::valid
  • Example#3605 - Ejemplo de CachingIterator::getCache.
  • Example#3606 - Argumentos disponibles de la llamada de retorno
  • Example#3607 - Ejemplos básicos de llamada de retorno
  • Example#3608 - Un DirectoryIterator::__construct ejemplo
  • Example#3609 - Ejemplo de DirectoryIterator::current
  • Example#3610 - Ejemplo de DirectoryIterator::getBasename
  • Example#3611 - Ejemplo de DirectoryIterator::getExtension
  • Example#3612 -
  • Example#3613 - Ejemplo de DirectoryIterator::getFilename
  • Example#3614 - Ejemplo de DirectoryIterator::isDot
  • Example#3615 - Ejemplo de DirectoryIterator::key
  • Example#3616 - Ejemplo de DirectoryIterator::next
  • Example#3617 - Ejemplo de DirectoryIterator::rewind
  • Example#3618 - Ejemplo de DirectoryIterator::seek
  • Example#3619 - Ejemplo de DirectoryIterator::__toString
  • Example#3620 - Ejemplo de DirectoryIterator::valid
  • Example#3621 - Ejemplo de FilesystemIterator::__construct
  • Example#3622 - Ejemplo de FilesystemIterator::current
  • Example#3623 - Ejemplo de FilesystemIterator::key
  • Example#3624 - Ejemplo de FilesystemIterator::next
  • Example#3625 - Ejemplo de FilesystemIterator::rewind
  • Example#3626 - Ejemplo de FilesystemIterator::key
  • Example#3627 - Ejemplo de FilterIterator::accept
  • Example#3628 - Ejemplo de GlobIterator
  • Example#3629 - Ejemplo de GlobIterator::count
  • Example#3630 - Ejemplo de InfiniteIterator::__construct
  • Example#3631 - Ejemplo de uso de LimitIterator
  • Example#3632 - Ejemplo de LimitIterator::__construct
  • Example#3633 - Ejemplo de LimitIterator::getPosition
  • Example#3634 - Iterar un MultipleIterator
  • Example#3635 - Ejemplo de NoRewindIterator::__construct
  • Example#3636 - Ejemplo de NoRewindIterator::rewind
  • Example#3637 - Ejemplo de RecursiveArrayIterator::getChildren
  • Example#3638 - Ejemplo de RecursiveArrayIterator::hasChildren
  • Example#3639 - Argumentos disponibles de la llamada de retorno
  • Example#3640 - Ejemplo básico de llamada de retorno recursiva
  • Example#3641 - Uso básico de RecursiveCallbackFilterIterator::hasChildren
  • Example#3642 - Ejemplo de RecursiveDirectoryIterator
  • Example#3643 - Ejemplo de getSubPath
  • Example#3644 - Ejemplo de getSubPathname
  • Example#3645 - Ejemplo básico de RecursiveFilterIterator
  • Example#3646 - Ejemplo de RecursiveFilterIterator
  • Example#3647 - Iterar un RecursiveIteratorIterator
  • Example#3648 - Ejemplo de RecursiveRegexIterator::__construct
  • Example#3649 - Ejemplo de RecursiveRegexIterator::getChildren
  • Example#3650 - Ejemplo de RecursiveRegexIterator::hasChildren
  • Example#3651 - RegexIterator::accept example
  • Example#3652 - Ejemplo de RegexIterator::__construct
  • Example#3653 - Ejemplo de RegexIterator::getFlags
  • Example#3654 - Ejemplo de RegexIterator::getMode
  • Example#3655 - Ejemplo de RegexIterator::getPregFlags
  • Example#3656 - Ejemplo de RegexIterator::setFlags
  • Example#3657 - Ejemplo de RegexIterator::setMode
  • Example#3658 - Ejemplo de RegexIterator::setPregFlags
  • Example#3659 - Ejemplo de Countable::count
  • Example#3660 - Uso básico
  • Example#3661 - Ejemplo de SeekableIterator::seek
  • Example#3662 - Ejemplo de class_implements
  • Example#3663 - Ejemplo de class_parents
  • Example#3664 - Ejemplo de class_uses
  • Example#3665 - Ejemplo de iterator_apply
  • Example#3666 - Ejemplo de iterator_count
  • Example#3667 - iterator_count modifica la posición
  • Example#3668 - iterator_count en bucles foreach
  • Example#3669 - Ejemplo de iterator_to_array
  • Example#3670 - spl_autoload_register como sustituto de una función __autoload
  • Example#3671 - Ejemplo de spl_autoload_register donde la clase no es cargada
  • Example#3672 - Ejemplo de spl_classes
  • Example#3673 - Ejemplo de spl_object_hash
  • Example#3674 - A spl_object_id example
  • Example#3675 - SplFileInfo::__construct ejemplo
  • Example#3676 - Ejemplo de SplFileInfo::getATime
  • Example#3677 - SplFileInfo::getBasenameejemplo
  • Example#3678 - Ejemplo de SplFileInfo::getCTime
  • Example#3679 - SplFileInfo::getExtension ejemplo
  • Example#3680 -
  • Example#3681 - SplFileInfo::getFilename ejemplo
  • Example#3682 - Ejemplo de SplFileInfo::getGroup
  • Example#3683 - Ejemplo de SplFileInfo::getLinkTarget
  • Example#3684 - Ejemplo de SplFileInfo::getMTime
  • Example#3685 - Ejemplo de SplFileInfo::getOwner
  • Example#3686 - Ejemplo de SplFileInfo::getPath
  • Example#3687 - Ejemplo de SplFileInfo::getPathInfo
  • Example#3688 - Ejemplo de SplFileInfo::getPathname
  • Example#3689 - Ejemplo de SplFileInfo::getPerms
  • Example#3690 - Ejemplo de SplFileInfo::getRealPath
  • Example#3691 - SplFileInfo::getSize example
  • Example#3692 - Ejemplo de SplFileInfo::getType
  • Example#3693 - Ejemplo de SplFileInfo::isDir
  • Example#3694 - Ejemplo de SplFileInfo::isExecutable
  • Example#3695 - Ejemplo de SplFileInfo::isFile
  • Example#3696 - Ejemplo de SplFileInfo::isLink
  • Example#3697 - Ejemplo de SplFileInfo::isReadable
  • Example#3698 - Ejemplo de SplFileInfo::isWriteable
  • Example#3699 - Ejemplo de SplFileInfo::openFile
  • Example#3700 - Ejemplo de SplFileInfo::setFileClass
  • Example#3701 - Ejemplo de SplFileInfo::setFileClass
  • Example#3702 - Ejemplo de SplFileInfo::__toString
  • Example#3703 - Ejemplo de SplFileObject::__construct
  • Example#3704 - Ejemplo de SplFileObject::current
  • Example#3705 - Ejemplo de SplFileObject::eof
  • Example#3706 - Ejemplo de SplFileObject::fflush
  • Example#3707 - Ejemplo de SplFileObject::fgetc
  • Example#3708 - Ejemplo de SplFileObject::fgetcsv
  • Example#3709 - Ejemplo de SplFileObject::READ_CSV
  • Example#3710 - Ejemplo de SplFileObject::fgets
  • Example#3711 - Ejemplo de SplFileObject::fgetss
  • Example#3712 - Ejemplo de SplFileObject::flock
  • Example#3713 - Ejemplo de SplFileObject::fpassthru
  • Example#3714 - Ejemplo de SplFileObject::fputcsv
  • Example#3715 - Ejemplo de SplFileObject::fread
  • Example#3716 - Ejemplo de SplFileObject::fscanf
  • Example#3717 - Ejemplo de SplFileObject::fseek
  • Example#3718 - Ejemplo de SplFileObject::fstat
  • Example#3719 - Ejemplo de SplFileObject::ftell
  • Example#3720 - Ejemplo de SplFileObject::ftruncate
  • Example#3721 - Ejemplo de SplFileObject::fwrite
  • Example#3722 - Ejemplo de SplFileObject::getCsvControl
  • Example#3723 - Ejemplo de SplFileObject::getFlags
  • Example#3724 - Ejemplo de SplFileObject::getMaxLineLen
  • Example#3725 - Ejemplo de SplFileObject::key
  • Example#3726 - SplFileObject::key ejemplo con SplFileObject::setMaxLineLen
  • Example#3727 - Ejemplo de SplFileObject::next
  • Example#3728 - Ejemplo de SplFileObject::rewind
  • Example#3729 - Ejemplo de SplFileObject::seek
  • Example#3730 - Ejemplo de SplFileObject::setCsvControl
  • Example#3731 - Ejemplo de SplFileObject::setFlags
  • Example#3732 - Ejemplo de SplFileObject::setMaxLineLen
  • Example#3733 - Ejemplo de SplFileObject::valid
  • Example#3734 - Ejemplo de SplTempFileObject
  • Example#3735 - Ejemplo de ArrayObject::append
  • Example#3736 - ArrayObject::asort example
  • Example#3737 - Ejemplo de ArrayObject::__construct
  • Example#3738 - Ejemplo de ArrayObject::count
  • Example#3739 - ArrayObject::exchangeArray example
  • Example#3740 - ArrayObject::getArrayCopy example
  • Example#3741 - Ejemplo de ArrayObject::getFlags
  • Example#3742 - Ejemplo de ArrayObject::getIterator
  • Example#3743 - ArrayObject::getIteratorClass example
  • Example#3744 - Ejemplo de ArrayObject::ksort
  • Example#3745 - Ejemplo de ArrayObject::natcasesort
  • Example#3746 - Ejemplo de ArrayObject::natsort
  • Example#3747 - Ejemplo de ArrayObject::offsetExists
  • Example#3748 - Ejemplo de ArrayObject::offsetGet
  • Example#3749 - Ejemplo de ArrayObject::offsetSet
  • Example#3750 - Ejemplo de ArrayObject::offsetUnset
  • Example#3751 - Ejemplo de ArrayObject::serialize
  • Example#3752 - Ejemplo de ArrayObject::setFlags
  • Example#3753 - Ejemplo de ArrayObject::setIteratorClass
  • Example#3754 - Ejemplo de ArrayObject::uasort
  • Example#3755 - Ejemplo de ArrayObject::uksort
  • Example#3756 - Usar file_get_contents para recuperar información desde múltiples fuentes
  • Example#3757 - Hacer una petición POST a un servidor https
  • Example#3758 - Escribir información en un archivo compirmido
  • Example#3759 - Un Flujo para leer/escribir variables globales
  • Example#3760 - Listar los ficheros de archivos tar
  • Example#3761 - Ejemplos de stream_bucket_prepend
  • Example#3762 - Usar stream_context_create
  • Example#3763 - Usar stream_context_get_default
  • Example#3764 - Ejemplo de stream_context_get_options
  • Example#3765 - Ejemplo de stream_context_get_params
  • Example#3766 - Ejemplo de stream_context_set_default
  • Example#3767 - stream_context_set_options example
  • Example#3768 - Un ejemplo de stream_copy_to_stream
  • Example#3769 - Controlar dónde son aplicados los filtros
  • Example#3770 - Filtro para poner en mayúsculas caracteres en el flujo foo-bar.txt
  • Example#3771 - Registrar una clase de filtro genérica para comparar múltiples nombres de filtro.
  • Example#3772 - Refiltrar dináminamente un flujo
  • Example#3773 - Ejemplo de stream_get_contents
  • Example#3774 - Usar stream_get_filters
  • Example#3775 - Ejemplo de stream_get_meta_data
  • Example#3776 - Usar stream_get_transports
  • Example#3777 - Ejemplo de stream_get_wrappers
  • Example#3778 - Comprobar la existencia de una envoltura de flujo
  • Example#3779 - Ejemplo de stream_is_local
  • Example#3780 - stream_isatty example
  • Example#3781 - Ejemplo de stream_notification_callback
  • Example#3782 - Barra de progreso sencilla para la descarga por parte del cliente por línea de comandos
  • Example#3783 - Ejemplo de stream_resolve_include_path
  • Example#3784 - Ejemplo de stream_select
  • Example#3785 - Ejemplo de stream_set_timeout
  • Example#3786 - Ejemplo de stream_set_write_buffer
  • Example#3787 - Ejemplo de stream_socket_client
  • Example#3788 - Usar una conexión UDP
  • Example#3789 - Ejemplo de stream_socket_enable_crypto
  • Example#3790 - Un ejemplo de stream_socket_pair
  • Example#3791 - Ejemplo de stream_socket_recvfrom
  • Example#3792 - Ejemplo de stream_socket_sendto
  • Example#3793 - Usar sockets de servidor de TCP
  • Example#3794 - Usar sockets de servidor de UDP
  • Example#3795 - Un ejemplo de stream_socket_shutdown
  • Example#3796 - Cómo registrar una envoltura de flujo
  • Example#3797 - Uso Básico Tidy
  • Example#3798 - Ejemplo de tidy::getBody
  • Example#3799 - Ejemplo de tidy::cleanrepair
  • Example#3800 - Ejemplo de tidy::__construct
  • Example#3801 - Ejemplo de tidy::diagnose
  • Example#3802 - Ejemplo de tidy_get_error_buffer
  • Example#3803 - Ejemplo de tidy::getConfig
  • Example#3804 - Ejemplo de tidy_getopt
  • Example#3805 - Imprimir todas las opciones, junto con su documentación y sus valores por omisión
  • Example#3806 - Ejemplo de tidy::getStatus
  • Example#3807 - Ejemplo de tidy::head
  • Example#3808 - Ejemplo de tidy::html
  • Example#3809 - Ejemplo de tidy::parseFile
  • Example#3810 - Ejemplo de tidy::parseString
  • Example#3811 - Ejemplo de tidy::repairFile
  • Example#3812 - Ejemplo de tidy::repairString
  • Example#3813 - tidy::root ejemplo
  • Example#3814 - Ejemplo de tidyNode::hasChildren
  • Example#3815 - Ejemplo de tidyNode::hasChildren
  • Example#3816 - Ejemplo de tidyNode::hasSiblings
  • Example#3817 - Extraer el código ASP embebido en un documento HTML
  • Example#3818 - Extraer los comentarios de un documento HTML
  • Example#3819 - Extraer el código HTML de un documento HTML
  • Example#3820 - Extrer el código JSTE de un documento HTML
  • Example#3821 - Extraer el código PHP embebido en un documento HTML
  • Example#3822 - Extraer el texto de un documento HTML
  • Example#3823 - Ejemplo de ob_tidyhandler
  • Example#3824 - Ejemplo de la función tidy_access_count
  • Example#3825 - Ejemplo de la función tidy_config_count
  • Example#3826 - Ejemplo de la función tidy_error_count
  • Example#3827 - Ejemplo de la función tidy_get_output
  • Example#3828 - Ejemplo de la función tidy_warning_count
  • Example#3829 - Quitar comentarios con el tokenizer
  • Example#3830 - token_get_all ejemplos
  • Example#3831 - ejemplo de token_get_all usado en una clase con una palabra reservada
  • Example#3832 - token_name ejemplo
  • Example#3833 - Ejemplo de base64_decode
  • Example#3834 - Ejemplo de base64_encode
  • Example#3835 - Ejemplo de get_headers
  • Example#3836 - get_headers using HEAD example
  • Example#3837 - Lo que procesa get_meta_tags
  • Example#3838 - Lo que devuelve get_meta_tags
  • Example#3839 - Uso simple de http_build_query
  • Example#3840 - http_build_query con elementos indexados numéricamente.
  • Example#3841 - con arrays complejos http_build_query
  • Example#3842 - Uso de http_build_query con un objeto
  • Example#3843 - Un ejemplo de parse_url
  • Example#3844 - Un ejemplo de parse_url con el esquema ausente
  • Example#3845 - Ejemplo de rawurldecode
  • Example#3846 - Inclusión de una contraseña en una URL FTP
  • Example#3847 - Ejemplo 2 de rawurlencode
  • Example#3848 - Ejemplo de urldecode
  • Example#3849 - Ejemplo de urlencode
  • Example#3850 - Ejemplo de urlencode y ejemplo de htmlentities
  • Example#3851 - Básica ejecución Javascript
  • Example#3852 - Yaml Example
  • Example#3853 - Ejemplo de análisis de callback
  • Example#3854 - Ejemplo de emisión de callback
  • Example#3855 - Ejemplo de yaml_emit
  • Example#3856 - Ejemplo de yaml_parse
  • Example#3857 - Distribución clásica del directorio Application
  • Example#3858 - Entrada
  • Example#3859 - Regla de sobrescritura
  • Example#3860 - Configuración de la aplicación
  • Example#3861 - Controlador predeterminado
  • Example#3862 - Plantilla de vistas predeterminada
  • Example#3863 - Ejecutar la aplicación
  • Example#3864 - Un ejemplo de array de PHP
  • Example#3865 - Un ejemplo de un fichero ini
  • Example#3866 - Un ejemplo de A Bootstrap
  • Example#3867 - Ejemplo de Yaf_Application::bootstrap
  • Example#3868 - Ejemplo de Yaf_Application::clearLastError
  • Example#3869 - A ini config file example
  • Example#3870 - Ejemplo de Yaf_Application::__construct
  • Example#3871 - Ejemplo de Yaf_Application::__construct
  • Example#3872 - Ejemplo de Yaf_Application::environ
  • Example#3873 - Ejemplo de Yaf_Application::execute
  • Example#3874 - Ejemplo de Yaf_Application::getConfig
  • Example#3875 - Ejemplo de Yaf_Application::getDispatcher
  • Example#3876 - Ejemplo de Yaf_Application::getLastErrorMsg
  • Example#3877 - Ejemplo de Yaf_Application::getLastErrorNo
  • Example#3878 - Ejemplo de Yaf_Application::getModules
  • Example#3879 - Ejemplo de arranque
  • Example#3880 - Ejemplo de Yaf_Dispatcher::autoRender
  • Example#3881 - Ejemplo de Yaf_Dispatcher::catchException
  • Example#3882 - Yaf_Dispatcher::registerPluginexample
  • Example#3883 - Ejemplo de un motor de Vistas personalizado
  • Example#3884 - Ejemplo de Yaf_Dispatcher::setView
  • Example#3885 - Ejemplo de Yaf_Dispatcher::throwexception
  • Example#3886 - Ejemplo de Yaf_Dispatcher::throwexception
  • Example#3887 - Ejemplo de Yaf_Config_Ini
  • Example#3888 - Definir una acción en un fichero aparte
  • Example#3889 - Dummy_action.php
  • Example#3890 - Ejemplo de Yaf_Controller_Abstract::forward
  • Example#3891 - Ejemplo de Yaf_Action_Abstract::execute
  • Example#3892 - Ejemplo de Yaf_Action_Abstract::execute
  • Example#3893 - Ejemplo de Yaf_View_Simple::assign
  • Example#3894 - Ejemplo de template
  • Example#3895 - Ejemplo de Yaf_View_Simple::assignRef
  • Example#3896 - Ejemplo de template
  • Example#3897 - Ejemplo de Yaf_View_Simple::clear
  • Example#3898 - Ejemplo de Yaf_View_Simple::__constructor
  • Example#3899 - Ejemplo de Yaf_View_Simple::__set
  • Example#3900 - Ejemplo de configuración
  • Example#3901 - Registrar el espacio de nombres local
  • Example#3902 - Load class example
  • Example#3903 - Ejemplo de carga de una clase en el espacio de nombres
  • Example#3904 - Ejemplo de carga de clase MVC
  • Example#3905 - Distinciones de clases MVC
  • Example#3906 - Ejemplo de carga MVC
  • Example#3907 - Ejemplo de Yaf_Loader::registerNamespace
  • Example#3908 - Ejemplo de Yaf_Loader::registerLocalNamespace
  • Example#3909 - Ejemplo de Yaf_Loader::registerNamespace
  • Example#3910 - Plugin example
  • Example#3911 - Ejemplo de Yaf_Plugin_Abstract::routerShutdown
  • Example#3912 - Ejemplo de Yaf_Response_Abstract::appendBody
  • Example#3913 - Ejemplo de Yaf_Response_Abstract::getBody
  • Example#3914 - Ejemplo de Yaf_Response_Abstract::prependBody
  • Example#3915 - Ejemplo de Yaf_Response_Abstract::response
  • Example#3916 - Ejemplo de Yaf_Response_Abstract::setBody
  • Example#3917 - Ejemplo de Yaf_Route_Map::assemble
  • Example#3918 - Ejemplo de Yaf_Route_Map
  • Example#3919 - Ejemplo de Yaf_Route_Map
  • Example#3920 - Yaf_Route_Mapexample
  • Example#3921 - Ejemplo de Yaf_Route_Regex::assemble
  • Example#3922 - Ejemplo de Yaf_Route_Regex
  • Example#3923 - Ejemplo de Yaf_Route_Regex(como en 2.3.0)
  • Example#3924 - Ejemplo de Yaf_Route_Regex y el nombre de la zona de captura (a partir de 2.3.0)
  • Example#3925 - Ejemplo de Yaf_Route_Regex
  • Example#3926 - Ejemplo de Yaf_Route_Rewrite::assemble
  • Example#3927 - Ejemplo de Yaf_Route_Rewrite
  • Example#3928 - Ejemplo de Yaf_Route_Rewrite
  • Example#3929 - Ejemplo de Yaf_Route_Rewrite (como en 2.3.0)
  • Example#3930 - Regla de reescritura para Apache
  • Example#3931 - Regla de reescritura para Apache
  • Example#3932 - Regla de reescritura para Lighttpd
  • Example#3933 - Regla de reescritura para Nginx
  • Example#3934 - Ejemplo de Yaf_Route_Static (ruta predeterminada)
  • Example#3935 - Ejemplo de application.ini
  • Example#3936 - Ejemplo de Yaf_Dispatcher::autoConfig
  • Example#3937 - Ejemplo de Yaf_Dispatcher::autoRender
  • Example#3938 - Registrar algunas rutas en el Arranque
  • Example#3939 - Complemento Dummy.php (bajo application.directory/plugins)
  • Example#3940 - Ejemplo de Yaf_Route_Simple::assemble
  • Example#3941 - Ejemplo de Yaf_Route_Simple::route
  • Example#3942 - Ejemplo de Yaf_Route_Simple::route
  • Example#3943 - Ejemplo de Yaf_Route_Static::assemble
  • Example#3944 - Ejemplo de Yaf_Route_Static::route
  • Example#3945 - Ejemplo de Yaf_Route_Supervar::assemble
  • Example#3946 - Ejemplo de Yaf_Route_Supervar
  • Example#3947 - INI example
  • Example#3948 - Ejemplo de secciones INI
  • Example#3949 - Ejemplo de INI
  • Example#3950 - Ejemplo de taint
  • Example#3951 - Vector
  • Example#3952 - Map
  • Example#3953 - Ds\Collection::clear example
  • Example#3954 - Ds\Collection::copy example
  • Example#3955 - Ds\Collection::isEmpty example
  • Example#3956 - Ds\Collection::toArray example
  • Example#3957 - Ds\Hashable::hash example
  • Example#3958 - Ds\Sequence::allocate example
  • Example#3959 - Ds\Sequence::apply example
  • Example#3960 - Ds\Sequence::capacity example
  • Example#3961 - Ds\Sequence::contains example
  • Example#3962 - Ds\Sequence::filter example using callback function
  • Example#3963 - Ds\Sequence::filter example without a callback function
  • Example#3964 - Ds\Sequence::find example
  • Example#3965 - Ds\Sequence::first example
  • Example#3966 - Ds\Sequence::get example
  • Example#3967 - Ds\Sequence::get example using array syntax
  • Example#3968 - Ds\Sequence::insert example
  • Example#3969 - Ds\Sequence::join example using a separator string
  • Example#3970 - Ds\Sequence::join example without a separator string
  • Example#3971 - Ds\Sequence::last example
  • Example#3972 - Ds\Sequence::map example
  • Example#3973 - Ds\Sequence::merge example
  • Example#3974 - Ds\Sequence::pop example
  • Example#3975 - Ds\Sequence::push example
  • Example#3976 - Ds\Sequence::reduce with initial value example
  • Example#3977 - Ds\Sequence::reduce without an initial value example
  • Example#3978 - Ds\Sequence::remove example
  • Example#3979 - Ds\Sequence::reverse example
  • Example#3980 - Ds\Sequence::reversed example
  • Example#3981 - Ds\Sequence::rotate example
  • Example#3982 - Ds\Sequence::set example
  • Example#3983 - Ds\Sequence::set example using array syntax
  • Example#3984 - Ds\Sequence::shift example
  • Example#3985 - Ds\Sequence::slice example
  • Example#3986 - Ds\Sequence::sort example
  • Example#3987 - Ds\Sequence::sort example using a comparator
  • Example#3988 - Ds\Sequence::sorted example
  • Example#3989 - Ds\Sequence::sorted example using a comparator
  • Example#3990 - Ds\Sequence::sum integer example
  • Example#3991 - Ds\Sequence::sum float example
  • Example#3992 - Ds\Sequence::unshift example
  • Example#3993 - Ds\Vector::allocate example
  • Example#3994 - Ds\Vector::apply example
  • Example#3995 - Ds\Vector::capacity example
  • Example#3996 - Ds\Vector::clear example
  • Example#3997 - Ds\Vector::__construct example
  • Example#3998 - Ds\Vector::contains example
  • Example#3999 - Ds\Vector::copy example
  • Example#4000 - Ds\Vector::filter example using callback function
  • Example#4001 - Ds\Vector::filter example without a callback function
  • Example#4002 - Ds\Vector::find example
  • Example#4003 - Ds\Vector::first example
  • Example#4004 - Ds\Vector::get example
  • Example#4005 - Ds\Vector::get example using array syntax
  • Example#4006 - Ds\Vector::insert example
  • Example#4007 - Ds\Vector::isEmpty example
  • Example#4008 - Ds\Vector::join example using a separator string
  • Example#4009 - Ds\Vector::join example without a separator string
  • Example#4010 - Ds\Vector::last example
  • Example#4011 - Ds\Vector::map example
  • Example#4012 - Ds\Vector::merge example
  • Example#4013 - Ds\Vector::pop example
  • Example#4014 - Ds\Vector::push example
  • Example#4015 - Ds\Vector::reduce with initial value example
  • Example#4016 - Ds\Vector::reduce without an initial value example
  • Example#4017 - Ds\Vector::remove example
  • Example#4018 - Ds\Vector::reverse example
  • Example#4019 - Ds\Vector::reversed example
  • Example#4020 - Ds\Vector::rotate example
  • Example#4021 - Ds\Vector::set example
  • Example#4022 - Ds\Vector::set example using array syntax
  • Example#4023 - Ds\Vector::shift example
  • Example#4024 - Ds\Vector::slice example
  • Example#4025 - Ds\Vector::sort example
  • Example#4026 - Ds\Vector::sort example using a comparator
  • Example#4027 - Ds\Vector::sorted example
  • Example#4028 - Ds\Vector::sorted example using a comparator
  • Example#4029 - Ds\Vector::sum integer example
  • Example#4030 - Ds\Vector::sum float example
  • Example#4031 - Ds\Vector::toArray example
  • Example#4032 - Ds\Vector::unshift example
  • Example#4033 - Ds\Deque::allocate example
  • Example#4034 - Ds\Deque::apply example
  • Example#4035 - Ds\Deque::capacity example
  • Example#4036 - Ds\Deque::clear example
  • Example#4037 - Ds\Deque::__construct example
  • Example#4038 - Ds\Deque::contains example
  • Example#4039 - Ds\Deque::copy example
  • Example#4040 - Ds\Deque::filter example using callback function
  • Example#4041 - Ds\Deque::filter example without a callback function
  • Example#4042 - Ds\Deque::find example
  • Example#4043 - Ds\Deque::first example
  • Example#4044 - Ds\Deque::get example
  • Example#4045 - Ds\Deque::get example using array syntax
  • Example#4046 - Ds\Deque::insert example
  • Example#4047 - Ds\Deque::isEmpty example
  • Example#4048 - Ds\Deque::join example using a separator string
  • Example#4049 - Ds\Deque::join example without a separator string
  • Example#4050 - Ds\Deque::last example
  • Example#4051 - Ds\Deque::map example
  • Example#4052 - Ds\Deque::merge example
  • Example#4053 - Ds\Deque::pop example
  • Example#4054 - Ds\Deque::push example
  • Example#4055 - Ds\Deque::reduce with initial value example
  • Example#4056 - Ds\Deque::reduce without an initial value example
  • Example#4057 - Ds\Deque::remove example
  • Example#4058 - Ds\Deque::reverse example
  • Example#4059 - Ds\Deque::reversed example
  • Example#4060 - Ds\Deque::rotate example
  • Example#4061 - Ds\Deque::set example
  • Example#4062 - Ds\Deque::set example using array syntax
  • Example#4063 - Ds\Deque::shift example
  • Example#4064 - Ds\Deque::slice example
  • Example#4065 - Ds\Deque::sort example
  • Example#4066 - Ds\Deque::sort example using a comparator
  • Example#4067 - Ds\Deque::sorted example
  • Example#4068 - Ds\Deque::sorted example using a comparator
  • Example#4069 - Ds\Deque::sum integer example
  • Example#4070 - Ds\Deque::sum float example
  • Example#4071 - Ds\Deque::toArray example
  • Example#4072 - Ds\Deque::unshift example
  • Example#4073 - Ds\Map::allocate example
  • Example#4074 - Ds\Map::apply example
  • Example#4075 - Ds\Map::capacity example
  • Example#4076 - Ds\Map::clear example
  • Example#4077 - Ds\Map::__construct example
  • Example#4078 - Ds\Map::copy example
  • Example#4079 - Ds\Map::diff example
  • Example#4080 - Ds\Map::filter example using callback function
  • Example#4081 - Ds\Map::filter example without a callback function
  • Example#4082 - Ds\Map::first example
  • Example#4083 - Ds\Map::get example
  • Example#4084 - Ds\Map::get example using array syntax
  • Example#4085 - Ds\Map::hasKey example
  • Example#4086 - Ds\Map::hasValue example
  • Example#4087 - Ds\Map::intersect example
  • Example#4088 - Ds\Map::isEmpty example
  • Example#4089 - Ds\Map::keys example
  • Example#4090 - Ds\Map::ksort example
  • Example#4091 - Ds\Map::ksort example using a comparator
  • Example#4092 - Ds\Map::ksorted example
  • Example#4093 - Ds\Map::ksorted example using a comparator
  • Example#4094 - Ds\Map::last example
  • Example#4095 - Ds\Map::map example
  • Example#4096 - Ds\Map::merge example
  • Example#4097 - Ds\Map::pairs example
  • Example#4098 - Ds\Map::put example
  • Example#4099 - Ds\Map::put example using objects as keys
  • Example#4100 - Ds\Map::putAll example
  • Example#4101 - Ds\Map::reduce with initial value example
  • Example#4102 - Ds\Map::reduce without an initial value example
  • Example#4103 - Ds\Map::remove example
  • Example#4104 - Ds\Map::reverse example
  • Example#4105 - Ds\Map::reversed example
  • Example#4106 - Ds\Map::skip example
  • Example#4107 - Ds\Map::slice example
  • Example#4108 - Ds\Map::sort example
  • Example#4109 - Ds\Map::sort example using a comparator
  • Example#4110 - Ds\Map::sort example
  • Example#4111 - Ds\Map::sort example using a comparator
  • Example#4112 - Ds\Map::sum integer example
  • Example#4113 - Ds\Map::sum float example
  • Example#4114 - Ds\Map::toArray example
  • Example#4115 - Ds\Map::union example
  • Example#4116 - Ds\Map::values example
  • Example#4117 - Ds\Map::xor example
  • Example#4118 - Ds\Pair::clear example
  • Example#4119 - Ds\Pair::copy example
  • Example#4120 - Ds\Pair::isEmpty example
  • Example#4121 - Ds\Pair::toArray example
  • Example#4122 - Ds\Set::add example using integers
  • Example#4123 - Ds\Set::add example using objects
  • Example#4124 - Ds\Set::allocate example
  • Example#4125 - Ds\Set::capacity example
  • Example#4126 - Ds\Set::clear example
  • Example#4127 - Ds\Set::__construct example
  • Example#4128 - Ds\Set::contains example
  • Example#4129 - Ds\Set::copy example
  • Example#4130 - Ds\Set::diff example
  • Example#4131 - Ds\Set::filter example using callback function
  • Example#4132 - Ds\Set::filter example without a callback function
  • Example#4133 - Ds\Set::first example
  • Example#4134 - Ds\Set::get example
  • Example#4135 - Ds\Set::get example using array syntax
  • Example#4136 - Ds\Set::intersect example
  • Example#4137 - Ds\Set::isEmpty example
  • Example#4138 - Ds\Set::join example using a separator string
  • Example#4139 - Ds\Set::join example without a separator string
  • Example#4140 - Ds\Set::last example
  • Example#4141 - Ds\Set::merge example
  • Example#4142 - Ds\Set::reduce with initial value example
  • Example#4143 - Ds\Set::reduce without an initial value example
  • Example#4144 - Ds\Set::remove example
  • Example#4145 - Ds\Set::reverse example
  • Example#4146 - Ds\Set::reversed example
  • Example#4147 - Ds\Set::slice example
  • Example#4148 - Ds\Set::sort example
  • Example#4149 - Ds\Set::sort example using a comparator
  • Example#4150 - Ds\Set::sorted example
  • Example#4151 - Ds\Set::sorted example using a comparator
  • Example#4152 - Ds\Set::sum integer example
  • Example#4153 - Ds\Set::sum float example
  • Example#4154 - Ds\Set::toArray example
  • Example#4155 - Ds\Set::union example
  • Example#4156 - Ds\Set::xor example
  • Example#4157 - Ds\Stack::clear example
  • Example#4158 - Ds\Stack::__construct example
  • Example#4159 - Ds\Stack::copy example
  • Example#4160 - Ds\Stack::isEmpty example
  • Example#4161 - Ds\Stack::peek example
  • Example#4162 - Ds\Stack::pop example
  • Example#4163 - Ds\Stack::push example
  • Example#4164 - Ds\Stack::toArray example
  • Example#4165 - Ds\Queue::allocate example
  • Example#4166 - Ds\Queue::capacity example
  • Example#4167 - Ds\Queue::clear example
  • Example#4168 - Ds\Queue::__construct example
  • Example#4169 - Ds\Queue::copy example
  • Example#4170 - Ds\Queue::isEmpty example
  • Example#4171 - Ds\Queue::peek example
  • Example#4172 - Ds\Queue::pop example
  • Example#4173 - Ejemplo de Ds\Queue::push
  • Example#4174 - Ejemplo de Ds\Queue::toArray
  • Example#4175 - Ds\PriorityQueue::allocate example
  • Example#4176 - Ds\PriorityQueue::capacity example
  • Example#4177 - Ds\PriorityQueue::clear example
  • Example#4178 - Ds\PriorityQueue::__construct example
  • Example#4179 - Ds\PriorityQueue::copy example
  • Example#4180 - Ds\PriorityQueue::isEmpty example
  • Example#4181 - Ds\PriorityQueue::peek example
  • Example#4182 - Ds\PriorityQueue::pop example
  • Example#4183 - Ds\PriorityQueue::push example
  • Example#4184 - Ds\PriorityQueue::toArray example
  • Example#4185 - var_representation Examples
  • Example#4186 - Escaping control characters
  • Example#4187 - Exporting stdClass
  • Example#4188 - Exporting classes
  • Example#4189 - Using __set_state()
  • Example#4190 - Uso del módulo cURL de PHP para capturar página principal de example.com
  • Example#4191 - Inicializar una nueva sesión CURL y capturar una página web
  • Example#4192 - Copiar un recurso cURL
  • Example#4193 - curl_errno ejemplo
  • Example#4194 - Ejemplo de curl_error
  • Example#4195 - Ejemplo con curl_escape
  • Example#4196 - Capturar una página web
  • Example#4197 - Ejemplo de curl_getinfo
  • Example#4198 - Ejemplo de curl_getinfo con el parámetro opt
  • Example#4199 - Inicia una nueva sesión cURL y captura una página web
  • Example#4200 - curl_multi_add_handle example
  • Example#4201 - curl_multi_close example
  • Example#4202 - curl_multi_exec example
  • Example#4203 - Un ejemplo de curl_multi_info_read
  • Example#4204 - curl_multi_init example
  • Example#4205 - Ejemplo con curl_multi_strerror
  • Example#4206 - Ejemplo con curl_reset
  • Example#4207 - Iniciando una nueva sesión cURL y capturando una página web
  • Example#4208 - O nuestra implementación de curl_setopt_array
  • Example#4209 - Inicializar una nueva sesión de cURL y obtener una página web
  • Example#4210 - Subir un fichero (obsoleto a partir de PHP 5.5.0)
  • Example#4211 - Ejemplo con curl_share_setopt
  • Example#4212 - Ejemplo con curl_share_init
  • Example#4213 - Ejemplo de curl_share_setopt
  • Example#4214 - Ejemplo de curl_errno
  • Example#4215 - Ejemplo de curl_escape
  • Example#4216 - curl_upkeep example
  • Example#4217 - ejemplo de curl_version
  • Example#4218 - Ejemplo con CURLFile::__construct
  • Example#4219 - Simple HTTP client
  • Example#4220 - HTTP client using asynchronous DNS resolver
  • Example#4221 - Echo server
  • Example#4222 - SSL echo server
  • Example#4223 - Signal handler
  • Example#4224 - Use libevent's loop to process requests of `eio' extension
  • Example#4225 - Miscellaneous
  • Example#4226 - Simple HTTP server
  • Example#4227 - Simple HTTPS server
  • Example#4228 - OpenSSL connection
  • Example#4229 - EventHttpConnection::makeRequest example
  • Example#4230 - Connection listener based on a UNIX domain socket
  • Example#4231 - Simple SMTP server
  • Example#4232 - Handling SIGTERM signal
  • Example#4233 - Adding a custom signal
  • Example#4234 - Adding a timer
  • Example#4235 - Ejemplo con EventBase::getFeatures
  • Example#4236 - Ejemplo con EventBase::getMethod
  • Example#4237 - EventBuffer::search example
  • Example#4238 - EventBufferEvent::connect example
  • Example#4239 - Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console
  • Example#4240 - EventBufferEvent::connectHost example
  • Example#4241 - Buffer event's read callback
  • Example#4242 - EventBufferEvent::getOutput example
  • Example#4243 - EventBufferEvent::sslError example
  • Example#4244 - Simple SMTP server
  • Example#4245 - EventConfig::avoidMethod example
  • Example#4246 - EventConfig::__construct example
  • Example#4247 - EventConfig::requireFeatures example
  • Example#4248 - EventHttp::accept example
  • Example#4249 - EventHttp::addServerAlias example
  • Example#4250 - EventHttp::bind example
  • Example#4251 - Simple HTTP server
  • Example#4252 - EventHttp::setCallback example
  • Example#4253 - EventHttp::setDefaultCallback example
  • Example#4254 - EventHttpConnection::makeRequest example
  • Example#4255 - EventHttpConnection::setCloseCallback example
  • Example#4256 - EventHttpRequest::__construct example
  • Example#4257 - EventHttpRequest::sendError example
  • Example#4258 - EventListener::__construct example
  • Example#4259 - EventSslContext::__construct example
  • Example#4260 - Ejemplo FTP
  • Example#4261 - Ejemplo de ftp_alloc
  • Example#4262 - Ejemplo de ftp_cdup
  • Example#4263 - Ejemplo de ftp_chdir
  • Example#4264 - Ejemplo de ftp_chmod
  • Example#4265 - Ejemplo de ftp_close
  • Example#4266 - Ejemplo de ftp_connect
  • Example#4267 - Ejemplo de ftp_delete
  • Example#4268 - Ejemplo de ftp_exec
  • Example#4269 - Ejemplo de ftp_fget
  • Example#4270 - Ejemplo de ftp_fput
  • Example#4271 - Ejemplo de ftp_get_option
  • Example#4272 - Ejemplo de ftp_get
  • Example#4273 - Ejemplo de ftp_login
  • Example#4274 - Ejemplo de ftp_mdtm
  • Example#4275 - Ejemplo de ftp_mkdir
  • Example#4276 - ftp_mlsd example
  • Example#4277 - Ejemplo de ftp_nb_continue
  • Example#4278 - Ejemplo de ftp_nb_fget
  • Example#4279 - Ejemplo de ftp_nb_fput
  • Example#4280 - Ejemplo de ftp_nb_get
  • Example#4281 - Reanudar una descarga con ftp_nb_get
  • Example#4282 - Reanudar una descarga en la posición 100 a un nuevo archivo con ftp_nb_get
  • Example#4283 - Ejemplo de ftp_nb_put
  • Example#4284 - Reanudación de un proceso de carga con ftp_nb_put
  • Example#4285 - Ejemplo de ftp_nlist
  • Example#4286 - Ejemplo de ftp_pasv
  • Example#4287 - Ejemplo de ftp_put
  • Example#4288 - Ejemplo de ftp_pwd
  • Example#4289 - Uso de ftp_raw para iniciar sesión en un servidor FTP de forma manual.
  • Example#4290 - Ejemplo de ftp_rawlist
  • Example#4291 - Ejemplo de ftp_rename
  • Example#4292 - Ejemplo de ftp_rmdir
  • Example#4293 - Ejemplo de ftp_set_option
  • Example#4294 - Envío de un comando SITE a un servidor FTP
  • Example#4295 - Ejemplo de ftp_size
  • Example#4296 - Ejemplo de ftp_ssl_connect
  • Example#4297 - Ejemplo de ftp_systype
  • Example#4298 - Cliente y trabajador básicos en Gearman
  • Example#4299 - Cliente y trabajador básicos en Gearman, trabajo en segundo plano
  • Example#4300 - Cliente y trabajador básicos, enviando tareas
  • Example#4301 - Añadir dos servidores de trabajos
  • Example#4302 - Añade dos servidores de trabajos
  • Example#4303 - Envío básico de dos tareas
  • Example#4304 - Envío básico de dos tareas pasando contexto de la aplicación
  • Example#4305 - Dos tareas, una en segundo plano y la otra no
  • Example#4306 - Una tarea de prioridad alta junto con dos tareas de prioridad normal
  • Example#4307 - Una tarea de baja prioridad junto con dos tareas de prioridad normal
  • Example#4308 - Monitor para el estado de finalización de múltiples tareas en segundo plano
  • Example#4309 - Envío de un trabajo con retorno inmediato
  • Example#4310 - Envío de un trabajo y obtención del estado incremental
  • Example#4311 - Envío y monitorización de un trabajo en segundo plano
  • Example#4312 - Envío de un trabajo sencillo con retorno inmediato
  • Example#4313 - Enviar un trabajo y recuperar el estado incremental
  • Example#4314 - Obtiene el estado de un trabajo en ejecución de larga duración
  • Example#4315 - Monitorización del estado de un trabajo ejecutandose en segundo plano
  • Example#4316 - Sencillo trabajador que usa los datos de contexto de aplicación
  • Example#4317 - Añade servidores Gearman alternativos
  • Example#4318 - Añade dos servidores de trabajo
  • Example#4319 - Ejemplo de GearmanWorker::setId
  • Example#4320 - Un trabajador sencillo con un tiempo de espera de 5 segundos
  • Example#4321 - Running worker in non-blocking mode
  • Example#4322 - GearmanWorker::work example
  • Example#4323 - Testing support for paged result control
  • Example#4324 - Ejemplo de búsqueda LDAP
  • Example#4325 - Ejemplo completo con enlace autenticado
  • Example#4326 - Ejemplo de autenticación
  • Example#4327 - Ejemplo de autenticación anónima
  • Example#4328 - Ejemplo completo de revisión de contraseña
  • Example#4329 - Ejemplo de conexión a un servidor LDAP.
  • Example#4330 - Ejemplo de conexión segura a un servidor LDAP.
  • Example#4331 - Paginación LDAP
  • Example#4332 - Paginación LDAP
  • Example#4333 - Ejemplo de ldap-count-entries
  • Example#4334 - Enumerando todos los mensajes de error de LDAP
  • Example#4335 - Generación y captura de un error
  • Example#4336 - PASSWD extended operation
  • Example#4337 - Whoami extended operation
  • Example#4338 - Mostrar la lista de atributos mantenida por una entrada de directorio en particular
  • Example#4339 - Revisar la versión del protocolo
  • Example#4340 - Listar todos los valores del atributo "correo" para una entrada de directorio
  • Example#4341 - Producir una lista de todas las unidades organizacionales de una organización
  • Example#4342 - Add a telephone number to a contact
  • Example#4343 - Rename a user
  • Example#4344 - Add two e-mail addresses to a user
  • Example#4345 - Change a user's password
  • Example#4346 - Change a user's password (Active Directory)
  • Example#4347 - Ejemplo de ldap_parse_result
  • Example#4348 - Búsqueda LDAP
  • Example#4349 - Establecer la versión del protocolo
  • Example#4350 - Establecer controles del servidor
  • Example#4351 - Clasificador de LDAP
  • Example#4352 - Ejemplos de la extensión memcache extension
  • Example#4353 - Usando el gestor de sesiones de memcache
  • Example#4354 - Ejemplo Memcache::add
  • Example#4355 - Ejemplo Memcache::addServer
  • Example#4356 - Ejemplo Memcache::close
  • Example#4357 - Memcache::connect example
  • Example#4358 - Ejemplo Memcache::decrement
  • Example#4359 - Ejemplo de Memcache::delete
  • Example#4360 - Ejemplo de Memcache::flush
  • Example#4361 - Ejemplo de Memcache::get
  • Example#4362 - Ejemplo de Memcache::getExtendedStats
  • Example#4363 - Ejemplo de Memcache::getServerStatus
  • Example#4364 - Ejemplo de Memcache::getVersion
  • Example#4365 - Ejemplo de Memcache::increment
  • Example#4366 - Ejemplo de Memcache::pconnect
  • Example#4367 - Ejemplo de Memcache::replace
  • Example#4368 - Ejemplo de Memcache::set
  • Example#4369 - Ejemplo de Memcache::set
  • Example#4370 - Ejemplo de Memcache::setCompressThreshold
  • Example#4371 - Ejemplo de Memcache::setServerParams
  • Example#4372 - Ejemplo retrollamada de resultados
  • Example#4373 - Ejemplo de lectura de retrollamada
  • Example#4374 - Ejemplo de Memcached::addServer
  • Example#4375 - Ejemplo de Memcached::addServers
  • Example#4376 - Ejemplo de Memcached::append
  • Example#4377 - Ejemplo de Memcached::cas
  • Example#4378 - Crear un objeto Memcached
  • Example#4379 - Ejemplo de Memcached::decrement
  • Example#4380 - Ejemplo de Memcached::delete
  • Example#4381 - Ejemplo de Memcached::fetch
  • Example#4382 - Ejemplo de Memcached::getDelayed
  • Example#4383 - Ejemplo de Memcached::flush
  • Example#4384 - Ejemplo 1 Memcached::get
  • Example#4385 - Otro ejemplo de Memcached::get
  • Example#4386 - Ejemplo de Memcached::getDelayed
  • Example#4387 - Ejemplo de Memcached::getMulti
  • Example#4388 - Ejemplo de Memcached::GET_PRESERVE_ORDER
  • Example#4389 - Obtener opciones de Memcached
  • Example#4390 - Ejemplo de Memcached::getResultCode
  • Example#4391 - Ejemplo de Memcached::getResultMessage
  • Example#4392 - Ejemplo de Memcached::getServerByKey
  • Example#4393 - Ejemplo de Memcached::getServerList
  • Example#4394 - Ejemplo de Memcached::getStats
  • Example#4395 - Ejemplo de Memcached::getVersion
  • Example#4396 - Ejemplo de Memcached::increment
  • Example#4397 - Ejemplo de Memcached::prepend
  • Example#4398 - Ejemplo de Memcached::set
  • Example#4399 - Ejemplo de Memcached::setByKey
  • Example#4400 - Ejemplo de Memcached::setMulti
  • Example#4401 - Establecer una opción de Memcached
  • Example#4402 - Establecer opciones de Memcached
  • Example#4403 - mqseries_back example
  • Example#4404 - mqseries_begin example
  • Example#4405 - mqseries_close example
  • Example#4406 - mqseries_cmit example
  • Example#4407 - mqseries_conn example
  • Example#4408 - mqseries_connx example
  • Example#4409 - mqseries_connx example using SSL connection & OCSP Responder URL
  • Example#4410 - mqseries_disc example
  • Example#4411 - mqseries_get example
  • Example#4412 - mqseries_inq example
  • Example#4413 - mqseries_open example
  • Example#4414 - mqseries_put example
  • Example#4415 - mqseries_strerror example
  • Example#4416 - Using dns_get_record
  • Example#4417 - Using dns_get_record and DNS_ANY
  • Example#4418 - Ejemplo de fsockopen
  • Example#4419 - Utilización de una conexión UDP
  • Example#4420 - Un ejemplo sencillo de gethostbyaddr
  • Example#4421 - Ejemplo simple de gethostbyname
  • Example#4422 - Ejemplo de gethostbynamel
  • Example#4423 - Un ejemplo simple de gethostname
  • Example#4424 - Ejemplo de getprotobyname
  • Example#4425 - Ejemplo de getservbyname
  • Example#4426 - header_register_callback example
  • Example#4427 - Eliminar un encabezado específico.
  • Example#4428 - Eliminar todos los encabezados previamente establecidos.
  • Example#4429 - Diálogo de descarga
  • Example#4430 - Directivas caché
  • Example#4431 - Ejemplos usando headers_list
  • Example#4432 - Ejemplos usando headers_sent
  • Example#4433 - Empleo de http_response_code en un entorno de servidor web
  • Example#4434 - Empleo de http_response_code en un entorno CLI
  • Example#4435 - Ejemplo de inet_ntop
  • Example#4436 - Ejemplo de inet_pton
  • Example#4437 - Ejemplo de ip2long
  • Example#4438 - Desplegar una dirección IP
  • Example#4439 - Ejemplo de envío con setcookie
  • Example#4440 - Ejemplo de eliminación con setcookie
  • Example#4441 - setcookie y los arrays
  • Example#4442 - Uso de syslog
  • Example#4443 - Procedimiento de utilización de rrd
  • Example#4444 - Procedimiento de utilización de OOP rrd
  • Example#4445 - Ejemplo de RRDGraph::setOptions
  • Example#4446 - Establecer varias opciones de color
  • Example#4447 - Ejemplos de RRDUpdater::update
  • Example#4448 - Fetch instrumented calls
  • Example#4449 - Fetch the list of functions scoutapm will instrument
  • Example#4450 - snmp_get_quick_print example
  • Example#4451 - Using snmp_get_valueretrieval
  • Example#4452 - Using snmp_read_mib
  • Example#4453 - Using snmp_set_enum_print
  • Example#4454 - Using snmprealwalk
  • Example#4455 - Using snmp_set_quick_print
  • Example#4456 - Using snmp_set_valueretrieval
  • Example#4457 - Using snmp2_get
  • Example#4458 - Using snmp2_get_next
  • Example#4459 - Using snmp2_real_walk
  • Example#4460 - Using snmp2_set
  • Example#4461 - Using snmp2_set for setting BITS SNMP object id
  • Example#4462 - snmp2_walk Example
  • Example#4463 - Using snmp3_get
  • Example#4464 - Using snmp3_getnext
  • Example#4465 - Using snmp3_real_walk
  • Example#4466 - Using snmp3_set
  • Example#4467 - Using snmp3_set for setting BITS SNMP object id
  • Example#4468 - snmp3_walk Example
  • Example#4469 - Using snmpget
  • Example#4470 - Using snmpgetnext
  • Example#4471 - Using snmprealwalk
  • Example#4472 - Using snmpset
  • Example#4473 - Using snmpset for setting BITS SNMP object id
  • Example#4474 - snmpwalk Example
  • Example#4475 - snmpwalkoid Example
  • Example#4476 - Ejemplo de SNMP::close
  • Example#4477 - Fetching sysLocation
  • Example#4478 - Single SNMP object
  • Example#4479 - Multiple SNMP objects
  • Example#4480 - Ejemplo de SNMP::getErrno
  • Example#4481 - Ejemplo de SNMP::getError
  • Example#4482 - Single SNMP object
  • Example#4483 - Miltiple SNMP objects
  • Example#4484 - Set single SNMP object id
  • Example#4485 - Set multiple values using single SNMP::set call
  • Example#4486 - Using SNMP::set for setting BITS SNMP object id
  • Example#4487 - SNMP::setSecurity example
  • Example#4488 - SNMP::walk example
  • Example#4489 - suffixAsKey example
  • Example#4490 - Ejemplo de socket: Servidor TCP/IP sencillo
  • Example#4491 - Ejemplo de socket: Cliente TCP/IP sencillo
  • Example#4492 - Using socket_atmark to set the source address
  • Example#4493 - Usar socket_bind para establecer la dirección de origen
  • Example#4494 - Ejemplo de socket_create_pair
  • Example#4495 - Ejemplo IPC de socket_create_pair
  • Example#4496 - Ejemplo de socket_get_option
  • Example#4497 - Ejemplo de socket_import_stream
  • Example#4498 - Un ejemplo de socket_last_error
  • Example#4499 - Un ejemplo de socket_recv
  • Example#4500 - Un ejemplo de socket_recvfrom
  • Example#4501 - Usar null con socket_select
  • Example#4502 - Comprender el resultado de socket_select
  • Example#4503 - Un ejemplo de socket_select
  • Example#4504 - Ejemplo de socket_sendto
  • Example#4505 - Un ejemplo de socket_set_block
  • Example#4506 - Un ejemplo de socket_set_nonblock
  • Example#4507 - Un ejemplo de socket_set_option
  • Example#4508 - Ejemplo de socket_strerror
  • Example#4509 - Authenticating with a ssh agent
  • Example#4510 - Authentication using a public hostkey
  • Example#4511 - Retrieving a list of authentication methods
  • Example#4512 - Authenticating with a password
  • Example#4513 - Authentication using a public key
  • Example#4514 - ssh2_connect
  • Example#4515 - Executing a command
  • Example#4516 - Opening a shell and retrieving the stderr stream associated with it
  • Example#4517 - Checking the fingerprint against a known value
  • Example#4518 - Determining what methods were negotiated
  • Example#4519 - Adding a publickey with ssh2_publickey_add
  • Example#4520 - Listing authorized keys with ssh2_publickey_list
  • Example#4521 - Descargar un fichero mediante SCP
  • Example#4522 - Cargar un fichero via SCP
  • Example#4523 - Changing the mode of a file on a remote server
  • Example#4524 - Stating a symbolic link via SFTP
  • Example#4525 - Creating a directory on a remote server
  • Example#4526 - Reading a symbolic link
  • Example#4527 - Resolving a pathname
  • Example#4528 - Renaming a file via sftp
  • Example#4529 - Removing a directory on a remote server
  • Example#4530 - Stating a file via SFTP
  • Example#4531 - Creating a symbolic link
  • Example#4532 - Deleting a file
  • Example#4533 - Abrir un fichero a través de SFTP
  • Example#4534 - Requesting an interactive shell
  • Example#4535 - Opening a tunnel to an arbitrary host
  • Example#4536 - Estilo orientado a objetos
  • Example#4537 - Estilo por procedimientos
  • Example#4538 - Ejemplo de stomp_connect_error
  • Example#4539 - Ejemplo de stomp_version
  • Example#4540 - Estilo orientado a objetos
  • Example#4541 - Estilo por procedimientos
  • Example#4542 - Estilo orientado a objetos
  • Example#4543 - Estilo por procedimientos
  • Example#4544 - Estilo orientado a objetos
  • Example#4545 - Estilo por procedimientos
  • Example#4546 - Estilo orientado a objetos
  • Example#4547 - Estilo por procedimientos
  • Example#4548 - Estilo orientado a objetos
  • Example#4549 - Estilo por procedimientos
  • Example#4550 - Estilo orientado a objetos
  • Example#4551 - Estilo por procedimientos
  • Example#4552 - Estilo orientado a objetos
  • Example#4553 - Estilo procedural
  • Example#4554 - Estilo orientado a objetos
  • Example#4555 - Estilo por procedimientos
  • Example#4556 - Estilo orientado a objetos
  • Example#4557 - Estilo por procedimientos
  • Example#4558 - Train from array
  • Example#4559 - Train from a file
  • Example#4560 - Ejemplo de svn_add
  • Example#4561 - Ejemplo de autenticación por omisión
  • Example#4562 - Ejemplo de svn_blame
  • Example#4563 - Ejemplo básico
  • Example#4564 - Ejemplo básico
  • Example#4565 - Ejemplo básico
  • Example#4566 - Ejemplo básico
  • Example#4567 - Ejemplo básico
  • Example#4568 - Ejemplo básico
  • Example#4569 - Comparando dos revisiones de una ruta de acceso a repositorio
  • Example#4570 - Comparativa portable de dos ficheros locales
  • Example#4571 - Ejemplo de svn_export
  • Example#4572 - Ejemplo básico
  • Example#4573 - svn_log example
  • Example#4574 - svn_ls example
  • Example#4575 - Ejemplo básico
  • Example#4576 - Ejemplo básico
  • Example#4577 - Denegar todas las conexiones desde localhost
  • Example#4578 - Prohibición de una URL
  • Example#4579 - Obtención de una instantánea de las estadísticas
  • Example#4580 - Lectura del log de varnish en la memoria compartida
  • Example#4581 - ejemplo de VarnishAdmin::__construct
  • Example#4582 - Busqueda Paralela usando YAZ
  • Example#4583 - Configuración del CCL
  • Example#4584 - Análisis CCL
  • Example#4585 - Actualizar registro
  • Example#4586 - Array para registro GRS-1
  • Example#4587 - Trabajar con MARCXML
  • Example#4588 - función PHP que escanea títulos
  • Example#4589 - Query Examples
  • Example#4590 - Criterios de Ordenación
  • Example#4591 - Un ejemplo de ZMQContext
  • Example#4592 - Un ejemplo de ZMQContext
  • Example#4593 - Un ejemplo de ZMQContext
  • Example#4594 - Un ejemplo de ZMQSocket
  • Example#4595 - Un ejemplo de send/recv
  • Example#4596 - Un ejemplo de ZMQPoll
  • Example#4597 - zookeeper_dispatch example #1
  • Example#4598 - zookeeper_dispatch example #2
  • Example#4599 - Zookeeper::addAuth example
  • Example#4600 - Zookeeper::create example
  • Example#4601 - Zookeeper::delete example
  • Example#4602 - Zookeeper::exists example
  • Example#4603 - Zookeeper::get example
  • Example#4604 - Zookeeper::get stat example
  • Example#4605 - Zookeeper::getAcl example
  • Example#4606 - Zookeeper::getChildren example
  • Example#4607 - Zookeeper::set example
  • Example#4608 - Zookeeper::setAcl example
  • Example#4609 - Zookeeper::setDebugLevel example
  • Example#4610 - ZookeeperConfig::add example
  • Example#4611 - ZookeeperConfig::get example
  • Example#4612 - ZookeeperConfig::remove example
  • Example#4613 - ZookeeperConfig::set example
  • Example#4614 - Ejemplo de solr_get_version
  • Example#4615 - Contenido del archivo BootStrap
  • Example#4616 - Añadir un documento al índice
  • Example#4617 - Fusionar un documento con otro documento
  • Example#4618 - Buscar documentos - respuestas de SolrObject
  • Example#4619 - Buscar documentos - respuestas de SolrDocument
  • Example#4620 - Ejemplo sencillo de TermsComponent - básico
  • Example#4621 - Ejemplo sencillo de TermsComponent - usar un prefijo
  • Example#4622 - Ejemplo sencillo de TermsComponent - especificar una frecuencia mínima
  • Example#4623 - Ejemplo sencillo de Facet
  • Example#4624 - Ejemplo sencillo de Facet - con sobrescritura de campo opcional para mincount
  • Example#4625 - Ejemplo de fecha de faceta
  • Example#4626 - Conectar a un Servidor con SSL Habilitado
  • Example#4627 - Colapsar un SolrQuery
  • Example#4628 - Ejemplo de conseguir el tiempo real Solr(RTG) SolrClient::getById
  • Example#4629 - SolrInputDocument::addChildDocument example
  • Example#4630 - SolrInputDocument::addChildDocuments example
  • Example#4631 - Ejemplo de SolrDocument::toArray
  • Example#4632 - Ejemplo de SolrObject::__construct
  • Example#4633 - Ejemplo de SolrObject::offsetUnset
  • Example#4634 - Ejemplo de SolrClient::addDocument
  • Example#4635 - Ejemplo 2 de SolrClient::addDocument
  • Example#4636 - Ejemplo de SolrClient::addDocuments
  • Example#4637 - Ejemplo de SolrClient::__construct
  • Example#4638 - Ejemplo de SolrQuery::deleteByQuery
  • Example#4639 - SolrClient::getById example
  • Example#4640 - SolrClient::getByIds example
  • Example#4641 - Ejemplo de SolrClient::ping
  • Example#4642 - Ejemplo de SolrClient::query
  • Example#4643 - Ejemplo de SolrClient::request
  • Example#4644 - Ejemplo de SolrClient::setResponseWriter
  • Example#4645 - Ejemplo de SolrParams::setParam
  • Example#4646 - Ejemplo de SolrQuery::addFacetField
  • Example#4647 - Ejemplo de SolrQuery::addFacetField
  • Example#4648 - Ejemplo de SolrQuery::addFilterQuery
  • Example#4649 - SolrQuery::addGroupSortField example
  • Example#4650 - SolrQuery::collapse example
  • Example#4651 - SolrQuery::setExpand example
  • Example#4652 - SolrDisMaxQuery::addBigramPhraseField example
  • Example#4653 - SolrDisMaxQuery::addBoostQuery example
  • Example#4654 - SolrDisMaxQuery::addPhraseField example
  • Example#4655 - SolrDisMaxQuery::addQueryField example
  • Example#4656 - SolrDisMaxQuery::addTrigramPhraseField example
  • Example#4657 - SolrDisMaxQuery::addUserField example
  • Example#4658 - SolrDisMaxQuery::__construct example
  • Example#4659 - SolrDisMaxQuery::removeBigramPhraseField example
  • Example#4660 - SolrDisMaxQuery::removeBoostQuery example
  • Example#4661 - SolrDisMaxQuery::removePhraseField example
  • Example#4662 - SolrDisMaxQuery::removeQueryField example
  • Example#4663 - SolrDisMaxQuery::removeTrigramPhraseField example
  • Example#4664 - SolrDisMaxQuery::removeUserField example
  • Example#4665 - SolrDisMaxQuery::setBigramPhraseFields example
  • Example#4666 - SolrDisMaxQuery::setBigramPhraseSlop example
  • Example#4667 - SolrDisMaxQuery::setBoostFunction example
  • Example#4668 - SolrDisMaxQuery::setBoostQuery example
  • Example#4669 - SolrDisMaxQuery::setMinimumMatch example
  • Example#4670 - SolrDisMaxQuery::setPhraseFields example
  • Example#4671 - SolrDisMaxQuery::setPhraseSlop example
  • Example#4672 - SolrDisMaxQuery::setQueryAlt example
  • Example#4673 - SolrDisMaxQuery::setQueryPhraseSlop example
  • Example#4674 - SolrDisMaxQuery::setTieBreaker example
  • Example#4675 - SolrDisMaxQuery::setTrigramPhraseFields example
  • Example#4676 - SolrDisMaxQuery::setTrigramPhraseSlop example
  • Example#4677 - SolrDisMaxQuery::setUserFields example
  • Example#4678 - SolrDisMaxQuery::useDisMaxQueryParser example
  • Example#4679 - SolrDisMaxQuery::useEDisMaxQueryParser example
  • Example#4680 - SolrCollapseFunction::__construct example
  • Example#4681 - SolrCollapseFunction::setHint example
  • Example#4682 - SolrCollapseFunction::setMax example
  • Example#4683 - Desactivar el intérprete de PHP en un directorio utilizando .htaccess
  • Example#4684 - Ejemplo de apache_get_modules
  • Example#4685 - Ejemplo de apache_get_version
  • Example#4686 - Ejemplo de apache_getenv
  • Example#4687 - apache_lookup_uri example
  • Example#4688 - Paso de información entre PHP y Perl
  • Example#4689 - Registro de valores en access.log
  • Example#4690 - Ejemplo de apache_request_headers
  • Example#4691 - Ejemplo de apache_response_headers
  • Example#4692 - Estableciendo una variable de entorno de Apache usando apache_setenv
  • Example#4693 - Ejemplo de getallheaders
  • Example#4694 - Registrar una variable con $_SESSION.
  • Example#4695 - Desregistrar una variable con $_SESSION
  • Example#4696 - Contar el número de peticiones de un sólo usuario
  • Example#4697 - Ejemplo de información
  • Example#4698 - Ejemplo de session_cache_expire
  • Example#4699 - Ejemplo de session_cache_limiter
  • Example#4700 - Ejemplo de session_create_id con session_regenerate_id
  • Example#4701 - Destruir una sesión con $_SESSION
  • Example#4702 - Ejemplo de session_gc para administradores de tareas como cron
  • Example#4703 - Ejemplo de session_gc para un script accesible al usuario
  • Example#4704 - Ejemplo de session_name
  • Example#4705 - Un ejemplo de session_regenerate_id
  • Example#4706 - Gestor de seseiones personalizado: véase el código completo en la sinopsis de SessionHandlerInterface.
  • Example#4707 - Gestor de almacenamiento de sesiones personalizado usando objetos
  • Example#4708 - pagina1.php
  • Example#4709 - pagina2.php
  • Example#4710 - Sobrescribir el tiempo de vida de la cookie
  • Example#4711 - Leer la sesión y cerrarla
  • Example#4712 - Usar SessionHandler para añadir encriptación a los gestores de almacenamiento internos de PHP.
  • Example#4713 - Ejemplo usando SessionHandlerInterface
  • Example#4714 - Tokenize comma separated integer list
  • Example#4715 - Tokenize assign statement
  • Example#4716 - Simple calculator
  • Example#4717 - Parse words out from a sentence
  • Example#4718 - Ejemplos de patrones válidos
  • Example#4719 - Ejemplos de patrones no válidos
  • Example#4720 - Ejemplo comparando preg_filter con preg_replace
  • Example#4721 - Ejemplo de preg_grep
  • Example#4722 - preg_last_error_msg example
  • Example#4723 - Ejemplo de preg_last_error
  • Example#4724 - Obtener todos los números de teléfono de algún texto.
  • Example#4725 - Buscar coincidencias de etiquetas HTML (codicioso)
  • Example#4726 - Usar sub-patrones nominados
  • Example#4727 - Busca la cadena de texto "php"
  • Example#4728 - Busca la palabra "web"
  • Example#4729 - Obtener el nombre de dominio de una URL
  • Example#4730 - Usar sub-patrones nominados
  • Example#4731 - Ejemplo de preg_quote
  • Example#4732 - Poner en cursiva una palabra dentro de un texto
  • Example#4733 - Ejemplo de preg_replace_callback_array
  • Example#4734 - preg_replace_callback y función anónima
  • Example#4735 - Ejemplo de preg_replace_callback
  • Example#4736 - preg_replace_callback usando una estructura recursiva para manejar el código BB encapsulado
  • Example#4737 - Usar retroreferencias seguidas de literales numéricos
  • Example#4738 - Emplear arrays indexados con preg_replace
  • Example#4739 - Sustituir varios valores
  • Example#4740 - Quitar los espacios en blanco
  • Example#4741 - Usar el parámetro count
  • Example#4742 - Ejemplo de preg_split : Obtener las partes de un string de búsqueda
  • Example#4743 - Dividir un string en sus caracteres constituyentes
  • Example#4744 - Dividir un string mediante coincidencias y sus índices
  • Example#4745 - Ejemplo de addcslashes
  • Example#4746 - Un ejemplo de addslashes
  • Example#4747 - chr Ejemplo
  • Example#4748 - Ejemplo de chunk_split
  • Example#4749 - Ejemplo de convert_uudecode
  • Example#4750 - Ejemplo de convert_uuencode
  • Example#4751 - count_chars example
  • Example#4752 - Mostrar una suma de verificación crc32
  • Example#4753 - crypt examples
  • Example#4754 - Using crypt with htpasswd
  • Example#4755 - Using crypt with different hash types
  • Example#4756 - Ejemplos de echo
  • Example#4757 - Ejemplo de explode
  • Example#4758 - Ejemplos de la devolución de explode
  • Example#4759 - Ejemplos del parámetro limit
  • Example#4760 - fprintf: enteros con relleno de ceros
  • Example#4761 - fprintf: dando formato a valores monetarios
  • Example#4762 - Ejemplo de tabla de traducción
  • Example#4763 - Ejemplo de hex2bin
  • Example#4764 - Decodificación de entidades HTML
  • Example#4765 - Un ejemplo de htmlentities
  • Example#4766 - Uso de ENT_IGNORE
  • Example#4767 - Un ejemplo de htmlspecialchars_decode
  • Example#4768 - Ejemplo de htmlspecialchars
  • Example#4769 - Ejemplo de implode
  • Example#4770 - Ejemplo de lcfirst
  • Example#4771 - Ejemplo de levenshtein
  • Example#4772 - Ejemplo de localeconv
  • Example#4773 - Ejemplo de uso de ltrim
  • Example#4774 - Ejemplo de uso de md5_file
  • Example#4775 - Ejemplo de md5
  • Example#4776 - Ejemplo básico de metaphone
  • Example#4777 - Utilizando el parámetro phonemes
  • Example#4778 - Ejemplos de money_format
  • Example#4779 - Usar nl2br
  • Example#4780 - Generar marcado HTML válido utilizando el parámetro is_xhtml
  • Example#4781 - Varios separadores de nueva línea
  • Example#4782 - Ejemplo de number_format
  • Example#4783 - Ejemplo de ord
  • Example#4784 - Examinar los bytes individuales de un string UTF-8
  • Example#4785 - Utilizando parse_str
  • Example#4786 - Ejemplos de print
  • Example#4787 - Ejemplo de uso de rtrim
  • Example#4788 - Ejemplos de setlocale
  • Example#4789 - Ejemplos para Windows de setlocale
  • Example#4790 - Ejemplo de sha1_file
  • Example#4791 - Ejemplo de sha1
  • Example#4792 - Ejemplos de soundex
  • Example#4793 - Intercambio de argumentos
  • Example#4794 - Intercambio de argumentos
  • Example#4795 - Intercambio de argumentos
  • Example#4796 - Intercambio de argumentos
  • Example#4797 - Especificar un carácter de relleno
  • Example#4798 - Especificador de posición con otros especificadores
  • Example#4799 - printf: ejemplos varios
  • Example#4800 - printf: especificadores de string
  • Example#4801 - sprintf: valores de tipo integer rellenados con ceros
  • Example#4802 - sprintf: formato de moneda
  • Example#4803 - sprintf: notación científica
  • Example#4804 - Ejemplo de sscanf
  • Example#4805 - sscanf - using optional parameters
  • Example#4806 - Using the empty string ''
  • Example#4807 - Showing case-sensitivity
  • Example#4808 - Basic str_decrement example
  • Example#4809 - str_decrement example with a carry
  • Example#4810 - Using the empty string ''
  • Example#4811 - Showing case-sensitivity
  • Example#4812 - Basic str_increment example
  • Example#4813 - str_increment example with a carry
  • Example#4814 - Ejemplo de str_ireplace
  • Example#4815 - Ejemplo de str_pad
  • Example#4816 - Ejemplo de str_repeat
  • Example#4817 - Ejemplos básicos de str_replace
  • Example#4818 - Ejemplos de trampas potenciales con str_replace
  • Example#4819 - Ejemplo de str_rot13
  • Example#4820 - Ejemplo de str_shuffle
  • Example#4821 - Ejemplos de uso de str_split
  • Example#4822 - Using the empty string ''
  • Example#4823 - Showing case-sensitivity
  • Example#4824 - Ejemplo de str_word_count
  • Example#4825 - Ejemplo de strcasecmp
  • Example#4826 - Ejemplo de strcmp
  • Example#4827 - Ejemplo de strcspn
  • Example#4828 - Ejemplo de strip_tags
  • Example#4829 - Ejemplos de stripos
  • Example#4830 - Un ejemplo de stripslashes
  • Example#4831 - Utilizando stripslashes en un array
  • Example#4832 - Ejemplo de stristr
  • Example#4833 - Probando si un string se encuentra o no
  • Example#4834 - Utilizando un needle no "string"
  • Example#4835 - Un ejemplo destrlen
  • Example#4836 - Ejemplo de strpbrk
  • Example#4837 - Usando ===
  • Example#4838 - Usando !==
  • Example#4839 - Uso de offset
  • Example#4840 - Ejemplo de strrchr
  • Example#4841 - Invertir una cadena con strrev
  • Example#4842 - Un ejemplo simple de strripos
  • Example#4843 - Verificando si hay una aguja en el pajar
  • Example#4844 - Buscando con desplazamientos
  • Example#4845 - Ejemplo de strspn
  • Example#4846 - Ejemplo de strstr
  • Example#4847 - Ejemplo de strtok
  • Example#4848 - Comportamiento anterior de strtok
  • Example#4849 - Comportamiento nuevo de strtok
  • Example#4850 - Ejemplo de strtolower
  • Example#4851 - Ejemplo de strtoupper
  • Example#4852 - Ejemplo de strtr
  • Example#4853 - Ejemplo de strtr con dos argumentos
  • Example#4854 - Comparación del comportamiento de strtr
  • Example#4855 - Un ejemplo de substr_compare
  • Example#4856 - Ejemplo de substr_count
  • Example#4857 - Ejemplo desubstr_replace
  • Example#4858 - Usando substr_replace para reemplazar múltiples strings de una vez
  • Example#4859 - Usando un start negativo
  • Example#4860 - Usando un length negativo
  • Example#4861 - Uso básico de substr
  • Example#4862 - Comportamiento de casting de substr
  • Example#4863 -
  • Example#4864 - Ejemplo de uso de trim
  • Example#4865 - Uso de trim en valores de un array
  • Example#4866 - Ejemplo de ucfirst
  • Example#4867 - Ejemplo de ucwords
  • Example#4868 - Ejemplo de ucwords con delimitadores personalizados
  • Example#4869 - Ejemplos básicos
  • Example#4870 - Ejemplos básico
  • Example#4871 - vfprintf: números extendidos con ceros
  • Example#4872 - vprintf: zero-padded integers
  • Example#4873 - vsprintf: zero-padded integers
  • Example#4874 - Ejemplo de wordwrap
  • Example#4875 - Ejemplo de wordwrap
  • Example#4876 - Ejemplo de wordwrap
  • Example#4877 - Ejemplo de array_change_key_case
  • Example#4878 - Ejemplo de array_chunk
  • Example#4879 - Obtener la columna de nombres del conjunto de resultados
  • Example#4880 - Obtener la columna de apellidos del conjunto de resultados, indexada por la columna "id"
  • Example#4881 - Obtener la columna de nombres de usuarios de la propiedad pública "nombre_usuario" de un objeto
  • Example#4882 - Obtener la columna de nombres de la propiedad privada "nombre" de un objeto empleando el método mágico __get.
  • Example#4883 - Ejemplo simple de array_combine
  • Example#4884 - Ejemplo de array_count_values
  • Example#4885 - Ejemplo de array_diff_assoc
  • Example#4886 - Ejemplo de array_diff_assoc
  • Example#4887 - Ejemplo de array_diff_key
  • Example#4888 - Ejemplo de array_diff_uassoc
  • Example#4889 - Ejemplo de array_diff_ukey
  • Example#4890 - Ejemplo de array_diff
  • Example#4891 - Ejemplo de array_fill_keys
  • Example#4892 - Ejemplo de array_fill
  • Example#4893 - Ejemplo de array_filter
  • Example#4894 - array_filter sin callback
  • Example#4895 - array_filter con flag
  • Example#4896 - Ejemplo de array_flip
  • Example#4897 - Ejemplo de array_flip : collision
  • Example#4898 - Ejemplo de array_intersect_assoc
  • Example#4899 - Ejemplo de array_intersect_key
  • Example#4900 - Ejemplo de array_intersect_uassoc
  • Example#4901 - Ejemplo de array_intersect_ukey
  • Example#4902 - Ejemplo de array_intersect
  • Example#4903 - array_is_list example
  • Example#4904 - Ejemplo de array_key_exists
  • Example#4905 - array_key_exists vs isset
  • Example#4906 - Uso básico de array_key_first
  • Example#4907 - Ejemplo de array_keys
  • Example#4908 - Ejemplo de array_map
  • Example#4909 - array_map usando una función lambda (desde PHP 5.3.0)
  • Example#4910 - array_map - usando más arrays
  • Example#4911 - Crear un array de arrays
  • Example#4912 - array_map - con claves de tipo string
  • Example#4913 - Ejemplo de array_merge_recursive
  • Example#4914 - Ejemplo de array_merge
  • Example#4915 - Ejemplo de sencillo de array_merge
  • Example#4916 - array_merge con tipos que no son array
  • Example#4917 - Ordenar varios arrays
  • Example#4918 - Ordenar un array multidimensional
  • Example#4919 - Ordenar resultados de una base de datos
  • Example#4920 - Ordenación sin considerar mayúsculas/minúsculas
  • Example#4921 - Ejemplo de array_pad
  • Example#4922 - Ejemplo de array_pop
  • Example#4923 - Ejemplo de array_product
  • Example#4924 - Ejemplo de array_push
  • Example#4925 - Ejemplo de array_rand
  • Example#4926 - Ejemplo de array_reduce
  • Example#4927 - Ejemplo de array_replace_recursive
  • Example#4928 - array_replace_recursive y comportamiento recursivo
  • Example#4929 - Ejemplo de array_replace
  • Example#4930 - Ejemplo de array_reverse
  • Example#4931 - Ejemplo de array_search
  • Example#4932 - Ejemplo de array_shift
  • Example#4933 - Ejemplos de array_slice
  • Example#4934 - Ejemplos de array_splice
  • Example#4935 - Ejemplos de array_splice
  • Example#4936 - Ejemplos de array_sum
  • Example#4937 - Ejemplo de array_udiff_assoc
  • Example#4938 - Ejemplo de array_udiff_uassoc
  • Example#4939 - Ejemplo de array_udiff usando objetos de stdClass
  • Example#4940 - Ejemplo de array_udiff usando objetos de DateTime
  • Example#4941 - Ejemplo de array_uintersect_assoc
  • Example#4942 - Ejemplo de array_uintersect_uassoc
  • Example#4943 - Ejemplo de array_uintersect
  • Example#4944 - Ejemplo de array_unique
  • Example#4945 - array_unique y tipos
  • Example#4946 - Ejemplo de array_unshift
  • Example#4947 - Ejemplo de array_values
  • Example#4948 - Ejemplo de array_walk_recursive
  • Example#4949 - Ejemplo de array_walk
  • Example#4950 - Ejemplo de array
  • Example#4951 - Array con índice automático
  • Example#4952 - array con índice de base 1
  • Example#4953 - Accessing an array inside double quotes
  • Example#4954 - Ejemplo de arsort
  • Example#4955 - Ejemplo de la función asort
  • Example#4956 - Ejemplo de compact
  • Example#4957 - Ejemplo de count
  • Example#4958 - Ejemplo de count recursivo
  • Example#4959 - Ejemplo de uso de current y similares
  • Example#4960 - Ejemplo de each
  • Example#4961 - Atravesar un array con each
  • Example#4962 - Ejemplo de end
  • Example#4963 - Ejemplo de extract
  • Example#4964 - Ejemplo de in_array
  • Example#4965 - Ejemplo de in_array en modo estricto
  • Example#4966 - in_array con un array como aguja
  • Example#4967 - Ejemplo de key
  • Example#4968 - Ejemplo de krsort
  • Example#4969 - Ejemplo de ksort
  • Example#4970 - Ejemplos de list
  • Example#4971 - Un ejemplo del uso de list
  • Example#4972 - Empleo de list anidados
  • Example#4973 - Uso de list con índices de array
  • Example#4974 - list y orden de definiciones de índices
  • Example#4975 - Ejemplo de natcasesort
  • Example#4976 - Ejemplos de natsort demostrando su uso básico
  • Example#4977 - Ejemplos de natsort demostrando trampas potenciales
  • Example#4978 - Ejemplo del uso de next y similares
  • Example#4979 - Ejemplo de uso de prev and friends
  • Example#4980 - Ejemplos de range
  • Example#4981 - Ejemplo de reset
  • Example#4982 - Ejemplo de rsort
  • Example#4983 - Ejemplo de shuffle
  • Example#4984 - Ejemplo de sort
  • Example#4985 - Ejemplo de sort usando la ordenación insensible a mayúsculas/minúsculas natural
  • Example#4986 - Ejemplo básico de uasort
  • Example#4987 - Ejemplo de uksort
  • Example#4988 - Ejemplo de usort
  • Example#4989 - Ejemplo de usort usando un array multidimensional
  • Example#4990 - Ejemplo de usort usando una función miembro de un objeto
  • Example#4991 - Ejemplo de usort usando un cierre para ordenar un array multidimensional
  • Example#4992 - classes.inc
  • Example#4993 - test_script.php
  • Example#4994 - Ejemplo de class_alias
  • Example#4995 - Ejemplo de class_exists
  • Example#4996 - Ejemplo del parámetro autoload
  • Example#4997 - enum_exists example
  • Example#4998 - Usar get_called_class
  • Example#4999 - Ejemplo de get_class_methods
  • Example#5000 - Ejemplo de get_class_vars
  • Example#5001 - get_class_vars y comportamiento de ámbito
  • Example#5002 - Usar get_class
  • Example#5003 - Usar get_class en superclass
  • Example#5004 - Ejemplo de get_declared_classes
  • Example#5005 - Ejemplo de get_declared_interfaces
  • Example#5006 - get_mangled_object_vars example
  • Example#5007 - Uso de get_object_vars
  • Example#5008 - Usar get_parent_class
  • Example#5009 - Ejemplo de interface_exists
  • Example#5010 - Ejemplo de is_a
  • Example#5011 - Usar el operador instanceof en PHP 5
  • Example#5012 - Ejemplo de is_subclass_of
  • Example#5013 - Ejemplo de is_subclass_of usando una interfaz
  • Example#5014 - Ejemplo de method_exists
  • Example#5015 - Ejemplo de method_exists estático
  • Example#5016 - Un ejemplo de property_exists
  • Example#5017 - Un ejemplo de ctype_alnum (usando la localización predeterminada)
  • Example#5018 - Un ejemplo de ctype_alpha (usando la localización predeterminada)
  • Example#5019 - Un ejemplo de ctype_cntrl
  • Example#5020 - Un ejemplo de ctype_digit
  • Example#5021 - Un ejemplo de ctype_digit comparando strings con integers
  • Example#5022 - Un ejemplo de ctype_graph
  • Example#5023 - Un ejemplo de ctype_lower (usando la localidad predeterminada)
  • Example#5024 - Un ejemplo de ctype_print
  • Example#5025 - Un ejemplo de ctype_punct
  • Example#5026 - Un ejemplo de ctype_space
  • Example#5027 - Un ejemplo de ctype_upper (usando la localidad predeterminada)
  • Example#5028 - Un ejemplo de ctype_xdigit
  • Example#5029 - Configuring the default filter to act like htmlspecialchars
  • Example#5030 - Configurar el filtro predeterminado para que actúe como htmlspecialchars
  • Example#5031 - Validación de direcciones de correo con filter_var
  • Example#5032 - Validación de direcciones IP con filter_var
  • Example#5033 - Pasando opciones a filter_var
  • Example#5034 - Saneando y validando direcciones de correo
  • Example#5035 - Configuración de un filtro por omisión
  • Example#5036 - Un ejemplo con filter_input_array
  • Example#5037 - Un ejemplo de filter_input
  • Example#5038 - Ejemplo de filter_list
  • Example#5039 - Ejemplo de filter_var_array
  • Example#5040 - Un ejemplo de filter_var
  • Example#5041 - Ejemplo de call_user_func_array
  • Example#5042 - call_user_func_array usando un nombre de espacio de nombres
  • Example#5043 - Usar una función lambda
  • Example#5044 - Ejemplo de call_user_func y referencias
  • Example#5045 - Ejemplo de call_user_func
  • Example#5046 - call_user_func usando un nombre de espacios de nombres
  • Example#5047 - Usar un método de clase con call_user_func
  • Example#5048 - Usar una función lambda con call_user_func
  • Example#5049 - Crear una función anónima con create_function
  • Example#5050 - Hacer una función de proceso general con create_function
  • Example#5051 - Usar funciones anónimas como funciones de llamada de retorno
  • Example#5052 - Ejemplo de forward_static_call_array
  • Example#5053 - Ejemplo de forward_static_call
  • Example#5054 - Ejemplo de func_get_arg
  • Example#5055 - Ejemplo de func_get_arg antes y después de PHP 5.3
  • Example#5056 - func_get_arg ejemplo de argumentos byref (pasa un objeto como referencia) y byval (pasa un objeto como valor)
  • Example#5057 - Ejemplo de func_get_args
  • Example#5058 - func_get_args ejemplo de argumentos byref (pasa un objeto como referencia) y byval (pasa un objeto como valor)
  • Example#5059 - Ejemplo de func_num_args
  • Example#5060 - Ejemplo de function_exists
  • Example#5061 - Ejemplo de get_defined_functions
  • Example#5062 - Ejemplo de register_shutdown_function
  • Example#5063 - Ejemplo de register_tick_function
  • Example#5064 - Quickhash Example
  • Example#5065 - Quickhash ArrayAccess Example
  • Example#5066 - Quickhash Iterator Example
  • Example#5067 - Quickhash String Values Example
  • Example#5068 - QuickHashIntSet::add example
  • Example#5069 - QuickHashIntSet::__construct example
  • Example#5070 - QuickHashIntSet::delete example
  • Example#5071 - QuickHashIntSet::exists example
  • Example#5072 - QuickHashIntSet::getSize example
  • Example#5073 - QuickHashIntSet::loadFromFile example
  • Example#5074 - QuickHashIntSet::loadFromString example
  • Example#5075 - QuickHashIntSet::saveToFile example
  • Example#5076 - QuickHashIntSet::saveToString example
  • Example#5077 - QuickHashIntHash::add example
  • Example#5078 - QuickHashIntHash::__construct example
  • Example#5079 - QuickHashIntHash::delete example
  • Example#5080 - QuickHashIntHash::exists example
  • Example#5081 - QuickHashIntHash::get example
  • Example#5082 - QuickHashIntHash::getSize example
  • Example#5083 - QuickHash IntHash file format
  • Example#5084 - QuickHash IntHash file format
  • Example#5085 - QuickHashIntHash::loadFromFile example
  • Example#5086 - QuickHashIntHash::loadFromString example
  • Example#5087 - QuickHashIntHash::saveToFile example
  • Example#5088 - QuickHashIntHash::saveToString example
  • Example#5089 - QuickHashIntHash::set example
  • Example#5090 - QuickHashIntHash::update example
  • Example#5091 - QuickHashStringIntHash::add example
  • Example#5092 - QuickHashStringIntHash::__construct example
  • Example#5093 - QuickHashStringIntHash::delete example
  • Example#5094 - QuickHashStringIntHash::get example
  • Example#5095 - QuickHashStringIntHash::getSize example
  • Example#5096 - QuickHash StringIntHash file format
  • Example#5097 - QuickHash IntHash file format
  • Example#5098 - QuickHashStringIntHash::loadFromFile example
  • Example#5099 - QuickHashStringIntHash::loadFromString example
  • Example#5100 - QuickHashStringIntHash::saveToFile example
  • Example#5101 - QuickHashStringIntHash::saveToString example
  • Example#5102 - QuickHashStringIntHash::set example
  • Example#5103 - QuickHashStringIntHash::update example
  • Example#5104 - QuickHashIntStringHash::add example
  • Example#5105 - QuickHashIntStringHash::__construct example
  • Example#5106 - QuickHashIntStringHash::delete example
  • Example#5107 - QuickHashIntStringHash::get example
  • Example#5108 - QuickHashIntStringHash::getSize example
  • Example#5109 - QuickHash IntString file format
  • Example#5110 - QuickHash IntString file format
  • Example#5111 - QuickHashIntStringHash::loadFromFile example
  • Example#5112 - QuickHashIntStringHash::loadFromString example
  • Example#5113 - QuickHashIntStringHash::saveToFile example
  • Example#5114 - QuickHashIntStringHash::saveToString example
  • Example#5115 - QuickHashIntStringHash::set example
  • Example#5116 - QuickHashIntStringHash::update example
  • Example#5117 - Ejemplo de Reflection desde Shell (un terminal)
  • Example#5118 - Extendiendo las clases incorporadas
  • Example#5119 - Funcionamiento básico de ReflectionClass
  • Example#5120 - Uso básico de ReflectionClass::export
  • Example#5121 - Basic usage
  • Example#5122 - Filtering results by class name
  • Example#5123 - Filtering results by class name, with inheritance
  • Example#5124 - Uso básico de ReflectionClass::getConstructor
  • Example#5125 - Ejemplo de ReflectionClass::getDefaultProperties
  • Example#5126 - Ejemplo de ReflectionClass::getDocComment
  • Example#5127 - Ejemplo de ReflectionClass::getEndLine
  • Example#5128 - Uso básico de ReflectionClass::getExtension
  • Example#5129 - Uso básico de ReflectionClass::getExtensionName
  • Example#5130 - Ejemplo de ReflectionClass::getInterfaceNames
  • Example#5131 - Ejemplo de ReflectionClass::getInterfaces
  • Example#5132 - Uso básico de ReflectionClass::getMethod
  • Example#5133 - Uso básico de ReflectionClass::getMethods
  • Example#5134 - Filtrar los resultados de ReflectionClass::getMethods
  • Example#5135 - Ejemplo de ReflectionClass::getName
  • Example#5136 - Ejemplo de ReflectionClass::getNamespaceName
  • Example#5137 - Ejemplo de filtrado con ReflectionClass::getProperties
  • Example#5138 - Uso básico de ReflectionClass::getProperty
  • Example#5139 - Basic ReflectionClass::getReflectionConstants example
  • Example#5140 - Ejemplo de ReflectionClass::getShortName
  • Example#5141 - Uso básico de ReflectionClass::getStaticPropertyValue
  • Example#5142 - Ejemplo de ReflectionClass::hasConstant
  • Example#5143 - Ejemplo de ReflectionClass::hasMethod
  • Example#5144 - Ejemplo de ReflectionClass::hasProperty
  • Example#5145 - Ejemplo de ReflectionClass::inNamespace
  • Example#5146 - Ejemplo de ReflectionClass::isAbstract
  • Example#5147 - ReflectionClass::isAnonymous example
  • Example#5148 - Uso básico de ReflectionClass::isCloneable
  • Example#5149 - Ejemplo de ReflectionClass::isFinal
  • Example#5150 - Ejemplo relacionado con ReflectionClass::isInstance
  • Example#5151 - Ejemplo de ReflectionClass::isInstantiable
  • Example#5152 - Uso básico de ReflectionClass::isInterface
  • Example#5153 - Uso básico de ReflectionClass::isInternal
  • Example#5154 - Basic ReflectionClass::isIterable Usage
  • Example#5155 - Ejemplo de ReflectionClass::isIterateable
  • Example#5156 - ReflectionClass::isReadOnly example
  • Example#5157 - Uso básico de ReflectionClass::newInstanceArgs
  • Example#5158 - Ejemplo de ReflectionClass::__toString
  • Example#5159 - Basic usage
  • Example#5160 - Filtering results by class name
  • Example#5161 - Filtering results by class name, with inheritance
  • Example#5162 - ReflectionClassConstant::isEnumCase example
  • Example#5163 - Ejemplo de ReflectionExtension
  • Example#5164 - Ejemplo de ReflectionExtension::getClasses
  • Example#5165 - Ejemplo de ReflectionExtension::getClassNames
  • Example#5166 - Ejemplo de ReflectionExtension::getConstants
  • Example#5167 - Ejemplo de ReflectionExtension::getDependencies
  • Example#5168 - Ejemplo de ReflectionExtension::getFunctions
  • Example#5169 - Ejemplo de ReflectionExtension::getINIEntries
  • Example#5170 - Ejemplo de ReflectionExtension::getName
  • Example#5171 - Ejemplo de ReflectionExtension::getVersion
  • Example#5172 - Ejemplo de ReflectionExtension::info
  • Example#5173 - Ejemplo de ReflectionFunction::__construct
  • Example#5174 - Ejemplo de ReflectionFunction::invoke example
  • Example#5175 - Ejemplo de ReflectionFunction::invokeArgs
  • Example#5176 - Ejemplo de ReflectionFunction::invokeArgs con argumentos por referencia
  • Example#5177 - ReflectionFunction::isAnonymous example
  • Example#5178 - Ejemplo de ReflectionFunction::__toString
  • Example#5179 - Basic usage with a class method
  • Example#5180 - Basic usage with a function
  • Example#5181 - Filtering results by class name
  • Example#5182 - Filtering results by class name, with inheritance
  • Example#5183 - ReflectionFunctionAbstract::getClosureUsedVariables example
  • Example#5184 - ReflectionFunctionAbstract::getReturnType example
  • Example#5185 - Usage on built-in functions
  • Example#5186 - ReflectionFunctionAbstract::getTentativeReturnType example
  • Example#5187 - ReflectionFunctionAbstract::hasReturnType example
  • Example#5188 - Usage on built-in functions
  • Example#5189 - Ejemplo de ReflectionFunctionAbstract::hasTentativeReturnType
  • Example#5190 - Ejemplo de ReflectionFunctionAbstract::isClosure
  • Example#5191 - Ejemplo de ReflectionFunctionAbstract::isDeprecated
  • Example#5192 - Ejemplo de ReflectionMethod::__construct
  • Example#5193 - ReflectionMethod::createFromMethodName example
  • Example#5194 - Ejemplo de ReflectionMethod::getDeclaringClass
  • Example#5195 - Ejemplo de ReflectionMethod::getModifiers
  • Example#5196 - Ejemplo de ReflectionMethod::getPrototype
  • Example#5197 - ReflectionMethod::hasPrototype example
  • Example#5198 - Ejemplo de ReflectionMethod::invoke
  • Example#5199 - Ejemplo de ReflectionMethod::invokeArgs
  • Example#5200 - Ejemplo de ReflectionMethod::__toString
  • Example#5201 - ReflectionNamedType::isBuiltin example
  • Example#5202 - Usando la clase ReflectionParameter
  • Example#5203 - Basic usage
  • Example#5204 - Filtering results by class name
  • Example#5205 - Filtering results by class name, with inheritance
  • Example#5206 - Utilizar la clase ReflectionParameter
  • Example#5207 - Obtener la clase que declaró el método
  • Example#5208 - Obtención de los valores por defecto de los parámetros de la función
  • Example#5209 - ReflectionParameter::getType Usage as of PHP 7.1.0
  • Example#5210 - ReflectionParameter::getType Usage before PHP 7.1.0
  • Example#5211 - ReflectionParameter::getType Usage in PHP 8.0.0 and later
  • Example#5212 - ReflectionParameter::hasType example
  • Example#5213 - Ejemplo de ReflectionProperty::__construct
  • Example#5214 - Obtener el valor de propiedades privadas y protegidas con ReflectionProperty
  • Example#5215 - Basic usage
  • Example#5216 - Filtering results by class name
  • Example#5217 - Filtering results by class name, with inheritance
  • Example#5218 - ReflectionProperty::getDefaultValue example
  • Example#5219 - Ejemplo de ReflectionProperty::getDocComment
  • Example#5220 - ReflectionProperty::getType example
  • Example#5221 - Ejemplo de ReflectionProperty::getValue
  • Example#5222 - ReflectionProperty::hasDefaultValue example
  • Example#5223 - ReflectionProperty::hasType example
  • Example#5224 - Ejemplo de ReflectionClass::isDefault
  • Example#5225 - ReflectionProperty::isInitialized example
  • Example#5226 - ReflectionProperty::isPromoted example
  • Example#5227 - Ejemplo de ReflectionProperty::setValue
  • Example#5228 - ReflectionType::allowsNull example
  • Example#5229 - ReflectionType::__toString example
  • Example#5230 - ReflectionUnionType::getTypes example
  • Example#5231 - ReflectionGenerator::__construct example
  • Example#5232 - ReflectionGenerator::getExecutingFile example
  • Example#5233 - ReflectionGenerator::getExecutingGenerator example
  • Example#5234 - ReflectionGenerator::getExecutingLine example
  • Example#5235 - ReflectionGenerator::getFunction example
  • Example#5236 - ReflectionGenerator::getThis example
  • Example#5237 - ReflectionGenerator::getTrace example
  • Example#5238 - Basic ReflectionReference::getId usage
  • Example#5239 - Ejemplos de boolval
  • Example#5240 - Ejemplo debug_zval_dump
  • Example#5241 -
  • Example#5242 -
  • Example#5243 - Una simple comparación empty / isset
  • Example#5244 - empty en índices de string
  • Example#5245 - Ejemplo de floatval
  • Example#5246 - Ejemplo de floatval con caracteres a la izquierda no numéricos
  • Example#5247 - get_debug_type example
  • Example#5248 - Ejemplo de get_defined_vars
  • Example#5249 - get_resource_id produces the same result as an int cast
  • Example#5250 - Ejemplo deget_resource_type
  • Example#5251 - Ejemplo de gettype
  • Example#5252 - Ejemplos de intval
  • Example#5253 - Comprobar que la variable es un array
  • Example#5254 - Ejemplos de is_bool
  • Example#5255 - Ejemplo de is_callable
  • Example#5256 - Función is_callable y constructores
  • Example#5257 - ejemplos de is_countable
  • Example#5258 - Ejemplo de is_float
  • Example#5259 - Ejemplo de is_int
  • Example#5260 - ejemplos de is_iterable
  • Example#5261 - Ejemplo is_null
  • Example#5262 - Ejemplos de is_numeric
  • Example#5263 - Ejemplo is_object
  • Example#5264 - Ejemplo de is_resource
  • Example#5265 - Ejemplo is_scalar
  • Example#5266 - Ejemplo is_string
  • Example#5267 - Ejemplos isset
  • Example#5268 - isset en indices de String
  • Example#5269 - Ejemplo print_r
  • Example#5270 - Ejemplo del parámetro devolver
  • Example#5271 - Ejemplo serialize
  • Example#5272 - Ejemplo settype
  • Example#5273 - strval usando el método mágico __toString() de PHP 5
  • Example#5274 - Ejemplo de unserialize
  • Example#5275 - Ejemplo de unserialize_callback_func
  • Example#5276 - Ejemplo de unset
  • Example#5277 - Usando el forzado a (unset)
  • Example#5278 - Ejemplo var_dump
  • Example#5279 - Ejemplos de var_export
  • Example#5280 - Exportación de clases a partir de PHP 5.1.0
  • Example#5281 - Uso de __set_state (a partir de PHP 5.1.0)
  • Example#5282 -
  • Example#5283 - Ejemplo de OAuth::fetch
  • Example#5284 - Ejemplo de OAuth::getAccessToken
  • Example#5285 - Ejemplo de OAuth::getRequestToken
  • Example#5286 - Ejemplo de OAuth::setRequestEngine
  • Example#5287 - Ejemplo de OAuth::setRsaCertificate
  • Example#5288 - Ejemplo OAuth::setToken
  • Example#5289 - Ejemplo de OAuthProvider::__construct
  • Example#5290 - Ejemplo del callback OAuthProvider::consumerHandler
  • Example#5291 - Ejemplo de OAuthProvider::generateToken
  • Example#5292 - Ejemplo de OAuthProvider::is2LeggedEndpoint
  • Example#5293 - Ejemplo de OAuthProvider::timestampNonceHandler
  • Example#5294 - Ejemplo del callback OAuthProvider::tokenHandler
  • Example#5295 - Ejemplo de is_soap_fault
  • Example#5296 - El método estándar de SOAP para el informe de errores con las excepciones
  • Example#5297 - Ejemplo de SoapClient::__doRequest
  • Example#5298 - Ejemplo de SoapClient::__getFunctions
  • Example#5299 - Ejemplo de SoapClient::__getLastRequest()
  • Example#5300 - Ejemplo de SoapClient::__getLastRequestHeaders()
  • Example#5301 - Ejemplo de SoapClient::__getLastResponse()
  • Example#5302 - Ejemplo de SoapClient::__getLastResponse()
  • Example#5303 - Ejemplo de SoapClient::__getTypes
  • Example#5304 - Ejemplo de SoapClient::__setLocation
  • Example#5305 - Ejemplo de SoapClient::__setSoapHeaders
  • Example#5306 - Definir múltiples encabezados
  • Example#5307 - Ejemplo de SoapClient::__soapCall
  • Example#5308 - Ejemplos de SoapServer::addFunction
  • Example#5309 - Ejemplo de SoapServer::getFunctions
  • Example#5310 - Ejemplo de SoapServer::handle
  • Example#5311 - Ejemplo de SoapServer::setPersistence
  • Example#5312 - Ejemplo de servidor de Yar
  • Example#5313 - Acceder al servidor desde el navegador (petición GET)
  • Example#5314 - Ejemplo de cliente de Yar
  • Example#5315 - Ejemplo de cliente concurrente de Yar
  • Example#5316 - Ejemplo de Yar_Server::__construct
  • Example#5317 - Ejemplo de Yar_Server::handle
  • Example#5318 - Ejemplo de Yar_Client::__call
  • Example#5319 - Ejemplo de Yar_Client::__construct
  • Example#5320 - Ejemplo de Yar_Client::setOpt
  • Example#5321 - Ejemplo de Yar_Concurrent_Client::call
  • Example#5322 - Ejemplo de Yar_Concurrent_Client::loop
  • Example#5323 - Ejemplo de Yar_Concurrent_Client::reset
  • Example#5324 - Ejemplo de Yar_Server_Exception::getType
  • Example#5325 - Ejemplo de Yar_Client_Exception::getType
  • Example#5326 - Ejmeplo de las funciones de clietes de XMLRPC
  • Example#5327 - Ejemplo de tipo de XML-RPC
  • Example#5328 - A xmlrpc_set_type example
  • Example#5329 - For Each en ASP
  • Example#5330 - while() ... Next() en PHP 4
  • Example#5331 - foreach en PHP 5
  • Example#5332 - Ejemplo COM (1)
  • Example#5333 - Ejemplo COM (2)
  • Example#5334 - Ejemplo DOTNET
  • Example#5335 - Ejemplo de una clase VARIANT, utilizada en PHP 4.x
  • Example#5336 - Ejemplo de una clase VARIANT, utilizada en PHP 5
  • Example#5337 - Basic COMPersistHelper::saveToFile Usage
  • Example#5338 - Ejemplo de absorción de un evento COM
  • Example#5339 - Registrar un script de PHP para ejecutarlo como un servicio
  • Example#5340 - Dejar de registrar un servicio
  • Example#5341 - Ejecutar como un servicio
  • Example#5342 - Un ejemplo de win32_create_service
  • Example#5343 - Un ejemplo de win32_delete_service
  • Example#5344 - Un ejemplo de win32_start_service_ctrl_dispatcher
  • Example#5345 - book.xml
  • Example#5346 - Creación de un nuevo objeto DOMAttr
  • Example#5347 - Ejemplo de DOMAttr::isId()
  • Example#5348 - Crear un nuevo objeto DOMCdataSection
  • Example#5349 - DOMCharacterData::after example
  • Example#5350 - DOMCharacterData::before example
  • Example#5351 - DOMCharacterData::remove example
  • Example#5352 - DOMCharacterData::replaceWith example
  • Example#5353 - Creando un nuevo DOMComment
  • Example#5354 - DOMDocument::adoptNode example
  • Example#5355 - DOMDocument::append example
  • Example#5356 - Creando un nuevo DOMDocument
  • Example#5357 - Crear un nuevo elemento e insertarlo como raíz
  • Example#5358 - Pasando texto que contiene un & sin escapar como valor
  • Example#5359 - Crear un nuevo elemento e insertarlo como raíz
  • Example#5360 - Un ejemplo de prefijo de nombre de espacio
  • Example#5361 - Ejemplo de DOMDocument::getElementById()
  • Example#5362 - Ejemplo de uso básico
  • Example#5363 - Obtener todos los elementos XInclude
  • Example#5364 - DOMDocument::importNode ejemplo
  • Example#5365 - Creando un Documento
  • Example#5366 - Creando un Documento
  • Example#5367 - Crear un Documento
  • Example#5368 - Crear un Documento
  • Example#5369 - Invocación estática de loadXML
  • Example#5370 - DOMDocument::prepend example
  • Example#5371 - Añadir un nuevo método a DOMElement para facilitar su código
  • Example#5372 - Recuperar elementos como clase personalizada
  • Example#5373 - Recuperar un propio documento
  • Example#5374 - DOMDocument::replaceChildren example
  • Example#5375 - Guardar un árbol DOM en un fichero
  • Example#5376 - Salvar un árbol HTML en una cadena
  • Example#5377 - Guardar un árbol HTML en un archivo
  • Example#5378 - Guardar un árbol DOM en un string
  • Example#5379 - Ejemplo de validación de DTD
  • Example#5380 - Ejemplo de DOMDocument::xinclude()
  • Example#5381 - DOMDocumentFragment::append example
  • Example#5382 - Añadir información XML a su documento
  • Example#5383 - DOMDocumentFragment::prepend example
  • Example#5384 - DOMDocumentFragment::replaceChildren example
  • Example#5385 - DOMElement::after example
  • Example#5386 - DOMElement::append example
  • Example#5387 - DOMElement::before example
  • Example#5388 - Crear un nuevo objeto DOMElement
  • Example#5389 - DOMElement::getAttributeNames example
  • Example#5390 - DOMElement::insertAdjacentElement example
  • Example#5391 - DOMElement::insertAdjacentText example
  • Example#5392 - DOMElement::prepend example
  • Example#5393 - DOMElement::remove example
  • Example#5394 - DOMElement::replaceChildren example
  • Example#5395 - DOMElement::replaceWith example
  • Example#5396 - Establecer un atributo
  • Example#5397 - DOMElement::toggleAttribute example
  • Example#5398 - Crear un nuevo objeto DOMEntityReference
  • Example#5399 - Crear un documento con un DTD adjunto
  • Example#5400 - Comprobar su Implementación DOM
  • Example#5401 - Añadiendo un hijo
  • Example#5402 - Hijos anidados
  • Example#5403 - DOMNode::contains example
  • Example#5404 - Ejemplo de DOMNode::getLineNo
  • Example#5405 - Ejemplo de DOMNode::getNodePath
  • Example#5406 - DOMNode::getRootNode example
  • Example#5407 - DOMNode::isEqualNode example
  • Example#5408 - Eliminar un hijo
  • Example#5409 - Atravesar todas las entradas de una tabla
  • Example#5410 - Crear un nuevo objeto DOMProcessingInstruction
  • Example#5411 - Crear un nuevo objeto DOMText
  • Example#5412 - Obtener el número de todos los libros en inglés
  • Example#5413 - Obtener todos los libros en inglés
  • Example#5414 - book.xml
  • Example#5415 - DOMXPath::registerPHPFunctions con php:functionString
  • Example#5416 - DOMXPath::registerPHPFunctions con php:function
  • Example#5417 - Importar SimpleXML a DOM con dom_import_simplexml
  • Example#5418 - Ejemplo de libxml_get_errors
  • Example#5419 - Ejemplo de libxml_set_external_entity_loader
  • Example#5420 - Ejemplo de libxml_set_streams_context
  • Example#5421 - Ejemplo de libxml_use_internal_errors
  • Example#5422 - El fichero ejemplo.php a incluir con el string XML
  • Example#5423 - Obtener <argumento>
  • Example#5424 - Obtener <frase>
  • Example#5425 - Acceder a elementos no únicos en SimpleXML
  • Example#5426 - Utilizar atributos
  • Example#5427 - Comparar elementos y atributos con texto
  • Example#5428 - Comparar dos elementos
  • Example#5429 - Utilizar XPath
  • Example#5430 - Establecer valores
  • Example#5431 - Añadir elementos y atributos
  • Example#5432 - Interoperatibilidad con DOM
  • Example#5433 - Cargar un string XML erróneo
  • Example#5434 - Añadir atributos e hijos a un elemento SimpleXML
  • Example#5435 - Añade atributos e hijos a un elemento SimpleXML
  • Example#5436 - Retornar XML
  • Example#5437 - Usando asXML() en resultados SimpleXMLElement::xpath
  • Example#5438 - Interpreta un string XML
  • Example#5439 - Recorre el pseudo-array children()
  • Example#5440 - Usando espacio de nombres
  • Example#5441 - Crea un objeto SimpleXMLElement
  • Example#5442 - Crea un objeto SimpleXMLElement a partir de una URL
  • Example#5443 - Cuenta el número de hijos
  • Example#5444 - Return the current element
  • Example#5445 - Obtener los espacios de nombres del documento
  • Example#5446 - Trabajando con múltiples espacios de nombre
  • Example#5447 - Retornar el nombre del elemento XML
  • Example#5448 - Obtener el nombre de espacio del documento en uso
  • Example#5449 - Return the sub-elements of the current element
  • Example#5450 - Check whether the current element has sub-elements
  • Example#5451 - Get the current XML tag key
  • Example#5452 - Move to the next element
  • Example#5453 - Estableciendo un prefijo para el namespace a usar en una petición XPath
  • Example#5454 - Rewind to the first element
  • Example#5455 - Get string content
  • Example#5456 - Check whether the current element is valid
  • Example#5457 - Xpath
  • Example#5458 - Importando desde DOM
  • Example#5459 - Interpreta un documento XML
  • Example#5460 - Interpreta un string XML
  • Example#5461 - Serializing a single value with WDDX
  • Example#5462 - Using incremental packets with WDDX
  • Example#5463 - wddx_serialize_vars example
  • Example#5464 - Mostrar la estructura de elementos XML
  • Example#5465 - Asignar XML a HTML
  • Example#5466 - Ejemplo de entidades XML externas
  • Example#5467 - xmltest.xml
  • Example#5468 - xmltest2.xml
  • Example#5469 - Ejemplo de xml_parse_into_struct
  • Example#5470 - moldb.xml - pequeña base de datos de información molecular
  • Example#5471 - parsemoldb.php - interpreta moldb.xml dentro de un array de objetos moleculares
  • Example#5472 - Ejemplo xml_set_object
  • Example#5473 - Validando el XML
  • Example#5474 - Crear un simple documento XML
  • Example#5475 - Trabajar con espacios de nombres XML
  • Example#5476 - Trabajando con el OO API
  • Example#5477 - collection.xml
  • Example#5478 - collection.xsl
  • Example#5479 - fruits.xml
  • Example#5480 - fruits.xsl
  • Example#5481 - Errores de compaginación e impresión
  • Example#5482 - Creando un XSLTProcessor
  • Example#5483 - Comprobando si tiene EXSLT
  • Example#5484 - Sencilla llamada a una función de PHP desde una hoja de estilos
  • Example#5485 - Changing the owner before the transformation
  • Example#5486 - Ejemplo de salida de información
  • Example#5487 - Transformando en un DOMDocument
  • Example#5488 - Transformando a un fichero HTML
  • Example#5489 - Transformando a un string
  • Example#5490 - Un elemento oculto de un formulario HTML
  • Example#5491 - Datos a editar por el usuario
  • Example#5492 - En un URL
  • Example#5493 - Generación de Javascript con PHP
  • Example#5494 - Ejemplo de Código PHP/FI
  • Example#5495 - Activar la notificación completa de errores por pantalla para el dominio dev.
  • Example#5496 - Añadir un script de seguridad para aréas protegidas
  • Example#5497 - include_path en Unix
  • Example#5498 - include_path en Windows
  • Example#5499 - include_path en Unix usando la variable de entorno ${USER}
  • Example#5500 - string.rot13
  • Example#5501 - string.toupper
  • Example#5502 - string.tolower
  • Example#5503 - string.strip_tags
  • Example#5504 - convert.base64-encode & convert.base64-decode
  • Example#5505 - convert.quoted-printable-encode & convert.quoted-printable-decode
  • Example#5506 - convert.iconv.*
  • Example#5507 - zlib.deflate y zlib.inflate
  • Example#5508 - zlib.deflate simple
  • Example#5509 - bzip2.compress y bzip2.decompress
  • Example#5510 - Encriptar/Desencriptar con Blowfish
  • Example#5511 - 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

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.