Performs a logical exclusion on two variants

  • « variant_sub
  • win32service »
  • PHP Manual
  • COM Funções
  • Performs a logical exclusion on two variants

variant_xor

(PHP 5, PHP 7, PHP 8)

variant_xor — Performs a logical exclusion on two variants

Descrição

variant_xor(mixed $left, mixed $right): variant

Performs a logical exclusion.

Parâmetros

left

The left operand.

right

The right operand.

Nota:

Assim como todas as funções aritméticas variantes, os parâmetros para esta função podem ser um tipo nativo do PHP (inteiro, string, ponto flutuante, booleano ou null) ou uma instância de uma classe COM, VARIANT ou DOTNET. Tipos nativos do PHP serão convertidos em variantes usando as mesmas regras encontradas no construtor da classe variant. Objetos COM e DOTNET terão o valor de sua propriedade padrão obtido e usado como o valor da variante.

As funções aritméticas variantes são wrappers para funções com nomes semelhantes na biblioteca COM; para mais informações sobre estas funções, consulte a biblioteca MSDN. As funções do PHP são nomeadas de forma ligeiramente diferente; por exemplo, variant_add() no PHP corresponde a VarAdd() na documentação da MSDN.

Valor Retornado

Variant XOR Rules
If left is | If right is | then the result is
true | true | false
true | false | true
false | true | true
false | false | false
null | null | null

Erros

Throws a com_exception on failure.

Veja Também

  • variant_or() - Performs a logical disjunction on two variants
  • variant_and() - Performs a bitwise AND operation between two variants

User Contributed Notes

tinelbarb at yahoo dot com 30-Aug-2010 12:21
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)
tinelbarb at yahoo dot com 30-Aug-2010 12:20
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)
tinelbarb at yahoo dot com dot RE-MO-VE dot ME 30-Aug-2010 12:20
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)


win32service

  • Introdução
  • Instalação/Configuração
    • Dependências
    • Instalação
    • Configurações em Execução
    • Tipos de Recurso
    • Security consideration
  • Constantes pré-definidas
    • Win32Service Service Type Bitmasks
    • Win32Service Service Status Constants
    • Win32Service Service Control Message Constants
    • Win32Service Service Control Message Accepted Bitmasks
    • Win32Service Service Start Type Constants
    • Win32Service Service Error Control Constants
    • Win32Service Service Flag Constants
    • Win32 Error Codes
    • Win32 Base Priority Classes
    • Win32 Recovery action
    • Win32 Service informations
  • Win32ServiceException — The Win32ServiceException class
  • Exemplos
  • win32service Funções
    • win32_continue_service — Resumes a paused service
    • win32_create_service — Creates a new service entry in the SCM database
    • win32_delete_service — Deletes a service entry from the SCM database
    • win32_get_last_control_message — Returns the last control message that was sent to this service
    • win32_pause_service — Pauses a service
    • win32_query_service_status — Queries the status of a service
    • win32_send_custom_control — Send a custom control to the service
    • win32_set_service_exit_code — Define or return the exit code for the current running service
    • win32_set_service_exit_mode — Define or return the exit mode for the current running service
    • win32_set_service_status — Update the service status
    • win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name
    • win32_start_service — Starts a service
    • win32_stop_service — Stops a service

User Contributed Notes

jbnahan at php dot net 12-Jun-2019 11:45
The version 0.4 allow now to send and receive a custom control code.


Introdução

The win32service extension is a Windows specific extension that allows PHP to communicate with the Service Control Manager to start, stop, register and unregister services, and even allows your PHP scripts to run as a service.

User Contributed Notes

There are no user contributed notes for this page.


Instalação/Configuração

Índice

  • Dependências
  • Instalação
  • Configurações em Execução
  • Tipos de Recurso
  • Security consideration

User Contributed Notes

There are no user contributed notes for this page.


Dependências

The versions of Windows supported are the same as the Visual C++ redistributable package used to build PHP.

User Contributed Notes

There are no user contributed notes for this page.


Instalação

Informações para instalar esta extensão PECL podem ser encontradas no capítulo Instalação de Extensões PECL do manual. Informações adicionais, como novas versões, downloads, arquivos fontes, informações do mantenedor e um CHANGELOG, podem ser encontradas aqui: » https://pecl.php.net/package/win32service

User Contributed Notes

alphp 10-Jan-2017 03:08
Para actualizar esta extensión a PHP-7 se está trabajando en https://github.com/win32service/win32service
Ya ha disponibles algunos binarios para poder probar.

To update this extension to PHP-7 is working at https://github.com/win32service/win32service
Some binaries have already been available for testing.


Security consideration

This extension needs administrator privileges for some actions such as create, delete, start, stop, pause and continue. This requirement can cause an elevation of privileges if the service control is available from the web interface or remote control.

You can set the ACL on the service after adding it into SCM to delegate the current administration tasks to an non administrator account or service account. For further instructions, see the » Microsoft Knowledge Base.

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-definidas

Índice

  • Win32Service Service Type Bitmasks
  • Win32Service Service Status Constants
  • Win32Service Service Control Message Constants
  • Win32Service Service Control Message Accepted Bitmasks
  • Win32Service Service Start Type Constants
  • Win32Service Service Error Control Constants
  • Win32Service Service Flag Constants
  • Win32 Error Codes
  • Win32 Base Priority Classes
  • Win32 Recovery action
  • Win32 Service informations

As contantes abaixo são definidas por esta extensão e só estarão disponíveis quando a extensão tiver sido compilada no PHP ou tiver sido carregada dinamicamente em tempo de execução.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Type Bitmasks

  • « Constantes pré-definidas
  • Win32Service Service Status Constants »
  • PHP Manual
  • Constantes pré-definidas
  • Win32Service Service Type Bitmasks
Win32Service Service Type Bitmasks
Constant | Value | Description
WIN32_SERVICE_WIN32_OWN_PROCESS | 0x00000010 | The service runs in its own process.
WIN32_SERVICE_INTERACTIVE_PROCESS | 0x00000100 | The service can interact with the desktop. This option is not available on Windows Vista or later.
WIN32_SERVICE_WIN32_OWN_PROCESS_INTERACTIVE | 0x00000110 | The service runs in its own process and can interact with the desktop. This option is not available on Windows Vista or later.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Status Constants

  • « Win32Service Service Type Bitmasks
  • Win32Service Service Control Message Constants »
  • PHP Manual
  • Constantes pré-definidas
  • Win32Service Service Status Constants
Win32Service Service Status Constants
Constant | Value | Description
WIN32_SERVICE_CONTINUE_PENDING | 0x00000005 | The service continue is pending.
WIN32_SERVICE_PAUSE_PENDING | 0x00000006 | The service pause is pending.
WIN32_SERVICE_PAUSED | 0x00000007 | The service is paused.
WIN32_SERVICE_RUNNING | 0x00000004 | The service is running.
WIN32_SERVICE_START_PENDING | 0x00000002 | The service is starting.
WIN32_SERVICE_STOP_PENDING | 0x00000003 | The service is stopping.
WIN32_SERVICE_STOPPED | 0x00000001 | The service is not running.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Control Message Constants

  • « Win32Service Service Status Constants
  • Win32Service Service Control Message Accepted Bitmasks »
  • PHP Manual
  • Constantes pré-definidas
  • Win32Service Service Control Message Constants
Win32Service Service Control Message Constants
Constant | Value | Description
WIN32_SERVICE_CONTROL_CONTINUE | 0x00000003 | Notifies a paused service that it should resume.
WIN32_SERVICE_CONTROL_DEVICEEVENT | 0x0000000B |
WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE | 0x0000000C |
WIN32_SERVICE_CONTROL_INTERROGATE | 0x00000004 | Notifies a service that it should report its current status information to the service control manager.
WIN32_SERVICE_CONTROL_NETBINDADD | 0x00000007 | Notifies a network service that there is a new component for binding.
WIN32_SERVICE_CONTROL_NETBINDDISABLE | 0x0000000A | Notifies a network service that one of its bindings has been disabled.
WIN32_SERVICE_CONTROL_NETBINDENABLE | 0x00000009 | Notifies a network service that a disabled binding has been enabled.
WIN32_SERVICE_CONTROL_NETBINDREMOVE | 0x00000008 | Notifies a network service that a component for binding has been removed.
WIN32_SERVICE_CONTROL_PARAMCHANGE | 0x00000006 | Notifies a service that its startup parameters have changed.
WIN32_SERVICE_CONTROL_PAUSE | 0x00000002 | Notifies a service that it should pause.
WIN32_SERVICE_CONTROL_POWEREVENT | 0x0000000D |
WIN32_SERVICE_CONTROL_PRESHUTDOWN | 0x0000000F | Notifies a service that the system will be shutting down. A service that handles this notification blocks system shutdown until the service stops or the preshutdown time-out interval expires. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_CONTROL_SESSIONCHANGE | 0x0000000E |
WIN32_SERVICE_CONTROL_SHUTDOWN | 0x00000005 | Notifies a service that the system is shutting down so the service can perform cleanup tasks. If a service accepts this control code, it must stop after it performs its cleanup tasks. After the SCM sends this control code, it will not send other control codes to the service.
WIN32_SERVICE_CONTROL_STOP | 0x00000001 | Notifies a service that it should stop.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Control Message Accepted Bitmasks

  • « Win32Service Service Control Message Constants
  • Win32Service Service Start Type Constants »
  • PHP Manual
  • Constantes pré-definidas
  • Win32Service Service Control Message Accepted Bitmasks
Win32Service Service Control Message Accepted Bitmasks
Constant | Value | Description
WIN32_SERVICE_ACCEPT_HARDWAREPROFILECHANGE | 0x00000020 | The service is notified when the computer's hardware profile has changed. This enables the system to send WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE notifications to the service.
WIN32_SERVICE_ACCEPT_NETBINDCHANGE | 0x00000010 | The service is a network component that can accept changes in its binding without being stopped and restarted. This control code allows the service to receive WIN32_SERVICE_CONTROL_NETBINDADD, WIN32_SERVICE_CONTROL_NETBINDREMOVE, WIN32_SERVICE_CONTROL_NETBINDENABLE, and WIN32_SERVICE_CONTROL_NETBINDDISABLE notifications.
WIN32_SERVICE_ACCEPT_PARAMCHANGE | 0x00000008 | The service can reread its startup parameters without being stopped and restarted. This control code allows the service to receive WIN32_SERVICE_CONTROL_PARAMCHANGE notifications.
WIN32_SERVICE_ACCEPT_PAUSE_CONTINUE | 0x00000002 | The service can be paused and continued. This control code allows the service to receive WIN32_SERVICE_CONTROL_PAUSE and WIN32_SERVICE_CONTROL_CONTINUE notifications.
WIN32_SERVICE_ACCEPT_POWEREVENT | 0x00000040 | The service is notified when the computer's power status has changed. This enables the system to send WIN32_SERVICE_CONTROL_POWEREVENT notifications to the service.
WIN32_SERVICE_ACCEPT_PRESHUTDOWN | 0x00000100 | The service can perform preshutdown tasks. This control code enables the service to receive WIN32_SERVICE_CONTROL_PRESHUTDOWN notifications. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_ACCEPT_SESSIONCHANGE | 0x00000080 | The service is notified when the computer's session status has changed. This enables the system to send WIN32_SERVICE_CONTROL_SESSIONCHANGE notifications to the service. Windows 2000: This value is not supported
WIN32_SERVICE_ACCEPT_SHUTDOWN | 0x00000004 | The service is notified when system shutdown occurs. This control code allows the service to receive WIN32_SERVICE_CONTROL_SHUTDOWN notifications.
WIN32_SERVICE_ACCEPT_STOP | 0x00000001 | The service can be stopped. This control code allows the service to receive WIN32_SERVICE_CONTROL_STOP notifications.
WIN32_SERVICE_ACCEPT_TIMECHANGE | 0x00000200 | The service is notified when the system time has changed. This enables the system to send WIN32_SERVICE_CONTROL_TIMECHANGE notifications to the service. Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP/2000: This control code is not supported.
WIN32_SERVICE_ACCEPT_TRIGGEREVENT | 0x00000400 | The service is notified when an event for which the service has registered occurs. This enables the system to send WIN32_SERVICE_CONTROL_TRIGGEREVENT notifications to the service. Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP/2000: This control code is not supported.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Start Type Constants

  • « Win32Service Service Control Message Accepted Bitmasks
  • Win32Service Service Error Control Constants »
  • PHP Manual
  • Constantes pré-definidas
  • Win32Service Service Start Type Constants
Win32Service Service Start Type Constants
Constant | Value | Description
WIN32_SERVICE_BOOT_START | 0x00000000 | A device driver started by the system loader. This value is valid only for driver services.
WIN32_SERVICE_SYSTEM_START | 0x00000001 | A device driver started by the IoInitSystem function. This value is valid only for driver services.
WIN32_SERVICE_AUTO_START | 0x00000002 | A service started automatically by the service control manager during system startup.
WIN32_SERVICE_DEMAND_START | 0x00000003 | A service started by the service control manager when a process calls the StartService function.
WIN32_SERVICE_DISABLED | 0x00000004 | A service that cannot be started. Attempts to start the service result in the error code WIN32_ERROR_SERVICE_DISABLED.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Error Control Constants

  • « Win32Service Service Start Type Constants
  • Win32Service Service Flag Constants »
  • PHP Manual
  • Constantes pré-definidas
  • Win32Service Service Error Control Constants
Win32Service Service Error Control Constants
Constant | Value | Description
WIN32_SERVICE_ERROR_IGNORE | 0x00000000 | The startup program ignores the error and continues the startup operation.
WIN32_SERVICE_ERROR_NORMAL | 0x00000001 | The startup program logs the error in the event log but continues the startup operation.
WIN32_SERVICE_ERROR_SEVERE | 0x00000002 | The startup program logs the error in the event log. If the last-known-good configuration is being started, the startup operation continues. Otherwise, the system is restarted with the last-known-good configuration.
WIN32_SERVICE_ERROR_CRITICAL | 0x00000003 | The startup program logs the error in the event log, if possible. If the last-known-good configuration is being started, the startup operation fails. Otherwise, the system is restarted with the last-known good configuration.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Flag Constants

  • « Win32Service Service Error Control Constants
  • Win32 Error Codes »
  • PHP Manual
  • Constantes pré-definidas
  • Win32Service Service Flag Constants
Win32Service Service Flag Constants
Constant | Value | Description
WIN32_SERVICE_RUNS_IN_SYSTEM_PROCESS | 0x00000001 | The service runs in a system process that must always be running.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Error Codes

  • « Win32Service Service Flag Constants
  • Win32 Base Priority Classes »
  • PHP Manual
  • Constantes pré-definidas
  • Win32 Error Codes

Nota:

These constants are no longer in use as of Win32Service 1.0.0.

Win32 Error Codes
Constant | Value | Description
WIN32_ERROR_ACCESS_DENIED | 0x00000005 | The handle to the SCM database does not have the appropriate access rights.
WIN32_ERROR_CIRCULAR_DEPENDENCY | 0x00000423 | A circular service dependency was specified.
WIN32_ERROR_DATABASE_DOES_NOT_EXIST | 0x00000429 | The specified database does not exist.
WIN32_ERROR_DEPENDENT_SERVICES_RUNNING | 0x0000041B | The service cannot be stopped because other running services are dependent on it.
WIN32_ERROR_DUPLICATE_SERVICE_NAME | 0x00000436 | The display name already exists in the service control manager database either as a service name or as another display name.
WIN32_ERROR_FAILED_SERVICE_CONTROLLER_CONNECT | 0x00000427 | This error is returned if the program is being run as a console application rather than as a service. If the program will be run as a console application for debugging purposes, structure it such that service-specific code is not called.
WIN32_ERROR_INSUFFICIENT_BUFFER | 0x0000007A | The buffer is too small for the service status structure. Nothing was written to the structure.
WIN32_ERROR_INVALID_DATA | 0x0000000D | The specified service status structure is invalid.
WIN32_ERROR_INVALID_HANDLE | 0x00000006 | The handle to the specified service control manager database is invalid.
WIN32_ERROR_INVALID_LEVEL | 0x0000007C | The InfoLevel parameter contains an unsupported value.
WIN32_ERROR_INVALID_NAME | 0x0000007B | The specified service name is invalid.
WIN32_ERROR_INVALID_PARAMETER | 0x00000057 | A parameter that was specified is invalid.
WIN32_ERROR_INVALID_SERVICE_ACCOUNT | 0x00000421 | The user account name specified in the user parameter does not exist. See win32_create_service().
WIN32_ERROR_INVALID_SERVICE_CONTROL | 0x0000041C | The requested control code is not valid, or it is unacceptable to the service.
WIN32_ERROR_PATH_NOT_FOUND | 0x00000003 | The service binary file could not be found.
WIN32_ERROR_SERVICE_ALREADY_RUNNING | 0x00000420 | An instance of the service is already running.
WIN32_ERROR_SERVICE_CANNOT_ACCEPT_CTRL | 0x00000425 | The requested control code cannot be sent to the service because the state of the service is WIN32_SERVICE_STOPPED, WIN32_SERVICE_START_PENDING, or WIN32_SERVICE_STOP_PENDING.
WIN32_ERROR_SERVICE_DATABASE_LOCKED | 0x0000041F | The database is locked.
WIN32_ERROR_SERVICE_DEPENDENCY_DELETED | 0x00000433 | The service depends on a service that does not exist or has been marked for deletion.
WIN32_ERROR_SERVICE_DEPENDENCY_FAIL | 0x0000042C | The service depends on another service that has failed to start.
WIN32_ERROR_SERVICE_DISABLED | 0x00000422 | The service has been disabled.
WIN32_ERROR_SERVICE_DOES_NOT_EXIST | 0x00000424 | The specified service does not exist as an installed service.
WIN32_ERROR_SERVICE_EXISTS | 0x00000431 | The specified service already exists in this database.
WIN32_ERROR_SERVICE_LOGON_FAILED | 0x0000042D | The service did not start due to a logon failure. This error occurs if the service is configured to run under an account that does not have the "Log on as a service" right.
WIN32_ERROR_SERVICE_MARKED_FOR_DELETE | 0x00000430 | The specified service has already been marked for deletion.
WIN32_ERROR_SERVICE_NO_THREAD | 0x0000041E | A thread could not be created for the service.
WIN32_ERROR_SERVICE_NOT_ACTIVE | 0x00000426 | The service has not been started.
WIN32_ERROR_SERVICE_REQUEST_TIMEOUT | 0x0000041D | The process for the service was started, but it did not call StartServiceCtrlDispatcher, or the thread that called StartServiceCtrlDispatcher may be blocked in a control handler function.
WIN32_ERROR_SHUTDOWN_IN_PROGRESS | 0x0000045B | The system is shutting down; this function cannot be called.
WIN32_ERROR_SERVICE_SPECIFIC_ERROR | 0x0000042A | The service has returned a service-specific error code.
WIN32_NO_ERROR | 0x00000000 | No error.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Base Priority Classes

  • « Win32 Error Codes
  • Win32 Recovery action »
  • PHP Manual
  • Constantes pré-definidas
  • Win32 Base Priority Classes
Win32 Base Priority Classes
Constant | Value | Description
WIN32_ABOVE_NORMAL_PRIORITY_CLASS | 0x00008000 | Process that has priority above WIN32_NORMAL_PRIORITY_CLASS but below WIN32_HIGH_PRIORITY_CLASS.
WIN32_BELOW_NORMAL_PRIORITY_CLASS | 0x00004000 | Process that has priority above WIN32_IDLE_PRIORITY_CLASS but below WIN32_NORMAL_PRIORITY_CLASS.
WIN32_HIGH_PRIORITY_CLASS | 0x00000080 | Process that performs time-critical tasks that must be executed immediately. The threads of the process preempt the threads of normal or idle priority class processes. An example is the Task List, which must respond quickly when called by the user, regardless of the load on the operating system. Use extreme care when using the high-priority class, because a high-priority class application can use nearly all available CPU time.
WIN32_IDLE_PRIORITY_CLASS | 0x00000040 | Process whose threads run only when the system is idle. The threads of the process are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle-priority class is inherited by child processes.
WIN32_NORMAL_PRIORITY_CLASS | 0x00000020 | Process with no special scheduling needs.
WIN32_REALTIME_PRIORITY_CLASS | 0x00000100 | Process that has the highest possible priority. The threads of the process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Recovery action

  • « Win32 Base Priority Classes
  • Win32 Service informations »
  • PHP Manual
  • Constantes pré-definidas
  • Win32 Recovery action
Win32 Recovery action
Constant | Value | Description
WIN32_SC_ACTION_NONE | 0x00000000 | No action.
WIN32_SC_ACTION_RESTART | 0x00000001 | Restart the service.
WIN32_SC_ACTION_REBOOT | 0x00000002 | Restart the server.
WIN32_SC_ACTION_RUN_COMMAND | 0x00000003 | Run a command.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Service informations

  • « Win32 Recovery action
  • Win32ServiceException »
  • PHP Manual
  • Constantes pré-definidas
  • Win32 Service informations
Win32 Service informations
Constant | Value | Description
WIN32_INFO_SERVICE | "service" |
WIN32_INFO_DISPLAY | "display" |
WIN32_INFO_USER | "user" |
WIN32_INFO_PASSWORD | "password" |
WIN32_INFO_PATH | "path" |
WIN32_INFO_PARAMS | "params" |
WIN32_INFO_DESCRIPTION | "description" |
WIN32_INFO_START_TYPE | "start_type" |
INFO_LOAD_ORDER | "load_order" |
INFO_SVC_TYPE | "svc_type" |
INFO_ERROR_CONTROL | "error_control" |
INFO_DELAYED_START | "delayed_start" |
INFO_BASE_PRIORITY | "base_priority" |
INFO_DEPENDENCIES | "dependencies" |
INFO_RECOVERY_DELAY | "recovery_delay" |
INFO_RECOVERY_ACTION_1 | "recovery_action_1" |
INFO_RECOVERY_ACTION_2 | "recovery_action_2" |
INFO_RECOVERY_ACTION_3 | "recovery_action_3" |
INFO_RECOVERY_RESET_PERIOD | "recovery_reset_period" |
INFO_RECOVERY_ENABLED | "recovery_enabled" |
INFO_RECOVERY_REBOOT_MSG | "recovery_reboot_msg" |
INFO_RECOVERY_COMMAND | "recovery_command" |

User Contributed Notes

There are no user contributed notes for this page.


The Win32ServiceException class

(PECL win32service >=1.0.0)

Introdução

The exception replaces the old mechanism where the error value needed to be compared to constants to detect which error was emitted. The Exception code is equal to the value of the error value and the exception message is based on the corresponding constant name.

Sinopse da classe

class Win32ServiceException extends Exception {
/* Propriedades herdadas */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Métodos herdados */
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.


Exemplos

Exemplo #1 Registering a PHP script to run as a service

<?php
win32_create_service(array(
'service' => 'dummyphp', # the name of your service
'display' => 'sample dummy PHP service', # short description
'description' => 'This is a dummy Windows service created using PHP.', # long description
'params' => '"' . __FILE__ . '" run', # path to the script and parameters
));
?>

Exemplo #2 Unregistering a service

<?php
win32_delete_service('dummyphp');
?>

Exemplo #3 Running as a service

<?php
if ($argv[1] == 'run') {
win32_start_service_ctrl_dispatcher('dummyphp');

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
# do your work here.
# try not to take up more than 30 seconds before going around the loop
# again
}
}
?>

User Contributed Notes

There are no user contributed notes for this page.


win32service Funções

Índice

  • win32_continue_service — Resumes a paused service
  • win32_create_service — Creates a new service entry in the SCM database
  • win32_delete_service — Deletes a service entry from the SCM database
  • win32_get_last_control_message — Returns the last control message that was sent to this service
  • win32_pause_service — Pauses a service
  • win32_query_service_status — Queries the status of a service
  • win32_send_custom_control — Send a custom control to the service
  • win32_set_service_exit_code — Define or return the exit code for the current running service
  • win32_set_service_exit_mode — Define or return the exit mode for the current running service
  • win32_set_service_status — Update the service status
  • win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name
  • win32_start_service — Starts a service
  • win32_stop_service — Stops a service

User Contributed Notes

brian dot ngure at gmail dot com 30-Apr-2010 03:03
An example of how it should be done:

<?php

class TestClass {
    private $args;

    function __construct($arg) {
        $this->args = $arg;
        $this->run();
    }

    private function run() {
        if ($this->args == 'run') {
            win32_start_service_ctrl_dispatcher('test_service');

            while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
                # do your work here.
                # try not to take up more than 30 seconds before going around the loop
                # again
            }
        }
    }
}

$object = new TestClass($argv[1]);

?>


Resumes a paused service

  • « win32service Funções
  • win32_create_service »
  • PHP Manual
  • win32service Funções
  • Resumes a paused service

win32_continue_service

(PECL win32service >=0.1.0)

win32_continue_service — Resumes a paused service

Descrição

win32_continue_service(string $servicename, string $machine = ?): void

Resumes a paused, named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

Parâmetros

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Valor Retornado

Nenhum valor é retornado.

Prior to version 1.0.0, retornava WIN32_NO_ERROR em caso de sucesso, false se houver um problema com os parâmetros ou um Código de Erro Win32 em caso de falha.

Erros

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

Veja Também

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Creates a new service entry in the SCM database

  • « win32_continue_service
  • win32_delete_service »
  • PHP Manual
  • win32service Funções
  • Creates a new service entry in the SCM database

win32_create_service

(PECL win32service >=0.1.0)

win32_create_service — Creates a new service entry in the SCM database

Descrição

win32_create_service(array $details, string $machine = ?): void

Attempts to add a service into the SCM database. Administrative privileges are required for this to succeed.

Parâmetros

details

An array of service details:

service

The short name of the service. This is the name that you will use to control the service using the net command. The service must be unique (no two services can share the same name), and, ideally, should avoid having spaces in the name.

display

The display name of the service. This is the name that you will see in the Services Applet.

description

The long description of the service. This is the description that you will see in the Services Applet.

user

The name of the user account under which you want the service to run. If omitted, the service will run as the LocalSystem account. If the username is specified, you must also provide a password.

password

The password that corresponds to the user.

path

The full path to the executable module that will be launched when the service is started. If omitted, the path to the current PHP process will be used.

params

Command line parameters to pass to the service when it starts. If you want to run a PHP script as the service, then the first parameter should be the full path to the PHP script that you intend to run. If the script name or path contains spaces, then wrap the full path to the PHP script with ".

load_order

Controls the load_order. This is not yet fully supported.

svc_type

Sets the service type. If omitted, the default value is WIN32_SERVICE_WIN32_OWN_PROCESS. Don't change this unless you know what you're doing.

start_type

Specifies how the service should be started. The default is WIN32_SERVICE_AUTO_START which means the service will be launched when the machine starts up.

error_control

Informs the SCM what it should do when it detects a problem with the service. The default is WIN32_SERVER_ERROR_IGNORE. Changing this value is not yet fully supported.

delayed_start

If delayed_start is set to true, then this will inform the SCM that this service should be started after other auto-start services are started plus a short delay.

Any service can be marked as a delayed auto-start service; however, this setting has no effect unless the service's start_type is WIN32_SERVICE_AUTO_START.

This setting is only applicable on Windows Vista and Windows Server 2008 or greater.

base_priority

To reduce the impact on processor utilisation, it may be necessary to set a base priority lower than normal.

The base_priority can be set to one of the constants define in Win32 Base Priority Classes.

dependencies

To define the dependencies for your service, it may be necessary to set this parameter to the list of the services names in an array.

recovery_delay

This parameter defines the delay between the fail and the execution of recovery action. The value is in milliseconds.

The default value is 60000.

recovery_action_1

The action will be executed on first failure. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_1 can be set to one of the constants defined in Win32 Recovery action.

recovery_action_2

The action will be executed on second failure. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_2 can be set to one of the constants defined in Win32 Recovery action.

recovery_action_3

The action will be executed on next failures. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_3 can be set to one of the constants defined in Win32 Recovery action.

recovery_reset_period

The failure count will be reset after the delay defined in the parameter. The delay is expirement in seconds.

The default value is 86400.

recovery_enabled

Set this parameter at true to enable the recovery settings, false to disable.

The default value is false

recovery_reboot_msg

Set this parameter to define the message saved into the Windows Event Log before the reboot. Used only if one action is set to WIN32_SC_ACTION_REBOOT.

recovery_command

Set this parameter to define the command executed when one action is defined on WIN32_SC_ACTION_RUN_COMMAND.

machine

The optional machine name on which you want to create a service. If omitted, it will use the local machine.

Valor Retornado

Nenhum valor é retornado.

Prior to version 1.0.0, retornava WIN32_NO_ERROR em caso de sucesso, false se houver um problema com os parâmetros ou um Código de Erro Win32 em caso de falha.

Erros

A ValueError is thrown if the value of service parameter is empty.

A ValueError is thrown if the value of path parameter is missing or empty.

A ValueError is thrown if the value of svc_type parameter is wrong.

A ValueError is thrown if the value of start_type parameter is wrong.

A ValueError is thrown if the value of error_control parameter is wrong.

A ValueError is thrown if the value of base_priority parameter is wrong.

A ValueError is thrown if the value of recovery_delay parameter is not between 0 and PHP_INT_MAX.

A ValueError is thrown if the value of recovery_action_1 parameter is wrong.

A ValueError is thrown if the value of recovery_action_2 parameter is wrong.

A ValueError is thrown if the value of recovery_action_3 parameter is wrong.

A ValueError is thrown if the value of recovery_reset_period parameter is not between 0 and PHP_INT_MAX.

A Win32ServiceException is thrown on error.

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.4.0 | The dependencies, recovery_delay, recovery_action_1, recovery_action_2, recovery_action_3, recovery_reset_period, recovery_enabled, recovery_reboot_msg and recovery_command parameters have been added.

Exemplos

Exemplo #1 A win32_create_service() example

Create a service with the short name 'dummyphp'.

<?php
$x = win32_create_service(array(
'service' => 'dummyphp', // the name of your service
'display' => 'sample dummy PHP service', // short description
'description' => 'This is a dummy Windows service created using PHP.', // long description
'params' => '"' . __FILE__ . '" run', // path to the script and parameters
));
debug_zval_dump($x);
?>

Exemplo #2 A win32_create_service() example with dependencies

Create a service with the short name 'dummyphp' and dependencies.

<?php
$x = win32_create_service(array(
'service' => 'dummyphp', // the name of your service
'display' => 'sample dummy PHP service', // short description
'description' => 'This is a dummy Windows service created using PHP.', // long description
'params' => '"' . __FILE__ . '" run', // path to the script and parameters
'dependencies' => array("Netman"), // The list of the dependencies
));
debug_zval_dump($x);
?>

Exemplo #3 A win32_create_service() example with recovery

Create a service with the short name 'dummyphp' and recovery settings.

<?php
$x = win32_create_service(array(
'service' => 'dummyphp', // the name of your service
'display' => 'sample dummy PHP service', // short description
'description' => 'This is a dummy Windows service created using PHP.', // long description
'params' => '"' . __FILE__ . '" run', // path to the script and parameters
'recovery_delay' => 120000, // Recovery action is executed after 2 minutes
'recovery_action_1' => WIN32_SC_ACTION_RESTART, // On first failure, restart the service
'recovery_action_2' => WIN32_SC_ACTION_RUN_COMMAND, // On second failure, execute the commmand
'recovery_action_3' => WIN32_SC_ACTION_NONE, // On other failure, do nothing
'recovery_reset_period' => 86400, // Reset the fail counter after 1 day
'recovery_enabled' => true, // Enable the recovery parameter
'recovery_reboot_msg' => null, // Do not define a reboot message, it's not needed here
'recovery_command' => "c:\clean-service.bat", // When the action is WIN32_SC_ACTION_RUN_COMMAND, execute this command
));
debug_zval_dump($x);
?>

Veja Também

  • win32_delete_service() - Deletes a service entry from the SCM database
  • Win32 Base Priority Classes
  • Win32 Recovery action
  • Win32 Error Codes

User Contributed Notes

Anonymous 08-Oct-2010 10:05
[An example of how to create a Windows service.  Evaluate code first and use at your own risk!]

<?php

//No timeouts, Flush Content immediatly
    set_time_limit(0);
    ob_implicit_flush();

//Service Settings
    $phpPath = "D:\\php\\php5.2.9";
    $ServiceName = 'phpServiceName';
    $ServiceDisplay = 'phpDisplayName';

//Windows Service Control
    $ServiceAction = "status";
    //$ServiceAction = "debug";
    if ( isset($_GET['ServiceAction']) and strlen($_GET['ServiceAction']) ) {
        $ServiceAction = addslashes($_GET['ServiceAction']);
    } else if ( isset($argv) and isset($argv[1]) and strlen($argv[1]) ) {
        $ServiceAction = $argv[1];
    }
    if( $ServiceAction == "status" ) {
        $ServiceStatus = win32_query_service_status($ServiceName);
        if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_STOPPED ) {
            echo "Service Stopped\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_START_PENDING ) {
            echo "Service Start Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_STOP_PENDING ) {
            echo "Service Stop Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_RUNNING ) {
            echo "Service Running\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_CONTINUE_PENDING ) {
            echo "Service Continue Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_PAUSE_PENDING ) {
            echo "Service Pause Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_PAUSED ) {
            echo "Service Paused\n\n";
        } else{
            echo "Service Unknown\n\n";
        }
      exit;
    } else if ( $ServiceAction == "install" ) {
    //Install Windows Service
        win32_create_service( Array(
            'service' => $ServiceName,
            'display' => $ServiceDisplay,
            'params' => __FILE__ . " run",
            'path' => $phpPath."\\php.exe",
        ));
        echo "Service Installed\n\n";
        exit;
    } else if ( $ServiceAction == "uninstall" ) {
    //Remove Windows Service
        win32_delete_service($ServiceName);
        echo "Service Removed\n\n";
        exit;
    } else if( $ServiceAction == "start") {
    //Start Windows Service
      win32_start_service($ServiceName);
      echo "Service Started\n\n";
      exit;
    } else if( $ServiceAction == "stop" ) {
    //Stop Windows Service
      win32_stop_service($ServiceName);
      echo "Service Stopped\n\n";
      exit;
    } else if ( $ServiceAction == "run" ) {
    //Run Windows Service
        win32_start_service_ctrl_dispatcher($ServiceName);
        win32_set_service_status(WIN32_SERVICE_RUNNING);
    } else if ( $ServiceAction == "debug" ) {
    //Debug Windows Service
        set_time_limit(10);
    } else {
        exit();
    }

//Server Loop
    while (1) {
    //Handle Windows Service Request
        usleep(100*1000);
        if ( $ServiceAction == "run" ) {
            switch ( win32_get_last_control_message() ) {
                case WIN32_SERVICE_CONTROL_CONTINUE:
                    break;
                case WIN32_SERVICE_CONTROL_INTERROGATE:
                    win32_set_service_status(WIN32_NO_ERROR);
                break;
                case WIN32_SERVICE_CONTROL_STOP:
                    win32_set_service_status(WIN32_SERVICE_STOPPED);
                    exit;
                default:
                    win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED);
            }
        }
    //User Loop
        sleep(1);
        echo "\n<BR>YOUR CODE HERE";
    }

//Exit
    if ( $ServiceAction == "run" ) {
        win32_set_service_status(WIN32_SERVICE_STOPPED);
    }
    exit();
?>
pauljamesthomson at gmail dot com 22-Jan-2007 04:54
Other start_type values:

0x00000002: A service started automatically by the service control manager during system startup. For more information, see Automatically Starting Services.

0x00000000: A device driver started by the system loader. This value is valid only for driver services.

0x00000003: A service started by the service control manager when a process calls the win32_start_service() function.

0x00000004: A service that cannot be started. Attempts to start the service result in the error code

0x00000001: A device driver started by the IoInitSystem function. This value is valid only for driver services.

I can confirm that 0x00000003 works as expected (service is created, but must be started manually).

More here:

http://msdn2.microsoft.com/en-us/library/ms682450.aspx


Deletes a service entry from the SCM database

  • « win32_create_service
  • win32_get_last_control_message »
  • PHP Manual
  • win32service Funções
  • Deletes a service entry from the SCM database

win32_delete_service

(PECL win32service >=0.1.0)

win32_delete_service — Deletes a service entry from the SCM database

Descrição

win32_delete_service(string $servicename, string $machine = ?): void

Attempts to delete a service from the SCM database. Administrative privileges are required for this to succeed.

This function really just marks the service for deletion. If other processes (such as the Services Applet) are open, then the deletion will be deferred until those applications are closed. If a service is marked for deletion, further attempts to delete it will fail, and attempts to create a new service with that name will also fail.

Parâmetros

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Valor Retornado

Nenhum valor é retornado.

Prior to version 1.0.0, retornava WIN32_NO_ERROR em caso de sucesso, false se houver um problema com os parâmetros ou um Código de Erro Win32 em caso de falha.

Erros

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.

Exemplos

Exemplo #1 A win32_delete_service() example

Deletes the dummyphp service.

<?php
win32_delete_service('dummyphp');
?>

Veja Também

  • win32_create_service() - Creates a new service entry in the SCM database
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Returns the last control message that was sent to this service

  • « win32_delete_service
  • win32_pause_service »
  • PHP Manual
  • win32service Funções
  • Returns the last control message that was sent to this service

win32_get_last_control_message

(PECL win32service >=0.1.0)

win32_get_last_control_message — Returns the last control message that was sent to this service

Descrição

win32_get_last_control_message(): int

Returns the control code that was last sent to this service process. When running as a service you should periodically check this to determine if your service needs to stop running.

Cuidado

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns a control constant which will be one of the Win32Service Service Control Message Constants: WIN32_SERVICE_CONTROL_CONTINUE, WIN32_SERVICE_CONTROL_DEVICEEVENT, WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE, WIN32_SERVICE_CONTROL_INTERROGATE, WIN32_SERVICE_CONTROL_NETBINDADD, WIN32_SERVICE_CONTROL_NETBINDDISABLE, WIN32_SERVICE_CONTROL_NETBINDENABLE, WIN32_SERVICE_CONTROL_NETBINDREMOVE, WIN32_SERVICE_CONTROL_PARAMCHANGE, WIN32_SERVICE_CONTROL_PAUSE, WIN32_SERVICE_CONTROL_POWEREVENT, WIN32_SERVICE_CONTROL_PRESHUTDOWN, WIN32_SERVICE_CONTROL_SESSIONCHANGE, WIN32_SERVICE_CONTROL_SHUTDOWN, WIN32_SERVICE_CONTROL_STOP.

If the value is between 128 and 255, the control code is custom.

Erros

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 0.2.0 | This function works only in the "cli" SAPI.

Veja Também

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32Service Service Control Message Constants

User Contributed Notes

There are no user contributed notes for this page.


Pauses a service

  • « win32_get_last_control_message
  • win32_query_service_status »
  • PHP Manual
  • win32service Funções
  • Pauses a service

win32_pause_service

(PECL win32service >=0.1.0)

win32_pause_service — Pauses a service

Descrição

win32_pause_service(string $servicename, string $machine = ?): void

Pauses a named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

Parâmetros

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Valor Retornado

Nenhum valor é retornado.

Prior to version 1.0.0, retornava WIN32_NO_ERROR em caso de sucesso, false se houver um problema com os parâmetros ou um Código de Erro Win32 em caso de falha.

Erros

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

Veja Também

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Queries the status of a service

  • « win32_pause_service
  • win32_send_custom_control »
  • PHP Manual
  • win32service Funções
  • Queries the status of a service

win32_query_service_status

(PECL win32service >=0.1.0)

win32_query_service_status — Queries the status of a service

Descrição

win32_query_service_status(string $servicename, string $machine = ?): array

Queries the current status for a service, returning an array of information.

Parâmetros

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Valor Retornado

Returns an array consisting of the following information on success

Prior version 1.0.0, false se houver um problema com os parâmetros ou um Código de Erro Win32 em caso de falha.

ServiceType

The dwServiceType. See Win32Service Service Type Bitmasks.

CurrentState

The dwCurrentState. See Win32Service Service Status Constants.

ControlsAccepted

Which service controls are accepted by the service. See Win32Service Service Control Message Accepted Bitmasks.

Win32ExitCode

If the service exited, the return code from the process. This value is equal to WIN32_ERROR_SERVICE_SPECIFIC_ERROR if the exit mode is not gracefuly. See Win32Service error codes and win32_set_service_exit_mode()

ServiceSpecificExitCode

If the service exited with an error condition, the service specific code that is logged in the event log is visible here. This value is equal to the value defined by win32_set_service_exit_code()

CheckPoint

If the service is shutting down, holds the current check point number. This is used by the SCM as a kind of heart-beat to detect a wedged service process. The value of the check point is best interpreted in conjunction with the WaitHint value.

WaitHint

If the service is shutting down it will set WaitHint to a checkpoint value that will indicate 100% completion. This can be used to implement a progress indicator.

ProcessId

The Windows process identifier. If 0, the process is not running.

ServiceFlags

The dwServiceFlags. See Win32Service Service Flag Constants.

Erros

A ValueError is thrown if the value of servicename parameter is empty.

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now array, previously it was mixed.

Veja Também

  • Win32Service Predefined Constants

User Contributed Notes

demers dot alex at gmail dot com 21-Jul-2009 08:39
This function will return an array containing the above information as a return value, but if this fails it will return an integer which is a System Error Code. All the System Error Codes can be found here:

http://msdn.microsoft.com/en-us/library/ms681381%28VS.85%29.aspx

In my case, it returned 5, in which I immediately knew why and fixed the issue right away.

In the case of mnemotronic at netscape dot net, here in the documentation notes, it returned 1060 which is:

ERROR_SERVICE_DOES_NOT_EXIST
1060 (0x424)
The specified service does not exist as an installed service.

Again, it should not return FALSE, instead an System Error Code for Windows.


Send a custom control to the service

  • « win32_query_service_status
  • win32_set_service_exit_code »
  • PHP Manual
  • win32service Funções
  • Send a custom control to the service

win32_send_custom_control

(PECL win32service >=0.4.0)

win32_send_custom_control — Send a custom control to the service

Descrição

win32_send_custom_control(string $servicename, int $control, string $machine = ?): void

See » Microsoft ControlService function for more details

Parâmetros

servicename

The short name of the service.

control

The custom contole value between 128 and 255.

machine

Optional machine name. If omitted, the local machine is used.

Valor Retornado

Nenhum valor é retornado.

Prior to version 1.0.0, retornava WIN32_NO_ERROR em caso de sucesso, false se houver um problema com os parâmetros ou um Código de Erro Win32 em caso de falha.

Erros

Prior to version 1.0.0, if the control value is not between 128 and 255, this function emits an E_ERROR level error.

A ValueError is thrown if the value of servicename parameter is empty.

A ValueError is thrown if the value of control parameter is not between 128 and 255.

A Win32ServiceException is thrown on error.

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.

Veja Também

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Define or return the exit code for the current running service

  • « win32_send_custom_control
  • win32_set_service_exit_mode »
  • PHP Manual
  • win32service Funções
  • Define or return the exit code for the current running service

win32_set_service_exit_code

(PECL win32service >=0.4.0)

win32_set_service_exit_code — Define or return the exit code for the current running service

Descrição

win32_set_service_exit_code(int $exitCode = 1): int

Change or return the exit code. The exit code is used only if the exit mode is not graceful. If the value is not zero, the recovery configuration can be used after service fail. See » Microsoft system error codes for more details

Cuidado

This function work only in "cli" SAPI. On other SAPI this function is disabled.

Parâmetros

exitCode

The return code used on exit.

Valor Retornado

Return the current or old exit code.

Erros

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.

Veja Também

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service

User Contributed Notes

There are no user contributed notes for this page.


Define or return the exit mode for the current running service

  • « win32_set_service_exit_code
  • win32_set_service_status »
  • PHP Manual
  • win32service Funções
  • Define or return the exit mode for the current running service

win32_set_service_exit_mode

(PECL win32service >=0.4.0)

win32_set_service_exit_mode — Define or return the exit mode for the current running service

Descrição

win32_set_service_exit_mode(bool $gracefulMode = true): bool

If gracefulMode parameter is provided, the exit mode is changed. When the exit mode is not gracefuly, the exit code used can be set with the win32_set_service_exit_code() function.

Cuidado

This function work only in "cli" SAPI. On other SAPI this function is disabled.

Parâmetros

gracefulMode

true for exit graceful. false for exit with error.

Valor Retornado

Return the current or old exit mode.

Erros

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.

Veja Também

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_code() - Define or return the exit code for the current running service

User Contributed Notes

There are no user contributed notes for this page.


Update the service status

  • « win32_set_service_exit_mode
  • win32_start_service_ctrl_dispatcher »
  • PHP Manual
  • win32service Funções
  • Update the service status

win32_set_service_status

(PECL win32service >=0.1.0)

win32_set_service_status — Update the service status

Descrição

win32_set_service_status(int $status, int $checkpoint = 0): void

Informs the SCM of the current status of a running service. This call is only valid for a running service process.

Cuidado

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

Parâmetros

status

The service status code, one of WIN32_SERVICE_RUNNING, WIN32_SERVICE_STOPPED, WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING, WIN32_SERVICE_PAUSE_PENDING, WIN32_SERVICE_PAUSED.

checkpoint

The checkpoint value the service increments periodically to report its progress during a lengthy start, stop, pause, or continue operation. For example, the service should increment this value as it completes each step of its initialization when it is starting up.

The checkpoint is only valid when the status is one of WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING or WIN32_SERVICE_PAUSE_PENDING.

Valor Retornado

Nenhum valor é retornado.

Prior to version 1.0.0, retornava WIN32_NO_ERROR em caso de sucesso, false se houver um problema com os parâmetros ou um Código de Erro Win32 em caso de falha.

Erros

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.2.0 | This function works only in the "cli" SAPI.

Veja Também

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_get_last_control_message() - Returns the last control message that was sent to this service
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32Service Service Status Constants

User Contributed Notes

paul_nelson57071 at yahoo dot com 13-May-2010 11:04
So after much searching I finally found all the peices to make a working windows service & server including:
- Installing & Uninstalling the service
- Starting & Stopping the Service
- Actually running a basic Server
- Responding to windows Service to Stop/Start/Restart

I hope you find this useful! I did this using PHP 5.2 and the PECL library for 5.2 (PHP 5.3 at the time does not have a PECL Library compiled for it)

<?php
    //Service Settings
    $Service = 'MyServiceFinal';
    $Display = 'My PHP Service';

    //Server Settings
    $host = '127.0.0.1';        //Bind to IP #
    $port = 23;                            //On port #
    $max = 20;                            //Maximum Clients

    //Exit if no start-up argument is passed
    if (!isset($argv[1])){ShowHelp(); exit;}

    //Create Windows Service
    if ($argv[1] == 'install') {
    $x = win32_create_service(array(
        'service' => $Service,
        'display' => $Service,
        'params' => __file__ . ' run',
        'path' => 'c:\\php\\php.exe',
    ));
    debug_zval_dump($x);
    echo "Service Installed\n\n";
    exit;

  //Remove Windows Service
    } else if ($argv[1] == 'uninstall') {
        $x = win32_delete_service($Service);
        debug_zval_dump($x);
        echo "Service Removed\n\n";
        exit;

  //Start Windows Service
    } elseif($argv[1] == "start") {
      $x = win32_start_service($Service);
      debug_zval_dump($x);
      echo "Service Started\n\n";
      exit;

    //Stop Windows Service
    } elseif($argv[1] == "stop") {
      $x = win32_stop_service($Service);
      debug_zval_dump($x);
      echo "Service Stopped\n\n";
      exit;

    //Unkown Command
    } else if ($argv[1] != 'run') {
        ShowHelp(); exit();
    }

//Tell windows the service has started...
if (!win32_start_service_ctrl_dispatcher($Service)) die("Could not connect to service : $Service");
win32_set_service_status(WIN32_SERVICE_RUNNING);

// No timeouts, flush content immediatly
set_time_limit(0);
ob_implicit_flush();

//Server Loop
while (1) {
    usleep(500);

    //Handle Windows Service Request
    switch (win32_get_last_control_message()) {
        case WIN32_SERVICE_CONTROL_CONTINUE: break; // Continue server routine
        case WIN32_SERVICE_CONTROL_INTERROGATE: win32_set_service_status(WIN32_NO_ERROR); break; // Respond with status
        case WIN32_SERVICE_CONTROL_STOP: win32_set_service_status(WIN32_SERVICE_STOPPED); exit; // Terminate script
        default: win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }
    //Acutal Server Code

}

//Clean up and Exit
win32_set_service_status(WIN32_SERVICE_STOPPED);
exit;

//*************** FUNCTIONS ***************
function ShowHelp(){
    echo "Usage:
    install:\t installs servce
    uninstall:\t deletes service
    start:\t\t Start the windows service
    stop:\t\t Stops the windows service
    run:\t\t called by CMS to run the service

For information on code numbers type 'net helpmsg xxxx'
EXAMPEL: 'net helpmsg 1072'

    ";
}
?>
m dot hald at surfto dot ch 12-May-2008 04:16
On my Machine (Win XP SP2) the function "win32_get_last_control_message" never returns 4 so i will have to reply to 0 also.

finally after mixing several examples i now have a version working woithout filling my event log with errors:

<?php

/*
 * PHP SAMPLE TEMPLATE
 */

/*
 * APP MAIN FUNCTION
 * Called each second after the function last time finished
 * Should not take longer than max 20 seconds to execute
 * ELSE you should call NTServiceResponder(); at least each 20 secs
 * WARNING: NTServiceResponder will exit; if there was a STOP request
 */
function Service_Main()
{
    // YOU APPLICATION CODE HERE !!!
    sleep(1); // dummy something
}

/********************************************************************
 *
 * SERVICE CONTROLLING
 *
 ********************************************************************/

$SERVICE_NAME = "phptestservice";
$SERVICE_DISPLAY = "Test Service with PHP";

// so u can get: $SERVICE_PATH_PARTS["dirname"] $SERVICE_PATH_PARTS["basename"]  $SERVICE_PATH_PARTS["extension"]
$SERVICE_PATH_PARTS = pathinfo(__FILE__);

$SERVICE_PARAMS = " run";

    if (!isset($argv[1]))
    {
        die("this application need to be installed as a service.\n run with param install");
    }

    if ($argv[1] == 'install')
    {
        $x = win32_create_service(array(
                                        'service' => $SERVICE_NAME,
                                        'display' => $SERVICE_DISPLAY,
                                        'params' =>  __FILE__ . $SERVICE_PARAMS,
                                        //'path' =>  $SERVICE_PATH_PARTS["dirname"] . '\php.exe'
                                        ));
        debug_zval_dump($x);
        exit;
    }
    else if ($argv[1] == 'uninstall')
    {
        $x = win32_delete_service('dummyphp');
        debug_zval_dump($x);
        exit;
    }
    else if ($argv[1] != 'run')
    {
        die("bogus args, needs to run as service");
    }

    // Connect to service dispatcher and notify that startup was successful
    if (!win32_start_service_ctrl_dispatcher($SERVICE_NAME)) die('Could not connect to service :'.$SERVICE_NAME);
    win32_set_service_status(WIN32_SERVICE_RUNNING);

    // Main Server Loop
    while (1)
    {
        NTServiceResponder();

        // Main script goes here
        Service_Main();

        sleep(1); // at least 1 sec delay per loop
    }
    win32_set_service_status(WIN32_SERVICE_STOPPED);

/*
 * Response to NTServiceRequests
 */
function NTServiceResponder()
{

    switch (win32_get_last_control_message())
    {
    case 0: // PATCH for: seems never to go to 4 (WIN32_SERVICE_CONTROL_INTERROGATE)
        win32_set_service_status(WIN32_SERVICE_RUNNING);
        return TRUE;
        break;
    case WIN32_SERVICE_CONTROL_CONTINUE:
        return TRUE; // "Continue"
    case WIN32_SERVICE_CONTROL_INTERROGATE:
        win32_set_service_status(WIN32_SERVICE_RUNNING);
        return TRUE; // Respond with status
    case WIN32_SERVICE_CONTROL_STOP:
        win32_set_service_status(WIN32_SERVICE_STOPPED);
        exit; // Terminate script
    default:
        win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }

    return FALSE;
}

?>


Registers the script with the SCM, so that it can act as the service with the given name

  • « win32_set_service_status
  • win32_start_service »
  • PHP Manual
  • win32service Funções
  • Registers the script with the SCM, so that it can act as the service with the given name

win32_start_service_ctrl_dispatcher

(PECL win32service >=0.1.0)

win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name

Descrição

win32_start_service_ctrl_dispatcher(string $name, bool $gracefulMode = true): void

When launched via the Service Control Manager, a service process is required to "check-in" with it to establish service monitoring and communication facilities. This function performs the check-in by spawning a thread to handle the lower-level communication with the service control manager.

Once started, the service process should do 2 things. The first is to tell the Service Control Manager that the service is running. This is achieved by calling win32_set_service_status() with the WIN32_SERVICE_RUNNING constant. If you need to perform some lengthy process before the service is actually running, then you can use the WIN32_SERVICE_START_PENDING constant. The second is to continue to check-in with the service control manager so that it can determine if it should terminate. This is achieved by periodically calling win32_get_last_control_message() and handling the return code appropriately.

Cuidado

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

Parâmetros

name

The short-name of the service, as registered by win32_create_service().

gracefulMode

true for exit graceful. false for exit with error. See win32_set_service_exit_mode() for more details.

Valor Retornado

Nenhum valor é retornado.

Prior to version 1.0.0, retornava WIN32_NO_ERROR em caso de sucesso, false se houver um problema com os parâmetros ou um Código de Erro Win32 em caso de falha.

Erros

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.4.0 | The parameter gracefulMode has been added.
PECL win32service 0.2.0 | This function works only in the "cli" SAPI.

Exemplos

Exemplo #1 A win32_start_service_ctrl_dispatcher() example

Check if the service is runnig under the SCM.

<?php
if (!win32_start_service_ctrl_dispatcher('dummyphp')) {
die("I'm probably not running under the service control manager");
}

win32_set_service_status(WIN32_SERVICE_START_PENDING);

// Some lengthy process to get this service up and running.

win32_set_service_status(WIN32_SERVICE_RUNNING);

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
# do some work here, trying not to take more than around 30 seconds
# before coming back into the loop again
}
?>

Veja Também

  • win32_set_service_status() - Update the service status
  • win32_get_last_control_message() - Returns the last control message that was sent to this service
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32 Error Codes

User Contributed Notes

andrea 09-Oct-2009 03:07
Insert value of params between " if the string have a space:

<?php
// First you need to create a service, you only need to do this once
/*
win32_create_service(array(
    'service' => 'myphpservice',
    'display' => 'My PHP Service',
    'params' => '"c:\\my folder\myphpservice.php"',
    'path' => 'c:\\PHP\\php.exe'));
*/
?>
dylan at nopower dot org 14-Jul-2007 07:59
<?php
// First you need to create a service, you only need to do this once
/*
win32_create_service(array(
    'service' => 'myphpservice',
    'display' => 'My PHP Service',
    'params' => 'c:\\myphpservice.php',
    'path' => 'c:\\PHP\\php.exe'));
*/

$myservicename = 'myphpservice';

// Connect to service dispatcher and notify that startup was successful
if (!win32_start_service_ctrl_dispatcher($myservicename)) die('Could not connect to service :'.$myservicename);
win32_set_service_status(WIN32_SERVICE_RUNNING);

// Main Server Loop
while (1) {
    switch (win32_get_last_control_message()) {
        case WIN32_SERVICE_CONTROL_CONTINUE: break; // Continue server routine
        case WIN32_SERVICE_CONTROL_INTERROGATE: win32_set_service_status(WIN32_NO_ERROR); break; // Respond with status
        case WIN32_SERVICE_CONTROL_STOP: win32_set_service_status(WIN32_SERVICE_STOPPED); exit; // Terminate script
        default: win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }

    // Main script goes here

    sleep(10); // Run every 10 seconds
}
win32_set_service_status(WIN32_SERVICE_STOPPED);
?>
Guibod 10-Jul-2007 05:41
Don't try to call "win32_start_service_ctrl_dispatcher" too late in your code. You'd trigger a #2186 error : "The service is not responding to the control function." (from commande line) or a #1053 error : "The service did not respond to the start or control request in a timely fashion." (from services GUI).

Try not to load a bunch of PEAR classes before to register php script as Service like I did.

Another good hint, to get a verbose version of the return code, you can call "NET HELPMSG ###" from command line where ### is your error code.


Starts a service

  • « win32_start_service_ctrl_dispatcher
  • win32_stop_service »
  • PHP Manual
  • win32service Funções
  • Starts a service

win32_start_service

(PECL win32service >=0.1.0)

win32_start_service — Starts a service

Descrição

win32_start_service(string $servicename, string $machine = ?): void

Attempts to start the named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

Parâmetros

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Valor Retornado

Nenhum valor é retornado.

Prior to version 1.0.0, retornava WIN32_NO_ERROR em caso de sucesso, false se houver um problema com os parâmetros ou um Código de Erro Win32 em caso de falha.

Erros

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

Veja Também

  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Stops a service

  • « win32_start_service
  • Manipulação de XML »
  • PHP Manual
  • win32service Funções
  • Stops a service

win32_stop_service

(PECL win32service >=0.1.0)

win32_stop_service — Stops a service

Descrição

win32_stop_service(string $servicename, string $machine = ?): void

Stops a named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

Parâmetros

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Valor Retornado

Nenhum valor é retornado.

Prior to version 1.0.0, retornava WIN32_NO_ERROR em caso de sucesso, false se houver um problema com os parâmetros ou um Código de Erro Win32 em caso de falha.

Erros

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

Changelog

Versão | Descrição
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

Veja Também

  • win32_start_service() - Starts a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Manipulação de XML

  • DOM — Document Object Model
    • Introdução
    • Instalação/Configuração
    • Constantes pré-definidas
    • Exemplos
    • DOMAttr — Classe DOMAttr
    • DOMCdataSection — The DOMCdataSection class
    • DOMCharacterData — The DOMCharacterData class
    • DOMChildNode — The DOMChildNode interface
    • DOMComment — The DOMComment class
    • DOMDocument — The DOMDocument class
    • DOMDocumentFragment — The DOMDocumentFragment class
    • DOMDocumentType — The DOMDocumentType class
    • DOMElement — The DOMElement class
    • DOMEntity — The DOMEntity class
    • DOMEntityReference — The DOMEntityReference class
    • DOMException — The DOMException class
    • DOMImplementation — The DOMImplementation class
    • DOMNamedNodeMap — The DOMNamedNodeMap class
    • DOMNode — The DOMNode class
    • DOMNodeList — The DOMNodeList class
    • DOMNotation — The DOMNotation class
    • DOMParentNode — The DOMParentNode interface
    • DOMProcessingInstruction — The DOMProcessingInstruction class
    • DOMText — The DOMText class
    • DOMXPath — The DOMXPath class
    • DOM Funções
  • libxml
    • Introdução
    • Instalação/Configuração
    • Constantes pré-definidas
    • libXMLError — The libXMLError class
    • Funções da libxml
  • SimpleXML
    • Introdução
    • Instalação/Configuração
    • Constantes pré-definidas
    • Exemplos
    • SimpleXMLElement — A classe SimpleXMLElement
    • SimpleXMLIterator — A classe SimpleXMLIterator
    • Funções da SimpleXML
  • WDDX
    • Introdução
    • Instalação/Configuração
    • Constantes pré-definidas
    • Exemplos
    • Funções da WDDX
  • XMLDiff — XML diff and merge
    • Introdução
    • Instalação/Configuração
    • XMLDiff\Base — The XMLDiff\Base class
    • XMLDiff\DOM — The XMLDiff\DOM class
    • XMLDiff\Memory — The XMLDiff\Memory class
    • XMLDiff\File — The XMLDiff\File class
  • Analisador de XML
    • Introdução
    • Instalação/Configuração
    • Constantes pré-definidas
    • Manipuladores de Evento
    • Case Folding
    • Códigos de Erro
    • Codificação de caracteres
    • Exemplos
    • Funções para analisar XML
    • XMLParser — The XMLParser class
  • XMLReader
    • Introdução
    • Instalação/Configuração
    • XMLReader — The XMLReader class
  • XMLWriter
    • Introdução
    • Instalação/Configuração
    • Constantes pré-definidas
    • Exemplos
    • XMLWriter — The XMLWriter class
  • XSL
    • Introdução
    • Instalação/Configuração
    • Constantes pré-definidas
    • Exemplos
    • XSLTProcessor — A classe XSLTProcessor

User Contributed Notes

There are no user contributed notes for this page.


Document Object Model

  • Introdução
  • Instalação/Configuração
    • Dependências
    • Instalação
    • Configurações em Execução
    • Tipos de Recurso
  • Constantes pré-definidas
  • Exemplos
  • DOMAttr — Classe DOMAttr
    • DOMAttr::__construct — Creates a new DOMAttr object
    • DOMAttr::isId — Checks if attribute is a defined ID
  • DOMCdataSection — The DOMCdataSection class
    • DOMCdataSection::__construct — Constructs a new DOMCdataSection object
  • DOMCharacterData — The DOMCharacterData class
    • DOMCharacterData::after — Adds nodes after the character data
    • DOMCharacterData::appendData — Append the string to the end of the character data of the node
    • DOMCharacterData::before — Adds nodes before the node
    • DOMCharacterData::deleteData — Remove a range of characters from the node
    • DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset
    • DOMCharacterData::remove — Removes the character data
    • DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node
    • DOMCharacterData::replaceWith — Replaces the character data with new nodes
    • DOMCharacterData::substringData — Extracts a range of data from the node
  • DOMChildNode — The DOMChildNode interface
    • DOMChildNode::after — Adds nodes after the node
    • DOMChildNode::before — Adds nodes before the node
    • DOMChildNode::remove — Removes the node
    • DOMChildNode::replaceWith — Replaces the node with new nodes
  • DOMComment — The DOMComment class
    • DOMComment::__construct — Creates a new DOMComment object
  • DOMDocument — The DOMDocument class
    • DOMDocument::adoptNode — Transfer a node from another document
    • DOMDocument::append — Appends nodes after the last child node
    • DOMDocument::__construct — Creates a new DOMDocument object
    • DOMDocument::createAttribute — Create new attribute
    • DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
    • DOMDocument::createCDATASection — Create new cdata node
    • DOMDocument::createComment — Create new comment node
    • DOMDocument::createDocumentFragment — Create new document fragment
    • DOMDocument::createElement — Create new element node
    • DOMDocument::createElementNS — Create new element node with an associated namespace
    • DOMDocument::createEntityReference — Create new entity reference node
    • DOMDocument::createProcessingInstruction — Creates new PI node
    • DOMDocument::createTextNode — Create new text node
    • DOMDocument::getElementById — Searches for an element with a certain id
    • DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
    • DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace
    • DOMDocument::importNode — Import node into current document
    • DOMDocument::load — Load XML from a file
    • DOMDocument::loadHTML — Load HTML from a string
    • DOMDocument::loadHTMLFile — Load HTML from a file
    • DOMDocument::loadXML — Load XML from a string
    • DOMDocument::normalizeDocument — Normalizes the document
    • DOMDocument::prepend — Prepends nodes before the first child node
    • DOMDocument::registerNodeClass — Register extended class used to create base node type
    • DOMDocument::relaxNGValidate — Performs relaxNG validation on the document
    • DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document
    • DOMDocument::replaceChildren — Replace children in document
    • DOMDocument::save — Dumps the internal XML tree back into a file
    • DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting
    • DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting
    • DOMDocument::saveXML — Dumps the internal XML tree back into a string
    • DOMDocument::schemaValidate — Validates a document based on a schema. Only XML Schema 1.0 is supported.
    • DOMDocument::schemaValidateSource — Validates a document based on a schema
    • DOMDocument::validate — Validates the document based on its DTD
    • DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object
  • DOMDocumentFragment — The DOMDocumentFragment class
    • DOMDocumentFragment::append — Appends nodes after the last child node
    • DOMDocumentFragment::appendXML — Append raw XML data
    • DOMDocumentFragment::__construct — Constructs a DOMDocumentFragment object
    • DOMDocumentFragment::prepend — Prepends nodes before the first child node
    • DOMDocumentFragment::replaceChildren — Replace children in fragment
  • DOMDocumentType — The DOMDocumentType class
  • DOMElement — The DOMElement class
    • 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 — Creates a new DOMElement object
    • DOMElement::getAttribute — Returns value of attribute
    • DOMElement::getAttributeNames — Get attribute names
    • DOMElement::getAttributeNode — Returns attribute node
    • DOMElement::getAttributeNodeNS — Returns attribute node
    • DOMElement::getAttributeNS — Returns value of attribute
    • DOMElement::getElementsByTagName — Gets elements by tagname
    • DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName
    • DOMElement::hasAttribute — Checks to see if attribute exists
    • DOMElement::hasAttributeNS — Checks to see if attribute exists
    • DOMElement::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 — Removes attribute
    • DOMElement::removeAttributeNode — Removes attribute
    • DOMElement::removeAttributeNS — Removes attribute
    • DOMElement::replaceChildren — Replace children in element
    • DOMElement::replaceWith — Replaces the element with new nodes
    • DOMElement::setAttribute — Adds new or modifies existing attribute
    • DOMElement::setAttributeNode — Adds new attribute node to element
    • DOMElement::setAttributeNodeNS — Adds new attribute node to element
    • DOMElement::setAttributeNS — Adds new attribute
    • DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID
    • DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID
    • DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID
    • DOMElement::toggleAttribute — Toggle attribute
  • DOMEntity — The DOMEntity class
  • DOMEntityReference — The DOMEntityReference class
    • DOMEntityReference::__construct — Creates a new DOMEntityReference object
  • DOMException — The DOMException class
  • DOMImplementation — The DOMImplementation class
    • DOMImplementation::__construct — Creates a new DOMImplementation object
    • DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element
    • DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object
    • DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature
  • DOMNamedNodeMap — The DOMNamedNodeMap class
    • DOMNamedNodeMap::count — Get number of nodes in the map
    • DOMNamedNodeMap::getIterator — Retrieve an external iterator
    • DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name
    • DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI
    • DOMNamedNodeMap::item — Retrieves a node specified by index
  • DOMNode — The DOMNode class
    • DOMNode::appendChild — Adiciona um novo filho ao final dos filhos
    • DOMNode::C14N — Canonicalize nodes to a string
    • DOMNode::C14NFile — Canonicalize nodes to a file
    • DOMNode::cloneNode — Clones a node
    • DOMNode::contains — Checks if node contains other node
    • DOMNode::getLineNo — Get line number for a node
    • DOMNode::getNodePath — Get an XPath for a node
    • DOMNode::getRootNode — Get root node
    • DOMNode::hasAttributes — Checks if node has attributes
    • DOMNode::hasChildNodes — Checks if node has children
    • DOMNode::insertBefore — Adds a new child before a reference node
    • DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not
    • DOMNode::isEqualNode — Checks that both nodes are equal
    • DOMNode::isSameNode — Indicates if two nodes are the same node
    • DOMNode::isSupported — Checks if feature is supported for specified version
    • DOMNode::lookupNamespaceURI — Gets the namespace URI of the node based on the prefix
    • DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI
    • DOMNode::normalize — Normalizes the node
    • DOMNode::removeChild — Removes child from list of children
    • DOMNode::replaceChild — Replaces a child
  • DOMNodeList — The DOMNodeList class
    • DOMNodeList::count — Get number of nodes in the list
    • DOMNodeList::getIterator — Retrieve an external iterator
    • DOMNodeList::item — Retrieves a node specified by index
  • DOMNotation — The DOMNotation class
  • DOMParentNode — The DOMParentNode interface
    • DOMParentNode::append — Appends nodes after the last child node
    • DOMParentNode::prepend — Prepends nodes before the first child node
    • DOMParentNode::replaceChildren — Replace children in node
  • DOMProcessingInstruction — The DOMProcessingInstruction class
    • DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object
  • DOMText — The DOMText class
    • DOMText::__construct — Creates a new DOMText object
    • DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content
    • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
    • DOMText::splitText — Quebra este nó em dois nós no deslocamento especificado
  • DOMXPath — The DOMXPath class
    • DOMXPath::__construct — Creates a new DOMXPath object
    • DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible
    • DOMXPath::query — Evaluates the given XPath expression
    • DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object
    • DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions
  • DOM Funções
    • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

User Contributed Notes

chealer at gmail dot com 05-Jul-2018 05:12
This extension allows editing an HTML snippet, for example removing an element:
??$dom = new DOMDocument();
??$dom->loadHTML('keep<b id="simple">REMOVE</b>');
$??remove = $dom->getElementById('simple');
??$dom->removeChild($??remove);
echo ??$dom->saveHTML();
...would output "keep".

But it does not preserve formatting. If your code defines attributes using double quotes, saveHTML() may for instance return single quotes instead.
emmanuellutula at hotmail dot com 24-Apr-2018 04:35
If you want to  use DOMDocument in your PHPUnit Tests drive on Symfony Controller (testing form)! Use like :

namespace Tests\YourBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use YourBundle\Controller\TextController;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient(array(), array());

        $crawler = $client->request('GET', '/text/add');
        $this->assertTrue($crawler->filter("form")->count() > 0, "Text form exist !");

        $form = $crawler->filter("form")->form();

        $domDocument = new \DOMDocument;

        $domInput = $domDocument->createElement('input');
        $dom = $domDocument->appendChild($domInput);
        $dom->setAttribute('slug', 'bloc');

        $formInput = new \Symfony\Component\DomCrawler\Field\InputFormField($domInput);
        $form->set($formInput);

        $crawler = $client->submit($form);

        if ($client->getResponse()->isRedirect())
        {
            $crawler = $client->followRedirect(false);
        }

       // $this->assertTrue($client->getResponse()->isSuccessful());
        //$this->assertEquals(200, $client->getResponse()->getStatusCode(),
        //             "Unexpected HTTP status code for GET /backoffice/login");

    }
}
ohcc at 163 dot com 29-Oct-2015 05:31
<?php
    // this note is about how to get a DOMNode's outerHTML and innerHTML.
    $dom = new DOMDocument('1.0','UTF-8');
    $dom->loadHTML('<html><body><div><p>p1</p><p>p2</p></div></body></html>');
    $node = $dom->getElementsByTagName('div')->item(0);
    $outerHTML = $node->ownerDocument->saveHTML($node);
    $innerHTML = '';
    foreach ($node->childNodes as $childNode){
        $innerHTML .= $childNode->ownerDocument->saveHTML($childNode);
    }
    echo '<h2>outerHTML: </h2>';
    echo htmlspecialchars($outerHTML);
    echo '<h2>innerHTML: </h2>';
    echo htmlspecialchars($innerHTML);
?>
super dot puma at gmail dot com 13-May-2014 04:57
If  you want to print the DOM XML file content, you can use the next code:

$doc = new DOMDocument();
$doc->load($xmlFileName);
echo "<br>" . $doc->documentURI;
$x = $doc->documentElement;
getNodeContent($x->childNodes, 0);

function getNodeContent($nodes, $level){
    foreach ($nodes AS $item) {
    //  print "<br><br>TIPO: " . $item->nodeType ;
      printValues($item, $level);
      if ($item->nodeType == 1) { //DOMElement
          foreach ($item->attributes AS $itemAtt) {
              printValues($itemAtt, $level+3);
          }
          if($item->childNodes || $item->childNodes->lenth > 0) {
              getNodeContent($item->childNodes, $level+5);
          }
      }
    }
}

function printValues($item, $level){
    if ($item->nodeType == 1) { //DOMElement
        printLevel($level);
        print $item->nodeName . " = " . $item->nodeValue;
    }
    if ($item->nodeType == 2) { //DOMAttr
        printLevel($level);
        print $item->name . " = " . $item->value ;
    }
    if ($item->nodeType == 3) { //DOMText
      if ($item->isWhitespaceInElementContent() == false){
        printLevel($level);
        print $item->wholeText ;
      }
    }
}

function printLevel($level)
{
    print "<br>";
    if ($level == 0) {
        print "<br>";
    }
    for($i=0; $i < $level; $i++) {
        print "-";
    }
}
Drupella 16-Sep-2011 09:18
Here is a fast innerHTML function that returns the result without iterating over child nodes.

<?php
function innerHTML($el) {
  $doc = new DOMDocument();
  $doc->appendChild($doc->importNode($el, TRUE));
  $html = trim($doc->saveHTML());
  $tag = $el->nodeName;
  return preg_replace('@^<' . $tag . '[^>]*>|</' . $tag . '>$@', '', $html);
}
?>

Example
<?php
$doc = new DOMDocument();
// A corrupt HTML string
$doc->loadHTML('<HTML><A HREF="ss">asd</A>');
$body = $doc->getElementsByTagName('body')->item(0);
print htmlspecialchars(innerHTML($body));
// Prints <a href="ss">asd</a>
?>
ben_demott at hotmail dot com 23-Apr-2010 01:36
A function among several others to parse a google results page, I wrote this some time ago - google has probably changed their site since then, but I thought this might be helpful to someone.

I'm moving servers, but I will probably throw this up on my blog when I get it back up.

<?php

function googleResult($listItem) {
    // given a LIST ITEM element, this will validate, and return an array for that LI entry as an inline result from google.
    /*
     * <li class='g w0'>
     *   <h3 class='r'>
     *     <a href='the URL' class='l'>
     *       Description <em>description</em>
     *     </a>
     *   </h3>
     * </li>
     *
       UPDATE:
       This function will now look for any subcontainer that has an href, it doesn't have to be an H3
       this will make it work with a few more formatted search results.
     */

    $listItem = $listItem->childNodes;
        // Yes I don't use instanceof - I guess you'll have to deal.
    foreach($listItem as $element) {
        if(is_object($element) && get_class($element) == 'DOMElement' && $element->hasChildNodes()) {
            $hrefContainer = $element->childNodes;
            foreach($hrefContainer as $element2) {
                if(is_object($element2) && get_class($element2) == 'DOMElement' && $element2->nodeName == 'a' && $element2->hasAttribute('href')) {
                    $anchor = $element2;
                    unset($h3);
                    unset($element2);
                    break;
                } else {
                  //print __LINE__ ." :: Breaking out of loop (normal result) element is not an annchor Element='".$element2->nodeName."'\n";
                }
            }
            unset($element);
            unset($listItem);
            break;
        }
    }
    if(empty($anchor) || !is_object($anchor) || get_class($anchor) != 'DOMElement') {
        //print __LINE__ ." :: Returning false, did not locate anchor through iteration...";
        return false;
    }
    $href = $anchor->getAttribute('href');
    if(empty($href)) {
        //print __LINE__ ." :: Found anchor object, could not read href attribute / href is empty? href='$href'\n";
        return false;
    }
    $description = $anchor->childNodes;
    $urlDescription = '';
    foreach($description as $words) {
        $name =  trim($words->nodeName);
        if($name == 'em' || $name == '#text' || $name == 'b') {
            if(!empty($words->nodeValue)) {
                $text = trim($words->nodeValue);
                $urlDescription = $urlDescription . $text . ' ';
            }
        }
    }
    $urlDescription = htmlspecialchars_decode($urlDescription, ENT_QUOTES);
    $urlDescription = trim($urlDescription);
    return array('description' => $urlDescription, 'href' => $href);
}
sweisman at pobox dot com 24-Sep-2009 01:19
I had problems with the dom2array_full function by "nospam at ya dot ru". Here's my function, which works correctly for my project, and might work for yours:

<?php
function dom_to_array($root)
{
    $result = array();

    if ($root->hasAttributes())
    {
        $attrs = $root->attributes;

        foreach ($attrs as $i => $attr)
            $result[$attr->name] = $attr->value;
    }

    $children = $root->childNodes;

    if ($children->length == 1)
    {
        $child = $children->item(0);

        if ($child->nodeType == XML_TEXT_NODE)
        {
            $result['_value'] = $child->nodeValue;

            if (count($result) == 1)
                return $result['_value'];
            else
                return $result;
        }
    }

    $group = array();

    for($i = 0; $i < $children->length; $i++)
    {
        $child = $children->item($i);

        if (!isset($result[$child->nodeName]))
            $result[$child->nodeName] = dom_to_array($child);
        else
        {
            if (!isset($group[$child->nodeName]))
            {
                $tmp = $result[$child->nodeName];
                $result[$child->nodeName] = array($tmp);
                $group[$child->nodeName] = 1;
            }

            $result[$child->nodeName][] = dom_to_array($child);
        }
    }

    return $result;
}
?>
odessa131 at aol dot nospam dot com 20-Sep-2009 06:49
I had the hardest time updating a complex XML document. Here's a quick example on how to do it.

<?php

// Load the XML from a file.
$xml = "a2062.xml"; // This is an XFDL form previously unencoded and ungzipped.
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->Load($xml);

// Create an XPath query.
// Note: you must define the namespace if the XML document has defined namespaces.
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('xfdl', "http://www.PureEdge.com/XFDL/6.5");

// Locate the value for the first Item Description field.
$query = "//xfdl:page/xfdl:field[@sid='ITEMDESA']/xfdl:value";
$nodeList = $xpath->query($query);

$nodeList->item(0)->nodeValue = "This is the text in the value node of the first Item Description field inside the DA 2062 PureEdge form.";

$dom->save($xml);

?>

I hope this helps someone.
philipwaynerollins at gmail dot com 29-Jul-2009 02:06
You can get the "innerHTML" by nodeValue so

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'p', 'Sensei Ninja' );
    print $ele->nodeValue;
?>

You can even set it if you want

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'p' );
    $ele->nodeValue = 'Sensei Ninja';
    $doc->appendChild( $ele );
    print $doc->saveHTML( );
?>
Junior 20-Mar-2009 01:26
innerHTML in PHP DOM

<?php
function DOMinnerHTML($element)
{
    $innerHTML = "";
    $children = $element->childNodes;
    foreach ($children as $child)
    {
        $tmp_dom = new DOMDocument();
        $tmp_dom->appendChild($tmp_dom->importNode($child, true));
        $innerHTML.=trim($tmp_dom->saveHTML());
    }
    return $innerHTML;
}
?>

Example:

<?php
$dom= new DOMDocument();
$dom->load($html_string);
$dom->preserveWhiteSpace = false;

$domTable = $dom->getElementsByTagName("table");

foreach ($domTable as $tables)
{
    echo DOMinnerHTML($tables);
}
?>
nospam at ya dot ru 06-Jan-2009 10:18
<?PHP
function dom2array_full($node){
    $result = array();
    if($node->nodeType == XML_TEXT_NODE) {
        $result = $node->nodeValue;
    }
    else {
        if($node->hasAttributes()) {
            $attributes = $node->attributes;
            if(!is_null($attributes))
                foreach ($attributes as $index=>$attr)
                    $result[$attr->name] = $attr->value;
        }
        if($node->hasChildNodes()){
            $children = $node->childNodes;
            for($i=0;$i<$children->length;$i++) {
                $child = $children->item($i);
                if($child->nodeName != '#text')
                if(!isset($result[$child->nodeName]))
                    $result[$child->nodeName] = dom2array($child);
                else {
                    $aux = $result[$child->nodeName];
                    $result[$child->nodeName] = array( $aux );
                    $result[$child->nodeName][] = dom2array($child);
                }
            }
        }
    }
    return $result;
}
?>
fantasyman3000 at gmail dot com 06-Dec-2008 05:37
In response to "simlee at indiana dot edu",
- First of all thanks for sharing your funciton.
- It didn't work for me so i rewrite it from scratch using different method.

Here is the new version, hope it helps someone :

<?php
/**
* result sample : /html[1]/body[1]/span[1]/fieldset[1]/div[1]
* @return string
*/
function getNodeXPath( $node ) {
    $result='';
    while ($parentNode = $node->parentNode) {
        $nodeIndex=-1;
        $nodeTagIndex=0;
        do {
            $nodeIndex++;
            $testNode = $parentNode->childNodes->item( $nodeIndex );

            if ($testNode->nodeName==$node->nodeName and $testNode->parentNode->isSameNode($node->parentNode) and $testNode->childNodes->length>0) {
                //echo "{$testNode->parentNode->nodeName}-{$testNode->nodeName}-{}<br/>";
                $nodeTagIndex++;
            }

        } while (!$node->isSameNode($testNode));

        $result="/{$node->nodeName}[{$nodeTagIndex}]".$result;
        $node=$parentNode;
    };
    return $result;
}
?>

By Sina.Salek.ws
miguelangelhdz at NOSPAM dot com 22-Sep-2008 06:19
After searching how to extend the DOMDocument and DOMElement I found a way in the bug: http://bugs.php.net/bug.php?id=35104. The following code shows how:

<?php
class extDOMDocument extends DOMDocument {
 public function createElement($name, $value=null) {
  $orphan = new extDOMElement($name, $value); // new  sub-class object
  $docFragment = $this->createDocumentFragment(); // lightweight container maintains "ownerDocument"
  $docFragment->appendChild($orphan); // attach
  $ret = $docFragment->removeChild($orphan); // remove
  return $ret; // ownerDocument set; won't be destroyed on  method exit
 }
 // .. more class definition
}

class extDOMElement extends DOMElement {
 function __construct($name, $value='', $namespaceURI=null) {
  parent::__construct($name, $value, $namespaceURI);
 }
  //  ... more class definition here
}

$doc = new extDOMDocument('test');
$el = $doc->createElement('tagname');
$el->setAttribute("attr", "val");
$doc->appendChild($el);

// append discards the DOMDocumentFragment and just adds its child nodes, but ownerDocument is maintained.
echo get_class($el)."<br/>";
echo get_class($doc->documentElement)."<br/>";
echo "<xmp>".$doc->saveXML()."</xmp>";
?>
tobiasz.cudnik[at]gmail.com 29-Jul-2008 06:47
If you need simple interface to DOM check out phpQuery - jQuery port to PHP:
http://code.google.com/p/phpquery/

It uses CSS selectors to fetch nodes.
Here's example how it works:
<?php
// just one file to include
require('phpQuery/phpQuery.php');

$html = '
<div>
    mydiv
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
</div>';

// intialize new DOM from markup
phpQuery::newDocument($markup)
    ->find('ul > li')
        ->addClass('my-new-class')
        ->filter(':last')
            ->addClass('last-li');

// query all unordered lists in last used DOM
pq('ul')->insertAfter('div');

// iterate all LIs from last used DOM
foreach(pq('li') as $li) {
    // iteration returns plain DOM nodes, not phpQuery objects
    pq($li)->addClass('my-second-new-class');
}

// same as pq('anything')->htmlOuter()
// but on document root (returns doctype etc)
print phpQuery::getDocument();
?>

It uses DOM extension and XPath so it works only in PHP5.
Sven Arduwie 16-Mar-2008 06:28
I needed a function that quickly converts an xml with key/value pairs to an array.

for example:
<?xml version="1.0" encoding="UTF-8"?>
<test>
    <key id="Array key #1" value="Value #1"/>
    <key id="Array key #2" value="Value #2"/>
    <key id="Dupe" value="Duplicate keys"/>
    <key id="Dupe" value="create numeric arrays"/>
    <key id="And another key">
        <![CDATA[
            Multiline
            data
            works
            just
            as
            well.
        ]]>
    </key>
    <nested>
        <key id="Nested key" value="Nested data works as well, but it still results in a 1 dimensional array."/>
    </nested>
</test>

Results in the following array:
array(5) {
  ["Array key #1"]=>
  string(8) "Value #1"
  ["Array key #2"]=>
  string(8) "Value #2"
  ["Dupe"]=>
  array(2) {
    [0]=>
    string(14) "Duplicate keys"
    [1]=>
    string(21) "create numeric arrays"
  }
  ["And another key"]=>
  string(49) "Multiline
            data
            works
            just
            as
            well."
  ["Nested key"]=>
  string(73) "Nested data works as well, but it still results in a 1 dimensional array."
}

Here's the code:
<?php
    function xml2array($xml) {
        $domDocument = new DOMDocument;
        $domDocument->loadXML($xml);
        $domXPath = new DOMXPath($domDocument);
        $array = array();
        foreach ($domXPath->query('//key') as $keyDOM) {
            $id = $keyDOM->getAttribute('id');
            $value = $keyDOM->hasAttribute('value') ? $keyDOM->getAttribute('value') : trim($keyDOM->textContent);
            if (array_key_exists($id, $array)) {
                if (is_array($array[$id])) {
                    $array[$id][] = $value;
                } else {
                    $array[$id] = array($array[$id]);
                    $array[$id][] = $value;
                }
            } else {
                $array[$id] = $value;
            }
        }
        return $array;
    }
?>
danf dot 1979 at []gmail[] dot com 24-Feb-2008 07:47
This is a couple of classes to deal with yahoo yui menu.

/*
  $menubar = new MenuBar();

  $file = new Menu("File");
  $file->setAttribute("href", "http://file.com");

  $quit = new Menu("Quit");
  $quit->setAttribute("href", "http://quit.com");

  $file->appendChild($quit);
  $menubar->appendChild($file);

  echo $menubar->grab();
*/

//
// Author: Daniel Queirolo.
// LGPL
//

/** ---------------------------------
/**  Class MenuBar()
/**  Creates a the menubar and appends
/**  yuimenubaritems to it.
/** ---------------------------------*/

class MenuBar extends DOMDocument
{

  public $menuID = "nav_menu";  // holds the css id that javascript yui menu code should have to recognize
  private $UL;                  // This node holds every menu, This is THE node.

  /** ---------------------------------
  /**  Constructor
  /**  Generates a menubar skeleton and the UL node
  /** ---------------------------------*/

  public function __construct() {

    parent::__construct();

    $rootdiv = parent::createElement("div");
    $rootdiv->setAttribute("class", "yui-skin-sam");

    parent::appendChild($rootdiv);

    $yui_menubar = parent::createElement("div");
    $yui_menubar->setAttribute("id", $this->menuID);
    $yui_menubar->setAttribute("class", "yuimenubar");

    $rootdiv->appendChild($yui_menubar);

    $bd = parent::createElement("div");
    $bd->setAttribute("class", "bd");

    $yui_menubar->appendChild($bd);

    $ul = parent::createElement("ul");
    $ul->setAttribute("class", "first-of-type");

    // ALL Menu() instances ocurr inside an <ul> tag.

    $this->UL = $bd->appendChild($ul);

  }

  /** ---------------------------------
  /**  appendChild()
  /**  Appends a new yuimenubaritem to the menubar UL node.
  /**  This function changes <li> and <a> classes to yuiMENUBARsomething
  /** ---------------------------------*/

  public function appendChild($child) {

    $li = parent::importNode($child->LI, true);

    $li->setAttribute("class", "yuimenubaritem");

    $li->getElementsByTagName("a")->item(0)->setAttribute("class", "yuimenubaritemlabel");

    $this->UL->appendChild($li);

  }

  public function grab() {

    return parent::saveHTML();

  }

}

/** ---------------------------------
/**  Class Menu()
/**  Creates a yuimenuitem li node
/** ---------------------------------*/

class Menu extends DOMDocument {

  public $LI; // stores the <li> node (THE link) that will be exported to MenuBar() or used on appendChild()

  /** ---------------------------------
  /**  Constructor
  /**  Generates a yuimenuitem li node
  /**  No yuimenubar items are created here. MenuBar handles that.
  /** ---------------------------------*/

  public function __construct($link_name) {

    parent::__construct();

    $li = parent::createElement("li");
    $li->setAttribute("class", "yuimenuitem");

    // LI node stores THE link.
    // if appendChild is used, the new (sub) Menu() would be LI node child.

    $this->LI = parent::appendChild($li);

    $a = parent::createElement("a", $link_name);
    $a->setAttribute("class", "yuimenuitemlabel");

    $li->appendChild($a);

    $this->li = $li;
    $this->a = $a;

  }

  /** ---------------------------------
  /**  appendChild
  /**  Appends a (sub) Menu() to current Menu() in LI
  /** ---------------------------------*/

  public function appendChild($child) {

    $yuimenu = parent::createElement("div");
    $yuimenu->setAttribute("class", "yuimenu");

    $this->LI->appendChild($yuimenu);

    $bd = parent::createElement("div");
    $bd->setAttribute("class", "bd");

    $yuimenu->appendChild($bd);

    $ul = parent::createElement("ul");

    $bd->appendChild($ul);

    // child->NODE holds THE link from the new child (from child's __construct())

    $ul->appendChild(parent::importNode($child->LI, true));

  }

  public function setAttribute($name, $value, $node="a") {

      if ($node == "a") {
        $this->a->setAttribute($name, $value);
      }

      else {
        $this->li->setAttribute($name, $value);
      }
  }

}
Anonymous 29-Jan-2008 11:37
In response to...
"If you create your own custom element extending DOMElement and append him in place of the document element, you cannot access to any new members newly defined in your custom class via DOMDocument::$documentElement."

... it is not a bug, it is a feature. The DOMDocument::$documentElement property name may be misleading but according to the DOM Level 2 Core specification it is a convenience attribute meant to access the root element of your DOMDocument. See here: http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document
ryoroxdahouse at hotmail dot com 25-Jan-2008 12:14
I use DOM to generate dynamically XHTML document.

When trying to extend the DOMDocument and DOMElement classes, I found a very annoying bug concerning DOMDocument::$documentElement.

If you create your own custom element extending DOMElement and append him in place of the document element, you cannot access to any new members newly defined in your custom class via DOMDocument::$documentElement.

In my situation, I cannot use DOMDocument::registerNodeClass() because the document element is not necessarily the base class for all the elements in my document.

*******
problem
*******

See bellow for the repro step:

<?php
    class MyElement extends DOMElement{
        public $myProp="myProp";
        public function myMethod(){
            return 'myMethod()';
        }
    }

    $myDocument=new DOMDocument();
    $myDocument->appendChild(new MyElement('myElement','myElement'));
    echo ('$myElement->myProp :'.$myDocument->documentElement->myProp.'<br />');
    echo ('$myElement->myMethod :'.$myDocument->documentElement->myMethod().'<br />');
?>

will output:

Notice: Undefined property: DOMElement::$myProp in C:\Program Files\EasyPHP 2.0b1\www\testDOMBug\test2.php on line 11
$myElement->myProp :

Fatal error: Call to undefined method DOMElement::myMethod() in C:\Program Files\EasyPHP 2.0b1\www\testDOMBug\test2.php on line 12

*******
solution
*******

After searching around, I found a pretty odd way to fix this problem. It seems that you have to stock a reference to your appended document element in an user-defined (and persistent) variable (in other words, not only in DOMDocument::$documentElement). See below:

<?php
    class MyElement extends DOMElement{
        public $myProp="myProp";
        public function myMethod(){
            return 'myMethod()';
        }
    }

    $myDocument=new DOMDocument();
    $mydocumentElement=$myDocument->appendChild(new MyElement('myElement','myElement')); //here is the hack
    echo ('$myElement->myProp :'.$myDocument->documentElement->myProp.'<br />');
    echo ('$myElement->myMethod :'.$myDocument->documentElement->myMethod().'<br />');
?>

will output:

$myElement->myProp :myProp
$myElement->myMethod :myMethod()

Hope it will help.
naudyj at aus3d.com 03-Jan-2008 05:06
The following can take a XML_TEXT_NODE node and return the contents in an array. Yanick's contribution rocks - but
it overwrote with duplicates only keeping the last line
in the returned array. All the other functions i tested from various sources failed to handle text nodes correctly. Hope this helps someone. It is adapted from code on this site.

function myTextNode($n, &$a)
{
 static $depth = 0;
 static $sz = '';

 if ($cn = $n->firstChild)
 {
  while ($cn)
  {
   if ($cn->nodeType == XML_TEXT_NODE)
   {
    $sz .= $cn->nodeValue;
   }
   elseif ($cn->nodeType == XML_ELEMENT_NODE)
   {
    $b = 1;
    if ($cn->hasChildNodes())
    {
     $depth++;
     if ($this->myHeadings($cn, $a))
     {
      if ($sz){
       array_push($a, $sz);
       $sz = '';
      }
     }
     $depth--;
    }
   }
   $cn = $cn->nextSibling;
  }
  return $b;
 }
}

so you could use:

$nodes = $dom->getElementsByTagName("td");
if($nodes){
 foreach ($nodes as $node){
  $a = Array();
  myTextNode($node, $a);
 }
}
jim.filter (at gmail.com) 03-Nov-2007 07:42
Array to DOM

Here is a recursive function to turn a multidimensional array into an XML document.  It will handle multiple elements of the same tag, but only one per parent element. IE:

Can't generate:         Can generate:
<root>                  <root>
  <sub1>data1</sub1>      <subs1>
  <sub1>data2</sub1>         <value>data1</value>
  <sub2>data1</sub2>         <value>data2</value>
  <sub2>data2</sub2>      </subs1>
</root>                   <subs2>
                            <value>data1</value>
                            <value>data2</value>
                          <subs2>
                        </root>

Also, the function performs no type of error checking on your array and will throw a DOMException if a key value you used in your array contains invalid characters for a proper DOM tag. This function is untested for "deep" multidimensional arrays.

Complete code ready to run with example:

<?PHP
  function AtoX($array, $DOM=null, $root=null){

    if($DOM  == null){$DOM  = new DOMDocument('1.0', 'iso-8859-1');}
    if($root == null){$root = $DOM->appendChild($DOM->createElement('root'));}

    $name = $array['#MULTIPLE_ELEMENT_NAME'];

      foreach($array as $key => $value){
        if(is_int($key) && $name != null){
          if(is_array($value)){
            $subroot = $root->appendChild($DOM->createElement($name));
            AtoX($value, $DOM, $subroot);
          }
          else if(is_scalar($value)){
            $root->appendChild($DOM->createElement($name, $value));
          }
        }
        else if(is_string($key) && $key != '#MULTIPLE_ELEMENT_NAME'){
          if(is_array($value)){
            $subroot = $root->appendChild($DOM->createElement($key));
            AtoX($value, $DOM, $subroot);
          }
          else if(is_scalar($value)){
            $root->appendChild($DOM->createElement($key, $value));
          }
        }
      }
    return $DOM;
  }

  $array = array(
                    '#MULTIPLE_ELEMENT_NAME' => 'GenericDatas',
                    'Date'      => 'November 03, 2007',
                    'Company'   => 'Facility One',
                    'Field'     => 'Facility Management Software',
                    'Employees' => array(
                                      '#MULTIPLE_ELEMENT_NAME' => 'Employee',
                                      'Cindy',
                                      'Sean',
                                      'Joe',
                                      'Owen',
                                      'Jim',
                                      'Dale',
                                      'Kelly',
                                      'Ryan',
                                      'Johnathan',
                                      'Robin',
                                      'William Marcus',
                                      'NewCoops' => array(
                                                          '#MULTIPLE_ELEMENT_NAME' => 'Coop',
                                                          'John',
                                                          'Tyler',
                                                          'Ray',
                                                          'Dawn'
                                                         )
                                    ),
                    'Datas',
                    'DATAS',
                    'OtherDatas'
                );

  $DOM  = new DOMDocument('1.0', 'iso-8859-1');
  $root = $DOM->appendChild($DOM->createElement('CompanyData'));
  $DOM  = AtoX($array, $DOM, $root);
  $DOM->save('C:\test.xml');
?>
PHPdeveloper 06-Sep-2007 02:46
The Yanik's dom2array() function (added on 14-Mar-2007 08:40) does not handle multiple nodes with the same name, i.e.:

<foo>
  <name>aa</name>
  <name>bb</name>
</foo>

It will overwrite former and your array will contain just the last one ("bb")
Francois Hill 01-Aug-2007 11:21
In response to lutfi at smartconsultant dot us :

(see my post on
http://fr2.php.net/manual/en/
function.dom-domdocument-getelementsbytagname.php
)

Use this class I wrote:

class XPathableNode extends DOMNode
{
    protected $Node;
    protected $DOMDocument_from_node;
    protected $DOMXpath_for_node;

    public function __construct(/* DOMNode */ $node)
    {
        $this->Node=$node;
        $this->DOMDocument_from_node=new
                                                          DomDocument();
        $domNode=$this->DOMDocument_from_node
                                  ->importNode($this->Node, true);
        $this->DOMDocument_from_node
                                 ->appendChild($domNode);
        $this->DomXpath_for_node =
                    new Domxpath($this->
                                         DOMDocument_from_node);
    }

    public function convertHTML()
    {    return $this->DOMDocument_from_node
                                                             ->saveHTML();
    }

    public /*DomNodeList*/ function applyXpath($xpath)
    {    return $this->DomXpath_for_node
                                                       ->query($xpath);
    }
}

(sorry for the display... What a terrible hinderance on the
part of php.net !)

Then :
Make a new XPathableNode out of your parent node.
You may then retrieve a DOMNodeList from it by applying a
xpath (thus being able to specify the depth  and name of
elements you want).

Has got me around some (of the many) DOM awkwardnesses a few times.

;o)
Sanados at failure dot at 05-Jun-2007 02:45
appended to
brian dot reynolds at risaris dot com
20-Feb-2007 10:09

when you got variable nodes at start you array fails and looses nodes  beneath.
solution that counts occurance though eats up performance:

function xmlToArray($n)
{
    $xml_array = array();
    $occurance = array();

     foreach($n->childNodes as $nc)
     {
         $occurance[$nc->nodeName]++;
     }

    foreach($n->childNodes as $nc){
        if( $nc->hasChildNodes() )
        {
            if($occurance[$nc->nodeName] > 1)
            {
                $xml_array[$nc->nodeName][] = xmlToArray($nc);
            }
            else
            {
                $xml_array[$nc->nodeName] = xmlToArray($nc);
            }
        }
        else
        {
            return utf8_decode($nc->nodeValue);
        }
    }
    return $xml_array;
}
Yanik <clonyara(at)ahoo(dot)com> 13-Mar-2007 11:40
I hate DOM model !
so I wrote dom2array simple function (simple for use):

function dom2array($node) {
  $res = array();
  print $node->nodeType.'<br/>';
  if($node->nodeType == XML_TEXT_NODE){
      $res = $node->nodeValue;
  }
  else{
      if($node->hasAttributes()){
          $attributes = $node->attributes;
          if(!is_null($attributes)){
              $res['@attributes'] = array();
              foreach ($attributes as $index=>$attr) {
                  $res['@attributes'][$attr->name] = $attr->value;
              }
          }
      }
      if($node->hasChildNodes()){
          $children = $node->childNodes;
          for($i=0;$i<$children->length;$i++){
              $child = $children->item($i);
              $res[$child->nodeName] = dom2array($child);
          }
      }
  }
  return $res;
}
Nevyn at N dot O dot S dot P dot A dot M dot emai dot it 10-Mar-2007 07:35
I wrote a couple of functions to:
 - create a DOMDocument from a file
 - parse the namespaces in it
 - create a XPath object with all the namespaces registered
 - load the schemalocations
 - validate the file on the main schema (the one without prefix)

It is useful for me, see if it is also for someone else!!

Giulio

function decodeNode($node)
{
    $out = $node->ownerDocument->saveXML($node);
    $re = "{^<((?:\\w*:)?\\w*)". //the tag name
    "[\\s\n\r]*((?:[\\s\n\r]*".
    "(?:\\w*:)?\\w+[\\s\n\r]*=[\\s\n\r]*". //possible attribute name
    "(?:\"[^\"]*\"|\'[^\']*\'))*)". //attribute value
    "[\\s\n\r]*>[\r\n]*".
    "((?:.*[\r\n]*)*)". //content
    "[\r\n]*</\\1>$}"; //closing tag
    preg_match($re, $out, $mat);
    return $mat;
}

function innerXml($node)
{
    $mat = decodeNode($node);
    return $mat[3];
}

function getnodeAttributes($node)
{
    $mat = decodeNode($node);
    $txt = $mat[2];
    $re = "{((?:\\w*:)?\\w+)[\\s\n\r]*=[\\s\n\r]*(\"[^\"]*\"|\'[^\']*\')}";
    preg_match_all($re, $txt, $mat);
    $att = array();
    for ($i=0; $i<count($mat[0]); $i++)
    {
        $value = $mat[2][$i];
        if ($value[0] == "\'" || $value[0] == "\"")
        {
            $len = strlen($value);
            $value = substr($value, 1, strlen($value)-2);
        }
        $att[ $mat[1][$i] ] = $value;
    }
    return $att;
}

function loadXml($file)
{
    $doc = new DOMDocument();
    $doc->load($file);
    //cerca l'attributo xmlns
    $xsi = false;
    $doc->namespaces = array();
    $doc->xpath = new DOMXPath($doc);

    $attr = getnodeAttributes($doc->documentElement);
    foreach ($attr as $name => $value)
    {
        if (substr($name,0,5) == "xmlns")
        {
            $uri = $value;
            $pre = $doc->documentElement->lookupPrefix($uri);
            if ($uri == "http://www.w3.org/2001/XMLSchema-instance")
                $xsi = $pre;
            $doc->namespaces[$pre] = $uri;
            if ($pre == "")
                $pre = "noname";
            $doc->xpath->registerNamespace($pre, $uri);
        }
    }

    if ($xsi)
    {
        $doc->schemaLocations = array();
        $lst = $doc->xpath->query("//@$xsi:schemaLocation");
        foreach($lst as $el)
        {
            $re = "{[\\s\n\r]*([^\\s\n\r]+)[\\s\n\r]*([^\\s\n\r]+)}";
            preg_match_all($re, $el->nodeValue, $mat);
            for ($i=0; $i<count($mat[0]); $i++)
            {
                $value = $mat[2][$i];
                $doc->schemaLocations[ $mat[1][$i] ] = $value;
            }
        }

        $olddir = getcwd();
        chdir(dirname($file));
        $schema = $doc->schemaLocations[$doc->namespaces[""]];
        if (substr($schema,0,7) == "file://")
        {
            $schema = substr($value,7);
        }
        if (!$doc->schemaValidate($schema))
            dbg()->err("Invalid file");
        chdir($olddir);
    }

    return $doc;
}
brian dot reynolds at risaris dot com 20-Feb-2007 01:09
I found the xml2array function below very useful, but there seems to be a bug in it. The $item variable was never getting set. I've expanded this out to be a bit more readable, and the corrected code is :

function xmlToArray($n)
{
    $return=array();

    foreach($n->childNodes as $nc){
        if( $nc->hasChildNodes() ){
            if( $n->firstChild->nodeName== $n->lastChild->nodeName&&$n->childNodes->length>1){
                $item = $n->firstChild;
                $return[$nc->nodeName][]=$this->xmlToArray($item);
            }
            else{
                 $return[$nc->nodeName]=$this->xmlToArray($nc);
            }
       }
       else{
           $return=$nc->nodeValue;
       }
    }
    return $return;
}
cooper at asu dot ntu-kpi dot kiev dot ua 22-Nov-2006 02:32
If you are using not object-oriented functions and it takes too much time to change them all (or you'll be replacing them later) then as a temporary decision can be used this modules:

For DOM XML:
http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/

For XSLT:
http://alexandre.alapetite.net/doc-alex/xslt-php4-php5/
sean at lookin3d dot com 17-Aug-2006 10:21
$xmlDoc=<<<XML
<?xml version="1.0"?>
<methodCall>
   <methodName>examples.getStateName</methodName>
   <params>
      <param>
         <value><i4>41</i4></value>
         </param>
      </params>
   </methodCall>
XML;

$xml= new DOMDocument();
$xml->preserveWhiteSpace=false;
$xml->loadXML($xmlDoc);
print_r(xml2array($xml));

function xml2array($n)
{
    $return=array();
    foreach($n->childNodes as $nc)
    ($nc->hasChildNodes())
    ?($n->firstChild->nodeName== $n->lastChild->nodeName&&$n->childNodes->length>1)
    ?$return[$nc->nodeName][]=xml2array($item)
    :$return[$nc->nodeName]=xml2array($nc)
    :$return=$nc->nodeValue;
    return $return;
}
simlee at indiana dot edu 29-Dec-2005 12:16
The project I'm currently working on uses XPaths to dynamically navigate through chunks of an XML file.  I couldn't find any PHP code on the net that would build the XPath to a node for me, so I wrote my own function.  Turns out it wasn't as hard as I thought it might be (yay recursion), though it does entail using some PHP shenanigans...

Hopefully it'll save someone else the trouble of reinventing this wheel.

<?php
    function getNodeXPath( $node ) {
        // REMEMBER THAT XPATHS USE BASE-1 INSTEAD OF BASE-0!!!

        // Get the index for the current node by looping through the siblings.
        $parentNode = $node->parentNode;
        if( $parentNode != null ) {
            $nodeIndex = 0;
            do {
                $testNode = $parentNode->childNodes->item( $nodeIndex );
                $nodeName = $testNode->nodeName;
                $nodeIndex++;

                // PHP trickery!  Here we create a counter based on the node
                //  name of the test node to use in the XPath.
                if( !isset( $$nodeName ) ) $$nodeName = 1;
                else $$nodeName++;

                // Failsafe return value.
                if( $nodeIndex > $parentNode->childNodes->length ) return( "/" );
            } while( !$node->isSameNode( $testNode ) );

            // Recursively get the XPath for the parent.
            return( getNodeXPath( $parentNode ) . "/{$node->nodeName}[{$$nodeName}]" );
        } else {
            // Hit the root node!  Note that the slash is added when
            //  building the XPath, so we return just an empty string.
            return( "" );
        }
    }
?>
johanwthijs-at-hotmail-dot-com 14-Dec-2005 06:25
Being an experienced ASP developer I was wondering how to replace textual content of a node (with msxml this is simply acheived by setting the 'text' property of a node). Out of frustration I started to play around with SimpleXml but I could not get it to work in combination with xPath.

I took me a lot of time to find out so I hope this helps others:

function replaceNodeText($objXml, $objNode, $strNewContent){
    /*
    This function replaces a node's string content with strNewContent
    */
    $objNodeListNested = &$objNode->childNodes;
    foreach ( $objNodeListNested as $objNodeNested ){
         if ($objNodeNested->nodeType == XML_TEXT_NODE)$objNode->removeChild ($objNodeNested);
    }

    $objNode->appendChild($objXml->createTextNode($strNewContent));
}

$objXml= new DOMDocument();
$objXml->loadXML('<root><node id="1">bla</note></root>');
$objXpath = new domxpath($objXml);

$strXpath="/root/node[@id='1']";
$objNodeList = $objXpath ->query($strXpath);
foreach ($objNodeList as $objNode){
//pass the node by reference
replaceNodeText($objXml, &$objNode, $strImportedValue);
}
mark at vectrex dot org dot uk 17-Nov-2005 02:10
Note that these DOM functions expect (and presumably return) all their data in UTF-8 character encoding, regardless of what PHP's current encoding is. This means that text nodes, attribute values etc, should be in utf8.

This applies even if you're generating an XML document which is not ultimately in utf8.

Mark
toby at tobiasly dot com 22-Oct-2005 11:08
This module is not included by default either in the CentOS 4 "centosplus" repository. For those using PHP5 on CentOS 4, a simple "yum --enablerepo=centosplus install php-xml" will do the trick (this will install both the XML and DOM modules).
pes_cz 29-Sep-2005 12:32
When I tried to parse my XHTML Strict files with DOM extension, it couldn't understand xhtml entities (like &copy;). I found post about it here (14-Jul-2005 09:05) which adviced to add resolveExternals = true, but it was very slow. There was some small note about xml catalogs but without any glue. Here it is:

XML catalogs is something like cache. Download all needed dtd's to /etc/xml, edit file /etc/xml/catalog and add this line: <public publicId="-//W3C//DTD XHTML 1.0 Strict//EN" uri="file:///etc/xml/xhtml1-strict.dtd" />

Thats all. Thanks to http://www.whump.com/moreLikeThis/link/03815
amir.laherATcomplinet.com 22-Aug-2005 05:09
This particular W3C page provides invaluable documentation for the DOM classes implemented in php5 (via libxml2). It fills in plenty of php.net's gaps:

http://www.w3.org/TR/DOM-Level-2-Core/core.html

Some key examples:
* concise summary of the class heirachy (1.1.1)
* clarification that DOM level 2 doesn't allow for population of internal DTDs
* explanation of DOMNode->normalize()
* explanation of the DOMImplementation class

The interfaces are described in OMG's Interface Definition Language
aidan at php dot net 19-Jul-2005 06:04
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:

DomDocument->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);

DomDocument->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
aidan at php dot net 18-Jul-2005 08:27
When dealing with validation or loading, the output errors can be quite annoying.

PHP 5.1 introduces libxml_get_errors().

http://php.net/libxml_get_errors
php at webdevelopers dot cz 14-Jul-2005 12:05
[Editor's Note: If you're using entities, then you have no choice. XML Catalogs can speed DTD resolution.]

Never use

$dom->resolveExternals=true;

when parsing XHTML document that has the DOCTYPE declaration with DTD URL specified in it.

Otherwise parsing the XHTML with DOCTYPE like this one:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

will result in PHP/DOM downloading the DTD file from W3C site when parsing your document. It will add extra delay to your script - I experienced that $dom->load()'s total time was from 1 to 16 seconds.

elixon
spammable69 at hotmail dot com 11-Apr-2005 10:18
I wrote a framework to implement the StyleSheet interfaces as specified on the W3C website.  The code is written in PHP, and is NOT a complete implementation.  Use it how ya like.  I was planning on adding the CSSStyleSheet interfaces as well.  Feel free to ask.

<?
    class StyleSheetList {
        public length;
        private self;

        function __construct ( ) {
            $this->self = array();
        }

        function __get($property, $&ret) {
            if($property == 'length')
                $ret = count($this->self);
            return true;
        }

        function __set($property, $val) {
            if($property == 'length')
                return true;
        }

        function item( $index ) {
            return $this->self[$index];
        }
    }

    class MediaList extends StyleSheetList {

        function appendMedium ( $newMedium ) {
            array_push($this->self, $newMedium);
        }

        function deleteMedium ( $oldMedium ) {
            foreach($this->self as $item) {
                if( $item == $oldMedium ) {
                    $item = $this->self[ $this->length-1 ];
                    array_pop($this->self);
                    break;
                }
            }
        }
    }

    class DocumentStyle {
        public styleSheets;

        function __construct ( ) {
            $this->styleSheets = new StyleSheetList();
        }

        function __set($property, $val) {
            if($property == 'styleSheets')
                return true;
        }
    }

    class LinkStyle {
        public sheet;

        function __construct () {
            $this->sheet = new StyleSheet();
        }

        function __set($property, $val) {
            if($property == 'sheet')
                return true;
        }
    }

    class StyleSheet {
        public type;
        public disabled;
        public ownerNode;
        public parentStyleSheet;
        public href;
        public title;
        public media;

        function __construct( $type, $disabled, $ownerNode, $parentStyleSheet, $href, $title){
            $this->type = $type;
            $this->disabled = $disabled;
            $this->media = new MediaList();
            $this->ownerNode = $ownerNode;
            $this->parentStyleSheet = $parentStyleSheet;
            $this->href = $href;
            $this->title = $title;
        }
    }
?>

Only contactable via http://murpsoft.com/contact.html


Introdução

A extensão DOM permite operar em documentos XML e HTML através da API DOM diretamente do PHP.

Nota:

A extensão DOM usa codificação UTF-8. Use mb_convert_encoding(), UConverter::transcode() ou iconv() para lidar com outras codificações.

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


Instalação

Esta extensão está habilitada por padrão. Ela pode ser desabilitada usando a seguinte opção em tempo de compilação: --disable-dom

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-definidas

As contantes abaixo são definidas por esta extensão e só estarão disponíveis quando a extensão tiver sido compilada no PHP ou tiver sido carregada dinamicamente em tempo de execução.

Constantes XML
Constante | Valor | Descrição
XML_ELEMENT_NODE (int) | 1 | Nó é um DOMElement
XML_ATTRIBUTE_NODE (int) | 2 | Nó é um DOMAttr
XML_TEXT_NODE (int) | 3 | Nó é um DOMText
XML_CDATA_SECTION_NODE (int) | 4 | Nó é um DOMCharacterData
XML_ENTITY_REF_NODE (int) | 5 | Nó é um DOMEntityReference
XML_ENTITY_NODE (int) | 6 | Nó é um DOMEntity
XML_PI_NODE (int) | 7 | Nó é um DOMProcessingInstruction
XML_COMMENT_NODE (int) | 8 | Nó é um DOMComment
XML_DOCUMENT_NODE (int) | 9 | Nó é um DOMDocument
XML_DOCUMENT_TYPE_NODE (int) | 10 | Nó é um DOMDocumentType
XML_DOCUMENT_FRAG_NODE (int) | 11 | Nó é um DOMDocumentFragment
XML_NOTATION_NODE (int) | 12 | Nó é um DOMNotation
XML_HTML_DOCUMENT_NODE (int) | 13 |
XML_DTD_NODE (int) | 14 |
XML_ELEMENT_DECL_NODE (int) | 15 |
XML_ATTRIBUTE_DECL_NODE (int) | 16 |
XML_ENTITY_DECL_NODE (int) | 17 |
XML_NAMESPACE_DECL_NODE (int) | 18 |
XML_ATTRIBUTE_CDATA (int) | 1 |
XML_ATTRIBUTE_ID (int) | 2 |
XML_ATTRIBUTE_IDREF (int) | 3 |
XML_ATTRIBUTE_IDREFS (int) | 4 |
XML_ATTRIBUTE_ENTITY (int) | 5 |
XML_ATTRIBUTE_NMTOKEN (int) | 7 |
XML_ATTRIBUTE_NMTOKENS (int) | 8 |
XML_ATTRIBUTE_ENUMERATION (int) | 9 |
XML_ATTRIBUTE_NOTATION (int) | 10 |
Constantes DOMException
Constante | Valor | Descrição
DOM_PHP_ERR (int) | 0 | Código não pertencente á especificação DOM. Significativa apenas para erros do PHP
DOM_INDEX_SIZE_ERR (int) | 1 | Se o índice ou tamanho for negativo, ou maior do que o permitido.
DOMSTRING_SIZE_ERR (int) | 2 | Se o tamanho do texto especificado não couber em DOMString.
DOM_HIERARCHY_REQUEST_ERR (int) | 3 | Se algum nó for inserido em um lugar que não o pertence
DOM_WRONG_DOCUMENT_ERR (int) | 4 | Se um nó é utilizado em um documento diferente ao qual foi criado
DOM_INVALID_CHARACTER_ERR (int) | 5 | Se um caracter inválido é utilizado, como por exemplo em um nome.
DOM_NO_DATA_ALLOWED_ERR (int) | 6 | Se um conteúdo é utilizado com um nó que não suporta conteúdo.
DOM_NO_MODIFICATION_ALLOWED_ERR (int) | 7 | Se ocorrer uma tentativa de modificação é feita em um objeto que não permite modificações
DOM_NOT_FOUND_ERR (int) | 8 | Se ocorrer uma tentativa de referênciar um nó em um contexto onde o mesmo não existe.
DOM_NOT_SUPPORTED_ERR (int) | 9 | Se a implementação não suportar o tipo de objeto ou operação solicitados.
DOM_INUSE_ATTRIBUTE_ERR (int) | 10 | Se ocorrer a tentativa de adicionar um atributo que já está em uso em outro lugar.
DOM_INVALID_STATE_ERR (int) | 11 | Se ocorrer a tentativa de usar um objeto que não é mais válido.
DOM_SYNTAX_ERR (int) | 12 | Se um conjunto de caracteres inválido ou ilegal for utilizado.
DOM_INVALID_MODIFICATION_ERR (int) | 13 | If an attempt is made to modify the type of the underlying object.
DOM_NAMESPACE_ERR (int) | 14 | Se uma tentativa de criar ou modificar um objeto incorretamente considerando namespaces.
DOM_INVALID_ACCESS_ERR (int) | 15 | Se o parâmetro ou operação não é suportada pelo objeto subjacente.
DOM_VALIDATION_ERR (int) | 16 | Se uma chamada á um método como insertBefore ou removeChild invalidar o nó respeitando a "validação parcial", essa exceção será lançada e a operação não será realizada.

User Contributed Notes

There are no user contributed notes for this page.


Exemplos

Many examples in this reference require an XML file. We will use book.xml that contains the following:

Exemplo #1 book.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
]>
<book id="listing">
 <title>My lists</title>
 <chapter id="books">
  <title>My books</title>
  <para>
   <informaltable>
    <tgroup cols="4">
     <thead>
      <row>
       <entry>Title</entry>
       <entry>Author</entry>
       <entry>Language</entry>
       <entry>ISBN</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
      <row>
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
      <row>
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
      <!-- TODO: I have a lot of remaining books to add.. -->
     </tbody>
    </tgroup>
   </informaltable>
  </para>
 </chapter>
</book>

User Contributed Notes

There are no user contributed notes for this page.


Classe DOMAttr

(PHP 5, PHP 7, PHP 8)

Introdução

DOMAttr representa um atributo no objeto DOMElement.

Sinopse da classe

class DOMAttr extends DOMNode {
/* Propriedades */
public readonly string $name;
public readonly bool $specified = true;
public string $value;
public readonly ?DOMElement $ownerElement;
public readonly mixed $schemaTypeInfo = null;
/* Propriedades herdadas */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos */
public __construct(string $name, string $value = "")
public isId(): bool
/* Métodos herdados */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriedades

name

O nome do atributo

ownerElement

O elemento que contém o atributo ou null.

schemaTypeInfo

Não foi implementado ainda, sempre será null

specified

Não foi implementado ainda, sempre será true

value

O valor do atributo.

Nota:

Observe que entidades XML são expandidas ao atribuir um valor. Portanto o caracter & tem um comportamento especial. Configurar um value para si mesmo irá falhar se value contiver um &. Para evitar uma substituição de entidades, utilize DOMElement::setAttribute().

Veja Também

  • » Especificação da W3C para Attr

Índice

  • DOMAttr::__construct — Creates a new DOMAttr object
  • DOMAttr::isId — Checks if attribute is a defined ID

User Contributed Notes

greubel at nkey dot de 06-Dec-2014 03:04
Please take care on debugging DOMAttr related code. This will cause an E_WARNING that retrieving schemaTypeInfo attribute is not implemented yet. An IDE like Eclipse will inspect the object and its member elements. In conjunction with registered error handlers, which will translate the E_WARNING into Exception your debugging session will end unexpectedly. This has caused me some trouble while debugging my PHPUnit test case in eclipse using "Makegood" plugin.

A possible workarround is to deactivate the error handling during debugging using error_reporting(0). Remove the statement after finishing your debugging session.

Notable ticket in Bugtracker: https://bugs.php.net/bug.php?id=61858
And a xdebug tracker ticket: http://bugs.xdebug.org/view.php?id=910
chregu at php dot net 23-Mar-2009 11:20
See also the properties from the inherited class DOMNode ( http://php.net/manual/en/class.domnode.php ), eg. namespaceURI, prefix, localName, etc, especially if you have to deal with namespaced attributes


Creates a new DOMAttr object

  • « DOMAttr
  • DOMAttr::isId »
  • PHP Manual
  • DOMAttr
  • Creates a new DOMAttr object

DOMAttr::__construct

(PHP 5, PHP 7, PHP 8)

DOMAttr::__construct — Creates a new DOMAttr object

Descrição

public DOMAttr::__construct(string $name, string $value = "")

Creates a new DOMAttr object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writable node, use DOMDocument::createAttribute.

Parâmetros

name

The tag name of the attribute.

value

The value of the attribute.

Exemplos

Exemplo #1 Creating a new DOMAttr object

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$attr = $element->setAttributeNode(new DOMAttr('attr', 'attrvalue'));
echo $dom->saveXML();

?>

O exemplo acima produzirá:

<?xml version="1.0" encoding="utf-8"?>
<root attr="attrvalue" />

Veja Também

  • DOMDocument::createAttribute() - Create new attribute

User Contributed Notes

Anonymous 18-Sep-2014 10:48
The output should be:

<?xml version="1.0" encoding="iso-8859-1"?>
<root attr="attrvalue"/>


Checks if attribute is a defined ID

  • « DOMAttr::__construct
  • DOMCdataSection »
  • PHP Manual
  • DOMAttr
  • Checks if attribute is a defined ID

DOMAttr::isId

(PHP 5, PHP 7, PHP 8)

DOMAttr::isId — Checks if attribute is a defined ID

Descrição

public DOMAttr::isId(): bool

This function checks if the attribute is a defined ID.

According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID. You need to validate your document with DOMDocument::validate or DOMDocument::validateOnParse before using this function.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Exemplos

Exemplo #1 DOMAttr::isId() Example

<?php

$doc = new DomDocument;

// We need to validate our document before referring to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

// We retrieve the attribute named id of the chapter element
$attr = $doc->getElementsByTagName('chapter')->item(0)->getAttributeNode('id');

var_dump($attr->isId()); // bool(true)

?>

User Contributed Notes

There are no user contributed notes for this page.


The DOMCdataSection class

(PHP 5, PHP 7, PHP 8)

Introdução

The DOMCdataSection inherits from DOMText for textual representation of CData constructs.

Sinopse da classe

class DOMCdataSection extends DOMText {
/* Propriedades herdadas */
public readonly string $wholeText;
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos */
public __construct(string $data)
/* Métodos herdados */
public DOMText::isElementContentWhitespace(): bool
public DOMText::isWhitespaceInElementContent(): bool
public DOMText::splitText(int $offset): DOMText|false
public DOMCharacterData::after(DOMNode|string ...$nodes): void
public DOMCharacterData::appendData(string $data): true
public DOMCharacterData::before(DOMNode|string ...$nodes): void
public DOMCharacterData::deleteData(int $offset, int $count): bool
public DOMCharacterData::insertData(int $offset, string $data): bool
public DOMCharacterData::remove(): void
public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool
public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void
public DOMCharacterData::substringData(int $offset, int $count): string|false
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Índice

  • DOMCdataSection::__construct — Constructs a new DOMCdataSection object

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new DOMCdataSection object

  • « DOMCdataSection
  • DOMCharacterData »
  • PHP Manual
  • DOMCdataSection
  • Constructs a new DOMCdataSection object

DOMCdataSection::__construct

(PHP 5, PHP 7, PHP 8)

DOMCdataSection::__construct — Constructs a new DOMCdataSection object

Descrição

public DOMCdataSection::__construct(string $data)

Constructs a new CDATA node. This works like the DOMText class.

Parâmetros

data

The value of the CDATA node. If not supplied, an empty CDATA node is created.

Exemplos

Exemplo #1 Creating a new DOMCdataSection object

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMCdataSection('root value'));
echo $dom->saveXML();

?>

O exemplo acima produzirá:

<?xml version="1.0" encoding="utf-8"?>
<root><![CDATA[root value]]></root>

Veja Também

  • DOMText::__construct() - Creates a new DOMText object
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

There are no user contributed notes for this page.


The DOMCharacterData class

(PHP 5, PHP 7, PHP 8)

Introdução

Represents nodes with character data. No nodes directly correspond to this class, but other nodes do inherit from it.

Sinopse da classe

class DOMCharacterData extends DOMNode implements DOMChildNode {
/* Propriedades */
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
/* Propriedades herdadas */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos */
public after(DOMNode|string ...$nodes): void
public appendData(string $data): true
public before(DOMNode|string ...$nodes): void
public deleteData(int $offset, int $count): bool
public insertData(int $offset, string $data): bool
public remove(): void
public replaceData(int $offset, int $count, string $data): bool
public replaceWith(DOMNode|string ...$nodes): void
public substringData(int $offset, int $count): string|false
/* Métodos herdados */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriedades

data

The contents of the node.

length

The length of the contents.

nextElementSibling

The next sibling element or null.

previousElementSibling

The previous sibling element or null.

Changelog

Versão | Descrição
8.0.0 | The nextElementSibling and previousElementSibling properties have been added.
8.0.0 | DOMCharacterData implements DOMChildNode now.

Veja Também

  • » W3C specification of CharacterData

Índice

  • DOMCharacterData::after — Adds nodes after the character data
  • DOMCharacterData::appendData — Append the string to the end of the character data of the node
  • DOMCharacterData::before — Adds nodes before the node
  • DOMCharacterData::deleteData — Remove a range of characters from the node
  • DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::remove — Removes the character data
  • DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node
  • DOMCharacterData::replaceWith — Replaces the character data with new nodes
  • DOMCharacterData::substringData — Extracts a range of data from the node

User Contributed Notes

jesdisciple dot FOO at gmail dot BAR dot com 08-Jul-2010 04:35
In case you're looking for the CDATA class to which nodes /do/ correspond, it's called DOMCdataSection (per my PHP installation) and isn't documented on php.net.  Presumably, it doesn't add anything to this API.

See also: http://www.php.net/manual/en/domdocument.createcdatasection.php


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

Descrição

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

Adds the passed nodes after the element.

Parâmetros

nodes

Nodes to be added after the node. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se o pai é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou este próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

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

User Contributed Notes

There are no user contributed notes for this page.


Append the string to the end of the character data of the node

  • « DOMCharacterData::after
  • DOMCharacterData::before »
  • PHP Manual
  • DOMCharacterData
  • Append the string to the end of the character data of the node

DOMCharacterData::appendData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::appendData — Append the string to the end of the character data of the node

Descrição

public DOMCharacterData::appendData(string $data): true

Append the string data to the end of the character data of the node.

Parâmetros

data

The string to append.

Valor Retornado

Sempre retorna true.

Changelog

Versão | Descrição
8.3.0 | This function now has a tentative true return type.

Veja Também

  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


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

Descrição

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

Adds the passed nodes before the node.

Parâmetros

nodes

Nodes to be added before the node. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se o pai é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou este próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

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

User Contributed Notes

There are no user contributed notes for this page.


Remove a range of characters from the node

  • « DOMCharacterData::before
  • DOMCharacterData::insertData »
  • PHP Manual
  • DOMCharacterData
  • Remove a range of characters from the node

DOMCharacterData::deleteData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::deleteData — Remove a range of characters from the node

Descrição

public DOMCharacterData::deleteData(int $offset, int $count): bool

Deletes count characters starting from position offset.

Parâmetros

offset

The offset from which to start removing.

count

The number of characters to delete. If the sum of offset and count exceeds the length, then all characters to the end of the data are deleted.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

Veja Também

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


Insert a string at the specified 16-bit unit offset

  • « DOMCharacterData::deleteData
  • DOMCharacterData::remove »
  • PHP Manual
  • DOMCharacterData
  • Insert a string at the specified 16-bit unit offset

DOMCharacterData::insertData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset

Descrição

public DOMCharacterData::insertData(int $offset, string $data): bool

Inserts string data at position offset.

Parâmetros

offset

The character offset at which to insert.

data

The string to insert.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data.

Veja Também

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


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

Descrição

public DOMCharacterData::remove(): void

Removes the character data.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Nenhum valor é retornado.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

  • DOMChildNode::remove() - Removes the node
  • 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() - Removes child from list of children

User Contributed Notes

There are no user contributed notes for this page.


Replace a substring within the DOMCharacterData node

  • « DOMCharacterData::remove
  • DOMCharacterData::replaceWith »
  • PHP Manual
  • DOMCharacterData
  • Replace a substring within the DOMCharacterData node

DOMCharacterData::replaceData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node

Descrição

public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool

Replace count characters starting from position offset with data.

Parâmetros

offset

The offset from which to start replacing.

count

The number of characters to replace. If the sum of offset and count exceeds the length, then all characters to the end of the data are replaced.

data

The string with which the range must be replaced.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

Veja Também

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


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

Descrição

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

Replaces the character data with new nodes.

Parâmetros

nodes

The replacement nodes. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se o pai é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou este próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

  • DOMChildNode::replaceWith() - Replaces the node with new nodes
  • 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.


Extracts a range of data from the node

  • « DOMCharacterData::replaceWith
  • DOMChildNode »
  • PHP Manual
  • DOMCharacterData
  • Extracts a range of data from the node

DOMCharacterData::substringData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::substringData — Extracts a range of data from the node

Descrição

public DOMCharacterData::substringData(int $offset, int $count): string|false

Returns the specified substring.

Parâmetros

offset

Start offset of substring to extract.

count

The number of characters to extract.

Valor Retornado

The specified substring. If the sum of offset and count exceeds the length, then all 16-bit units to the end of the data are returned.

Erros

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

Veja Também

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node

User Contributed Notes

There are no user contributed notes for this page.


The DOMChildNode interface

(PHP 8)

Resumo da Interface

interface DOMChildNode {
/* Métodos */
public after(DOMNode|string ...$nodes): void
public before(DOMNode|string ...$nodes): void
public remove(): void
public replaceWith(DOMNode|string ...$nodes): void
}

Índice

  • DOMChildNode::after — Adds nodes after the node
  • DOMChildNode::before — Adds nodes before the node
  • DOMChildNode::remove — Removes the node
  • DOMChildNode::replaceWith — Replaces the node with new nodes

User Contributed Notes

There are no user contributed notes for this page.


Adds nodes after the node

  • « DOMChildNode
  • DOMChildNode::before »
  • PHP Manual
  • DOMChildNode
  • Adds nodes after the node

DOMChildNode::after

(PHP 8)

DOMChildNode::after — Adds nodes after the node

Descrição

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

Adds the passed nodes after the node.

Parâmetros

nodes

Nodes to be added after the node. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se o pai é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou este próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Veja Também

  • DOMChildNode::before() - Adds nodes before the node
  • DOMChildNode::remove() - Removes the node
  • DOMChildNode::replaceWith() - Replaces the node with new nodes
  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos

User Contributed Notes

There are no user contributed notes for this page.


Adds nodes before the node

  • « DOMChildNode::after
  • DOMChildNode::remove »
  • PHP Manual
  • DOMChildNode
  • Adds nodes before the node

DOMChildNode::before

(PHP 8)

DOMChildNode::before — Adds nodes before the node

Descrição

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

Adds the passed nodes before the node.

Parâmetros

nodes

Nodes to be added before the node. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se o pai é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou este próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Veja Também

  • DOMChildNode::after() - Adds nodes after the node
  • DOMChildNode::remove() - Removes the node
  • DOMChildNode::replaceWith() - Replaces the node with new nodes

User Contributed Notes

There are no user contributed notes for this page.


Removes the node

  • « DOMChildNode::before
  • DOMChildNode::replaceWith »
  • PHP Manual
  • DOMChildNode
  • Removes the node

DOMChildNode::remove

(PHP 8)

DOMChildNode::remove — Removes the node

Descrição

public DOMChildNode::remove(): void

Removes the node.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Nenhum valor é retornado.

Veja Também

  • DOMChildNode::after() - Adds nodes after the node
  • DOMChildNode::before() - Adds nodes before the node
  • DOMChildNode::replaceWith() - Replaces the node with new nodes
  • DOMNode::removeChild() - Removes child from list of children

User Contributed Notes

There are no user contributed notes for this page.


Replaces the node with new nodes

  • « DOMChildNode::remove
  • DOMComment »
  • PHP Manual
  • DOMChildNode
  • Replaces the node with new nodes

DOMChildNode::replaceWith

(PHP 8)

DOMChildNode::replaceWith — Replaces the node with new nodes

Descrição

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

Replaces the node with new nodes.

Parâmetros

nodes

The replacement nodes. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se o pai é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou este próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Veja Também

  • DOMChildNode::after() - Adds nodes after the node
  • DOMChildNode::before() - Adds nodes before the node
  • DOMChildNode::remove() - Removes the node
  • DOMNode::replaceChild() - Replaces a child

User Contributed Notes

There are no user contributed notes for this page.


The DOMComment class

(PHP 5, PHP 7, PHP 8)

Introdução

Represents comment nodes, characters delimited by <!-- and -->.

Sinopse da classe

class DOMComment extends DOMCharacterData {
/* Propriedades herdadas */
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos */
public __construct(string $data = "")
/* Métodos herdados */
public DOMCharacterData::after(DOMNode|string ...$nodes): void
public DOMCharacterData::appendData(string $data): true
public DOMCharacterData::before(DOMNode|string ...$nodes): void
public DOMCharacterData::deleteData(int $offset, int $count): bool
public DOMCharacterData::insertData(int $offset, string $data): bool
public DOMCharacterData::remove(): void
public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool
public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void
public DOMCharacterData::substringData(int $offset, int $count): string|false
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Veja Também

  • » W3C specification of Comment

Índice

  • DOMComment::__construct — Creates a new DOMComment object

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

?>


Creates a new DOMComment object

  • « DOMComment
  • DOMDocument »
  • PHP Manual
  • DOMComment
  • Creates a new DOMComment object

DOMComment::__construct

(PHP 5, PHP 7, PHP 8)

DOMComment::__construct — Creates a new DOMComment object

Descrição

public DOMComment::__construct(string $data = "")

Creates a new DOMComment object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createComment.

Parâmetros

data

The value of the comment.

Exemplos

Exemplo #1 Creating a new DOMComment

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$comment = $element->appendChild(new DOMComment('root comment'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root><!--root comment--></root> */

?>

Veja Também

  • DOMDocument::createComment() - Create new comment node

User Contributed Notes

There are no user contributed notes for this page.


The DOMDocument class

(PHP 5, PHP 7, PHP 8)

Introdução

Represents an entire HTML or XML document; serves as the root of the document tree.

Sinopse da classe

class DOMDocument extends DOMNode implements DOMParentNode {
/* Propriedades */
public readonly ?DOMDocumentType $doctype;
public readonly DOMImplementation $implementation;
public readonly ?DOMElement $documentElement;
public readonly ?string $actualEncoding;
public ?string $encoding;
public readonly ?string $xmlEncoding;
public bool $standalone;
public bool $xmlStandalone;
public ?string $version;
public ?string $xmlVersion;
public bool $strictErrorChecking;
public ?string $documentURI;
public readonly mixed $config;
public bool $formatOutput;
public bool $validateOnParse;
public bool $resolveExternals;
public bool $preserveWhiteSpace;
public bool $recover;
public bool $substituteEntities;
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
/* Propriedades herdadas */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos */
public __construct(string $version = "1.0", string $encoding = "")
public adoptNode(DOMNode $node): DOMNode|false
public append(DOMNode|string ...$nodes): void
public createAttribute(string $localName): DOMAttr|false
public createAttributeNS(?string $namespace, string $qualifiedName): DOMAttr|false
public createCDATASection(string $data): DOMCdataSection|false
public createComment(string $data): DOMComment
public createDocumentFragment(): DOMDocumentFragment
public createElement(string $localName, string $value = ""): DOMElement|false
public createElementNS(?string $namespace, string $qualifiedName, string $value = ""): DOMElement|false
public createEntityReference(string $name): DOMEntityReference|false
public createProcessingInstruction(string $target, string $data = ""): DOMProcessingInstruction|false
public createTextNode(string $data): DOMText
public getElementById(string $elementId): ?DOMElement
public getElementsByTagName(string $qualifiedName): DOMNodeList
public getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList
public importNode(DOMNode $node, bool $deep = false): DOMNode|false
public load(string $filename, int $options = 0): bool
public loadHTML(string $source, int $options = 0): bool
public loadHTMLFile(string $filename, int $options = 0): bool
public loadXML(string $source, int $options = 0): bool
public normalizeDocument(): void
public prepend(DOMNode|string ...$nodes): void
public registerNodeClass(string $baseClass, ?string $extendedClass): bool
public relaxNGValidate(string $filename): bool
public relaxNGValidateSource(string $source): bool
public replaceChildren(DOMNode|string ...$nodes): void
public save(string $filename, int $options = 0): int|false
public saveHTML(?DOMNode $node = null): string|false
public saveHTMLFile(string $filename): int|false
public saveXML(?DOMNode $node = null, int $options = 0): string|false
public schemaValidate(string $filename, int $flags = 0): bool
public schemaValidateSource(string $source, int $flags = 0): bool
public validate(): bool
public xinclude(int $options = 0): int|false
/* Métodos herdados */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriedades

actualEncoding

Deprecated. Actual encoding of the document, is a readonly equivalent to encoding.

childElementCount

The number of child elements.

config

Deprecated. Configuration used when DOMDocument::normalizeDocument() is invoked.

doctype

The Document Type Declaration associated with this document.

documentElement

The DOMElement object that is the first document element. If not found, this evaluates to null.

documentURI

The location of the document or null if undefined.

encoding

Encoding of the document, as specified by the XML declaration. This attribute is not present in the final DOM Level 3 specification, but is the only way of manipulating XML document encoding in this implementation.

firstElementChild

First child element or null.

formatOutput

Nicely formats output with indentation and extra space. This has no effect if the document was loaded with preserveWhitespace enabled.

implementation

The DOMImplementation object that handles this document.

lastElementChild

Last child element or null.

preserveWhiteSpace

Do not remove redundant white space. Default to true. Setting this to false has the same effect as passing LIBXML_NOBLANKS as option to DOMDocument::load() etc.

recover

Proprietary. Enables recovery mode, i.e. trying to parse non-well formed documents. This attribute is not part of the DOM specification and is specific to libxml.

resolveExternals

Set it to true to load external entities from a doctype declaration. This is useful for including character entities in your XML document.

standalone

Deprecated. Whether or not the document is standalone, as specified by the XML declaration, corresponds to xmlStandalone.

strictErrorChecking

Throws DOMException on errors. Default to true.

substituteEntities

Proprietary. Whether or not to substitute entities. This attribute is not part of the DOM specification and is specific to libxml. Default to false.

Cuidado

Enabling entity substitution may facilitate XML External Entity (XXE) attacks.

validateOnParse

Loads and validates against the DTD. Default to false.

Cuidado

Enabling validating the DTD may facilitate XML External Entity (XXE) attacks.

version

Deprecated. Version of XML, corresponds to xmlVersion.

xmlEncoding

An attribute specifying, as part of the XML declaration, the encoding of this document. This is null when unspecified or when it is not known, such as when the Document was created in memory.

xmlStandalone

An attribute specifying, as part of the XML declaration, whether this document is standalone. This is false when unspecified.

xmlVersion

An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is "1.0".

Changelog

Versão | Descrição
8.0.0 | DOMDocument implements DOMParentNode now.
8.0.0 | The unimplemented method DOMDocument::renameNode() has been removed.

Notas

Nota:

A extensão DOM usa codificação UTF-8. Use mb_convert_encoding(), UConverter::transcode() ou iconv() para lidar com outras codificações.

Nota:

Ao usar json_encode() em um objeto DOMDocument, o resultado será a codificação de um objeto vazio.

Veja Também

  • » W3C specification for Document

Índice

  • DOMDocument::adoptNode — Transfer a node from another document
  • DOMDocument::append — Appends nodes after the last child node
  • DOMDocument::__construct — Creates a new DOMDocument object
  • DOMDocument::createAttribute — Create new attribute
  • DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection — Create new cdata node
  • DOMDocument::createComment — Create new comment node
  • DOMDocument::createDocumentFragment — Create new document fragment
  • DOMDocument::createElement — Create new element node
  • DOMDocument::createElementNS — Create new element node with an associated namespace
  • DOMDocument::createEntityReference — Create new entity reference node
  • DOMDocument::createProcessingInstruction — Creates new PI node
  • DOMDocument::createTextNode — Create new text node
  • DOMDocument::getElementById — Searches for an element with a certain id
  • DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
  • DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace
  • DOMDocument::importNode — Import node into current document
  • DOMDocument::load — Load XML from a file
  • DOMDocument::loadHTML — Load HTML from a string
  • DOMDocument::loadHTMLFile — Load HTML from a file
  • DOMDocument::loadXML — Load XML from a string
  • DOMDocument::normalizeDocument — Normalizes the document
  • DOMDocument::prepend — Prepends nodes before the first child node
  • DOMDocument::registerNodeClass — Register extended class used to create base node type
  • DOMDocument::relaxNGValidate — Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document
  • DOMDocument::replaceChildren — Replace children in document
  • DOMDocument::save — Dumps the internal XML tree back into a file
  • DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting
  • DOMDocument::saveXML — Dumps the internal XML tree back into a string
  • DOMDocument::schemaValidate — Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource — Validates a document based on a schema
  • DOMDocument::validate — Validates the document based on its DTD
  • DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object

User Contributed Notes

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

Descrição

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

Transfer a node from another document into the current document.

Parâmetros

node

The node to transfer.

Valor Retornado

The node that was transfered, or false on error.

Erros

DOM_NOT_SUPPORTED_ERR

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

Exemplos

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

O exemplo acima produzirá:

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

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

Veja Também

  • DOMDocument::importNode() - Import node into current document

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

Descrição

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

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

Parâmetros

nodes

The nodes to append. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

<hello/>
beautiful
<world/>

Veja Também

  • DOMParentNode::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.


Creates a new DOMDocument object

  • « DOMDocument::append
  • DOMDocument::createAttribute »
  • PHP Manual
  • DOMDocument
  • Creates a new DOMDocument object

DOMDocument::__construct

(PHP 5, PHP 7, PHP 8)

DOMDocument::__construct — Creates a new DOMDocument object

Descrição

public DOMDocument::__construct(string $version = "1.0", string $encoding = "")

Creates a new DOMDocument object.

Parâmetros

version

The version number of the document as part of the XML declaration.

encoding

The encoding of the document as part of the XML declaration.

Exemplos

Exemplo #1 Creating a new DOMDocument

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?> */

?>

Veja Também

  • DOMImplementation::createDocument() - Creates a DOMDocument object of the specified type with its document element

User Contributed Notes

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

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
_ michael 01-Jun-2010 07:23
The constuctor arguments are useful if you want to build a new document using createElement, appendChild etc.

By contrast, these arguments are overriden as soon as you load a document from source by calling load() or loadXML().

* If the source contains an XML declaration specifying an encoding, that encoding is used.
* If the XML declaration does not specify an encoding, or if the source does not contain a declaration at all, UTF-8 is assumed.

This behaviour applies no matter what you declared when you called new DOMDocument().
blackhailang at gmail dot com 09-Oct-2008 07:54
domdocument::domdocument() expects at least
At the least, I found that It due to ZEND optimizer, uninstall it,working well, but the speeds will be slowlly :-(.

Comment :
item 1 : 2008-10-03 17:10:58, gkrong said:
"Warning: domdocument::domdocument() expects at least 1
 parameter"
If you use PHP 5 in windows, you don't need to declare
php_domxml.dll in your php.ini file.
so u can give comment in the line php_domxml.dll in your
php.ini file.
you only need to comment it out, but do not delete the
php_domxml.dll file in the ext directory.
steve at mrclay dot org 08-Oct-2008 09:45
To expand on bholbrook's comment, if you receive this: "Warning: domdocument::domdocument() expects at least 1 parameter", it is due to the old domxml extension, which you need to disable.

domxml overwrites DOMDocument::_construct with an alias to domxml_open_mem, so this code:
<?php
$doc = new DOMDocument();
?>
...essentially does this:
<?php
$dom = domxml_open_mem();
?>
...which is why PHP complains about expecting at least 1 parameter (it expects a string of XML).
christian dot reinecke at web dot de 15-Jul-2008 07:09
If you get the error message "domdocument::domdocument() expects parameter 2 to be long, string given"  for a code sample like this:

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->xmlStandalone = false;
echo $dom->saveXML();

which is obviously correct if you compare the constructor signature:

__construct  ([ string $version  [, string $encoding  ]] )

make sure you're not overwritting this dom library by another (f.e. extension=php_domxml.dll in php.ini). XAMPP f.e. delivers its standard version with php_domxml.dll which ends up in this error message
dave at revlob dot com 14-Feb-2008 02:07
@Jarl

Not sure if this is what you meant when you said "The constructor example clearly shows that version and encoding only end up in the XML header", but you can also affect other parameters in the generated XML header, by accessing the DOMDocument's properties, for example:

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->xmlStandalone = false;
echo $dom->saveXML();

// <?xml version="1.0" encoding="UTF-8" standalone="no"?>
bholbrook at servillian dot com 05-Dec-2007 02:25
Make sure that php_domxml.dll on windows is removed before using the domdocument class as they cannot coexist.
jarl kringelding skim punt com 24-Sep-2007 02:22
Be aware using the encoding parameter in the constructor.
It does not mean that all data is automatically encoded for you in the supplied encoding. You need to do that yourself once you choose an encoding other than the default UTF-8. See the note on DOM Functions on how to properly work with other encodings...

The constructor example clearly shows that version and encoding only end up in the XML header.


Create new attribute

  • « DOMDocument::__construct
  • DOMDocument::createAttributeNS »
  • PHP Manual
  • DOMDocument
  • Create new attribute

DOMDocument::createAttribute

(PHP 5, PHP 7, PHP 8)

DOMDocument::createAttribute — Create new attribute

Descrição

public DOMDocument::createAttribute(string $localName): DOMAttr|false

This function creates a new instance of class DOMAttr. Este nó não aparecerá no documento a menos que seja inserido, por exemplo, com DOMNode::appendChild().

Parâmetros

localName

The name of the attribute.

Valor Retornado

The new DOMAttr or false if an error occurred.

Erros

DOM_INVALID_CHARACTER_ERR

Raised if localName contains an invalid character.

Veja Também

  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Skateside 05-Apr-2013 04:16
This may be obvious to most people, but it gave me a few minutes of head-scratching before I figured it out, but ampersands need to be properly escaped as HTML entities.

<?php
$doc= new DOMDocument('1.0', "UTF-8");

$invalid_elem = $doc->createElement('field', 'incorrect attribute');
$invalid_attr = $doc->createAttribute('name');
$invalid_attr->value = 'foo&bar';
$invalid_elem->appendChild($invalid_attr);
$doc->appendChild($invalid_elem);

$valid_elem = $doc->createElement('field', 'correct attribute');
$valid_attr = $doc->createAttribute('name');
$valid_attr->value = 'foo&amp;bar';
$valid_elem->appendChild($valid_attr);
$doc->appendChild($valid_elem);

?>

Will output:
<?xml version="1.0" encoding="UTF-8"?>
<field name="foo">incorrect attribute</field>
<field name="foo&bar">correct attribute</field>

As near as I can figure out, no exception is thrown for an invalid attribute. This will affect DOMDocuments created as HTML as well as XML.
Beerkeeper 09-Nov-2011 07:19
Just in case it isn't clear (like I had), an example:

<?php

$domDocument = new DOMDocument('1.0', "UTF-8");
$domElement = $domDocument->createElement('field','some random data');
$domAttribute = $domDocument->createAttribute('name');

// Value for the created attribute
$domAttribute->value = 'attributevalue';

// Don't forget to append it to the element
$domElement->appendChild($domAttribute);

// Append it to the document itself
$domDocument->appendChild($domElement);

?>

Will output:
<?xml version="1.0" encoding="UTF-8"?>
<field name="attributevalue">some random data</field>


Create new attribute node with an associated namespace

  • « DOMDocument::createAttribute
  • DOMDocument::createCDATASection »
  • PHP Manual
  • DOMDocument
  • Create new attribute node with an associated namespace

DOMDocument::createAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMDocument::createAttributeNS — Create new attribute node with an associated namespace

Descrição

public DOMDocument::createAttributeNS(?string $namespace, string $qualifiedName): DOMAttr|false

This function creates a new instance of class DOMAttr. Este nó não aparecerá no documento a menos que seja inserido, por exemplo, com DOMNode::appendChild().

Parâmetros

namespace

The URI of the namespace.

qualifiedName

The tag name and prefix of the attribute, as prefix:tagname.

Valor Retornado

The new DOMAttr or false if an error occurred.

Erros

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespace is null.

Changelog

Versão | Descrição
8.3.0 | Calling this method without specifying a prefix will now choose a prefix instead of assuming the default namespace. Previously this would create an attribute without a prefix and incorrectly apply the namespace to the owner element because default namespaces don't apply on attributes.
8.3.0 | Calling this method using a prefix that was already declared on the owner element with a different namespace URI will now change the new prefix to avoid creating namespace conflicts. This aligns the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_NAMESPACE_ERR.

Veja Também

  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

_ michael 01-Jun-2010 07:35
If a new namespace is introduced while creating and inserting an attribute, createAttributeNS() does not behave in the same way as createElementNS().

(1) Location: With createAttributeNS(), the new namespace is declared at the level of the document element. By contrast, createElementNS() declares the new namespace at the level of the affected element itself.

(2) Timing: With createAttributeNS(), the new namespace is declared in the document as soon as the attribute is created - the attribute does not actually have to be inserted. createElementNS() doesn't affect the document as long as the element is not inserted.

An example:

<?php

    $source = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root><tag></tag></root>
XML;

    /*

     I. createAttributeNS:
     * a new namespace shows up immediately, even without insertion of the attribute
     * the new namespace is declared at the level of the document element

    */

    $doc = new DOMDocument( '1.0' );
    $doc->loadXML( $source );

    // (1) We just create a "namespace'd" attribute without appending it to any element.
    $attr_ns = $doc->createAttributeNS( '{namespace_uri_here}', 'example:attr' );

    print $doc->saveXML() . "\n";

    /*
      Result: The namespace declaration appears, having been added to the document element. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root xmlns:example="{namespace_uri_here}"><tag/></root>

    */

    // (2) Next, we give the attribute a value and insert it.
    $attr_ns->value = 'value';
    $doc->getElementsByTagName( 'tag' )->item(0)->appendChild( $attr_ns );

    print $doc->saveXML() . "\n";

    /*
      Result: The "namespace'd" attribute shows up as well. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root xmlns:example="{namespace_uri_here}"><tag example:attr="value"/></root>

    */

    /*

     II. createElementNS:
     * a new namespace shows up only when the element is inserted
     * the new namespace is declared at the level of the inserted element

    */

    $doc = new DOMDocument( '1.0' );
    $doc->loadXML( $source );

    // (1) We create a "namespace'd" element without inserting it into the document.
    $elem_ns = $doc->createElementNS( '{namespace_uri_here}', 'example:newtag' );

    print $doc->saveXML() . "\n";

    /*
      Result: The document remains unchanged. Output:

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

    */

    // (2) Next, we insert the new element.
    $doc->getElementsByTagName( 'tag' )->item(0)->appendChild( $elem_ns );

    print $doc->saveXML() . "\n";

    /*
      Result: The namespace declaration appears, and it is embedded in the element using it. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root><tag><example:newtag xmlns:example="{namespace_uri_here}"/></tag></root>

    */

?>


Create new cdata node

  • « DOMDocument::createAttributeNS
  • DOMDocument::createComment »
  • PHP Manual
  • DOMDocument
  • Create new cdata node

DOMDocument::createCDATASection

(PHP 5, PHP 7, PHP 8)

DOMDocument::createCDATASection — Create new cdata node

Descrição

public DOMDocument::createCDATASection(string $data): DOMCdataSection|false

This function creates a new instance of class DOMCDATASection. Este nó não aparecerá no documento a menos que seja inserido, por exemplo, com DOMNode::appendChild().

Parâmetros

data

The content of the cdata.

Valor Retornado

The new DOMCDATASection or false if an error occurred.

Veja Também

  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Marc info[at]braincast.nl 08-Mar-2011 01:55
Here's some code that takes an associative array and prints it asXML() but creates CDATA sections for each string

<?php
class SimpleXMLExtended extends SimpleXMLElement{
    public function addCData($string){
        $dom = dom_import_simplexml($this);
        $cdata = $dom->ownerDocument->createCDATASection($string);
        $dom->appendChild($cdata);
    }
}
function assocArrayToXML($root_element_name,$ar){
    $xml = new SimpleXMLExtended("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
    $f = create_function('$f,$c,$a','
            foreach($a as $k=>$v) {
                if(is_array($v)) {
                    if (!is_numeric($k))$ch=$c->addChild($k);
                    else $ch = $c->addChild(substr($c->getName(),0,-1));
                    $f($f,$ch,$v);
                } else {
                    if (is_numeric($v)){ $c->addChild($k, $v);
                    }else{$n = $c->addChild($k); $n->addCData($v);}
                }
            }');
    $f($f,$xml,$ar);
    return $xml->asXML();
}

/* sample */
$result = array("title"=>"CDATA Sample");
$result['items'] = array();
$result['items'][] = array('title'=>'Some string', 'number' => 1);
$result['items'][] = array('title'=>'Some string', 'number' => 2);
$result['items'][] = array('title'=>'Some string', 'number' => 3);

echo assocArrayToXML('result',$result);
?>

The is_numeric check could be changed by a more elaborate regular expression to check if the string is actually xml unsafe but this worked for me.
jesdisciple dot FOO at gmail dot BAR dot com 08-Jul-2010 04:44
If you would like to refer to the documentation for the class of the returned object, see http://www.php.net/manual/en/class.domcharacterdata.php
info at troptoek dot com 24-Mar-2008 09:40
A common issue seems to be adding javascript to CDATA and the browser throwing a javascript error. To ensure the javascript works use the following code when adding CDATA:

<?php
/**
 * Append Caracter Data to a node and check for a javascript node
 *
 * @param DOMElement $appendToNode
 * @param string $text
 */
function appendCdata($appendToNode, $text)
{
    if (strtolower($appendToNode->nodeName) == 'script') {  // Javascript hack
        $cm = $appendToNode->ownerDocument->createTextNode("\n//");
        $ct = $appendToNode->ownerDocument->createCDATASection("\n" . $text . "\n//");
        $appendToNode->appendChild($cm);
        $appendToNode->appendChild($ct);
    } else {  // Normal CDATA node
        $ct = $appendToNode->ownerDocument->createCDATASection($text);
        $appendToNode->appendChild($ct);
    }
}
?>
The result should be:

<script type="text/javascript">
//<![CDATA[
function someJsText() {
   document.write('Some js with <a href="#">HTML</a> content');
}
//]]></script>
loathsome 04-Aug-2007 02:28
Here's a function that will create a CDATA-section around a string coming from SimpleXML.

<?php
function sxml_cdata($path, $string){
  $dom = dom_import_simplexml($path);
  $cdata = $dom->ownerDocument->createCDATASection($string);
  $dom->appendChild($cdata);
}
?>


Create new comment node

  • « DOMDocument::createCDATASection
  • DOMDocument::createDocumentFragment »
  • PHP Manual
  • DOMDocument
  • Create new comment node

DOMDocument::createComment

(PHP 5, PHP 7, PHP 8)

DOMDocument::createComment — Create new comment node

Descrição

public DOMDocument::createComment(string $data): DOMComment

This function creates a new instance of class DOMComment. Este nó não aparecerá no documento a menos que seja inserido, por exemplo, com DOMNode::appendChild().

Parâmetros

data

The content of the comment.

Valor Retornado

The new DOMComment.

Changelog

Versão | Descrição
8.1.0 | In case of an error, a DomException is thrown now. Previously, false was returned.

Veja Também

  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

php dot sirlancelot at spamgourmet dot com 25-Nov-2009 12:10
To prevent a parser error when the comment string would contain the character sequence "--", do this:

<?php

$CommentString = 'This contains -- some weird -- characters.';

$CommentNode = $DomDocument->createComment(
        str_replace('--', '-'.chr(194).chr(173).'-', $CommentString)
);
?>

This will insert a Soft Hyphen in between the two hyphens which will not cause the parser to error out.
capps at solareclipse dot net 29-Mar-2007 03:55
Use caution: this function does NOT escape, encode, or otherwise change the contents of the string.

This means that if your string contains two hyphens in a row (--), that will *end* the comment, which can easily create invalid XML when the document is serialized.


Create new document fragment

  • « DOMDocument::createComment
  • DOMDocument::createElement »
  • PHP Manual
  • DOMDocument
  • Create new document fragment

DOMDocument::createDocumentFragment

(PHP 5, PHP 7, PHP 8)

DOMDocument::createDocumentFragment — Create new document fragment

Descrição

public DOMDocument::createDocumentFragment(): DOMDocumentFragment

This function creates a new instance of class DOMDocumentFragment. Este nó não aparecerá no documento a menos que seja inserido, por exemplo, com DOMNode::appendChild().

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

The new DOMDocumentFragment.

Changelog

Versão | Descrição
8.1.0 | In case of an error, a DomException is thrown now. Previously, false was returned.

Veja Também

  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

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>

?>


Create new element node

  • « DOMDocument::createDocumentFragment
  • DOMDocument::createElementNS »
  • PHP Manual
  • DOMDocument
  • Create new element node

DOMDocument::createElement

(PHP 5, PHP 7, PHP 8)

DOMDocument::createElement — Create new element node

Descrição

public DOMDocument::createElement(string $localName, string $value = ""): DOMElement|false

This function creates a new instance of class DOMElement. Este nó não aparecerá no documento a menos que seja inserido, por exemplo, com DOMNode::appendChild().

Parâmetros

localName

The tag name of the element.

value

The value of the element. By default, an empty element will be created. The value can also be set later with DOMElement::$nodeValue.

The value is used verbatim except that the < and > entity references will escaped. Note that & has to be manually escaped; otherwise it is regarded as starting an entity reference. Also " won't be escaped.

Valor Retornado

Returns a new instance of class DOMElement or false if an error occurred.

Erros

DOM_INVALID_CHARACTER_ERR

Raised if localName contains an invalid character.

Exemplos

Exemplo #1 Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElement('test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

O exemplo acima produzirá:

<?xml version="1.0" encoding="utf-8"?>
<test>This is the root element!</test>

Exemplo #2 Passing text containing an unescaped & as value

<?php
$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->createElement('foo', 'me & you');
$dom->appendChild($element);
echo $dom->saveXML();
?>

O exemplo acima produzirá algo semelhante a:

Warning: DOMDocument::createElement(): unterminated entity reference             you in /in/BjTCg on line 4
<?xml version="1.0" encoding="utf-8"?>
<foo/>

Notas

Nota:

The value will not be escaped. Use DOMDocument::createTextNode() to create a text node with escaping support.

Veja Também

  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

dignat at yahoo dot com 15-Nov-2017 10:25
To create an element with DomDocument and to escape ampersand in the value.

Do this:

$element = new DOMDocument('1.0', 'UTF-8');

$test = $element->createElement('text');

$test ->appendChild($element->createElement('name'))
      ->appendChild($element->createtextNode('& I am ampersand');
tschmieder at bitworks dot de 24-Mar-2015 05:42
Remember:

If you want to perform multiple actions with a new node, you may need to create a copy of it before

means:
## Create an address to an unique memory block !
$td = $dom->createElement('td');
## Change some things in this original unique pattern
$td->setAttribute('class', 'saldo');

## clone the unique pattern to two own one's
$td1 = clone $td;
$td2 = clone $td;

## alter properties in each one
$td1->nodeValue = 'Ich bin die erste neue Node';
$td2->nodeValue = 'Ich bin die zweite neue Node';

## find the parent element
$tr = $dom->getElementById('t001-tr001');
## find the first and the last child (here only for clearity)
$first = $tr->firstChild;
$last = $tr->lastChild;

## produce the new nodes
$newtd1 = $tr->insertBefore($td1, $first);
$newtd2 = $tr->appendChild($td2);

conclusion:
YOU NEED AN ORIGINAL NEW NODE FOR EACH ACTION!
funkathustra 04-Mar-2012 08:44
Although the built-in DOM functions are great, since they're designed to support generic XML, generating HTML DOMs becomes particularly verbose. I ended up writing this function to drastically speed things up.
Instead of calling something like
<?php
  $div = $dom->createElement("div");
  $div->setAttribute("class","MyClass");
  $div->setAttribute("id","MyID");
  $someOtherDiv->appendChild($div);
?>
you can accomplish the same thing with:
<?php
  $div = newElement("div", $someOtherDiv, "class=MyClass;id=MyID");
?>
The "key1=value;key2=value" syntax is really fast to use, but obviously doesn't hold up if your content has those characters in it. So, you can also pass it an array:
<?php
  $div = newElement("div", $someOtherDiv, array("class","MyClass"));
?>
Or an array of arrays, representing different attributes:
<?php
  $div = newElement("form", $someOtherDiv, array(array("method","get"), array("action","/refer/?id=5");
?>

Here's the function:

<?php
function newElement($type, $insertInto = NULL, $params=NULL, $content="")
    {
        $tempEl =  $this->dom->createElement($type, $content);
        if(gettype($params) == "string" && strlen($params) > 0)
        {
            $attributesCollection =split(";", $params);
            foreach($attributesCollection  as $attribute)
            {
                $keyvalue = split("=", $attribute);
                $tempEl->setAttribute($keyvalue[0], $keyvalue[1]);
            }
        }
        if(gettype($params) == "array")
        {
            if(gettype($params[0]) == "array")
            {
                foreach($params as $attribute)
                {
                    $tempEl->setAttribute($attribute[0], $attribute[1]);
                }
            } else {
                $tempEl->setAttribute($params[0], $params[1]);
            }
        }
?>
lars dot c dot magnusson at gmail dot com 26-Nov-2010 01:56
You may think insertBefore and insertAfter is a direct alternative for appendChild, this is not the case.

<?php
$dom = new DOMDocument();
$dom->load($file);

$dom->appendChild($newNode); //Works fine
$dom->insertBefore($newNode, $refNode); //Will fail

$refNode->parentNode->insertBefore($newNode, $refNode); // thanx to yasindagli (first post)
?>
yasindagli at gmail dot com 17-Jun-2009 02:01
To create elements with attributes,

<?php

function createElement($domObj, $tag_name, $value = NULL, $attributes = NULL)
{
    $element = ($value != NULL ) ? $domObj->createElement($tag_name, $value) : $domObj->createElement($tag_name);

    if( $attributes != NULL )
    {
        foreach ($attributes as $attr=>$val)
        {
            $element->setAttribute($attr, $val);
        }
    }

    return $element;
}

$dom = new DOMDocument('1.0', 'utf-8');

$elm = createElement($dom, 'foo', 'bar', array('attr_name'=>'attr_value'));

$dom->appendChild($elm);

echo $dom->saveXML();

?>

outputs :
<?xml version="1.0" encoding="utf-8"?>
<foo attr_name="attr_value">bar</foo>
chris AT cmbuckley DOT co DOT uk 26-May-2009 07:45
Note that the NUL character "\0" is not in the list of invalid characters for $name, so no error is triggered, but the tag name will be truncated at the null byte:

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$el = $dom->createElement('foo' . "\0" . 'bar', 'Hello World');
echo $el->tagName; // outputs "foo"

?>
estill at gvtc dot com 12-Jun-2007 02:38
Note that the second parameter (value), although convenient, is non-standard. You should create elements like this instead:

<?php
$doc = new DOMDocument('1.0', 'iso-8859-1');

$root = $doc->createElement('test');
$doc->appendChild($root);

$root_text = $doc->createTextNode('This is the root element!');
$root->appendChild($root_text);

print $doc->saveXML();
?>

Or, alternatively, extend the DOMDocument class and add your own custom, convenience method to avoid intruding on the standard:

<?php
class CustomDOMDocument extends DOMDocument {
  function createElementWithText($name, $child_text) {
    // Creates an element with a child text node

    // @param  string  $name        element tag name
    // @param  string  $child_text  child node text

    // @return  object  new element

    $element = $this->createElement($name);

    $element_text = $this->createTextNode($child_text);
    $element->appendChild($element_text);

    return $element;
  }
}

$doc = new CustomDOMDocument('1.0', 'iso-8859-1');

$root = $doc->createElementWithText('test', 'This is the root element!');
$doc->appendChild($root);

print $doc->saveXML();
?>

Also use caution with (or avoid) the 'DOMElement->nodeValue' property. It can return some unexpected values and changing its value will replace (remove) all descendants of the element with a single text node. It's also non-standard; according to the DOM spec it should return NULL.
mikek dot nospam at nospam dot muonics dot com 03-Mar-2007 05:24
With regard to the note below about needing htmlentities to avoid warnings about unterminated entity references, I thought it worthwhile to mention that that you don't need to with createTextNode and DOMText::__construct.  If you mix both methods of setting text nodes and do (or don't) apply htmlentities consistently to all data to be displayed, you'll get &amp;s (or warnings and badly-formed xml).

It's probably in one's best interest to extend DOMElement and DOMDocument so that it creates a DOMText node and appends it, rather than passing it up to the DOMElement constructor.  Otherwise, good luck using (or not using) htmlentities in all the right places in your code, especially as code changes get made.

<?php

class XDOMElement extends DOMElement {
    function __construct($name, $value = null, $namespaceURI = null) {
        parent::__construct($name, null, $namespaceURI);
    }
}

class XDOMDocument extends DOMDocument {
    function __construct($version = null, $encoding = null) {
        parent::__construct($version, $encoding);
        $this->registerNodeClass('DOMElement', 'XDOMElement');
    }

    function createElement($name, $value = null, $namespaceURI = null) {
        $element = new XDOMElement($name, $value, $namespaceURI);
        $element = $this->importNode($element);
        if (!empty($value)) {
            $element->appendChild(new DOMText($value));
        }
        return $element;
    }
}

$doc1 = new XDOMDocument();
$doc1_e1 = $doc1->createElement('foo', 'bar & baz');
$doc1->appendChild($doc1_e1);
echo $doc1->saveXML();

$doc2 = new XDOMDocument();
$doc2_e1 = $doc2->createElement('foo');
$doc2->appendChild($doc2_e1);
$doc2_e1->appendChild($doc2->createTextNode('bar & baz'));
echo $doc2->saveXML();

?>

Text specified in createElement:
<?xml version=""?>
<foo>bar &amp; baz</foo>

Text added via createTextNode:
<?xml version=""?>
<foo>bar &amp; baz</foo>
sergsokolenko at gmail dot com 30-Jan-2007 04:11
To avoid warning message "unterminated entity reference" you may use htmlentities() for escaping supplied value:
<?php
//...
$dom->createElement('name', htmlentities($text))
//...
?>


Create new element node with an associated namespace

  • « DOMDocument::createElement
  • DOMDocument::createEntityReference »
  • PHP Manual
  • DOMDocument
  • Create new element node with an associated namespace

DOMDocument::createElementNS

(PHP 5, PHP 7, PHP 8)

DOMDocument::createElementNS — Create new element node with an associated namespace

Descrição

public DOMDocument::createElementNS(?string $namespace, string $qualifiedName, string $value = ""): DOMElement|false

This function creates a new element node with an associated namespace. Este nó não aparecerá no documento a menos que seja inserido, por exemplo, com DOMNode::appendChild().

Parâmetros

namespace

The URI of the namespace.

qualifiedName

The qualified name of the element, as prefix:tagname.

value

The value of the element. By default, an empty element will be created. You can also set the value later with DOMElement::$nodeValue.

Valor Retornado

The new DOMElement or false if an error occurred.

Erros

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name.

Exemplos

Exemplo #1 Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

O exemplo acima produzirá:

<?xml version="1.0" encoding="utf-8"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

Exemplo #2 A namespace prefix example

<?php
$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElementNS('http://www.w3.org/2005/Atom', 'element');
$doc->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:g', 'http://base.google.com/ns/1.0');
$item = $doc->createElementNS('http://base.google.com/ns/1.0', 'g:item_type', 'house');
$root->appendChild($item);

echo $doc->saveXML(), "\n";

echo $item->namespaceURI, "\n"; // Outputs: http://base.google.com/ns/1.0
echo $item->prefix, "\n"; // Outputs: g
echo $item->localName, "\n"; // Outputs: item_type
?>

O exemplo acima produzirá:

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

Veja Também

  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Martin 27-Dec-2011 09:39
To avoid multiple xmlns re-declaration, make sure you appending ElementNS into actual DOMDocument tree (not into some currently-assembed derelict element).


Create new entity reference node

  • « DOMDocument::createElementNS
  • DOMDocument::createProcessingInstruction »
  • PHP Manual
  • DOMDocument
  • Create new entity reference node

DOMDocument::createEntityReference

(PHP 5, PHP 7, PHP 8)

DOMDocument::createEntityReference — Create new entity reference node

Descrição

public DOMDocument::createEntityReference(string $name): DOMEntityReference|false

This function creates a new instance of class DOMEntityReference. Este nó não aparecerá no documento a menos que seja inserido, por exemplo, com DOMNode::appendChild().

Parâmetros

name

The content of the entity reference, e.g. the entity reference minus the leading & and the trailing ; characters.

Valor Retornado

The new DOMEntityReference or false if an error occurred.

Erros

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

Veja Também

  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

alicewonder at shastaherps dot org 24-Sep-2015 07:48
It appears that this does not work with numbered entities, only named entities.

$nbspace = $dom->createEntityReference('nbsp');

works

$nbspace = $dom->createEntityReference('#160');

does not. This makes this function rather useless when generating an XSL unless you modify the XSL doctype to include the named entity for the character you want.
Tuhin Bepari 04-Nov-2013 06:00
<?php
/*Entity is a group of words which print a special symbol.
Like if we want to show copy right symbol in html page then we use &copy; code and browser convert this to actual copyright symbol.
There have lots of entity, you can find them all form http://dev.w3.org/html5/html-author/charref
if you want to use < or > or both <> into a node value than xml will give and warning or make this value as a node.
So tell the xml parser that < or > is not tag symbol it is a entity.To do that you have to right &lt(<) and &gt;(>) instead of < and > symbol.

Entity references always begin with an ampersand (&) and end with a semicolon (;).
DO not need to use & and ; symbol begin and end of entity.Remove it when you want to use it to DOMDocument::createEntityReference
Then append to to a tag where you want to show this symbol.Like below
*/
$dom=new DOMDocument("1.0","UTF-8");
$example=$dom->createElement("example","This is copyright ");
$entity=$dom->createEntityReference("copy");
$example->appendChild($entity);
$dom->appendChild($example);
echo $dom->saveXML();

output is
This is copyright ©


Creates new PI node

  • « DOMDocument::createEntityReference
  • DOMDocument::createTextNode »
  • PHP Manual
  • DOMDocument
  • Creates new PI node

DOMDocument::createProcessingInstruction

(PHP 5, PHP 7, PHP 8)

DOMDocument::createProcessingInstruction — Creates new PI node

Descrição

public DOMDocument::createProcessingInstruction(string $target, string $data = ""): DOMProcessingInstruction|false

This function creates a new instance of class DOMProcessingInstruction. Este nó não aparecerá no documento a menos que seja inserido, por exemplo, com DOMNode::appendChild().

Parâmetros

target

The target of the processing instruction.

data

The content of the processing instruction.

Valor Retornado

The new DOMProcessingInstruction or false if an error occurred.

Erros

DOM_INVALID_CHARACTER_ERR

Raised if target contains an invalid character.

Veja Também

  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

romain at supinfo dot com 03-Feb-2009 11:57
A use exemple of this method :

Usefull for generating an XML linked with a XSLT !

<?php

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

//to have indented output, not just a line
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;

// ------------- Interresting part here ------------

//creating an xslt adding processing line
$xslt = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="base.xsl"');

//adding it to the xml
$xml->appendChild($xslt);

// ----------- / Interresting part here -------------

//adding some elements
$root = $xml->createElement("list");
$node = $xml->createElement("contact", "John Doe");
$root-> appendChild($node);
$xml-> appendChild($root);

//creating the file
$xml-> save("output.xml");

?>

output.xml :

<?xml version="1.0" encoding="ISO-8859-15"?>
<?xml-stylesheet type="text/xsl" href="base.xsl"?> //the line has been created successfully
<list>
  <contact>John Doe</contact>
</list>


Create new text node

  • « DOMDocument::createProcessingInstruction
  • DOMDocument::getElementById »
  • PHP Manual
  • DOMDocument
  • Create new text node

DOMDocument::createTextNode

(PHP 5, PHP 7, PHP 8)

DOMDocument::createTextNode — Create new text node

Descrição

public DOMDocument::createTextNode(string $data): DOMText

This function creates a new instance of class DOMText. Este nó não aparecerá no documento a menos que seja inserido, por exemplo, com DOMNode::appendChild().

Parâmetros

data

The content of the text.

Valor Retornado

The new DOMText.

Changelog

Versão | Descrição
8.1.0 | In case of an error, a DomException is thrown now. Previously, false was returned.

Veja Também

  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node

User Contributed Notes

drewish at katherinehouse dot com 16-Dec-2014 10:03
The docs don't mention it but this method performs escaping on the value. If you don't want that use createElement() instead.
Alex Kaye 25-Jul-2009 07:04
A quick note to anyone who is using character entities (e.g. &copy;) in this, and finding them automatically escaped. The correct thing to do here is to use the createEntityReference method (e.g. createEntityReference("copy");), and then appendChild this entity between text nodes.

Example:

<?php
$copyright_text_1 = $this->document->createTextNode("Copyright ");
$copyright_text_2 = $this->document->createTextNode(" Alex Kaye 2009");
$copyright_symbol = $this->document->createEntityReference("copy");
$copyright->appendChild($copyright_text_1);
$copyright->appendChild($copyright_symbol);
$copyright->appendChild($copyright_text_2);
?>


Searches for an element with a certain id

  • « DOMDocument::createTextNode
  • DOMDocument::getElementsByTagName »
  • PHP Manual
  • DOMDocument
  • Searches for an element with a certain id

DOMDocument::getElementById

(PHP 5, PHP 7, PHP 8)

DOMDocument::getElementById — Searches for an element with a certain id

Descrição

public DOMDocument::getElementById(string $elementId): ?DOMElement

This function is similar to DOMDocument::getElementsByTagName but searches for an element with a given id.

For this function to work, you will need either to set some ID attributes with DOMElement::setIdAttribute or a DTD which defines an attribute to be of type ID. In the later case, you will need to validate your document with DOMDocument::validate or DOMDocument::$validateOnParse before using this function.

Parâmetros

elementId

The unique id value for an element.

Valor Retornado

Returns the DOMElement or null if the element is not found.

Exemplos

Exemplo #1 DOMDocument::getElementById() Example

Os exemplos a seguir usam um arquivo book.xml que contém o seguinte:

<?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>Princípios do PHP</title>
    <author email="jim.smith@basics.php">Jim Smith</author>
    <author email="jane.smith@basics.php">Jane Smith</author>
    <xhtml:blurb><![CDATA[
<p><em>Princípios do PHP</em> fornece uma introdução ao PHP.</p>
]]></xhtml:blurb>
  </book>
  <book id="php-advanced">
    <title>Programação PHP Avançada</title>
    <author email="jon.doe@advanced.php">Jon Doe</author>
  </book>
</books>
<?php

$doc = new DomDocument;

// We need to validate our document before referring to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

echo "The element whose id is 'php-basics' is: " . $doc->getElementById('php-basics')->tagName . "\n";

?>

O exemplo acima produzirá:

The element whose id is 'php-basics' is: book

Veja Também

  • DOMDocument::getElementsByTagName() - Searches for all elements with given local tag name

User Contributed Notes

Hoi 07-Jul-2020 10:39
To set a hidden id that can be used by $dom->getElementById() apply setAttribute('id', true) as in the following example

                    $createItemNode = function ($data) use ($dom) {
                        $node = $dom->createElement("Item");
                        $node->setAttribute('id', $data->id);
                        $node->setAttribute('hed', $data->hed);
                        $node->setAttribute('run_time', $data->run_time);
                        $node->setAttribute('date', $data->date);

                        // Internally mark the id as 'xml:id' for getElementById to work. Adding xml:id manually to the tag will cause loadXML to throw an error DOMDocument: xml:id is not a NCName in Entity
                        $node->setIdAttribute('id', true);

                        return $node;
                    };

With $node->setIdAttribute('id', true), $dom->getElementById($id) will work

When you do $dom->saveXML(), the final doc will not contain any xml:id attribute.
ed at edgiardina dot com 13-Oct-2010 11:41
Please note that if your HTML does not contain a doctype declaration, then getElementById will always return null.
paradox_haze at live dot de 02-Mar-2010 10:53
Had some issues with getElementById() while searching for a specific element in a XHTML document.
I wrote a small function what was solving my problem:

<?php
function getElementById($id)
{
    $xpath = new DOMXPath($this->domDocument);
    return $xpath->query("//*[@id='$id']")->item(0);
}
?>
carl2088 at gmail dot com 11-Apr-2009 12:41
From my experience, getElementById seem to work fine without any setups if you have loaded a HTML document. But in order for getElementById to work with a simple XML document that you've "constructed", you have to set up the id with "xml:" prefix and use setIdAttribute on the element you created or it won't work. See following example, hope this will save someone's frustration. If you have loaded the xml file, then all you have to make sure is the ID has a xml: prefix for the attribute.  But if you start to append the XML document, don't forget to setIdAttribute on the id name or those elements or getElementById will return null when you try to find them.

<?php

    /* test.xml
    <?xml version="1.0" encoding="utf-8"?>
    <root>
        <child xml:id="id_xxxxxx" status="partial">
            <sub_child>Some Data</sub_child>
        </child>
    </root>
    */

    $xmlDom = new DOMDocument('1.0', 'utf-8');
    $xmlDom->formatOutput = true;                        // we want a nice output

    // create a root
    $eltRoot = $xmlDom->createElement("root");
    $xmlDom->appendChild($eltRoot);

    $eltChild = $xmlDom->createElement("child");
    $eltRoot->appendChild($eltChild);

    // add a id attribute
    $attr = $xmlDom->createAttribute("xml:id");    // needs xml prefix or getElementById won't work
    $eltChild->appendChild($attr);

    /// create the text node and append to the created element
    $tNode = $xmlDom->createTextNode("id_8120528");
    $attr->appendChild($tNode);
    $eltChild->setIdAttribute("xml:id", true);    // VERY IMPORT or getElementById won't work

    // add a id attribute
    $attr = $xmlDom->createAttribute("status");
    $eltChild->appendChild($attr);

    /// create the text node and append to the created element
    $tNode = $xmlDom->createTextNode("partial");
    $attr->appendChild($tNode);

    // add a subchild
    $eltSub = $xmlDom->createElement("sub_child");
    $eltChild->appendChild($eltSub);

    $tNode = $xmlDom->createTextNode("Some Data");
    $eltSub->appendChild($tNode);

    $id = null;
    $id = $xmlDom->getElementById("id_8120528");

    assert ($id != null);

    $strId = $id->getAttribute("xml:id"); // bug? empty
    $strStatus = $id->getAttribute("status"); // this works!

    assert ($id !=null);

    $xmlDom->save("./_data/test.xml");

    $xmlDom->load("./_data/test.xml"); // reloading fixes the problem

    $nodeRoot = $xmlDom->getElementsByTagName("root");
    if ($nodeRoot->length > 0) {
        $eltRoot = $nodeRoot->item(0);
    }

    assert($eltRoot != null);

    $id = null;
    $id = $xmlDom->getElementById("id_8120528");

    assert ($id != null);

    $strId = $id->getAttribute("xml:id"); // this works now!
    $strStatus = $id->getAttribute("status"); // this works!

?>
guillaume dot crico at gmail dot com 01-Oct-2008 07:55
You don't want to use "xml:id" ?
Here is the relaxNG trick (with a generic schema):
(tested with libxml 2.6.26)

<?php
$doc = new DOMDocument();
$doc->load(...);

$rng = '
<grammar xmlns="http://relaxng.org/ns/structure/1.0" datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
    <start>
        <element>
            <anyName/>
            <ref name="anythingID"/>
        </element>
    </start>
    <define name="anythingID">
        <zeroOrMore>
            <choice>
                <element>
                    <anyName/>
                    <ref name="anythingID"/>
                </element>
                <attribute name="id">
                    <data type="ID"/>
                </attribute>
                <zeroOrMore>
                    <attribute><anyName/></attribute>
                </zeroOrMore>
                <text/>
            </choice>
        </zeroOrMore>
    </define>
</grammar>
';

$doc->relaxNGValidateSource($rng);
var_dump($doc->getElementById('id1'));
?>

Note that ID values must be valid ones :
  - integers do no work!
  - @see http://www.w3.org/TR/REC-xml/#id
  - => (Letter | '_' | ':') ( Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender  )*
simon at somewhere dot com 29-Jan-2007 08:07
SAVE YOURSELF A MAJOR HEADACHE AND A LOT OF SEARCHING THROUGH DOCUMENTATION -

Instead of using $object->setAttribute('id', 'id_name_here')
USE THIS: $object->setAttribute('xml:id', 'id_name_here')

Then, to get the node value: $domDocumentObject->getElementById('id_name_here');

The xml:id attribute should AUTOMATICALLY be defined!!

Woohoo!  That was easy......
jonbarnett at gmail dot com 01-Nov-2006 08:36
If your XML document does not have a DTD that defines the "id" attribute as an ID, then the easiest thing to do is to use XPath->query() to find an element that matches "//[@id='x']"
Tangui dot Le-Pense at laposte dot net 08-Apr-2006 06:00
Validating a document from a DTD so as to use getElementById is sometimes impossible (for example when the head and body elements are not included yet in a XHtml document : the validation failed).
Fortunately, xml:id is supported by this function :)
That may be useful.
http://www.w3.org/TR/xml-id/
20-Dec-2005 07:04
If you're trying to use getElementById with a xml file validated on a xsd file you must first use the schemaValidate function or getElementById will return null
Example:

  $dom = new DomDocument();
  $dom->load("users.xml");
  $dom->schemaValidate("users.xsd");

  $curruser = $dom->getElementById($user->name);
bart at mediawave dot nl 11-Sep-2005 04:46
It seems getElementById works fine without setting validateOnParse to true. Which is nice since setting this to true caused some performance problems with my script.


Searches for all elements with given local tag name

  • « DOMDocument::getElementById
  • DOMDocument::getElementsByTagNameNS »
  • PHP Manual
  • DOMDocument
  • Searches for all elements with given local tag name

DOMDocument::getElementsByTagName

(PHP 5, PHP 7, PHP 8)

DOMDocument::getElementsByTagName — Searches for all elements with given local tag name

Descrição

public DOMDocument::getElementsByTagName(string $qualifiedName): DOMNodeList

This function returns a new instance of class DOMNodeList containing all the elements with a given local tag name.

Parâmetros

qualifiedName

The local name (without namespace) of the tag to match on. The special value * matches all tags.

Valor Retornado

A new DOMNodeList object containing all the matched elements.

Exemplos

Exemplo #1 Basic Usage Example

<?php
$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<books>
<book>Patterns of Enterprise Application Architecture</book>
<book>Design Patterns: Elements of Reusable Software Design</book>
<book>Clean Code</book>
</books>
XML;

$dom = new DOMDocument;
$dom->loadXML($xml);
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
echo $book->nodeValue, PHP_EOL;
}
?>

O exemplo acima produzirá:

Patterns of Enterprise Application Architecture
Design Patterns: Elements of Reusable Software Design
Clean Code

Veja Também

  • DOMDocument::getElementsByTagNameNS() - Searches for all elements with given tag name in specified namespace

User Contributed Notes

Mateusz K 19-Dec-2019 08:04
If you want to move all nodes to another tag you can do it like that
Eg: replace <div> with nodes to <p> with the same nodes.

function replaceDomElementTag(DOMDocument $dom, DOMElement $node, string $tagName)
{
        $newElement = $dom->createElement($tagName);
        while ($node->childNodes->length)
            $newElement->appendChild($node->childNodes[0]);

        $node->parentNode->replaceChild($newElement, $node);
}

$dom = new DOMDocument();
replaceDomElementTag($dom, $divElementToReplace, 'p');
rsvvuuren at hotmail dot com 10-Jan-2014 10:00
I was in need of $dom->getElementsByTagName that would hist magic within a contextNode.

Why i needed getElementsByTagName instead of just simple using an xPath->query is because while looping through the returned nodelist, more nodes with the tagName i was looking for where created.

When using getElementsByTagName, the new nodes are "added" to the nodelist i already am looping through.

When using an xpath query, you wil only loop through the original nodelist, the newly created elements wil not appear in that nodelist.

I was already using an extended class on domDocument, so it was simple to create an kind of getElementsByTagName that would accept an contextNode.

<?php
class SmartDocument extends DOMDocument {
    private $localDom;
    public $xpath;
    private $serialize = array('localDom');

    private $elemName;
    private $elemCounter;

    /**
     * Constructor
     */
    function __construct() {
        parent::__construct ( '1.0', 'UTF-8' );
        $this->preserveWhiteSpace = false;
        $this->recover = TRUE;
        $this->xpath = new DOMXpath ( $this );
    }

    /**
     * GetElementsByTagname within an contextNode
     *
     * @param string $name
     * @param DomNode $contextNode
     * @return DOMNode|NULL
     */
    public function getElementsByTagNameContext($name, $contextNode) {

        if($this->elemName!=$name) {
            $this->elemCounter     = 0;
            $this->elemName        =$name;
        }

        $this->elemLength      = $this->xpath->evaluate('count(.//*[name()="'.$this->elemName.'"])', $contextNode);
        while($this->elemCounter < $this->elemLength) {
            $this->elemCounter++;
            $nl = $this->xpath->query('.//*[name()="'.$this->elemName.'"]['.$this->elemCounter.']', $contextNode);
            if($nl->length == 1) {
                return $nl->item(0);
            }
        }

        $this->elemLength      = null;
        $this->elemCounter     = null;
        $this->elemName        = null;
        return null;
    }
}

?>

Usage:

<?php

 $doc = new SmartDocument();
 $doc->load('book.xml');

 $nl = $doc->query('//books');
 foreach($nl as $node) {
  while($book = $doc->getElementsByTagNameContext('book', $node)) {
   //When you now create new nodes within this loop as child or following-sibling of this node
  // They show up within this loop
  }

 }

?>
simon at onepointltd dot com 10-Sep-2013 07:54
Here is a function to convert the populated tables in and HTML document into an array.

<?php
//Create an array containing all the populated tables in an HTML page
//Returned array: tables_to_array[table number][row number][column number]
function tables_to_array ($url) {
  $htmlDocDom = new DOMDocument();

  @$htmlDocDom->loadHTMLFile($url);
  $htmlDocDom->preserveWhiteSpace = false;
  $tableCounter = 0;
  $htmlDocTableArray = array();
  $htmlDocTables = $htmlDocDom->getElementsByTagName('table');
  foreach ($htmlDocTables as $htmlDocTable) {
    $htmlDocTableArray[$tableCounter] = array();
    $htmlDocRows= $htmlDocTable->getElementsByTagName('tr');
    $htmlDocRowCount = 0;
    $htmlDocTableArray[$tableCounter] = array();
    foreach ($htmlDocRows as $htmlDocRow) {
      if (strlen($htmlDocRow->nodeValue) > 1)
      {
        $htmlDocColCount = 0;
        $htmlDocTableArray[$tableCounter][$htmlDocRowCount] = array();
        $htmlDocCols = $htmlDocRow->getElementsByTagName('td');
        foreach ($htmlDocCols as $htmlDocCol) {
          $htmlDocTableArray[$tableCounter][$htmlDocRowCount][] = $htmlDocCol->nodeValue;
          $htmlDocColCount++;
        }
        $htmlDocRowCount++;
      }
    }
    if ($htmlDocRowCount > 1) $tableCounter++;
  }
  return($htmlDocTableArray);
}
?>
yaakov dot moddel at gmail dot com 28-Aug-2012 10:47
This is a very simplistic way to traverse xml nodes and childnodes using the DOMDocument class

<?php
$xml ='<?xml version="1.0" encoding="utf-8"?>
<root>
    <Parent>
        <child>child 1</child>
        <child>child 2</child>
        <child>child 3</child>
        <subParent>
            <Grandchild>Grandchild 1</Grandchild>
            <Grandchild>Grandchild 2</Grandchild>
            <Grandchild>Grandchild 3</Grandchild>
        </subParent>
    </Parent>
    <Parent>
        <child>child 4</child>
        <child>child 5</child>
        <child>child 6</child>
        <subParent>
            <Grandchild>Grandchild 4</Grandchild>
            <Grandchild>Grandchild 5</Grandchild>
            <Grandchild>Grandchild 6</Grandchild>
        </subParent>
    </Parent>
</root>';
      $doc = new DOMDocument();
      $doc->preserveWhiteSpace = false;
      $doc->loadXML($xml);
      $i=0;
            while(is_object($finance = $doc->getElementsByTagName("Parent")->item($i)))
            {
                     foreach($finance->childNodes as $nodename)
                     {
                             if($nodename->nodeName=='subParent')
                                {
                                     foreach($nodename->childNodes as $subNodes)
                                     {
                                     echo $subNodes->nodeName." - ".$subNodes->nodeValue."<br>";
                                     }
                                }
                             else
                                {
                                echo $nodename->nodeName." - ".$nodename->nodeValue."<br>";
                                }
                     }
      $i++;
            }
?>
metron at underhive-planet dot com 08-Oct-2010 05:28
My first try to get a stable solution with this function, failed with this Exception:

"Fatal error: Call to undefined method DOMNodeList::getElementsByTagName()"
This is the xml snipplet:
<?xml version="1.0" encoding="UTF-8"?>
<root>
 <component>
  <properties>
    ....<any element>
  </properties>
 </component>
</root>

So the php code to climb along the elements is:
<?php

$src = new DOMDocument('1.0', 'utf-8');
$src->formatOutput = true;
$src->preserveWhiteSpace = false;

//Loading extern file
$src->load('../xml/Item_component.xml');

//Check each child of first indexed branch node of: <component>
//First get element after root element: <component>

//1st level
$component = $src->getElementsByTagName('component')->item(0);

//2nd level, get next element after component, here it fails!!
$properties = $component->getElementsByTagName('properties')->item(0);
...
?>

I realised, that there is a different when using different libxml2 versions on Apache2. This code will fail with libxml2 version 2.6.23 and PHP version 5.2.6
--
->It works fine with libxml2 version 2.6.32 and PHP version 5.2.6-3ubuntu4.6
->...and finally it also works with libxml2 2.7.7 and PHP >= 5.3

So if you bored to search for solutions with DOM like I did, please ensure that your www environment has the correct libxml2 / PHP Version installed on your apache2 server.
calvin at g mail 02-Oct-2010 04:41
My first post!
And this is how I get elements by attribute and its value.
For an example, if I want to grab all DIV tags with class name 'className', then...

<?php
$some_link = 'some website';
$tagName = 'div';
$attrName = 'class';
$attrValue = 'className';

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
@$dom->loadHTMLFile($some_link);

$html = getTags( $dom, $tagName, $attrName, $attrValue );
echo $html;

function getTags( $dom, $tagName, $attrName, $attrValue ){
    $html = '';
    $domxpath = new DOMXPath($dom);
    $newDom = new DOMDocument;
    $newDom->formatOutput = true;

    $filtered = $domxpath->query("//$tagName" . '[@' . $attrName . "='$attrValue']");
    // $filtered =  $domxpath->query('//div[@class="className"]');
    // '//' when you don't know 'absolute' path

    // since above returns DomNodeList Object
    // I use following routine to convert it to string(html); copied it from someone's post in this site. Thank you.
    $i = 0;
    while( $myItem = $filtered->item($i++) ){
        $node = $newDom->importNode( $myItem, true );    // import node
        $newDom->appendChild($node);                    // append node
    }
    $html = $newDom->saveHTML();
    return $html;
}

?>

Please, improve it, and share it.
Philip N 01-Sep-2010 03:17
Note that when using getElementsByTagName that it is a dynamic list. Thus if you have code which adjusts the DOM structure it will change the results of the getElementsByTagName results list.

The following code iterates through a complete set of results and changes them all to a new tag:

<?php
 $nodes = $xml->getElementsByTagName ("oldtag");

 $nodeListLength = $nodes->length; // this value will also change
 for ($i = 0; $i < $nodeListLength; $i ++)
 {
    $node = $nodes->item(0);

    // some code to change the tag name from "oldtag" to something else
    // e.g. encrypting a tag element
 }
?>

Since the list is dynamically updating, $nodes->item(0) is the next "unchanged" tag.
Marco Maranao 27-Apr-2010 10:22
The following takes a list of news items from an XML file (or an RSS feed), assigning it to an array first for a name value pair and then generating an HTML list.

<?php

$xml  =<<<EOT
<?xml version="1.0" encoding="ISO-8859-1"?>
<news>
    <item>
        <title>News 1</title>
        <created>04/2/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
    <item>
        <title>News 2</title>
        <created>04/25/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
    <item>
        <title>News 3</title>
        <created>04/27/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
</news>
EOT;

$doc = new DOMDocument();

if ($doc->loadXML($xml)) {
    $items = $doc->getElementsByTagName('item');
    $headlines = array();

    foreach($items as $item) {
        $headline = array();

        if($item->childNodes->length) {
            foreach($item->childNodes as $i) {
                $headline[$i->nodeName] = $i->nodeValue;
            }
        }

        $headlines[] = $headline;
    }

    if(!empty($headlines)) {
        $hc = 0;

        echo '<ul>';

        foreach($headlines as $headline) {
            if(++$hc <= 3) {
                echo '<li>'
                    .'<a href="'.$headline['url'].'" target="_blank">'
                        .'<span>'.date('F j, Y', strtotime($headline['created'])).'</span><br />'
                        .$headline['title']
                    .'</a>'
                .'</li>';
            }
        }

        echo '</ul>';
    }
}

?>
james 01-Feb-2010 07:03
Problem:
You have an XML document that contains filename references to, say, images. Each filename reference is defined by <file>filename.ext</file> tag. You'd like to perform perform additional validation, say, after running the XML document through XSD validation. The additional validation can be any of your choice, in this example, it would be ideal to convert the PHP code to a function. The function would then determine if the images exist and return either an integer value or a boolean.

<?xml version="1.0"?>
<root>
<box>
<file>example.png</file>
</box>
<content>
<item>
<image><file>example2.png</file></image>
<caption>The above image is an example</caption>
</item>
</content>
</root>

Solution:
<?php

$dom = new DomDocument();
$dom->prevservWhiteSpace = false;

if (!@$dom->load("example.xml")) {
    echo "example.xml doesn't exist!\n";
    return;
}

$imageList = $dom->getElementsByTagName('file');
$imageCnt  = $imageList->length;

for ($idx = 0; $idx < $imageCnt; $idx++) {
    print $imageList->item($idx)->nodeValue . "\n";
}

?>

The above PHP code could easily be turned into a function that returns an array of image filenames, an integer value relative to the number of images found, etc.

Hope this is helpful.
gurmukh24 at gmail dot com 03-Mar-2009 04:06
Following Example is of multiple attributes and multiple child nodes. this is being used to make joomla plugin for bulk upload of articles. Gurmukh Singh Bhatti

<?php
$xml =<<<EOT
<?xml version="1.0"?>
<root>
<section name="Section1">
  <category id="Category1" name="google">
   <arti name="article1">
   <p>any html code here</p>
   <b>my name is so so</b>
    </arti>
   <arti name="article2">value2</arti>
   <arti name="article3">value3</arti>
   <arti name="article4">value4</arti>
  </category>
    <category id="Category2" name="yahoo">
   <arti name="articleSection2">Test value</arti>
  </category>
</section>
<section name="Section2">
  <category id="category1_of_section2" name="msn">
   <arti name="article2">value1</arti>
   <arti name="article3">value2</arti>
  </category>
    <category id="Category2_of_section2" name="webcare">
    <arti name="param3">value4</arti>
   </category>
</section>
</root>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('section'); // Find Sections
$k=0;
foreach ($params as $param) //go to each section 1 by 1
{
         echo "Section Attribute :-> ".$params->item($k)->getAttribute('name')."<br>";   //get section attribute
         $params2 = $params->item($k)->getElementsByTagName('category'); //digg categories with in Section
      $i=0; // values is used to iterate categories
        foreach ($params2 as $p) {
           echo "&nbsp;&nbsp;- Category Attribute Name :-> ".$params2->item($i)->getAttribute('name')."<br>"; //get Category attributes
            $params3 = $params2->item($i)->getElementsByTagName('arti'); //dig Arti into Categories
                 $j=0;//values used to interate Arti
                     foreach ($params3 as $p2)
                   {
                    echo "&nbsp;&nbsp;&nbsp;- Article Attribute Name : ".$params3->item($j)->getAttribute('name').""; //get arti atributes
echo "&nbsp;&nbsp; Value : ".$params3->item($j)->nodeValue."<br>"; //get Node value ;
                              $j++;
                   }
         $i++;
      }
$k++;

}
?>

output :
 Section Attribute :-> Section1
  - Category Attribute Name :-> google
            - Article Attribute Name : article1   Value : any html code heremy name is so so
            - Article Attribute Name : article2   Value : value2
            - Article Attribute Name : article3   Value : value3
            - Article Attribute Name : article4   Value : value4
  - Category Attribute Name :-> yahoo
            - Article Attribute Name : articleSection2   Value : Test value
Section Attribute :-> Section2
  - Category Attribute Name :-> msn
            - Article Attribute Name : article2   Value : value1
            - Article Attribute Name : article3   Value : value2
  - Category Attribute Name :-> webcare
            - Article Attribute Name : param3   Value : value4
James L 19-Aug-2008 04:04
Return if there are no matches is an empty DOMNodeList. Check using length property, e.g.:

<?php
$nodes=$domDocument->getElementsByTagName('book') ;
if ($nodes->length==0) {
   // no results
}
?>
jason at shaped dot ca 11-Feb-2008 04:59
in response to tildy at pr dot hu

my preferred way is (in example to gather country data from an iso 3166 xml flie)

$countries = new DOMDocument();
$countries->load("./lib/iso_3166.xml");

$countriesList = $countries->getElementsByTagName("ISO_3166-1_Entry");

foreach($countriesList as $country) {
    $values = $country->getElementsByTagName("*");
    foreach($values as $node) {
      echo $node->nodeName."=".$node->nodeValue;
    }
}
Finding values of a node 14-Mar-2007 02:01
I don't know if this is that obvious but it was not for me, so in addition to gem at rellim dot com's posting:
adding

<?php
echo $param -> nodeValue.'<br>';
?>

to the loop will output
value1
value2
value3
gem at rellim dot com 29-Sep-2004 04:20
Here is an example of getElementsByTagName():

<?php
$xml =<<<EOT
<?xml version="1.0"?>
<config>
  <section id="section1">
   <param name="param1">value1</param>
   <param name="param2">value2</param>
  </section>
  <section id="section2">
   <param name="param3">value3</param>
  </section>
</config>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('param');

foreach ($params as $param) {
       echo $param -> getAttribute('name').'<br>';
}
?>

Expected result:
--------------
param1
param2
param3


Searches for all elements with given tag name in specified namespace

  • « DOMDocument::getElementsByTagName
  • DOMDocument::importNode »
  • PHP Manual
  • DOMDocument
  • Searches for all elements with given tag name in specified namespace

DOMDocument::getElementsByTagNameNS

(PHP 5, PHP 7, PHP 8)

DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace

Descrição

public DOMDocument::getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList

Returns a DOMNodeList of all elements with a given local name and a namespace URI.

Parâmetros

namespace

The namespace URI of the elements to match on. The special value "*" matches all namespaces. Passing null matches the empty namespace.

localName

The local name of the elements to match on. The special value "*" matches all local names.

Valor Retornado

A new DOMNodeList object containing all the matched elements.

Changelog

Versão | Descrição
8.0.3 | namespace is nullable now.

Exemplos

Exemplo #1 Get all the XInclude elements

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Books of the other guy..</title>
<para>
<xi:include href="book.xml">
<xi:fallback>
<error>xinclude: book.xml not found</error>
</xi:fallback>
</xi:include>
<include>
This is another namespace
</include>
</para>
</chapter>
EOD;
$dom = new DOMDocument;

// load the XML string defined above
$dom->loadXML($xml);

foreach ($dom->getElementsByTagNameNS('http://www.w3.org/2001/XInclude', '*') as $element) {
echo 'local name: ', $element->localName, ', prefix: ', $element->prefix, "\n";
}
?>

O exemplo acima produzirá:

local name: include, prefix: xi
local name: fallback, prefix: xi

Veja Também

  • DOMDocument::getElementsByTagName() - Searches for all elements with given local tag name

User Contributed Notes

RiKdnUA at mail dot ru 19-Mar-2015 07:47
<?php
ini_set("display_errors","on"); error_reporting(-1);
$doc="<?xml version='1.0' encoding='WINDOWS-1251'?>
<htm:body xmlns:htm='w3.org'>
<span>Text</span>
<htm:img htm:src='imgSrc'/>
</htm:body>";
$dom = new DOMDocument('1.0','WINDOWS-1251');
$dom->preserveWhiteSpace=false;
$dom->loadXML($doc);
$domList=$dom->getElementsByTagNameNS('*','*');//all namespaces, all local names
echo "?????????? ?????????. The number of elements: ".$domList->length."<br />";// 2 (not 3)
for ($i=0; $i<$domList->length; $i++)
{echo "??????? $i. The element $i: ".$domList->item($i)->tagName."<br />";
}
/*
Tested in PHP 5.2.9-2 and 5.2.17
The above example will output:
?????????? ?????????. The number of elements: 2
??????? 0. The element 0: htm:body
??????? 1. The element 1: htm:img

?????. ?? ?????? ??????? span
Conclusion. Not found span element
*/
?>


Import node into current document

  • « DOMDocument::getElementsByTagNameNS
  • DOMDocument::load »
  • PHP Manual
  • DOMDocument
  • Import node into current document

DOMDocument::importNode

(PHP 5, PHP 7, PHP 8)

DOMDocument::importNode — Import node into current document

Descrição

public DOMDocument::importNode(DOMNode $node, bool $deep = false): DOMNode|false

This function returns a copy of the node to import and associates it with the current document.

Parâmetros

node

The node to import.

deep

If set to true, this method will recursively import the subtree under the node.

Nota:

To copy the nodes attributes deep needs to be set to true

Valor Retornado

The copied node or false, if it cannot be copied.

Erros

DOMException is thrown if node cannot be imported.

Exemplos

Exemplo #1 DOMDocument::importNode() example

Copying nodes between documents.

<?php

$orgdoc = new DOMDocument;
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>");

// The node we want to import to a new document
$node = $orgdoc->getElementsByTagName("element")->item(0);

// Create a new document
$newdoc = new DOMDocument;
$newdoc->formatOutput = true;

// Add some markup
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>");

echo "The 'new document' before copying nodes into it:\n";
echo $newdoc->saveXML();

// Import the node, and all its children, to the document
$node = $newdoc->importNode($node, true);
// And then append it to the "<root>" node
$newdoc->documentElement->appendChild($node);

echo "\nThe 'new document' after copying the nodes into it:\n";
echo $newdoc->saveXML();
?>

O exemplo acima produzirá:

The 'new document' before copying nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
</root>

The 'new document' after copying the nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
  <element>
    <child>text in child</child>
  </element>
</root>

User Contributed Notes

rikdnua at mail dot ru 11-Sep-2013 01:54
The behavior of importNode($node, false) is different in PHP 5.2.9-2 and PHP 5.2.17.
The second option is explicitly set to false. In PHP 5.2.9-2 importNode() imports the elements WITHOUT attributes. In PHP 5.2.17 the elements imported ALONG with their attributes.
<?php
$xml="
<html>
<a href='yandex.com'>Yandex.com</a>
<a href='rik.dn.ua'>RiK.dn.ua</a>
</html>
";
$doc=new domDocument('1.0');
$doc->loadXML($xml);
$list=$doc->getElementsByTagName('a');
$doc1=new domDocument('1.0');
$doc1->formatOutput=true;
for($i=0; $i<$list->length; $i++) $doc1->appendChild($doc1->importNode($list->item($i), false));
$doc1->save('file.xml');
?>

file.xml PHP 5.2.9-2
<?xml version="1.0"?>
<a/>
<a/>

file.xml PHP 5.2.17
<?xml version="1.0"?>
<a href="yandex.com"/>
<a href="rik.dn.ua"/>
c dot 1 at smithies dot org 19-Oct-2009 06:40
Assume that $source and $dest are instances of DOMDocument. Assume that $sourcedoc contains an element with ID 'sourceID' and that $destdoc contains an element with ID 'destID'. Assume that we have already set up source and destination element variables thus:

<?php
 $src = $sourcedoc->getElementById('sourceID');
 $dst = $destdoc->getElementById('destID');
?>

Finally, assume that $sel has more than one child node.

In order to import the child elements of $src as children of $dst, you might do something like this:

<?php
$src = $dest->importNode($src, TRUE);

foreach ($src->childNodes as $el) $dst->appendChild($el);
?>

But this does not work. foreach gets confused, because (as noted below) appending an imported element to another existing element in the same document causes it to be removed from its current parent element.

Therefore, the following technique should be used:

<?php
foreach ($src->childNodes as $el) $dst->appendChild($destdoc->importNode($el, TRUE));
?>
p dot reisinger at gmail dot com 29-Dec-2008 03:43
When you use function/method below, php automaticaly inserts namespaces (if you have some). If you want to join xml files exactly, then you can just use placeholders and treat xml as a string.
<?php
function joinXMLStrings($file1, $file2)
{
    //remove xml declaration
    $file2 = trim(preg_replace('/<\?xml.*\?>/', '', $file2, 1));

    //insert file2 in the place of placeholder in the first file
    $file1 = trim(preg_replace('/<\?file2\s\?>/', $file2, $file1, 1));
}
?>

so function looks like this and you insert two xml files. First file has to have placeholder (where you insert file2). Placeholder in this case will be <?file2 ?>

!!!this is only for ilustration - test before you use it
p dot reisinger at gmail dot com 23-Dec-2008 07:32
method (can be used as a function as well) that joins two xml files. first argument is parent xml (the one to be inserted into), second child (the one to be inserted) and third is optional argument that specifies the parent's tag where to insert children xml. If not specified then children is inserted as the last element, just before end of the root
<?php
    protected function joinXML($parent, $child, $tag = null)
    {
        $DOMChild = new DOMDocument;
        $DOMChild->loadXML($child);
        $node = $DOMChild->documentElement;

        $DOMParent = new DOMDocument;
        $DOMParent->formatOutput = true;
        $DOMParent->loadXML($parent);

        $node = $DOMParent->importNode($node, true);

        if ($tag !== null) {
            $tag = $DOMParent->getElementsByTagName($tag)->item(0);
            $tag->appendChild($node);
        } else {
            $DOMParent->documentElement->appendChild($node);
        }

        return $DOMParent->saveXML();
    }
?>
mailme at sove dot nl 11-Jun-2008 05:29
DOMDocument->importNode with seconds argument false will leave attributes behind. To fix this:

$__DOM->importNode
   (
      $__INPUT->cloneNode(false), true
   );

$__DOM (DOMDocument) will import the $__INPUT node (DOMElement) INCLUDING attributes.
mark at 4inloop dot de 05-Apr-2007 05:51
When you left out the second argument or enter false, not only the child nodes are ommited. The attributes of the node are also cut off.
adjwilli 05-Oct-2006 01:08
Editing XML with PHP can be a pain in the Secretary of State Powell, so here's a script to replace an XML node with a user-provided one through the POST. It's usually a good idea to run the $_POST['xml'] through a validation check and clean it for other thing before running this.

Pretty much this script expects a user-provided node called $_POST['xml'] and the XPath of the node in the original document that you want to replace called $_POST['XPath']. It also loads the original XML document from $xml. The function nodeRunner begins with the root node of the document you're editting and the XPath for the root element (these are more to make recursion easy than anything else).

$doc = new DOMDocument();
$doc->loadXML($xml); // $xml expects an XML string

function nodeRunner ($node,$xpath) {
    global $doc;
    if ($xpath == $_POST['XPath']) {

        $xmlPost = new DOMDocument();
        $xmlPost->loadXML($_POST['xml']);

        $newNode = $doc->importNode($xmlPost->firstChild,true);

        $node->parentNode->replaceChild($newNode,$node);
    } else {

        $page = 1;
        $section = 1;

        if ($node->hasChildNodes()) {
            foreach ($node->childNodes as $nodling) {
                $nodeName = $nodling->nodeName;
                if ($nodeName == 'page' || $nodeName == 'section') {
                    nodeRunner ($nodling,$xpath."/".$nodeName."[".$$nodeName."]");
                    $$nodeName++;
                }
            }
        }
    }
}

nodeRunner ($doc->documentElement,"/root[1]"); // /root should be explicit name of the root  element of the XPath

$doc->saveXML();
stomas 19-Sep-2006 06:14
I think this should do the same:

<?
 // Import $b into $a's document
 function myimport($a, $b)
 {
   if ($a->ownerDocument->isSameNode($b->ownerDocument))
   {
    return $b->cloneNode(TRUE);
   }
   else
   {
    return $a->ownerDocument->importNode($b, TRUE);
   }
 }
 ?>
Colin 12-Sep-2006 09:11
As of PHP 5.1.6 with libxml 2.6.26 and DOM/XML API version 20031129, importNode() does nothing if attempting to import from the same document.  Meaning, if you do an $ret = importNode and then appendChild($ret) or insertBefore($ret, ...) then you will end up *moving* the node instead of ending up with a copy.

If you expect importNode to give you a copy of the source (in this case, a deep copy) then you must account for them being from the same document.  This function addresses this:

<?
// Import $b into $a's document
function myimport($a, $b)
{
  if ($a->ownerDocument->isSameNode($b->ownerDocument))
  {
    $temp = new DOMDocument();
    $ret = $temp->importNode($b, TRUE);
    return $a->ownerDocument->importNode($ret, TRUE);
  }
  else
  {
    return $a->ownerDocument->importNode($b, TRUE);
  }
}
?>

(Function was freshly coded for this note but I based it off another, working function of mine.)

This function checks if the documents are the same and uses a new document (guaranteed to be different this way) to force a copy into $temp and then force a copy back into $a->ownerDocument.

Obviously, no error checking has been done.
andy dot clark at dial dot pipex dot com 15-Aug-2006 08:20
One useful use of importNode is to copy one node onto another.

function CopyXMLNode($SourceNode,$DestNode)
 {
  if ($SourceNode->nodeName != '#text')
   {
     //Copy this node
    $node = $DestNode->ownerDocument->importNode($SourceNode, true);
    $node = $DestNode->appendChild($node);
    //Now copy the child nodes
    foreach ($SourceNode->childNodes AS $item)
     {
     $this->CopyXMLNode($item,$node);
     }
    }
  }
Fitopaldi 03-Aug-2005 11:29
importNode returns a copy of the node to import and associates it with the current document, but not import the node to the current DOMDocument. Use appendChild for import the copy of the node to current DOMDocument.

<?
 $domNode = $dom->importNode($aDomNode, true);
 $currentDomDocument->appendChild($domNode);
?>


Load XML from a file

  • « DOMDocument::importNode
  • DOMDocument::loadHTML »
  • PHP Manual
  • DOMDocument
  • Load XML from a file

DOMDocument::load

(PHP 5, PHP 7, PHP 8)

DOMDocument::load — Load XML from a file

Descrição

public DOMDocument::load(string $filename, int $options = 0): bool

Loads an XML document from a file.

Aviso

Unix style paths with forward slashes can cause significant performance degradation on Windows systems; be sure to call realpath() in such a case.

Parâmetros

filename

The path to the XML document.

options

Bitwise OR of the libxml option constants.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

Changelog

Versão | Descrição
8.3.0 | This function now has a tentative bool return type.
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

Exemplos

Exemplo #1 Creating a Document

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

Veja Também

  • DOMDocument::loadXML() - Load XML from a string
  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string

User Contributed Notes

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


Load HTML from a string

  • « DOMDocument::load
  • DOMDocument::loadHTMLFile »
  • PHP Manual
  • DOMDocument
  • Load HTML from a string

DOMDocument::loadHTML

(PHP 5, PHP 7, PHP 8)

DOMDocument::loadHTML — Load HTML from a string

Descrição

public DOMDocument::loadHTML(string $source, int $options = 0): bool

The function parses the HTML contained in the string source. Unlike loading XML, HTML does not have to be well-formed to load.

Aviso

This function parses the input using an HTML 4 parser. The parsing rules of HTML 5, which is what modern web browsers use, are different. Depending on the input this might result in a different DOM structure. Therefore this function cannot be safely used for sanitizing HTML.

As an example, some HTML elements will implicitly close a parent element when encountered. The rules for automatically closing parent elements differ between HTML 4 and HTML 5 and thus the resulting DOM structure that DOMDocument sees might be different from the DOM structure a web browser sees, possibly allowing an attacker to break the resulting HTML.

Parâmetros

source

The HTML string.

options

Bit a bit OR das constantes de opções da libxml.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros

If an empty string is passed as the source, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

Embora o HTML malformado deva ser carregado com sucesso, esta função pode gerar erros E_WARNING quando encontrar marcação incorreta. As funções de tratamento de erros da biblioteca libxml podem ser usadas para lidar com esses erros.

Changelog

Versão | Descrição
8.3.0 | This function now has a tentative bool return type.
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

Exemplos

Exemplo #1 Creating a Document

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

Veja Também

  • DOMDocument::loadHTMLFile() - Load HTML from a file
  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting

User Contributed Notes

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.


Load HTML from a file

  • « DOMDocument::loadHTML
  • DOMDocument::loadXML »
  • PHP Manual
  • DOMDocument
  • Load HTML from a file

DOMDocument::loadHTMLFile

(PHP 5, PHP 7, PHP 8)

DOMDocument::loadHTMLFile — Load HTML from a file

Descrição

public DOMDocument::loadHTMLFile(string $filename, int $options = 0): bool

The function parses the HTML document in the file named filename. Unlike loading XML, HTML does not have to be well-formed to load.

Aviso

This function parses the input using an HTML 4 parser. The parsing rules of HTML 5, which is what modern web browsers use, are different. Depending on the input this might result in a different DOM structure. Therefore this function cannot be safely used for sanitizing HTML.

As an example, some HTML elements will implicitly close a parent element when encountered. The rules for automatically closing parent elements differ between HTML 4 and HTML 5 and thus the resulting DOM structure that DOMDocument sees might be different from the DOM structure a web browser sees, possibly allowing an attacker to break the resulting HTML.

Parâmetros

filename

The path to the HTML file.

options

Bit a bit OR das constantes de opções da libxml.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

Embora o HTML malformado deva ser carregado com sucesso, esta função pode gerar erros E_WARNING quando encontrar marcação incorreta. As funções de tratamento de erros da biblioteca libxml podem ser usadas para lidar com esses erros.

Changelog

Versão | Descrição
8.3.0 | This function now has a tentative bool return type.
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

Exemplos

Exemplo #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
echo $doc->saveHTML();
?>

Veja Também

  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting

User Contributed Notes

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

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
onemanbanddan at gmail dot com 04-Mar-2014 12:28
The options for surpressing errors and warnings will not work with this as they do for loadXML()
e.g.
<?php
$doc->loadHTMLFile($file, LIBXML_NOWARNING | LIBXML_NOERROR);
?>
will not work.
you must use:
<?php
libxml_use_internal_errors(true);
$doc->loadHTMLFile($file);
?>
and handle the exceptions as neccesarry.
Mark Omohundro, ajamyajax dot com 28-Nov-2008 06:32
<?php
// try this html listing example for all nodes / includes a few getElementsByTagName options:

$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

// example 1:
$elements = $doc->getElementsByTagName('*');
// example 2:
$elements = $doc->getElementsByTagName('html');
// example 3:
//$elements = $doc->getElementsByTagName('body');
// example 4:
//$elements = $doc->getElementsByTagName('table');
// example 5:
//$elements = $doc->getElementsByTagName('div');

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>". $element->nodeName. ": ";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}
?>
gzech at SPAMFILTER dot eso dot org 21-Feb-2007 02:09
If you want to suppress output warnings from loadHTMLFile($url), put an @ sign in front. This even works in:
<?php
$load = @$dom->loadHTMLFile($url);
?>
andy at carobert dot com 25-May-2005 01:24
This puts the HTML into a DOM object which can be parsed by individual tags, attributes, etc..  Here is an example of getting all the 'href' attributes and corresponding node values out of the 'a' tag. Very cool....

<?php
$myhtml = <<<EOF
<html>
<head>
<title>My Page</title>
</head>
<body>
<p><a href="/mypage1">Hello World!</a></p>
<p><a href="/mypage2">Another Hello World!</a></p>
</body>
</html>
EOF;

$doc = new DOMDocument();
$doc->loadHTML($myhtml);

$tags = $doc->getElementsByTagName('a');

foreach ($tags as $tag) {
       echo $tag->getAttribute('href').' | '.$tag->nodeValue."\n";
}
?>

This should output:

/mypage1 | Hello World!
/mypage2 | Another Hello World!
bens at effortlessis dot com 08-Apr-2005 05:11
Note that this function doesn't parse the individual tags WITHIN the html file - it's all loaded as a "black box", and you end up with an XML widget that comprises nothing but the complete chunk of HTML.

I was hoping it would function as a sort of HTML-validator/parser, but that doesn't seem to be the case.


Load XML from a string

  • « DOMDocument::loadHTMLFile
  • DOMDocument::normalizeDocument »
  • PHP Manual
  • DOMDocument
  • Load XML from a string

DOMDocument::loadXML

(PHP 5, PHP 7, PHP 8)

DOMDocument::loadXML — Load XML from a string

Descrição

public DOMDocument::loadXML(string $source, int $options = 0): bool

Loads an XML document from a string.

Parâmetros

source

The string containing the XML.

options

Bitwise OR of the libxml option constants.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros

If an empty string is passed as the source, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

Changelog

Versão | Descrição
8.3.0 | This function now has a tentative bool return type.
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

Exemplos

Exemplo #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Veja Também

  • DOMDocument::load() - Load XML from a file
  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string

User Contributed Notes

Adrian Wiik 13-Nov-2019 09:02
A call to loadXML() will overwrite the XML declaration previously created in the constructor of DOMDocument. This can cause encoding problems if there is no XML declaration in the loaded XML and you don't have control over the source (e.g. if the XML is coming from a webservice). To fix this, set encoding AFTER loading the XML using the 'encoding' class property of DOMDocument. Example:

Bad situation:

test.xml:
<test>
    <hello>hi</hello>
    <field>ø</field>
</test>

test.php:
$xmlDoc = new DOMDocument("1.0", "utf-8"); // Parameters here are overwritten anyway when using loadXML(), and are not really relevant
$testXML = file_get_contents("test.xml");
$xmlDoc->loadXML($testXML);
// Print the contents to a file or in a log function to get the output, using $xmlDoc->saveXML()

Output:
<?xml version="1.0"?>
<test>
    <hello>hi</hello>
    <field>&#xF8;</field>
</test>

Good situation:

test.xml:
<test>
    <hello>hi</hello>
    <field>ø</field>
</test>

test.php:
$xmlDoc = new DOMDocument("1.0", "utf-8"); // Parameters here are overwritten anyway when using loadXML(), and are not really relevant
$testXML = file_get_contents("test.xml");
$xmlDoc->loadXML($testXML);
$xmlDoc->encoding = "utf-8";
// Print the contents to a file or in a log function to get the output, using $xmlDoc->saveXML()

Output:
<?xml version="1.0" encoding="utf-8"?>
<test>
    <hello>hi</hello>
    <field>ø</field>
</test>
Gustavo L. Fabro 14-Nov-2013 04:41
Always remember that with the default parameters this function doesn't handle well large files, i.e. if a text node is longer than 10Mb it can raise an exception stating:

DOMDocument::loadXML(): internal error Extra content at the end of the document in Entity

even though the XML is fine.

The cause is a definition in parserInternals.h of lixml:
#define XML_MAX_TEXT_LENGTH 10000000

To allow the function to process larger files, pass the LIBXML_PARSEHUGE as an option and it will work just fine:

$domDocument->loadXML($xml, LIBXML_PARSEHUGE);
szalma dot laszlo at zengo dot eu 27-Oct-2009 08:14
Loading from a string works fine without the <?xml version="1.0" encoding="utf-8"?> header, but in this case the xmlEncoding won't be set, and this makes the utf-8 characters (international, and special characters) to be encoded as hexa entities when saved with saveXML()!
remacg 26-Feb-2009 07:33
Instead of doing this:

<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$dd2->loadXML($str);

echo $dd2->saveXML();
?>

simply use:

loadHTML() rather than loadXML().
olalonde at NOSPAM dot gmail dot com 21-Mar-2008 05:00
For some reason, when you set DOMDocument's property 'recover' to true, using '@' to mask errors thrown by loadXml() won't work.

Here's my workaround:

function maskErrors() {}
set_error_handler('maskErrors');
$dom->loadXml($xml);
restore_error_handler();

You could also simply do this: error_reporting(0); and then set back error_reporting to its original state.
Stuart Grimshaw 26-Jun-2007 01:57
Possible values for the options parameter can be found here:

http://us3.php.net/manual/en/ref.libxml.php#libxml.constants
Marc Liyanage 18-Jun-2007 07:08
The documentation states that loadXML can be called statically, but this is misleading. This feature seems to be a special case hack and its use seems to be discouraged according to http://bugs.php.net/bug.php?id=41398.

Calling the method statically will fail with an error if the code runs with E_STRICT error reporting enabled.

The documentation should be changed to make it clear that a static call is against recommended practice and won't work with E_STRICT.
jazzslider at hotmail dot com 30-Apr-2007 01:14
When using loadXML() to parse a string that contains entity references (e.g., &nbsp;), be sure that those entity references are properly declared through the use of a DOCTYPE declaration; otherwise, loadXML() will not be able to interpret the string.

Example:
<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd1 = new DOMDocument();
$dd1->loadXML($str);

echo $dd1->saveXML();
?>

Given the above code, PHP will issue a Warning about the entity 'nbsp' not being properly declared.  Also, the call to saveXML() will return nothing but a trimmed-down version of the original processing instruction...everything else is gone, and all because of the undeclared entity.

Instead, explicitly declare the entity first:
<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$dd2->loadXML($str);

echo $dd2->saveXML();
?>

Since the 'nbsp' entity is defined in the DOCTYPE, PHP no longer issues that Warning; the string is now well-formed, and loadXML() understands it perfectly.

You can also use references to external DTDs in the same way (e.g., <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">), which is particularly important if you need to do this for many different documents with many different possible entities.

Also, as a sidenote...entity references created by createEntityReference() do not need this kind of explicit declaration.
shaoyu73 at gmail dot com 15-Mar-2007 08:53
earth at anonymous dot com,

preserveWhiteSpace property needs to be set to false for formatOutput to work properly, for some reason.

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadXML($xmlStr);
...
$element->appendChild(...);
...
$dom->formatOutput = true;
$xmlStr = $dom->saveXML();
echo $xmlStr;

This would format the output nicely.
Gavin Sinai gsinai at gmx dot net 30-Aug-2006 07:34
loadXml reports an error instead of throwing an exception when the xml is not well formed. This is annoying if you are trying to to loadXml() in a try...catch statement. Apparently its a feature, not a bug, because this conforms to a spefication.

If you want to catch an exception instead of generating a report, you could do something like

<?php
function HandleXmlError($errno, $errstr, $errfile, $errline)
{
    if ($errno==E_WARNING && (substr_count($errstr,"DOMDocument::loadXML()")>0))
    {
        throw new DOMException($errstr);
    }
    else
        return false;
}

function XmlLoader($strXml)
{
    set_error_handler('HandleXmlError');
    $dom = new DOMDocument();
    $dom->loadXml($strXml);
    restore_error_handler();
    return $dom;
 }

?>

Returning false in function HandleXmlError() causes a fallback to the default error handler.
mp at webfactory dot de 08-Aug-2006 08:26
While loadXML() expects its input to have a leading XML processing instruction to deduce the encoding used, there's no such concept in (non-XML) HTML documents. Thus, the libxml library underlying the DOM functions peeks at the <META> tags to figure out the encoding used.

See http://xmlsoft.org/encoding.html.
earth at anonymous dot com 12-Apr-2006 02:28
Note that loadXML crops off beginning and trailing whitespace and linebreaks.

When using loadXML and appendChild to add a chunk of XML to an existing document, you may want to force a linebreak between the end of the XML chunk and the next line (usually a close tag) in the output file:

$childDocument = new DOMDocument;
$childDocument>preserveWhiteSpace = true;
$childDocument->loadXML(..XML-Chunk..);
$mNewNode = $mainDOcument->importNode($childDocument->documentElement, true);
$ParentNode->appendChild($mNewNode);
$ParentNode->appendChild($mainDocument->createTextNode("\\n  ");

Although it is said that DOM should not be used to make 'pretty' XML output, it is something I struggled with to get something that was readable for testing.  Another solution is to use the createDocumentFragment()->appendXML(..XML-Chunk..) instead, which seems not to trim off linebreaks like DOMDocument->loadXML() does.


Normalizes the document

  • « DOMDocument::loadXML
  • DOMDocument::prepend »
  • PHP Manual
  • DOMDocument
  • Normalizes the document

DOMDocument::normalizeDocument

(PHP 5, PHP 7, PHP 8)

DOMDocument::normalizeDocument — Normalizes the document

Descrição

public DOMDocument::normalizeDocument(): void

This method acts as if you saved and then loaded the document, putting the document in a "normal" form.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Nenhum valor é retornado.

Veja Também

  • » The DOM Specification
  • DOMNode::normalize() - Normalizes the node

User Contributed Notes

lingasamy dot sakthivel at gmail dot com 16-Apr-2015 05:44
You can use this in this way.

$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML($content); // html content
$xpath = new DOMXPath($doc);
$doc->normalizeDocument();

Note that, you can use $doc->normalizeDocument(); at any point of time.


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

Descrição

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

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

Parâmetros

nodes

The nodes to prepend. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

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

User Contributed Notes

There are no user contributed notes for this page.


Register extended class used to create base node type

  • « DOMDocument::prepend
  • DOMDocument::relaxNGValidate »
  • PHP Manual
  • DOMDocument
  • Register extended class used to create base node type

DOMDocument::registerNodeClass

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

DOMDocument::registerNodeClass — Register extended class used to create base node type

Descrição

public DOMDocument::registerNodeClass(string $baseClass, ?string $extendedClass): bool

This method allows you to register your own extended DOM class to be used afterward by the PHP DOM extension.

This method is not part of the DOM standard.

Cuidado

The constructor of the objects of the registered node classes is not called.

Parâmetros

baseClass

The DOM class that you want to extend. You can find a list of these classes in the chapter introduction.

extendedClass

Your extended class name. If null is provided, any previously registered class extending baseClass will be removed.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Exemplos

Exemplo #1 Adding a new method to DOMElement to ease our code

<?php

class myElement extends DOMElement {
function appendElement($name) {
return $this->appendChild(new myElement($name));
}
}

class myDocument extends DOMDocument {
function setRoot($name) {
return $this->appendChild(new myElement($name));
}
}

$doc = new myDocument();
$doc->registerNodeClass('DOMElement', 'myElement');

// From now on, adding an element to another costs only one method call !
$root = $doc->setRoot('root');
$child = $root->appendElement('child');
$child->setAttribute('foo', 'bar');

echo $doc->saveXML();

?>

O exemplo acima produzirá:

<?xml version="1.0"?>
<root><child foo="bar"/></root>

Exemplo #2 Retrieving elements as custom class

<?php
class myElement extends DOMElement {
public function __toString() {
return $this->nodeValue;
}
}

$doc = new DOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");
$doc->registerNodeClass("DOMElement", "myElement");

$element = $doc->getElementsByTagName("child")->item(0);
var_dump(get_class($element));

// And take advantage of the __toString method..
echo $element;
?>

O exemplo acima produzirá:

string(9) "myElement"
text in child

Exemplo #3 Retrieving owner document

When instantiating a custom DOMDocument the ownerDocument property will refer to the instantiated class. However, if all references to that class are removed, it will be destroyed and new DOMDocument will be created instead. For that reason you might use DOMDocument::registerNodeClass() with DOMDocument

<?php
class MyDOMDocument extends DOMDocument {
}

class MyOtherDOMDocument extends DOMDocument {
}

// Create MyDOMDocument with some XML
$doc = new MyDOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");

$child = $doc->getElementsByTagName("child")->item(0);

// The current owner of the node is MyDOMDocument
var_dump(get_class($child->ownerDocument));
// MyDOMDocument is destroyed
unset($doc);
// And new DOMDocument instance is created
var_dump(get_class($child->ownerDocument));

// Import a node from MyDOMDocument
$newdoc = new MyOtherDOMDocument;
$child = $newdoc->importNode($child);

// Register custom DOMDocument
$newdoc->registerNodeClass("DOMDocument", "MyOtherDOMDocument");

var_dump(get_class($child->ownerDocument));
unset($doc);
// New MyOtherDOMDocument is created
var_dump(get_class($child->ownerDocument));
?>

O exemplo acima produzirá:

string(13) "MyDOMDocument"
string(11) "DOMDocument"
string(18) "MyOtherDOMDocument"
string(18) "MyOtherDOMDocument"

Exemplo #4 Custom objects are transient

Cuidado

Objects of the registered node classes are transient, i.e. they are destroyed when they are no longer referenced from PHP code, and recreated when being retrieved again. That implies that custom property values will be lost after recreation.

<?php
class MyDOMElement extends DOMElement
{
public $myProp = 'default value';
}

$doc = new DOMDocument();
$doc->registerNodeClass('DOMElement', 'MyDOMElement');

$node = $doc->createElement('a');
$node->myProp = 'modified value';
$doc->appendChild($node);

echo $doc->childNodes[0]->myProp, PHP_EOL;
unset($node);
echo $doc->childNodes[0]->myProp, PHP_EOL;
?>

O exemplo acima produzirá:

modified value
default value

User Contributed Notes

crh3675 at gmail dot com 25-Sep-2009 08:23
Creating innerHTML and outerHTML

<?php

class DOMHTMLElement extends DOMElement
{
    function __construct() { parent::__construct();}

    public function innerHTML()
    {
        $doc = new DOMDocument();
      foreach ($this->childNodes as $child){
          $doc->appendChild($doc->importNode($child, true));
        }
        $content = $doc->saveHTML();
        return $content;
    }

    public function outerHTML()
    {
        $doc = new DOMDocument();
        $doc->appendChild($doc->importNode($this, true));
        $content = $doc->saveHTML();
        return $content;
    }
}

$dom = DOMDocument::loadHTMLFile($file);
$dom->registerNodeClass('DOMElement','DOMHTMLElement');

if($dom)
{
    $xpath = new DOMXpath($dom);
    $regions = $xpath->query("//*[contains(@class, 'editable')]");
    $content = '';

    foreach($regions as $region){
        $content .= $region->outerHTML();
    }

    return $content;

}else{
    throw new Exception('Cannot parse HTML.  Please verify the syntax is correct.');
}
?>
arnold at adaniels dot nl 22-Jul-2009 03:10
Note than save and saveXML are not affected by __toString().


Performs relaxNG validation on the document

  • « DOMDocument::registerNodeClass
  • DOMDocument::relaxNGValidateSource »
  • PHP Manual
  • DOMDocument
  • Performs relaxNG validation on the document

DOMDocument::relaxNGValidate

(PHP 5, PHP 7, PHP 8)

DOMDocument::relaxNGValidate — Performs relaxNG validation on the document

Descrição

public DOMDocument::relaxNGValidate(string $filename): bool

Performs » relaxNG validation on the document based on the given RNG schema.

Parâmetros

filename

The RNG file.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

scarywound at gmail dot com 17-Oct-2012 11:39
Keep in mind that this method can't handle schemas in compact syntax!


Performs relaxNG validation on the document

  • « DOMDocument::relaxNGValidate
  • DOMDocument::replaceChildren »
  • PHP Manual
  • DOMDocument
  • Performs relaxNG validation on the document

DOMDocument::relaxNGValidateSource

(PHP 5, PHP 7, PHP 8)

DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document

Descrição

public DOMDocument::relaxNGValidateSource(string $source): bool

Performs » relaxNG validation on the document based on the given RNG source.

Parâmetros

source

A string containing the RNG schema.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

There are no user contributed notes for this page.


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

Descrição

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

Replaces the children in the document with new nodes.

Parâmetros

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

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

User Contributed Notes

There are no user contributed notes for this page.


Dumps the internal XML tree back into a file

  • « DOMDocument::replaceChildren
  • DOMDocument::saveHTML »
  • PHP Manual
  • DOMDocument
  • Dumps the internal XML tree back into a file

DOMDocument::save

(PHP 5, PHP 7, PHP 8)

DOMDocument::save — Dumps the internal XML tree back into a file

Descrição

public DOMDocument::save(string $filename, int $options = 0): int|false

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parâmetros

filename

The path to the saved XML document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

Valor Retornado

Returns the number of bytes written or false if an error occurred.

Exemplos

Exemplo #1 Saving a DOM tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->save("/tmp/test.xml") . ' bytes'; // Wrote: 72 bytes

?>

Veja Também

  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string
  • DOMDocument::load() - Load XML from a file
  • DOMDocument::loadXML() - Load XML from a string

User Contributed Notes

dubois-holvoet dot patrick at neuf dot fr 25-Feb-2016 08:13
I just intend to bring my little contribution to the use of DOMDocument::save() function along with PHP serialize() function.

Sometimes you could have to serialize a PHP object before you put it into a XML structure (or other..). And then I suppose you could have to save this XML structure in a file. Of course, you will further need to read this file and unserialize it before to use its content.

The problem appears when there are some properties described as Protected in the object to be serialized.

As it’s written in the PHP documentation, serialize function add for those protected properties an asterisk before the name of the property along with a NULL character on each side of the asterisk.
In this case, the DOMDocument::save function will stop the save operation just before the first NULL character met in the string to be saved, because PHP consider it as a potential risk.
So, after that, the unserialize operation of the file become impossible.

To solve that, here is a first solution to apply :

For the serialize , before the DOMDocument::save() ::
$data_serial = explode("\x00\x2A\x00", serialize($object));  //take off the 'NULL * NULL' string
$data_serial = implode("\x5C\x30\x2A\x5C\x30", $data_serial);    //and replace with '\0*\0' string

Before the unserialize :
$data_serial = explode("\x5C\x30\x2A\x5C\x30", $serialized_object);    // take off the '\0*\0' string
$serial_object = implode("\x00\x2A\x00", $data_serial);      // and replace with 'NULL * NULL' string as included by the previous serialize

And a second solution :

For the serialize, before the DOMDocument::save() :
$serialized_object = addslashes(serialize($object)) ;

Before re-using the object in your application :
$object = unserialize(stripslashes($serialized_object)) ;

Hope this will help some.
ludvig at ergopedia dot no 31-Oct-2014 10:21
When creating a DOMDocument from scratch and saving it, the encoding will be utf-8, although it's declared as iso-8859-1.

When loading an XML-file declared and saved as iso-8859-1, php will keep the correct encoding when it's saved after changes are made.

Php converts files declared as iso-8859-1 to utf-8 internally. To add text containing special characters, the text must be encoded as utf-8. When the document is saved, special characters are converted to iso-8859-1.

To save an xml created from scratch, use fopen/fwrite and utf8_decode:

   $doc = new DOMDocument('1.0', 'iso-8859-1');

//Add som nodes and text with apropriate methods

   $f = fopen('xmlfile.xml', 'w+');
   fwrite($f, utf8_decode($doc->saveXML()));
   fclose($f);
john at johnreid dot it 06-Aug-2013 09:42
I had been hitting my head against the wall when I couldn't get an edited XML file to save due to file permissions, even though I knew that it was OK.

Eventually I realised that for some odd reason, when I went to save the XML file, it would try to write the file to the root directory.

As such, use realpath() to keep the complete system path to the XML file when you load it:

<?php
$myfile = 'myxml.xml';
$myfile = realpath($myfile);
$doc = new DOMDocument('1.0');
$doc->load($myfile);

// Let's just add a couple of elements for good measure
$root = $doc->documentElement;

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is a title');
$text = $title->appendChild($text);

$doc->save($myfile);
?>
ss at littlerain dot com 01-Feb-2009 12:05
In addition to:
DOMDocument->formatOutput = true
DOMDocument->preserveWhiteSpace = false

...you also have to ensure you don't add text nodes as siblings of element nodes, or formatOutput won't work.
chenel324 at gmail dot com 19-Oct-2008 06:38
It took me forever to discover that
DOMDocument->formatOutput = true
will only have an effect on documents that are loaded from disk if one also sets
DOMDocument->preserveWhiteSpace = false ....

Hope this saves somebody a headache.
siegparr at NOSPAM dot web dot de 07-Jul-2006 08:00
The XML parser converts the text of an XML document into UTF-8, even if you have set the character encoding of the XML, for example as a second parameter of the DOMDocument constructor. After parsing the XML with the load() command all its texts have been converted to UTF-8.

In case you append text nodes with special characters (e. g. Umlaut) to your XML document you should therefore use utf8_encode() with your text to convert it into UTF-8 before you append the text to the document. Otherwise you will get an error message like "output conversion failed due to conv error" at the save() command. See example below:

<?php
// Text to insert into XML below
$txt = "a text with special characters like 'ä', 'ß', 'Ü' etc.";

// Create Instance of DOMDocument
$dom =  new DOMDocument;
// Load XML file
// Was created before with DOMDocument('1.0', 'iso-8859-1')
$dom = $dom->load("file.xml");
// Find the parent node
$parent = $dom->documentElement;
// Create Instance of DomXPath
$xpath = new DomXPath($dom);
// new node will be inserted before this node
$next = $xpath->query("//parentnode/childnode");
// Create the new element
$new_elem = $dom->createElement('new_elem');
// Insert the new element
$parent->insertBefore($new_elem, $next->item(0));
// DOMXML = utf-8! (will be converted to iso-8859-1 only at 'save()')
// prevents error message "output conversion failed due to conv error" at 'save()'
$txt = utf8_encode($txt);
// Create new text node with utf-8 encoded string
$nodetext = $dom->createTextNode("$txt");
// Append text node to new element
$nodetext = $new_elem->appendChild($nodetext);
// save
$dom->save("file.xml");
?>

Hope this helps someone.

siegparr


Dumps the internal document into a string using HTML formatting

  • « DOMDocument::save
  • DOMDocument::saveHTMLFile »
  • PHP Manual
  • DOMDocument
  • Dumps the internal document into a string using HTML formatting

DOMDocument::saveHTML

(PHP 5, PHP 7, PHP 8)

DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting

Descrição

public DOMDocument::saveHTML(?DOMNode $node = null): string|false

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parâmetros

node

Optional parameter to output a subset of the document.

Valor Retornado

Returns the HTML, or false if an error occurred.

Exemplos

Exemplo #1 Saving a HTML tree into a string

<?php

$doc = new DOMDocument('1.0');

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo $doc->saveHTML();

?>

Veja Também

  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting
  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::loadHTMLFile() - Load HTML from a file

User Contributed Notes

jeboy 28-Sep-2017 02:57
LIBXML_HTML_NOIMPLIED doesn't work on PHP 7.1.9 with libxml2-2.7.8
sasha @ goldnet dot ca 27-Jul-2017 04:21
When saving HTML fragment initiated with LIBXML_HTML_NOIMPLIED option, it will end up being "broken" as libxml requires root element. libxml will attempt to fix the fragment by adding closing tag at the end of string based on the first opened tag it encounters in the fragment.

For an example:

<h1>Foo</h1><p>bar</p>

will end up as:

<h1>Foo<p>bar</p></h1>

Easiest workaround is adding root tag yourself and stripping it later:

$html->loadHTML('<html>' . $content .'</html>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$content = str_replace(array('<html>','</html>') , '' , $html->saveHTML());
contact at cathexis dot de 31-Aug-2016 10:41
If you load HTML from a string ensure the charset is set.

<?php
...
$html_src = '<html><head><meta content="text/html; CHARSET=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>


Dumps the internal document into a file using HTML formatting

  • « DOMDocument::saveHTML
  • DOMDocument::saveXML »
  • PHP Manual
  • DOMDocument
  • Dumps the internal document into a file using HTML formatting

DOMDocument::saveHTMLFile

(PHP 5, PHP 7, PHP 8)

DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting

Descrição

public DOMDocument::saveHTMLFile(string $filename): int|false

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parâmetros

filename

The path to the saved HTML document.

Valor Retornado

Returns the number of bytes written or false if an error occurred.

Exemplos

Exemplo #1 Saving a HTML tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->saveHTMLFile("/tmp/test.html") . ' bytes'; // Wrote: 129 bytes

?>

Veja Também

  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::loadHTMLFile() - Load HTML from a file

User Contributed Notes

RiKdnUA at mail dot ru 27-Jul-2013 04:15
saveHTMLFile() always saves the file in UTF-8. Even if the DOMDocument->encoding explicitly prescribe different from UTF-8 encoding. All "non-Latin" characters will be converted to HTML-entities. Tested in PHP 5.2.9-2 and PHP 5.2.17. Example:

<?php
$document=new domDocument('1.0', 'WINDOWS-1251');
$document->loadHTML('<html><head><title>Russian language</title></head><body>??????? ????</body></html>');
$document->formatOutput=true;
$document->encoding='WINDOWS-1251';
echo "???????? ????. Recorded bytes: ".$document->saveHTMLFile('html.html');
?>

Method recorded file in UTF-8 encoding. The contents of the file html.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; CHARSET=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.


Dumps the internal XML tree back into a string

  • « DOMDocument::saveHTMLFile
  • DOMDocument::schemaValidate »
  • PHP Manual
  • DOMDocument
  • Dumps the internal XML tree back into a string

DOMDocument::saveXML

(PHP 5, PHP 7, PHP 8)

DOMDocument::saveXML — Dumps the internal XML tree back into a string

Descrição

public DOMDocument::saveXML(?DOMNode $node = null, int $options = 0): string|false

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parâmetros

node

Use this parameter to output only a specific node without XML declaration rather than the entire document.

options

Additional Options. The LIBXML_NOEMPTYTAG and LIBXML_NOXMLDECL options are supported. Prior to PHP 8.3.0, only the LIBXML_NOEMPTYTAG option is supported.

Valor Retornado

Returns the XML, or false if an error occurred.

Erros

DOM_WRONG_DOCUMENT_ERR

Raised if node is from another document.

Changelog

Versão | Descrição
8.3.0 | LIBXML_NOXMLDECL is now supported.

Exemplos

Exemplo #1 Saving a DOM tree into a string

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo "Saving all the document:\n";
echo $doc->saveXML() . "\n";

echo "Saving only the title part:\n";
echo $doc->saveXML($title);

?>

O exemplo acima produzirá:

Saving all the document:
<?xml version="1.0"?>
<book>
  <title>This is the title</title>
</book>

Saving only the title part:
<title>This is the title</title>

Veja Também

  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::load() - Load XML from a file
  • DOMDocument::loadXML() - Load XML from a string

User Contributed Notes

liumenglei0211 at 163 dot com 17-Jan-2019 07:50
How to display two tags when the node content is empty.

<?php
$dom     = new \DOMDocument('1.0');
$document = $dom->createElement('document');
$document = $dom->appendChild($document);
$head = $dom->createElement('title','this is title');
$content = $dom->createElement('content','');
$document->appendChild($head);
$document->appendChild($content);
echo $dom->saveXML();
?>

In XML, they are considered exactly the same thing, and any parser should recognize both forms.However, you can write it this way if you still need it

<?php
echo $dom->saveXML($dom->documentElement, LIBXML_NOEMPTYTAG);
?>

Example 1:

<?xml version="1.0"?>
<document>
    <title>this is title</title>
    <content/>
</document>

Example 2:
<document>
    <title>this is test</title>
    <content></content>
</document>
Frank 29-Mar-2017 06:40
I would like to create a DOM document Xml Guestbook ..can somebody help to me?

Username, Comments in form read/write the task.

Thanks if somebody save me :)
Alexander Fedulin 05-Mar-2014 08:29
As @fbernodi said earlier, there is a problem with saveXML of DOMNode when you have a number of defined namespaces. The simple solution for this:

<code>
   // $node is some node of some other document
   $temp_document = new DOMDocument('1.0', 'utf-8');
   $temp_document->appendChild($temp_document->importNode($node, true));
   echo $temp_document->saveXML();
</code>
fbernoldi at gmail dot com 01-Aug-2013 08:24
Hello,

I had an unexpected behavior in some parsing code, because of this saveXML method that is saving the tags without namespace specification. If you try to load into a DOMDocument a string saved from a DOMNode that has a referenced namespace but it the original document it was not defined in that element, you get a not well formed xml. In the example you can see the issue and a possible solution, the other solution may be add to the ChildElement node the namespace reference (<testNS:ChildElement testNS="http://example.org">), but in my scenario it was not needed.

<?php

//Test XML
$test_xml =
"<?xml version=\"1.0\"?>
<testNS:RootNode xmlns:testNS=\"http://example.org\">
    <testNS:ChildElement>
        <testNS:AnotherChildElement>I'm a Another Child node.</testNS:AnotherChildElement>
    </testNS:ChildElement>
</testNS:RootNode>";

//We define our Test DOMDocument
$domDoc = new DOMDocument("1.0");
$domDoc->loadXML($test_xml);

//We use xpath to search ChildElement:
$domXPath = new DOMXPath($domDoc);
$domXPath->registerNamespace("testNS", "http://example.org");
$DOMNodeList_ChildElement = $domXPath->query("//testNS:RootNode/testNS:ChildElement");
$ChildElement = $DOMNodeList_ChildElement->item(0);

echo "Not usefull xml to load in another document:\n\n";
echo $domDoc->saveXML($ChildElement);

/* Output here:
 *
 * Not usefull xml to load in another document:
 *
 *  <testNS:ChildElement>
 *        <testNS:AnotherChildElement>I'm a Another Child node.</testNS:AnotherChildElement>
 *    </testNS:ChildElement>
 *
 */

/**
 * Function to help us clone the element to another document.
 * @param DOMElement $node The node to clone.
 * @param DOMDocument $doc The document where we are going to reference the elements.
 * @return DOMElement The new cloned element without namespace.
 */
function cloneNode($node, $doc) {
    //Create new element with the original localName (w/o namespace)
    $nd = $doc->createElement($node->localName);

    //Clone attributes
    foreach($node->attributes as $value)
        $nd->setAttribute($value->localName, $value->value);

    //No more childs then we finish.
    if (!$node->childNodes)
        return $nd;
    //We have childs, add them
    foreach($node->childNodes as $child) {
        if ($child->nodeName=="#text") //Only needed to clone text nodes, i.e. text comments, spaces, tabs. etc.
            $nd->appendChild($doc->createTextNode($child->nodeValue));
        else
            $nd->appendChild(cloneNode($child, $doc)); //recursion to clone all children.
    }
    return $nd;
}

//New Document to reference the new node without namespaces
$domDoc2 = new DOMDocument("1.0");

//We clone this node taking out the namespace
$new_node = cloneNode($ChildElement, $domDoc2);

echo "\n\nWe can load this into a DOMDocument without problems:\n\n";
echo $domDoc2->saveXML($new_node);

/*
 * We can load this into a DOMDocument without problems:
 *
 *    <ChildElement>
 *        <AnotherChildElement>I'm a Another Child node.</AnotherChildElement>
 *    </ChildElement>
 */

?>
xianrenb at gmail dot com 15-Jul-2012 10:54
If you want to save xhtml (in a string), you may try the following method:
<?php
    $doc = new DOMDocument('1.0');

    // ...

    $xhtml = (string) $doc->saveXML($doc->doctype);
    $xhtml .= "\n";
    $xhtml .= (string) $doc->saveXML($doc->documentElement);
?>
samstah at gmail dot com 19-Mar-2010 03:56
We discovered using DOMDocument::saveHTML() that it converts to HTML 4.01 compatible markup; rather than XHTML. The simple answer is to use saveXML() instead, although this adds the XML declaration to the top.

To qjerry.com at gmail.com, thanks for the pointer below - but I think that the simplest way seems to be using:
<?php $domDocument->saveXML($domDocument->documentElement); ?>

Of course, if you're dealing with XHTML, this will strip any <!DOCTYPE> declarations in the document too.
qjerry.com at gmail.com 04-May-2009 04:24
The simpliest (and probably the fastest) way to strip an XML declaration (<?xml version="1.0" ... ?>) out of output document, is to output child nodes of DOMDocument separately:

<?php

$document = new DOMDocument();
$document->load('/some/file.xml');

// this will also output doctype and comments at top level
foreach($document->childNodes as $node)
    $result .= $document->saveXML($node)."\n";

echo $result;

?>

This might be userful when dealing with browser compatibility issues, for example, well known problem with valid XHTML in IE6.
vikramvmalhotra at hotmail dot com 27-Jan-2009 03:49
if you are storing multi-byte characters in XML, then saving the XML using saveXML() will create problems. It will spit out the characters converted in encoded format.

<?php
$str = domdoc->saveXML(); // gives "&x#1245;" some encoded data
?>

Instead do the following

<?php
$str = domdoc->saveXML(domdoc->documentElement); // gives "??????" correct multi-byte data
?>
shinsh at shinmugen dot net 23-May-2008 07:57
Be careful, this function has been changed in 5.2.6 version. Adding a required parameter which is not that required wasn't the most intelligent idea ever, especially for a function which is often used.

To fix your programs if you have an error, fill the first parameter like this:

$dom->saveXML($dom->documentElement);

Why didn't the devs simply implement this as optional parameter, fixing the default parameter as documentElement?
Kriogen 26-Dec-2007 12:57
Create before test.xml with:
<?xml version="1.0" encoding="utf-8"?>
<Photos>
</Photos>

and past after in your php-file:

<?php
$simp = simplexml_load_file('test.xml');
$node = $simp->addChild('home');
$node->addChild('mychild', 'insert text');
$s = simplexml_import_dom($simp);
$s->saveXML('test.xml');
?>

This code creating a child-nod in the root.
Owner http://www.mensfashion.ru
JITR 02-Aug-2007 05:10
Comment to `devin at SPAMISBAD dot tritarget dot com''s post:

Thanks for pointing out the pitfalls of `formatOutput' vs. `load*()'. This has certainly saved me from some possible surprises.

I think the seemingly strange behaviour can be explained. Warning: The following stuff is mostly based on deductions and experiments. Much less on studying the sources and specs (I'm not sure some of these would provide answer anyway, at least not easily).

As you point out, `preserveWhiteSpace' must be set before loading the DOM from the source string (I'm working with `loadXML()' but I believe the situation should be the same with `load()' you used). This looks logical, as this property seems to control the parsing and DOM creation process during which text nodes containing the whitespace are either included or dropped. This can be proven by dumping the DOM structure and comparing the results based on the value of `preserveWhiteSpace'. With `preserveWhiteSpace' set to `FALSE', no text nodes containing whitespace will be present in the returned DOM. When this property is `TRUE', these nodes will be present.

Note: When speaking about the whitespace in the previous paragraph, we're most certainly speaking about so called `whitespace in element content' or `element content whitespace', if I'm not mistaken. See also my comment in the notes of `DOMText->isWhitespaceInElementContent()' method.

As for the mysterious effect on the output of `saveXLM()', I think the explanation lies in the presence or absence of the above mentioned whitespace text nodes. This was also proven by experiments: After adding such a node into a DOM which contained none (the DOM was created using `loadXML()' with `preserveWhiteSpace' set to `FALSE'), the output formatting got affected in a such a way, the formatting got lost for the rest of the document after the added node. I think the presence of whitespace text nodes forces such rendering, that the content of these nodes is used to separate adjoining nodes thus disabling default formatting. Only when there are no such text nodes present, the ouput formatting takes effect (provided the `formatOutput' is set to `TRUE', of course).

Well, the thing I don't really understand is how you did get an output of a signle line with `formatOutput' set to `TRUE'. This has happened to me when no whitespace text nodes were present (ie. when loading the XML with `preserveWhiteSpace' set to `FALSE') *and* with `formatOutput' set to *`FALSE'* (with the opposite value of `formatOutput', the formatting should do it's work and you should not end up with just one line). But I haven't seen your source. Perhaps you had whitespace nodes containing no new-lines in your DOM?

As for the CAUTION about root element, I didn't see any problems with empty root element neither in shortened nor full form. What did you have in mind, when you said it `WORKS' or `DOES NOT WORK'?
Sander 25-Apr-2007 05:35
Note that for large DOM trees (tens of thousands of elements nested at least a few levels deep), setting formatOutput to true drives up memory usage to rather insane levels when you call saveXML(). (Tested with PHP 5.2.1) Pretty output is not worth that cost.
nevyn at NOSPAM dot email dot PLEASE dot it 27-Dec-2006 01:41
A little function to get the full xml contents of a Xml node.

function innerXml($node)
{
    $out = $node->ownerDocument->saveXML($node);
    $re = "{^<(\\w*)(?:\\s*\\w+=(?:\"[^\"]*\"|\'[^\']*\'))*\\s*>(.*)</\\1>$}";
    preg_match($re, $out, $mat);
    return $mat[2];
}
devin at SPAMISBAD dot tritarget dot com 14-Aug-2006 10:52
It took some searching to figure this one out. I didn't see much in the way of explaining this glitch in the manual thus far. (For PHP5 I believe)

formatOutput = true; appears to fail when the origin of the DOM came from a file via load(). EX:

<?php
    $dom = new DOMDocument();
    $dom->load ("test.xml");
    $dom->formatOutput = true;

    $new_tag = $dom->createElement ('testNode');
    $new_tag->appendChild (
        $dom->createElement ('test', 'this is a test'));
    $dom->documentElement->appendChild ($new_tag);

    printf ("<pre>%s</pre>", htmlentities ($dom->saveXML()));
?>

Will not indent the output and will display the modified nodes all in one long line. Makes for editing a config.xml a bit difficult when saving to a file.

By adding the preserveWhiteSpace = false; BEFORE the load() the formatOutput works as expected. EX:

<?php
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->load ("test.xml");
    $dom->formatOutput = true;

    $new_tag = $dom->createElement ('testNode');
    $new_tag->appendChild (
        $dom->createElement ('test', 'this is a test'));
    $dom->documentElement->appendChild ($new_tag);

    printf ("<pre>%s</pre>", htmlentities ($dom->saveXML()));
?>

CAUTION: If your loaded xml file (test.xml) has an empty root node that is not shortened or has no children this will NOT work.

Example:

DOES NOT WORK:
<?xml version="1.0"?>
<root>
</root>

WORKS:
<?xml version="1.0"?>
<root/>

WORKS:
<?xml version="1.0"?>
<root>
  <!-- comment -->
</root>

WORKS:
<?xml version="1.0"?>
<root>
  <child/>
</root>
26-Mar-2006 04:20
I used the function posted by "joe" but the following works to me for get the innerXML
<?php
$itemLeido = $XMLRespuesta->getElementsByTagName("articulos");
foreach($itemLeido as $node) {
    echo($node->ownerDocument->saveXML($node));
}
?>
mswiercz at mwerk dot com 10-Sep-2004 03:43
Quick tip to minimize memory when generating documents with DOM.

Rather than using
   $xmlStr = DOMDocument->saveXML();
   echo $xmlStr;

to dump a large DOM to the output buffer, use a PHP output stream, as in

   DOMDocument->save('php://output');

A lot of memory will be saved when generating large DOMs.
padys at tlen dot pl 05-Aug-2004 07:36
When you save whole document:
DOMDocument->saveXML() produces string in encoding defined in property DOMDocument->encoding.

When you save only one node:
DOMDocument->saveXML(DOMNode) produces always string in UTF-8.


Validates a document based on a schema. Only XML Schema 1.0 is supported.

  • « DOMDocument::saveXML
  • DOMDocument::schemaValidateSource »
  • PHP Manual
  • DOMDocument
  • Validates a document based on a schema. Only XML Schema 1.0 is supported.

DOMDocument::schemaValidate

(PHP 5, PHP 7, PHP 8)

DOMDocument::schemaValidate — Validates a document based on a schema. Only XML Schema 1.0 is supported.

Descrição

public DOMDocument::schemaValidate(string $filename, int $flags = 0): bool

Validates a document based on the given schema file.

Parâmetros

filename

The path to the schema.

flags

A bitmask of Libxml schema validation flags. Currently the only supported value is LIBXML_SCHEMA_CREATE. Available since Libxml 2.6.14.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

mmamsch at googlemail dot com 16-Sep-2015 10:01
A note for people trying to validate complex schemas with PHP.  It seems that libxml will not automatically try to import referenced schemas, but simply skip the validation if the schemas were not explicitly imported.

In our example we tried to validate an XML file against a schema with the namespace "xttp://automotive-his.de/200706/rif" that contains a reference to the namespace "xttp://automotive-his.de/200706/rif-xhtml":

  <xsd:complexType name="XHTML-CONTENT">
    <xsd:sequence>
      <xsd:any namespace="xttp://automotive-his.de/200706/rif-xhtml"/>
    </xsd:sequence>
  </xsd:complexType>

which basically says that an xhtml-content element can contain any element from the rif-xhtml namespace.

However since libxml does not know where to find the schema file, it will stop the validation if the elements from the referenced namespace, passing also document with invalid xhtml content as valid.

The solution was to create a combined schema, which contains import statements for all files matching the referenced schemas:

<xsd:schema xmlns:xs="xttp://www.w3.org/2001/XMLSchema">
<xs:import namespace="xttp://automotive-his.de/200706/rif-xhtml" schemaLocation="rif-xhtml.xsd"/>
<xs:import namespace="xttp://automotive-his.de/200706/rif" schemaLocation="rif.xsd"/>
<xs:import namespace="xttp://www.w3.org/XML/1998/namespace" schemaLocation="../xml.xsd"/>
</xsd:schema>

Note that the schemaLocation tells the validator, where to find the files for the corresponding namespaces. When validating the XML document against this combined schema, libxml validated correctly the content inside the XHTML-Content.

Hope this helps someone out there.
wkoehler at ce-gmbh dot com 11-Jan-2011 02:37
In older versions of PHP5 this function might cause error messages when dealing with namespaces. I had problems with PHP 5.2.14 which comes with libXML V2.6.16. After switching to PHP 5.3.5 with libXML V2.7.7 I no longer had problems. Took me only about 30 hrs to figure that one out.
NetPanther 27-Mar-2009 01:42
Initial situation:
- Debian Lenny
- Apache 2 with PHP 5.2.6
- libxml 2.6.32

Problem: While trying to validate a manually created (!) DOMDocument against an existing XML Schema, I ran into a warning like the one below. Validation fails, even though the document IS valid and the command line tool xmllint confirms this (even with libxml 2.6.32, so this must be a problem with DOM). The validation works fine with libxml 2.7.3.

Warning: DOMDocument::schemaValidate() [domdocument.schemavalidate]: Element 'YourRootElementName': No matching global declaration available for the validation root. in /var/www/YourFile.php on line X

Solution: As libxml 2.7.3 is not provided for Debian Lenny yet and this problem seems to be caused by DOM (s.o.), I currently use the following workaround on my machines. DOM obviously has some namespace problems with documents, that have been created manually (i.e. they were not loaded from a file).

So my workaround is saving the DOMDocument temporarily, re-loading it and then validating the temporary DOMDocument. Strangely enough the validation of the same document (= same content) now works. Sure, creating a temporary file is not a nice solution, but unless this bug is fixed, this workaround should do just fine.

<?php

// Works with libxml 2.7.3 and higher.
public function isValid()
{
  return $this->dom->schemaValidate('schema.xsd');
}

// Workaround for prior libxml versions, e.g. 2.6.32.
public function isValid()
{
  // Create temporary file and save manually created DOMDocument.
  $tempFile = time() . '-' . rand() . '-document.tmp';
  $this->dom->save($tempFile);

  // Create temporary DOMDocument and re-load content from file.
  $tempDom = new DOMDocument();
  $tempDom->load($tempFile);

  // Delete temporary file.
  if (is_file($tempFile))
  {
    unlink($tempFile);
  }

  // Validate temporary DOMDocument.
  return $tempDom->schemaValidate('schema.xsd');
}

?>
poletto at jeuxvideo dot com 13-Feb-2008 12:32
I had a tricky issue using this method, i thought it was bug but i realized i misundestood something about namespaces.
When you want to use a schema to describe an xml document, you basically put the default namespace to a personnal namespace (and you refer to this namespace in the targetNamespace attribute of your schema).

<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://my.uri.net">
  <elt>
    <x>blabla</x>
    <y>blabla</y>
  </elt>
</root>

That xmlns attribute specifies a "default namespace" and means that the root element and its children are in this namespace.
What i misunderstood is that, there's no way with the DOM api to specify a "default namespace" for each children of the root element.
Thus you may need to use createElementNS() and createAttributeNS() methods for each created element or attribute in the document specifying the URI of your namespace each time ("http://my.uri.net").

This only applies if you want to validate a document built with the API, not with a document loaded from an xml file or stream.
justin at redwiredesign dot com 08-Nov-2006 03:32
In his previous comment, Mike A wrote about validating documents using an XSD. However, you can validate without one. In my case, I needed to ensure that the content entered was just valid XML or not, and I couldn't find an XSD to support that. So I wrote this:

public static function validate($xml)
{
    libxml_use_internal_errors(true);

    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->loadXML($xml);

    $errors = libxml_get_errors();
    if (empty($errors))
    {
        return true;
    }

    $error = $errors[0];
    if ($error->level < 3)
    {
        return true;
    }

    $lines = explode("\r", $xml);
    $line = $lines[($error->line)-1];

    $message = $error->message.' at line '.$error->line.':<br />'.htmlentities($line);

    return $message;
}

The catch here is that the function only checks for the first error is LIBXML_ERR_FATAL, which would break XSL/XML compilation.

In my experience, the errors are returned by libxml_get_errors in descending severity, so this may be an OK thing to do.
Mike A. 17-Feb-2006 12:03
For more detailed feedback from DOMDocument::schemaValidate, disable libxml errors and fetch error information yourself.  See http://php.net/manual/en/ref.libxml.php for more info.

example.xml
<?xml version="1.0"?>
<example>
    <child_string>This is an example.</child_string>
    <child_integer>Error condition.</child_integer>
</example>

example.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
    <xs:element name="example">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="child_string" type="xs:string"/>
                <xs:element name="child_integer" type="xs:integer"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

<?php

function libxml_display_error($error)
{
    $return = "<br/>\n";
    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "<b>Warning $error->code</b>: ";
            break;
        case LIBXML_ERR_ERROR:
            $return .= "<b>Error $error->code</b>: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "<b>Fatal Error $error->code</b>: ";
            break;
    }
    $return .= trim($error->message);
    if ($error->file) {
        $return .=    " in <b>$error->file</b>";
    }
    $return .= " on line <b>$error->line</b>\n";

    return $return;
}

function libxml_display_errors() {
    $errors = libxml_get_errors();
    foreach ($errors as $error) {
        print libxml_display_error($error);
    }
    libxml_clear_errors();
}

// Enable user error handling
libxml_use_internal_errors(true);

$xml = new DOMDocument();
$xml->load('example.xml');

if (!$xml->schemaValidate('example.xsd')) {
    print '<b>DOMDocument::schemaValidate() Generated Errors!</b>';
    libxml_display_errors();
}

?>

Old error message:
Warning: DOMDocument::schemaValidate() [function.schemaValidate]: Element 'child_integer': 'Error condition.' is not a valid value of the atomic type 'xs:integer'. in example.php on line 40

New error message:
DOMDocument::schemaValidate() Generated Errors!
Error 1824: Element 'child_integer': 'Error condition.' is not a valid value of the atomic type 'xs:integer'. in example.xml on line 4


Validates a document based on a schema

  • « DOMDocument::schemaValidate
  • DOMDocument::validate »
  • PHP Manual
  • DOMDocument
  • Validates a document based on a schema

DOMDocument::schemaValidateSource

(PHP 5, PHP 7, PHP 8)

DOMDocument::schemaValidateSource — Validates a document based on a schema

Descrição

public DOMDocument::schemaValidateSource(string $source, int $flags = 0): bool

Validates a document based on a schema defined in the given string.

Parâmetros

source

A string containing the schema.

flags

A bitmask of Libxml schema validation flags. Currently the only supported value is LIBXML_SCHEMA_CREATE. Available since Libxml 2.6.14.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

There are no user contributed notes for this page.


Validates the document based on its DTD

  • « DOMDocument::schemaValidateSource
  • DOMDocument::xinclude »
  • PHP Manual
  • DOMDocument
  • Validates the document based on its DTD

DOMDocument::validate

(PHP 5, PHP 7, PHP 8)

DOMDocument::validate — Validates the document based on its DTD

Descrição

public DOMDocument::validate(): bool

Validates the document based on its DTD.

You can also use the validateOnParse property of DOMDocument to make a DTD validation.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha. If the document has no DTD attached, this method will return false.

Exemplos

Exemplo #1 Example of DTD validation

<?php
$dom = new DOMDocument;
$dom->load('book.xml');
if ($dom->validate()) {
echo "This document is valid!\n";
}
?>

You can also validate your XML file while loading it:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->load('book.xml');
?>

Veja Também

  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document

User Contributed Notes

cabral dot brc at gmail dot com 08-Sep-2010 12:46
I was trying to validate my SVG file just to get the IDs with getElementById(),

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text id="text_titulo" x="150" y="20" font-family="Arial" font-size="15px" style="font-weight:bold;">Title</text>
<text id="text_subtitulo" x="200" y="35" font-family="Arial" font-size="10px">Sub Title</text>
<g transform="translate(0,50) scale(0.1)">
  <a id="a_AC" ...... >
    <polygon id="polygon_AC" ....... />
  </a>
</g>
</svg>

but when calling $dom->load(), it was getting the errors "failed to open stream" and "Validation failed: no DTD found !I/O warning : failed to load external entity"
so I created my own validation wrapper (I just want to find the IDs with getElementById() )

<?php
  $docSVG = new DOMDocument();
  $docSVG->load(realpath($filepath));
  setAllId($docSVG);

function setAllId($DOMNode){
  if($DOMNode->hasChildNodes()){
    foreach ($DOMNode->childNodes as $DOMElement) {
      if($DOMElement->hasAttributes()){
        $id=$DOMElement->getAttribute("id");
        if($id){
          $DOMElement->setIdAttribute("id",$id);
        }
      }
      setAllId($DOMElement);
    }
  }
}
?>
a dot schaffhirt at sedna-soft dot de 17-Sep-2008 02:22
When validating documents with this method there are two issues I don't like about it. First, it creates a bunch of warnings, which one would not expect, as the plot of calling this method is preventing any warnings that could occur when erroneously relying on the document's validity. Second, it only returns a boolean with no chance of getting additional details about the reasons for rendering invalid.

That's the reason for me to use a little wrapper, which I post here in case anyone finds it useful.

Please note that it only works with PHP5 or later.

<?php
    class MyDOMDocument {
        private $_delegate;
        private $_validationErrors;

        public function __construct (DOMDocument $pDocument) {
            $this->_delegate = $pDocument;
            $this->_validationErrors = array();
        }

        public function __call ($pMethodName, $pArgs) {
            if ($pMethodName == "validate") {
                $eh = set_error_handler(array($this, "onValidateError"));
                $rv = $this->_delegate->validate();
                if ($eh) {
                    set_error_handler($eh);
                }
                return $rv;
            }
            else {
                return call_user_func_array(array($this->_delegate, $pMethodName), $pArgs);
            }
        }
        public function __get ($pMemberName) {
            if ($pMemberName == "errors") {
                return $this->_validationErrors;
            }
            else {
                return $this->_delegate->$pMemberName;
            }
        }
        public function __set ($pMemberName, $pValue) {
            $this->_delegate->$pMemberName = $pValue;
        }
        public function onValidateError ($pNo, $pString, $pFile = null, $pLine = null, $pContext = null) {
            $this->_validationErrors[] = preg_replace("/^.+: */", "", $pString);
        }
    }
?>

<?php
    // $doc is a DOMDocument object
    $myDoc = new MyDOMDocument($doc); // copy constructor

    // do anything with $myDoc that you would with $doc

    $isValid = $myDoc->validate(); // won't create warnings
    if (!$isValid) {
        print_r($myDoc->errors); // the array all warnings are collected in
    }
?>

Maybe you need to change the the part
preg_replace("/^.+: */", "", $pString)
to something different depending on your system's error reporting settings (HTML or plain text), whatsoever

Best Regards,

Anja
darren at viamedia dot co dot za 05-Aug-2008 07:19
If you are loading xml with the intention of validating it against an internal dtd and you have experienced issues with the validation it could be related to missing LIBXML constants.

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

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:
<?php
$dom = new DOMDocument;
// Resolve externals
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);
// OR
// Validate against DTD
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
$dom->validate();
?>


Substitutes XIncludes in a DOMDocument Object

  • « DOMDocument::validate
  • DOMDocumentFragment »
  • PHP Manual
  • DOMDocument
  • Substitutes XIncludes in a DOMDocument Object

DOMDocument::xinclude

(PHP 5, PHP 7, PHP 8)

DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object

Descrição

public DOMDocument::xinclude(int $options = 0): int|false

This method substitutes » XIncludes in a DOMDocument object.

Nota:

Due to libxml2 automatically resolving entities, this method will produce unexpected results if the included XML file have an attached DTD.

Parâmetros

options

Bit a bit OR das constantes de opções da libxml.

Valor Retornado

Returns the number of XIncludes in the document, -1 if some processing failed, or false if there were no substitutions.

Exemplos

Exemplo #1 DOMDocument::xinclude() example

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Books of the other guy..</title>
<para>
<xi:include href="book.xml">
<xi:fallback>
<error>xinclude: book.xml not found</error>
</xi:fallback>
</xi:include>
</para>
</chapter>
EOD;

$dom = new DOMDocument;

// let's have a nice output
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// load the XML string defined above
$dom->loadXML($xml);

// substitute xincludes
$dom->xinclude();

echo $dom->saveXML();

?>

O exemplo acima produzirá algo semelhante 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();

?>


The DOMDocumentFragment class

(PHP 5, PHP 7, PHP 8)

Sinopse da classe

class DOMDocumentFragment extends DOMNode implements DOMParentNode {
/* Propriedades */
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
/* Propriedades herdadas */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos */
public __construct()
public append(DOMNode|string ...$nodes): void
public appendXML(string $data): bool
public prepend(DOMNode|string ...$nodes): void
public replaceChildren(DOMNode|string ...$nodes): void
/* Métodos herdados */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriedades

childElementCount

The number of child elements.

firstElementChild

First child element or null.

lastElementChild

Last child element or null.

Changelog

Versão | Descrição
8.0.0 | The firstElementChild, lastElementChild, and childElementCount properties have been added.
8.0.0 | DOMDocumentFragment implements DOMParentNode now.

Índice

  • DOMDocumentFragment::append — Appends nodes after the last child node
  • DOMDocumentFragment::appendXML — Append raw XML data
  • 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

Descrição

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

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

Parâmetros

nodes

The nodes to append. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

<hello/>beautiful<world/>

Veja Também

  • DOMParentNode::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.


Append raw XML data

  • « DOMDocumentFragment::append
  • DOMDocumentFragment::__construct »
  • PHP Manual
  • DOMDocumentFragment
  • Append raw XML data

DOMDocumentFragment::appendXML

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

DOMDocumentFragment::appendXML — Append raw XML data

Descrição

public DOMDocumentFragment::appendXML(string $data): bool

Appends raw XML data to a DOMDocumentFragment.

This method is not part of the DOM standard. It was created as a simpler approach for appending an XML DocumentFragment in a DOMDocument.

If you want to stick to the standards, you will have to create a temporary DOMDocument with a dummy root and then loop through the child nodes of the root of your XML data to append them.

Parâmetros

data

XML to append.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Exemplos

Exemplo #1 Appending XML data to your document

<?php
$doc = new DOMDocument();
$doc->loadXML("<root/>");
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($f);
echo $doc->saveXML();
?>

O exemplo acima produzirá:

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

Descrição

public DOMDocumentFragment::__construct()

Parâmetros

Esta função não possui 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

Descrição

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

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

Parâmetros

nodes

The nodes to prepend. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

<hello/>beautiful<world/>

Veja Também

  • DOMParentNode::prepend() - Prepends nodes before the first child node
  • 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

Descrição

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

Replaces the children in the document fragment with new nodes.

Parâmetros

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

beautiful
<world/>

Veja Também

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

User Contributed Notes

There are no user contributed notes for this page.


The DOMDocumentType class

(PHP 5, PHP 7, PHP 8)

Introdução

Each DOMDocument has a doctype attribute whose value is either null or a DOMDocumentType object.

Sinopse da classe

class DOMDocumentType extends DOMNode {
/* Propriedades */
public readonly string $name;
public readonly DOMNamedNodeMap $entities;
public readonly DOMNamedNodeMap $notations;
public readonly string $publicId;
public readonly string $systemId;
public readonly ?string $internalSubset;
/* Propriedades herdadas */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos herdados */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriedades

publicId

The public identifier of the external subset.

systemId

The system identifier of the external subset. This may be an absolute URI or not.

name

The name of DTD; i.e., the name immediately following the DOCTYPE keyword.

entities

A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.

notations

A DOMNamedNodeMap containing the notations declared in the DTD.

internalSubset

The internal subset as a string, or null if there is none. This does not contain the delimiting square brackets.

User Contributed Notes

There are no user contributed notes for this page.


The DOMElement class

(PHP 5, PHP 7, PHP 8)

Sinopse da classe

class DOMElement extends DOMNode implements DOMParentNode, DOMChildNode {
/* Propriedades */
public readonly string $tagName;
public string $className;
public string $id;
public readonly mixed $schemaTypeInfo = null;
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
/* Propriedades herdadas */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos */
public __construct(string $qualifiedName, ?string $value = null, string $namespace = "")
public after(DOMNode|string ...$nodes): void
public append(DOMNode|string ...$nodes): void
public before(DOMNode|string ...$nodes): void
public getAttribute(string $qualifiedName): string
public getAttributeNames(): array
public getAttributeNode(string $qualifiedName): DOMAttr|DOMNameSpaceNode|false
public getAttributeNodeNS(?string $namespace, string $localName): DOMAttr|DOMNameSpaceNode|null
public getAttributeNS(?string $namespace, string $localName): string
public getElementsByTagName(string $qualifiedName): DOMNodeList
public getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList
public hasAttribute(string $qualifiedName): bool
public hasAttributeNS(?string $namespace, string $localName): bool
public insertAdjacentElement(string $where, DOMElement $element): ?DOMElement
public insertAdjacentText(string $where, string $data): void
public prepend(DOMNode|string ...$nodes): void
public remove(): void
public removeAttribute(string $qualifiedName): bool
public removeAttributeNode(DOMAttr $attr): DOMAttr|false
public removeAttributeNS(?string $namespace, string $localName): void
public replaceChildren(DOMNode|string ...$nodes): void
public replaceWith(DOMNode|string ...$nodes): void
public setAttribute(string $qualifiedName, string $value): DOMAttr|bool
public setAttributeNode(DOMAttr $attr): DOMAttr|null|false
public setAttributeNodeNS(DOMAttr $attr): DOMAttr|null|false
public setAttributeNS(?string $namespace, string $qualifiedName, string $value): void
public setIdAttribute(string $qualifiedName, bool $isId): void
public setIdAttributeNode(DOMAttr $attr, bool $isId): void
public setIdAttributeNS(string $namespace, string $qualifiedName, bool $isId): void
public toggleAttribute(string $qualifiedName, ?bool $force = null): bool
/* Métodos herdados */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriedades

childElementCount

The number of child elements.

firstElementChild

First child element or null.

lastElementChild

Last child element or null.

nextElementSibling

The next sibling element or null.

previousElementSibling

The previous sibling element or null.

schemaTypeInfo

Not implemented yet, always return null

tagName

The element name

className

A string representing the classes of the element separated by spaces

id

The element ID

Changelog

Versão | Descrição
8.0.0 | The firstElementChild, lastElementChild, childElementCount, previousElementSibling, and nextElementSibling properties have been added.
8.0.0 | DOMElement implements DOMParentNode and DOMChildNode now.

Notas

Nota:

A extensão DOM usa codificação UTF-8. Use mb_convert_encoding(), UConverter::transcode() ou iconv() para lidar com outras codificações.

Índice

  • 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 — Creates a new DOMElement object
  • DOMElement::getAttribute — Returns value of attribute
  • DOMElement::getAttributeNames — Get attribute names
  • DOMElement::getAttributeNode — Returns attribute node
  • DOMElement::getAttributeNodeNS — Returns attribute node
  • DOMElement::getAttributeNS — Returns value of attribute
  • DOMElement::getElementsByTagName — Gets elements by tagname
  • DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName
  • DOMElement::hasAttribute — Checks to see if attribute exists
  • DOMElement::hasAttributeNS — Checks to see if attribute exists
  • DOMElement::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 — Removes attribute
  • DOMElement::removeAttributeNode — Removes attribute
  • DOMElement::removeAttributeNS — Removes attribute
  • DOMElement::replaceChildren — Replace children in element
  • DOMElement::replaceWith — Replaces the element with new nodes
  • DOMElement::setAttribute — Adds new or modifies existing attribute
  • DOMElement::setAttributeNode — Adds new attribute node to element
  • DOMElement::setAttributeNodeNS — Adds new attribute node to element
  • DOMElement::setAttributeNS — Adds new attribute
  • DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID
  • DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID
  • DOMElement::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

Descrição

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

Adds the passed nodes after the element.

Parâmetros

nodes

Nodes to be added after the node. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se o pai é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou este próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

  • DOMChildNode::after() - Adds nodes after the node
  • 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

Descrição

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

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

Parâmetros

nodes

The nodes to append. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

  • DOMParentNode::append() - Appends nodes after the last child node
  • 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

Descrição

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

Adds the passed nodes before the element.

Parâmetros

nodes

Nodes to be added before the node. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se o pai é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou este próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

hello
<beautiful/>
<world/>

Veja Também

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

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DOMElement object

  • « DOMElement::before
  • DOMElement::getAttribute »
  • PHP Manual
  • DOMElement
  • Creates a new DOMElement object

DOMElement::__construct

(PHP 5, PHP 7, PHP 8)

DOMElement::__construct — Creates a new DOMElement object

Descrição

public DOMElement::__construct(string $qualifiedName, ?string $value = null, string $namespace = "")

Creates a new DOMElement object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createElement or DOMDocument::createElementNS.

Parâmetros

qualifiedName

The tag name of the element. When also passing in namespaceURI, the element name may take a prefix to be associated with the URI.

value

The value of the element.

namespace

A namespace URI to create the element within a specific namespace.

Exemplos

Exemplo #1 Creating a new DOMElement

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$element_ns = new DOMElement('pr:node1', 'thisvalue', 'http://xyz');
$element->appendChild($element_ns);
echo $dom->saveXML(); /* <?xml version="1.0" encoding="utf-8"?>
<root><pr:node1 xmlns:pr="http://xyz">thisvalue</pr:node1></root> */

?>

Veja Também

  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace

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


Returns value of attribute

  • « DOMElement::__construct
  • DOMElement::getAttributeNames »
  • PHP Manual
  • DOMElement
  • Returns value of attribute

DOMElement::getAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttribute — Returns value of attribute

Descrição

public DOMElement::getAttribute(string $qualifiedName): string

Gets the value of the attribute with name qualifiedName for the current node.

Parâmetros

qualifiedName

The name of the attribute.

Valor Retornado

The value of the attribute, or an empty string if no attribute with the given qualifiedName is found.

Veja Também

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::setAttribute() - Adds new or modifies existing attribute
  • DOMElement::removeAttribute() - Removes attribute

User Contributed Notes

mpalmer at cybersource dot com 09-Nov-2007 03:32
- - - - - - - - - - - - - -

XML Data:
<data>
<Report ID="1">
    <Date>REVIEW</Date>
    <AuthorID>1</AuthorID>
</Report>
<Report ID="2">
    <Date>REVIEW</Date>
    <AuthorID>2</AuthorID>
</Report>
</data>

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

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load( 'data.xml' );

$searchNode = $xmlDoc->getElementsByTagName( "Report" );

foreach( $searchNode as $searchNode )
{
    $valueID = $searchNode->getAttribute('ID');

    $xmlDate = $searchNode->getElementsByTagName( "Date" );
    $valueDate = $xmlDate->item(0)->nodeValue;

    $xmlAuthorID = $searchNode->getElementsByTagName( "AuthorID" );
    $valueAuthorID = $xmlAuthorID->item(0)->nodeValue;

    echo "$valueID - $valueDate - $valueAuthorID\n";
}
?>

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

Output:

1 - REVIEW - 1
2 - REVIEW - 2

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


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

Descrição

public DOMElement::getAttributeNames(): array

Get attribute names.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Return attribute names.

Exemplos

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

O exemplo acima produzirá:

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.


Returns attribute node

  • « DOMElement::getAttributeNames
  • DOMElement::getAttributeNodeNS »
  • PHP Manual
  • DOMElement
  • Returns attribute node

DOMElement::getAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttributeNode — Returns attribute node

Descrição

public DOMElement::getAttributeNode(string $qualifiedName): DOMAttr|DOMNameSpaceNode|false

Returns the attribute node with name qualifiedName for the current element.

Parâmetros

qualifiedName

The name of the attribute.

Valor Retornado

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr.

Veja Também

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::setAttributeNode() - Adds new attribute node to element
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

lowezar at gmail dot com 28-Feb-2011 08:22
It may also return DOMNameSpaceNode if you`re requesting 'xmlns:_prefix_'. So you`re unable to remove it with removeAttributeNode() which requires DOMAttr as parameter.
Alex 18-Feb-2009 08:33
Just trying to add some clarification: this function will return boolean "false" when there is not a $name attribute :)

Cheers, Alex


Returns attribute node

  • « DOMElement::getAttributeNode
  • DOMElement::getAttributeNS »
  • PHP Manual
  • DOMElement
  • Returns attribute node

DOMElement::getAttributeNodeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttributeNodeNS — Returns attribute node

Descrição

public DOMElement::getAttributeNodeNS(?string $namespace, string $localName): DOMAttr|DOMNameSpaceNode|null

Returns the attribute node in namespace namespace with local name localName for the current node.

Parâmetros

namespace

The namespace URI.

localName

The local name.

Valor Retornado

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr object.

Veja Também

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::setAttributeNodeNS() - Adds new attribute node to element
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Returns value of attribute

  • « DOMElement::getAttributeNodeNS
  • DOMElement::getElementsByTagName »
  • PHP Manual
  • DOMElement
  • Returns value of attribute

DOMElement::getAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttributeNS — Returns value of attribute

Descrição

public DOMElement::getAttributeNS(?string $namespace, string $localName): string

Gets the value of the attribute in namespace namespace with local name localName for the current node.

Parâmetros

namespace

The namespace URI.

localName

The local name.

Valor Retornado

The value of the attribute, or an empty string if no attribute with the given localName and namespace is found.

Veja Também

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::setAttributeNS() - Adds new attribute
  • DOMElement::removeAttributeNS() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Gets elements by tagname

  • « DOMElement::getAttributeNS
  • DOMElement::getElementsByTagNameNS »
  • PHP Manual
  • DOMElement
  • Gets elements by tagname

DOMElement::getElementsByTagName

(PHP 5, PHP 7, PHP 8)

DOMElement::getElementsByTagName — Gets elements by tagname

Descrição

public DOMElement::getElementsByTagName(string $qualifiedName): DOMNodeList

This function returns a new instance of the class DOMNodeList of all descendant elements with a given tag qualifiedName, in the order in which they are encountered in a preorder traversal of this element tree.

Parâmetros

qualifiedName

The tag name. Use * to return all elements within the element tree.

Valor Retornado

This function returns a new instance of the class DOMNodeList of all matched elements.

Veja Também

  • DOMElement::getElementsByTagNameNS() - Get elements by namespaceURI and localName

User Contributed Notes

There are no user contributed notes for this page.


Get elements by namespaceURI and localName

  • « DOMElement::getElementsByTagName
  • DOMElement::hasAttribute »
  • PHP Manual
  • DOMElement
  • Get elements by namespaceURI and localName

DOMElement::getElementsByTagNameNS

(PHP 5, PHP 7, PHP 8)

DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName

Descrição

public DOMElement::getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList

This function fetch all the descendant elements with a given localName and namespace.

Parâmetros

namespace

The namespace URI of the elements to match on. The special value "*" matches all namespaces. Passing null matches the empty namespace.

localName

The local name of the elements to match on. The special value "*" matches all local names.

Valor Retornado

This function returns a new instance of the class DOMNodeList of all matched elements in the order in which they are encountered in a preorder traversal of this element tree.

Changelog

Versão | Descrição
8.0.3 | namespace is nullable now.

Veja Também

  • DOMElement::getElementsByTagName() - Gets elements by tagname

User Contributed Notes

spam at chovy dot com 03-Jun-2009 05:36
I had some difficulty stripping all default NS attributes for an ns-uri in one shot, the following will work though...first strip the documentElement namespace, then getElementsByTagNameNS() -- the documentation should reflect that the 2nd argument is actually the name of the tag, not the local namespace prefix as I first expected:

<?php

function strip_default_ns( $xml = null, $ns_uri = 'http://example.com/XML-Foo' ) {
    $ns_local = '';
    $ns_tag = '*';

    if ( empty($xml) ) return false;

    //remove document namespace
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    $dom->documentElement->removeAttributeNS($ns_uri, $ns_local);

    //strip element namespaces
    foreach ( $dom->getElementsByTagNameNS($ns_uri, $ns_tag) as $elem ) {
        $elem->removeAttributeNS($ns_uri, $ns_local);
    }

    return $dom->saveXML();
}

$stripped_xml = strip_default_ns($the_xml);

?>

$stripped_xml can now take advantage of running XPath queries on it for the NULL namespace.


Checks to see if attribute exists

  • « DOMElement::getElementsByTagNameNS
  • DOMElement::hasAttributeNS »
  • PHP Manual
  • DOMElement
  • Checks to see if attribute exists

DOMElement::hasAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::hasAttribute — Checks to see if attribute exists

Descrição

public DOMElement::hasAttribute(string $qualifiedName): bool

Indicates whether attribute named qualifiedName exists as a member of the element.

Parâmetros

qualifiedName

The attribute name.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::setAttribute() - Adds new or modifies existing attribute
  • DOMElement::removeAttribute() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Checks to see if attribute exists

  • « DOMElement::hasAttribute
  • DOMElement::insertAdjacentElement »
  • PHP Manual
  • DOMElement
  • Checks to see if attribute exists

DOMElement::hasAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::hasAttributeNS — Checks to see if attribute exists

Descrição

public DOMElement::hasAttributeNS(?string $namespace, string $localName): bool

Indicates whether attribute in namespace namespace named localName exists as a member of the element.

Parâmetros

namespace

The namespace URI.

localName

The local name.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::setAttributeNS() - Adds new attribute
  • DOMElement::removeAttributeNS() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


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

Descrição

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.

Valor Retornado

Return DOMElement or null on failure.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

  • 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

Descrição

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.

Valor Retornado

Nenhum valor é retornado.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

  • 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

Descrição

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

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

Parâmetros

nodes

The nodes to prepend. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

  • DOMParentNode::prepend() - Prepends nodes before the first child node
  • 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

Descrição

public DOMElement::remove(): void

Removes the element.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Nenhum valor é retornado.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

  • DOMElement::after() - Adds nodes after the element
  • DOMElement::before() - Adds nodes before the element
  • DOMElement::replaceWith() - Replaces the element with new nodes
  • DOMNode::removeChild() - Removes child from list of children

User Contributed Notes

There are no user contributed notes for this page.


Removes attribute

  • « DOMElement::remove
  • DOMElement::removeAttributeNode »
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::removeAttribute — Removes attribute

Descrição

public DOMElement::removeAttribute(string $qualifiedName): bool

Removes attribute named qualifiedName from the element.

Parâmetros

qualifiedName

The name of the attribute.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Veja Também

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::setAttribute() - Adds new or modifies existing attribute

User Contributed Notes

suwayan at mail dot ru 30-Mar-2012 12:19
<?php
/*When I try to get a some attribute from not validated HTML or XML document, PHP dies with no errors in logs or output:
*/
        function is_attribute_value($obj,$type,$value)
        {
            $_ret=false;
            if($obj)
            {
                if($val=$obj->getAttribute($type))
                {
                    if($val==$value)
                    {
                        $_ret=true;
                    }
                }
            }
            return $_ret;
        }
//And this check helped to me:
        function is_attribute_value($obj,$type,$value)
        {
            $_ret=false;
            if($obj->attributes)
            {
                if($val=$obj->getAttribute($type))
                {
                    if($val==$value)
                    {
                        $_ret=true;
                    }
                }
            }
            return $_ret;
        }
?>
Rakesh Verma - rakeshnsony at gmail dot com 10-Nov-2010 11:38
<?php

//Store your html into $html variable.

$html="<html>
<head>
<title>Rakesh Verma</title>
</head>

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

</html>";

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

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

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

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

        $newURL=$url.".au";

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

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

echo $html;

?>


Removes attribute

  • « DOMElement::removeAttribute
  • DOMElement::removeAttributeNS »
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::removeAttributeNode — Removes attribute

Descrição

public DOMElement::removeAttributeNode(DOMAttr $attr): DOMAttr|false

Removes attribute attr from the element.

Parâmetros

attr

The attribute node.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND_ERROR

Raised if attr is not an attribute of the element.

Veja Também

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNode() - Returns attribute node
  • DOMElement::setAttributeNode() - Adds new attribute node to element

User Contributed Notes

xr07354 at gmx dot de 18-Jun-2013 01:16
Basic: I use PHP5.4.9 from Ubuntu 13.04 repository. The aim of my code is to iterate HTML source (as a DomDocument) recursively and cleanup everything that is not valid to be used inside Epub files (i.e. and attribute align is not valid for paragraphs in Epubs).

FIRST: Today I tried removing attributes from a DOMElement using this simple code:
<?php
for ( $k=0; $k < $element->attributes->length; $k++) {
    if( /* some rule */ ){
        var_dump( $element->attributes->item($k)->nodeName);
        $element->removeAttributeNode( $element->attributes->item($k));
    }
}
?>
Unfortunately all attributes still existed when this loop was finished, even if these var_dumps told me that deleting them was tried.

I solved this problem iterating the attributes list backward:
<?php
for ( $k = $element->attributes->length - 1; $k >= 0; --$k) {
    if( /* same rule */ ){
        var_dump( $element->attributes->item($k)->nodeName);
        $element->removeAttributeNode( $element->attributes->item($k));
    }
}
?>
SECOND: DOMElement::removeAttributeNode does NOT return a bool but a DOMAttr object.


Removes attribute

  • « DOMElement::removeAttributeNode
  • DOMElement::replaceChildren »
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::removeAttributeNS — Removes attribute

Descrição

public DOMElement::removeAttributeNS(?string $namespace, string $localName): void

Removes attribute localName in namespace namespace from the element.

Parâmetros

namespace

The namespace URI.

localName

The local name.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Veja Também

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::setAttributeNS() - Adds new attribute

User Contributed Notes

primaryspace at hotmail dot com 10-Aug-2005 12:56
This method can be used to remove a namespace declaration from an element, even though the declaration is not considered an attribute by the DOM.  The prefix will be removed from any element or attribute using it.

<?php

$dom = DOMDocument::loadXML('<foo:root xmlns:foo="http:bar"/>');
$element = $dom->childNodes->item(0);

// prints '0':
echo (int) $element->hasAttributeNS('http:bar', 'foo');

$element->removeAttributeNS('http:bar', 'foo');

/* prints '<?xml version="1.0"?> <root/>': */
print htmlentities($dom->saveXML());

?>


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

Descrição

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

Replaces the children in the element with new nodes.

Parâmetros

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

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

User Contributed Notes

There are no user contributed notes for this page.


Replaces the element with new nodes

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

DOMElement::replaceWith

(PHP 8)

DOMElement::replaceWith — Replaces the element with new nodes

Descrição

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

Replaces the element with new nodes.

Parâmetros

nodes

The replacement nodes. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se o pai é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou este próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

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

O exemplo acima produzirá:

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

Veja Também

  • DOMChildNode::replaceWith() - Replaces the node with new nodes
  • 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.


Adds new or modifies existing attribute

  • « DOMElement::replaceWith
  • DOMElement::setAttributeNode »
  • PHP Manual
  • DOMElement
  • Adds new or modifies existing attribute

DOMElement::setAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttribute — Adds new or modifies existing attribute

Descrição

public DOMElement::setAttribute(string $qualifiedName, string $value): DOMAttr|bool

Sets an attribute with name qualifiedName to the given value. If the attribute does not exist, it will be created.

Parâmetros

qualifiedName

The name of the attribute.

value

The value of the attribute.

Valor Retornado

The created or modified DOMAttr or false if an error occurred.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Exemplos

Exemplo #1 Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

Veja Também

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::removeAttribute() - Removes attribute

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


Adds new attribute node to element

  • « DOMElement::setAttribute
  • DOMElement::setAttributeNodeNS »
  • PHP Manual
  • DOMElement
  • Adds new attribute node to element

DOMElement::setAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttributeNode — Adds new attribute node to element

Descrição

public DOMElement::setAttributeNode(DOMAttr $attr): DOMAttr|null|false

Adds new attribute node attr to element. If an attribute with the same name already exists on the element, that attribute is replaced by attr.

Parâmetros

attr

The attribute node.

Valor Retornado

Returns the old attribute if it has been replaced or null if there was no old attribute. If a DOM_WRONG_DOCUMENT_ERR error is raised, and strictErrorChecking is false, false is returned.

Erros

DOM_WRONG_DOCUMENT_ERR

Raised if attr belongs to a different document than the element.

Veja Também

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNode() - Returns attribute node
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

karvjorm at users.sourceforge.net 02-Mar-2007 04:01
$dom = new DomDocument('1.0','iso-8859-15');

$ht_ml = $dom->appendChild($dom->createElement('html'));

$he_ad = $ht_ml->appendChild($dom->createElement('head'));

$tit_le= $he_ad->appendChild($dom->createElement('title'));
$tit_le->appendChild($dom->createTextNode('DOMAttr test'));

$me_ta = $he_ad->appendChild(new DOMElement('meta'));
$me_ta->setAttributeNode(new DOMAttr('name', 'Description'));
$me_ta->setAttributeNode(new DOMAttr('content', 'example'));

$me_ta = $he_ad->appendChild(new DOMElement('meta'));
$me_ta->setAttributeNode(new DOMAttr('name', 'Author'));
$me_ta->setAttributeNode(new DOMAttr('content', 'karvjorm'));

Result:

<?xml version="1.0" encoding="iso-8859-15"?>
<html>
  <head>
    <title>DOMAttr test</title>
    <meta name="Description" content="example"/>
    <meta name="Author" content="karvjorm"/>
  </head>


Adds new attribute node to element

  • « DOMElement::setAttributeNode
  • DOMElement::setAttributeNS »
  • PHP Manual
  • DOMElement
  • Adds new attribute node to element

DOMElement::setAttributeNodeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttributeNodeNS — Adds new attribute node to element

Descrição

public DOMElement::setAttributeNodeNS(DOMAttr $attr): DOMAttr|null|false

Adds new attribute node attr to element, keeping the namespace into account. If an attribute with the same name already exists on the element, that attribute is replaced by attr.

Parâmetros

attr

The attribute node.

Valor Retornado

Returns the old attribute if it has been replaced or null if there was no old attribute. If a DOM_WRONG_DOCUMENT_ERR error is raised, and strictErrorChecking is false, false is returned.

Erros

DOM_WRONG_DOCUMENT_ERR

Raised if attr belongs to a different document than the element.

Veja Também

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNodeNS() - Returns attribute node
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Adds new attribute

  • « DOMElement::setAttributeNodeNS
  • DOMElement::setIdAttribute »
  • PHP Manual
  • DOMElement
  • Adds new attribute

DOMElement::setAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttributeNS — Adds new attribute

Descrição

public DOMElement::setAttributeNS(?string $namespace, string $qualifiedName, string $value): void

Sets an attribute with namespace namespace and name name to the given value. If the attribute does not exist, it will be created.

Parâmetros

namespace

The namespace URI.

qualifiedName

The qualified name of the attribute, as prefix:tagname.

value

The value of the attribute.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespace is null.

Veja Também

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::removeAttributeNS() - Removes attribute

User Contributed Notes

catalinenache78 at gmail dot com 18-May-2011 07:39
To add new brand xml namespace use:

<?php
    $element->setAttributeNS(
        'http://www.w3.org/2000/xmlns/', // xmlns namespace URI
        'xmlns:mynamespace',
        'example.com/mynamespace'
    );
?>

'http://www.w3.org/2000/xmlns/' URI is important
to be able to add  new namespaces !!!

Later you can use your namespace like:

<?php
    $element->setAttributeNS(
        'example.com/mynamespace',
        'mynamespace:something',
        'value'
    );
?>


Declares the attribute specified by name to be of type ID

  • « DOMElement::setAttributeNS
  • DOMElement::setIdAttributeNode »
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by name to be of type ID

DOMElement::setIdAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID

Descrição

public DOMElement::setIdAttribute(string $qualifiedName, bool $isId): void

Declares the attribute qualifiedName to be of type ID.

Parâmetros

qualifiedName

The name of the attribute.

isId

Set it to true if you want qualifiedName to be of type ID, false otherwise.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if qualifiedName is not an attribute of this element.

Veja Também

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttributeNode() - Declares the attribute specified by node to be of type ID
  • DOMElement::setIdAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID

User Contributed Notes

There are no user contributed notes for this page.


Declares the attribute specified by node to be of type ID

  • « DOMElement::setIdAttribute
  • DOMElement::setIdAttributeNS »
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by node to be of type ID

DOMElement::setIdAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID

Descrição

public DOMElement::setIdAttributeNode(DOMAttr $attr, bool $isId): void

Declares the attribute specified by attr to be of type ID.

Parâmetros

attr

The attribute node.

isId

Set it to true if you want name to be of type ID, false otherwise.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

Veja Também

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID

User Contributed Notes

There are no user contributed notes for this page.


Declares the attribute specified by local name and namespace URI to be of type ID

  • « DOMElement::setIdAttributeNode
  • DOMElement::toggleAttribute »
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by local name and namespace URI to be of type ID

DOMElement::setIdAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID

Descrição

public DOMElement::setIdAttributeNS(string $namespace, string $qualifiedName, bool $isId): void

Declares the attribute specified by qualifiedName and namespace to be of type ID.

Parâmetros

namespace

The namespace URI of the attribute.

qualifiedName

The local name of the attribute, as prefix:tagname.

isId

Set it to true if you want name to be of type ID, false otherwise.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

Veja Também

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNode() - Declares the attribute specified by node to be of type ID

User Contributed Notes

There are no user contributed notes for this page.


Toggle attribute

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

DOMElement::toggleAttribute

(PHP 8 >= 8.3.0)

DOMElement::toggleAttribute — Toggle attribute

Descrição

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.

Valor Retornado

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

Exemplos

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

O exemplo acima produzirá:

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.


The DOMEntity class

(PHP 5, PHP 7, PHP 8)

Introdução

This interface represents a known entity, either parsed or unparsed, in an XML document.

Sinopse da classe

class DOMEntity extends DOMNode {
/* Propriedades */
public readonly ?string $publicId;
public readonly ?string $systemId;
public readonly ?string $notationName;
public readonly ?string $actualEncoding = null;
public readonly ?string $encoding = null;
public readonly ?string $version = null;
/* Propriedades herdadas */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos herdados */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriedades

publicId

The public identifier associated with the entity if specified, and null otherwise.

systemId

The system identifier associated with the entity if specified, and null otherwise. This may be an absolute URI or not.

notationName

For unparsed entities, the name of the notation for the entity. For parsed entities, this is null.

actualEncoding

An attribute specifying the encoding used for this entity at the time of parsing, when it is an external parsed entity. This is null if it is an entity from the internal subset or if it is not known.

encoding

An attribute specifying, as part of the text declaration, the encoding of this entity, when it is an external parsed entity. This is null otherwise.

version

An attribute specifying, as part of the text declaration, the version number of this entity, when it is an external parsed entity. This is null otherwise.

User Contributed Notes

There are no user contributed notes for this page.


The DOMEntityReference class

(PHP 5, PHP 7, PHP 8)

Sinopse da classe

class DOMEntityReference extends DOMNode {
/* Propriedades herdadas */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos */
public __construct(string $name)
/* Métodos herdados */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Índice

  • DOMEntityReference::__construct — Creates a new DOMEntityReference object

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DOMEntityReference object

  • « DOMEntityReference
  • DOMException »
  • PHP Manual
  • DOMEntityReference
  • Creates a new DOMEntityReference object

DOMEntityReference::__construct

(PHP 5, PHP 7, PHP 8)

DOMEntityReference::__construct — Creates a new DOMEntityReference object

Descrição

public DOMEntityReference::__construct(string $name)

Creates a new DOMEntityReference object.

Parâmetros

name

The name of the entity reference.

Exemplos

Exemplo #1 Creating a new DOMEntityReference

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$entity = $element->appendChild(new DOMEntityReference('nbsp'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>&nbsp;</root> */

?>

Veja Também

  • DOMDocument::createEntityReference() - Create new entity reference node

User Contributed Notes

There are no user contributed notes for this page.


The DOMException class

(PHP 5, PHP 7, PHP 8)

Introdução

DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.

See also Exceções.

Sinopse da classe

final class DOMException extends Exception {
/* Propriedades */
public int $code;
/* Propriedades herdadas */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Métodos herdados */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

Propriedades

code

An integer indicating the type of error generated

User Contributed Notes

There are no user contributed notes for this page.


The DOMImplementation class

(PHP 5, PHP 7, PHP 8)

Introdução

The DOMImplementation class provides a number of methods for performing operations that are independent of any particular instance of the document object model.

Sinopse da classe

class DOMImplementation {
/* Métodos */
public createDocument(?string $namespace = null, string $qualifiedName = "", ?DOMDocumentType $doctype = null): DOMDocument|false
public createDocumentType(string $qualifiedName, string $publicId = "", string $systemId = ""): DOMDocumentType|false
public hasFeature(string $feature, string $version): bool
}

Índice

  • DOMImplementation::__construct — Creates a new DOMImplementation object
  • DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element
  • DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object
  • DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature

User Contributed Notes

LANGE.LUDO 07-Nov-2014 06:05
Ok got it working like a charm using "proxy pattern" with traits. The idea being declaring the common methods inside a "trait" in order for extended and registered Node Classes to have access even if not derived / child of the extended DOMNode…

Here a small snippet :
<?php
    namespace my;

    trait tNode
    {    // We need the magic method __get in order to add properties such as DOMNode->parentElement
        public function __get($name)
        {    if(property_exists($this, $name)){return $this->$name;}
            if(method_exists($this, $name)){return $this->$name();}
            throw new \ErrorException('my\\Node property \''.(string) $name.'\' not found…', 42, E_USER_WARNING);
        }

        // parentElement property definition
        private function parentElement()
        {    if($this->parentNode === null){return null;}
            if($this->parentNode->nodeType === XML_ELEMENT_NODE){return $this->parentNode;}
            return $this->parentNode->parentElement();
        }

        // JavaScript equivalent
        public function isEqualNode(\DOMNode $node){return $this->isSameNode($node);}
        public function compareDocumentPosition(\DOMNode $otherNode)
        {    if($this->ownerDocument !== $otherNode->ownerDocument){return DOCUMENT_POSITION_DISCONNECTED;}
            $c = strcmp($this->getNodePath(), $otherNode->getNodePath());
            if($c === 0){return 0;}
            else if($c < 0){return DOCUMENT_POSITION_FOLLOWING | ($c < -1 ? DOCUMENT_POSITION_CONTAINED_BY : 0);}
            return DOCUMENT_POSITION_PRECEDING | ($c > 1 ? DOCUMENT_POSITION_CONTAINS : 0);
        }
        public function contains(\DOMNode $otherNode){return ($this->compareDocumentPosition($otherNode) >= DOCUMENT_POSITION_CONTAINED_BY);}
    }

    class Document extends \DomDocument
    {    public function __construct($version=null, $encoding=null)
        {    parent::__construct($version, $encoding);
            $this->registerNodeClass('DOMNode', 'my\Node');
            $this->registerNodeClass('DOMElement', 'my\Element');
            $this->registerNodeClass('DOMDocument', 'my\Document');
            /* [...] */
        }
    }

    class Element extends \DOMElement
    {    use tNode;
        /* [...] */
    }

    class Node extends \DOMNode
    {    use tNode;
        /* [...] */
    }

?>
LANGE.LUDO 07-Nov-2014 08:14
From what I've seen you must "recode" the "createDocument" method in order to call your own object extension…

<?php
[...]
    public function createDocument($namespaceURI=null, $qualifiedName=null, DOMDocumentType $docType=null)
    {    $doc=new Document();
        $doc->appendChild(parent::createDocumentType('html'));
        $this->doc->appendChild($namespaceURI ? $this->doc->createElementNS($namespaceURI,$qualifiedName) : $this->doc->createElement($qualifiedName));
    return $doc;
    }
[...]
?>

Where I am struggling is extending the whole tree so that calling the customized Implementation method returns a whole extended tree…
Expected result : Implementation > Document > DOMDocument > Node > DOMNode
Actual result : Implementation > Document > DOMDocument > DOMNode :(
LANGE.LUDO 05-Nov-2014 10:59
Why not use the DOMImplementation to directly register your DOM Class extensions ?

<?php
namespace My;
class Implementation extends \DOMImplementation
{    private $doc;
    public function __construct(){return $this->createDocument();}
    public function __get($name){return $this->doc->{$name};}
    public function __set($name,$value){$this->doc->{$name}=$value;}
    public function __isset($name){return isset($this->doc->{$name});}
    public function __unset($name){return $this->doc->__unset($name);}
    public function __call($name,$args){return call_user_func_array(array($this->doc,$name),$args);}

    public function createDocument($namespaceURI=null,$qualifiedName=null,DOMDocumentType $docType=null)
    {    $this->doc=parent::createDocument($namespaceURI,$qualifiedName,$docType);
        $this->doc->xmlVersion='1.0';
        $this->doc->xmlEncoding='UTF-8';
        $this->doc->registerNodeClass('DOMDocument','My\Document');
        $this->doc->registerNodeClass('DOMDocumentFragment','My\DocumentFragment');
        $this->doc->registerNodeClass('DOMElement','My\Element');
        $this->doc->registerNodeClass('DOMComment','My\Comment');
        $this->doc->registerNodeClass('DOMNode','My\Node');
        /* …, …, … */
        return $this->doc;
    }
}
?>
giorgio dot liscio at email dot it 20-Jul-2010 06:26
officially, the w3 specifies that the way to access dom interfaces is through this class

so if you use

$doc = new DOMDocument("1.0", "UTF-8");

use instead:

$x = new DOMImplementation();
$doc = $x->createDocument(NULL,"rootElementName");
$doc->xmlVersion="1.0";
$doc->xmlEncoding="UTF-8";

it is not required by php's implementation, but, probably, it is a good practice

see:

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementation

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementationList

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementationSource


Creates a new DOMImplementation object

  • « DOMImplementation
  • DOMImplementation::createDocument »
  • PHP Manual
  • DOMImplementation
  • Creates a new DOMImplementation object

DOMImplementation::__construct

(PHP 5, PHP 7)

DOMImplementation::__construct — Creates a new DOMImplementation object

Descrição

DOMImplementation::__construct()

Creates a new DOMImplementation object.

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


Creates a DOMDocument object of the specified type with its document element

  • « DOMImplementation::__construct
  • DOMImplementation::createDocumentType »
  • PHP Manual
  • DOMImplementation
  • Creates a DOMDocument object of the specified type with its document element

DOMImplementation::createDocument

(PHP 5, PHP 7, PHP 8)

DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element

Descrição

public DOMImplementation::createDocument(?string $namespace = null, string $qualifiedName = "", ?DOMDocumentType $doctype = null): DOMDocument|false

Creates a DOMDocument object of the specified type with its document element.

Parâmetros

namespace

The namespace URI of the document element to create.

qualifiedName

The qualified name of the document element to create.

doctype

The type of document to create or null.

Valor Retornado

A new DOMDocument object or false on error. If namespace, qualifiedName, and doctype are null, the returned DOMDocument is empty with no document element

Erros

DOM_WRONG_DOCUMENT_ERR

Raised if doctype has already been used with a different document or was created from a different implementation.

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by namespace and qualifiedName.

Changelog

Versão | Descrição
8.0.3 | namespace is now nullable.
8.0.0 | doctype is now nullable.
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

Veja Também

  • DOMDocument::__construct() - Creates a new DOMDocument object
  • DOMImplementation::createDocumentType() - Creates an empty DOMDocumentType object

User Contributed Notes

sleistico at gmail dot com 02-Jul-2018 03:48
I just recently got an error, having to do with deprecation, by using the type of calls in the other example listed here.  What I had to do instead looks like this...

$htmldoc = (new DOMImplementation)->createDocument(null, 'html', (new DOMImplementation)->createDocumentType("html"));

This creates a document with <!DOCTYPE html> at the top of it.
eboyjr 22-Jul-2010 12:48
To add on to the other example, here's how to create an XHTML 1.0 transitional document with head, title, and body elements.

<?php

$document = DOMImplementation::createDocument(null, 'html',
    DOMImplementation::createDocumentType("html",
        "-//W3C//DTD XHTML 1.0 Transitional//EN",
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"));
$document->formatOutput = true;

$html = $document->documentElement;
$head = $document->createElement('head');
$title = $document->createElement('title');
$text = $document->createTextNode('Title of Page');
$body = $document->createElement('body');

$title->appendChild($text);
$head->appendChild($title);
$html->appendChild($head);
$html->appendChild($body);

echo $document->saveXML();
?>

This outputs: (http links removed due to spam)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "doctype.dtd">
<html xmlns="w3org1999xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; CHARSET=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);
?>


Creates an empty DOMDocumentType object

  • « DOMImplementation::createDocument
  • DOMImplementation::hasFeature »
  • PHP Manual
  • DOMImplementation
  • Creates an empty DOMDocumentType object

DOMImplementation::createDocumentType

(PHP 5, PHP 7, PHP 8)

DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object

Descrição

public DOMImplementation::createDocumentType(string $qualifiedName, string $publicId = "", string $systemId = ""): DOMDocumentType|false

Creates an empty DOMDocumentType object. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur.

Parâmetros

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Valor Retornado

A new DOMDocumentType node with its ownerDocument set to null or false on error.

Erros

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by qualifiedName.

Changelog

Versão | Descrição
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

Exemplos

Exemplo #1 Creating a document with an attached DTD

<?php

// Creates an instance of the DOMImplementation class
$imp = new DOMImplementation;

// Creates a DOMDocumentType instance
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Creates a DOMDocument instance
$dom = $imp->createDocument("", "", $dtd);

// Set other properties
$dom->encoding = 'UTF-8';
$dom->standalone = false;

// Create an empty element
$element = $dom->createElement('graph');

// Append the element
$dom->appendChild($element);

// Retrieve and print the document
echo $dom->saveXML();

?>

O exemplo acima produzirá:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

Veja Também

  • DOMImplementation::createDocument() - Creates a DOMDocument object of the specified type with its document element

User Contributed Notes

until-all-bytes-are-free at example dot org 09-Apr-2011 04:28
I had problems to use a DTD from a file. It needed to be resolved relatively and it contained characters that made DomDocument failed to resolve the file.

Encoding and an absolute filename did not help much. So I used the data:// streamwrapper ( http://php.net/manual/en/wrappers.data.php ) as a work-around:

<?php

// relative or absolute filename
$path = '...';

// convert file contents into a filename
$data = file_get_contents($path);
$systemId = 'data://text/plain;base64,'.base64_encode($data);

// ...

// Creates a DOMDocumentType instance
$dtd = $aImp->createDocumentType('qualified name', '', $systemId);

?>

Works like a charm.


Test if the DOM implementation implements a specific feature

  • « DOMImplementation::createDocumentType
  • DOMNamedNodeMap »
  • PHP Manual
  • DOMImplementation
  • Test if the DOM implementation implements a specific feature

DOMImplementation::hasFeature

(PHP 5, PHP 7, PHP 8)

DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature

Descrição

public DOMImplementation::hasFeature(string $feature, string $version): bool

Test if the DOM implementation implements a specific feature.

You can find a list of all features in the » Conformance section of the DOM specification.

Parâmetros

feature

The feature to test.

version

The version number of the feature to test. In level 2, this can be either 2.0 or 1.0.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

Exemplos

Exemplo #1 Testing your DOM Implementation

<?php

$features = array(
'Core' => 'Core module',
'XML' => 'XML module',
'HTML' => 'HTML module',
'Views' => 'Views module',
'Stylesheets' => 'Style Sheets module',
'CSS' => 'CSS module',
'CSS2' => 'CSS2 module',
'Events' => 'Events module',
'UIEvents' => 'User interface Events module',
'MouseEvents' => 'Mouse Events module',
'MutationEvents' => 'Mutation Events module',
'HTMLEvents' => 'HTML Events module',
'Range' => 'Range module',
'Traversal' => 'Traversal module'
);

foreach ($features as $key => $name) {
if (DOMImplementation::hasFeature($key, '2.0')) {
echo "Has feature $name\n";
} else {
echo "Missing feature $name\n";
}
}

?>

Veja Também

  • DOMNode::isSupported() - Checks if feature is supported for specified version

User Contributed Notes

There are no user contributed notes for this page.


The DOMNamedNodeMap class

(PHP 5, PHP 7, PHP 8)

Sinopse da classe

class DOMNamedNodeMap implements IteratorAggregate, Countable {
/* Propriedades */
public readonly int $length;
/* Métodos */
public count(): int
public getIterator(): Iterator
public getNamedItem(string $qualifiedName): ?DOMNode
public getNamedItemNS(?string $namespace, string $localName): ?DOMNode
public item(int $index): ?DOMNode
}

Propriedades

length

The number of nodes in the map. The range of valid child node indices is 0 to length - 1 inclusive.

Changelog

Versão | Descrição
8.0.0 | The unimplemented methods DOMNamedNodeMap::setNamedItem(), DOMNamedNodeMap::removeNamedItem(), DOMNamedNodeMap::setNamedItemNS() and DOMNamedNodeMap::removeNamedItem() have been removed.
8.0.0 | DOMNamedNodeMap implements IteratorAggregate now. Previously, Traversable was implemented instead.

Índice

  • DOMNamedNodeMap::count — Get number of nodes in the map
  • DOMNamedNodeMap::getIterator — Retrieve an external iterator
  • DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name
  • DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI
  • DOMNamedNodeMap::item — Retrieves a node specified by index

User Contributed Notes

sirajshaikh96 at yahoo dot com 01-Jan-2021 02:48
I have tried to solve the general problem occurs in DOMNamedNodeMap that during executing for/foreachloop after executing removeAttribute('$name') for item(0), item(1) is not executing and warning occurs. Following codes give the solution of this problem that in loop item(0) should be applied rather than item($i) because after removing first attribute node now present element has only one attribute node.

<?php
$html  = '<h1 id="h1test" class="h2test">Heading</h1>';
$html .= '<p align="left" class="right">Hello World</p>';

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

// remove attributes from  the h1 element
$h1 = $doc->getElementsByTagName('h1')->item(0);
$length = $h1->attributes->length;
for ($i = 0; $i < $length; $i++) {
    $name = $h1->attributes->item(0)->nodeName;
    $value = $h1->attributes->item(0)->nodeValue;
    $h1->removeAttribute($name);
    echo "h1: removed attribute name :- " .$name."</br>";
    echo "h1: removed attribute value :- " .$value."</br>";
    }
// remove attributes from the p element
$p = $doc->getElementsByTagName('p')->item(0);
for ($i = 0; $i < $length; $i++) {
    $name = $p->attributes->item(0)->nodeName;
    $value = $p->attributes->item(0)->nodeValue;
    $p->removeAttribute($name);
    echo "p: removed attribute name :- " .$name."</br>";
    echo "p: removed attribute value :- " .$value."</br>";
}
?>

OUTPUT:

h1: removed attribute name :- id
h1: removed attribute value :- h1test
h1: removed attribute name :- class
h1: removed attribute value :- h2test
p: removed attribute name :- align
p: removed attribute value :- left
p: removed attribute name :- class
p: removed attribute value :- right
kendsnyder at gmail dot com 29-Oct-2009 07:55
To add to xafford's comment. When iterating a named node map collection using ->item() or using foreach, removing a attribute with DOMNode->removeAttribute() or DOMNode->removeAttributeNode() alters the collection as if it were a stack. To illustrate, the code below tries to remove all attributes from each element but only removes the first. One work around is to copy the named node map into an array before removing attributes. Using PHP 5.2.9 on Windows XP.

<?php
error_reporting(E_ALL);
$html  = '<h1 id="h1test" class="h1test">Heading</h1>';
$html .= '<p align="left" class="ptest">Hello World</p>';

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

// remove attributes from  the h1 element
$h1 = $doc->getElementsByTagName('h1')->item(0);
$length = $h1->attributes->length;
for ($i = 0; $i < $length; ++$i) {
    $name = $h1->attributes->item($i)->name;
    $h1->removeAttribute($name);
    echo "h1: removed attribute `$name`<br>";
}
// remove attributes from the p element
$p = $doc->getElementsByTagName('p')->item(0);
foreach ($p->attributes as $name => $attrNode) {
    $p->removeAttribute($name);
    echo "p: removed attribute `$name`<br>";
}

?>

OUTPUT:
-------
h1: removed attribute `id`

Notice: Trying to get property of non-object in nodemap.php on line 13
h1: removed attribute ``
p: removed attribute `align`
xafford 15-Oct-2009 03:16
I stumbled upon a problem with DOMNamedNodeMap. If you iterate over a DOMNamedNodeMap, representing the attributes of a DOMElement with foreach and you use DOMElement::removeAttributeNode only the first attribute will be handled.

Example (not complete):

<?php

/*
 * Imagine you got a node like this:
 * <a onclick="alert('evil')" href="http://example.com">evil</a>
 * and onclick should be removed, href would not be tested.
 */

foreach ( $node->attributes as $attribute )
{

    echo 'checking attribute ', $attribute->name, '<br />';

    if ( ! in_array ( $attribute->name, $allowed_attributes ) )
    {
        $node->removeAttributeNode ( $attribute );
    }

}

?>

The output would be:

checking attribute onclick


Get number of nodes in the map

  • « DOMNamedNodeMap
  • DOMNamedNodeMap::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

Descrição

public DOMNamedNodeMap::count(): int

Gets the number of nodes in the map.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public DOMNamedNodeMap::getIterator(): Iterator

Returns an external iterator for the named node map.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Uma instância de um objeto que implementa Iterator ou Traversable

Erros

Lança uma Exception em caso de falha.

Veja Também

  • IteratorAggregate::getIterator() - Recupera um iterator externo

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a node specified by name

  • « DOMNamedNodeMap::getIterator
  • DOMNamedNodeMap::getNamedItemNS »
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by name

DOMNamedNodeMap::getNamedItem

(PHP 5, PHP 7, PHP 8)

DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name

Descrição

public DOMNamedNodeMap::getNamedItem(string $qualifiedName): ?DOMNode

Retrieves a node specified by its nodeName.

Parâmetros

qualifiedName

The nodeName of the node to retrieve.

Valor Retornado

A node (of any type) with the specified nodeName, or null if no node is found.

Veja Também

  • DOMNamedNodeMap::getNamedItemNS() - Retrieves a node specified by local name and namespace URI

User Contributed Notes

franp at free dot fr 03-Mar-2006 07:28
Basic example of use :

<?xml version="1.0" encoding="UTF-8"?>
<racine version="2.0a">
  <article/>
</racine>

<?php
(...)
 echo $doc->documentElement->attributes->getNamedItem("version")->nodeValue;

// returns "2.0a"
?>


Retrieves a node specified by local name and namespace URI

  • « DOMNamedNodeMap::getNamedItem
  • DOMNamedNodeMap::item »
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by local name and namespace URI

DOMNamedNodeMap::getNamedItemNS

(PHP 5, PHP 7, PHP 8)

DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI

Descrição

public DOMNamedNodeMap::getNamedItemNS(?string $namespace, string $localName): ?DOMNode

Retrieves a node specified by localName and namespace.

Parâmetros

namespace

The namespace URI of the node to retrieve.

localName

The local name of the node to retrieve.

Valor Retornado

A node (of any type) with the specified local name and namespace URI, or null if no node is found.

Veja Também

  • DOMNamedNodeMap::getNamedItem() - Retrieves a node specified by name

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a node specified by index

  • « DOMNamedNodeMap::getNamedItemNS
  • DOMNode »
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by index

DOMNamedNodeMap::item

(PHP 5, PHP 7, PHP 8)

DOMNamedNodeMap::item — Retrieves a node specified by index

Descrição

public DOMNamedNodeMap::item(int $index): ?DOMNode

Retrieves a node specified by index within the DOMNamedNodeMap object.

Parâmetros

index

Index into this map.

Valor Retornado

The node at the indexth position in the map, or null if that is not a valid index (greater than or equal to the number of nodes in this map).

User Contributed Notes

reyjacobs at yahoo dot com 07-Mar-2008 11:24
Nevermind: I got it, and here it is:

<?php
if($element->hasAttributes())
{
    $attributes = $element->attributes;
    if(!is_null($attributes))
    {
        foreach ($attributes as $index=>$attr)
        {
            echo $attr->name."=\"".$attr->value."\"";
        }
    }
}
?>


The DOMNode class

(PHP 5, PHP 7, PHP 8)

Sinopse da classe

class DOMNode {
/* Propriedades */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos */
public appendChild(DOMNode $node): DOMNode|false
public C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public cloneNode(bool $deep = false): DOMNode|false
public contains(DOMNode|DOMNameSpaceNode|null $other): bool
public getLineNo(): int
public getNodePath(): ?string
public getRootNode(array $options = null): DOMNode
public hasAttributes(): bool
public hasChildNodes(): bool
public insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public isDefaultNamespace(string $namespace): bool
public isEqualNode(?DOMNode $otherNode): bool
public isSameNode(DOMNode $otherNode): bool
public isSupported(string $feature, string $version): bool
public lookupNamespaceURI(?string $prefix): ?string
public lookupPrefix(string $namespace): ?string
public normalize(): void
public removeChild(DOMNode $child): DOMNode|false
public replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriedades

nodeName

Returns the most accurate name for the current node type

nodeValue

The value of this node, depending on its type. Contrary to the W3C specification, the node value of DOMElement nodes is equal to DOMNode::textContent instead of null.

nodeType

Gets the type of the node. One of the predefined XML_xxx_NODE constants

parentNode

The parent of this node. If there is no such node, this returns null.

parentElement

The parent element of this element. If there is no such element, this returns null.

childNodes

A DOMNodeList that contains all children of this node. If there are no children, this is an empty DOMNodeList.

firstChild

The first child of this node. If there is no such node, this returns null.

lastChild

The last child of this node. If there is no such node, this returns null.

previousSibling

The node immediately preceding this node. If there is no such node, this returns null.

nextSibling

The node immediately following this node. If there is no such node, this returns null.

attributes

A DOMNamedNodeMap containing the attributes of this node (if it is a DOMElement) or null otherwise.

isConnected

Whether the node is connected to a document

ownerDocument

The DOMDocument object associated with this node, or null if this node is a DOMDocument

namespaceURI

The namespace URI of this node, or null if it is unspecified.

prefix

The namespace prefix of this node.

localName

Returns the local part of the qualified name of this node.

baseURI

The absolute base URI of this node or null if the implementation wasn't able to obtain an absolute URI.

textContent

The text content of this node and its descendants.

Changelog

Versão | Descrição
8.3.0 | Properties DOMNode::$parentElement, and DOMNode::$isConnected have been added.
8.0.0 | The unimplemented methods DOMNode::compareDocumentPosition(), DOMNode::isEqualNode(), DOMNode::getFeature(), DOMNode::setUserData() and DOMNode::getUserData() have been removed.

Notas

Nota:

A extensão DOM usa codificação UTF-8. Use mb_convert_encoding(), UConverter::transcode() ou iconv() para lidar com outras codificações.

Veja Também

  • » W3C specification of Node

Índice

  • DOMNode::appendChild — Adiciona um novo filho ao final dos filhos
  • DOMNode::C14N — Canonicalize nodes to a string
  • DOMNode::C14NFile — Canonicalize nodes to a file
  • DOMNode::cloneNode — Clones a node
  • DOMNode::contains — Checks if node contains other node
  • DOMNode::getLineNo — Get line number for a node
  • DOMNode::getNodePath — Get an XPath for a node
  • DOMNode::getRootNode — Get root node
  • DOMNode::hasAttributes — Checks if node has attributes
  • DOMNode::hasChildNodes — Checks if node has children
  • DOMNode::insertBefore — Adds a new child before a reference node
  • DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not
  • DOMNode::isEqualNode — Checks that both nodes are equal
  • DOMNode::isSameNode — Indicates if two nodes are the same node
  • DOMNode::isSupported — Checks if feature is supported for specified version
  • DOMNode::lookupNamespaceURI — Gets the namespace URI of the node based on the prefix
  • DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI
  • DOMNode::normalize — Normalizes the node
  • DOMNode::removeChild — Removes child from list of children
  • DOMNode::replaceChild — Replaces a child

User Contributed Notes

Anonymous 06-May-2018 04:12
It would be helpful if docs for concrete properties mentioned readonly status of some properties:
"
ownerDocument

    The DOMDocument object associated with this node.

"
zlk1214 at gmail dot com 15-Jan-2016 01:07
A function that can set the inner HTML without encoding error. $html can be broken content such as "<a ID=id20>ssss"
function setInnerHTML($node, $html) {
    removeChildren($node);
    if (empty($html)) {
        return;
    }

    $doc = $node->ownerDocument;
    $htmlclip = new DOMDocument();
    $htmlclip->loadHTML('<meta http-equiv="Content-Type" content="text/html;CHARSET=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.


Adiciona um novo filho ao final dos filhos

  • « DOMNode
  • DOMNode::C14N »
  • PHP Manual
  • DOMNode
  • Adiciona um novo filho ao final dos filhos

DOMNode::appendChild

(PHP 5, PHP 7, PHP 8)

DOMNode::appendChild — Adiciona um novo filho ao final dos filhos

Descrição

public DOMNode::appendChild(DOMNode $node): DOMNode|false

Esta função acrescenta um filho a uma lista existente de filhos, ou cria uma nova lista de filhos. O filho pode ser criado, por exemplo, com DOMDocument::createElement(), DOMDocument::createTextNode() etc. ou simplesmente pode usaando-se qualquer outro nó.

Ao usar um nó existente ele será movido.

Parâmetros

node

O nó filho anexado.

Valor Retornado

O nó adicionado ou false em caso de erro.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Lançado se este nó for somente leitura, ou se o pai anterior do nó que está sendo inserido for somente leitura.

DOM_HIERARCHY_REQUEST_ERR

Lançada se este nó for de um tipo que não permite que filhos do tipo do node, ou se o nó a ser anexado for um dos ancestrais deste nó, ou se for este próprio nó.

DOM_WRONG_DOCUMENT_ERR

Lançado se node foi criado por um documento diferente do documento que criou este nó.

Exemplos

O exemplo a seguir irá adicionar um novo nó de elemento de um documento novo.

Exemplo #1 Adicionando um nó filho

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

Exemplo #2 Filhos aninhados

<?php

$doc = new DOMDocument;

$headNode = $doc->createElement("head");
$doc->appendChild($headNode);

$titleNode = $doc->createElement("title");
$headNode->appendChild($titleNode);

echo $doc->saveXML();
?>

Veja Também

  • DOMChildNode::after() - Adds nodes after the node
  • DOMNode::insertBefore() - Adds a new child before a reference node
  • DOMNode::removeChild() - Removes child from list of children
  • DOMNode::replaceChild() - Replaces a child

User Contributed Notes

cweiske at php dot net 05-Nov-2017 01:56
If you want to move the children of one node to another, you cannot simply iterate on $element->childNodes - you have to make an array first:

<?php
$children = [];
foreach ($elemWithChildren->childNodes as $child) {
    $children[] = $child;
}
foreach ($children as $child) {
    $targetElement->appendChild($child);
}
?>
frame at dynamiccreated dot de 01-Dec-2010 04:14
Aware dealing with DOMNodeList and appendChild() on the same Node.

If you want to replace only the children not the DOMElement itself you probably foreach childNodes-property or get the DOMElements with a for-loop and item()-method of the DOMNodeList.

You will fail if you not clone the received single DOMElement. Actually the count of the DOMNodelist will be decreased on appendChild count but appendChild seems to refer to the old Nodelist and nothing visible will happen. Cloning will help.
krisdover at hotmail dot com 31-May-2008 08:49
What's not mentioned here is that DOMNode::appendChild() can also be used to move an existing node to another part of the DOMDocument, e.g.

<?php
$doc = new DOMDocument();
$doc->loadXML("<foobar><bar/><foo/></foobar>");
$bar = $doc->documentElement->firstChild;
$foo = $doc->documentElement->lastChild;
$foo->appendChild($bar);
print $doc->saveXML();
?>

This produces:

<?xml version="1.0"?>
<foobar><foo><bar/></foo></foobar>

Note that the nodes "<foo/>" and "<bar/>" were siblings, i.e. the first and last child of "<foobar>" but using appendChild() we were able to move "<bar/>" so that it is a child of "<foo/>".

This saves you the trouble of doing a DOMNode::removeChild($bar) to remove "<bar/>" before appending it as a child of "<foo/>".

Kris Dover
jrtayloriv at gmail dot com 30-Mar-2008 04:56
If you want to create nested DOM elements:

<?php
    $doc = new DOMDocument();

    $foo = $doc->createElement("foo");
    $doc->appendChild($foo);

    $bar = $doc->createElement("bar");
    $foo->appendChild($bar);

    $bazz = $doc->createElement("bazz");
    $foo->appendChild($bazz);

    echo $doc->saveXML();
?>

Is equivalent to:

<foo>
  <bar></bar>
  <bazz></bazz>
</foo>


Canonicalize nodes to a string

  • « DOMNode::appendChild
  • DOMNode::C14NFile »
  • PHP Manual
  • DOMNode
  • Canonicalize nodes to a string

DOMNode::C14N

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

DOMNode::C14N — Canonicalize nodes to a string

Descrição

public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false

Canonicalize nodes to a string

Parâmetros

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

withComments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

nsPrefixes

An array of namespace prefixes to filter the nodes by.

Valor Retornado

Returns canonicalized nodes as a string ou false em caso de falha

Veja Também

  • DOMNode::C14NFile() - Canonicalize nodes to a file

User Contributed Notes

lordbaco 28-Jan-2016 09:57
Good to know:

<< Due to a known issue in XML canonicalization in PHP, processing large metadata files in SimpleSAMLphp takes a big amount of resources, with that amount growing approximately by the square of the number of entities in the metadata set >>
https://simplesamlphp.org/metaprocessing

<< The C14N() function appears to have a runtime that is O(N^2) (or possibly worse?) depending on input size, which means that it becomes very slow as the input grows. For example, an input with around 196000 nodes takes about 290 seconds, while an input with 486000 nodes takes 2200 seconds. >>
https://bugs.php.net/bug.php?id=53655

We had the same issue with a 4.1 MB XML (105k lines). The sample code of ticket  #53655 takes 1h36 minute to canonicalize it!
jorda at edpsciences dot org 13-Mar-2015 09:11
C14N() returns an empty string if the node is not included in the document tree:
<?php
$d = new DOMDocument('1.0');
$d->loadXML('<foo></foo>');
$n = $d->createElement('bar');
var_dump($n->C14N());
$d->documentElement->appendChild($n);
var_dump($n->C14N());
?>
output:
string(0) ""
string(11) "<bar></bar>"
Rijk 27-Mar-2013 09:26
When working with (malformed) HTML, you're probably better off using DOMDocument's saveHTML() method instead. C14N() will attempt to make your HTML valid XML, for example by converting <br> to <br></br>.

So instead of:
$html = $Node->C14N();

Use:
$html = $Node->ownerDocument->saveHTML( $Node );


Canonicalize nodes to a file

  • « DOMNode::C14N
  • DOMNode::cloneNode »
  • PHP Manual
  • DOMNode
  • Canonicalize nodes to a file

DOMNode::C14NFile

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

DOMNode::C14NFile — Canonicalize nodes to a file

Descrição

public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false

Canonicalize nodes to a file.

Parâmetros

uri

Path to write the output to.

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

withComments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

nsPrefixes

An array of namespace prefixes to filter the nodes by.

Valor Retornado

Number of bytes written ou false em caso de falha

Veja Também

  • DOMNode::C14N() - Canonicalize nodes to a string

User Contributed Notes

There are no user contributed notes for this page.


Clones a node

  • « DOMNode::C14NFile
  • DOMNode::contains »
  • PHP Manual
  • DOMNode
  • Clones a node

DOMNode::cloneNode

(PHP 5, PHP 7, PHP 8)

DOMNode::cloneNode — Clones a node

Descrição

public DOMNode::cloneNode(bool $deep = false): DOMNode|false

Creates a copy of the node.

Parâmetros

deep

Indicates whether to copy all descendant nodes. This parameter is defaulted to false.

Valor Retornado

The cloned node.

User Contributed Notes

cmd at 1xinternet dot de 16-Nov-2016 12:11
If you need to clone node including all child DOMNode elements:

private function cloneNode($node){

        $nd = new DOMNode();

        for ($i = 0; $i < $node->childNodes->length; $i++) {
            $child = $node->childNodes->item($i);
            if ($child->nodeType === XML_TEXT_NODE) {
                $nd->appendChild($node->cloneNode(true));
            }
            else{
                $nd->appendChild($this->cloneNode($child));
            }
        }

        return $nd;
    }
h-fate at gmx dot net 01-Oct-2014 07:48
If you have an object that holds a DOMNode, cloning the object won't clone the DOMNode with it. If you simply copy the object or add its DOMNode several times, you will in fact only move the DOMNode in the tree, not multiply it. That might seem obvious, but took me half a day to find out.

The object needs to use __clone and clone the node manually:

<?php
class containsNode {
    public $node; //set from somewhere

    public function __clone() {
        $this->node = $this->node->cloneNode(TRUE);
    }
}
?>
frame at dynamiccreated dot de 02-Dec-2012 02:19
Remeber that DOMNode always needs a reference to a parent node or DOMDocument.

For example, if you try to clone a node - copy all children - and overwrite or delete the variable which holds the cloned node - all children will loose any reference and getting invalid.

This will cause a nice message like "Couldn't... node no longer exists" if you have luck. In most cases PHP only gives you the poor information "Couldn't fetch DOM[...]" which makes hard to find out whats going on, depending on the current operation.
cemkalyoncu at gmail dot com 28-Apr-2009 03:04
If you need some function to clone a node without touching namespaces you can use the following.

<?php
private function cloneNode($node,$doc){
    $nd=$doc->createElement($node->nodeName);

    foreach($node->attributes as $value)
        $nd->setAttribute($value->nodeName,$value->value);

    if(!$node->childNodes)
        return $nd;

    foreach($node->childNodes as $child) {
        if($child->nodeName=="#text")
            $nd->appendChild($doc->createTextNode($child->nodeValue));
        else
            $nd->appendChild(cloneNode($child,$doc));
    }

    return $nd;
}
?>
[montana] at [percepticon] dot [com] 16-Feb-2009 02:23
<?php

//@oliver thanks for example source...

/*
 cloneNode(false) does not omit
 Attributes of cloned node,
 to achieve this an iteration is required.
 this is probably less efficient
 than merely creating a new
 node from the desired nodeName
 but in some cases could be useful.

use case:

omit subnodes and attributes of
secured portions of an xml document
without altering expected general structure;
*/
//xml to use

$file="<?xml version='1.0'?>
<book type='paperback'>
    <title name='MAP'>Red Nails</title>
    <price>$12.99</price>
    <author>
        <name first='Robert' middle='E' last='Howard'/>
        <birthdate disco='false' nirvana='definitely'>
            9/21/1977
            <month title='september' />
        </birthdate>
    </author>
    <author>
        <name first='Arthur' middle='Mc' last='Kayn'/>
    </author>
</book>";

$doc = new domDocument;

$doc->loadXML($file);

$xpath = new domXPath($doc);

$query = "//author/birthdate";
$xpathQuery = $xpath->query($query);

//would be a loop in production code...
$child = $xpathQuery->item(0);

$parent = $child->parentNode;

$doppel = $child->cloneNode(false);

$limit = $doppel->attributes->length;

for ($a=0;$a<$limit;$a++) {
    $doppel->removeAttributeNode($doppel->attributes->item(0));
}
//swap for now empty node
$parent->replaceChild( $doppel, $child);

print $doc->saveXML();

?>
oliver dot christen at camptocamp dot com 19-Nov-2004 08:48
simple exemple of node cloning

<?xml version="1.0"?>

<book type="paperback">
    <title name='MAP'>Red Nails</title>
    <price>$12.99</price>
    <author>
        <name first="Robert" middle="E" last="Howard"/>
        <birthdate>9/21/1977</birthdate>
    </author>
    <author>
        <name first="Arthur" middle="Mc" last="Kayn"/>
    </author>
</book>

<?php

//filename xml file to use
$file = 'book.xml';

$doc = new domDocument;

if (file_exists($file)) {
    $doc->load($file);
} else {
    exit('Erreur !.');
}

$xpath = new domXPath($doc);

$query = "//author/*";
$xpathQuery = $xpath->query($query);

$size = $xpathQuery->length;
for ($i=0; $i<$size; $i++){
    $node = $xpathQuery->item($i);
    if ($node->nodeName == 'birthdate' && $node->hasChildNodes() && $node->firstChild->textContent != ''){
        $clonenode = $node->cloneNode(true);
        $refnode = $node;
    }
}
for ($i=0; $i<$size; $i++){
    $node = $xpathQuery->item($i);
    if (!$node->isSameNode($refnode)){
        $newnode = $node->appendChild($clonenode);
    }
}

print $doc->saveXML();

?>


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

Descrição

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

Checks if node contains other node.

Parâmetros

other

Node to be checked.

Valor Retornado

Returns true if node contains other node, false otherwise.

Exemplos

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

O exemplo acima produzirá:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Get line number for a node

  • « DOMNode::contains
  • DOMNode::getNodePath »
  • PHP Manual
  • DOMNode
  • Get line number for a node

DOMNode::getLineNo

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

DOMNode::getLineNo — Get line number for a node

Descrição

public DOMNode::getLineNo(): int

Gets line number for where the node is defined.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Always returns the line number where the node was defined in.

Exemplos

Exemplo #1 DOMNode::getLineNo() example

<?php
// XML dump for below example
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
<node />
</root>
XML;

// Create a new DOMDocument instance
$dom = new DOMDocument;

// Load the XML
$dom->loadXML($xml);

// Print where the line where the 'node' element was defined in
printf('The <node> tag is defined on line %d', $dom->getElementsByTagName('node')->item(0)->getLineNo());
?>

O exemplo acima produzirá:

The <node> tag is defined in line 3

User Contributed Notes

ruud at vanmelick dot com 25-Oct-2013 09:15
The 65535 line number limit is no longer a problem when you use libxml 2.9 or higher, but you have to explicitly enable support for big line numbers:

<?php
define('XML_PARSE_BIG_LINES', 4194304);
$dom = new DOMDocument;
$dom->loadXML($xml, XML_PARSE_BIG_LINES);
?>
Anonymous 19-May-2012 02:21
The DOMNode::getLineNo() method doesn't work properly due to a libxml2 bug.

https://bugzilla.gnome.org/show_bug.cgi?id=676026
luke dot NOREPLY at webconnex dot com 04-Mar-2011 06:28
This function is buggy. It doesn't always return the correct line number, especially for text elements. As an alternative you can do something like this:

<?php
$text = $node->ownerDocument->saveXML($node);
$line += substr_count($text, "\n");
?>

You'll want to keep a reference to $line (starting at 0) and add to it as you parse over the document recursively.

In order for this to work you have to tell DOMDocument to preserve white space before loading the document.


Get an XPath for a node

  • « DOMNode::getLineNo
  • DOMNode::getRootNode »
  • PHP Manual
  • DOMNode
  • Get an XPath for a node

DOMNode::getNodePath

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

DOMNode::getNodePath — Get an XPath for a node

Descrição

public DOMNode::getNodePath(): ?string

Gets an XPath location path for the node.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns a string containing the XPath, or null in case of an error.

Exemplos

Exemplo #1 DOMNode::getNodePath() example

<?php
// Create a new DOMDocument instance
$dom = new DOMDocument;

// Load the XML
$dom->loadXML('
<fruits>
<apples>
<apple>braeburn</apple>
<apple>granny smith</apple>
</apples>
<pears>
<pear>conference</pear>
</pears>
</fruits>
');

// Print XPath for each element
foreach ($dom->getElementsByTagName('*') as $node) {
echo $node->getNodePath() . "\n";
}
?>

O exemplo acima produzirá:

/fruits
/fruits/apples
/fruits/apples/apple[1]
/fruits/apples/apple[2]
/fruits/pears
/fruits/pears/pear

Veja Também

  • 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

Descrição

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

Get root node.

Parâmetros

options

This parameter has no effect yet.

Valor Retornado

Returns the root node.

Exemplos

Exemplo #1 DOMNode::getRootNode() example

<?php

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

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

O exemplo acima produzirá:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Checks if node has attributes

  • « DOMNode::getRootNode
  • DOMNode::hasChildNodes »
  • PHP Manual
  • DOMNode
  • Checks if node has attributes

DOMNode::hasAttributes

(PHP 5, PHP 7, PHP 8)

DOMNode::hasAttributes — Checks if node has attributes

Descrição

public DOMNode::hasAttributes(): bool

This method checks if the node has attributes. The tested node has to be an XML_ELEMENT_NODE.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • DOMNode::hasChildNodes() - Checks if node has children

User Contributed Notes

There are no user contributed notes for this page.


Checks if node has children

  • « DOMNode::hasAttributes
  • DOMNode::insertBefore »
  • PHP Manual
  • DOMNode
  • Checks if node has children

DOMNode::hasChildNodes

(PHP 5, PHP 7, PHP 8)

DOMNode::hasChildNodes — Checks if node has children

Descrição

public DOMNode::hasChildNodes(): bool

This function checks if the node has children.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • DOMNode::hasAttributes() - Checks if node has attributes

User Contributed Notes

Anonymous 21-Mar-2015 04:33
Hi what if its a dynamic file and we cannot use get elements by tag name then how do we print the contents of all level tags?
richard dot gildx at gmail dot com 29-Jul-2012 01:20
This "hasChildNodes()" exercise is simple enough to make it clear and understandable. Or, you could take it as a tag empty check. By Richard Holm, Sweden.

<?php
$xmldoc=
'<?xml version="1.0" ?>
<root>
<text>Text</text>
<none/>
<empty></empty>
<space> </space>
</root>';

$domdoc=new DOMDocument();
$domdoc->loadXML($xmldoc);

$tag=$domdoc->getElementsByTagName('root')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('text')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('none')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('empty')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('space')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";
?>

Output:
root hasChildNodes
text hasChildNodes
none hasNoChildNodes
empty hasNoChildNodes
space hasChildNodes
sansana 14-Oct-2010 07:04
Personally I think using a simple:[code]if($DOMNode->childNodes <>0){}[/code] works better.
syngcw at syncgw.com 04-Jan-2010 05:53
This function is a bit tricky. If you want to find XML childnodes it is useless. You need to create a work-around:

<?php

$x = new DOMDocument();
$x->loadXML('
<A>
 <B>b-text</B>
 <C>
  <D>d-text</D>
 </C>
 <E/>
</A>');

shownode($x->getElementsByTagName('A')->item(0));
function shownode($x) {
 foreach ($x->childNodes as $p)
  if (hasChild($p)) {
      echo $p->nodeName.' -> CHILDNODES<br>';
      shownode($p);
  } elseif ($p->nodeType == XML_ELEMENT_NODE)
   echo $p->nodeName.' '.$p->nodeValue.'<br>';
}
function hasChild($p) {
 if ($p->hasChildNodes()) {
  foreach ($p->childNodes as $c) {
   if ($c->nodeType == XML_ELEMENT_NODE)
    return true;
  }
 }
 return false;
}

?>

shows:
B b-text
C -> CHILDNODES
D d-text
E
jintoppy at gmail dot com 28-Apr-2009 04:13
<?php

$doc = new DOMDocument;
$node = $doc->createElement("FirstMain", "First Main Node. This have child");
$doc->appendChild($node);
$childnode = $doc->createElement("childnode", "child node");
$node->appendChild($childnode);
$secondnode = $doc->createElement("SecondMain", "First Main Node. This don't have child");
$doc->appendChild($secondnode);
$doc->saveXML();
$nodeElmt = $doc->getElementsByTagName("FirstMain");
/*
if given as $nodeElmt = $doc->getElementsByTagName("childnode");
the output would be "This node has childnodes"

if given as $nodeElmt = $doc->getElementsByTagName("SecondMain");
the output would be "This node has no childnodes"

*/

foreach($nodeElmt as $nodeElmt)
{
if($nodeElmt->hasChildNodes())
{
echo "This node has childnodes";
}
else
{
echo "This node has no childnodes";
}
}

  ?>

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

Output:

This node has childnodes

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


Adds a new child before a reference node

  • « DOMNode::hasChildNodes
  • DOMNode::isDefaultNamespace »
  • PHP Manual
  • DOMNode
  • Adds a new child before a reference node

DOMNode::insertBefore

(PHP 5, PHP 7, PHP 8)

DOMNode::insertBefore — Adds a new child before a reference node

Descrição

public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false

This function inserts a new node right before the reference node. If you plan to do further modifications on the appended child you must use the returned node.

When using an existing node it will be moved.

Parâmetros

node

The new node.

child

The reference node. If not supplied, node is appended to the children.

Valor Retornado

The inserted node or false on error.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the node node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if node was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if child is not a child of this node.

Veja Também

  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos

User Contributed Notes

jarry1250 at gmail dot com 30-May-2015 01:59
Note that supplying the same node for $newnode and $refnode leads to an E_WARNING ("Couldn't add newnode as the previous sibling of refnode"). For example imagine one wanted to make $newnode the first child of its parent by doing:

<?php
$firstSibling = $newnode->parentNode->firstChild;
// Bad:
$newnode->parentNode->insertBefore( $newnode, $firstSibling );
?>

This would generate a warning if it already was the first child of its parent, since $newnode and $firstSibling are identical. Easy to work around though:

<?php
$firstSibling = $newnode->parentNode->firstChild;
// Better:
if( $newnode !== $firstSibling ) {
    $newnode->parentNode->insertBefore( $newnode, $firstSibling );
}
?>
DrTebi at Yahoo 03-Oct-2007 05:54
Sorry, my previous posting worked only for the top node. Here the corrected version, which will work for any node:

XML
----
<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person>
  <person>Thomas</person>
</contacts>

PHP
---
<?php
// load XML, create XPath object
$xml = new DomDocument();
$xml->preserveWhitespace = false;
$xml->load('contacts.xml');
$xpath = new DOMXPath($xml);

// get node eva, which we will append to
$eva = $xpath->query('/contacts/person[.="Eva"]')->item(0);

// create node john
$john = $xml->createElement('person', 'John');

// insert john after eva
//   "in eva's parent node (=contacts) insert
//   john before eva's next node"
// this also works if eva would be the last node
$eva->parentNode->insertBefore($john, $eva->nextSibling);

// show result
header('Content-Type: text/plain');
print $xml->saveXML();
?>

Result
------
<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person><person>John</person>
  <person>Thomas</person>
</contacts>
justin at redwiredesign dot com 07-Feb-2007 08:20
The previous example is incorrect, and causes a DOM_NOT_FOUND error, as the child nodes are not direct descendants of the root node.

Therefore, the line:

$parent_path = "/root";

needs to change to:

$parent_path = "/root/parent";

or

$parent_path = "//parent";

for this example to work
jg at handcode dot de 18-Aug-2005 12:18
example to insert <newnode/> between <chid1/> and <child2/>

<?xml version="1.0" encoding="ISO-8859-1" ?>
<root>
  <parent>
    <child nr="1"/>
    <child nr="2"/>
  </parent>
</root>

<?php

$xml_src = 'test.xml';

// XPath-Querys
$parent_path = "//parent";
$next_path = "//parent/child[@nr='2']";

// Create a new DOM document
$dom = new DomDocument();
$dom->load($xml_src);

// Find the parent node
$xpath = new DomXPath($dom);

// Find parent node
$parent = $xpath->query($parent_path);

// new node will be inserted before this node
$next = $xpath->query($next_path);

// Create the new element
$element = $dom->createElement('newnode');

// Insert the new element
$parent->item(0)->insertBefore($element, $next->item(0));

echo $dom->saveXML();

?>
Jerry Ellis 03-Jun-2005 12:45
1st argument) a node to insert
2nd argument) a reference node - this is the node that the new node will be inserted before

The trick to using this method is that the OBJECT on which you actually CALL the insertBefore() method is actually the PARENT node of the reference node!

INCORRECT:
$DOMNode_refNode->insertBefore($DOMNode_newNode, $DOMNode_refNode);

CORRECT:
$DOMNode_refNode->parentNode->insertBefore($DOMNode_newNode, $DOMNode_refNode);


Checks if the specified namespaceURI is the default namespace or not

  • « DOMNode::insertBefore
  • DOMNode::isEqualNode »
  • PHP Manual
  • DOMNode
  • Checks if the specified namespaceURI is the default namespace or not

DOMNode::isDefaultNamespace

(PHP 5, PHP 7, PHP 8)

DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not

Descrição

public DOMNode::isDefaultNamespace(string $namespace): bool

Tells whether namespace is the default namespace.

Parâmetros

namespace

The namespace URI to look for.

Valor Retornado

Return true if namespace is the default namespace, false otherwise.

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

Descrição

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

Checks that both nodes are equal.

Parâmetros

otherNode

The node.

Valor Retornado

Returns true if both nodes are equal, false otherwise.

Exemplos

Exemplo #1 DOMNode::isEqualNode() example

<?php

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

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

O exemplo acima produzirá:

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Indicates if two nodes are the same node

  • « DOMNode::isEqualNode
  • DOMNode::isSupported »
  • PHP Manual
  • DOMNode
  • Indicates if two nodes are the same node

DOMNode::isSameNode

(PHP 5, PHP 7, PHP 8)

DOMNode::isSameNode — Indicates if two nodes are the same node

Descrição

public DOMNode::isSameNode(DOMNode $otherNode): bool

This function indicates if two nodes are the same node. The comparison is not based on content

Parâmetros

otherNode

The compared node.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

User Contributed Notes

There are no user contributed notes for this page.


Checks if feature is supported for specified version

  • « DOMNode::isSameNode
  • DOMNode::lookupNamespaceURI »
  • PHP Manual
  • DOMNode
  • Checks if feature is supported for specified version

DOMNode::isSupported

(PHP 5, PHP 7, PHP 8)

DOMNode::isSupported — Checks if feature is supported for specified version

Descrição

public DOMNode::isSupported(string $feature, string $version): bool

Checks if the asked feature is supported for the specified version.

Parâmetros

feature

The feature to test. See the example of DOMImplementation::hasFeature() for a list of features.

version

The version number of the feature to test.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • DOMImplementation::hasFeature() - Test if the DOM implementation implements a specific feature

User Contributed Notes

There are no user contributed notes for this page.


Gets the namespace URI of the node based on the prefix

  • « DOMNode::isSupported
  • DOMNode::lookupPrefix »
  • PHP Manual
  • DOMNode
  • Gets the namespace URI of the node based on the prefix

DOMNode::lookupNamespaceURI

(PHP 5, PHP 7, PHP 8)

DOMNode::lookupNamespaceURI — Gets the namespace URI of the node based on the prefix

Descrição

public DOMNode::lookupNamespaceURI(?string $prefix): ?string

Gets the namespace URI of the node based on the prefix.

Parâmetros

prefix

The prefix to look for. If this parameter is null, the method will return the default namespace URI, if any.

Valor Retornado

Returns the associated namespace URI or null if none is found.

Veja Também

  • DOMNode::lookupPrefix() - Gets the namespace prefix of the node based on the namespace URI

User Contributed Notes

_ michael 30-Apr-2010 02:22
You have to pass *null* to lookupNamespaceURI if you want to read the default namespace. Passing an empty string doesn't work - even though the documentation says that lookupNamespaceURI takes a string as argument (and null would just be converted to an empty string).
lewar 05-Jun-2007 05:20
Simple way to get the URI of the default namespace:

<?php
    $document = new DOMDocument();
    $document->load($xml_file);
    $uri = $document->documentElement->lookupnamespaceURI(NULL);
?>


Gets the namespace prefix of the node based on the namespace URI

  • « DOMNode::lookupNamespaceURI
  • DOMNode::normalize »
  • PHP Manual
  • DOMNode
  • Gets the namespace prefix of the node based on the namespace URI

DOMNode::lookupPrefix

(PHP 5, PHP 7, PHP 8)

DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI

Descrição

public DOMNode::lookupPrefix(string $namespace): ?string

Gets the namespace prefix of the node based on the namespace URI.

Parâmetros

namespace

The namespace URI.

Valor Retornado

The prefix of the namespace or null on error.

Veja Também

  • DOMNode::lookupNamespaceUri() - Gets the namespace URI of the node based on the prefix

User Contributed Notes

There are no user contributed notes for this page.


Normalizes the node

  • « DOMNode::lookupPrefix
  • DOMNode::removeChild »
  • PHP Manual
  • DOMNode
  • Normalizes the node

DOMNode::normalize

(PHP 5, PHP 7, PHP 8)

DOMNode::normalize — Normalizes the node

Descrição

public DOMNode::normalize(): void

Remove empty text nodes and merge adjacent text nodes in this node and all its children.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Nenhum valor é retornado.

Veja Também

  • » The DOM Specification
  • DOMDocument::normalizeDocument() - Normalizes the document

User Contributed Notes

Amir Laher 22-Aug-2005 04:45
This is a quote from the DOM level 2 spec, explaining the normalize() function.
----
normalize
Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes. This can be used to ensure that the DOM view of a document is the same as if it were saved and re-loaded, and is useful when operations (such as XPointer [XPointer] lookups) that depend on a particular document tree structure are to be used.
----
(source: http://www.w3.org/TR/DOM-Level-2-Core/core.html)

i.e. the idea of normalize is to make text nodes the same as they would be if the xml document was re-loaded into DOM. It's handy if you want to compare DOM nodes.


Removes child from list of children

  • « DOMNode::normalize
  • DOMNode::replaceChild »
  • PHP Manual
  • DOMNode
  • Removes child from list of children

DOMNode::removeChild

(PHP 5, PHP 7, PHP 8)

DOMNode::removeChild — Removes child from list of children

Descrição

public DOMNode::removeChild(DOMNode $child): DOMNode|false

This functions removes a child from a list of children.

Parâmetros

child

The removed child.

Valor Retornado

If the child could be removed the function returns the old child or false on error.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly.

DOM_NOT_FOUND

Raised if child is not a child of this node.

Exemplos

The following example will delete the chapter element of our XML document.

Exemplo #1 Removing a child

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// we retrieve the chapter and remove it from the book
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo $doc->saveXML();
?>

O exemplo acima produzirá:

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

Veja Também

  • DOMChildNode::remove() - Removes the node
  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMNode::replaceChild() - Replaces a child

User Contributed Notes

nggit@phpindonesia 01-Feb-2019 02:29
You can use foreach to remove multiple elements from a DOMNodeList, only if you use a temporary array or via XPath query.
If not, the simplest way will be:

<?php

while ($element = $nodeList->item(0)) {
    $element->parentNode->removeChild($element);
}

?>
Kenney 28-Mar-2013 10:19
This method will remove all child nodes but leave the attributes (and namespace declarations) intact.

<?php
function removeChildren( &$node )
{
  $node->parentNode->replaceChild(
    $n = $node->cloneNode( false ),
    $node );

  $node = $n;
}
?>
drimsun at gmail dot com 11-Feb-2010 03:37
If you try to remove children of a nested node (e.g. a <ul> list that contains another <ul>) and only remove the first level of child nodes, you'll get a messed-up node object.

Upon re-use of the messed-up node you'll get an error message that says: "Fatal error: Call to a member function blahblah() on a non-object".

To remove ALL child nodes, use this recursive function instead:
<?php
/**
 * Helper function that removes all child nodes of $node recursively
 * (i.e. including child nodes of the child nodes and so forth).
 */
function remove_children(&$node) {
  while ($node->firstChild) {
    while ($node->firstChild->firstChild) {
      remove_children($node->firstChild);
    }
    $node->removeChild($node->firstChild);
  }
}
?>
Justin Carlson 05-Nov-2009 11:46
Just a note, if you remove a node the whitespace it occupied will remain if you save the file.

To avoid this, use $document->preserveWhiteSpace = false;

For Example:

<?php
$document = new DomDocument();
$document->preserveWhiteSpace = false;
?>
crazy888s at hotmail dot com 15-Apr-2009 01:50
You can't remove DOMNodes from a DOMNodeList as you're iterating over them in a foreach loop. For example...

<?php
$domNodeList = $domDocument->getElementsByTagname('p');
foreach ( $domNodeList as $domElement ) {
  //  ...do stuff with $domElement...
  $domElement->parentNode->removeChild($domElement);
}
?>

... will seemingly leave the internal iterator on the foreach out of wack and results will be quite strange. Though, making a queue of items to remove seems to work. For example...

<?php
$domNodeList = $domDocument->getElementsByTagname('p');
$domElemsToRemove = array();
foreach ( $domNodeList as $domElement ) {
  // ...do stuff with $domElement...
  $domElemsToRemove[] = $domElement;
}
foreach( $domElemsToRemove as $domElement ){
  $domElement->parentNode->removeChild($domElement);
}
?>
Justin Sheckler 30-Jan-2009 08:44
These two functions might be helpful to anyone trying to delete a node and all of its children:

<?php
function deleteNode($node) {
    deleteChildren($node);
    $parent = $node->parentNode;
    $oldnode = $parent->removeChild($node);
}

function deleteChildren($node) {
    while (isset($node->firstChild)) {
        deleteChildren($node->firstChild);
        $node->removeChild($node->firstChild);
    }
}
?>
tim cameron ryan 19-Jul-2008 01:00
Or something like:

<?php

while ($node->childNodes->length)
     $node->removeChild($node->firstChild);

?>
Michael D (DigitalGemstones.com) 05-Jul-2008 04:15
Note that iterating through the childNodes array and removing those children will stop the iteration.

For example:
<?php
foreach($node->childNodes as $child)
{
  if(iWantToDeleteThisNode($child))
     $child->parentNode->removeChild($child);
}
?>

Will not work.  Note that in removing the node, the childNodes array gets rebuilt (it seems) and so only the first item will be removed.  In order to properly remove all the children you want to remove, you will need to do something like the following:

<?php
$nodesToDelete = array();
foreach($node->childNodes as $child)
{
  if(iWantToDeleteThisNode($child))
    $nodesToDelete[] = $child;
}
foreach($nodesToDelete as $node)
{
  $node->parentNode->removeChild($node);
}
?>

I believe this is actually more efficient than the first snippet would be (if it worked) but obviously I cannot benchmark it.
Wala 04-Apr-2008 10:57
I used the following to delete an entire node using the child element:

<?php
$childElement->parentNode->parentNode-> removeChild($childElement->parentNode);
?>

I could not have thought of it without the help of everyone who contributed to this thread.

Thanks!

(I had to introduce the extra space between parentNode->removeChild to get rid of the wordwrap() warning while posting this note)
Vasil Rangelov 06-Oct-2007 10:14
At the time of writing, I suppose rightfully, removeChild() removes only the selected node, but when you remove an element, it's child elements are not removed. If you want to achieve that, replaceChild() is the solution.

The following should remove all descendants of the $node DOMNode, regardless of it's name:
<?php
$node->replaceChild(new DOMElement($node->nodeName), $node);
?>
If you're replacing the root element, you must explicitly state that with $node->documentElement as the second argument.
mytto at openxtrem dot com 07-Sep-2005 02:20
Back again on removing childs and iterators robustness.

Things get a bit more complicated when you only want to remove 'some' nodes according to a certain condition. Then you can't just remove the first one repeatedly.

The trick is to copy the content of the node list into a more robust collection than DOMNodeList, I name array!

The following piece of code will, for instance, remove all empty child nodes:

<?php
// Copy childNodes array
$childNodes = array();
foreach($node->childNodes as $childNode) {
  $childNodes[] = $childNode;
}

// Browse with the copy
foreach ($childNodes as $childNode) {
  if (!$childNode->hasChildNodes()); {
    $childNode->parentNode->removeChild($childNode);
  }
}
?>
blaine (at) blainegarrett (dot com) 23-Aug-2005 10:10
This might be obvious, but might help someone as well...

If you simply have a node that you need to remove (perhaps from an xpath) and don't know the parent node offhand (the examples seem to assume you have the parent in a variable), then you can do something easy like this...

$node->parentNode->removeChild($node);

parentNode is a scalar property of the Element.

Hope that helps.

--
Blaine Garrett
pedro at leb dot usp dot br 30-May-2005 04:24
You may also use the hasChild function:
<?php

while($node->hasChildNodes()) {
  $node->removeChild($node->childNodes->item(0));
}

?>

When you remove a childNode, the next node becomes the first one!
vsematika at centrum dot cz 13-Feb-2005 03:35
For those who don't understand >sbeam at onsetcorps dot net on 02-Feb-2005 12:07< 'hack', here's a little discussion:

First but *wrong* try would be:
<?php
foreach ($parent->childNodes as $child) {
   $parent->removeChild($child);
?>
This doesn't work because DOM tree id modified on-the-fly and this confuses foreach loop.

The idea behind sbeam's trick is that after removing the first item in the first iteration, the second item in childNodes nodelist immediately becomes the first item. That's why we must _always_ remove the first child. Here's another implementation:

<?php
$count = $parent->childNodes->length;
for ($i = 0; $i < $count; $i++) {
   $oldNode = $parent->removeChild($parent->childNodes->item(0)); // !!! not item($i) !!!
}
?>


Replaces a child

  • « DOMNode::removeChild
  • DOMNodeList »
  • PHP Manual
  • DOMNode
  • Replaces a child

DOMNode::replaceChild

(PHP 5, PHP 7, PHP 8)

DOMNode::replaceChild — Replaces a child

Descrição

public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false

This function replaces the child child with the passed new node. If the node is already a child it will not be added a second time. If the replacement succeeds the old node is returned.

Parâmetros

node

The new node. It must be a member of the target document, i.e. created by one of the DOMDocument->createXXX() methods or imported in the document by DOMDocument::importNode.

child

The old node.

Valor Retornado

The old node or false if an error occur.

Erros

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the node node, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if node was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if child is not a child of this node.

Veja Também

  • DOMChildNode::replaceWith() - Replaces the node with new nodes
  • DOMNode::appendChild() - Adiciona um novo filho ao final dos filhos
  • DOMNode::removeChild() - Removes child from list of children

User Contributed Notes

chealer at gmail dot com 15-Aug-2018 03:07
As of version 5.6, PHP still behaves as reported by jb at jbpros dot com. To use replaceChild() in a loop, the more standard pattern used in the following example can be used:

for ($currentNode = 0; $currentNode < $link->childNodes->length; $currentNode++) {
    $child = $link->childNodes[$currentNode];

    // "Remove" links, since links can't contain links
    if ($child instanceof DOMElement && $child->tagName == 'a') {
        $replacement = $dom->createTextNode($child->textContent);
        $link->replaceChild($replacement, $child);
    }
}
jb at jbpros dot com 01-Mar-2005 08:08
If you are trying to replace more than one node at once, you have to be careful about iterating over the DOMNodeList.  If the old node has a different name from the new node, it will be removed from the list once it has been replaced.  Use a regressive loop:

<?php

$xml = new DOMDocument;
$xml->load('docfile.xml');

$elements = $xml->getElementsByTagNameNS('http://www.example.com/NS/', '*');
$i = $elements->length - 1;
while ($i > -1) {
    $element = $elements->item($i);
    $ignore = false;

    $newelement = $xml>createTextNode('Some new node!');
    $element->parentNode->replaceChild($newelement, $element);
    $i--;
}

?>

The loop counter ($i) will always be in the list's interval as removed elements indexes are above the counter.
aidan at php dot net 26-Dec-2004 02:17
Here is a simple example for replacing a node:

Let's define our XML like so:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<root>
  <parent>
     <child>bar</child>
     <child>foo</child>
  </parent>
</root>
XML;
?>

If we wanted to replace the entire <parent> node, we could do something like this:

<?php
// Create a new document fragment to hold the new <parent> node
$parent = new DomDocument;
$parent_node = $parent ->createElement('parent');

// Add some children
$parent_node->appendChild($parent->createElement('child', 'somevalue'));
$parent_node->appendChild($parent->createElement('child', 'anothervalue'));

// Add the keywordset into the new document
// The $parent variable now holds the new node as a document fragment
$parent->appendChild($parent_node);
?>

Next, we need to locate the old node:

<?php
// Load the XML
$dom = new DomDocument;
$dom->loadXML($xml);

// Locate the old parent node
$xpath = new DOMXpath($dom);
$nodelist = $xpath->query('/root/parent');
$oldnode = $nodelist->item(0);
?>

We then import and replace the new node:

<?php
// Load the $parent document fragment into the current document
$newnode = $dom->importNode($parent->documentElement, true);

// Replace
$oldnode->parentNode->replaceChild($newnode, $oldnode);

// Display
echo $dom->saveXML();
?>

Our new node is successfully imported:

<?xml version="1.0"?>
<root>
<parent><child>somevalue</child><child>anothervalue</child></parent>
</root>
franp at free dot fr 23-Sep-2004 08:39
1) If your XPath query returns a NodeList including a unique item, or if you know for sure the order of the items returned, you can use the "item(n)" syntax instead of the "foreach" syntax.
This can greatly improve you code lisibility.
s the method name implies, replaceChild cannot replace a node itself but a child of a node.
The trick is to use replaceChild on the parent node of your Xpath query result.

<?xml version="1.0" ?>
<action>
 <actionGlobal>
  <actionGlobalFR>sometext</actionGlobalFR>
 <actionGlobal>
</action>

$frag = $doc->createElement("actionGlobalFR");
$fragA = $doc->createTextNode("anothertext");
$frag->appendChild($fragA);

$xpResult = $xp->query("/action/actionGlobal/actionGlobalFR");
$blipblip = $xpResult->item(0)->parentNode->replaceChild($ajout, $xpResult->item(0));

2) Also, as the method name implies, replaceChild cannot replace a node itself but a child of a node.
Still it is possible to replace a node pointed by XPath istead of its child.
The trick is to use replaceChild on the parent node of your Xpath query result.

<?xml version="1.0" ?>
<action>
  <FR>French Text</FR>
</action>

<?php
$frag = $doc->createElement("EN");
$fragA = $doc->createTextNode("English Text");
$frag->appendChild($fragA);

$xpResult = $xp->query("/action/FR");
$blipblip = $xpResult->item(0)->parentNode->replaceChild($fragA, $xpResult->item(0));
?>

Et voil? !

This produces :
<?xml version="1.0" ?>
<action>
  <EN>English Text</EN>
</action>

....................................................

3) Also, be carefull, you CANNOT replace a node that doesn't exist.
While this may seems obvious, it is easy to forget.

Consider this :
<?xml version="1.0" ?>
<action>
  <EN></EN>
</action>

You cannot use replaceChild() to turn this into :
<?xml version="1.0" ?>
<action>
  <EN>Some text</EN>
</action>

The reason is that since the <EN></EN> element is empty, it has no child (this is clearer to understand if you consider that <EN></EN> can be written <EN />).
The fact that you intend to put some text inbetween <EN> and </EN> does not change the fact that it has no text yet, thus no child yet.
When dealing with DOM, do not take your dream for the reality. The DOM parser doen't care about your dreams. If an element is currently empty, it has no child, whatever you intend to fill in.

Thus, the solution to teh problem is to use appendChild intead of replaceChild :

<?php
$fragA = $doc->createTextNode("Some Text");
$xpResult = $xp->query("/action/EN");
$blipblip = $xpResult->item(0)->appendChild($fragA);
?>

This produces the awaited :
<?xml version="1.0" ?>
<action>
  <EN>Some Text</EN>
</action>

....................................................

4) Note that the description of replaceChild in the doc is wrong. Arguments have been inverted.
The correct description is :
object DOMNode->replaceChild (object newnode, object oldnode)


The DOMNodeList class

(PHP 5, PHP 7, PHP 8)

Sinopse da classe

class DOMNodeList implements IteratorAggregate, Countable {
/* Propriedades */
public readonly int $length;
/* Métodos */
public count(): int
public getIterator(): Iterator
public item(int $index): DOMElement|DOMNode|DOMNameSpaceNode|null
}

Propriedades

length

The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

Changelog

Versão | Descrição
8.0.0 | DOMNodeList implements IteratorAggregate now. Previously, Traversable was implemented instead.
7.2.0 | The Countable interface is implemented and returns the value of the length property.

Veja Também

  • » W3C specification of NodeList

Índice

  • DOMNodeList::count — Get number of nodes in the list
  • DOMNodeList::getIterator — Retrieve an external iterator
  • DOMNodeList::item — Retrieves a node specified by index

User Contributed Notes

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

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

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

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

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

</code>

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

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

  public function __construct (DOMNodeList $node_list) {

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

    parent::__construct($nodes);

  }

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

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

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

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

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

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

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

Our code:

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

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

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

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

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

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

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

This only gives you the first element ...

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

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

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

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

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

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


Get number of nodes in the list

  • « DOMNodeList
  • DOMNodeList::getIterator »
  • PHP Manual
  • DOMNodeList
  • Get number of nodes in the list

DOMNodeList::count

(PHP 7 >= 7.2.0, PHP 8)

DOMNodeList::count — Get number of nodes in the list

Descrição

public DOMNodeList::count(): int

Gets the number of nodes in the list.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns the number of nodes in the list, which is identical to the length property.

User Contributed Notes

plimpton47 at example dot com 04-May-2018 08:09
Be careful with using this function as it's not available for anything before PHP 7.2, use the length property instead


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

Descrição

public DOMNodeList::getIterator(): Iterator

Returns an external iterator for the node list.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Uma instância de um objeto que implementa Iterator ou Traversable

Erros

Lança uma Exception em caso de falha.

Veja Também

  • IteratorAggregate::getIterator() - Recupera um iterator externo

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a node specified by index

  • « DOMNodeList::getIterator
  • DOMNotation »
  • PHP Manual
  • DOMNodeList
  • Retrieves a node specified by index

DOMNodeList::item

(PHP 5, PHP 7, PHP 8)

DOMNodeList::item — Retrieves a node specified by index

Descrição

public DOMNodeList::item(int $index): DOMElement|DOMNode|DOMNameSpaceNode|null

Retrieves a node specified by index within the DOMNodeList object.

Dica

If you need to know the number of nodes in the collection, use the length property of the DOMNodeList object.

Parâmetros

index

Index of the node into the collection.

Valor Retornado

The node at the indexth position in the DOMNodeList, or null if that is not a valid index.

Exemplos

Exemplo #1 Traversing all the entries of the table

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$items = $doc->getElementsByTagName('entry');

for ($i = 0; $i < $items->length; $i++) {
echo $items->item($i)->nodeValue . "\n";
}

?>

Alternatively, you can use foreach, which is a much more convenient way:

<?php

foreach ($items as $item) {
echo $item->nodeValue . "\n";
}

?>

O exemplo acima produzirá:

Title
Author
Language
ISBN
The Grapes of Wrath
John Steinbeck
en
0140186409
The Pearl
John Steinbeck
en
014017737X
Samarcande
Amine Maalouf
fr
2253051209

User Contributed Notes

jeffpuckett2 at gmail dot com 15-Jun-2016 02:55
DOMNodelist::item can return a DOMElement object, which extends DOMNode class. But it can also return a DOMText object.

<?php
$xml = '
<root>
  <node/>
  <node>
    <sub>more</sub>
  </node>
  <node>
    <sub>another</sub>
  </node>
  <node>value</node>
</root>
';

$doc = new DOMDocument();
$doc->loadXML($xml);

$items = $doc->documentElement->childNodes;
for ($i = 0; $i < $items->length; $i++)
  echo get_class($items->item($i)).PHP_EOL;
?>

Results in this output:

DOMText
DOMElement
DOMText
DOMElement
DOMText
DOMElement
DOMText
DOMElement
DOMText
Anonymous 25-Jun-2012 11:36
calling domnodelist->item($i) with an index $i greater than domnodelist->length - 1 , will return the entire document, will not produce an error, and will not circle back to the start of the list.
Nagy Attila 06-Jan-2011 09:02
DOMNodeList::item does not return in constant time!

If you need to iterate over large nodelist then you'd better use standard navigation.

Instead of:

<?php
foreach ($nodelist as $node) {
    // do something
}
?>

you could do:

<?php
$node = $parentnode->firstChild;

do {
    // do something
} while ($node = $node->nextSibling);
?>
olivier dot berger at it-sudparis dot eu 21-Aug-2008 02:56
It seems that with zend.ze1_compatibility_mode on, the only way to iterate over the items list is with :
for ($i = 0; $i < $nodeList->length; ++$i) {
    $nodeName = $nodeList->item($i)->nodeName;
    $nodeValue = $nodeList->item($i)->nodeValue;
}

As other attemps failed :

for ($i = 0; $i < $nodeList->length; ++$i) {
    $node = &$nodeList->item($i);
    $nodeName = $node->nodeName;
    $nodeValue = $node->nodeValue;
}

or :
foreach ($nodeList as $node) {
    echo $node->nodeName;
    echo $node->nodeValue;
}
vinyanov at poczta dot onet dot pl 05-Jan-2008 10:12
SimpleXML has its own SPL iterator. See http://www.php.net/~helly/php/ext/spl/classSimpleXMLIterator.html . But I guess that there are none for DOM nodes. By the way, two out of three implementations I found over the Net were not recursive, so I wrote my own. Here is the snippet:

<?php

class DOMNodeListIterator implements RecursiveIterator
{
    private
        $nodes,
        $offset;

    function __construct(DOMNodeList $nodes)
    {
        return $this -> nodes = $nodes;
    }

    function rewind()
    {
        return $this -> offset = 0;
    }

    function current()
    {
        return $this -> nodes -> item($this -> offset);
    }

    function key()
    {
        return $this -> current() -> nodeName;
    }

    function next()
    {
        return $this -> offset++;
    }

    function valid()
    {
        return $this -> offset < $this -> nodes -> length;
    }

    function hasChildren()
    {
        return isset($this -> current() -> childNodes -> length) && $this -> current() -> childNodes -> length > 0;
    }

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

?>

Remember to use RecursiveIteratorIterator::SELF_FIRST flag when you create your iterator iterator.

<?php

$iterator = new DOMNodeListIterator($document -> childNodes);
$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);

?>

Should work, has just few minutes though. :)
Hayley Watson 29-Oct-2007 02:14
Keep in mind that DOMNodelists are "live" - changes to the document or node that the DOMNodelist was derived from will be reflected in the DOMNodelist. In other words, a list of a parent node's children will change if you change the parent's children!
james dot dunmore at gmai dot com 27-Jul-2007 08:57
tfg_allardyce at gmail dot com

I have had exactly this problem.

To rectify I've had to do this:
<?php
$old_element = $doc->getElementsByTagName('Element1')->item(0);
$new_element = $doc->createElement('NewElement1');

$old_element_childNodes = $old_element->childNodes;
$length = $old_element_childNodes->length;

for($i = 0; $i < $length; $i++)
{
    $oldChildren_array[] = $old_element_childNodes->item($i);
}

foreach($oldChildren_array as $old_c)
{
    $new_element->appendChild($old_c);
}
?>

Rather than this:
(which I will bug report)
<?php
$old_element = $doc->getElementsByTagName('Element1')->item(0):
$new_element = $doc->createElement('NewElement1');

foreach($old_element->childNode as $node)
{
     $new_element->appendChild($node);
}

?>

Using the latter, randomally removes the children!
Geoffrey Thubron 26-May-2007 02:47
@ tfg_allardyce at gmail dot com

You could loop through the list backwards, that way, you are only ever taking off the last item from the list, and hence wont have disrupted the order.
oliver dot christen at camptocamp dot com 13-Feb-2007 07:27
NodeList are something annoying because you can't output the content with a simple print_r, so I did a little function that add all the node to a new empty DOMDocument and output it as a string.
Have fun.

<?php

public function domNodeList_to_string($DomNodeList) {
    $output = '';
    $doc = new DOMDocument;
    while ( $node = $DomNodeList->item($i) ) {
        // import node
        $domNode = $doc->importNode($node, true);
        // append node
        $doc->appendChild($domNode);
        $i++;
    }
    $output = $doc->saveXML();
    $output = print_r($output, 1);
    // I added this because xml output and ajax do not like each others
    $output = htmlspecialchars($output);
    return $output;
}

?>


The DOMNotation class

(PHP 5, PHP 7, PHP 8)

Sinopse da classe

class DOMNotation extends DOMNode {
/* Propriedades */
public readonly string $publicId;
public readonly string $systemId;
/* Propriedades herdadas */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos herdados */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriedades

publicId

systemId

User Contributed Notes

There are no user contributed notes for this page.


The DOMParentNode interface

(PHP 8)

Resumo da Interface

interface DOMParentNode {
/* Métodos */
public append(DOMNode|string ...$nodes): void
public prepend(DOMNode|string ...$nodes): void
public replaceChildren(DOMNode|string ...$nodes): void
}

Índice

  • DOMParentNode::append — Appends nodes after the last child node
  • DOMParentNode::prepend — Prepends nodes before the first child node
  • DOMParentNode::replaceChildren — Replace children in node

User Contributed Notes

There are no user contributed notes for this page.


Appends nodes after the last child node

  • « DOMParentNode
  • DOMParentNode::prepend »
  • PHP Manual
  • DOMParentNode
  • Appends nodes after the last child node

DOMParentNode::append

(PHP 8)

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

Descrição

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

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

Parâmetros

nodes

The nodes to append. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Veja Também

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

User Contributed Notes

There are no user contributed notes for this page.


Prepends nodes before the first child node

  • « DOMParentNode::append
  • DOMParentNode::replaceChildren »
  • PHP Manual
  • DOMParentNode
  • Prepends nodes before the first child node

DOMParentNode::prepend

(PHP 8)

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

Descrição

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

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

Parâmetros

nodes

The nodes to prepend. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Veja Também

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

User Contributed Notes

There are no user contributed notes for this page.


Replace children in node

  • « DOMParentNode::prepend
  • DOMProcessingInstruction »
  • PHP Manual
  • DOMParentNode
  • Replace children in node

DOMParentNode::replaceChildren

(PHP 8 >= 8.3.0)

DOMParentNode::replaceChildren — Replace children in node

Descrição

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

Replace children in node.

Parâmetros

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

Valor Retornado

Nenhum valor é retornado.

Erros

DOM_HIERARCHY_REQUEST_ERR

Emitido se este nó é de um tipo que não permite filhos do tipo de um dos nodes informados, ou se o nó a ser inserido é um dos ancestrais deste nó, ou o próprio nó.

DOM_WRONG_DOCUMENT_ERR

Emitido se um dos nodes informados foi criado a partir de um documento diferente daquele que criou este nó.

Changelog

Versão | Descrição
8.3.0 | Calling this method on a node without an owner document now works. Anteriormente, era lançada uma exceção DOMException com código DOM_HIERARCHY_REQUEST_ERR.

Exemplos

Exemplo #1 DOMParentNode::replaceChildren() example

<?php

$dom = new DOMDocument();
$dom->loadHTML('<!DOCTYPE HTML><html><p>hi</p> test <p>hi2</p></html>');

$dom->documentElement->replaceChildren('foo', $dom->createElement('p'), 'bar');
echo $dom->saveXML();
?>

O exemplo acima produzirá:

<?xml version="1.0" standalone="yes"?>
<!DOCTYPE HTML>
<html>foo<p/>bar</html>

User Contributed Notes

There are no user contributed notes for this page.


The DOMProcessingInstruction class

(PHP 5, PHP 7, PHP 8)

Sinopse da classe

class DOMProcessingInstruction extends DOMNode {
/* Propriedades */
public readonly string $target;
public string $data;
/* Propriedades herdadas */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos */
public __construct(string $name, string $value = "")
/* Métodos herdados */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriedades

target

data

Índice

  • DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DOMProcessingInstruction object

  • « DOMProcessingInstruction
  • DOMText »
  • PHP Manual
  • DOMProcessingInstruction
  • Creates a new DOMProcessingInstruction object

DOMProcessingInstruction::__construct

(PHP 5, PHP 7, PHP 8)

DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object

Descrição

public DOMProcessingInstruction::__construct(string $name, string $value = "")

Creates a new DOMProcessingInstruction object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createProcessingInstruction.

Parâmetros

name

The tag name of the processing instruction.

value

The value of the processing instruction.

Exemplos

Exemplo #1 Creating a new DOMProcessingInstruction object

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$html = $dom->appendChild(new DOMElement('html'));
$body = $html->appendChild(new DOMElement('body'));
$pinode = new DOMProcessingInstruction('php', 'echo "Hello World"; ');
$body->appendChild($pinode);
echo $dom->saveXML();

?>

O exemplo acima produzirá:

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

Veja Também

  • DOMDocument::createProcessingInstruction() - Creates new PI node

User Contributed Notes

There are no user contributed notes for this page.


The DOMText class

(PHP 5, PHP 7, PHP 8)

Introdução

The DOMText class inherits from DOMCharacterData and represents the textual content of a DOMElement or DOMAttr.

Sinopse da classe

class DOMText extends DOMCharacterData {
/* Propriedades */
public readonly string $wholeText;
/* Propriedades herdadas */
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* Métodos */
public __construct(string $data = "")
public isElementContentWhitespace(): bool
public isWhitespaceInElementContent(): bool
public splitText(int $offset): DOMText|false
/* Métodos herdados */
public DOMCharacterData::after(DOMNode|string ...$nodes): void
public DOMCharacterData::appendData(string $data): true
public DOMCharacterData::before(DOMNode|string ...$nodes): void
public DOMCharacterData::deleteData(int $offset, int $count): bool
public DOMCharacterData::insertData(int $offset, string $data): bool
public DOMCharacterData::remove(): void
public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool
public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void
public DOMCharacterData::substringData(int $offset, int $count): string|false
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Propriedades

wholeText

Holds all the text of logically-adjacent (not separated by Element, Comment or Processing Instruction) Text nodes.

Changelog

Versão | Descrição
8.0.0 | The unimplemented method DOMText::replaceWholeText() has been removed.

Índice

  • DOMText::__construct — Creates a new DOMText object
  • DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content
  • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
  • DOMText::splitText — Quebra este nó em dois nós no deslocamento 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 );
      }
    }
  }
}


Creates a new DOMText object

  • « DOMText
  • DOMText::isElementContentWhitespace »
  • PHP Manual
  • DOMText
  • Creates a new DOMText object

DOMText::__construct

(PHP 5, PHP 7, PHP 8)

DOMText::__construct — Creates a new DOMText object

Descrição

public DOMText::__construct(string $data = "")

Creates a new DOMText object.

Parâmetros

data

The value of the text node. If not supplied an empty text node is created.

Exemplos

Exemplo #1 Creating a new DOMText

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMText('root value'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>root value</root> */

?>

Veja Também

  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Thomas 27-Apr-2012 01:54
I experinced that DOMText, given a integer as only value to the constructor failed to return valid data. I had to typecast the input to a string first:

$intValue = 3252; // Post/Zip-code
$some_element->appendChild( new DOMText( (string) $intValue) );

When not typecasting using "(string)" the XML output from $root->saveXML() would not validate.


Returns whether this text node contains whitespace in element content

  • « DOMText::__construct
  • DOMText::isWhitespaceInElementContent »
  • PHP Manual
  • DOMText
  • Returns whether this text node contains whitespace in element content

DOMText::isElementContentWhitespace

(Não há informação de versão disponível, talvez apenas no Git)

DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content

Descrição

public DOMText::isElementContentWhitespace(): bool

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

User Contributed Notes

riking 28-Jun-2018 12:17
This is the recommended (W3C) function name for the equivalent:
http://php.net/manual/en/domtext.iswhitespaceinelementcontent.php

See there for additional notes.


Indicates whether this text node contains whitespace

  • « DOMText::isElementContentWhitespace
  • DOMText::splitText »
  • PHP Manual
  • DOMText
  • Indicates whether this text node contains whitespace

DOMText::isWhitespaceInElementContent

(PHP 5, PHP 7, PHP 8)

DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace

Descrição

public DOMText::isWhitespaceInElementContent(): bool

Indicates whether this text node contains only whitespace or it is empty. The text node is determined to contain whitespace in element content during the load of the document.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns true if node contains zero or more whitespace characters and nothing else. Returns false otherwise.

User Contributed Notes

JITR 07-Jul-2007 03:36
To add to `permidion at yahoo dot com''s comment:

Quite true. According to DOM Level 3 Core, the `isWhitespaceInElementContent()' method indicates, whether the node contains `whitespace in element content' (or `element content whitespace' according to the newer spec), see [1].

Btw, it seems the `isWhitespaceInElementContent()' method was replaced with the `isElementContentWhitespace' attribute in the current W3C recommendation, see [2].

I have the feeling, though, it would be more precise with the word `only' added, like: `... indicates, whether the node contains *only* element content whitespace.' This would better correspond with the fact the result is false, when there are any non-whitespace characters present (in addition to the whitespace ones), as already noted.

[1] (please concatenate the following two lines)
http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html
#core-Text3-isWhitespaceInElementContent
[2] (please concatenate the following two lines)
http://www.w3.org/TR/DOM-Level-3-Core/core.html
#Text3-isElementContentWhitespace
permidion at yahoo dot com 28-Oct-2004 08:30
if you have an xml element such as <name>Foo Bar</name> (note the space), isWhitespaceInElementContent will return false.
However it will return true for <name><name> or <name/>
so, that function can be used to determine if the element has a text content or not


Quebra este nó em dois nós no deslocamento especificado

  • « DOMText::isWhitespaceInElementContent
  • DOMXPath »
  • PHP Manual
  • DOMText
  • Quebra este nó em dois nós no deslocamento especificado

DOMText::splitText

(PHP 5, PHP 7, PHP 8)

DOMText::splitText — Quebra este nó em dois nós no deslocamento especificado

Descrição

public DOMText::splitText(int $offset): DOMText|false

Quebra este nó em dois no offset especificado, mantendo ambos na árvore como irmãos.

Depois de dividido, esse nó conterá todo o conteúdo até o offset. Se o nó original tinha um nó pai, o novo nó será inserido como o próximo irmão do nó original. Quando o offset for igual ao tamanho desse nó, o novo nó não terá dados.

Parâmetros

offset

O deslocamento para dividir, começando em 0.

Valor Retornado

O novo nó do mesmo tipo, que contém todo o conteúdo durante e após o offset.

User Contributed Notes

Flix Cloutier 28-Oct-2013 05:31
It should be noted that $offset is a **character offset**, not a **byte offset**. This means that most other PHP string functions that deal with lengths and offsets (strlen, strpos, preg_match with PREG_OFFSET_CAPTURE, etc.) use and return values unsuitable for this method if used with multibyte strings (like UTF-8 strings).

Byte offsets can be converted to character offsets with mb_strlen:

<?php
function char_offset($string, $byte_offset, $encoding = null)
{
    $substr = substr($string, 0, $byte_offset);
    return mb_strlen($substr, $encoding ?: mb_internal_encoding());
}
?>


The DOMXPath class

(PHP 5, PHP 7, PHP 8)

Introdução

Supports XPath 1.0

Sinopse da classe

class DOMXPath {
/* Propriedades */
public readonly DOMDocument $document;
public bool $registerNodeNamespaces;
/* Métodos */
public __construct(DOMDocument $document, bool $registerNodeNS = true)
public evaluate(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed
public query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed
public registerNamespace(string $prefix, string $namespace): bool
public registerPhpFunctions(string|array|null $restrict = null): void
}

Propriedades

document

registerNodeNamespaces

When set to true, namespaces in the node are registered.

Changelog

Versão | Descrição
8.0.0 | The registerNodeNamespaces property has been added.

Índice

  • DOMXPath::__construct — Creates a new DOMXPath object
  • DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible
  • DOMXPath::query — Evaluates the given XPath expression
  • DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object
  • DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions

User Contributed Notes

TechNyquist 08-Jan-2020 09:16
When working with XML (as a strict format) might be very important to give a namespace to XPath object in order to make it work properly.

I was experiencing "query" always returning empty node lists, it could not find anything. Only a broad "//*" was able to show off only the root element.

Then found out that registering the namespace reported in the "xmlns" attribute of the root element in the XPath object, and writing the namespace near the elements name, made it work properly.

So for an XML like this (from a sitemap):

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://example.com/index.php</loc>
        <lastmod>2005-01-01</lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>
</urlset>

I needed the following XPath configuration:

<?php

    $doc = new DOMDocument;
    $doc->load("sitemap.xml");
    $xpath = new DOMXPath($doc);
    $xpath->registerNamespace('ns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
    $nodes = $xpath->query('//ns:urlset/ns:url');

?>

Then again, that "xmlns" could be provided dynamically from the root element attribute of course.
peter at softcoded dot com 03-May-2017 05:51
You may not always know at runtime whether your file has
a namespace or not. This can make it difficult to create
XPath queries. Use the seriously underdocumented
"namespaceURI" property of the documentElement of a
DOMDocument to determine if there is a namespace.
Use code such as the following:

$doc = new DOMDocument();
$doc->load($file);
$xpath = new DOMXPath($doc);
$ns = $doc->documentElement->namespaceURI;
if($ns) {
  $xpath->registerNamespace("ns", $ns);
  $nodes = $xpath->query("//ns:em[@class='glossterm']");
} else {
  $nodes = $xpath->query("//em[@class='glossterm']");
}
//look at nodes here
peter at softcoded dot com 03-May-2017 04:46
Using XPath expressions can save a lot of programming
and allow you to home in on only the nodes you want.
Suppose you want to delete all empty <p> tags.
If you create a query using the following XPath expression,
you can find <p> tags that do not have any text
(other than spaces), any attributes,
any children or comments:

$expression = "//p[not(@*)
   and not(*)
   and not(./comment())
   and normalize-space(text())='']";

This expression will only find para tags that look like:

<p>[any number of spaces]</p>
<p></p>

Imagine the code you would have to add if you used
DOMDocument::getElementsByTagName("p") instead.
archimedix32783262 at mailinator dot com 03-Sep-2014 12:03
Note that evaluate() will use the same encoding as the XML document.

So if you have a UTF-16 XML, you will have to query using UTF-16 strings.

You can use iconv() to convert from your code's encoding to the target encoding for better legibility.
dhz 05-Jan-2011 10:47
I just spent far too much time chasing this one....

When running an xpath query on a table be careful about table internal nodes (ie: <tr></tr>, and <td></td>).  If the master <table> tag is missing, then query() (and likely evaluate() also) will return unexpected results.

I had a DOMNode with a structure like this:

<td>
    <table></table>
    <table>
        <tr>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>
</td>

Upon which I was trying to do a relative query (ie: <?php $xpath_obj->query('my/x/path', $relative_node); ?>).

But because of the lone outer <td></td> tags, the inner tags were being invalidated, while the nodes were still recognized.  Meaning that the following query would work:

<?php $xpath_obj->query('*[2]/*[*[2]]', $relative_node); ?>

But when replacing any of the "*" tokens with the corresponding (and valid) "table", "tr", or "td" tokens the query would inexplicably break.
Mark Omohundro, ajamyajax dot com 14-Dec-2008 09:15
<?php
// to retrieve selected html data, try these DomXPath examples:

$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

$xpath = new DOMXpath($doc);

// example 1: for everything with an id
//$elements = $xpath->query("//*[@id]");

// example 2: for node data in a selected id
//$elements = $xpath->query("/html/body/div[@id='yourTagIdHere']");

// example 3: same as above with wildcard
$elements = $xpath->query("*/div[@id='yourTagIdHere']");

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>[". $element->nodeName. "]";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}
?>


Creates a new DOMXPath object

  • « DOMXPath
  • DOMXPath::evaluate »
  • PHP Manual
  • DOMXPath
  • Creates a new DOMXPath object

DOMXPath::__construct

(PHP 5, PHP 7, PHP 8)

DOMXPath::__construct — Creates a new DOMXPath object

Descrição

public DOMXPath::__construct(DOMDocument $document, bool $registerNodeNS = true)

Creates a new DOMXPath object.

Parâmetros

document

The DOMDocument associated with the DOMXPath.

User Contributed Notes

thsoft at vipmail dot hu 04-Jul-2007 04:57
As of PHP 5.2.0, DOMXPath object implements XPath 1.0.
Saulo Vallory 26-Jun-2007 03:23
The DOMXPath object doesn't create a reference to the document. If you load a new xml using either load, loadXML or loadHTML functions the DOMXPath object will still query and evaluate over the source in the DOMDocument when it was created.


Evaluates the given XPath expression and returns a typed result if possible

  • « DOMXPath::__construct
  • DOMXPath::query »
  • PHP Manual
  • DOMXPath
  • Evaluates the given XPath expression and returns a typed result if possible

DOMXPath::evaluate

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

DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible

Descrição

public DOMXPath::evaluate(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed

Executes the given XPath expression and returns a typed result if possible.

Parâmetros

expression

The XPath expression to execute.

contextNode

The optional contextNode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

Valor Retornado

Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression.

If the expression is malformed or the contextNode is invalid, DOMXPath::evaluate() returns false.

Exemplos

Exemplo #1 Getting the count of all the english books

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'count(row/entry[. = "en"])';

$entries = $xpath->evaluate($query, $tbody);
echo "There are $entries english books\n";

?>

O exemplo acima produzirá:

There are 2 english books

Veja Também

  • DOMXPath::query() - Evaluates the given XPath expression

User Contributed Notes

danny at webdevelopers dot eu 28-Jan-2020 11:36
The only way how to distinguish FALSE returned value from syntax error FALSE is to re-run the XPath expression wrapped in string() function. If must return empty string. If it returns FALSE again then it is an error.

<?php

        $ret=$this->xp->evaluate($eval, $context);

        // Error detection: DOMXPath::evaluate() returns FALSE on error
        // so does DOMXPath::evaluate("boolean(/nothing)")
        // @workaround webdevelopers.eu
        if ($ret === false && $this->xp->evaluate("string($eval)", $context) === false) {
            throw new Exception("Invalid XPath expression ".json_encode($eval), 3491);
        }
?>
aazaharov81 at gmail dot com 14-Jan-2015 12:48
To query DOMNodes by their HTML classes, use such snippet
<?php

// CssClassXPathSelector
function ccxs($class) {
    return '[contains(concat(" ", normalize-space(@class), " "), " ' . $class . ' ")]';
}

 // then just
 $domitems = $this->xpath("//*[@id='searchResultsRows']//a" . ccxs('listing_row'));
?>
daniel at danielnorton dot com 25-Jun-2011 09:56
Note that this method does not provide any means to distinguish between a successful result that returns FALSE and an error.

For example, this will succeed and return FALSE:

<?php $xpath->evaluate("1 = 0"); ?>

One workaround when you know you are expecting a Boolean is to wrap the result with string(). e.g.

<?php $xpath->evaluate("string(1 = 0)"); ?>

This will return a string "false" on success, or the Boolean FALSE on error.
Damien Bezborodov 28-Mar-2011 06:13
If your expression returns a node set, you will get a DOMNodeList instead of a typed result. Instead, try modifying your expression from "//node[1]" to "string(//node[1])".
yuriucsal at NOSPAM dot yahoo dot com dot br 06-Mar-2005 12:55
this class can substitute the method evaluate while it is not validated. Made for Yuri Bastos and Jo?o Gilberto Magalh?es.

<?php

    class XPtahQuery
    {
        // function returns a DOMNodeList from a relative xPath
        public static function selectNodes($pNode, $xPath)
        {

            $pos = strpos(self::getFullXpath($pNode),"/",1);
            $xPathQuery = substr(self::getFullXpath($pNode),$pos);//to paste  /#document[1]/
            $xPathQueryFull = $xPathQuery. $xPath;
            $domXPath = new DOMXPath($pNode->ownerDocument);
            $rNodeList = $domXPath->query($xPathQueryFull);

                return $rNodeList;
        }
        // function returns a DOMNode from a xPath from other DOMNode
        public static function selectSingleNode($pNode, $xPath)
        {

            $pos = strpos(self::getFullXpath($pNode),"/",1);
            $xPathQuery = substr(self::getFullXpath($pNode),$pos);//to paste  /#document[1]/
            $xPathQueryFull = $xPathQuery. $xPath;
            $domXPath = new DOMXPath($pNode->ownerDocument);
            $rNode = $domXPath->query($xPathQueryFull)->item(0);

                return $rNode;
        }
        //utilitaries functions off selectSingleNode
        private function getNodePos($pNode, $nodeName)
        {
            if($pNode == null)
                {
                        return 0;
            }
            else
            {
                $var = 0;
                    if ($pNode->previousSibling != null)
                    {
                    if ($pNode->previousSibling->nodeName == $nodeName)
                    {
                        $var = 1;
                    }
                    }
                    return self::getNodePos($pNode->previousSibling, $nodeName) + $var;
            }
        }
        //utilitaries functions off selectSingleNode
        private function getFullXpath($pNode)
        {
            if($pNode == null)
                {
                        return "";
            }
            else
            {

                return self::getFullXpath($pNode->parentNode) . "/" . $pNode->nodeName . "[" .strval(self::getNodePos($pNode, $pNode->nodeName)+1) . "]";//+1 to get the real xPath index

            }
        }
    }
?>


Evaluates the given XPath expression

  • « DOMXPath::evaluate
  • DOMXPath::registerNamespace »
  • PHP Manual
  • DOMXPath
  • Evaluates the given XPath expression

DOMXPath::query

(PHP 5, PHP 7, PHP 8)

DOMXPath::query — Evaluates the given XPath expression

Descrição

public DOMXPath::query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed

Executes the given XPath expression.

Parâmetros

expression

The XPath expression to execute.

contextNode

The optional contextNode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

Valor Retornado

Returns a DOMNodeList containing all nodes matching the given XPath expression. Any expression which does not return nodes will return an empty DOMNodeList.

If the expression is malformed or the contextNode is invalid, DOMXPath::query() returns false.

Exemplos

Exemplo #1 Getting all the english books

<?php

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// We start from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
" by {$entry->previousSibling->nodeValue}\n";
}
?>

O exemplo acima produzirá:

Found The Grapes of Wrath, by John Steinbeck
Found The Pearl, by John Steinbeck

We can also use the contextNode parameter to shorten our expression:

<?php

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'row/entry[. = "en"]';

$entries = $xpath->query($query, $tbody);

foreach ($entries as $entry) {
echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
" by {$entry->previousSibling->nodeValue}\n";
}
?>

Veja Também

  • DOMXPath::evaluate() - Evaluates the given XPath expression and returns a typed result if possible

User Contributed Notes

chris dot russo99 at gmail dot com 17-Aug-2016 03:58
If you can't find a solution for PHP XPATH case sensitivity, you can always try this approach:

http://fsockopen.com/php-programming/your-final-stop-for-php-xpath-case-insensitive

Instead of inserting PHP functions into a XPATH object, convert the XPATH object into an Array(), and then use any PHP function, the regular way.
ikmahesh at cdac dot in 08-Jul-2015 09:29
The parameters for $xPath->query() method is case sensitive.
It matches IDs exact words.
RiKdnUa at mail dot ru 17-Sep-2013 04:26
?????? XPath ??????? ? XML ?????????. XML ???????? ????????? ???????? ? ??????? ?? ??????????? ???????? (?????????). ??? ????????????? ? XPath ??????? ?????????, ??????? DOMXPath::query() ?????? ?????????????? ? ?????? ?? ????????. ????? ?????? ???????, ???? ???? ????????? ???. ???? ????? ??????? ?????? ???? ? ????????? WINDOWS-1251. ?????????? ? PHP 5.2.9-2 ? PHP 5.2.17

Example XPath-query to the XML-document. XML-document contains an elements with the names of non-Latin characters (cyrillic). When used predicate in XPath-query, function DOMXPath::query() gives a warning and query does not work. In order to earned the query, it is necessary to explicitly specify the axis. The file of this example is to be in the encoding WINDOWS-1251. Tested in PHP 5.2.9-2 and PHP 5.2.17
<?php
ini_set("display_errors","on");
error_reporting(-1);
function utf8encode($str){return iconv('WINDOWS-1251', 'UTF-8', $str);}
$xml="<?xml version='1.0' encoding='WINDOWS-1251'?>
<?????>
<?????? href='yandex.com'>??????</??????>
<?????? href='rik.dn.ua/fotopan.php'>?.??????</??????>
</?????>
";
$document=new domDocument();
$document->preserveWhiteSpace=false;
$document->loadXML($xml);
$domxpath=new domXpath($document);
$list=$domxpath->query(utf8encode('/child::?????/child::??????'));//Ok
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/?????/??????'));//Ok
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/child::?????/child::??????[position()=1]'));//Ok
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/?????/??????[1]'));//Warning: DOMXPath::query() [domxpath.query]: Invalid expression in ...
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/?????/??????[position()=1]'));//Warning: DOMXPath::query() [domxpath.query]: Invalid expression in ...
echo '$list->length='.$list->length."\n<br/>\n";
?>
info at syncgw dot com 22-Sep-2011 09:05
A warning to all PHP programmer using this function PHP 5.0.0.0: We needed an equivalent to upper-case() function (is not available in XPath 1.0).

XML-Document:

<Rec>
<SourceRef>./c:calendar2</SourceRef>
<SourceRef>./c:calendar</SourceRef>
</Rec>

using

query('//DataStore[translate(SourceRef,"abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ")="./C:CALENDAR"]/.')

returns ZERO matches.

If you change XML-Source to

<Rec>
<SourceRef>./c:calendar</SourceRef>
<SourceRef>./c:calendar2</SourceRef>
</Rec>

everything works fine
yuriscom at gmail dot com 07-Sep-2011 10:29
I hope it will be helpful for someone:

I spent some time to solve the problem when you query a string with quotes inside.

Suppose you have:
$parameter = "aaa \"bbb\"";
$domxpath->query("//path[text()=\"".$parameter."\""];

In versions > 5.3.0 there is registerPhpFunctions where you can put an addslashes. But in older version you cannot do it in simple way.

So the solution is to use a concat function. So when you have a substring with " inside, wrap it with '. And when you have a substring with ', then wrap with in ".

The code is:

<?php
$dom = new DOMDocument;
$dom->loadXML("<name>'bla' \"bla\" bla</name>");
$xpath = new DOMXPath($dom);
$nodeList = $xpath->query("//name[text()=concat(\"'bla' \" ,'\"bla\"' ,\" bla\")]");
?>

Below is the function that receives a string and returns a concat pattern for the xpath query.

<?php
    function getPattern_MQ($pattern) {
        // initiating an array of substrings
        $ar = array();
        // points to the current position in a string
        $offset = 0;
        $strlen = strlen($pattern);
        while (true) {
            // find a position of quotes
            $qPos = strpos($pattern, "\"", $offset);

            if (!$qPos) {
                // no more quotes
                $leftOver = $offset - $strlen;
                if ($leftOver < 0) {
                    $string = substr($pattern, $leftOver);
                    $ar[] = "\"" . $string . "\"";
                }
                break;
            }
            // add the whole substring before the quotes into the array
            $ar[] = "\"" . substr($pattern, $offset, ($qPos - $offset)) . "\"";
            // add the quotes wrapped with single quot
            $ar[] = "'" . substr($pattern, $qPos, 1) . "'";
            $offset = $qPos + 1;
        }
        // join the array to get: concat("aaa",'"',"bbb",'"');
        $pattern = "concat(''," . join(",", $dynamicPatternsAr) . ")";
        return $pattern;
    }
?>
chris AT cmbuckley DOT co DOT uk 14-Apr-2011 07:31
To help with the problem where the default namespace is not registered with the DOMXPath object, you can use the following replacement to update your paths accordingly:

<?php

$xml = <<<EOS
<root xmlns="urn:test">
    <foo>bar</foo>
</root>
EOS;

$expression = '//foo';
$prefix = 'fakeprefix';

$doc = new DOMDocument();
$doc->loadXML($xml);

$context = $doc->documentElement; // or whichever element you choose
$xpath = new DOMXPath($doc);

// register namespace as below, and apply a regex to the expression
if (null !== $context->namespaceURI) {
    $xpath->registerNamespace($prefix, $context->namespaceURI);
    $expression = preg_replace('#(::|/\s*|\A)(?![/@].+?|[a-z\-]+::)#', '$1' . $prefix . ':$2', $expression);
    var_dump($expression); // string(16) "//fakeprefix:foo"
}

$foo = $xpath->query($expression, $context)->item(0);
var_dump($doc->saveXML($foo)); // string(14) "<foo>bar</foo>"

?>
kkez at example dot com 03-Sep-2010 07:51
If the query() function seems to ignore your $contextnode, and instead returns all the tags in the document, try to use a relative path (use a . in front of the query):

<?php
    $xml = "<?xml version='1.0' encoding='UTF-8'?>
        <test>
            <tag1>
                <uselesstag>
                    <tag2>test</tag2>
                </uselesstag>
            </tag1>
            <tag2>test2</tag2>
        </test>";

    $dom = new DomDocument();
    $dom->loadXML($xml);
    $xpath = new DomXPath($dom);

    $tag1 = $dom->getElementsByTagName("tag1")->item(0);

    echo $xpath->query("//tag2")->length; //output 2 -> correct
    echo $xpath->query("//tag2", $tag1)->length; //output 2 -> wrong, the query is not relative
    echo $xpath->query(".//tag2", $tag1)->length; //output 1 -> correct (note the dot in front of //)
?>

See that i couldn't use $xpath->query("tag2", $tag1) as per the documentation, since "tag2" is not a direct child of "tag1".
I don't know why this note was deleted, i just tested it and it's correct.
It's not a bug, it's simply not written in the documentation.
Anonymous 27-Nov-2009 12:26
I found this useful for building page templates

<?php
$xsl = new DOMDocument;
$xsl->load('layout.xsl');

// Set the <xsl:include> href attribute, the inner stylesheet to include in this layout
$xpath = new DomXPath($xsl);
$res = $xpath->query('//xsl:include');
$res->item(0)->setAttribute('href','page.xsl');
$xsl->save('media/xsl/layout.xsl');
?>
Niklas 27-Aug-2008 02:36
For XPath escaping use the following method (of course it could be more efficient).
<?php
public function xpathescape($string)
{
$result = 'concat(';

for($i=0, $j=strlen($string); $i<$j; ++$i)
{
if($i > 0)
$result .= ",";

if($string[$i] == '\'')
$result .= "\"".$string[$i]."\"";
else
$result .= '\''.$string[$i].'\'';
}

$result .= ')';

return $result;
}
?>

Use it this way:
<php
$xpath->query('//example[sub='.xpathescape($acomplexstring).']');

?>
adam dot prall at thinkingman dot com 19-Jul-2008 09:01
If you're wondering, like I was, why your XPath queries are not returning any of the new DOMElements you create in your (X)HTML documents, and only the ones originally loaded in with (for example) loadXML(), this is why; if you're doing things right, you have registered the nameSpace 'html' after creating your DOMXPath object thus:

<?php

class XPathQueryLength {
     private $nameSpace = '';
     function __construct(DOMDocument $doc) {
          $this->xpath = new DOMXPath($this->doc);
          $this->xpath->registerNamespace(
                 'html','http://www.w3.org/1999/xhtml' );
     }
     function queryLength($query) {
          return $this->xpath->query($query)->length;
     }
}

?>

...but don't forget that when adding new elements to the above DOMDocument $doc, to use createElementNS() instead of createElement(), otherwise you'll have this problem:

<?php

//$doc is a previously loaded XHTML document containing a normal html, head and body structure
//$body is the first selected tag using $doc->getElementsByTagName('body');

$pTag = $doc->createElement('p','This is a new paragraph!');
$body->appendChild($pTag);

$xPath = new XPathQueryLength($doc);
print $xPath->queryLength('//html:p');

output: 0

print $xPath->queryLength('//p');

output: 1

?>

So do this instead:

<?php

//$doc is a previously loaded XHTML document containing a normal html, head and body structure
//$body is the first selected tag using $doc->getElementsByTagName('body');

$pTag = $doc->createElementNS('http://www.w3.org/1999/xhtml','p','This is a new paragraph!');
$body->appendChild($pTag);

$xPath = new XPathQueryLength($doc);
print $xPath->queryLength('//html:p');

output: 2

print $xPath->queryLength('//p');

output: 0

?>

The resulting XHTML file from both example scripts looks much like this:

<html>
  <head></head>
  <body>
     <p>This is a hardcoded paragraph.</p>
     <p>This is a new paragraph!</p>
  </body>
</html>

...so you would think that a paragraph is a paragraph is a paragraph, since you never see the prefix, as in "<html:p>This is a new paragraph!</html:p>".

This may seem glaringly obvious, but I was writing a class that converts CSS queries into XPath queries, and the fact that a namespace had been registered was rather buried in the code.

We love the DOM, the DOM is good to us.
Nibinaear 03-Mar-2008 06:15
I've searched the entire web looking for a way to update / modify/ change/ alter the elements of an xml file and found NOTHING!

So here it is, the defninitive way to "Change XML elements with PHP" rather than adding / appending new ones. This uses XPATH:

<?php

// Create a DOMDocument instance
$xml = new DOMDocument;

// Ignore whitespace between nodes (default: true)
$xml->preserveWhiteSpace = false;

$file='about.xml';

// Load the XML data source
$xml->Load($file);

$xpath = new DOMXPath($xml);

$query='/regions/branch';

$entries = $xpath->query($query);

foreach ($entries as $entry)
{
  $entry->firstChild->nodeValue="like this!";
  echo $entry->firstChild->nodeValue;
}

$xml->save($file);

?>
ondrej dot fischer at 4internet dot cz 25-Oct-2007 06:46
Unfortunately PHP's DOM extension doesn't support use of:
<?xml-stylesheet type="text/xsl" ... ?>
processing instruction.
Here is an example, how to implement it using XPath query and extending DOMDocument by a method output().

<?php

// This simple function adds missing direct usage of anonymous instances
// in PHP5's reference model
function a($var) {
   return $var;
}

// Extended DOMDocument class
class MyDOMDocument extends DOMDocument
{

   public function output()
   {
      $stylesheets = array();
      $PIs = a(new DOMXPath($this))
                  ->query('/processing-instruction("xml-stylesheet")');

      foreach($PIs as $PI)
      {
         // This might be implemented cleaner by regular parsing
         // of DOMProcessingInstruction::data property
         if(ereg('type *= *"text/xsl" +href *= *"([^"]+)"', $PI->data, $mem))
         {
            // Here should be verified, that XSL file exists.
            a($stylesheets[] = new DOMDocument())->load($mem[1]);
         }
      }

      if($stylesheets)
      {
         $processor = new XSLTProcessor();
         foreach($stylesheets as $stylesheet)
            $processor->importStylesheet($stylesheet);
         return $processor->transformToDoc($this);
      }
      // If no stylesheet instructions present, return self directly
      else return $this;

   }
}

?>

Usage:

<?php

$document = new MyDOMDocument();
$document->load('my.xml');
echo $document->output()->saveXML();

?>

With following file my.xml:

<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="my.xsl" ?>
<my-root />

and existing file my.xsl that code will transform the xml file using my.xsl and output the result.
jbarnett at flowershopnetwork dot com 11-Sep-2007 01:46
The order of nodes in the return value is not guaranteed.

When my code was on an old server, the returned DOMNodeList was in document order.  On the new server, the returned DOMNodeList is in a consistent order, but it is not in document order.

PHP passes this function call off to the xmlXPathEvalExpression() function in libxml.  That function in libxml only accepts two arguments - the same two this PHP function accepts.  There must have been a change in the libxml version from the old server to the new server, and that libxml behaves differently.

This would be okay if PHP had a way to compare nodes so I can resort the nodes manually, but there is not.

So, there is no guaranteed way to get an ordered list of nodes like DOM 3 XPath provides.
Hayley Watson 12-Aug-2007 05:43
Note that if your DOMDocument was loaded from HTML, where element and attribute names are case-insensitive, the DOM parser converts them all to lower-case, so your XPath queries will have to as well; '//A/@HREF' won't find anything even if the original HTML contained "<A HREF='example.com'>".
nicolas_rainardNOSPAM at yahoo dot fr 10-Jul-2007 02:04
Please note that what clochix says is valid for *any* document which has a default namespace (as it is the case for XHTML).

This document :

<?xml version="1.0" encoding="UTF-8" ?>

<root xmlns="http://www.exemple.org/namespace">

    <element id="1">
    ...
    </element>

    <element id="2">
    ...
    </element>

</element>

must be accessed this way :

$document = new DOMDocument();
$document->load('document.xml');

$xpath = new DOMXPath($document);
$xpath->registerNameSpace('fakeprefix', 'http://www.exemple.org/namespace');

$elements = $xpath->query('//fakeprefix:element');

Of course, there is no prefix in the original document, but the DOMXPath class *needs* one, whatever it is, if you use a default namespace. It *doesn't work* if you specify an empty prefix like this :

$xpath->registerNameSpace('', 'http://www.exemple.org/namespace');

Hope this help to spare some time...
clochix at clochix dot net 01-Mar-2007 04:05
If you want to perform queries on XHTML documents, you must fix a default namespace:

<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = true;
$doc->resolveExternals = true; // for character entities
$doc->load("http://www.w3.org/");
$xpath = new DOMXPath($doc);
// won't work
$entries = $xpath->query("//div");
// you should use :
$xpath->registerNamespace("html", "http://www.w3.org/1999/xhtml");
$entries = $xpath->query("//html:div");
?>
jakob dot voss at nichtich dot de 14-Nov-2005 12:33
You can transform the result nodes into new DOMDocument objects this way:

<?php
$result = $xpath->query($query);
$resultNode = $result->item(0);
$newDom = new DOMDocument;
$newDom->appendChild($newDom->importNode($resultNode,1));

print "<pre>" . htmlspecialchars($newDom->saveXML()) . "</pre>";
?>
Eric Hanson 12-Jul-2005 05:40
Two great XPath references follow.

XPath in Five Paragraphs (finally!):
http://www.rpbourret.com/xml/XPathIn5.htm

The w3c spec actually has a bunch of helpful examples:
http://www.w3.org/TR/xpath#location-paths


Registers the namespace with the DOMXPath object

  • « DOMXPath::query
  • DOMXPath::registerPhpFunctions »
  • PHP Manual
  • DOMXPath
  • Registers the namespace with the DOMXPath object

DOMXPath::registerNamespace

(PHP 5, PHP 7, PHP 8)

DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object

Descrição

public DOMXPath::registerNamespace(string $prefix, string $namespace): bool

Registers the namespace and prefix with the DOMXPath object.

Parâmetros

prefix

The prefix.

namespace

The URI of the namespace.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

User Contributed Notes

igor dot pellegrini at diespam-berlinonline dot de 10-Mar-2015 07:32
The documentation is not really detailed.
Probably someone is also interested in the possibility of unregistering the namespace.

Worths to note that the original libxml function "xmlXPathRegisterNs()"

* Does NOT accept NULL or empty string for the argument "$prefix".

   and

* Unregisters the namespace if the "$namespaceURI" argument is NULL.

Here the documentation:
http://xmlsoft.org/html/libxml-xpathInternals.html#xmlXPathRegisterNs
xmedeko at gmail dot com 20-Sep-2011 04:58
A general way to register the root default namespace:

<?php
$xml = new DomDocument();
$xml->load('data.xml');
$xpath = new DOMXPath($xml);
$rootNamespace = $xml->lookupNamespaceUri($xml->namespaceURI);
$xpath->registerNamespace('x', $rootNamespace);
?>

And then just query:

<?php $elementList = $xpath->query('//x:items/x:name'); ?>
dulao5 at gmail dot com 16-Jun-2009 12:01
The following code can work for XML default namespace.
<?php
$xml = <<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:other="http://other.w3.org/other" >
        <id>uYG7-sPwjFg</id>
        <published>2009-05-17T18:29:31.000Z</published>
</entry>
EOT;

$doc = new DOMDocument;
$doc->loadXML($xml);
$xpath =  DOMXPath($doc);

$xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");

$xpath_str = '//atom:entry/atom:published/text()';

$entries = $xpath->evaluate($xpath_str);

print $entries->item(0)->nodeValue ."\n";

?>
agent009 31-Mar-2009 04:55
Ok, here's a function that extends XPath syntax with the following special characters:

~ inserts default namespace prefix if defined

# shorthand for text()

% shorthand for comment()

$ shorthand for node()

?* shorthand for processing-instruction()

?foo shorthand for processing-instruction("foo")

? shorthand for processing-instruction("")

^ escapes following character (with literal or SGML entity as needed)

All of the above except ^ are ignored within quoted strings

<?php
function extendXPath($str, $defns = NULL) {
   $quote = false;
   $map = array(
      '~' => isset($defns) ? "$defns:" : '',
      '#' => 'text()',
      '%' => 'comment()',
      '$' => 'node()'
   );
   $out = '';

   for ($i = 0, $len = strlen($str); $i < $len; $i++) {
      $c = $str[$i];
      if (!$quote && array_key_exists($c, $map)) {
         $out .= $map[$c];
      } else switch ($c) {
         case '^':
            $out .= htmlspecialchars($str[++$i], ENT_QUOTES);
            break;
         case '?':
            if ($quote) {
               $out .= $c;
            } elseif ($str[$i + 1] == '*') {
               $out .= 'processing-instruction()';
               $i++;
            } else {
               preg_match('/^\w+/', substr($str, $i + 1), $matches);
               $out .= 'processing-instruction("'.$matches[0].'")';
               $i += strlen($matches[0]);
            };
            break;
         case '"':
            $quote = !$quote;
         default:
            $out .= $c;
      };
   };

   return $out;
}
?>
cameron kellough 14-Apr-2007 10:33
This is called prefix mapping and it is necessary to use xpath to handle documents which have default namespaces. //root/item will search for items with no namespace, not items with the namespace described as the default in the xmlns declaration.  This problem is maddening as it just looks on the surface like xpath isn't working.
spam at spam dot spam 31-Mar-2005 12:46
It is mentioned in a few places on the web, but it wasn't mentioned here. You need to use this function to set up a prefix for the default namespace of a document.

For instance, if you are trying to parse a Microsoft Spreadsheet XML file, which has the default namespace of "urn:schemas-microsoft-com:office:spreadsheet":

$doc = DOMDocument::load("my_spreadsheet.xml);
$xpath = new DOMXPath($doc);
$xpath->registerNamespace("m",
        "urn:schemas-microsoft-com:office:spreadsheet");
$query = '/m:Workbook/m:Worksheet[1]/m:Table';
$result = $xpath->query($query, $doc);

You can use anything in place of the 'm', but you have to specify something! Just asking for "/Workbook/Worksheet/Table" doesn't work.


Register PHP functions as XPath functions

  • « DOMXPath::registerNamespace
  • DOM Funções »
  • PHP Manual
  • DOMXPath
  • Register PHP functions as XPath functions

DOMXPath::registerPhpFunctions

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

DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions

Descrição

public DOMXPath::registerPhpFunctions(string|array|null $restrict = null): void

This method enables the ability to use PHP functions within XPath expressions.

Parâmetros

restrict

Use this parameter to only allow certain functions to be called from XPath.

This parameter can be either a string (a function name) or an array of function names.

Valor Retornado

Nenhum valor é retornado.

Exemplos

The following examples use book.xml which contains the following:

Exemplo #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>

Exemplo #2 DOMXPath::registerPHPFunctions() with php:functionString

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

$xpath = new DOMXPath($doc);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (no restrictions)
$xpath->registerPHPFunctions();

// Call substr function on the book title
$nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');

echo "Found {$nodes->length} books starting with 'PHP':\n";
foreach ($nodes as $node) {
$title = $node->getElementsByTagName("title")->item(0)->nodeValue;
$author = $node->getElementsByTagName("author")->item(0)->nodeValue;
echo "$title by $author\n";
}

?>

O exemplo acima produzirá algo semelhante a:

Found 2 books starting with 'PHP':
PHP Basics by Jim Smith
PHP Secrets by Jenny Smythe

Exemplo #3 DOMXPath::registerPHPFunctions() with php:function

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

$xpath = new DOMXPath($doc);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (has_multiple only)
$xpath->registerPHPFunctions("has_multiple");

function has_multiple($nodes) {
// Return true if more than one author
return count($nodes) > 1;
}
// Filter books with multiple authors
$books = $xpath->query('//book[php:function("has_multiple", author)]');

echo "Books with multiple authors:\n";
foreach ($books as $book) {
echo $book->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}

?>

O exemplo acima produzirá algo semelhante a:

Books with multiple authors:
PHP Basics

Veja Também

  • DOMXPath::registerNamespace() - Registers the namespace with the DOMXPath object
  • DOMXPath::query() - Evaluates the given XPath expression
  • DOMXPath::evaluate() - Evaluates the given XPath expression and returns a typed result if possible

User Contributed Notes

There are no user contributed notes for this page.


DOM Funções

Índice

  • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

User Contributed Notes

There are no user contributed notes for this page.


Gets a DOMElement object from a SimpleXMLElement object

  • « DOM Funções
  • libxml »
  • PHP Manual
  • DOM Funções
  • Gets a DOMElement object from a SimpleXMLElement object

dom_import_simplexml

(PHP 5, PHP 7, PHP 8)

dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

Descrição

dom_import_simplexml(object $node): DOMElement

This function takes the node node of class SimpleXML and makes it into a DOMElement node. This new object can then be used as a native DOMElement node.

Parâmetros

node

The SimpleXMLElement node.

Valor Retornado

The DOMElement node added.

Changelog

Versão | Descrição
8.0.0 | This function no longer returns null on failure.

Exemplos

Exemplo #1 Import SimpleXML into DOM with dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

if ($sxe === false) {
echo 'Error while parsing the document';
exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
echo 'Error while converting XML';
exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

?>

Veja Também

  • simplexml_import_dom() - Recebe um objeto SimpleXMLElement de um nó 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

  • Introdução
  • Instalação/Configuração
    • Dependências
    • Instalação para versões do PHP >= 7.4
    • Instalação para versões do PHP < 7.4
    • Configurações em Execução
    • Tipos de Recurso
  • Constantes pré-definidas
  • libXMLError — The libXMLError class
  • Funções da libxml
    • libxml_clear_errors — Limpa o buffer de erro da libxml
    • libxml_disable_entity_loader — Disable the ability to load external entities
    • libxml_get_errors — Obtém um array de erros
    • libxml_get_external_entity_loader — Get the current external entity loader
    • libxml_get_last_error — Obtém o último erro da libxml
    • libxml_set_external_entity_loader — Changes the default external entity loader
    • libxml_set_streams_context — Define o contexto de fluxos para o próximo carregamento ou escrita de documento libxml
    • libxml_use_internal_errors — Desabilita erros da libxml e permite que o usuário obtenha informações de erro conforme necessário

User Contributed Notes

There are no user contributed notes for this page.


Introdução

Estas funções/constantes estão disponíveis a partir do PHP 5.1.0, e as seguintes extensões do núcleo dependem desta extensão libxml: DOM, libxml, SimpleXML, SOAP, WDDX, XSL, XML, XMLReader, XMLRPC e XMLWriter.

User Contributed Notes

There are no user contributed notes for this page.


Instalação/Configuração

Índice

  • Dependências
  • Instalação para versões do PHP >= 7.4
  • Instalação para versões do PHP < 7.4
  • Configurações em Execução
  • Tipos de Recurso

User Contributed Notes

There are no user contributed notes for this page.


Dependências

Esta extensão requer » libxml >= 2.9.0 a partir do PHP 8.0. libxml >= 2.6.0 antes do PHP 8.0.

User Contributed Notes

There are no user contributed notes for this page.


Instalação para versões do PHP >= 7.4

A extensão libxml está habilitada por padrão, embora possa ser desabilitada com --without-libxml.

O PHP usa pkg-config para selecionar o arquivos correto de biblioteca e cabeçalhos, e as opções de compilação a serem usadas para libxml2. Para assegurar-se de que a versão pretendida da libxml2 está selecionada, a variável de ambiente PKG_CONFIG_PATH pode ser usada para controlar o caminho de pesquisa para pkg-config antes de executar o script de configuração:

PKG_CONFIG_PATH="/path/to/libxml2/prefix/lib/pkgconfig:/lib/pkgconfig"

User Contributed Notes

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


Instalação para versões do PHP < 7.4

A extensão libxml está habilitada por padrão, embora possa ser desabilitada com --disable-libxml.

A diretiva opcional --with-libxml-dir é usada para especificar a localização da libxml no sistema onde o PHP está sendo compilado, caso contrário apenas a localicação padrão é pesquisada. O processo configure pesquisa pela libxml (especificamente, xml2-config) na seguinte ordem:

  1. A localização ([DIR]) especificada com --with-libxml-dir ([DIR]=/bin/xml2-config)

  2. /usr/local/bin/xml2-config

  3. /usr/bin/xml2-config

Se configure não puder encontrar xml2-config no diretório especificado por --with-libxml-dir, ele continuará e pesquisará nas localizações padrões.

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-definidas

As contantes abaixo são definidas por esta extensão e só estarão disponíveis quando a extensão tiver sido compilada no PHP ou tiver sido carregada dinamicamente em tempo de execução.

LIBXML_BIGLINES (int)
Permite que números de linha maiores que 65535 sejam reportados corretamente.

Nota:

Disponível somente a partir do PHP 7.0.0 com Libxml >= 2.9.0

LIBXML_COMPACT (int)
Ativa a otimização de alocação de nós pequenos. Isto pode acelerar a aplicação sem a necessidade de se modificar o código.

Nota:

Somente disponível na Libxml >= 2.6.21

LIBXML_DTDATTR (int)
Atributos DTD padrões
LIBXML_DTDLOAD (int)
Carrega o subconjunto externo
LIBXML_DTDVALID (int)
Valida com o DTD
Cuidado

Habilitar a validação do DTD pode facilitar ataques do tipo XXE (Entidade Externa XML).

LIBXML_HTML_NOIMPLIED (int)
Define a opção HTML_PARSE_NOIMPLIED, que desliga a adição automática de elementos html/body... implícitos.

Nota:

Disponível somente na Libxml >= 2.7.7 (a partir do PHP >= 5.4.0)

LIBXML_HTML_NODEFDTD (int)
Define a opção HTML_PARSE_NODEFDTD, que evita que um doctype padrão seja adicionado quando um não for encontrado.

Nota:

Disponível somente na Libxml >= 2.7.8 (a partir do PHP >= 5.4.0)

LIBXML_NOBLANKS (int)
Remove nós em branco
LIBXML_NOCDATA (int)
Funde CDATA como nós de texto
LIBXML_NOEMPTYTAG (int)
Expande etiquetas vazias (ex.: <br/> para <br></br>)

Nota:

Atualmente, esta opção está disponível somente nas funções DOMDocument::save e DOMDocument::saveXML.

LIBXML_NOENT (int)
Substitui entidades
Cuidado

Habilitar dubstituição de entidade pode facilitar ataques do tipo XXE (XML External Entity).

LIBXML_NOERROR (int)
Suprime mensagens de erro
LIBXML_NONET (int)
Desabilita o acesso à rede ao carregar documentos
LIBXML_NOWARNING (int)
Suprime mensagens de alerta
LIBXML_NOXMLDECL (int)
Remove a declaração do XML ao salvar um documento

Nota:

Somente disponível na Libxml >= 2.6.21

LIBXML_NSCLEAN (int)
Remove declarações redundantes de espaço de nomes
LIBXML_PARSEHUGE (int)
Define a opção XML_PARSE_HUGE, que relaxa qualquer limite codificado do analisador. Isto afeta limites como profundidade máxima de um documento ou de recursão de entidade, assim como limites do tamanho dos nós de texto.

Nota:

Disponível somente na Libxml >= 2.7.0 (a partir do PHP >= 5.3.2 e do PHP >= 5.2.12)

LIBXML_PEDANTIC (int)
Defina a opção XML_PARSE_PEDANTIC, que habilita relatório pedantes de erros.

Nota:

Disponível a partir do PHP >= 5.4.0

LIBXML_XINCLUDE (int)
Implementa substituições XInclude
LIBXML_ERR_ERROR (int)
Um erro recuperável
LIBXML_ERR_FATAL (int)
Um erro fatal
LIBXML_ERR_NONE (int)
Sem erros
LIBXML_ERR_WARNING (int)
Um alerta simples
LIBXML_VERSION (int)
Versão da libxml como 20605 ou 20617
LIBXML_DOTTED_VERSION (string)
Versão da libxml como 2.6.5 ou 2.6.17
LIBXML_SCHEMA_CREATE (int)
Cria nós de valores padrões/fixos durante validação do esquema XSD

Nota:

Disponível somente na Libxml >= 2.6.14 (a partir do 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/>


The libXMLError class

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

Introdução

Contains various information about errors thrown by libxml. The error codes are described within the official » xmlError API documentation.

Sinopse da classe

class libXMLError {
/* Propriedades */
public int $level;
public int $code;
public int $column;
public string $message;
public string $file;
public int $line;
}

Propriedades

level

the severity of the error (one of the following constants: LIBXML_ERR_WARNING, LIBXML_ERR_ERROR or LIBXML_ERR_FATAL)

code

The error's code.

column

The column where the error occurred.

Nota:

This property isn't entirely implemented in libxml and therefore 0 is often returned.

message

The error message, if any.

file

The filename, or empty if the XML was loaded from a string.

line

The line where the error occurred.

User Contributed Notes

There are no user contributed notes for this page.


Funções da libxml

Índice

  • libxml_clear_errors — Limpa o buffer de erro da libxml
  • libxml_disable_entity_loader — Disable the ability to load external entities
  • libxml_get_errors — Obtém um array de erros
  • libxml_get_external_entity_loader — Get the current external entity loader
  • libxml_get_last_error — Obtém o último erro da libxml
  • libxml_set_external_entity_loader — Changes the default external entity loader
  • libxml_set_streams_context — Define o contexto de fluxos para o próximo carregamento ou escrita de documento libxml
  • libxml_use_internal_errors — Desabilita erros da libxml e permite que o usuário obtenha informações de erro conforme necessário

User Contributed Notes

There are no user contributed notes for this page.


Limpa o buffer de erro da libxml

  • « Funções da libxml
  • libxml_disable_entity_loader »
  • PHP Manual
  • Funções da libxml
  • Limpa o buffer de erro da libxml

libxml_clear_errors

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

libxml_clear_errors — Limpa o buffer de erro da libxml

Descrição

libxml_clear_errors(): void

libxml_clear_errors() limpa o buffer de erro da libxml.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Nenhum valor é retornado.

Veja Também

  • libxml_get_errors() - Obtém um array de erros
  • libxml_get_last_error() - Obtém o último erro da libxml

User Contributed Notes

There are no user contributed notes for this page.


Disable the ability to load external entities

  • « libxml_clear_errors
  • libxml_get_errors »
  • PHP Manual
  • Funções da libxml
  • Disable the ability to load external entities

libxml_disable_entity_loader

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

libxml_disable_entity_loader — Disable the ability to load external entities

Aviso

Esta função tornou-se OBSOLETA a partir do PHP 8.0.0. O uso desta função é fortemente desencorajado.

Descrição

libxml_disable_entity_loader(bool $disable = true): bool

Disable/enable the ability to load external entities. Note that disabling the loading of external entities may cause general issues with loading XML documents. However, as of libxml 2.9.0 entity substitution is disabled by default, so there is no need to disable the loading of external entities, unless there is the need to resolve internal entity references with LIBXML_NOENT. Generally, it is preferable to use libxml_set_external_entity_loader() to suppress loading of external entities.

Parâmetros

disable

Disable (true) or enable (false) libxml extensions (such as DOM, XMLWriter and XMLReader) to load external entities.

Valor Retornado

Returns the previous value.

Veja Também

  • libxml_use_internal_errors() - Desabilita erros da libxml e permite que o usuário obtenha informações de erro conforme necessário
  • libxml_set_external_entity_loader() - Changes the default external entity loader
  • The LIBXML_NOENT constant

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


Obtém um array de erros

  • « libxml_disable_entity_loader
  • libxml_get_external_entity_loader »
  • PHP Manual
  • Funções da libxml
  • Obtém um array de erros

libxml_get_errors

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

libxml_get_errors — Obtém um array de erros

Descrição

libxml_get_errors(): array

Obtém um array de erros.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna um array com objetos LibXMLError se houver algum erro no buffer, ou um array vazio caso contrário.

Exemplos

Exemplo #1 Um exemplo de libxml_get_errors()

Este exemplo demonstra como construir um simples manipulador de erro da libxml.

<?php

libxml_use_internal_errors(true);

$xmlstr = <<< XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<titles>PHP: Por Trás do Analisador</title>
</movie>
</movies>
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if ($doc === false) {
$errors = libxml_get_errors();

foreach ($errors as $error) {
echo display_xml_error($error, $xml);
}

libxml_clear_errors();
}

function display_xml_error($error, $xml)
{
$return = $xml[$error->line - 1] . "\n";
$return .= str_repeat('-', $error->column) . "^\n";

switch ($error->level) {
case LIBXML_ERR_WARNING:
$return .= "Alerta $error->code: ";
break;
case LIBXML_ERR_ERROR:
$return .= "Erro $error->code: ";
break;
case LIBXML_ERR_FATAL:
$return .= "Erro fatal $error->code: ";
break;
}

$return .= trim($error->message) .
"\n Line: $error->line" .
"\n Column: $error->column";

if ($error->file) {
$return .= "\n Arquivo: $error->file";
}

return "$return\n\n--------------------------------------------\n\n";
}

?>

O exemplo acima produzirá:

  <titles>PHP: Por Trás do Analisador</title>
----------------------------------------------^
Erro fatal 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46

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

Veja Também

  • libxml_get_last_error() - Obtém o último erro da libxml
  • libxml_clear_errors() - Limpa o buffer de erro da 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
  • Funções da 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

Descrição

libxml_get_external_entity_loader(): ?callable

Get external entity loader previously installed by libxml_set_external_entity_loader().

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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.

Veja Também

  • libxml_set_external_entity_loader() - Changes the default external entity loader

User Contributed Notes

There are no user contributed notes for this page.


Obtém o último erro da libxml

  • « libxml_get_external_entity_loader
  • libxml_set_external_entity_loader »
  • PHP Manual
  • Funções da libxml
  • Obtém o último erro da libxml

libxml_get_last_error

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

libxml_get_last_error — Obtém o último erro da libxml

Descrição

libxml_get_last_error(): LibXMLError|false

Obtém o último erro da libxml.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna um objeto LibXMLError se houver algum erro no buffer, false caso contrário.

Veja Também

  • libxml_get_errors() - Obtém um array de erros
  • libxml_clear_errors() - Limpa o buffer de erro da libxml

User Contributed Notes

There are no user contributed notes for this page.


Changes the default external entity loader

  • « libxml_get_last_error
  • libxml_set_streams_context »
  • PHP Manual
  • Funções da libxml
  • Changes the default external entity loader

libxml_set_external_entity_loader

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

libxml_set_external_entity_loader — Changes the default external entity loader

Descrição

libxml_set_external_entity_loader(?callable $resolver_function): bool

Changes the default external entity loader. This can be used to suppress the expansion of arbitrary external entities to avoid XXE attacks, even when LIBXML_NOENT has been set for the respective operation, and is usually preferable over calling libxml_disable_entity_loader().

Parâmetros

resolver_function

A callable with the following signature:

resolver(?string $public_id, string $system_id, array $context): resource|string|null
public_id
The public ID.
system_id
The system ID.
context
An array with the four elements "directory", "intSubName", "extSubURI" and "extSubSystem".
This callable should return a resource, a string from which a resource can be opened. If null is returned, the entity reference resolution will fail.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Exemplos

Exemplo #1 libxml_set_external_entity_loader() example

<?php
$xml = <<<XML
<!DOCTYPE foo PUBLIC "-//FOO/BAR" "http://example.com/foobar">
<foo>bar</foo>
XML;

$dtd = <<<DTD
<!ELEMENT foo (#PCDATA)>
DTD;

libxml_set_external_entity_loader(
function ($public, $system, $context) use($dtd) {
var_dump($public);
var_dump($system);
var_dump($context);
$f = fopen("php://temp", "r+");
fwrite($f, $dtd);
rewind($f);
return $f;
}
);

$dd = new DOMDocument;
$r = $dd->loadXML($xml);

var_dump($dd->validate());
?>

O exemplo acima produzirá:

string(10) "-//FOO/BAR"
string(25) "http://example.com/foobar"
array(4) {
    ["directory"]    => NULL
    ["intSubName"]   => NULL
    ["extSubURI"]    => NULL
    ["extSubSystem"] => NULL
}
bool(true)

Veja Também

  • libxml_disable_entity_loader() - Disable the ability to load external entities
  • libxml_get_external_entity_loader() - Get the current external entity loader

User Contributed Notes

There are no user contributed notes for this page.


Define o contexto de fluxos para o próximo carregamento ou escrita de documento libxml

  • « libxml_set_external_entity_loader
  • libxml_use_internal_errors »
  • PHP Manual
  • Funções da libxml
  • Define o contexto de fluxos para o próximo carregamento ou escrita de documento libxml

libxml_set_streams_context

(PHP 5, PHP 7, PHP 8)

libxml_set_streams_context — Define o contexto de fluxos para o próximo carregamento ou escrita de documento libxml

Descrição

libxml_set_streams_context(resource $context): void

Define contexto de fluxos para o próximo carregamento ou escrita de documento libxml.

Parâmetros

context

O recurso do contexto de fluxo (criado com stream_context_create())

Valor Retornado

Nenhum valor é retornado.

Exemplos

Exemplo #1 Um exemplo 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);

// solicita um arquivo por HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');

?>

Veja Também

  • stream_context_create() - Cria um contexto de fluxo

User Contributed Notes

There are no user contributed notes for this page.


Desabilita erros da libxml e permite que o usuário obtenha informações de erro conforme necessário

  • « libxml_set_streams_context
  • SimpleXML »
  • PHP Manual
  • Funções da libxml
  • Desabilita erros da libxml e permite que o usuário obtenha informações de erro conforme necessário

libxml_use_internal_errors

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

libxml_use_internal_errors — Desabilita erros da libxml e permite que o usuário obtenha informações de erro conforme necessário

Descrição

libxml_use_internal_errors(?bool $use_errors = null): bool

A função libxml_use_internal_errors() permite desabilitar os erros padrão da libxml e habilitar o tratamento de erros do usuário.

Parâmetros

use_errors

Habilita (true) ou desabilita (false) o tratamento de erros do usuário. Desabilitar também limpará quaisquer erros libxml existentes.

Valor Retornado

Esta função retorna o valor anterior de use_errors.

Changelog

Versão | Descrição
8.0.0 | O parâmetro use_errors agora pode ser nulo. Anteriormente, o padrão era false.

Exemplos

Exemplo #1 Exemplo de libxml_use_internal_errors()

Este exemplo demonstra o uso básico dos erros da libxml e o valor retornado por esta função.

<?php

// habilita o tratamento de erros do usuário
var_dump(libxml_use_internal_errors(true));

// carrega o documento
$doc = new DOMDocument;

if (!$doc->load('arquivo.xml')) {
foreach (libxml_get_errors() as $erro) {
// trata os erros aqui
}

libxml_clear_errors();
}

?>

O exemplo acima produzirá:

bool(false)

Veja Também

  • libxml_clear_errors() - Limpa o buffer de erro da libxml
  • libxml_get_errors() - Obtém um array de erros

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

  • Introdução
  • Instalação/Configuração
    • Dependências
    • Instalação
    • Configurações em Execução
    • Tipos de Recurso
  • Constantes pré-definidas
  • Exemplos
    • Basic SimpleXML usage
    • Dealing with XML errors
  • SimpleXMLElement — A classe SimpleXMLElement
    • SimpleXMLElement::addAttribute — Adiciona um atributo a elemento SimpleXML
    • SimpleXMLElement::addChild — Adiciona um elemento filho à um nó XML
    • SimpleXMLElement::asXML — Retorna uma string XML bem formada (well-formed) baseada em um elemento SimpleXML
    • SimpleXMLElement::attributes — Identifica um atributo de um elemento
    • SimpleXMLElement::children — Encontra os nós filhos de um dado nó
    • SimpleXMLElement::__construct — Cria um novo objeto SimpleXMLElement
    • SimpleXMLElement::count — Conta os filhos de um elemento
    • SimpleXMLElement::current — Returns the current element
    • SimpleXMLElement::getDocNamespaces — Retorna um namespace declarado no documento
    • SimpleXMLElement::getName — Pega o nome de um elemento XML
    • SimpleXMLElement::getNamespaces — Retorna os namespaces utilizados no 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 — Cria um prefixo/namespace de contexto para a próxima consulta XPath
    • SimpleXMLElement::rewind — Rewind to the first element
    • SimpleXMLElement::saveXML — Sinônimo de SimpleXMLElement::asXML
    • SimpleXMLElement::__toString — Retorna o conteúdo como uma string
    • SimpleXMLElement::valid — Check whether the current element is valid
    • SimpleXMLElement::xpath — Executa uma consulta XPath em dados XML
  • SimpleXMLIterator — A classe SimpleXMLIterator
  • Funções da SimpleXML
    • simplexml_import_dom — Recebe um objeto SimpleXMLElement de um nó DOM
    • simplexml_load_file — Interpreta um arquivo XML e o transforma em um objeto
    • simplexml_load_string — Interpreta uma string XML e a transforma em um 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.


Introdução

A extensão SimpleXML provê um conjunto de ferramentas fáceis e de simples utilização para converter XML em objetos que podem ser processados com seletores de propriedades e iteradores de arrays.

User Contributed Notes

There are no user contributed notes for this page.


Instalação

Esta extensão está habilitada por padrão. Ela pode ser desabilitada usando a seguinte opção em tempo de compilação: --disable-simplexml

User Contributed Notes

Rapitharian at hotmail dot com 24-Apr-2019 08:39
To install on CentOS and Redhat, run: sudo yum -y install php-xml
ottakar at freezed dot me 19-Dec-2017 09:31
This XML module is not provided on a default php (v7) install on Debian GNU/Linux stretch (9.3)
Add it with: sudo apt-get install php-xml
shashank at shankee dot com 31-May-2017 09:44
Installing simpleXml using composer:

"composer require ext-simplexml"

The extension is enabled by default in most distros. You can check the list of php modules using:

"php -m"
morel dot josh at hotmail dot com 17-Dec-2016 12:09
For Linux Ubuntu using PHP 7:
sudo apt-get install php7.0-xml


Exemplos

Índice

  • Basic SimpleXML usage
  • Dealing with XML errors

User Contributed Notes

Juan Herrera 19-Dec-2009 12:49
When using simplexml to access a element the returned object may be a SimpleXMLElement instead of a string.

Example:

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
    <cmd>login</cmd>
    <login>Richard</login>
</document>
XML;

$xml = simplexml_load_string($string);
print_r($xml);
$login = $xml->login;
print_r($login);
$login = (string) $xml->login;
print_r($login);
?>

Expected result:
----------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
Richard
Richard

Actual result:
--------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
SimpleXMLElement Object
(
    [0] => Richard
)
Richard

But this is an intended behavior. See http://bugs.php.net/bug.php?id=29500
info at accountr dot eu 05-May-2009 08:35
Instead of using  <?php eval($code) ?>

you can use this method,

<?php

$node = "node";

$XML = simplexml_load_file($file);

$text = (string)$XML->nodes->{$node}; // works
// or
$text2 = (string)$XML->{$node}->child; // also works fine

?>

I think it is much more easier instead of eval().
Kari P. 15-Aug-2008 02:17
To take care of proper error checking, one must use try-catch blocks:

<?php
try {
  $sxe = new SimpleXMLElement($xmlstring);
} catch (Exception $e) {
  echo "bad xml";
}
?>

To get rid of warnings, use @ in front of new:

<?php
try {
  $sxe = @new SimpleXMLElement($xmlstring);
} catch (Exception $e) {
  echo "bad xml";
}
?>
mike at mike-griffiths dot co dot uk 18-Apr-2008 09:11
It is important that you select the correct method of loading the XML in depending on the format of your XML file.

If you use the wrong function to load it in you will get some strange errors.


Basic SimpleXML usage

Many examples in this reference require an XML string. Instead of repeating this string in every example, we put it into a file which we include in each example. This included file is shown in the following example section. Alternatively, you could create an XML document and read it with simplexml_load_file().

Exemplo #1 Include file example.php with XML string

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El Act&#211;r</actor>
</character>
</characters>
<plot>
So, this language. It's like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
?>

The simplicity of SimpleXML appears most clearly when one extracts a string or number from a basic XML document.

Exemplo #2 Getting <plot>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

O exemplo acima produzirá:

   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.

Accessing elements within an XML document that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

Exemplo #3 Getting <line>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie->{'great-lines'}->line;
?>

O exemplo acima produzirá:

PHP solves all my web problems

Exemplo #4 Accessing non-unique elements in SimpleXML

When multiple instances of an element exist as children of a single parent element, normal iteration techniques apply.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* For each <character> node, we echo a separate <name>. */
foreach ($movies->movie->characters->character as $character) {
echo $character->name, ' played by ', $character->actor, PHP_EOL;
}

?>

O exemplo acima produzirá:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Nota:

Properties ($movies->movie in previous example) are not arrays. They are iterable and accessible objects.

Exemplo #5 Using attributes

So far, we have only covered the work of reading element names and their values. SimpleXML can also access element attributes. Access attributes of an element just as you would elements of an array.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Access the <rating> nodes of the first movie.
* Output the rating scale, too. */
foreach ($movies->movie[0]->rating as $rating) {
switch((string) $rating['type']) { // Get attributes as element indices
case 'thumbs':
echo $rating, ' thumbs up';
break;
case 'stars':
echo $rating, ' stars';
break;
}
}
?>

O exemplo acima produzirá:

7 thumbs up5 stars

Exemplo #6 Comparing Elements and Attributes with Text

To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

if ((string) $movies->movie->title == 'PHP: Behind the Parser') {
print 'My favorite movie.';
}

echo htmlentities((string) $movies->movie->title);
?>

O exemplo acima produzirá:

My favorite movie.PHP: Behind the Parser

Exemplo #7 Comparing Two Elements

Two SimpleXMLElements are considered different even if they point to the same element.

<?php
include 'example.php';

$movies1 = new SimpleXMLElement($xmlstr);
$movies2 = new SimpleXMLElement($xmlstr);
var_dump($movies1 == $movies2);
?>

O exemplo acima produzirá:

bool(false)

Exemplo #8 Using XPath

SimpleXML includes built-in XPath support. To find all <character> elements:

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

foreach ($movies->xpath('//character') as $character) {
echo $character->name, ' played by ', $character->actor, PHP_EOL;
}
?>

'//' serves as a wildcard. To specify absolute paths, omit one of the slashes.

O exemplo acima produzirá:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Exemplo #9 Setting values

Data in SimpleXML doesn't have to be constant. The object allows for manipulation of all of its elements.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$movies->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $movies->asXML();
?>

O exemplo acima produzirá:

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Miss Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>

Exemplo #10 Adding elements and attributes

SimpleXML has had the ability to easily add children and attributes.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$character = $movies->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movies->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');

echo $movies->asXML();
?>

O exemplo acima produzirá:

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  <character><name>Mr. Parser</name><actor>John Doe</actor></character></characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 <rating type="mpaa">PG</rating></movie>
</movies>

Exemplo #11 DOM Interoperability

PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML.

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}

$books = simplexml_import_dom($dom);

echo $books->book[0]->title;
?>

O exemplo acima produzirá:

blah

User Contributed Notes

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

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

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

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

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

Instead you need to cast to string or int first:

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

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

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

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

So, I used this code,

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

$json_string = json_encode($xml);

$result_array = json_decode($json_string, TRUE);

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

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

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

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

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

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

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

SimpleXML objects follow four basic rules:

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

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

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

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

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

<?php

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

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

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

<?php

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

    $xmlDoc = new SimpleXMLElement($xml);

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

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

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

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

?>

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


Dealing with XML errors

Dealing with XML errors when loading documents is a very simple task. Using the libxml functionality it is possible to suppress all XML errors when loading the document and then iterate over the errors.

The libXMLError object, returned by libxml_get_errors(), contains several properties including the message, line and column (position) of the error.

Exemplo #1 Loading broken XML string

<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if ($sxe === false) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
?>

O exemplo acima produzirá:

Failed loading XML
    Blank needed here
    parsing XML declaration: '?>' expected
    Opening and ending tag mismatch: xml line 1 and broken
    Premature end of data in tag broken line 1

Veja Também

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


A classe SimpleXMLElement

(PHP 5, PHP 7, PHP 8)

Introdução

Representa um elemento em um documento XML.

Sinopse da classe

class SimpleXMLElement implements Stringable, Countable, RecursiveIterator {
/* Métodos */
public __construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)
public addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void
public addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement
public asXML(?string $filename = null): string|bool
public attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public count(): int
public current(): SimpleXMLElement
public getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false
public getName(): string
public getNamespaces(bool $recursive = false): array
public getChildren(): ?SimpleXMLElement
public hasChildren(): bool
public key(): string
public next(): void
public registerXPathNamespace(string $prefix, string $namespace): bool
public rewind(): void
public __toString(): string
public valid(): bool
public xpath(string $expression): array|null|false
}

Changelog

Versão | Descrição
8.0.0 | SimpleXMLElement implementa Stringable, Countable, e RecursiveIterator agora.

Índice

  • SimpleXMLElement::addAttribute — Adiciona um atributo a elemento SimpleXML
  • SimpleXMLElement::addChild — Adiciona um elemento filho à um nó XML
  • SimpleXMLElement::asXML — Retorna uma string XML bem formada (well-formed) baseada em um elemento SimpleXML
  • SimpleXMLElement::attributes — Identifica um atributo de um elemento
  • SimpleXMLElement::children — Encontra os nós filhos de um dado nó
  • SimpleXMLElement::__construct — Cria um novo objeto SimpleXMLElement
  • SimpleXMLElement::count — Conta os filhos de um elemento
  • SimpleXMLElement::current — Returns the current element
  • SimpleXMLElement::getDocNamespaces — Retorna um namespace declarado no documento
  • SimpleXMLElement::getName — Pega o nome de um elemento XML
  • SimpleXMLElement::getNamespaces — Retorna os namespaces utilizados no 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 — Cria um prefixo/namespace de contexto para a próxima consulta XPath
  • SimpleXMLElement::rewind — Rewind to the first element
  • SimpleXMLElement::saveXML — Sinônimo de SimpleXMLElement::asXML
  • SimpleXMLElement::__toString — Retorna o conteúdo como uma string
  • SimpleXMLElement::valid — Check whether the current element is valid
  • SimpleXMLElement::xpath — Executa uma consulta XPath em dados 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.


Adiciona um atributo a elemento SimpleXML

  • « SimpleXMLElement
  • SimpleXMLElement::addChild »
  • PHP Manual
  • SimpleXMLElement
  • Adiciona um atributo a elemento SimpleXML

SimpleXMLElement::addAttribute

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

SimpleXMLElement::addAttribute — Adiciona um atributo a elemento SimpleXML

Descrição

public SimpleXMLElement::addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void

Adiciona um atributo à elemento SimpleXML

Parâmetros

qualifiedName

O nome do atributo a ser adicionado.

value

O valor do atributo.

namespace

Se especificado, diz a qual namespace o atributo pertence.

Valor Retornado

Nenhum valor é retornado.

Exemplos

Nota:

Os exemplos listados podem incluir o arquivo example.php, que referem-se a uma string XML encontrada no primeiro exemplo do guia de uso básico.

Exemplo #1 Adiciona atributos e filhos à um elemento SimpleXML

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

O exemplo acima produzirá algo semelhante a:

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

Veja Também

  • SimpleXMLElement::addChild() - Adiciona um elemento filho à um nó XML
  • Basic SimpleXML usage

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>


Adiciona um elemento filho à um nó XML

  • « SimpleXMLElement::addAttribute
  • SimpleXMLElement::asXML »
  • PHP Manual
  • SimpleXMLElement
  • Adiciona um elemento filho à um nó XML

SimpleXMLElement::addChild

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

SimpleXMLElement::addChild — Adiciona um elemento filho à um nó XML

Descrição

public SimpleXMLElement::addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement

Adiciona um elemento filho ao nó e retorna um elemento SimpleXML do nó filho.

Parâmetros

qualifiedName

O nome do elemento filho à ser adicionado.

value

Se especificado, o valor do elemento filho.

namespace

Se especificado, o namespace ao qual o elemento filho pertence.

Valor Retornado

O método addChild retorna um objeto SimpleXMLElement representando o filho adicionado ao nó XML em caso de sucesso; null em caso de falha.

Exemplos

Nota:

Os exemplos listados podem incluir o arquivo example.php, que referem-se a uma string XML encontrada no primeiro exemplo do guia de uso básico.

Exemplo #1 Adiciona atributos e filhos à um elemento SimpleXML

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

O exemplo acima produzirá algo semelhante a:

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

Veja Também

  • SimpleXMLElement::addAttribute() - Adiciona um atributo a elemento SimpleXML
  • Basic SimpleXML usage

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 uma string XML bem formada (well-formed) baseada em um elemento SimpleXML

  • « SimpleXMLElement::addChild
  • SimpleXMLElement::attributes »
  • PHP Manual
  • SimpleXMLElement
  • Retorna uma string XML bem formada (well-formed) baseada em um elemento SimpleXML

SimpleXMLElement::asXML

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::asXML — Retorna uma string XML bem formada (well-formed) baseada em um elemento SimpleXML

Descrição

public SimpleXMLElement::asXML(?string $filename = null): string|bool

O método asXML formata os dados dos objetos pais em XML de versão 1.0.

Parâmetros

filename

Se um string for fornecido, a função grava os dados no arquivo em vez de retorná-lo.

Valor Retornado

Se o filename não for especificado, esta função retornará uma string no caso de sucesso, e false no caso de erro. Se o parâmetro for especificado, retornará true se o arquivo for escrito com sucesso, e false caso contrário.

Changelog

Versão | Descrição
8.0.0 | filename é anulável agora.

Exemplos

Exemplo #1 Recuperando o XML

<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<d>
<c>code</c>
</d>
</a>
XML;

$xml = new SimpleXMLElement($string);

echo $xml->asXML(); // <?xml ... <a><b><c>text</c><c>stuff</c> ...

?>

O exemplo acima produzirá:

<?xml version="1.0"?>
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>

O método asXML também funcionará em resultados Xpath:

Exemplo #2 Utilizando asXML() em resultados SimpleXMLElement::xpath()

<?php
// Continued from example XML above.

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
echo $node->asXML(); // <c>text</c> and <c>stuff</c>
}
?>

O exemplo acima produzirá:

<c>text</c><c>stuff</c>

Veja Também

  • SimpleXMLElement::__toString() - Retorna o conteúdo como uma string
  • Basic SimpleXML usage

User Contributed Notes

andreas dot theissen at t-online dot de 27-Oct-2012 12:37
To prevent asXML from encoding vowels unwantedly, simply use an approriate XML header with encoding in advance.

If you do so, asXML will happily leave your vowels (and the header) entirely untouched.

<?php

$xmlstr =
'<?xml version="1.0" encoding="UTF-8"?>
<keys>
  <key lang="en">&lt;Insert&gt;</key>
  <key lang="de">&lt;Einfügen&gt;</key>
</keys>';

$sxe = new SimpleXMLElement($xmlstr);

$output = $sxe->asXML();

?>

$xmlstr and $output are identical now.

The subsequent use of html_entity_decode() (as proposed in the very beginning in another post) has several drawbacks:

1. It is slow
2. It is expensive
3. If there are already encoded arrow brackets or double quotes in your source for instance (as shown in the above example), markup will be broken.
oleg dot pavlin at gmail dot com 10-Jan-2012 04:17
Function asXML decodes special chars like ø, æ and others to &#xE6;, &#xF8;

To get normal output use without quoting:

$xml = html_entity_decode($xml, ENT_NOQUOTES, 'UTF-8');


Identifica um atributo de um elemento

  • « SimpleXMLElement::asXML
  • SimpleXMLElement::children »
  • PHP Manual
  • SimpleXMLElement
  • Identifica um atributo de um elemento

SimpleXMLElement::attributes

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::attributes — Identifica um atributo de um elemento

Descrição

public SimpleXMLElement::attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement

Esta função provê os atributos e valores definidos dentro de uma tag XML.

Nota: Na SimpleXML tornou-se comum adicionar propriedades iterativas à maioria dos métodos. Elas não podem ser visualizadas usando var_dump() ou qualquer outra coisa que possa examinar objetos.

Parâmetros

namespaceOrPrefix

Um namespace opcional para os atributos retornados

isPrefix

false por padrão

Valor Retornado

Retorna um objeto SimpleXMLElement que pode iterar os atributos da tag.

Retornará null se chamado em um objeto SimpleXMLElement que já represente um atributo e não uma tag.

Exemplos

Exemplo #1 Interpretando uma string XML

<?php
$string = <<<XML
<a xmlns:b>
<foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
?>

O exemplo acima produzirá:

name="one"
game="lonely"

Veja Também

  • Basic SimpleXML usage

User Contributed Notes

jurchiks101 at gmail dot com 23-May-2018 12:38
An undocumented way - and, IMO, a hack - of getting an element's value OR attributes
(but not both) without type-casting is to use the function `current()`:

<?php
$xml = new SimpleXMLElement(<<<'XML'
<foo>
    <bar>1</bar>
    <baz name="baz" />
    <qux name="qux">3</qux>
</foo>
XML
);

var_dump([
    'bar' => [
        $xml->bar,
        current($xml->bar),
    ],
    'baz' => [
        $xml->baz->attributes(),
        current($xml->baz->attributes()),
    ],
    'qux' => [
        // won't work here correctly
        $xml->qux,
        current($xml->qux),
        $xml->qux->attributes(),
        current($xml->qux->attributes()),
    ],
]);
?>

Results in the following output (re-formatted to shorten it):
```
array(3) {
  'bar' => array(2) {
    [0] => class SimpleXMLElement#2 (1) {
      public ${0} => string(1) "1"
    }
    [1] => string(1) "1"
  }
  'baz' => array(2) {
    [0] => class SimpleXMLElement#5 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [1] => array(1) {
      'name' => string(3) "baz"
    }
  }
  'qux' => array(4) {
    [0] => class SimpleXMLElement#6 (2) {
      public $@attributes => array(1) {
        ...
      }
      public ${0} => string(1) "3"
    }
    [1] => array(1) {
      'name' => string(3) "qux"
    }
    [2] => class SimpleXMLElement#7 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [3] => array(1) {
      'name' => string(3) "qux"
    }
  }
}
```

This apparently reads the element as an array and just returns the value of the first property, whether it be the attributes or the value. As seen in the third example, this is unreliable, especially if you're parsing XML from an outside source that may or may not have attributes on an element that you want the value of.

I certainly do NOT advise anyone to use this since it is undocumented and it is just a coincidence that it works, so it might break in the future without prior notice.
andy dot locologic+101 at gmail dot com 14-Aug-2015 10:00
Easiest and safest way to get attributes as an array is to use the iterator_to_array function (see http://php.net/manual/en/function.iterator-to-array.php):

<?php
      $x = new SimpleXMLElement('<div class="myclass" id="myid"/>');
      $attributes = iterator_to_array($x->attributes());
?>
zevnikrok 18-Dec-2014 11:01
If you wish to get attributes as an associative array of key value pairs, you don't need to iterate through them, you can get it with this one liner:

  reset($element->attributes())
webfelipemaia at gmail dot com 07-Sep-2013 05:11
Use attributes to display when it meets certain condition defined attribute / value in xml tags.

Use atributos para exibir quando atende determinada condição definida atributo / valor em tags XML.

Consider the following example:
Considere o seguinte exemplo:

(file.xml)

<?xml version="1.0" encoding="UTF-8"?>

<list>
    <item type="Language">
        <name>PHP</name>
        <link>www.php.net</link>
    </item>
    <item type="Database">
        <name>Java</name>
        <link>www.oracle.com/br/technologies/java/?</link>
    </item>
</list>

Checks if the attribute value equals "Language", if equal prints everything that is related to "Language".

Verifica se o valor do atributo é igual a "Language", se for, imprime tudo o que for relativo ao mesmo.

<?php

$xml = simplexml_load_file("file.xml");

foreach($xml->children() as $child) {

        $role = $child->attributes();

        foreach($child as $key => $value) {

            if($role == "Language")
            echo("[".$key ."] ".$value . "<br />");

        }
}
?>

output:
saída:

[name] PHP
[link] www.php.net
adrian at foeder dot de 14-Jun-2013 10:15
in order to get a possibly present xml:space attribute, use the following construct:

<?php
$simpleXmlElement->element->attributes('http://www.w3.org/XML/1998/namespace')->space;
?>

This will, for example, return 'preserve' if set.

Just passing by 'xml' as namespace argument of the attribute() method didn't work out for me. Passing by the complete namespace URI works also if it is not explicitly defined in the underlying XML document.

Also, $simpleXmlElement->getNamespaces() does not return anything of use.
totalwipeout at gmail dot com 08-Nov-2012 05:21
Tip to get a real array of all attributes of a node (not SimpleXML's object acting like an array)

<?php
//- $node is a SimpleXMLElement object

$atts_object = $node->attributes(); //- get all attributes, this is not a real array
$atts_array = (array) $atts_object; //- typecast to an array

//- grab the value of '@attributes' key, which contains the array your after
$atts_array = $atts_array['@attributes'];

var_dump($atts_object); //- outputs object(SimpleXMLElement)[19]
                        //-             public '@attributes' => ...

var_dump($atts_array); //- outputs array (size=11) ...

?>
Hope this helps!
chris at chlab dot ch 23-Mar-2012 10:16
Note that you must provide the namespace if you want to access an attribute of a non-default namespace:

Consider the following example:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
 <Table Foo="Bar" ss:ExpandedColumnCount="7">
 </Table>
</Workbook>
XML;

$sxml = new SimpleXMLElement($xml);

/**
 * Access attribute of default namespace
 */
var_dump((string) $sxml->Table[0]['Foo']);
// outputs: 'Bar'

/**
 * Access attribute of non-default namespace
 */
var_dump((int) $sxml->Table[0]['ExpandedColumnCount']);
// outputs: 0

var_dump((int) $sxml->Table[0]->attributes('ss', TRUE)->ExpandedColumnCount);
// outputs: '7'
?>
Andrei 16-May-2011 04:46
Reading the attributes of the root element with name space prefixes as in an Atom feed

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/&quot;Ck4EQXYzeCp7ImA9WhZWFE4.&quot;">

<?php
$xml =  @simplexml_load_file($feed);
$att_gd = $xml->attributes("gd",1);
$Etag = $att_gd["etag"];
?>
sarlak 27-Apr-2011 01:12
<?php
$att = 'attribueName';

// You can access an element's attribute just like this :
$attribute = $element->attributes()->$att;

// This will save the value of the attribute, and not the objet
$attribute = (string)$element->attributes()->$att;

// You also can edit it this way :
$element->attributes()->$att = 'New value of the attribute';
?>
leap 02-Apr-2011 09:07
If you want to save the value of an attribute into an array, typecast it to a string.

<?php
// stores an xml-element-object
$dataStore['value'] = $attributes->myValue

// stores the value of the attribute
$dataStore['value'] = (string)$attributes->myValue
?>
alan at performantsystems dot com 23-May-2010 10:26
So lets say you have database type data in an XML string called $xmlstring with the key or item ID as an XML Attribute and all content data as regular XML Elements, as above. SimpleXML processes the Attributes as an array, so we can play along and push the Attributes into an array. Then we can get the value of any specific Attribute we want by addressing it by name, such as "ID".

Considering this data:

<?xml version="1.0" encoding="utf-8"?>
<data>
   <item ID="30001">
      <Company>Navarro Corp.</Company>
   </item>
   <item ID="30002">
      <Company>Performant Systems</Company>
   </item>
   <item ID="30003">
      <Company>Digital Showcase</Company>
   </item>
</data>

Example of listing both the ID Attribute and Company Element values:

<?php
$xmlObject = new SimpleXMLElement($xmlstring);
foreach ($xmlObject->children() as $node) {
        $arr = $node->attributes();   // returns an array
        print ("ID=".$arr["ID"]);     // get the value of this attribute
        print ("  Company=".$node->Company);
        print ("<p><hr>");
}
?>
Xeoncross 10-Apr-2010 07:46
It is really simple to access attributes using array form. However, you must convert them to strings or ints if you plan on passing the values to functions.

<?php
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 55555
        )

    [text] => "hello world"
)
?>

Then using a function

<?php
function xml_attribute($object, $attribute)
{
    if(isset($object[$attribute]))
        return (string) $object[$attribute];
}
?>

I can get the "id" like this

<?php
print xml_attribute($xml, 'id'); //prints "55555"
?>
gillllberg at gmail dot com 04-Nov-2009 02:21
To get an attribute in the node, use node->attributes()->attributeName
skerr at mojavi dot org 09-Dec-2004 10:55
You can also access the node as an array to get attributes:

<?php

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

echo 'Attribute: ' . $xml['attribute'];

?>
inge at elektronaut dot no 26-May-2004 10:53
here's a simple function to get an attribute by name, based on the example

<?php
function findAttribute($object, $attribute) {
  foreach($object->attributes() as $a => $b) {
    if ($a == $attribute) {
      $return = $b;
    }
  }
  if($return) {
    return $return;
  }
}
?>


Encontra os nós filhos de um dado nó

  • « SimpleXMLElement::attributes
  • SimpleXMLElement::__construct »
  • PHP Manual
  • SimpleXMLElement
  • Encontra os nós filhos de um dado nó

SimpleXMLElement::children

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::children — Encontra os nós filhos de um dado nó

Descrição

public SimpleXMLElement::children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement

Este método encontra os nós filhos que estão dentro de um dado membro. O resultado segue as regras normais de iteração.

Nota: Na SimpleXML tornou-se comum adicionar propriedades iterativas à maioria dos métodos. Elas não podem ser visualizadas usando var_dump() ou qualquer outra coisa que possa examinar objetos.

Parâmetros

namespaceOrPrefix

Um namespace XML.

isPrefix

Se o parâmetro isPrefix for definido como true, namespaceOrPrefix será considerado um prefixo. Se definido como false, namespaceOrPrefix será considerado uma URL de um namespace.

Valor Retornado

Retorna um elemento SimpleXMLElement, não importando se o nó tem filhos ou não, a menos que o nó represente um atributo, caso em que null é retornado.

Exemplos

Exemplo #1 Percorrendo um pseudo-array children()

<?php
$xml = new SimpleXMLElement(
'<person>
<child role="son">
<child role="daughter"/>
</child>
<child role="daughter">
<child role="son">
<child role="son"/>
</child>
</child>
</person>');

foreach ($xml->children() as $second_gen) {
echo ' The person begot a ' . $second_gen['role'];

foreach ($second_gen->children() as $third_gen) {
echo ' who begot a ' . $third_gen['role'] . ';';

foreach ($third_gen->children() as $fourth_gen) {
echo ' and that ' . $third_gen['role'] .
' begot a ' . $fourth_gen['role'];
}
}
}
?>

O exemplo acima produzirá:

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

Exemplo #2 Utilizando namespaces

<?php
$xml = '<example xmlns:foo="my.foo.urn">
<foo:a>Apple</foo:a>
<foo:b>Banana</foo:b>
<c>Cherry</c>
</example>';

$sxe = new SimpleXMLElement($xml);

$kids = $sxe->children('foo');
var_dump(count($kids));

$kids = $sxe->children('foo', TRUE);
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn');
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn', TRUE);
var_dump(count($kids));

$kids = $sxe->children();
var_dump(count($kids));
?>
int(0)
int(2)
int(2)
int(0)
int(1)

Veja Também

  • SimpleXMLElement::count() - Conta os filhos de um elemento
  • count() - Conta todos os elementos de um array ou de um objeto Countable

User Contributed Notes

boan dot web at outlook dot com 15-Mar-2019 07:09
SimpleXMLElement::children can return null in this case:

<?php
$xml = '
<root attr="Hello"/>
';

$sxe = new SimpleXMLElement($xml);

$sxe_xpath = $sxe->xpath('/root/@attr')[0];

$children = $sxe_xpath->children();

var_export($children); // Is null
?>
thetazzbot at gmail dot com 08-Sep-2011 06:56
Ok so say you have this xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE nitf
PUBLIC "-//IPTC-NAA//DTD NITF 3.1//EN"
       "http://www.nitf.org/site/nitf-documentation/nitf-3-1.dtd">
<nitf>
  <head>
    <docdata management-status="embargoed">
      <!--data/2011/08/23/parties/doc4e53aa5783cca930694817.txt-->
      <doc-id id-string="doc4e53aa5783cca930694817"/>
      <date.release norm="20110823T000000"/>
      <key-list/>
    </docdata>
    <pubdata type="web" position.section="parties" position.sequence="0"/>
  </head>

-- snip --

If you need to access the nodes named "like.this" such as the date.release above, here is how I did it:

$xml = new SimpleXMLElement($xhtml);
 echo (string)$xml->head->docdata->{"date.release"}["norm"];

Took me a while to figure that one out ;)
coldshine1 at rambler dot ru 10-Dec-2010 02:37
This is my recursive simple function to parse XML with attributes.

<?php
function ParseXML($node, &$parent=array(), $only_child=true) {

        //Current node name
        $node_name = $node->getName();

        //Let's count children
        $only_child = true;
        if($node->count() > 1 ) $only_child = false;

        //If there is no child, then there may be text data
        if($only_child){
            $content="$node";
            if (strlen($content)>0) $parent['content']=$content;
        }

        //Get attributes of current node
        foreach ($node->attributes() as $k=>$v) {
            $parent['@attributes'][$k]="$v";
        }

        //Get children
        $count = 0;
        foreach ($node->children() as $child_name=>$child_node) {
            if(!$only_child) //If there are siblings then we'll add node to the end of the array
                LGServerPVR::ParseXML($child_node, $parent[$node_name][$child_name][$count], $only_child);
            else
                LGServerPVR::ParseXML($child_node, $parent[$node_name][$child_name], $only_child);
            $count++;
        }

        return $parent;
        //(c) c01d[s]h!nE 10.12.2010
    }

?>
Anonymous 26-Oct-2010 05:19
Here's my xml-to-array routine. Unlike many of the other comments here, this one takes namespaces into account.

<?php

class XmlArray {

  public function load_dom ($xml) {
    $node=simplexml_import_dom($xml);
    return $this->add_node($node);
  }

  public function load_string ($s) {
    $node=simplexml_load_string($s);
    return $this->add_node($node);
  }

  private function add_node ($node, &$parent=null, $namespace='', $recursive=false) {

    $namespaces = $node->getNameSpaces(true);
    $content="$node";

    $r['name']=$node->getName();
    if (!$recursive) {
      $tmp=array_keys($node->getNameSpaces(false));
      $r['namespace']=$tmp[0];
      $r['namespaces']=$namespaces;
    }
    if ($namespace) $r['namespace']=$namespace;
    if ($content) $r['content']=$content;

    foreach ($namespaces as $pre=>$ns) {
      foreach ($node->children($ns) as $k=>$v) {
        $this->add_node($v, $r['children'], $pre, true);
      }
      foreach ($node->attributes($ns) as $k=>$v) {
        $r['attributes'][$k]="$pre:$v";
      }
    }
    foreach ($node->children() as $k=>$v) {
      $this->add_node($v, $r['children'], '', true);
    }
    foreach ($node->attributes() as $k=>$v) {
      $r['attributes'][$k]="$v";
    }

    $parent[]=&$r;
    return $parent[0];

  }

}

?>
mrdaniellee at live dot com 10-Jan-2010 09:11
use this If you want to view the HTML as well as data.

normal dumps display the parsed versions of HTML.
This code displays the HTML as Text in a Text Area, and also display all other a data along side as an array

perfect for debugging (xml with html).

Try This Code:

<?php
$xml  = simplexml_load_file($url);

function xml2array_parse($xml){
     foreach ($xml->children() as $parent => $child){
         $return["$parent"] = xml2array_parse($child)?xml2array_parse($child):"$child";
     }
     return $return;
 }

 print "<pre><textarea style=\"width:200%;height:100%;\">";
 print_r(xml2array_parse($xml));
 print "</textarea></pre>";
?>
rodmen at gmail dot com 21-May-2009 08:32
Transform xml to array php

<?php
function xml2phpArray($xml,$arr){
    $iter = 0;
        foreach($xml->children() as $b){
                $a = $b->getName();
                if(!$b->children()){
                        $arr[$a] = trim($b[0]);
                }
                else{
                        $arr[$a][$iter] = array();
                        $arr[$a][$iter] = xml2phpArray($b,$arr[$a][$iter]);
                }
        $iter++;
        }
        return $arr;
}

$Array = simplexml_load_string(file_get_contents('myfile.xml'));
print_r(xml2phpArray($Array,array()));
?>
Anonymous 06-Sep-2008 05:39
for XML namespaces such as <dc:creator> in RSS feeds use

<?php
    $xml = new SimpleXMLElement($string);
    $item = $xml->channel[0]->item[0];
    $dc = $item->children("http://purl.org/dc/elements/1.1/");
    echo $dc->creator;
?>
transglobe at gmx dot de 19-Mar-2008 02:37
I made a slightly differnt approch towards the RecurseXML function. Beeing hungry I had problems with the code, as it did just overwrite two <maincourse>s. So here is what I did:

<?php

$xml = new SimpleXMLElement(
'<meal>
   <type>Lunch</type>
   <time>12:30</time>
   <menu>
     <entree>salad</entree>
     <maincourse>
        <part>ships</part>
        <part>steak</part>
     </maincourse>
     <maincourse>
        <part>fisch</part>
        <part>rice</part>
     </maincourse>
     <maincourse>
        <part>wine</part>
        <part>cheese</part>
     </maincourse>
   </menu>
</meal>');

$vals = array();
RecurseXML($xml,$vals);

foreach($vals as $key=>$value)
  print("{$key} = {$value}<BR>\n");

function RecurseXML($xml,&$vals,$parent="") {

  $childs=0;
  $child_count=-1; # Not realy needed.
  $arr=array();
        foreach ($xml->children() as $key=>$value) {
                if (in_array($key,$arr)) {
                        $child_count++;
                } else {
                        $child_count=0;
                }
                $arr[]=$key;
                $k=($parent == "") ? "$key.$child_count" : "$parent.$key.$child_count";
                $childs=RecurseXML($value,$vals,$k);
                if ($childs==0) {
                        $vals[$k]= (string)$value;
                }
        }

  return $childs;
}

?>
Output is like this:
type.0 = Lunch
time.0 = 12:30
menu.0.entree.0 = salad
menu.0.maincourse.0.part.0 = ships
menu.0.maincourse.0.part.1 = steak
menu.0.maincourse.0 =
menu.0.maincourse.1.part.0 = fisch
menu.0.maincourse.1.part.1 = rice
menu.0.maincourse.1 =
menu.0.maincourse.2.part.0 = wine
menu.0.maincourse.2.part.1 = cheese
menu.0.maincourse.2 =
menu.0 =

(Not beautiful, but it solved my case...)
crescentfreshpot at yahoo dot com 10-Dec-2007 08:16
Just a warning that the iterable returned from children() contains the '@attributes' key, which is "invisible" during a foreach but can be seen if using a different construct, such as list()=each() or casting to an array before iterating w/ foreach.
aero 23-May-2007 08:07
Here's a simple, recursive, function to transform XML data into pseudo E4X syntax ie. root.child.value = foobar

<?php
error_reporting(E_ALL);

$xml = new SimpleXMLElement(
'<Patriarch>
   <name>Bill</name>
   <wife>
     <name>Vi</name>
   </wife>
   <son>
     <name>Bill</name>
   </son>
   <daughter>
     <name>Jeri</name>
     <husband>
       <name>Mark</name>
     </husband>
     <son>
       <name>Greg</name>
     </son>
     <son>
       <name>Tim</name>
     </son>
     <son>
       <name>Mark</name>
     </son>
     <son>
       <name>Josh</name>
         <wife>
           <name>Kristine</name>
         </wife>
         <son>
           <name>Blake</name>
         </son>
         <daughter>
           <name>Liah</name>
         </daughter>
     </son>
   </daughter>
</Patriarch>');

RecurseXML($xml);

function RecurseXML($xml,$parent="")
{
   $child_count = 0;
   foreach($xml as $key=>$value)
   {
      $child_count++;
      if(RecurseXML($value,$parent.".".$key) == 0)  // no childern, aka "leaf node"
      {
         print($parent . "." . (string)$key . " = " . (string)$value . "<BR>\n");
      }
   }
   return $child_count;
}

?>

The output....

.name = Bill
.wife.name = Vi
.son.name = Bill
.daughter.name = Jeri
.daughter.husband.name = Mark
.daughter.son.name = Greg
.daughter.son.name = Tim
.daughter.son.name = Mark
.daughter.son.name = Josh
.daughter.son.wife.name = Kristine
.daughter.son.son.name = Blake
.daughter.son.daughter.name = Liah
taylorbarstow at that google mail thingy 21-Apr-2006 07:38
Sometimes you actually want an array, not a pseudo array.   This is especially true when you aren't dealing with attributes (i.e., you just want the array of child nodes).

Do like this:

<?php
$children = $sxml->xpath('child::node()');
?>

The reason you might want this is to be able to use array functions like array_shift, array_pop, etc.  This is especially true when you are writing recursive functions.  Simplexml works really well in iterative programming, but if you try to implement recursion it gets ugly.
Sebastian 27-Oct-2005 03:45
Just a quick addition:

If you need to access a child node which contains a dash, you need to encapsulate it with {""}.

For example:
<?php
foreach ($domain->domain-listing as $product) {
}
?>

The example above doesn't work because of the dash. But instead you need to use:
<?php
foreach ($domain->{"domain-listing"} as $product) {
}
?>

At least for me the second example works perfectly fine.
no-one 31-May-2005 06:05
For anyone who hasn't read Sterling Hughe's article (http://www.zend.com/php5/articles/php5-simplexml.php):

<?php
$xml_document =<<<EOT
<?xml version="1.0"?>
<root xmlns:foo="http://example.com">
  <foo:bar>baz</foo:bar>
</root>
EOT;

$xml_document = simplexml_load_xml($xml_document);

$foo_ns_bar = $xml_document->children('http://example.com');

echo $foo_ns_bar->bar[0]; // prints 'baz'
?>
Andrew Rose (rose dot andrew at gmail dot com) 16-Mar-2005 04:48
The example below shows the basic use of depth-first recursion to span the xml tree.

This is coded for the command line, and it prints out the original sentance above and then the copy cat sentence it creates itself for comparison, which as you will see; this example is slightly off from, I'll leave it upto you to resolve this issue.

All in all I personaly think xml and recursion go hand in hand, so if you don't understand recursion but know xml and want to use php to manipulate xml you will need to learn about recursion at some point.

<?php
$xml = simplexml_load_string(
'<person>
 <child role="son">
  <child role="daughter"/>
 </child>
 <child role="daughter">
  <child role="son">
   <child role="son"/>
  </child>
 </child>
</person>');

function recurse($child)
 {
   foreach($child->children() as $children) {
     echo ' who begot a '.$children['role'];
     recurse($children);
   }
    return;
 }

foreach($xml->children() as $children) {
 echo 'The person begot a '.$children['role'];
  recurse($children, 0);
 echo '; ';
}

echo "\n";
echo 'The person begot a son who begot a daughter; The person begot a daughter who begot a son; and that son begot a son'."\n";

?>
zyxwvu at users dot sourceforge dot net 15-Feb-2004 10:32
File:

<category>
  <item>text</item>
  <bold>text</bold>
  <item>text</item>
  <item>text</item>
  <mark>text</mark>
  <bold>text</bold>
</category>

If you want to get also names of the tags, you can use this loop layout:

<?php
foreach($category -> children() as $name => $node){
  echo $name.'<br/>';
}
?>


Cria um novo objeto SimpleXMLElement

  • « SimpleXMLElement::children
  • SimpleXMLElement::count »
  • PHP Manual
  • SimpleXMLElement
  • Cria um novo objeto SimpleXMLElement

SimpleXMLElement::__construct

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::__construct — Cria um novo objeto SimpleXMLElement

Descrição

public SimpleXMLElement::__construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)

Cria um novo objeto SimpleXMLElement.

Parâmetros

data

Uma string XML bem formada ou, um caminho ou URL para um documento XML se dataIsURL for true.

options

Opcionalmente utilizado para especificar parâmetros adicionais da Libxml, que afetam a leitura de documentos XML. Opções que afetam a saída de documentos XML (por exemplo, LIBXML_NOEMPTYTAG) é ignorada silenciosamente.

Nota:

Pode ser necessário passar LIBXML_PARSEHUGE para poder processar XML profundamente aninhados ou nós de texto muito grandes.

dataIsURL

Por padrão, dataIsURL é false. Utilize true para especificar que o parâmetro data é um caminho ou URL para um documento XML ao invés de string.

namespaceOrPrefix

Prefixo ou URI do namespace.

isPrefix

true se namespaceOrPrefix é um prefixo, false se é uma URI; o padrão será false.

Erros

Produz uma mensagem de erro E_WARNING para cada erro encontrado nos dados do XML e, adicionalmente, dispara uma Exception se as informações no XML não puderem ser interpretadas.

Dica

Utilize a função libxml_use_internal_errors() para suprimir todos os erros XML, e a função libxml_get_errors() para iterá-los, depois.

Exemplos

Nota:

Os exemplos listados podem incluir o arquivo example.php, que referem-se a uma string XML encontrada no primeiro exemplo do guia de uso básico.

Exemplo #1 Cria um objeto SimpleXMLElement

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;

?>

O exemplo acima produzirá:

PHP: Behind the Parser

Exemplo #2 Cria um objeto SimpleXMLElement de uma URL

<?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe->asXML();

?>

Veja Também

  • Basic SimpleXML usage
  • simplexml_load_string() - Interpreta uma string XML e a transforma em um objeto
  • simplexml_load_file() - Interpreta um arquivo XML e o transforma em um objeto
  • Dealing with XML errors
  • libxml_use_internal_errors() - Desabilita erros da libxml e permite que o usuário obtenha informações de erro conforme necessário
  • libxml_set_streams_context() - Define o contexto de fluxos para o próximo carregamento ou escrita de documento libxml

User Contributed Notes

info at ensostudio dot ru 20-Aug-2021 04:22
Extended SimpleXMLElement:
<?php
class XmlElement extends \SimpleXMLElement
{
    public static function factory(string $root): self
    {
        return new static('<?xml version="1.0" encoding="UTF-8"?><'.$root.'/>', LIBXML_BIGLINES | LIBXML_COMPACT);
    }

    /**
      * @param iterable $attributes An array of element attributes as name/value pairs
      * @return $this
      */
    public function addAttributes(iterable $attributes)
    {
        foreach ($attributes as $name => $value) {
            $this->addAttribute($name, $value);
        }

        return $this;
    }

    /**
      * @param string $name The sub-element name
      * @param string|array|null $valueOrAttributes The sub-element value or an array of attributes
      * @param string|null $namespace The sub-element namespace
      * @return static|null
      */
    public function addChild($name, $valueOrAttributes = null, $namespace = null)
    {
        if (is_array($valueOrAttributes)) {
            $child = parent::addChild($name, null, $namespace);
            foreach ($valueOrAttributes as $name => $value) {
                $child->addAttribute($name, $value);
            }
        } else {
            $child = parent::addChild($name, $valueOrAttributes, $namespace);
        }

        return $child;
    }

    /**
      * @param iterable $childs An array of sub-elements as name/value(or attributes) pairs
      * @return $this
      */
    public function addChilds(iterable $childs)
    {
        foreach ($childs as $name => $value) {
            $this->addChild($name, $value);
        }

        return $this;
    }
}
?>
rowan dot collins at gmail dot com 22-Apr-2017 03:23
The manual doesn't really explain what the $ns argument (and the accompanying $is_prefix) are for.

What they do is similar to the ->children() method: they set the context of the returned object to that namespace, so that access via ->elementName and ['attributeName'] refer to elements and attributes in that namespace.

In particular, they do *not* change the namespaces which exist on the document.

See this example:

<?php
// This XML contains two elements called <child>
// One is in the namespace http://example.com, with local prefix 'ws'
// The other has no namespace (no prefix, and no default namespace declared)
$xml = '<ws:example xmlns:ws="http://example.com"><child>Not in namespace</child><ws:child>In example namespace</ws:child></ws:example>';

$sx0 = new SimpleXMLElement($xml, 0, false);
$sx1 = new SimpleXMLElement($xml, 0, false, 'http://example.com');
$sx2 = new SimpleXMLElement($xml, 0, false, 'ws', true);

echo "
    Without: {$sx0->child}
    By namespace: {$sx1->child}
    By prefix: {$sx2->child}
";
?>

Output:

 Without: Not in namespace
 By namespace: In example namespace
 By prefix: In example namespace
ahmad dot mayahi at gmail dot com 07-Jun-2016 09:36
You won't be able to load an XML file without root element:

//This will throw an exception
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>', null, false);

//Here is the solution
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>', null, false);
Phil Cross 01-Sep-2014 11:39
It's worth noting, that you need to typecast dynamic property names to string in order to retrieve there value, for example:

<?php
    $xml = new SimpleXMLElement('records.xml', 0, true);

    // This will work as expected because its a hard coded property value
    foreach($xml as $record){
        echo $record->id;    // Will output the ID fine
    }

    // Dynamic properties require typecasting to string
    $xml_field = 'id';
    foreach($xml as $record){

        // This will dump a SimpleXMLElement object
        var_dump($record->$xml_field);

        // This will output the value as expected
        echo (string)$record->$xml_field;
    }
?>
bertolini dot cedric at me dot com 16-Jun-2014 11:07
It's worth noting that the behavior of SimpleXmlElement::__construct is not exactly the same as simplexml_load_string, regarding libxml_use_internal_errors().

In my case,

<?php
libxml_use_internal_errors(true);
new \SimpleXmlElement($data);
?>

was still throwing error. But as soon as I switched to

<?php
libxml_use_internal_errors(true);
simplexml_load_string($data);
?>

everything worked fine and I stopped getting an error.
kumarldh at gmail dot com 22-Mar-2011 10:50
Using libxml_use_internal_errors() may suppress errors but Exception still requires decent handling. I used following code snippet.

<?php
libxml_use_internal_errors(true);
try{
    $xmlToObject = new SimpleXMLElement($notSoWellFormedXML);
} catch (Exception $e){
    echo 'Please try again later...';
    exit();
}
?>
uramihsayibok, gmail, com 16-Aug-2009 06:52
As I was filling out a bug report, I realized why (speculation here) the constructor is final: so that functions like simplexml_load_file and simplexml_load_string can work. I imagine the PHP-ized code looks something like

<?php

function simplexml_load_file($filename, $class_name = "SimpleXMLElement", $options = 0, $ns = "", $is_prefix = false) {
    return new $class_name($filename, $options, true, $ns, $is_prefix);
}

?>

If we were to use a different $class_name and change the constructor's definition these functions wouldn't work.

There's no easy, sensible solution that keeps simplexml_load_file and simplexml_load_string.
tudor at culise dot net 20-Nov-2007 03:35
This class is extendable, but it's too bad that its constructor cannot be overriden (PHP says it's a final method). Thus the class should be wrapped using the delegation principle rather that extended.


Conta os filhos de um elemento

  • « SimpleXMLElement::__construct
  • SimpleXMLElement::current »
  • PHP Manual
  • SimpleXMLElement
  • Conta os filhos de um elemento

SimpleXMLElement::count

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

SimpleXMLElement::count — Conta os filhos de um elemento

Descrição

public SimpleXMLElement::count(): int

Este método conta o número de filhos de um elemento.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna o número de elementos de um elemento.

Exemplos

Exemplo #1 Contando o número de filhos

<?php
$xml = <<<EOF
<people>
<person name="Person 1">
<child/>
<child/>
<child/>
</person>
<person name="Person 2">
<child/>
<child/>
<child/>
<child/>
<child/>
</person>
</people>
EOF;

$elem = new SimpleXMLElement($xml);

foreach ($elem as $person) {
printf("%s has got %d children.\n", $person['name'], $person->count());
}
?>

O exemplo acima produzirá:

Person 1 has got 3 children.
Person 2 has got 5 children.

Veja Também

  • SimpleXMLElement::children() - Encontra os nós filhos de um dado nó

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

(Não há informação de versão disponível, talvez apenas no Git)

SimpleXMLElement::current — Returns the current element

Descrição

public SimpleXMLElement::current(): SimpleXMLElement
Aviso

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 função não possui parâmetros.

Valor Retornado

Returns the current element as a SimpleXMLElement object.

Erros

Throws an Error on failure.

Changelog

Versão | Descrição
8.1.0 | An Error is now thrown if SimpleXMLElement::current() is called on an invalid iterator. Previously, null was returned.

Exemplos

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

O exemplo acima produzirá:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP basics"
}

Veja Também

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


Retorna um namespace declarado no documento

  • « SimpleXMLElement::current
  • SimpleXMLElement::getName »
  • PHP Manual
  • SimpleXMLElement
  • Retorna um namespace declarado no documento

SimpleXMLElement::getDocNamespaces

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

SimpleXMLElement::getDocNamespaces — Retorna um namespace declarado no documento

Descrição

public SimpleXMLElement::getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false

Retorna um namespace declarado no documento

Parâmetros

recursive

Se especificado, retorna todos os namespaces declarados no nó pai e nos nós filhos. De outra forma, retornará apenas os namespaces declarados no nó raiz.

fromRoot

Permite checar recursivamente os namespaces sob um nó filho em vez do nó raiz do documento XML.

Valor Retornado

O método getDocNamespaces retorna uma array com os namespaces associados às suas URIs.

Exemplos

Exemplo #1 Pega os namespaces do documento

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns">
<p:person id="1">John Doe</p:person>
<p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces();
var_dump($namespaces);

?>

O exemplo acima produzirá:

array(1) {
   ["p"]=>
   string(21) "http://example.org/ns"
}

Exemplo #2 Trabalhando com múltiplos namespaces

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
<p:person t:id="1">John Doe</p:person>
<p:person t:id="2" a:addr="123 Street" xmlns:a="http://example.org/addr">
Susie Q. Public
</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces(TRUE);
var_dump($namespaces);

?>

O exemplo acima produzirá:

array(3) {
  ["p"]=>
  string(21) "http://example.org/ns"
  ["t"]=>
  string(23) "http://example.org/test"
  ["a"]=>
  string(23) "http://example.org/addr"
}

Veja Também

  • SimpleXMLElement::getNamespaces() - Retorna os namespaces utilizados no documento
  • SimpleXMLElement::registerXPathNamespace() - Cria um prefixo/namespace de contexto para a próxima consulta XPath

User Contributed Notes

There are no user contributed notes for this page.


Pega o nome de um elemento XML

  • « SimpleXMLElement::getDocNamespaces
  • SimpleXMLElement::getNamespaces »
  • PHP Manual
  • SimpleXMLElement
  • Pega o nome de um elemento XML

SimpleXMLElement::getName

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

SimpleXMLElement::getName — Pega o nome de um elemento XML

Descrição

public SimpleXMLElement::getName(): string

Pega o nome do elemento XML.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

O método getName retorna uma string com o nome da tag XML referenciada pelo objeto SimpleXMLElement.

Exemplos

Nota:

Os exemplos listados podem incluir o arquivo example.php, que referem-se a uma string XML encontrada no primeiro exemplo do guia de uso básico.

Exemplo #1 Pega os nomes dos elementos XML

<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $child)
{
echo $child->getName() . "\n";
}

?>

O exemplo acima produzirá:

movies
movie

User Contributed Notes

There are no user contributed notes for this page.


Retorna os namespaces utilizados no documento

  • « SimpleXMLElement::getName
  • SimpleXMLElement::getChildren »
  • PHP Manual
  • SimpleXMLElement
  • Retorna os namespaces utilizados no documento

SimpleXMLElement::getNamespaces

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

SimpleXMLElement::getNamespaces — Retorna os namespaces utilizados no documento

Descrição

public SimpleXMLElement::getNamespaces(bool $recursive = false): array

Retorna os namespaces utilizados no documento

Parâmetros

recursive

Se especificado, retorna todos os namespaces utilizados no nó pai e nos nós filhos. Caso contrário, retorna apenas os namespaces utilizados no nó raíz (root node).

Valor Retornado

O método getNamespaces retorna uma array de namespace com suas respectivas URIs.

Exemplos

Exemplo #1 Get document namespaces in use

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
<p:person id="1">John Doe</p:person>
<p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getNamespaces(true);
var_dump($namespaces);

?>

O exemplo acima produzirá:

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

Veja Também

  • SimpleXMLElement::getDocNamespaces() - Retorna um namespace declarado no documento
  • SimpleXMLElement::registerXPathNamespace() - Cria um prefixo/namespace de contexto para a próxima consulta 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

(Não há informação de versão disponível, talvez apenas no Git)

SimpleXMLElement::getChildren — Returns the sub-elements of the current element

Descrição

public SimpleXMLElement::getChildren(): ?SimpleXMLElement
Aviso

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 função não possui parâmetros.

Valor Retornado

Returns a SimpleXMLElement object containing the sub-elements of the current element.

Exemplos

Exemplo #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";
}
}
?>

O exemplo acima produzirá:

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

(Não há informação de versão disponível, talvez apenas no Git)

SimpleXMLElement::hasChildren — Checks whether the current element has sub elements

Descrição

public SimpleXMLElement::hasChildren(): bool
Aviso

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 função não possui parâmetros.

Valor Retornado

true if the current element has sub-elements, otherwise false

Exemplos

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

O exemplo acima produzirá:

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

(Não há informação de versão disponível, talvez apenas no Git)

SimpleXMLElement::key — Return current key

Descrição

public SimpleXMLElement::key(): string
Aviso

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 função não possui parâmetros.

Valor Retornado

Returns the XML tag name of the element referenced by the current SimpleXMLElement object.

Erros

Throws an Error on failure.

Changelog

Versão | Descrição
8.1.0 | An Error is now thrown if SimpleXMLElement::key() is called on an invalid iterator. Previously, false was returned.

Exemplos

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

?>

O exemplo acima produzirá:

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

(Não há informação de versão disponível, talvez apenas no Git)

SimpleXMLElement::next — Move to next element

Descrição

public SimpleXMLElement::next(): void
Aviso

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 função não possui parâmetros.

Valor Retornado

Nenhum valor é retornado.

Exemplos

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

O exemplo acima produzirá:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "XML basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Cria um prefixo/namespace de contexto para a próxima consulta XPath

  • « SimpleXMLElement::next
  • SimpleXMLElement::rewind »
  • PHP Manual
  • SimpleXMLElement
  • Cria um prefixo/namespace de contexto para a próxima consulta XPath

SimpleXMLElement::registerXPathNamespace

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

SimpleXMLElement::registerXPathNamespace — Cria um prefixo/namespace de contexto para a próxima consulta XPath

Descrição

public SimpleXMLElement::registerXPathNamespace(string $prefix, string $namespace): bool

Cria um prefixo/namespace de contexto para a próxima consulta XPath. Basicamente, esta função será útil se o provedor do documento XML informado, altera os prefixos dos namespaces. registerXPathNamespace criará um prefixo para o namespace associado, permitindo o acesso a nós no namespace sem a necessidade de mudar o código para permitir novos prefixos ditados pelo provedor.

Parâmetros

prefix

O prefixo do namespace utilizado na consulta XPath para o namespace dado em namespace.

namespace

O namespace para ser utilizado na consulta XPath. Este parâmetro deve fechar com um namespace utilizado pelo documento XML ou a consulta XPath utilizando prefix não retornará nenhum resultado.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Exemplos

Exemplo #1 Definindo um prefixo de namespace para ser usado em uma consulta XPath

<?php

$xml = <<<EOD
<book xmlns:chap="http://example.org/chapter-title">
<title>My Book</title>
<chapter id="1">
<chap:title>Chapter 1</chap:title>
<para>Donec velit. Nullam eget tellus vitae tortor gravida scelerisque.
In orci lorem, cursus imperdiet, ultricies non, hendrerit et, orci.
Nulla facilisi. Nullam velit nisl, laoreet id, condimentum ut,
ultricies id, mauris.</para>
</chapter>
<chapter id="2">
<chap:title>Chapter 2</chap:title>
<para>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin
gravida. Phasellus tincidunt massa vel urna. Proin adipiscing quam
vitae odio. Sed dictum. Ut tincidunt lorem ac lorem. Duis eros
tellus, pharetra id, faucibus eu, dapibus dictum, odio.</para>
</chapter>
</book>
EOD;

$sxe = new SimpleXMLElement($xml);

$sxe->registerXPathNamespace('c', 'http://example.org/chapter-title');
$result = $sxe->xpath('//c:title');

foreach ($result as $title) {
echo $title . "\n";
}

?>

O exemplo acima produzirá:

Chapter 1
Chapter 2

Perceba como como o documento XML mostrado no exemplo define o namespace com o prefixo de chap. Imagine que este documento (ou outro semelhante) deveria ter utilizado o prefixo de c no passado para o mesmo namespace. Uma vez que ele foi alterado, a consulta XPath não irá mais retornar os resultados apropriados e a consulta exigirá modificações. Utilizando registerXPathNamespace evita modificações futuras na consulta, mesmo que o provedor altere o prefixo dos namespaces.

Veja Também

  • SimpleXMLElement::xpath() - Executa uma consulta XPath em dados XML
  • SimpleXMLElement::getDocNamespaces() - Retorna um namespace declarado no documento
  • SimpleXMLElement::getNamespaces() - Retorna os namespaces utilizados no 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

(Não há informação de versão disponível, talvez apenas no Git)

SimpleXMLElement::rewind — Rewind to the first element

Descrição

public SimpleXMLElement::rewind(): void
Aviso

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 função não possui parâmetros.

Valor Retornado

Nenhum valor é retornado.

Exemplos

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

O exemplo acima produzirá:

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP Basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Sinônimo de SimpleXMLElement::asXML

  • « SimpleXMLElement::rewind
  • SimpleXMLElement::__toString »
  • PHP Manual
  • SimpleXMLElement
  • Sinônimo de SimpleXMLElement::asXML

SimpleXMLElement::saveXML

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

SimpleXMLElement::saveXML — Sinônimo de SimpleXMLElement::asXML()

Descrição

Este método é um apelido para: SimpleXMLElement::asXML()

User Contributed Notes

There are no user contributed notes for this page.


Retorna o conteúdo como uma string

  • « SimpleXMLElement::saveXML
  • SimpleXMLElement::valid »
  • PHP Manual
  • SimpleXMLElement
  • Retorna o conteúdo como uma string

SimpleXMLElement::__toString

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

SimpleXMLElement::__toString — Retorna o conteúdo como uma string

Descrição

public SimpleXMLElement::__toString(): string

Retorna o texto que está contido diretamente no elemento. Não retorna o texto que está dentro de elementos filhos.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna o conteúdo como uma string em caso de sucesso ou uma string varia, se falhar.

Exemplos

Exemplo #1 Recuperando o conteúdo como uma string

<?php
$xml = new SimpleXMLElement('<a>1 <b>2 </b>3</a>');
echo $xml;
?>

O exemplo acima produzirá:

1 3

Veja Também

  • SimpleXMLElement::asXML() - Retorna uma string XML bem formada (well-formed) baseada em um 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

(Não há informação de versão disponível, talvez apenas no Git)

SimpleXMLElement::valid — Check whether the current element is valid

Descrição

public SimpleXMLElement::valid(): bool
Aviso

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 função não possui parâmetros.

Valor Retornado

Returns true if the current element is valid, otherwise false

Exemplos

Exemplo #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.


Executa uma consulta XPath em dados XML

  • « SimpleXMLElement::valid
  • SimpleXMLIterator »
  • PHP Manual
  • SimpleXMLElement
  • Executa uma consulta XPath em dados XML

SimpleXMLElement::xpath

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::xpath — Executa uma consulta XPath em dados XML

Descrição

public SimpleXMLElement::xpath(string $expression): array|null|false

O método xpath vasculha o nó SimpleXML em busca de nós filhos correspondentes ao XPath expression.

Parâmetros

expression

Um caminho XPath

Valor Retornado

Retorna uma array de um objeto SimpleXMLElement em caso de sucesso; ou null ou false em caso de erro.

Exemplos

Exemplo #1 Xpath

<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<d>
<c>code</c>
</d>
</a>
XML;

$xml = new SimpleXMLElement($string);

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
echo '/a/b/c: ',$node,"\n";
}

/* Relative paths also work... */
$result = $xml->xpath('b/c');

foreach ($result as $node) {
echo 'b/c: ',$node,"\n";
}
?>

O exemplo acima produzirá:

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Note que os dois resultados são iguais.

Veja Também

  • SimpleXMLElement::registerXPathNamespace() - Cria um prefixo/namespace de contexto para a próxima consulta XPath
  • SimpleXMLElement::getDocNamespaces() - Retorna um namespace declarado no documento
  • SimpleXMLElement::getNamespaces() - Retorna os namespaces utilizados no documento
  • Basic SimpleXML usage

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"/>


A classe SimpleXMLIterator

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

Introdução

A classe SimpleXMLIterator provê iterações recursivas em todos os nós de um objeto SimpleXMLElement.

Sinopse da classe

class SimpleXMLIterator extends SimpleXMLElement {
/* Métodos herdados */
public SimpleXMLElement::__construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)
public SimpleXMLElement::addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void
public SimpleXMLElement::addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement
public SimpleXMLElement::asXML(?string $filename = null): string|bool
public SimpleXMLElement::attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public SimpleXMLElement::children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public SimpleXMLElement::count(): int
public SimpleXMLElement::current(): SimpleXMLElement
public SimpleXMLElement::getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false
public SimpleXMLElement::getName(): string
public SimpleXMLElement::getNamespaces(bool $recursive = false): array
public SimpleXMLElement::getChildren(): ?SimpleXMLElement
public SimpleXMLElement::hasChildren(): bool
public SimpleXMLElement::key(): string
public SimpleXMLElement::next(): void
public SimpleXMLElement::registerXPathNamespace(string $prefix, string $namespace): bool
public SimpleXMLElement::rewind(): void
public SimpleXMLElement::__toString(): string
public SimpleXMLElement::valid(): bool
public SimpleXMLElement::xpath(string $expression): array|null|false
}

Changelog

Versão | Descrição
8.0.0 | Métodos iteradores (SimpleXMLIterator::hasChildren(), SimpleXMLIterator::getChildren(), SimpleXMLIterator::current(), SimpleXMLIterator::key(), SimpleXMLIterator::next(),SimpleXMLIterator::rewind(), SimpleXMLIterator::valid()) foram movidos para SimpleXMLElement.
8.0.0 | SimpleXMLIterator implementa Stringable agora.

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


Funções da SimpleXML

Índice

  • simplexml_import_dom — Recebe um objeto SimpleXMLElement de um nó DOM
  • simplexml_load_file — Interpreta um arquivo XML e o transforma em um objeto
  • simplexml_load_string — Interpreta uma string XML e a transforma em um 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.


Recebe um objeto SimpleXMLElement de um nó DOM

  • « Funções da SimpleXML
  • simplexml_load_file »
  • PHP Manual
  • Funções da SimpleXML
  • Recebe um objeto SimpleXMLElement de um nó DOM

simplexml_import_dom

(PHP 5, PHP 7, PHP 8)

simplexml_import_dom — Recebe um objeto SimpleXMLElement de um nó DOM

Descrição

simplexml_import_dom(SimpleXMLElement|DOMNode $node, ?string $class_name = SimpleXMLElement::class): ?SimpleXMLElement

Esta função recebe um nó de um documento DOM e o transforma em um nó SimpleXML. O novo objeto pode ser utilizado como um elemento SimpleXML nativo.

Parâmetros

node

Um nó DOM

class_name

Pode-se utilizar o parâmetro opcional simplexml_import_dom() para retornar um objeto da classe especificada. A classe deve estender a classe SimpleXMLElement.

Valor Retornado

Retorna um SimpleXMLElement ou null em caso de falha.

Exemplos

Exemplo #1 Importando o DOM

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title;
?>

O exemplo acima produzirá:

blah

Veja Também

  • dom_import_simplexml() - Gets a DOMElement object from a SimpleXMLElement object
  • Basic SimpleXML usage

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 um arquivo XML e o transforma em um objeto

  • « simplexml_import_dom
  • simplexml_load_string »
  • PHP Manual
  • Funções da SimpleXML
  • Interpreta um arquivo XML e o transforma em um objeto

simplexml_load_file

(PHP 5, PHP 7, PHP 8)

simplexml_load_file — Interpreta um arquivo XML e o transforma em um objeto

Descrição

simplexml_load_file(
string $filename,
?string $class_name = SimpleXMLElement::class,
int $options = 0,
string $namespace_or_prefix = "",
bool $is_prefix = false
): SimpleXMLElement|false

Converte o documento XML bem-formado no arquivo indicado em um objeto.

Parâmetros

filename

Caminho para o arquivo XML

class_name

É possível utilizar o parâmetro opcional simplexml_load_file() para retornar um objeto da classe especificada. Esta classe deve estender SimpleXMLElement.

options

Bit a bit OR das constantes de opções da libxml.

namespace_or_prefix

Prefixo ou URI do namespace.

is_prefix

true se namespace_or_prefix for um prefixo, false se for URI; o padrão é false.

Valor Retornado

Retorna um objeto da classe SimpleXMLElement com propriedades contendo os dados do documento XML, ou false em caso de falha.

Aviso

Esta função pode retornar o valor booleano false, mas também pode retornar um valor não booleano que pode ser avaliado como false. Leia a seção sobre Booleanos para mais informações. Use o operador === para testar o valor retornado por esta função.

Erros

Produz uma mensagem de erro E_WARNING para cada erro encontrado nos dados XML.

Dica

Utilize a função libxml_use_internal_errors() para suprimir todos os erros XML e a função libxml_get_errors() para iterar sobre eles posteriormente.

Exemplos

Exemplo #1 Interpreta um documento XML

<?php
// O arquivo test.xml contém um documento XML com um elemento root
// e ao menos um elemento /[root]/title.

if (file_exists('test.xml')) {
$xml = simplexml_load_file('test.xml');

print_r($xml);
} else {
exit('Falha ao abrir test.xml.');
}
?>

Este script mostrará, em caso de sucesso:

SimpleXMLElement Object
(
  [title] => Example Title
  ...
)

Nesse ponto já é possível utilizar $xml->title e quaisquer outros elementos.

Veja Também

  • simplexml_load_string() - Interpreta uma string XML e a transforma em um objeto
  • SimpleXMLElement::__construct() - Cria um novo objeto SimpleXMLElement
  • Dealing with XML errors
  • libxml_use_internal_errors() - Desabilita erros da libxml e permite que o usuário obtenha informações de erro conforme necessário
  • Basic SimpleXML usage
  • libxml_set_streams_context() - Define o contexto de fluxos para o próximo carregamento ou escrita de documento libxml

User Contributed Notes

siraic at gmail dot com 20-Jun-2023 08:47
LibXML typically uses ten times the file size in memory to read a file, and this memory usage falls largely outside the memory limit guarded by PHP.
tg at debian dot org 20-Feb-2022 09:36
This function does not accept all pathnames, in spite of its documentation.

$ php -r 'print_r( simplexml_load_file("%25.xml"));'
PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "%25.xml" in Command line code on line 1
visualmind at nospam dot php dot net 18-Jan-2022 02:49
This may sometimes get missed, but if your xml nodes are in the format:
<prefix:element />

You need to make sure to set the [namespace or prefix] argument and the [isPrefix] argument to true. Also when recalling elements you need to avoid adding the prefix if that is already set, so in the above example "prefix:element" should be added as "element" but when saved the prefix will be added automatically.

If prefix is not set during load or object construction, load will fail to get the nodes correctly and you will not be able to recall elements directly so $xml->{'prefix:element'} will not work either.
sirgrayjn at gmail dot com 22-Sep-2016 09:51
// Be carefull if you migrate or use local machine
// for test/development.

// Windows directory separators: "\" and "/"
// You may mix separators "C:\somedir\www/img/bg.jpg".

// Mixed separators path work fine in other functions
// But simplexml_load_file() failed with mixed separators.

// Examples:
include("C:\dir\my.php");    // work (windows)
include("C:\dir/my.php");    // work (windows) with mixed
include("C:/dir/my.php");    // work (windows, linux)
simplexml_load_file("C:\dir\my.php");    // work
simplexml_load_file("C:\dir/my.php");    // failed with mixed
simplexml_load_file("C:/dir/my.php");    // work
rex111 at bigmir dot net 08-Sep-2016 03:02
Get all tags and their values. (recursive)

<?php
$xml = simplexml_load_file('settings.xml');

function all_tag($xml){
    $i=0; $name = "";
    foreach ($xml as $k){
        $tag = $k->getName();
        $tag_value = $xml->$tag;
        if ($name == $tag){ $i++;    }
                $name = $tag;
            echo $tag .' '.$tag_value[$i].'<br />';
        // recursive
           all_tag($xml->$tag->children());
    }
}

all_tag($xml);
?>
Rich 24-Nov-2015 02:51
I stumbled on this: a single element with a simple string in it becomes a string, but a single element with a *space* in it becomes an Array, with one element, the string space.

I'm sure to XML mystics this is wise and wonderful but it really confused me,  and I thought it might confuse others.

<?php
$parsed = simplexml_load_string('<container><space> </space><blank></blank><string>hello</string></container>');
$content = json_decode(json_encode($parsed),TRUE);
var_dump($content);
/* Output is:
array(3) {
  'space' => array(1) {           ? did NOT expect this!
    [0] => string(1) " "
  }
  'blank' => array(0) { }
  'string' => string(5) "hello"
}
 */
tuxedobob 30-Jun-2015 01:25
Occasionally you may try to load a file and have it complain about an entity and throw a parser error.

If this is the case, check to make sure that the file in question does not contain an ampersand (&) without a corresponding entity reference.

If it does, or if you want to err on the side of caution, then instead of using simplexml_load_file, try this:

$file = file_get_contents('stuff.xml');
$temp = preg_replace('/&(?!(quot|amp|pos|lt|gt);)/', '&amp;', $file);
$xml = simplexml_load_string($temp) or die("xml not loading");

Read the file into a string, add 'amp;' after any '&' that is not part of a character entity, then parse the string as xml.
kannan at 99deals dot in 04-Sep-2012 06:27
If you have some nodes which are having special characters, it would not load properly

for an instance see the nodes below
<node:number>1538-7445</node:number>
<node:coverDisplayDate>Sep  1 2012 12:00:00:000AM</node:coverDisplayDate>

either you have to change the : to other special characters like '-' in order to convert it properly

Correct Node
<node-number>1538-7445</node-number>
<node-coverDisplayDate>Sep  1 2012 12:00:00:000AM</node-coverDisplayDate>

I have wasted my precious time while debugging this. Please aware about this. ?
ricardo at ricardomartins dot info 21-Aug-2012 05:49
Sometimes we have xml's with hyphens nodes, like

<my_xml>
 <some-node>value</some-node>
</my_xml>

You'll need to use
<?php
$simpleXmlObj->{'some-node'}
?>

instead of
<?php
$simpleXmlObj->some-node;
?>
fusionstream at gmail dot com 05-Apr-2012 04:15
If you are loading many files, this may slow down your page load time.

To set a timeout, use file_get_context and then simplexml_load_string

<?php

$fp = fopen('http://www.example.com/rss', false, stream_create_context(array('http' => array('timeout', '1.5'))));

if ($fp) {
    print_r( simplexml_load_string($fp) );
} else {
    echo "The request timed out";
}
?>
sean at aliencreations dot com 17-Mar-2011 10:59
If you find that you are receiving 500 errors with simplexml_load_file() but you can access the xml/rss feed manually through a browser, your script is probably being blocked by a user agent sniffer.

Add this code before your xml call to remedy this issue

<?php

ini_set("user_agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
ini_set("max_execution_time", 0);
ini_set("memory_limit", "10000M");

$rss = simplexml_load_file($feed_url);

?>
Nanuit at ossi dot at 08-Feb-2011 01:51
A little function very helpfull in using simplexml_load_file behind a proxy

<?php
function getXMLfromURL($url) {
      $Proxy = getenv("HTTP_PROXY");

      if (strlen($Proxy) > 1) {
        $r_default_context = stream_context_get_default ( array
                    ('http' => array(
                        'proxy' => $Proxy,
                        'request_fulluri' => True,
                    ),
                )
            );
        libxml_set_streams_context($r_default_context);
      }
      $daten = simplexml_load_file($url);
      return ($daten);
    }
?>

where HTTP_PROXY is set to e.g.: tcp://proxy:8080
guego dot ol at ig dot com dot br 12-Nov-2010 03:26
Analyze fully XML.

<?php
$xml = simplexml_load_file('file.xml');

foreach($xml as $key0 => $value){
echo "..1..[$key0] => $value";
foreach($value->attributes() as $attributeskey0 => $attributesvalue1){
echo "________[$attributeskey0] = $attributesvalue1";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value as $key => $value2){
echo "....2.....[$key] => $value2";
foreach($value2->attributes() as $attributeskey => $attributesvalue2){
echo "________[$attributeskey] = $attributesvalue2";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value2 as $key2 => $value3){
echo ".........3..........[$key2] => $value3";
foreach($value3->attributes() as $attributeskey2 => $attributesvalue3){
echo "________[$attributeskey2] = $attributesvalue3";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value3 as $key3 => $value4){
echo "...................4....................[$key3] => $value4";
foreach($value4->attributes() as $attributeskey3 => $attributesvalue4){
echo "________[$attributeskey3] = $attributesvalue4";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value4 as $key4 => $value5){
echo ".....................5......................[$key4] => $value5";
foreach($value5->attributes() as $attributeskey4 => $attributesvalue5){
echo "________[$attributeskey4] = $attributesvalue5";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value5 as $key5 => $value6){
echo "......................6.......................[$key5] => $value6";
foreach($value6->attributes() as $attributeskey5 => $attributesvalue6){
echo "________[$attributeskey5] = $attributesvalue6";
}
echo '<br />';
}}}}}
echo '<br />';
}
?>
raduispas at gmail dot com 21-Oct-2010 06:12
if you want to check when this function fails,make sure to compare the return value with ===  instead of == :

<?php
$url = 'http://www.example.com';
$xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);
if($xml ===  FALSE)
{
   //deal with error
}
else { //do stuff }
?>

Otherwise you may end up with FALSE all the time even if the document is ok. Hope this helps someone ;)
jamie at splooshmedia dot co dot uk 31-Mar-2010 06:17
A wrapper around simplexml_load_file to circumvent nasty error messages when the xml server times out or gives a 500 error etc.

<?php
function loadXML2($domain, $path, $timeout = 30) {

    /*
        Usage:

        $xml = loadXML2("127.0.0.1", "/path/to/xml/server.php?code=do_something");
        if($xml) {
            // xml doc loaded
        } else {
            // failed. show friendly error message.
        }
    */

    $fp = fsockopen($domain, 80, $errno, $errstr, $timeout);
    if($fp) {
        // make request
        $out = "GET $path HTTP/1.1\r\n";
        $out .= "Host: $domain\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);

        // get response
        $resp = "";
        while (!feof($fp)) {
            $resp .= fgets($fp, 128);
        }
        fclose($fp);
        // check status is 200
        $status_regex = "/HTTP\/1\.\d\s(\d+)/";
        if(preg_match($status_regex, $resp, $matches) && $matches[1] == 200) {
            // load xml as object
            $parts = explode("\r\n\r\n", $resp);
            return simplexml_load_string($parts[1]);
        }
    }
    return false;

}
?>
Smokey 14-Mar-2010 10:16
for nested and same name values i'v made up this little bit for getting and displaying multiable values from google's geocode when a exact match is not found it returns all close matches in the following format(this is an abriged version of there output)

<Response>
  <Placemark id="1">
    <address> New York 24, NY, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.5850086,40.7207442,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="2">
    <address>New York 27, NY, USA</address>
    <AddressDetails>
      ...................
    </AddressDetails>
    <Point>
      <coordinates>-72.8987835,40.8003588,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="3">
    <address>Cedar Place School, 20 Cedar Pl, Yonkers, NY 10705, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.8966320,40.9256520,0</coordinates>
    </Point>
  </Placemark>
</Response>

<?php
// get and breakdown the results then store them in $var's
$Address = "99999 parkplace, new york, NY";
$urladdress = urlencode($Address);
$Base_url = "http://maps.google.com/maps/geo?q=";
$urlParts = "&output=xml";
$urlrequest = $Base_url . $urladdress . $urlParts;
$xml = simplexml_load_file($urlrequest);
$num = "0";
foreach ($xml->Response->Placemark as $value){
    $num++;
    $GeoFindAdd{$num} = $value->address;
    $GeoFindCords{$num} = $value->Point->coordinates;
}

// a simple display for the results
echo "Found ",$num," Possable Geo Data Sets <br>";
$CountNumResults = "0";
for ( ; $num > 0; $num--){
    $CountNumResults++;
    echo $countnum,"<br> Address = ",$GeoFindAdd{$num},"<br> Coordinates = ",$GeoFindCords{$num},"<br>";
}
echo "END";
?>
knl at bitflop dot com 11-Sep-2009 12:02
If you need to parse the data from SimpleXML into a session variable remember to define the data as a string first.

If you don't you will get warnings of "Node no longer exists" pointing to your session_start() function.

This will work:

<?php

    $new_version = simplexml_load_file('http://example.com/version.xml');
    $_SESSION['current_version'] = (string)$new_version->version;

?>
neil art neilanddeb dort com 17-Aug-2009 06:00
Because the encoding of my XML file is UTF-8 and the
encoding of my web page is iso-8859-1 I was getting strange characters such as â€™ instead of a right single quote.

The solution to this turned out to be hard to find, but really easy to implement.

http://uk3.php.net/manual/en/function.iconv.php

Using the iconv() function you can convert from one encodign to another, the TRANSLIT option seems to work best for what I needed.  Here's my example:

<?php
// convert string from utf-8 to iso8859-1
$horoscope = iconv( "UTF-8", "ISO-8859-1//TRANSLIT", $horoscope );
?>

I found the solution on this page...
http://tinyurl.com/lm39xc
Hope this helps
cryonyx at cerebrate dot ru 21-Oct-2008 03:34
In case you have a XML file with a series of equally named elements on one level simplexml incorrectly processes them and doesn't allow to walk through the array using foreach(). As far as I'm concerned, it is the problem caused by PHP xml_parser (see: http://ru2.php.net/manual/ru/function.xml-parser-create.php#53188).

To avoid this, just use count() and walk through the array using for().

Example:

<params>
  <param>
    <name>version.shell</name>
    <value>1.0</value>
  </param>
  <param>
      <name>version.core</name>
      <value>1.0</value>
  </param>
  <param>
      <name>file.lang</name>
      <value>vc.lang</value>
  </param>
  ...
</params>

<?php
$filename = '...';
$xml = simplexml_load_file($filename);
$p_cnt = count($xml->param);
for($i = 0; $i < $p_cnt; $i++) {
  $param = $xml->param[$i];
  ...;
}
?>
mario 02-Sep-2008 02:08
If you want CDATA in your object you should use LIBXML_NOCDATA

<?php
$xml = simplexml_load_file($file_xml, 'SimpleXMLElement',LIBXML_NOCDATA);

    print_r($xml);
?>
l [DOT] anzinger [AT] gmail [DOT] com 26-Mar-2008 09:03
If you don't want that the CDATA values get escaped, just load the XML with LIBXML_NOCDATA as an 3rd argument.

Note: A PHP version >= 5.1.0 is required for this to work.

Example:

<?php simplexml_load_file('xmldatei.xml', null, LIBXML_NOCDATA); ?>
php at werner dash ott dot de 29-Mar-2007 01:13
Making SimpleXMLElement objects session save.

Besides the effect of not surviving sessions, the SimpleXMLElement object may even crash the session_start() function when trying to re-enter the session!

To come up with a solution for this, I used a pattern as follows. The core idea is to transform the SimpleXMLElement between session calls to and from a string representation which of course is session save.

<?php
  //
  // session save handling of SimpleXMLElement objects
  // (applies to/ tested with PHP 5.1.5 and PHP 5.2.1)
  // The myClass pattern allows for conveniently accessing
  // XML structures while being session save
  //
  class myClass
  {
    private $o_XMLconfig = null;
    private $s_XMLconfig = '';

    public function __construct($args_configfile)
    {
      $this->o_XMLconfig = simplexml_load_file($args_configfile);
      $this->s_XMLconfig = $this->o_XMLconfig->asXML();
    } // __construct()

    public function __destruct()
    {
      $this->s_XMLconfig = $this->o_XMLconfig->asXML();
      unset($this->o_XMLconfig); // this object would otherwise crash
                                 // the subsequent call of
                                 // session_start()!
    } // __destruct()

    public function __wakeup()
    {
      $this->o_XMLconfig = simplexml_load_string($this->s_XMLconfig);
    } // __wakeup()

  } // class myClass
?>
wouter at code-b dot nl 20-Feb-2007 02:08
To correctly extract a value from a CDATA just make sure you cast the SimpleXML Element to a string value by using the cast operator:

<?php
$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<rss>
    <channel>
        <item>
            <title><![CDATA[Tom & Jerry]]></title>
        </item>
    </channel>
</rss>';

$xml = simplexml_load_string($xml);

// echo does the casting for you
echo $xml->channel->item->title;

// but vardump (or print_r) not!
var_dump($xml->channel->item->title);

// so cast the SimpleXML Element to 'string' solve this issue
var_dump((string) $xml->channel->item->title);
?>

Above will output:

Tom & Jerry

object(SimpleXMLElement)#4 (0) {}

string(11) "Tom & Jerry"
Kyle 10-Dec-2006 02:35
In regards to Anonymous on 7th April 2006

There is a way to get back HTML tags. For example:

<?xml version="1.0"?>
<intro>
    Welcome to <b>Example.com</b>!
</intro>

<?php
// I use @ so that it doesn't spit out content of my XML in an error message if the load fails. The content could be passwords so this is just to be safe.
$xml = @simplexml_load_file('content_intro.xml');
if ($xml) {
    // asXML() will keep the HTML tags but it will also keep the parent tag <intro> so I strip them out with a str_replace. You could obviously also use a preg_replace if you have lots of tags.
    $intro = str_replace(array('<intro>', '</intro>'), '', $xml->asXML());
} else {
    $error = "Could not load intro XML file.";
}
?>

With this method someone can change the intro in content_intro.xml and ensure that the HTML is well formed and not ruin the whole site design.
Anonymous 06-Apr-2006 09:21
What has been found when using the script is that simplexml_load_file() will remove any HTML formating inside the XML file, and will also only load so many layers deep. If your XML file is to deap, it will return a boolean false.
fdouteaud at gmail dot com 09-Mar-2006 05:21
Be careful if you are using simplexml data directly to feed your MySQL database using MYSQLi and bind parameters.

The data coming from simplexml are Objects and the bind parameters functions of MySQLi do NOT like that! (it causes some memory leak and can crash Apache/PHP)

In order to do this properly you MUST cast your values to the right type (string, integer...) before passing them to the binding methods of MySQLi.
I did not find that in the documentation and it caused me a lot of headache.
info at evasion dot cc 06-Feb-2006 08:26
Sorry there's a mistake in the previous function :
<?php
   function &getXMLnode($object, $param) {
       foreach($object as $key => $value) {
           if(isset($object->$key->$param)) {
               return $object->$key->$param;
           }
           if(is_object($object->$key)&&!empty($object->$key)) {
               $new_obj = $object->$key;
               // Must use getXMLnode function there (recursive)
               $ret = getXMLnode($new_obj, $param);

           }
       }
       if($ret) return (string) $ret;
       return false;
   }
?>
skutter at imprecision dot net 03-Feb-2006 09:11
So it seems SimpleXML doesn't support CDATA... I bashed together this little regex function to sort out the CDATA before trying to parse XML with the likes of simplexml_load_file / simplexml_load_string. Hope it might help somebody and would be very interested to hear of better solutions. (Other than *not* using SimpleXML of course! ;)

It looks for any <![CDATA [Text and HTML etc in here]]> elements, htmlspecialchar()'s the encapsulated data and then strips the "<![CDATA [" and "]]>" tags out.

<?php
function simplexml_unCDATAise($xml) {
    $new_xml = NULL;
    preg_match_all("/\<\!\[CDATA \[(.*)\]\]\>/U", $xml, $args);

    if (is_array($args)) {
        if (isset($args[0]) && isset($args[1])) {
            $new_xml = $xml;
            for ($i=0; $i<count($args[0]); $i++) {
                $old_text = $args[0][$i];
                $new_text = htmlspecialchars($args[1][$i]);
                $new_xml = str_replace($old_text, $new_text, $new_xml);
            }
        }
    }

    return $new_xml;
}

//Usage:
$xml = 'Your XML with CDATA...';
$xml = simplexml_unCDATAise($xml);
$xml_object = simplexml_load_string($xml);
?>
info at evasion dot cc 03-Feb-2006 03:37
Suppose you have loaded a XML file into $simpleXML_obj.
The structure is like below :

SimpleXMLElement Object
(

    [node1] => SimpleXMLElement Object
        (
            [subnode1] => value1
            [subnode2] => value2
            [subnode3] => value3
        )

    [node2] => SimpleXMLElement Object
        (
            [subnode4] => value4
            [subnode5] => value5
            [subnode6] => value6
        )

)

When searching a specific node in the object, you may use this function :

<?php

    function &getXMLnode($object, $param) {
        foreach($object as $key => $value) {
            if(isset($object->$key->$param)) {
                return $object->$key->$param;
            }
            if(is_object($object->$key)&&!empty($object->$key)) {
                $new_obj = $object->$key;
                $ret = getCfgParam($new_obj, $param);
            }
        }
        if($ret) return (string) $ret;
        return false;
    }
?>

So if you want to get subnode4 value you may use this function like this :

<?php
$result = getXMLnode($simpleXML_obj, 'subnode4');
echo $result;
?>

It display "value4"
genialbrainmachine at NOSPAM dot tiscali dot it 30-Sep-2005 08:52
Micro$oft Word uses non-standard characters and they create problems in using simplexml_load_file.
Many systems include non-standard Word character in their implementation of ISO-8859-1. So an XML document containing that characters can appear well-formed (i.e.) to many browsers. But if you try to load this kind of documents with simplexml_load_file you'll have a little bunch of troubles..
I believe that this is exactly the same question discussed in htmlentites. Following notes to htmlentitles are interesting here too (given in the reverse order, to grant the history):
http://it.php.net/manual/en/function.htmlentities.php#26379
http://it.php.net/manual/en/function.htmlentities.php#41152
http://it.php.net/manual/en/function.htmlentities.php#42126
http://it.php.net/manual/en/function.htmlentities.php#42511
mark 12-Sep-2005 11:06
If the property of an object is empty the array is not created. Here is a version object2array that transfers properly.

<?php
function object2array($object)
{
    $return = NULL;

    if(is_array($object))
    {
        foreach($object as $key => $value)
            $return[$key] = object2array($value);
    }
    else
    {
        $var = get_object_vars($object);

        if($var)
        {
            foreach($var as $key => $value)
                $return[$key] = ($key && !$value) ? NULL : object2array($value);
        }
        else return $object;
    }

    return $return;
}
?>


Interpreta uma string XML e a transforma em um objeto

  • « simplexml_load_file
  • WDDX »
  • PHP Manual
  • Funções da SimpleXML
  • Interpreta uma string XML e a transforma em um objeto

simplexml_load_string

(PHP 5, PHP 7, PHP 8)

simplexml_load_string — Interpreta uma string XML e a transforma em um objeto

Descrição

simplexml_load_string(
string $data,
?string $class_name = SimpleXMLElement::class,
int $options = 0,
string $namespace_or_prefix = "",
bool $is_prefix = false
): SimpleXMLElement|false

Recebe uma string XML bem-formada e a retorna como um objeto.

Parâmetros

data

Uma string XML bem-formada

class_name

Pode-se utilizar o parâmetro opcional simplexml_load_string() para retornar um objeto da classe especificada. Esta classe deve estender SimpleXMLElement.

options

Bit a bit OR das constantes de opções da libxml.

namespace_or_prefix

Prefixo ou URI do namespace.

is_prefix

true se namespace_or_prefix for um prefixo, false se for URI; o padrão é false.

Valor Retornado

Retorna um objeto da classe SimpleXMLElement com propriedades contendo os dados do documento XML, ou false em caso de falha.

Aviso

Esta função pode retornar o valor booleano false, mas também pode retornar um valor não booleano que pode ser avaliado como false. Leia a seção sobre Booleanos para mais informações. Use o operador === para testar o valor retornado por esta função.

Erros

Produz uma mensagem de erro E_WARNING para cada erro encontrado nos dados XML.

Dica

Utilize a função libxml_use_internal_errors() para suprimir todos os erros XML e a função libxml_get_errors() para iterar sobre eles posteriormente.

Exemplos

Exemplo #1 Interpretar uma string XML

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
<title>Forty What?</title>
<from>Joe</from>
<to>Jane</to>
<body>
I know that's the answer -- but what's the question?
</body>
</document>
XML;

$xml = simplexml_load_string($string);

print_r($xml);
?>

O exemplo acima produzirá:

SimpleXMLElement Object
(
  [title] => Forty What?
  [from] => Joe
  [to] => Jane
  [body] =>
   I know that's the answer -- but what's the question?
)

Nesse ponto já é possível utilizar $xml->body e afins.

Veja Também

  • simplexml_load_file() - Interpreta um arquivo XML e o transforma em um objeto
  • SimpleXMLElement::__construct() - Cria um novo objeto SimpleXMLElement
  • Dealing with XML errors
  • libxml_use_internal_errors() - Desabilita erros da libxml e permite que o usuário obtenha informações de erro conforme necessário
  • Basic SimpleXML usage

User Contributed Notes

erguven dot m at gmail dot com 11-May-2017 03:14
if you want to use a class which exists in a name space, use it full name. simple_load_string did not recognize short one.

class.new.php
<?php
namespace foo\bar;

class new extends SimpleXMLElement
{
    public function do()
    {
        echo "done";
    }
}
?>

false.php
<?php
use \foo\bar\new;

$result = simplexml_load_string($xml, 'new'); // it gives warning
$result->do(); // fatal error
?>

true.php
<?php
use \foo\bar\new;
$result = simplexml_load_string($xml, '\foo\bar\new');

$result->do(); // prints done
?>
artistan at gmail dot com 11-Jun-2015 12:32
Here is my update to Bob's simple SimpleXML wrapper function.
I noticed his version would turn an empty SimpleXMLElement into an empty array.

<?php
    /**
     * http://php.net/manual/en/function.simplexml-load-string.php#91564
     *
     * bool/array unserialize_xml ( string $input [ , callback $callback ] )
     * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data
     * Returns false on all failure
     * Notes:
     * Root XML tags are stripped
     * Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input
     * Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info
     *
     * @param $input
     * @param null $callback
     * @param bool $recurse
     * @return array|mixed
     *
     */
    function unserialize_xml($input, $callback = null, $recurse = false)
    {
        // Get input, loading an xml string with simplexml if its the top level of recursion
        $data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;
        // Convert SimpleXMLElements to array
        if ($data instanceof SimpleXMLElement){
            if(!empty($data)){
                $data = (array) $data;
            } else {
                $data = '';
            }
        }
        // Recurse into arrays
        if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);
        // Run callback and return
        return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
    }
?>
meustrus 07-May-2015 03:38
Be careful checking for parse errors. An empty SimpleXMLElement may resolve to FALSE, and if your XML contains no text or only contains namespaced elements your error check may be wrong. Always use `=== FALSE` when checking for parse errors.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<ns1:Root xmlns:ns1="http://example.com/custom">
<ns1:Node>There's stuff here</ns1:Node>
</ns1:Root>
XML;

$simplexml = simplexml_load_string($xml);

// This prints "Parse Error".
echo ($simplexml ? 'Valid XML' : 'Parse Error'), PHP_EOL;

// But this prints "There's stuff here", proving that
// the SimpleXML object was created successfully.
echo $simplexml->children('http://example.com/custom')->Node, PHP_EOL;

// Use this instead:
echo ($simplexml !== FALSE ? 'Valid XML' : 'Parse Error'), PHP_EOL;

?>

See:

https://bugs.php.net/bug.php?id=31045
https://bugs.php.net/bug.php?id=30972
https://bugs.php.net/bug.php?id=69596
dkrnl at yandex dot ru 30-Sep-2013 02:58
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

Usage example: http://github.com/dkrnl/SimpleXMLReader/blob/master/examples/example1.php
AllenJB 12-Oct-2012 08:09
<?php
$xml = json_decode(json_encode((array) simplexml_load_string($string)), 1);
?>

A reminder that json_encode attempts to convert data to UTF-8 without specific knowledge of the source encoding. This method can cause encoding issues if you're not working in UTF-8.
Anonymous 29-Feb-2012 08:54
Use libxml_disable_entity_loader() to restrict loading of external files.  See http://www.idontplaydarts.com/2011/02/scanning-the-internal-network-using-simplexml/
Diego Araos, diego at klapmedia dot com 05-Feb-2011 12:57
A simpler way to transform the result into an array (requires json module).

<?php
function object2array($object) { return @json_decode(@json_encode($object),1); }
?>

Example:
<?php
$xml_object=simplexml_load_string('<SOME XML DATA');
$xml_array=object2array($xml_object);
?>
ascammon at hotmail dot com 28-Dec-2010 01:04
I had a hard time finding this documented, so posting it here in case it helps someone:

If you want to use multiple libxml options, separate them with a pipe, like so:

<?php
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
?>
jeff at creabilis dot com 17-Nov-2009 02:28
If you want to set the charset of the outputed xml, simply set the encoding attribute like this :

<?php simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><xml/>'); ?>

The generated xml outputed by $xml->asXML will containt accentuated characters like 'é' instead of &#xE9;.

Hope this help
Bob 17-Jun-2009 02:16
Here is my simple SimpleXML wrapper function.
As far as I can tell, it does the same as Julio Cesar Oliveira's (above).
It parses an XML string into a multi-dimensional associative array.
The second argument is a callback that is run on all data (so for example, if you want all data trimmed, like Julio does in his function, just pass 'trim' as the second arg).
<?php
function unserialize_xml($input, $callback = null, $recurse = false)
/* bool/array unserialize_xml ( string $input [ , callback $callback ] )
 * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data
 * Returns false on all failure
 * Notes:
    * Root XML tags are stripped
    * Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input
    * Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info
 */
{
    // Get input, loading an xml string with simplexml if its the top level of recursion
    $data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;
    // Convert SimpleXMLElements to array
    if ($data instanceof SimpleXMLElement) $data = (array) $data;
    // Recurse into arrays
    if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);
    // Run callback and return
    return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
}
?>
Julio Cesar Oliveira 30-Mar-2009 07:14
The XML2Array func now Recursive!

<?php
function XML2Array ( $xml , $recursive = false )
{
    if ( ! $recursive )
    {
        $array = simplexml_load_string ( $xml ) ;
    }
    else
    {
        $array = $xml ;
    }

    $newArray = array () ;
    $array = ( array ) $array ;
    foreach ( $array as $key => $value )
    {
        $value = ( array ) $value ;
        if ( isset ( $value [ 0 ] ) )
        {
            $newArray [ $key ] = trim ( $value [ 0 ] ) ;
        }
        else
        {
            $newArray [ $key ] = XML2Array ( $value , true ) ;
        }
    }
    return $newArray ;
}
?>
javalc6 at gmail dot com 18-Oct-2008 06:25
I wanted to convert an array containing strings and other arrays of the same type into a simplexml object.

Here is the code of the function array2xml that I've developed to perform this conversion. Please note that this code is simple without any checks.

<?php
function array2xml($array, $tag) {

    function ia2xml($array) {
        $xml="";
        foreach ($array as $key=>$value) {
            if (is_array($value)) {
                $xml.="<$key>".ia2xml($value)."</$key>";
            } else {
                $xml.="<$key>".$value."</$key>";
            }
        }
        return $xml;
    }

    return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>");
}

$test['type']='lunch';
$test['time']='12:30';
$test['menu']=array('entree'=>'salad', 'maincourse'=>'steak');

echo array2xml($test,"meal")->asXML();
?>
rowan dot collins at gmail dot com 10-Jul-2008 07:07
There seems to be a lot of talk about SimpleXML having a "problem" with CDATA, and writing functions to rip it out, etc. I thought so too, at first, but it's actually behaving just fine under PHP 5.2.6

The key is noted above example #6 here:
http://uk2.php.net/manual/en/simplexml.examples.php

"To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object."

If a tag contains CDATA, SimpleXML remembers that fact, by representing it separately from the string content of the element. So some functions, including print_r(), might not show what you expect. But if you explicitly cast to a string, you get the whole content.

<?php
$xml = simplexml_load_string('<foo>Text1 &amp; XML entities</foo>');
print_r($xml);
/*
SimpleXMLElement Object
(
    [0] => Text1 & XML entities
)
*/

$xml2 = simplexml_load_string('<foo><![CDATA[Text2 & raw data]]></foo>');
print_r($xml2);
/*
SimpleXMLElement Object
(
)
*/
// Where's my CDATA?

// Let's try explicit casts
print_r( (string)$xml );
print_r( (string)$xml2 );
/*
Text1 & XML entities
Text2 & raw data
*/
// Much better
?>
amir_abiri at ipcmedia dot com 08-Feb-2008 08:47
It doesn't seem to be documented anywhere, but you can refer to an element "value" for the purpose of changing it like so:

<?php
$xml = simplexml_load_string('<root><number>1</number></root>');
echo $xml->asXml(). "\n\n";

$xml->number->{0} = $xml->number->{0} + 1;

echo $xml->asXml();
?>

echos:
<?xml version="1.0"?>
<root><number>1</number></root>

<?xml version="1.0"?>
<root><number>2</number></root>

However, this only works with a direct assignment, not with any of the other operators:

<?php
$xml = simplexml_load_string('<root><number>1</number></root>');
echo $xml->asXml(). "\n\n";

$xml->number->{0} += 1;
// Or:
$xml->number->{0}++;

echo $xml->asXml();
?>

Both of the above cases would result in:

<?xml version="1.0"?>
<root><number>1</number></root>

<?xml version="1.0"?>
<root><number>1<0/></number></root>
bojan 04-Feb-2008 04:38
As was said before don't use var_dump() or print_r() to see SimpleXML object structure as they do not returns always what you expect.
Consider the following:

<?php

// data in xml
$xml_txt = '
<root>
  <folder ID="65" active="1" permission="1"><![CDATA[aaaa]]></folder>
  <folder ID="65" active="1" permission="1"><![CDATA[bbbb]]></folder>
</root>';

// load xml into SimpleXML object
$xml = simplexml_load_string($xml_txt, 'SimpleXMLElement', LIBXML_NOCDATA);//LIBXML_NOCDATA LIBXML_NOWARNING

// see object structure
print_r($xml);

/* this prints
SimpleXMLElement Object
(
    [folder] => Array
        (
            [0] => aaaa
            [1] => bbbb
        )

)
*/

// but...
foreach ($xml->folder as $value){
    print_r($value);
}
/* prints complete structure of each folder element:
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [ID] => 65
            [active] => 1
            [permission] => 1
        )

    [0] => aaaa
)

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [ID] => 65
            [active] => 1
            [permission] => 1
        )

    [0] => bbbb
)

*/
?>
hattori at hanso dot com 15-Oct-2007 03:19
Theres a problem with the below workaround when serializing fields containing html CDATA. For any other content type then HTML try to modfiy function parseCDATA.
Just add these lines before serializing.
This is also a workaround for this bug http://bugs.php.net/bug.php?id=42001

<?PHP
if(strpos($content, '<![CDATA[')) {
   function parseCDATA($data) {
      return htmlentities($data[1]);
   }
   $content = preg_replace_callback(
      '#<!\[CDATA\[(.*)\]\]>#',
      'parseCDATA',
      str_replace("\n", " ", $content)
   );
}
?>
nbijnens at servs dot eu 10-Sep-2007 05:17
Please note that not all LIBXML options are supported with the options argument.

For instance LIBXML_XINCLUDE does not work. But there is however a work around:

<?php
$xml = new DOMDocument();
$xml->loadXML ($XMLString);

$xml->xinclude();
$xml = simplexml_import_dom($xml);

?>
Pedro 06-Jul-2007 01:28
Attention:

simplexml_load_string has a problem with entities other than (&lt;, &gt;, &amp;, &quot; and &apos;).

Use numeric character references instead!
m dot ament at mailcity dot com 06-Mar-2007 06:51
Warning:

The parsing of XML-data will stop when reaching character 0.
Please avoid this character in your XML-data.
mindpower 30-Jan-2007 03:03
A simple extension that adds a method for retrieving a specific attribute:

<?php
class simple_xml_extended extends SimpleXMLElement
{
    public    function    Attribute($name)
    {
        foreach($this->Attributes() as $key=>$val)
        {
            if($key == $name)
                return (string)$val;
        }
    }

}

$xml = simplexml_load_string('
<xml>
  <dog type="poodle" owner="Mrs Smith">Rover</dog>
</xml>', 'simple_xml_extended');

echo $xml->dog->Attribute('type');

?>

outputs 'poodle'

I prefer to use this technique rather than typecasting attributes.
Maciek Ruckgaber <maciekrb at gmai dot com> 07-Jun-2005 05:07
after wondering around some time, i just realized something (maybe obvious, not very much for me). Hope helps someone to not waste time as i did :-P

when you have something like:

<?php
$xmlstr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<double xmlns="http://foosite.foo/">2328</double>
XML;
?>

you will have the simpleXML object "transformed" to the text() content:

<?php
$xml = simplexml_load_string($xmlstr);
echo $xml; // this will echo 2328  (string)
?>
cellog at php dot net 31-Aug-2004 04:11
simplexml does not simply handle CDATA sections in a foreach loop.

<?php
$sx = simplexml_load_string('
<test>
 <one>hi</one>
 <two><![CDATA[stuff]]></two>
 <t>
  <for>two</for>
 </t>
 <multi>one</multi>
 <multi>two</multi>
</test>');
foreach((array) $sx as $tagname => $val) {
    if (is_string($val)) {
       // <one> will go here
    } elseif (is_array($val)) {
       // <multi> will go here because it happens multiple times
    } elseif (is_object($val)) {
      // <t> will go here because it contains tags
      // <two> will go here because it contains CDATA!
    }
}
?>

To test in the loop, do this

<?php
if (count((array) $val) == 0) {
    // this is not a tag that contains other tags
    $val = '' . $val;
    // now the CDATA is revealed magically.
}
?>


WDDX

  • Introdução
  • Instalação/Configuração
    • Dependências
    • Instalação
    • Configurações em Execução
    • Tipos de Recurso
  • Constantes pré-definidas
  • Exemplos
    • Exemplos de wddx
  • Funções da WDDX
    • wddx_add_vars — Add variables to a WDDX packet with the specified ID
    • wddx_deserialize — Desserializa um pacote WDDX
    • wddx_packet_end — Finaliza um pacote WDDX com o ID especificado
    • wddx_packet_start — Inicializa um novo pacote WDDX com uma estrutura dentro dele
    • wddx_serialize_value — Serializa um único valor em um pacote WDDX
    • wddx_serialize_vars — Serializa variáveis em um pacote WDDX

User Contributed Notes

There are no user contributed notes for this page.


Introdução

Aviso

Esta extensão está DEFASADA e DESAGREGADA a partir do PHP 7.4.0.

Essas funções tem o intuito de funcionar com » WDDX.

Aviso

Não passe entrada não confiável do usuário para a função wddx_deserialize(). Desserialização pode resultar em código sendo carregado e executado devido à instanciação de objetos e auto-carregamento, um usuário malicioso pode ser capaz de explorar isto. Use um formato de intercâmbio de dados padrão e seguro como JSON (via json_decode() e json_encode()) se for necessário passar dados serializados ao usuário.

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


Dependências

Esta extensão requer a extensão PHP libxml. Isso significa que ao compilar o PHP é preciso passar a flag de configuração --with-libxml, ou antes do PHP 7.4, --enable-libxml, embora isso seja feito implicitamente pois a libxml está habilitada por padrão.

Para usar WDDX, você precisará instalar a biblioteca expat (que vem com o Apache 1.3.7 ou superior).

User Contributed Notes

There are no user contributed notes for this page.


Instalação

PHP 7.4

Esta extensão foi movida para o repositório » PECL e não é mais distribuída com o PHP desde a versão 7.4.0

Informações para instalar esta extensão PECL podem ser encontradas no capítulo Instalação de Extensões PECL do manual. Informações adicionais, como novas versões, downloads, arquivos fontes, informações do mantenedor e um CHANGELOG, podem ser encontradas aqui: » https://pecl.php.net/package/wddx.

PHP < 7.4

Depois de instalar a bilioteca expat requerida, compile o PHP com a opção --enable-wddx, e use --with-libexpat-dir para a expat.

A versão do PHP para Windows tem suporte nativo para esta extensão. Nenhuma extensão adicional precisa ser carregada para usar essas funções.

User Contributed Notes

There are no user contributed notes for this page.


Tipos de Recurso

Essa extensão define um identificador de pacote WDDX retornado por wddx_packet_start().

User Contributed Notes

There are no user contributed notes for this page.


Exemplos

Índice

  • Exemplos de wddx

User Contributed Notes

dormilich at netscape dot net 27-Nov-2008 06:37
If you want to use the WDDX 1.0 DTD for validation (http://www.openwddx.org/downloads/dtd/wddx_dtd_10.txt) check that you define the comment as element, not as attribute.

<?xml version="1.0" encoding="iso-8859-1" ?>
<wddxPacket version='1.0'>
    <header>
        <comment>PHP</comment>
    </header>
    <data><!-- WDDX serialized data --></data>
</wddxPacket>


Exemplos de wddx

Todas as funções que serializam variáveis usam o primeiro elemento de um array para determinar se o array deve ser serializado em um array ou estrutura. Se o primeiro elemento tem uma chave string, então ele é serializado em uma estrutura, caso contrário, em um array.

Exemplo #1 Serializando um único valor com WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

Este exemplo irá produzir:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Exemplo #2 Usando pacotes incrementais com WDDX

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo $packet;
?>

Este exemplo irá produzir:

<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 devem ser codificadas em UTF-8; para lidar com outras codificações, converta a string primeiramente usando mb_convert_encoding(), você tem que primeiro UConverter::transcode() ou iconv().

User Contributed Notes

There are no user contributed notes for this page.


Funções da WDDX

Índice

  • wddx_add_vars — Add variables to a WDDX packet with the specified ID
  • wddx_deserialize — Desserializa um pacote WDDX
  • wddx_packet_end — Finaliza um pacote WDDX com o ID especificado
  • wddx_packet_start — Inicializa um novo pacote WDDX com uma estrutura dentro dele
  • wddx_serialize_value — Serializa um único valor em um pacote WDDX
  • wddx_serialize_vars — Serializa variáveis em um pacote WDDX

User Contributed Notes

iGEL 14-Mar-2008 02:03
As of version 5.2.5, this is wrong:

> Note: If you want to serialize non-ASCII characters you
> have to convert your data to UTF-8 first (see utf8_encode()
> and iconv()).

Serializing a string with WDDX will always convert it from ISO-8859-1 to UTF-8, no matter what the original encoding is. So if your data already are UTF-8, you get just gibberish.

You can restore the original encoding by using utf8_decode on the serialized wddx data, even though your original data may use chars not included in ISO-8859-1:

<?php
header("Content-Type: text/xml;encoding=utf-8");
echo utf8_decode(wddx_serialize_value("?? ???"));
?>

(This is why I dislike PHP, sorry)
egbert teeselink 23-Feb-2008 10:49
If your PHP doesn't have wddx support installed, and you need it, and you don't want to install PEAR just for wddx, try this short piece of code, based on SimpleXML:

//can read any wddx file generated from php arrays. assumes var elements are only inside struct elements and that only one packet exists.
function wddx_read_node($node, $type)
{
    switch($type)
    {
    case "boolean":
        return (string)$node;
    case "number":
    case "binary":
    case "string":
        return (string)$node;
    case "null":
        return null;
    case "array":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            $a[] = wddx_read_node($subnode, $subtype);
        }
        return $a;
    case "struct":
        $a = array();
        foreach($node as $subtype => $subnode)
        {
            list($key, $value) = wddx_read_node($subnode, $subtype); //must be a var element
            $a[$key] = $value;
        }
        return $a;
    case "var":
        list($subnode, $subtype) = getchild($node);
        return array((string)$node["name"], wddx_read_node($subnode, $subtype));
    case "data":
        list($subnode, $subtype) = getchild($node);
        return wddx_read_node($subnode, $subtype);
    }
}

function wddx_read($string)
{
    $xml = simplexml_load_string($string);
    $d = wddx_read_node($xml->data, "data");
    return $d;
}

important notice: this one may not work with all wddx input. multiple packets or variables outside a "struct" are not supported. basically, you always get a PHP (associative) array, never something else. feel free to make additions.
no at spam dot thx 12-Aug-2007 02:09
To bradburn at kiwi dot de:

PHP is only capable of serializing properly variables which match one of its native (scalar) types (See http://php.net/types). Which means that only variables of type booleans, integers, floating point numbers, string and NULL will be serialized properly.

I think there are two exceptions though:
- arrays are serialized by processing them recursively, so if its only composed of the above mentioned types, you should be fine.
- floating point numbers and integers may use the same representation while serialized in WDDX (I don't know much about WDDX, so I'm not 100% sure about this statement).

An interesting case would be whether objects can be serialized or not...
Jimmy Wimenta 15-Jul-2004 05:53
PHP's WDDX is useful only for exchanging data between PHP applications, but definetly not for exchanging data between different languages (which actually defeats the purpose of WDDX).

For example:

$hash1 = array ("2" => "Two", "4" => "Four", "5" => "Five");
$hash2 = array ("0" => "Zero", "1" => "One", "2" => "Two");

$hash1 will be serialized as hash, but
$hash2 will be serialized as array/list, because the key happen to be a sequence starting from 0.

Unless the library provide a way for users to specify the type, it can never be used for cross-platform data exchange.
Q1tum at hotmail dot com 21-Nov-2003 05:08
To insert arrays into a wddx variable here is a fine way to do it:

<?php

$sql = 'SELECT * FROM example';
$query = mysql_query($sql, $db) or die(mysql_error());

while($result = mysql_fetch_array($query)) {
    $id[] = $result[ 'id'];
    $name[] = $result['name'];
    $description[] = $result[$prefix . 'description'];
}

mysql_free_result($query);

wddx_add_vars($packet_id, "id");
wddx_add_vars($packet_id, "name");
wddx_add_vars($packet_id, "description");

$wddxSerializeValue = wddx_packet_end($packet_id);

?>
bradburn at kiwi dot de 30-Jul-2002 07:02
With ref to the above comment about typing, I have found that -- oddly enough -- PHP's WDDX supports the following WDDX types: null, boolean (true/false), number and string, *but* not date-time.

as an example, use the following values in an array that you then serialize:

$number = 5,
$null = NULL,
$bool = true,
$string = 'this is a string'.

they will all serialize correctly, e.g. the third entry comes out as:

<var name='bool'><boolean value='true'/></var>

i have tried with the 'official' format for WDDX 'datetime', e.g. '1998-9-15T09:05:32+4:0' (from the DTD @ http://www.openwddx.org/downloads/dtd/wddx_dtd_10.txt)  but have only succeeded in getting this encoded as a 'string' type.

if anyone else has any more information on this, it would be welcome. i would like to store the variables in 'appropriate' fields in a database, and the fact that only datetime is not supported is slightly irritating -- otherwise it would be a very useful function.
djm at web dot us dot uu dot net 18-Oct-1999 08:45
Since there aren't any examples of reversing the process, here's one. If you had the packet produced by the above example (without the htmlentities() call), you could retrieve the values like this:

<?php
$value = wddx_deserialize($packet);
print "pi is:<br>" . $value["pi"] . "<p>\n";
print "cities is:<br>\n";
while (list($key, $val) = each($value["cities"])) {
    print "$key => $val<br>\n";
}
?>

which outputs:

<pre>
pi is:
3.1415926

cities is:
0 => Austin
1 => Novato
2 => Seattle
</pre>


Add variables to a WDDX packet with the specified ID

  • « Funções da WDDX
  • wddx_deserialize »
  • PHP Manual
  • Funções da WDDX
  • Add variables to a WDDX packet with the specified ID

wddx_add_vars

(PHP 4, PHP 5, PHP 7)

wddx_add_vars — Add variables to a WDDX packet with the specified ID

Aviso

Esta função foi REMOVIDA a partir do PHP 7.4.0.

Descrição

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

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

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 !


Desserializa um pacote WDDX

  • « wddx_add_vars
  • wddx_packet_end »
  • PHP Manual
  • Funções da WDDX
  • Desserializa um pacote WDDX

wddx_deserialize

(PHP 4, PHP 5, PHP 7)

wddx_deserialize — Desserializa um pacote WDDX

Aviso

Esta função foi REMOVIDA a partir do PHP 7.4.0.

Descrição

wddx_deserialize(string $packet): mixed

Desserializa um packet WDDX.

Aviso

Não passe informações de usuários não confiáveis para wddx_deserialize(). A desserialização pode resultar no carregamento e execução do código devido à instanciação e carregamento automático do objeto, e um usuário mal-intencionado pode explorar isso. Use um formato de intercâmbio de dados padrão e seguro, como JSON (através de json_decode() e json_encode()) se você precisar passar dados serializados para o usuário.

Parâmetros

packet

Um pacote WDDX, como uma string ou stream.

Valor Retornado

Retorna o valor desserializado que pode ser uma string, um número ou um array. Observe que as estruturas são desserializadas em arrays associativos.

User Contributed Notes

valer underscore crisan at yahoo 01-Apr-2009 02:03
In PHP 5.2.9, we noticed that wddx serialize and deserialize seems to use UTF-8 encoding for XML input and the output data. There are some posts below that talk about fixing the input XML data so deserialize would work fine on special chars in ISO-8859-1 encoding, but none of the posts talks about the output encoding.

Consider this test:
$text = "Jür";
$packet = wddx_serialize_value($text);
$header = '<?xml version="1.0" encoding="iso-8859-1"?>';
$newText = wddx_deserialize($header . $packet);
echo "WDDX Packet: $packet\n";
echo "Deserialized Object: $newText\n";

The output is:

WDDX Packet: <wddxPacket version='1.0'><header/><data><string>Jür</string></data></wddxPacket>
Deserialized Object: JÃ¼r

The deserialized string is not in ISO-8859-1 encoding. It is in UTF-8 encoding. So we need to run utf8_decode() on the deserialized data to convert it back to ISO-8859-1 encoding which is what our application expects.

Hope this helps.
Magnus Deininger, dma05 at web dot de 12-Feb-2009 05:57
When writing your wddx file manually with an UTF-8 aware editor and saving it in utf-8, if your data gets its special characters mysteriously scrambled, try to add an xml header that marks the output as iso-8859-1, like this one:

<?xml version="1.1" encoding="iso-8859-1" ?>

This makes the wddx decode function treat the input as iso-8859-1, so it will not try to treat it as utf-8 and do an implicit decode to iso-8859-1. You will then have read all string data in the wddx packet in their original utf-8 encoding, so that 'echo' and other output functions will produce the intended result if you have set the output encoding to utf-8.

(Bugs reports on this behaviour seem to be treated as bogus, so it would seem in order to point out this incorrect and highly confusing side-effect.)
dormilich at netscape dot net 28-Nov-2008 05:13
When deserializing objects make sure you have the class definition loaded. wddx_deserialize() doesn't call the class itself, so you will receive a fatal error.
Nevertheless you can look for the class manually and delegate it to __autoload().

<?php
// $wddx_string needs to be valid XML to be loaded by SimpleXML.
// class_exists() will call the __autoload() function. if you don't
// want to use __autoloload(), use require_once()

function loadClassesFromWDDX($wddx_string)
{
    $xml = new SimpleXMLElement($wddx_string);

    foreach ($xml->xpath('//var') as $var)
    {
        if ($var['name'] == 'php_class_name')
        {
            if (!class_exists($var->string))
            {
                throw new Exception('Class '" . $var->string . "'not available.');
                // trigger_error('Class '" . $var->string . "'not available.', E_USER_ERROR);
            }
        }
    }
}
?>
dave at codexweb dot co dot za 21-Jan-2006 04:40
Here's a handy wddx_deserialize clone I wrote a while back. It uses PHP5 SimpleXML and recursion to do pretty much the same task as wddx_deserialize. Hope it comes in handy for someone.

<?php

if (!function_exists('wddx_deserialize'))
{
    /**
     * Clone implementation of wddx_deserialize
     */
    function wddx_deserialize($xmlpacket)
    {
        if ($xmlpacket instanceof SimpleXMLElement)
        {
            if (!empty($xmlpacket->struct))
            {
                $struct = array();
                foreach ($xmlpacket->xpath("struct/var") as $var)
                {
                    if (!empty($var["name"]))
                    {
                        $key = (string) $var["name"];
                        $struct[$key] = wddx_deserialize($var);
                    }
                }
                return $struct;
            }
            else if (!empty($xmlpacket->array))
            {
                $array = array();
                foreach ($xmlpacket->xpath("array/*") as $var)
                {
                    array_push($array, wddx_deserialize($var));
                }
                return $array;
            }
            else if (!empty($xmlpacket->string))
            {
                return (string) $xmlpacket->string;
            }
            else if (!empty($xmlpacket->number))
            {
                return (int) $xmlpacket->number;
            }
            else
            {
                if (is_numeric((string) $xmlpacket))
                {
                    return (int) $xmlpacket;
                }
                else
                {
                    return (string) $xmlpacket;
                }
            }
        }
        else
        {
            $sxe = simplexml_load_string($xmlpacket);
            $datanode = $sxe->xpath("/wddxPacket[@version='1.0']/data");
            return wddx_deserialize($datanode[0]);
        }
    }
}

?>
php dot net at werner-ott dot de 24-Nov-2005 12:20
On migrating wddx_deserialize() from PHP 4.x to PHP 5.1 (5.1.0RC6):

While

  $buffer = wddx_serialize_vars($some_array);
  $some_array = wddx_deserialize($buffer);

worked fine with PHP 4.x, the deserialization failed with PHP 5.1. In the above example $some_array will just be an empty string under 5.1

While wddx_serialize_vars() seems to behave identical in 4.x and 5.1, wddx_deserialize() does NOT.

Prepending XML encoding information to the buffer turned out to be at least a workaround. So, the following works with PHP 5.1:

  $buffer = wddx_serialize_vars($some_array);
  $buffer = '<?xml version="1.0"
          encoding="ISO-8859-1"?>'.
          $buffer;
  $some_array = wddx_deserialize($buffer);

NB: It may well be, that the behavioural difference between 4.x and 5.1 described above can only be observed if the array contains certain characters, i.e. german Umlaute (??????). So this workaround may not be necessary in each and every case.
mail_fidel at yahoo dot com 19-Nov-2004 12:11
To properly deserialize a wddx file it was to be utf8_encoded.

The following code will NOT work (PHP5.0.2 FreeBSD):

<?php
   $data = wddx_serialize_value(array("xyz???","abcd"));
   print $data;
   print_r(wddx_deserialize($data));

?>

Even thought the serialization is done right, the deserialization will not work unless you encode the text using utf8.

This code WILL work:

<?php
   $data = wddx_serialize_value(array(utf8_encode("xyz???"),"abcd"));
   print $data;
   print_r(wddx_deserialize($data));

?>
xavier at c-est-simple dot com 19-May-2004 04:09
JavaScript/PHP interroperability:

If you want to exchange wddx packets between a JavaScript application using the JS wddx library from openwddx (http://www.openwddx.org/downloads/), and a PHP script using wddx functions, be aware that the encoding of the classes of objects serialized in the wddx packet is not made the same way in both implementations.

The JS lib uses a 'type' attribute in the 'struct' tab and gives it the name of the class of the object serialized in the 'struct' element, while PHP uses a 'php_class_name' tag within the 'struct'.
NB : to get the type attribute with JS serialisation, you need to set the 'wddxSerializationType' member in your classes

Example with an object of class 'exemple' containing 2 members _attr1 and _attr2.
(NB : in french, 'example' is spelled 'exemple', okay ? :-)

JS serialization :
<wddxPacket version='1.0'>
 <header/>
 <data>
  <struct type="exemple">
   <var name='_attr1'>
    <string>foo</string>
   </var>
   <var name='_attr2'>
    <string>bar</string>
   </var>
  </struct>
 </data>
</wddxPacket>

php serialization:
<wddxPacket version='1.0'>
 <header/>
 <data>
  <struct>
   <var name='php_class_name'>
    <string>exemple</string>
   </var>
   <var name='_attr1'>
    <string>foo</string>
   </var>
   <var name='_attr2'>
    <string>bar</string>
   </var>
  </struct>
 </data>
</wddxPacket>

I like the JS approach better.
So if you need the compatibility, the workaround is quite simple:
- add a 'php_class_name' member in your JS objects, giving it the name of the class for value, and the JS generated packet will be correctly deserialized with PHP in classed objects.

- use a regexp on a PHP generated packet to add the 'type' attribute so that the JS deserialization instanciates objects of the right class:
      $pat = "/<struct><var name='php_class_name'><string>(\w+)<\/string>/" ;
      $rep = "<struct type='\$1'><var name='php_class_name'><string>\$1</string>" ;
      $serialised = preg_replace($pat, $rep, $serialised );
NB : this only works because the 'php_class_name' tag is just next to the 'struct' tag.
Who knows if this is going to be true in future releases... ?

This way, you can exchange JS and PHP objects (provided you define your JS and PHP classes the same way) smoothly...

It's worth saying that both implementations, as well as my interroperability workaround, handle correctly objects with members that are also objects.

NB : NB means Nota Bene.
xavier at c-est-simple.com 18-May-2004 10:19
Beware, although the deserialized objects are instanciated class objects (if the php_class_name tag is amongst the children of the struct tag and its text content is the name of a loaded class), the constructor of the class has not been called at all.
You can use the members and call the methods of the object all right, but any initialisation action that the constructor might be in charge of is missing.
php at mike2k dot com 10-Sep-2001 06:06
if you have WDDX data coming from a third party source and it isnt being parsed correctly in your php, try translating their WDDX. we have a third party sending us WDDX from cold fusion, and it uses a <recordset> element, which PHP seems to ignore (looking around the web we found some other people having trouble) so the (hopefully temporary) solution we found was to translate the WDDX midstream and then we were able to parse it:

$url = "http://somedomain.com/blah.wddx";
$fp = fopen($url,"r");
$page = fread($fp,10000);
fclose($fp);
$page = str_replace("<recordset","<struct",$page);
$page = str_replace("</recordset","</struct",$page);
$page = str_replace("<field","<var",$page);
$page = str_replace("</field","</var",$page);
$values = wddx_deserialize($page);
while(list($key,$val) = each($values)) {
        print "$key => $val<BR>";
}

this works for us. it's a hack, and hopefully php will support this in the future or something.
medvitz at medvitz dot net 14-Oct-2000 05:29
You can also serialize instantiated class objects with the wddx functions.
ie.

<?php
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "objvar");
$packet = wddx_packet_end($packet_id);

$a =  wddx_deserialize($packet);
$obj = $a[objvar];
?>

now $obj is a useable object, that looks like the original.

Note that with this method, you need to know what the variable name of the original object was.  You can use one of the array functions to get the object in the event that the original object's variable name was unknown.

*** only verified on linux with 4.0.2
djm at web dot us dot uu dot net 18-Oct-1999 09:58
The packet string you pass to this function doesn't have to be sanitized first; it searches for a WDDX packet within the string.  So the string can contain HTML markup and random text outside of the packet, and that is all ignored.
This means you can get a packet from another web page like this:
<?php
$fhandle = fopen("http://myserver.com/packet.php", "r");
if ($fhandle) {
        $page = fread($fhandle,10000);
        fclose($fhandle);
        $value = wddx_deserialize($page);
        print "pi is:<br>" . $value["pi"] . "<p>\n";
} else {
        print "could not get packet.php<p>";
}
?>


Finaliza um pacote WDDX com o ID especificado

  • « wddx_deserialize
  • wddx_packet_start »
  • PHP Manual
  • Funções da WDDX
  • Finaliza um pacote WDDX com o ID especificado

wddx_packet_end

(PHP 4, PHP 5, PHP 7)

wddx_packet_end — Finaliza um pacote WDDX com o ID especificado

Aviso

Esta função foi REMOVIDA a partir do PHP 7.4.0.

Descrição

wddx_packet_end(resource $packet_id): string

Finaliza e retorna um pacote WDDX escolhido.

Parâmetros

packet_id

Um pacote WDDX, retornado por wddx_packet_start().

Valor Retornado

Retorna a string com o pacote WDDX.

User Contributed Notes

There are no user contributed notes for this page.


Inicializa um novo pacote WDDX com uma estrutura dentro dele

  • « wddx_packet_end
  • wddx_serialize_value »
  • PHP Manual
  • Funções da WDDX
  • Inicializa um novo pacote WDDX com uma estrutura dentro dele

wddx_packet_start

(PHP 4, PHP 5, PHP 7)

wddx_packet_start — Inicializa um novo pacote WDDX com uma estrutura dentro dele

Aviso

Esta função foi REMOVIDA a partir do PHP 7.4.0.

Descrição

wddx_packet_start(string $comment = ?): resource

Inicializa um novo pacote WDDX para adição incremental de variáveis. A função cria automaticamente uma definição de estrutura dentro do pacote para armazenar as variáveis.

Parâmetros

comment

Uma string opcional contendo comentários.

Valor Retornado

Retorna o ID do pacote para ser usado em outras funções ou false em caso de erro.

User Contributed Notes

There are no user contributed notes for this page.


Serializa um único valor em um pacote WDDX

  • « wddx_packet_start
  • wddx_serialize_vars »
  • PHP Manual
  • Funções da WDDX
  • Serializa um único valor em um pacote WDDX

wddx_serialize_value

(PHP 4, PHP 5, PHP 7)

wddx_serialize_value — Serializa um único valor em um pacote WDDX

Aviso

Esta função foi REMOVIDA a partir do PHP 7.4.0.

Descrição

wddx_serialize_value(mixed $var, string $comment = ?): string

Cria um pacote WDDX a partir de uma única variável.

Parâmetros

var

Variável a ser serializada

comment

Um comentário (opcional) que aparece no cabeçalho do pacote.

Valor Retornado

Retorna o pacote WDDX ou false em caso de erro.

User Contributed Notes

chris at digitalbase dot com 04-Jan-2002 04:36
When serializing JavaScript objects to interact with PHP objects, you should make the JavaScript object's first entry a php_class_name.

PHP:
class myclass {
    var $name;
    var $age;
    var $ssn;
    ...

    function myclass() {
        $this->name = "";
        $this->age = "";
        $this->ssn = "";
        ...
    }
}

JavaScript:
// serialization example code is from the
// WDDX SDK http://www.openwddx.org
function SerializeMsg(name, age, ssn, ...) {
    var MyObj = new Object;

    // the following line is necessary in order
    // to deserialize back to a PHP object
    MyObj.php_class_name = "myclass";

    MyObj.name = name;
    MyObj.age = age;
    MyObj.ssn = ssn;
    ...

    // Create a new serializer "object" to do our work for us
    MySer = new WddxSerializer;

    // Serialize the Message variable into a WDDX Packet
    MyWDDXPacket = MySer.serialize(MyObj);

    // Output WDDX Packet so we can see what it looks like
    return MyWDDXPacket;
}

Now you can use this in a page which is its own form action:
<?php
// don't forget to include the class definition from above!
if (!isSet($wddx_packet))
    $MyObj = new myclass();
else
    $MyObj = wddx_deserialize($wddx_packet);
?>

<html>
<head>
<script language="JavaScript">
<!--
function Init() {
    // sets the form's text-elements
    tmp = document.MyForm;

    tmp.name.value = "<? echo $MyObj->name ?>";
    tmp.age.value = "<? echo $MyObj->age ?>";
    tmp.ssn.value = "<? echo $MyObj->ssn ?>";
    ...
}

function SerializeMsg(name, age, ssn, ...) {
// see above!
}

function SubmitForm() {
    // sumbits the form
    tmp = document.MyForm;

    tmp.wddx_packet.value =
    SerializeMsg(tmp.name.value, tmp.age.value, tmp.ssn.value,...);
    document.submit();
}
// -->
</script>
</head>
<body>
...
<form name="MyForm"
action="<? echo $PHP_SELF ?>" method="post">
<input name="wddx_packet" type="hidden">
<input name="name" type="text">
<input name="age" type="text">
<input name="ssn" type="text">
...
<input name="SubmitBtn" type="button" onclick="SumbitForm()">
</form>
</body>
</html>

---------------------------------
If you don't provide that first 'php_class_name' in the JavaScript function, then when PHP deserializes it will deserialize into an associative array and not an object instance.

Note that this provides a way to maintain state without
using sessions or cookies - just good old HTML!

Hope this helps!
--
Chris Hansen


Serializa variáveis em um pacote WDDX

  • « wddx_serialize_value
  • XMLDiff »
  • PHP Manual
  • Funções da WDDX
  • Serializa variáveis em um pacote WDDX

wddx_serialize_vars

(PHP 4, PHP 5, PHP 7)

wddx_serialize_vars — Serializa variáveis em um pacote WDDX

Aviso

Esta função foi REMOVIDA a partir do PHP 7.4.0.

Descrição

wddx_serialize_vars(mixed $var_name, mixed ...$var_names): string

Cria um pacote WDDX com um estrutura que contém a representação serializada das variáveis passadas.

Parâmetros

Essa função recebe um número variável de argumentos.

var_name

Pode ser ou uma string com o nome de uma variável ou um array contendo strings com o nome de variáveis ou outro array, recursivamente.

var_names

Valor Retornado

Retorna o pacote WDDX ou false em caso de erro.

Exemplos

Exemplo #1 Exemplo de uso de wddx_serialize_vars()

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>

O exemplo acima produzirá:

<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var>
<var name='b'><number>5.5</number></var><var name='c'><array length='3'>
<string>blue</string><string>orange</string><string>violet</string></array></var>
<var name='d'><string>colors</string></var></struct></data></wddxPacket>

User Contributed Notes

kangus at jaga dot us 13-Oct-2003 03:57
A function to use for dates with PHP & WDDX
getdate()

$ta="<FORM><TEXTAREA rows=15 cols=80>" ;
$te="</TEXTAREA></FORM>";
$packet_id=wddx_packet_start("Date Example--");
$myDate=getdate();
wddx_add_vars($packet_id,'myDate');
$package=wddx_packet_end($packet_id);
print($ta.$package.$te);

Produces:

<wddxPacket version='1.0'><header><comment>Date Example--</comment></header>
<data><struct><var name='myDate'>
<struct><var name='seconds'><number>12</number></var>
<var name='minutes'><number>55</number></var>
<var name='hours'><number>1</number></var>
<var name='mday'><number>13</number></var>
<var name='wday'><number>1</number></var>
<var name='mon'><number>10</number></var>
<var name='year'><number>2003</number></var>
<var name='yday'><number>285</number></var>
<var name='weekday'><string>Monday</string></var>
<var name='month'><string>October</string></var>
<var name='0'><number>1066031712</number>
</var></struct></var></struct></data></wddxPacket>
tychay at alumni dot caltech dot edu 31-Mar-2002 12:15
The above feature will cause a slight trouble since the name of the variable will always be "wddxtemp" but you can use preg_replace to fix that.

Also, a better approach is to serialize the entire class. WDDX will that write a reserved "php_class_name" variable which can be used to reconstruct the class during a deserialize.
tychay at alumni dot caltech dot edu 30-Mar-2002 10:49
You can use globals to get around the above in classes:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx_serialize($this->str);
    header('Content-Type: text/xml');
    echo ($this->wddx);
  }

  function wddx_serialize($var) {
    global $wddxtemp;
    unset($wddxtemp);
    $wddxtemp = $var;
    $this->wddx = wddx_serialize_vars("wddxtemp");
  }
}

new Test();
?>
-terry
tychay at alumni dot caltech dot edu 30-Mar-2002 10:45
You can use globals to get around the above in classes:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx_serialize($this->str);
    header('Content-Type: text/xml');
    echo ($this->wddx);
  }

  function wddx_serialize($var) {
    global $wddxtemp;
    unset($wddxtemp);
    $wddxtemp = $var;
    $this->wddx = wddx_serialize_vars("wddxtemp");
  }
}

new Test();
?>
-terry
christian dot knoflach at gmx dot at 21-May-2001 03:56
Be careful using WDDX - functions on object variables. As I just had to find out the following won't work:

<?php
class Test
{
  var $str;
  var $wddx;

  function Test()
  {
    $this->str = "test";
    $this->wddx = wddx_serialize_vars("this->str");
    print(htmlentities($this->wddx));
  }
}

new Test();
?>

That's what you'll get:
<wddxPacket version='1.0'><header/><data><struct></struct></data></wddxPacket>


XML diff and merge

  • Introdução
  • Instalação/Configuração
    • Dependências
    • Instalação
  • XMLDiff\Base — The XMLDiff\Base class
    • XMLDiff\Base::__construct — Constructor
    • XMLDiff\Base::diff — Produce diff of two XML documents
    • XMLDiff\Base::merge — Produce new XML document based on diff
  • XMLDiff\DOM — The XMLDiff\DOM class
    • XMLDiff\DOM::diff — Diff two DOMDocument objects
    • XMLDiff\DOM::merge — Produce merged DOMDocument
  • XMLDiff\Memory — The XMLDiff\Memory class
    • XMLDiff\Memory::diff — Diff two XML documents
    • XMLDiff\Memory::merge — Produce merged XML document
  • XMLDiff\File — The XMLDiff\File class
    • XMLDiff\File::diff — Diff two XML files
    • XMLDiff\File::merge — Produce merged XML document

User Contributed Notes

There are no user contributed notes for this page.


Introdução

The extension is able to produce diffs of two XML documents and then to apply the difference to the source document. The diff is a XML document containing copy/insert/delete instruction nodes in human readable format. DOMDocument objects, local files and strings in memory can be processed.

User Contributed Notes

There are no user contributed notes for this page.


Dependências

libdiffmark - version 0.10 is bundled with the extension. If diffmark is available from your system packages, its usage is strongly encouraged.

libxml extension

DOM extension

User Contributed Notes

There are no user contributed notes for this page.


Instalação

Esta extensão » PECL não é distribuída com o PHP.

Informações para instalar esta extensão PECL podem ser encontradas no capítulo Instalação de Extensões PECL do manual. Informações adicionais, como novas versões, downloads, arquivos fontes, informações do mantenedor e um CHANGELOG, podem ser encontradas aqui: » https://pecl.php.net/package/xmldiff.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/xmldiff/.

User Contributed Notes

There are no user contributed notes for this page.


The XMLDiff\Base class

(PECL xmldiff >= 0.8.0)

Introdução

Base abstract class for all the comparsion classes in the extension.

Sinopse da classe

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
}

Índice

  • XMLDiff\Base::__construct — Constructor
  • XMLDiff\Base::diff — Produce diff of two XML documents
  • XMLDiff\Base::merge — Produce new XML document based on diff

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • « XMLDiff\Base
  • XMLDiff\Base::diff »
  • PHP Manual
  • XMLDiff\Base
  • Constructor

XMLDiff\Base::__construct

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::__construct — Constructor

Descrição

public XMLDiff\Base::__construct(string $nsname)

Base constructor for all the worker classes in the xmldiff extension.

Parâmetros

nsname

Custom namespace name for the diff document. The default namespace is http://www.locus.cz/diffmark and that's enough to avoid namespace conflicts. Use this parameter if you want to change it for some reason.

User Contributed Notes

There are no user contributed notes for this page.


Produce diff of two XML documents

  • « XMLDiff\Base::__construct
  • XMLDiff\Base::merge »
  • PHP Manual
  • XMLDiff\Base
  • Produce diff of two XML documents

XMLDiff\Base::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::diff — Produce diff of two XML documents

Descrição

abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed

Abstract diff method to be implemented by inheriting classes.

The basic purpose of this method is to produce diff of the two documents. The param order matters and will produce different output.

Parâmetros

from

Source XML document.

to

Target XML document.

Valor Retornado

Implementation dependent.

User Contributed Notes

There are no user contributed notes for this page.


Produce new XML document based on diff

  • « XMLDiff\Base::diff
  • XMLDiff\DOM »
  • PHP Manual
  • XMLDiff\Base
  • Produce new XML document based on diff

XMLDiff\Base::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::merge — Produce new XML document based on diff

Descrição

abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed

Abstract merge method to be implemented by inheriting classes.

Basically the method purpose is to produce a new XML document based on the diff information.

Parâmetros

src

Source XML document.

diff

Document produced by the diff method.

Valor Retornado

Implementation dependent.

User Contributed Notes

There are no user contributed notes for this page.


The XMLDiff\DOM class

(PECL xmldiff >= 0.8.0)

Introdução

Sinopse da classe

class XMLDiff\DOM extends XMLDiff\Base {
/* Métodos */
public diff(DOMDocument $from, DOMDocument $to): DOMDocument
public merge(DOMDocument $src, DOMDocument $diff): DOMDocument
/* Métodos herdados */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Índice

  • XMLDiff\DOM::diff — Diff two DOMDocument objects
  • XMLDiff\DOM::merge — Produce merged DOMDocument

User Contributed Notes

There are no user contributed notes for this page.


Diff two DOMDocument objects

  • « XMLDiff\DOM
  • XMLDiff\DOM::merge »
  • PHP Manual
  • XMLDiff\DOM
  • Diff two DOMDocument objects

XMLDiff\DOM::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::diff — Diff two DOMDocument objects

Descrição

public XMLDiff\DOM::diff(DOMDocument $from, DOMDocument $to): DOMDocument

Diff two DOMDocument instances and produce the new one containing the diff information.

Parâmetros

from

Source DOMDocument object.

to

Target DOMDocument object.

Valor Retornado

DOMDocument with the diff information or NULL.

User Contributed Notes

jeewiya at gmail dot com 28-Mar-2018 10:43
XMLDiff\DOM can be use like this, for compare xml files changes.

<?php

function getChangeElements($currentContent, $oldContent) {
        try {
            $currentDoc = new DOMDocument();
            $currentDoc->loadXML($currentContent);

            $oldDoc = new DOMDocument();
            $oldDoc->loadXML($oldContent);
            $xmldiff = new XMLDiff\DOM();
            return $xmldiff->diff($oldDoc, $currentDoc);
        } catch (Exception $ex) {
            throw $ex;
        }
    }

getChangeElements('updated.xml', 'old.xml');

?>


Produce merged DOMDocument

  • « XMLDiff\DOM::diff
  • XMLDiff\Memory »
  • PHP Manual
  • XMLDiff\DOM
  • Produce merged DOMDocument

XMLDiff\DOM::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::merge — Produce merged DOMDocument

Descrição

public XMLDiff\DOM::merge(DOMDocument $src, DOMDocument $diff): DOMDocument

Create new DOMDocument based on the diff.

Parâmetros

src

Source DOMDocument object.

diff

DOMDocument object containing the diff information.

Valor Retornado

Merged DOMDocument or NULL.

User Contributed Notes

There are no user contributed notes for this page.


The XMLDiff\Memory class

(PECL xmldiff >= 0.8.0)

Introdução

Sinopse da classe

class XMLDiff\Memory extends XMLDiff\Base {
/* Métodos */
public diff(string $from, string $to): string
public merge(string $src, string $diff): string
/* Métodos herdados */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Índice

  • XMLDiff\Memory::diff — Diff two XML documents
  • XMLDiff\Memory::merge — Produce merged XML document

User Contributed Notes

There are no user contributed notes for this page.


Diff two XML documents

  • « XMLDiff\Memory
  • XMLDiff\Memory::merge »
  • PHP Manual
  • XMLDiff\Memory
  • Diff two XML documents

XMLDiff\Memory::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::diff — Diff two XML documents

Descrição

public XMLDiff\Memory::diff(string $from, string $to): string

Diff two strings containing XML documents and produce the diff information.

Parâmetros

from

Source XML document.

to

Target XML document.

Valor Retornado

String with the XML document containing the diff information or NULL.

User Contributed Notes

There are no user contributed notes for this page.


Produce merged XML document

  • « XMLDiff\Memory::diff
  • XMLDiff\File »
  • PHP Manual
  • XMLDiff\Memory
  • Produce merged XML document

XMLDiff\Memory::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::merge — Produce merged XML document

Descrição

public XMLDiff\Memory::merge(string $src, string $diff): string

Create new XML document based on diffs and source document.

Parâmetros

src

Source XML document.

diff

XML document containing diff information.

Valor Retornado

String with the new XML document or NULL.

User Contributed Notes

There are no user contributed notes for this page.


The XMLDiff\File class

(PECL xmldiff >= 0.8.0)

Introdução

Sinopse da classe

class XMLDiff\File extends XMLDiff\Base {
/* Métodos */
public diff(string $from, string $to): string
public merge(string $src, string $diff): string
/* Métodos herdados */
abstract public XMLDiff\Base::diff(mixed $from, mixed $to): mixed
abstract public XMLDiff\Base::merge(mixed $src, mixed $diff): mixed
}

Índice

  • XMLDiff\File::diff — Diff two XML files
  • XMLDiff\File::merge — Produce merged XML document

User Contributed Notes

ngbabu at gmail dot com 21-Nov-2015 08:45
The following snippet will show the use case of XMLDiff\File.

<?php
$dxml=new XMLDiff\File;
$diff = $dxml->diff("file1.xml", "file2.xml");
$difffile = 'difference.xml';
file_put_contents($difffile, $diff);
?>


Diff two XML files

  • « XMLDiff\File
  • XMLDiff\File::merge »
  • PHP Manual
  • XMLDiff\File
  • Diff two XML files

XMLDiff\File::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\File::diff — Diff two XML files

Descrição

public XMLDiff\File::diff(string $from, string $to): string

Diff two local XML files and produce string with the diff information.

Parâmetros

from

Path to the source document.

to

Path to the target document.

Valor Retornado

String with the XML document containing the diff information or NULL.

User Contributed Notes

There are no user contributed notes for this page.


Produce merged XML document

  • « XMLDiff\File::diff
  • Analisador de XML »
  • PHP Manual
  • XMLDiff\File
  • Produce merged XML document

XMLDiff\File::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\File::merge — Produce merged XML document

Descrição

public XMLDiff\File::merge(string $src, string $diff): string

Create new XML document based on diffs and source document.

Parâmetros

src

Path to the source XML document.

diff

Path to the XML document with the diff information.

Valor Retornado

String with the new XML document or NULL.

User Contributed Notes

There are no user contributed notes for this page.


Analisador de XML

  • Introdução
  • Instalação/Configuração
    • Dependências
    • Instalação
    • Configurações em Execução
    • Tipos de Recurso
  • Constantes pré-definidas
  • Manipuladores de Evento
  • Case Folding
  • Códigos de Erro
  • Codificação de caracteres
  • Exemplos
    • XML Element Structure Example
    • XML Tag Mapping Example
    • XML External Entity Example
  • Funções para analisar XML
    • xml_error_string — Obtém uma string de erro do analisador XML
    • xml_get_current_byte_index — Get current byte index for an XML parser
    • xml_get_current_column_number — Get current column number for an XML parser
    • xml_get_current_line_number — Get current line number for an XML parser
    • xml_get_error_code — Obtém um código de erro do analisador XML
    • xml_parse_into_struct — Analisa dados XML dentro de uma estrutura de array
    • xml_parse — Start parsing an XML document
    • xml_parser_create_ns — Cria um analisador XML com suporte a espaço de nomes
    • xml_parser_create — Cria um analisador XML
    • xml_parser_free — Libera um analisador XML
    • xml_parser_get_option — Obtém as opções de um analisador XML
    • xml_parser_set_option — Define opções em um analisador XML
    • xml_set_character_data_handler — Set up character data handler
    • xml_set_default_handler — Set up default handler
    • xml_set_element_handler — Set up start and end element handlers
    • xml_set_end_namespace_decl_handler — Set up end namespace declaration handler
    • xml_set_external_entity_ref_handler — Set up external entity reference handler
    • xml_set_notation_decl_handler — Set up notation declaration handler
    • xml_set_object — Use XML Parser within an object
    • xml_set_processing_instruction_handler — Set up processing instruction (PI) handler
    • xml_set_start_namespace_decl_handler — Set up start namespace declaration handler
    • xml_set_unparsed_entity_decl_handler — Set up unparsed entity declaration handler
  • XMLParser — The XMLParser class

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.


Introdução

XML (eXtensible Markup Language) é um formato de dados para intercâmbio de documentos estruturado na Web. É um padrão definido pela The World Wide Web Consortium (W3C). Informações sobre XML e tecnologias relacionadas podem ser encontradas em » http://www.w3.org/XML/.

Esta extensão do PHP implementa suporte para o expat de James Clark no PHP. Este conjunto de ferramentas permite analisar, porém não validar, documentos XML. Suporta três codificações de caracteres para also fontes, também fornecidas pelo PHP: US-ASCII, ISO-8859-1 e UTF-8. UTF-16 não é suportado.

Esta extensão permite criar analisadores XML e então definir manipuladores para diferentes eventos XML. Cada analisador XML também tem alguns parâmetros que podem ser ajustados.

User Contributed Notes

There are no user contributed notes for this page.


Dependências

Esta extensão requer a extensão PHP libxml. Isso significa que ao compilar o PHP é preciso passar a flag de configuração --with-libxml, ou antes do PHP 7.4, --enable-libxml, embora isso seja feito implicitamente pois a libxml está habilitada por padrão.

This extension uses an expat compat layer by default. It can use also expat, which can be found at » http://www.jclark.com/xml/expat.html. The Makefile that comes with expat does not build a library by default, you can use this make rule for that:

libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@
A source RPM package of expat can be found at » http://sourceforge.net/projects/expat/.

User Contributed Notes

There are no user contributed notes for this page.


Instalação

Esta extensão está habilitada por padrão. Ela pode ser desabilitada usando a seguinte opção em tempo de compilação: --disable-xml

Estas funções estão habilitadas por padrão, usando a biblioteca expat fornecida. Pode-se desabilitar o suporte a XML com a opção --disable-xml. Se o PHP foi compilado como módulo para o Apache 1.3.9 ou posterior, o PHP automaticamente utilizará a biblioteca expat fornecida pelo Apache. Se não for desejado usar a bilbioteca expat fornecida, configure o PHP com a opção --with-expat-dir=DIR, onde DIR aponta para o diretório base de instalação do expat.

A versão do PHP para Windows tem suporte nativo para esta extensão. Nenhuma extensão adicional precisa ser carregada para usar essas funções.

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 Recurso

Prior to PHP 8.0.0, the xml resource as returned by xml_parser_create() and xml_parser_create_ns() referenced an xml parser instance to be used with the functions provided by this extension.

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-definidas

As contantes abaixo são definidas por esta extensão e só estarão disponíveis quando a extensão tiver sido compilada no PHP ou tiver sido carregada dinamicamente em tempo de execução.

XML_ERROR_NONE (int)
XML_ERROR_NO_MEMORY (int)
XML_ERROR_SYNTAX (int)
XML_ERROR_NO_ELEMENTS (int)
XML_ERROR_INVALID_TOKEN (int)
XML_ERROR_UNCLOSED_TOKEN (int)
XML_ERROR_PARTIAL_CHAR (int)
XML_ERROR_TAG_MISMATCH (int)
XML_ERROR_DUPLICATE_ATTRIBUTE (int)
XML_ERROR_JUNK_AFTER_DOC_ELEMENT (int)
XML_ERROR_PARAM_ENTITY_REF (int)
XML_ERROR_UNDEFINED_ENTITY (int)
XML_ERROR_RECURSIVE_ENTITY_REF (int)
XML_ERROR_ASYNC_ENTITY (int)
XML_ERROR_BAD_CHAR_REF (int)
XML_ERROR_BINARY_ENTITY_REF (int)
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (int)
XML_ERROR_MISPLACED_XML_PI (int)
XML_ERROR_UNKNOWN_ENCODING (int)
XML_ERROR_INCORRECT_ENCODING (int)
XML_ERROR_UNCLOSED_CDATA_SECTION (int)
XML_ERROR_EXTERNAL_ENTITY_HANDLING (int)
XML_OPTION_CASE_FOLDING (int)
XML_OPTION_TARGET_ENCODING (int)
XML_OPTION_SKIP_TAGSTART (int)
XML_OPTION_SKIP_WHITE (int)
XML_SAX_IMPL (string)
Holds the SAX implementation method. Can be libxml or expat.

User Contributed Notes

There are no user contributed notes for this page.


Manipuladores de Evento

Os manipuladores de eventos de XML definidos são:

Manipuladores XML Suportados
Função do PHP pra definir manipulador | Descrição do evento
xml_set_element_handler() | Eventos de elementos são emitidos toda vez que o analisador XML encontrar o início ou o fim de etiquetas. Há manipuladores separados para etiquetas de início e etiquetas de fim.
xml_set_character_data_handler() | Dados de caracteres são de maneira geral todo o conteúdo de documentos XML que não seja marcação de etiquetas, incluindo espaços em branco entre as etiquetas. Note que o analisador XML não adiciona ou remove qualquer espaço em branco, é função da aplicação decidir se os espaços em branco são significativos.
xml_set_processing_instruction_handler() | Programadores de PHP devem estar familiarizados com instruções de processamento (PIs). <?php ?> é uma instrução de processamento, onde php é chamado de "alvo PI". O tratamento destes são específicos por aplicação, exceto que todos os alvos PI iniciados por "XML" são reservados.
xml_set_default_handler() | O que não vai para algum outro manipulador vai para o manipulador padrão. Pode-se obter informações como declarações XML e de tipos de documentos no manipulador padrão.
xml_set_unparsed_entity_decl_handler() | Este manipulador será chamado para declaração de uma entidade não analisada (NDATA).
xml_set_notation_decl_handler() | Este manipulador é chamado para declaração de uma notação.
xml_set_external_entity_ref_handler() | Este manipulador é chamado quando o analisador XML encontra uma referência a uma entidade geral analisada externamente. Isto pode ser uma referência para um arquivo ou URL, por examplo. Consulte o exemplo de entidade externa para uma demonstração.
xml_set_start_namespace_decl_handler() | Este manipulador é chamado para o início de uma declaração de espaço de nomes.
xml_set_end_namespace_decl_handler() | Este manipulador é chamado para o final de uma declaração de espaço de nomes. Note que este evento não é disparado pela biblioteca libXML.

User Contributed Notes

There are no user contributed notes for this page.


Case Folding

The element handler functions may get their element names case-folded. Case-folding is defined as "a process applied to a sequence of characters, in which those identified as non-uppercase are replaced by their uppercase equivalents". In other words, when it comes to XML, case-folding simply means uppercasing.

By default, all the element names that are passed to the handler functions are case-folded. This behaviour can be queried and controlled per XML parser with the xml_parser_get_option() and xml_parser_set_option() functions, respectively.

User Contributed Notes

There are no user contributed notes for this page.


Códigos de Erro

As seguintes constantes são definidas para erros no código XML (conforme retornado por 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
?>


Codificação de caracteres

A Extensão XML do PHP suporta o conjunto de caracteres » Unicode definido por diferentes codificações de caracteres diferentes. Há dois tipos de codificação de caracteres, codificação da fonte e codificação do destino. A apresentação interna do PHP do documento é sempre codificada com UTF-8.

Codificação na fonte é feita quando um documento XML é analisado. Ao criar um analisador XML, uma codificação na fonte pode ser especificada (esta codificação não poderá ser alterada mais tarde durante a atividade do analisador XML). As codificações na fonte suportadas são ISO-8859-1, US-ASCII e UTF-8. As duas primeiras são codificações de um byte, o que significa que cada caractere é representado por um único byte. UTF-8 pode codificar caracteres compostos por um número variável de bits (até 21) em um a quatro bytes. A codificação na fonte padrão usada pelo PHP é ISO-8859-1.

Codificação no destino é feita quando o PHP passa dados para as funções do analisador XML. Quando um analisador XML é criado, a codificação no destino é definido como a mesma da fonte, mas isto pode ser alterado a qualquer momento. A codificação no destino afetará dados de caracteres e também nomes de etiquetas e alvos de instrução de processamento.

Se o analisador XML encontrar caracteres de fora da faixa na qual sua codificação na fonte seja capaz de representar, ele retornará um erro.

Se o PHP encontrar caracteres no documento XML analisado que não possam ser representados na codificação de destino escolhida, os caracteres com problema serão "rebaixados". Atualmente, isto significa que tais caracteres serão substituídos por um sinal de interrogação.

User Contributed Notes

There are no user contributed notes for this page.


Exemplos

Índice

  • XML Element Structure Example
  • XML Tag Mapping Example
  • XML External Entity Example

User Contributed Notes

There are no user contributed notes for this page.


XML Element Structure Example

This first example displays the structure of the start elements in a document with indentation.

Exemplo #1 Show XML Element Structure

<?php
$file = "data.xml";
$depth = 0;

function startElement($parser, $name, $attrs)
{
global $depth;

for ($i = 0; $i < $depth; $i++) {
echo " ";
}
echo "$name\n";
$depth++;
}

function endElement($parser, $name)
{
global $depth;
$depth--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}
xml_parser_free($xml_parser);
?>

User Contributed Notes

Joachim Kruyswijk 27-Jun-2022 02:08
If you use strict_types=1, you'll get the warning "Notice: Resource ID#... used as offset, casting to integer".

Use

<?php $depth[(int) $parser]  ?>

instead of

<?php $depth[$parser]  ?>
Sample at hotmail dot com 04-Jul-2013 10:32
<?php

public static function xml2array($element, $arr = array())
    {
        if(is_string($element))
        {
            $element = (strlen($element) > 5 && substr($element, -4) === '.xml')
                            ? simplexml_load_file(DATAPATH.$element)
                            : simplexml_load_string($element);
        }
         $iter = 0;
        foreach($element->children() as $b)
        {
            $a = $b->getName();
            if(!$b->children()){
                    $arr[$a] = trim($b[0]);
            }
            else{
                    $arr[$a][$iter] = array();
                    $arr[$a][$iter] = self::xml2array($b,$arr[$a][$iter]);
            }
                $iter++;
        }
        return $arr;
    }
}

?>
roan at horning dot us 30-Oct-2009 09:07
The following example will echo back an xml file using the basic event based parser.  Currently, (at least in the version of PHP5 I'm using) it will skip The XML declaration and the Doctype declaration--they don't seem to be captured by the default handler.

<?php
echo "<pre>";

$file = "test.xml";
echo $file."\n";
global $inTag;

$inTag = "";
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);
xml_set_processing_instruction_handler($xml_parser, "pi_handler");
xml_set_default_handler($xml_parser, "parseDEFAULT");
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "contents");

if (!($fp = fopen($file, "r"))) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
       die( sprintf("XML error: %s at line %d",
                            xml_error_string(xml_get_error_code($xml_parser)),
                            xml_get_current_line_number($xml_parser)));
    }
}
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
       die( sprintf("XML error: %s at line %d",
                            xml_error_string(xml_get_error_code($xml_parser)),
                            xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);

function startElement($parser, $name, $attrs) {

    global $inTag;
    global $depth;

    $padTag = str_repeat(str_pad(" ", 3), $depth);

    if (!($inTag == "")) {
        echo "&gt;";
    }
    echo "\n$padTag&lt;$name";
    foreach ($attrs as $key => $value) {
        echo "\n$padTag".str_pad(" ", 3);
        echo " $key=\"$value\"";
    }
    $inTag = $name;
    $depth++;
}

function endElement($parser, $name) {

    global $depth;
   global $inTag;
    global $closeTag;

    $depth--;

   if ($closeTag == TRUE) {
       echo "&lt/$name&gt;";
       $inTag = "";
   } elseif ($inTag == $name) {
       echo " /&gt;";
       $inTag = "";
   } else {
         $padTag = str_repeat(str_pad(" ", 3), $depth);
       echo "\n$padTag&lt/$name&gt;";
    }
}

function contents($parser, $data) {

    global $closeTag;

    $data = preg_replace("/^\s+/", "", $data);
    $data = preg_replace("/\s+$/", "", $data);

    if (!($data == ""))  {
        echo "&gt;$data";
        $closeTag = TRUE;
    } else {
        $closeTag = FALSE;
     }
}

function parseDEFAULT($parser, $data) {

    $data = preg_replace("/</", "&lt;", $data);
    $data = preg_replace("/>/", "&gt;", $data);
    echo $data;
}

function pi_handler($parser, $target, $data) {

    echo "&lt;?$target $data?&gt;\n";
}
echo "</pre>";
?>


XML Tag Mapping Example

Exemplo #1 Map XML to HTML

This example maps tags in an XML document directly to HTML tags. Elements not found in the "map array" are ignored. Of course, this example will only work with a specific XML document type.

<?php
$file = "data.xml";
$map_array = array(
"BOLD" => "B",
"EMPHASIS" => "I",
"LITERAL" => "TT"
);

function startElement($parser, $name, $attrs)
{
global $map_array;
if (isset($map_array[$name])) {
echo "<$map_array[$name]>";
}
}

function endElement($parser, $name)
{
global $map_array;
if (isset($map_array[$name])) {
echo "</$map_array[$name]>";
}
}

function characterData($parser, $data)
{
echo $data;
}

$xml_parser = xml_parser_create();
// use case-folding so we are sure to find the tag in $map_array
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}
xml_parser_free($xml_parser);
?>

User Contributed Notes

There are no user contributed notes for this page.


XML External Entity Example

This example highlights XML code. It illustrates how to use an external entity reference handler to include and parse other documents, as well as how PIs can be processed, and a way of determining "trust" for PIs containing code.

XML documents that can be used for this example are found below the example (xmltest.xml and xmltest2.xml.)

Exemplo #1 External Entity Example

<?php
$file = "xmltest.xml";

function trustedFile($file)
{
// only trust local files owned by ourselves
if (!preg_match("@^([a-z][a-z0-9+.-]*)\:\/\/@i", $file)
&& fileowner($file) == getmyuid()) {
return true;
}
return false;
}

function startElement($parser, $name, $attribs)
{
echo "&lt;<font color=\"#0000cc\">$name</font>";
if (count($attribs)) {
foreach ($attribs as $k => $v) {
echo " <font color=\"#009900\">$k</font>=\"<font
color=\"#990000\">$v</font>\"";
}
}
echo "&gt;";
}

function endElement($parser, $name)
{
echo "&lt;/<font color=\"#0000cc\">$name</font>&gt;";
}

function characterData($parser, $data)
{
echo "<b>$data</b>";
}

function PIHandler($parser, $target, $data)
{
switch (strtolower($target)) {
case "php":
global $parser_file;
// 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);

?>

Exemplo #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>

This file is included from xmltest.xml:

Exemplo #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.


Funções para analisar XML

Índice

  • xml_error_string — Obtém uma string de erro do analisador XML
  • xml_get_current_byte_index — Get current byte index for an XML parser
  • xml_get_current_column_number — Get current column number for an XML parser
  • xml_get_current_line_number — Get current line number for an XML parser
  • xml_get_error_code — Obtém um código de erro do analisador XML
  • xml_parse_into_struct — Analisa dados XML dentro de uma estrutura de array
  • xml_parse — Start parsing an XML document
  • xml_parser_create_ns — Cria um analisador XML com suporte a espaço de nomes
  • xml_parser_create — Cria um analisador XML
  • xml_parser_free — Libera um analisador XML
  • xml_parser_get_option — Obtém as opções de um analisador XML
  • xml_parser_set_option — Define opções em um analisador XML
  • xml_set_character_data_handler — Set up character data handler
  • xml_set_default_handler — Set up default handler
  • xml_set_element_handler — Set up start and end element handlers
  • xml_set_end_namespace_decl_handler — Set up end namespace declaration handler
  • xml_set_external_entity_ref_handler — Set up external entity reference handler
  • xml_set_notation_decl_handler — Set up notation declaration handler
  • xml_set_object — Use XML Parser within an object
  • xml_set_processing_instruction_handler — Set up processing instruction (PI) handler
  • xml_set_start_namespace_decl_handler — Set up start namespace declaration handler
  • xml_set_unparsed_entity_decl_handler — Set up unparsed entity declaration handler

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.


Obtém uma string de erro do analisador XML

  • « Funções para analisar XML
  • xml_get_current_byte_index »
  • PHP Manual
  • Funções para analisar XML
  • Obtém uma string de erro do analisador XML

xml_error_string

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

xml_error_string — Obtém uma string de erro do analisador XML

Descrição

xml_error_string(int $error_code): ?string

Obtém a string do erro do analisador XML associada com o código de erro fornecido em error_code.

Parâmetros

error_code

Um código de erro de xml_get_error_code().

Valor Retornado

Retorna uma string com uma descrição textual do código de erro error_code, ou null se nenhuma descrição for encontrada.

Veja Também

  • xml_get_error_code() - Obtém um código de erro do analisador 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;
?>


Get current byte index for an XML parser

  • « xml_error_string
  • xml_get_current_column_number »
  • PHP Manual
  • Funções para analisar XML
  • Get current byte index for an XML parser

xml_get_current_byte_index

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

xml_get_current_byte_index — Get current byte index for an XML parser

Descrição

xml_get_current_byte_index(XMLParser $parser): int

Gets the current byte index of the given XML parser.

Parâmetros

parser

A reference to the XML parser to get byte index from.

Valor Retornado

Returns which byte index the parser is currently at in its data buffer (starting at 0).

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

Notas

Aviso

This function returns byte index according to UTF-8 encoded text disregarding if input is in another encoding.

Veja Também

  • xml_get_current_column_number() - Get current column number for an XML parser
  • xml_get_current_line_number() - Get current line number for an XML parser

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.


Get current column number for an XML parser

  • « xml_get_current_byte_index
  • xml_get_current_line_number »
  • PHP Manual
  • Funções para analisar XML
  • Get current column number for an XML parser

xml_get_current_column_number

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

xml_get_current_column_number — Get current column number for an XML parser

Descrição

xml_get_current_column_number(XMLParser $parser): int

Gets the current column number of the given XML parser.

Parâmetros

parser

A reference to the XML parser to get column number from.

Valor Retornado

Returns which column on the current line (as given by xml_get_current_line_number()) the parser is currently at.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

Veja Também

  • xml_get_current_byte_index() - Get current byte index for an XML parser
  • xml_get_current_line_number() - Get current line number for an XML parser

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.


Get current line number for an XML parser

  • « xml_get_current_column_number
  • xml_get_error_code »
  • PHP Manual
  • Funções para analisar XML
  • Get current line number for an XML parser

xml_get_current_line_number

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

xml_get_current_line_number — Get current line number for an XML parser

Descrição

xml_get_current_line_number(XMLParser $parser): int

Gets the current line number for the given XML parser.

Parâmetros

parser

A reference to the XML parser to get line number from.

Valor Retornado

Returns which line the parser is currently at in its data buffer.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

Veja Também

  • xml_get_current_column_number() - Get current column number for an XML parser
  • xml_get_current_byte_index() - Get current byte index for an XML parser

User Contributed Notes

There are no user contributed notes for this page.


Obtém um código de erro do analisador XML

  • « xml_get_current_line_number
  • xml_parse_into_struct »
  • PHP Manual
  • Funções para analisar XML
  • Obtém um código de erro do analisador XML

xml_get_error_code

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

xml_get_error_code — Obtém um código de erro do analisador XML

Descrição

xml_get_error_code(XMLParser $parser): int

Obtém o código de erro do analisador XML.

Parâmetros

parser

Uma referência para o analisador XML obter código de erro.

Valor Retornado

Retorna um dos códigos de erro listados na seção de código de erros.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

Veja Também

  • xml_error_string() - Obtém uma string de erro do analisador XML

User Contributed Notes

There are no user contributed notes for this page.


Analisa dados XML dentro de uma estrutura de array

  • « xml_get_error_code
  • xml_parse »
  • PHP Manual
  • Funções para analisar XML
  • Analisa dados XML dentro de uma estrutura de array

xml_parse_into_struct

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

xml_parse_into_struct — Analisa dados XML dentro de uma estrutura de array

Descrição

xml_parse_into_struct(
XMLParser $parser,
string $data,
array &$values,
array &$index = null
): int

Esta função analisa uma string XML para 2 estruturas de array paralelas, uma (index) contendo indicadores para a localização dos valores apropriados no array identificado por values. Estes dois últimos parâmetros deve ser passados por referência.

Parâmetros

parser

Uma referência ao analisador XML.

data

Uma string contendo os dados XML.

values

Um array contendo os valores do dados XML

index

Um array contendo ponteiros para a localização dos valores apropriados em $values.

Valor Retornado

xml_parse_into_struct() retorna 0 para falha e 1 para sucesso. Isto não é o mesmo que false e true, deve-se ter cuidado ao usar operadores como ===.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

Exemplos

Abaixo há um exemplo que ilustra a estrutura interna dos arrays sendo gerados pela função. Será usada uma simples etiqueta note embutida dentro da etiqueta para, e então será feita análise e depois mostradas as estruturas geredas:

Exemplo #1 Exemplo de xml_parse_into_struct()

<?php
$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);
?>

Ao executar o código, a saída 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
        )

)

Análise guiada por eventos (baseada na biblioteca expat) pode se tornar complicada quando se tem um documento XML complexo. Esta função não produz um objeto no estilo DOM, mas gera estruturas passíveis de serem organizadas em forma de árvore. Assim, pode-se criar objetos representando os dados no arquivo XML facilmente. Considere o seguinte arquivo XML representando um pequeno banco de dados de informações de aminoácidos:

Exemplo #2 moldb.xml - pequeno banco de dados de informações moleculares

<?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>
E um pouco de código para analisar o documento e gerar os objetos apropriados:

Exemplo #3 parsemoldb.php - analisa moldb.xml e cria o array dos objetos moleculares

<?php

class AminoAcid {
var $name; // nome do aminoácido
var $symbol; // símbolo de 3 letras
var $code; // código de 1 letra
var $type; // hidrofóbico, carregado ou natural

function __construct ($aa)
{
foreach ($aa as $k=>$v)
$this->$k = $aa[$k];
}
}

function readDatabase($filename)
{
// lê o banco de dados XML de aminoácidos
$data = file_get_contents($filename);
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $data, $values, $tags);
xml_parser_free($parser);

// faz um loop pelas estruturas
foreach ($tags as $key=>$val) {
if ($key == "molecule") {
$molranges = $val;
// cada par contíguo de entradas do array são os limites
// inferiores e superiores para cada definição 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 "** Banco de Dados de objetos de Aminoácidos:\n";
print_r($db);

?>
Depois de executar parsemoldb.php, a variável $db conterá um array dos objetos de AminoAcid, e a saída do script confirma isso:
** Banco de Dados de objetos de Aminoácidos:
Array
(
    [0] => aminoacid Object
        (
            [name] => Alanine
            [symbol] => ala
            [code] => A
            [type] => hydrophobic
        )

    [1] => aminoacid Object
        (
            [name] => Lysine
            [symbol] => lys
            [code] => K
            [type] => charged
        )

)

User Contributed Notes

Adam Tylmad 30-Apr-2009 12:58
Thanx to jukea i've upgraded the characterData-function to allow the value 0. Here is the new complete code:

<?php

class XMLParser {
    var $path;
    var $result;

    function cleanString($string) {
        return trim(str_replace("'", "&#39;", $string));
    }

    function XMLParser($encoding, $data) {
        $this->path = "\$this->result";
        $this->index = 0;

        $xml_parser = xml_parser_create($encoding);
        xml_set_object($xml_parser, &$this);
        xml_set_element_handler($xml_parser, 'startElement', 'endElement');
        xml_set_character_data_handler($xml_parser, 'characterData');

        xml_parse($xml_parser, $data, true);
        xml_parser_free($xml_parser);
    }

    function startElement($parser, $tag, $attributeList) {
        $this->path .= "->".$tag;
        eval("\$data = ".$this->path.";");
        if (is_array($data)) {
            $index = sizeof($data);
            $this->path .= "[".$index."]";
        } else if (is_object($data)) {
            eval($this->path." = array(".$this->path.");");
            $this->path .= "[1]";
        }

        foreach($attributeList as $name => $value)
            eval($this->path."->".$name. " = '".XMLParser::cleanString($value)."';");
    }

    function endElement($parser, $tag) {
        $this->path = substr($this->path, 0, strrpos($this->path, "->"));
    }

    function characterData($parser, $data) {
        if (strlen($data = XMLParser::cleanString($data)))
            eval($this->path." = '$data';");
    }
}

?>
aerik at thesylvans dot com 28-Nov-2008 03:55
Here's another attempt at dealing with rebuilding the xml from the array.  I'm basically preventing certain tags from being self closing by just checking for them explicitly (sure wish expat didn't interpret <textarea /> and <textarea></textarea> the same way (as "complete" tags).

<?php
function array2xml($xmlary){
  $o='';
  foreach($xmlary as $tag ){
    if($tag['tag'] == 'textarea' && !isset($tag['value'])){
      //fake a value so it won't self close
      $tag['value']='';
    }
    //tab space:
    $t = '';
    for($i=1; $i < $tag['level'];$i++){
      $t.="\t";
    }
    switch($tag['type']){
      case 'complete':
      case 'open':
        $o.=$t.'<'.$tag['tag'];
        if(isset($tag['attributes'])){
          foreach($tag['attributes'] as $attr=>$aval){
            $o.=' '.$attr.'="'.$aval.'"';
          }//foreach
        }//attributes
        if($tag['type'] == 'complete'){
          if(!isset($tag['value'])){
            $o .= ' />'."\n";
          } else {
            $o .= '>'."\n".$t.$tag['value']."\n".$t.'</'.$tag['tag'].'>'."\n";
          }
        }else{
          $o .= '>'."\n";
        }
        break;
      case 'close':
        $o .= $t.'</'.$tag['tag'].'>'."\n";
        break;
      case 'cdata':
        $o .= $t.$tag['value']."\n";
        break;
    }//switch
  }//foreach
}
?>
dale at ucsc dot edu 25-Sep-2008 04:16
here you can [re]assemble xml from a xml_parse_into_struct generated array: ie array2xml

<?php
$xml_parser = xml_parser_create( 'UTF-8' ); // UTF-8 or ISO-8859-1
xml_parser_set_option( $xml_parser, XML_OPTION_CASE_FOLDING, 0 );
xml_parser_set_option( $xml_parser, XML_OPTION_SKIP_WHITE, 1 );
xml_parse_into_struct( $xml_parser, $my_text_xml, $aryXML );
xml_parser_free($xml_parser);

//now use aryXML array to xml string:
        $o='';
        foreach( $aryXML as $tag ){
            //tab space:
            for($i=1; $i < $tag['level'];$i++)
                $o.="\t";
            if($tag['type']!='close'){
                if($tag['type']!='cdata')
                    $o.='<'.$tag['tag'];
                if(isset($tag['attributes'])){
                    foreach($tag['attributes'] as $attr=>$aval){
                        $o.=' '.$attr.'="'.$aval.'"';
                    }
                }
                if($tag['type']!='cdata'){
                    $o.=($tag['type']=='complete')?'/>'."\n":'>'."\n";
                }
                $o.=(isset($tag['value']))?$tag['value']:'';
            }else{
                $o.='</'.$tag['tag'].'>';
            }
        }
?>
Llorenc 09-Sep-2008 03:20
Sorry, forgot my last post below, I confused CDATA sections (<![CDATA[]]>) with the value type "cdata", which despite its name it's very different! The first allows adding markup (&,<,>) as regular text and the second is to indicate a not complete node between the open and close nodes. What is true is that the CDATA delimiters are lost after xml_parse_into_struct so it's not possible to revert the process.

Please, feel free to remove my comments or leave them if you think they can help anyone.
wickedfather at hotmail dot com 06-Jul-2008 12:33
Had a comment up that was removed saying I'd found drawbacks, but here's a class what I wrote which works fine for me.  Comments removed due to post restrictions.  Pass the xml into the parse method or in the constructor.  Php4 and 5 safe.

class XMLThing
{
    var $rawXML;
    var $valueArray = array();
    var $keyArray = array();
    var $parsed = array();
    var $index = 0;
    var $attribKey = 'attributes';
    var $valueKey = 'value';
    var $cdataKey = 'cdata';
    var $isError = false;
    var $error = '';

    function XMLThing($xml = NULL)
    {
        $this->rawXML = $xml;
    }

    function parse($xml = NULL)
    {
        if (!is_null($xml))
        {
            $this->rawXML = $xml;
        }

        $this->isError = false;

        if (!$this->parse_init())
        {
            return false;
        }

        $this->index = 0;
        $this->parsed = $this->parse_recurse();
        $this->status = 'parsing complete';

        return $this->parsed;
    }

    function parse_recurse()
    {
        $found = array();
        $tagCount = array();

        while (isset($this->valueArray[$this->index]))
        {
            $tag = $this->valueArray[$this->index];
            $this->index++;

            if ($tag['type'] == 'close')
            {
                return $found;
            }

            if ($tag['type'] == 'cdata')
            {
                $tag['tag'] = $this->cdataKey;
                $tag['type'] = 'complete';
            }

            $tagName = $tag['tag'];

            if (isset($tagCount[$tagName]))
            {
                if ($tagCount[$tagName] == 1)
                {
                    $found[$tagName] = array($found[$tagName]);
                }

                $tagRef =& $found[$tagName][$tagCount[$tagName]];
                $tagCount[$tagName]++;
            }
            else
            {
                $tagCount[$tagName] = 1;
                $tagRef =& $found[$tagName];
            }

            switch ($tag['type'])
            {
                case 'open':
                    $tagRef = $this->parse_recurse();

                    if (isset($tag['attributes']))
                    {
                        $tagRef[$this->attribKey] = $tag['attributes'];
                    }

                    if (isset($tag['value']))
                    {
                        if (isset($tagRef[$this->cdataKey]))
                        {
                            $tagRef[$this->cdataKey] = (array)$tagRef[$this->cdataKey];
                            array_unshift($tagRef[$this->cdataKey], $tag['value']);
                        }
                        else
                        {
                            $tagRef[$this->cdataKey] = $tag['value'];
                        }
                    }
                    break;

                case 'complete':
                    if (isset($tag['attributes']))
                    {
                        $tagRef[$this->attribKey] = $tag['attributes'];
                        $tagRef =& $tagRef[$this->valueKey];
                    }

                    if (isset($tag['value']))
                    {
                        $tagRef = $tag['value'];
                    }
                    break;
            }
        }

        return $found;
    }

    function parse_init()
    {
        $this->parser = xml_parser_create();

        $parser = $this->parser;
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        if (!$res = (bool)xml_parse_into_struct($parser, $this->rawXML, $this->valueArray, $this->keyArray))
        {
            $this->isError = true;
            $this->error = 'error: '.xml_error_string(xml_get_error_code($parser)).' at line '.xml_get_current_line_number($parser);
        }
        xml_parser_free($parser);

        return $res;
    }
}
jemptymethod at gmail dot com 16-Jun-2008 01:39
@wickedfather, re: beaudurrant....I just cannot concur that the latter's class is "great"....First of all, it doesn't handle attributes.  Second of all, as my code below demonstrates, there is no need waste processing by determining duplicates within their own loop.  Thirdly, when there are duplicates, it collapses the layer in the array above the duplicates.

Here is some much more consise code, though not (yet) object oriented, and also not yet handling attributes; it maintains a stack for each level:

<?php
function xml_parse_into_assoc($file) {
  $data = implode("", file($file));
  $p = xml_parser_create();

  xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);

  xml_parse_into_struct($p, $data, $vals, $index);
  xml_parser_free($p);

  $levels = array(null);

  foreach ($vals as $val) {
    if ($val['type'] == 'open' || $val['type'] == 'complete') {
      if (!array_key_exists($val['level'], $levels)) {
        $levels[$val['level']] = array();
      }
    }

    $prevLevel =& $levels[$val['level'] - 1];
    $parent = $prevLevel[sizeof($prevLevel)-1];

    if ($val['type'] == 'open') {
      $val['children'] = array();
      array_push(&$levels[$val['level']], $val);
      continue;
    }

    else if ($val['type'] == 'complete') {
      $parent['children'][$val['tag']] = $val['value'];
    }

    else if ($val['type'] == 'close') {
      $pop = array_pop($levels[$val['level']]);
      $tag = $pop['tag'];

      if ($parent) {
        if (!array_key_exists($tag, $parent['children'])) {
          $parent['children'][$tag] = $pop['children'];
        }
        else if (is_array($parent['children'][$tag])) {
          $parent['children'][$tag][] = $pop['children'];
        }
      }
      else {
        return(array($pop['tag'] => $pop['children']));
      }
    }

    $prevLevel[sizeof($prevLevel)-1] = $parent;
  }
}
?>
wickedfather at hotmail dot com 12-Apr-2008 08:36
To beaudurrant - that class is great and structures things in a very sensible way.  Only problem is that it raises an error if a tag is empty, so would suggest a simple mod to the parse method just to add an isset test.

if (isset($val['value']))
{
    $this->setArrayValue($this->output, $stack, $val['value']);
}
mathiasrav at gmail dot com 10-Mar-2008 08:42
In response to Anonymous' post at 26-Feb-2008 11:50:

Saying that you "don't understand everything" isn't going to get you very popular - you should understand the code you use.
foreach isn't *slow* in PHP, it is actually faster than the equivalent for-construct (which, in many cases, isn't available).

The reason your script is slow is simply your use of xml_parse_into_struct - it reads the whole XML-string and doesn't return until it has parsed and validated it all. If you're looking for efficiency, you'll have to use the more low-level xml_parser_create, xml_set_*_handler functions. Then make sure you don't keep everything in a huge array before outputting it (at least don't if you're going for efficiency).
beaudurrant at gmail dot com 19-Dec-2007 11:23
This is extending what Alf Marius Foss Olsen had posted above.

It takes into account array keys with the same name and uses an increment for them instead of overwriting the keys.

I am using it for SOAP requests (20K - 150K) and it parses very fast compared to PEAR.

<?

class XMLParser  {

    // raw xml
    private $rawXML;
    // xml parser
    private $parser = null;
    // array returned by the xml parser
    private $valueArray = array();
    private $keyArray = array();

    // arrays for dealing with duplicate keys
    private $duplicateKeys = array();

    // return data
    private $output = array();
    private $status;

    public function XMLParser($xml){
        $this->rawXML = $xml;
        $this->parser = xml_parser_create();
        return $this->parse();
    }

    private function parse(){

        $parser = $this->parser;

        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); // Dont mess with my cAsE sEtTings
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);     // Dont bother with empty info
        if(!xml_parse_into_struct($parser, $this->rawXML, $this->valueArray, $this->keyArray)){
            $this->status = 'error: '.xml_error_string(xml_get_error_code($parser)).' at line '.xml_get_current_line_number($parser);
            return false;
        }
        xml_parser_free($parser);

        $this->findDuplicateKeys();

        // tmp array used for stacking
        $stack = array();
        $increment = 0;

        foreach($this->valueArray as $val) {
            if($val['type'] == "open") {
                //if array key is duplicate then send in increment
                if(array_key_exists($val['tag'], $this->duplicateKeys)){
                    array_push($stack, $this->duplicateKeys[$val['tag']]);
                    $this->duplicateKeys[$val['tag']]++;
                }
                else{
                    // else send in tag
                    array_push($stack, $val['tag']);
                }
            } elseif($val['type'] == "close") {
                array_pop($stack);
                // reset the increment if they tag does not exists in the stack
                if(array_key_exists($val['tag'], $stack)){
                    $this->duplicateKeys[$val['tag']] = 0;
                }
            } elseif($val['type'] == "complete") {
                //if array key is duplicate then send in increment
                if(array_key_exists($val['tag'], $this->duplicateKeys)){
                    array_push($stack, $this->duplicateKeys[$val['tag']]);
                    $this->duplicateKeys[$val['tag']]++;
                }
                else{
                    // else send in tag
                    array_push($stack,  $val['tag']);
                }
                $this->setArrayValue($this->output, $stack, $val['value']);
                array_pop($stack);
            }
            $increment++;
        }

        $this->status = 'success: xml was parsed';
        return true;

    }

    private function findDuplicateKeys(){

        for($i=0;$i < count($this->valueArray); $i++) {
            // duplicate keys are when two complete tags are side by side
            if($this->valueArray[$i]['type'] == "complete"){
                if( $i+1 < count($this->valueArray) ){
                    if($this->valueArray[$i+1]['tag'] == $this->valueArray[$i]['tag'] && $this->valueArray[$i+1]['type'] == "complete"){
                        $this->duplicateKeys[$this->valueArray[$i]['tag']] = 0;
                    }
                }
            }
            // also when a close tag is before an open tag and the tags are the same
            if($this->valueArray[$i]['type'] == "close"){
                if( $i+1 < count($this->valueArray) ){
                    if(    $this->valueArray[$i+1]['type'] == "open" && $this->valueArray[$i+1]['tag'] == $this->valueArray[$i]['tag'])
                        $this->duplicateKeys[$this->valueArray[$i]['tag']] = 0;
                }
            }

        }

    }

    private function setArrayValue(&$array, $stack, $value){
        if ($stack) {
            $key = array_shift($stack);
            $this->setArrayValue($array[$key], $stack, $value);
            return $array;
        } else {
            $array = $value;
        }
    }

    public function getOutput(){
        return $this->output;
    }

    public function getStatus(){
        return $this->status;
    }

}

?>

Usage:

$p = new XMLParser($xml);
$p->getOutput();
Alf Marius Foss Olsen 12-Sep-2007 06:46
<?php
/*
  An easy lightweight (Array ->) XML -> Array algorithm..

  Typical case: You have an array you want to export to an external server,
                so you make XML out of it, exports it, and "on the other side"
                make it into an array again. These two functions will take care
                of that last part, ie XML -> Array

  NOTE! The function XMLToArray assumes that the XML _dont_ have nodes on the
        same level with the same name, then it just wont work. This is not a
        problem, as this case deals with Array -> XML -> Array, and an array
        cant have to identical indexes/keys.
*/

function XMLToArray($xml) {
  $parser = xml_parser_create('ISO-8859-1'); // For Latin-1 charset
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); // Dont mess with my cAsE sEtTings
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); // Dont bother with empty info
  xml_parse_into_struct($parser, $xml, $values);
  xml_parser_free($parser);

  $return = array(); // The returned array
  $stack = array(); // tmp array used for stacking
  foreach($values as $val) {
    if($val['type'] == "open") {
      array_push($stack, $val['tag']);
    } elseif($val['type'] == "close") {
      array_pop($stack);
    } elseif($val['type'] == "complete") {
      array_push($stack, $val['tag']);
      setArrayValue($return, $stack, $val['value']);
      array_pop($stack);
    }//if-elseif
  }//foreach
  return $return;
}//function XMLToArray

function setArrayValue(&$array, $stack, $value) {
  if ($stack) {
    $key = array_shift($stack);
    setArrayValue($array[$key], $stack, $value);
    return $array;
  } else {
    $array = $value;
  }//if-else
}//function setArrayValue

// USAGE:
$xml = <<<QQQ
<?xml version="1.0"?>
<root>
  <node1>Some text</node1>
  <node2a>
    <node2b>
      <node2c>Some text</node2c>
    </node2b>
  </node2a>
</root>\n
QQQ;
$array = XMLToArray($xml);
print "<pre>";
print_r($array);
print "</pre>";
//  Output:
//
//  Array
//  (
//      [root] => Array
//          (
//              [node1] => Some text
//              [node2a] => Array
//                  (
//                      [node2b] => Array
//                          (
//                              [node2c] => Some text
//                          )
//                  )
//          )
//  )
?>
vinod at citadel-soft dot com 01-Sep-2007 03:43
My previous code was having some bugs in, that is fixed now

<?php
class CSLXmlReader {
    private $tagstack;
    private $xmlvals;
    private  $xmlvarArrPos;
    private $xmlfile;
    function __construct($filename)  // constructor to intialize the stack and val array
    {

        $this->tagstack = array();   // contain the open tags till now
        $this->xmlvals = array();
        $this->xmlvarArrPos = $this->xmlvals;  // temporary variable to hold the current tag position
        $this->xmlfile = $filename;
    }
    function readDatabase()
    {
        // read the XML database
        $data = implode("", file($this->xmlfile));
        $parser = xml_parser_create();
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, $data, $values, $tags);
        xml_parser_free($parser);

        foreach($values as $key => $val)  //
        {
            if($val['type'] == "open")
            {
                array_push($this->tagstack, $val['tag']);
                $this->getArrayPath();
                if(count($this->xmlvarArrPos) > 0 && (!array_key_exists(0,$this->xmlvarArrPos)))
                {
                    $temp1 = $this->xmlvarArrPos;
                    $this->xmlvarArrPos =  array();
                    $this->xmlvarArrPos[0] = $temp1;
                    array_push($this->tagstack, 1);
                }
                else if( array_key_exists(0,$this->xmlvarArrPos)){
                    $opncount = count($this->xmlvarArrPos);
                    array_push($this->tagstack, $opncount);
                }
                $tagStackPointer += 1;
            }else if($val['type'] == "close")
            {
                while( $val['tag'] != ($lastOpened = array_pop($this->tagstack))){}
            }else if($val['type'] ==  "complete")
            {
                $this->getArrayPath();
                if( array_key_exists($val['tag'],$this->xmlvarArrPos))
                {
                    if(array_key_exists(0,$this->xmlvarArrPos[$val['tag']]))
                    {
                        $elementCount = count($this->xmlvarArrPos[$val['tag']]);
                        $this->xmlvarArrPos[$val['tag']][$elementCount] = $val['value'];
                    }else
                    {
                        $temp1 = $this->xmlvarArrPos[$val['tag']];
                        $this->xmlvarArrPos[$val['tag']] =  array();
                        $this->xmlvarArrPos[$val['tag']][0] = $temp1;
                        $this->xmlvarArrPos[$val['tag']][1] = $val['value'];
                    }
                } else
                {
                    $this->xmlvarArrPos[$val['tag']] = $val['value'];
                }
            }
        }
        reset($this->xmlvals);
        return $this->xmlvals;
    }
    function getArrayPath()
    {

        reset($this->xmlvals);
        $this->xmlvarArrPos = &$this->xmlvals;
        foreach($this->tagstack as $key)
        {
            $this->xmlvarArrPos = &$this->xmlvarArrPos[$key];

        }
    }

}

$readerObj  = new CSLXmlReader("test.xml");
$xmlvals = $readerObj->readDatabase();

echo "########## XML Values In array as the multidimentional array  #############\n";
echo "<pre>";
print_r($xmlvals);
echo "</pre>";

?>
siteres at gmail dot com 07-Feb-2007 01:38
PHP: XML to Array and backwards:

Here the XML with PHP solution: XML->Array and Array->XML.
Work with it as with usual array.

Sources are here:
http://mysrc.blogspot.com/2007/02/php-xml-to-array-and-backwards.html
(leave me comments:)

Example #1 (1.xml):

<ddd>
 <onemore dd="55">
  <tt>333</tt>
  <tt ss="s1">555</tt>
  <tt>777</tt>
 </onemore>
 <two>sdf rr</two>
</ddd>

The code:

$xml=xml2ary(file_get_contents('1.xml'));
print_r($xml);

Here is the Array result:

Array
(
   [ddd] => Array (
           [_c] => Array (
                   [_p] => Array *RECURSION*
                   [onemore] => Array (
                           [_a] => Array (
                                   [dd] => 55
                               )
                           [_c] => Array (
                                   [_p] => Array  *RECURSION*
                                   [tt] => Array (
                                           [0] => Array (
                                                   [_v] => 333
                                               )
                                           [1] => Array (
                                                   [_a] => Array (
                                                           [ss] => s1
                                                       )
                                                   [_v] => 555
                                               )
                                           [2] => Array (
                                                   [_v] => 777
                                               )
                                       )
                               )
                       )
                   [two] => Array (
                           [_v] => sdf rr
                       )
               )
       )
)
webmaster at after5webdesign dot com 30-Nov-2006 04:48
That parser also has a problem in which it will not parse more items than the current level it is on. That is, parsing this:  <1><2>A</2><2>B</2><2>C</2></1>
Will only result in this: A B
C is never processed.

It might be better with something like this:
          $file = get_url('http://news.search.yahoo.com/news/rss?p=current+events', URL_CONTENT);
          $data = $file['content'];
          $xml_parser = xml_parser_create();
          xml_parse_into_struct($xml_parser, $data, $vals, $index);
          xml_parser_free($xml_parser);
          //Uncomment the lines below to see the entire structure of your XML document
          //echo "<pre>INDEX: \n";
          //print_r ($index);
          //echo "\n \n \n VALUES:";
          //print_r ($vals);
          //echo "</pre>";
          $params = array();
          $level = array();
          $start_level = 1;
          foreach ($vals as $xml_elem) {
            if ($xml_elem['type'] == 'open') {
              if (array_key_exists('attributes',$xml_elem)) {
                list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
              } else {
                $level[$xml_elem['level']] = $xml_elem['tag'];
              }
            }
            if ($xml_elem['type'] == 'complete') {
              $php_stmt = '$params';
              while($start_level < $xml_elem['level']) {
                $php_stmt .= '[$level['.$start_level.']]';
                $start_level++;
              }
              $php_stmt .= '[$xml_elem[\'tag\']][] = $xml_elem[\'value\'];';
              eval($php_stmt);
              $start_level--;
            }
          }
          echo "<pre>";
          print_r ($params);
          echo "</pre>";

~Tim_Myth
Elad Elrom 12-Sep-2006 02:14
This is a quick fix for parsing XML from remote URL, some of the example above will work when trying to parse on your local server without "http://" but not when trying to parse from remote server using "http://www.URL"...

<?
$file="http://www.URL.com/file.XML";

$xml_parser = xml_parser_create();

$handle = fopen($file, "rb");
$contents = '';
while (!feof($handle)) {
  $data .= fread($handle, 8192);
}
fclose($handle);

xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
   if (array_key_exists('attributes',$xml_elem)) {
     list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
   } else {
     $level[$xml_elem['level']] = $xml_elem['tag'];
   }
  }
  if ($xml_elem['type'] == 'complete') {
   $start_level = 1;
   $php_stmt = '$params';
   while($start_level < $xml_elem['level']) {
     $php_stmt .= '[$level['.$start_level.']]';
     $start_level++;
   }
   $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
   eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";
?>
efredricksen at gmail dot com 24-May-2006 12:55
Perhaps the one true parser:? I modified xademax's fine code to tidy it up, codewise and style wise, rationalize some minor crazyness, and make names fit nomenclature from the XML spec. (There are no uses of eval, and shame on you people who do.)

<?php
class XmlElement {
  var $name;
  var $attributes;
  var $content;
  var $children;
};

function xml_to_object($xml) {
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $xml, $tags);
  xml_parser_free($parser);

  $elements = array();  // the currently filling [child] XmlElement array
  $stack = array();
  foreach ($tags as $tag) {
    $index = count($elements);
    if ($tag['type'] == "complete" || $tag['type'] == "open") {
      $elements[$index] = new XmlElement;
      $elements[$index]->name = $tag['tag'];
      $elements[$index]->attributes = $tag['attributes'];
      $elements[$index]->content = $tag['value'];
      if ($tag['type'] == "open") {  // push
        $elements[$index]->children = array();
        $stack[count($stack)] = &$elements;
        $elements = &$elements[$index]->children;
      }
    }
    if ($tag['type'] == "close") {  // pop
      $elements = &$stack[count($stack) - 1];
      unset($stack[count($stack) - 1]);
    }
  }
  return $elements[0];  // the single top-level element
}

// For example:
$xml = '
<parser>
   <name language="en-us">Fred Parser</name>
   <category>
       <name>Nomenclature</name>
       <note>Noteworthy</note>
   </category>
</parser>
';
print_r(xml_to_object($xml));
?>

will give:

xmlelement Object
(
    [name] => parser
    [attributes] =>
    [content] =>
    [children] => Array
        (
            [0] => xmlelement Object
                (
                    [name] => name
                    [attributes] => Array
                        (
                            [language] => en-us
                        )

                    [content] => Fred Parser
                    [children] =>
                )

            [1] => xmlelement Object
                (
                    [name] => category
                    [attributes] =>
                    [content] =>
                    [children] => Array
                        (
                            [0] => xmlelement Object
                                (
                                    [name] => name
                                    [attributes] =>
                                    [content] => Nomenclature
                                    [children] =>
                                )

                            [1] => xmlelement Object
                                (
                                    [name] => note
                                    [attributes] =>
                                    [content] => Noteworthy
                                    [children] =>
                                )

                        )

                )

        )

)
Stuart 23-May-2006 03:26
This is a great little function for a lot of XML work, but note that this function does not handle XML entities properly.

The basic XML entities &lt; &gt; &amp; &quot; are fine, just anything else will not work:

If the entity is defined in the XML header, the parser will drop it completely from the struct it creates.

If the entity is not defined in the XML then the parser will crash out with an undefined entity error.

You should be able to work around this limitation by using a preg_replace on your XML string before passing it to the parser.

(Further details in Bug #35271; this is just a warning to those thinking of using this function for parsing real XML documents not just trivial XML examples)
xademax at gmail dot com 08-Jan-2006 12:15
This is just another simple xml parser :)

<?php

class Xml
{
    var $tag;
    var $value;
    var $attributes;
    var $next;
}

function xml2array($xml_string)
{
    $Parser = xml_parser_create();
    xml_parser_set_option($Parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($Parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($Parser, $xml_string, $Xml_Values);
    xml_parser_free($Parser);
    $XmlClass = array();
    $LastObj = array();
    $NowObj = &$XmlClass;

    foreach($Xml_Values as $Xml_Key => $Xml_Value)
    {
        $Index = count($NowObj);
        if($Xml_Value["type"] == "complete")
        {
            $NowObj[$Index] = new Xml;
            $NowObj[$Index]->tag = $Xml_Value["tag"];
            $NowObj[$Index]->value = $Xml_Value["value"];
            $NowObj[$Index]->attributes = $Xml_Value["attributes"];
        }
        elseif($Xml_Value["type"] == "open")
        {
            $NowObj[$Index] = new Xml;
            $NowObj[$Index]->tag = $Xml_Value["tag"];
            $NowObj[$Index]->value = $Xml_Value["value"];
            $NowObj[$Index]->attributes = $Xml_Value["attributes"];
            $NowObj[$Index]->next = array();
            $LastObj[count($LastObj)] = &$NowObj;
            $NowObj = &$NowObj[$Index]->next;
        }
        elseif($Xml_Value["type"] == "close")
        {
            $NowObj = &$LastObj[count($LastObj) - 1];
            unset($LastObj[count($LastObj) - 1]);
        }

    }

    return $XmlClass;
}

$String = "
<parser>
    <parseur_name>MyParser</parseur_name>
    <category>
        <name>Name 1</name>
        <note>A note 1</note>
    </category>
</parser>
";
$Xml = xml2array($String);

print_r($Xml);
?>

This exemple will show :
Array
(
    [0] => Xml Object
        (
            [tag] => parser
            [value] =>
            [attributes] =>
            [next] => Array
                (
                    [0] => Xml Object
                        (
                            [tag] => parseur_name
                            [value] => MyParser
                            [attributes] =>
                            [next] =>
                        )

                    [1] => Xml Object
                        (
                            [tag] => category
                            [value] =>
                            [attributes] =>
                            [next] => Array
                                (
                                    [0] => Xml Object
                                        (
                                            [tag] => name
                                            [value] => Name 1
                                            [attributes] =>
                                            [next] =>
                                        )

                                    [1] => Xml Object
                                        (
                                            [tag] => note
                                            [value] => A note 1
                                            [attributes] =>
                                            [next] =>
                                        )

                                )

                        )

                )

        )

)
mbirth at webwriters dot de 08-Nov-2005 03:48
Searching for a nice and working way to get a RSS feed into an array-structure, I found the solution posted by kieran but disliked those several eval()s. So I wrote my own using references/pointers.

<?php

class RSSParser {

  var $struct = array();  // holds final structure
  var $curptr;  // current branch on $struct
  var $parents = array();  // parent branches of current branch

  function RSSParser($url) {
    $this->curptr =& $this->struct;  // set ref to base
    $xmlparser = xml_parser_create();
    xml_set_object($xmlparser, $this);
    xml_set_element_handler($xmlparser, 'tag_open', 'tag_close');
    xml_set_character_data_handler($xmlparser, 'cdata');
    $fp = fopen($url, 'r');

    while ($data = fread($fp, 4096))
      xml_parse($xmlparser, $data, feof($fp))
      || die(sprintf("XML error: %s at line %d",
         xml_error_string(xml_get_error_code($xmlparser)),
         xml_get_current_line_number($xmlparser)));

    fclose($fp);
    xml_parser_free($xmlparser);
  }

  function tag_open($parser, $tag, $attr) {
    $i = count($this->curptr['children']);
    $j = count($this->parents);
    $this->curptr['children'][$i]=array();  // add new child element
    $this->parents[$j] =& $this->curptr;  // store current position as parent
    $this->curptr =& $this->curptr['children'][$i];  // submerge to newly created child element
    $this->curptr['name'] = $tag;
    if (count($attr)>0) $this->curptr['attr'] = $attr;
  }

  function tag_close($parser, $tag) {
    $i = count($this->parents);
    if ($i>0) $this->curptr =& $this->parents[$i-1];  // return to parent element
    unset($this->parents[$i-1]);  // clear from list of parents
  }

  function cdata($parser, $data) {
    $data = trim($data);
    if (!empty($data)) {
      $this->curptr['value'] .= $data;
    }
  }

}

$myparser = new RSSParser('getitems.xml');
$anotherparser = new RSSParser('http://johndoe:secret@myfeeds.com/getfeed.xml');

print_r($myparser->struct);
print_r($anotherparser->struct);

?>
kieran at kieran dot ca 20-Oct-2005 09:20
<?
/*
|
| _xml2array - another abstraction layer on xml_parse_into_struct
|              that returns a nice nested array.
|
|      @param: $xml is a string containing a full xml document
|
|     returns: a nested php array that looks like this:
|
|              array
|              (
|                  [_name] => the name of the tag
|                  [_attributes] => an array of 'attribute'=>'value' combos
|                  [_value] => the text contents of the node
|                  [_children] => an array of these arrays, one for each node.
|              )
|
|       notes: thanks to 'jeffg at activestate dot com' who inspired
|              me to essentially re-write his example code from php.net
|
|           me: Kieran Huggins < kieran[at]kieran[dot]ca >
|
*/
function _xml2array($xml){
    global $keys;
    global $level;
    if(!is_array($xml)){ // init on first run
        $raw_xml = $xml;
        $p = xml_parser_create();
        xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($p, $raw_xml, $xml, $idx);
        xml_parser_free($p);
    }
    for($i=0;$i<count($xml,1);$i++){
        // set the current level
        $level = $xml[$i]['level'];

        if($level<1)break;

        // mark this level's tag in the array
        $keys[$level] = '['.$i.']';

        // if we've come down a level, sort output and destroy the upper level
        if(count($keys)>$level) unset($keys[count($keys)]);

        // ignore close tags, they're useless
        if($xml[$i]['type']=="open" || $xml[$i]['type']=="complete"){

            // build the evalstring
            $e = '$output'.implode('[\'_children\']',$keys);

            // set the tag name
            eval($e.'[\'_name\'] = $xml[$i][\'tag\'];');

            // set the attributes
            if($xml[$i]['attributes']){
                eval($e.'[\'_attributes\'] = $xml[$i][\'attributes\'];');
            }

            // set the value
            if($xml[$i]['value']){
                eval($e.'[\'_value\'] = trim($xml[$i][\'value\']);');
            }

        }

    }

    return $output;
}
?>
Chris Hester 28-Jul-2005 05:06
The array generated from XML stores not only the elements but also any spaces and linebreaks between the tags. This results in a much longer array. (I had 24 array fields instead of 10!) To cure this use the following code when creating the parser:

<?php
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE,1);
?>
PhF at madmac dot fr 23-Jun-2005 01:11
The code previously posted by noob at noobsrule dot com doesn't work when the same tag name is used at different levels.
(but perhaps "$php_used_prefix" was intended for that ?)
For example:
<RatedShipment>
  <TransportationCharges>
    ...
  </TransportationCharges>
  <RatedPackage>
    <TransportationCharges>
      ...
    </TransportationCharges>
  </RatedPackage>
</RatedShipment>
<?php
    $p = xml_parser_create();
    xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($p, $UPSxml, $values, $idx);
    xml_parser_free($p);

    // tracking used keys
    $usedKeys = array();
    $deepLevel = -1;

    // start a php array string (evaluated later)
    $forEvalPrefix = '$xml_array';

    // loop throught the value array
    foreach ($values as $key => $val) {
        $tagName = $val['tag']; // pass the key tag into a more friendly looking variable
        $level = $val['level']; // idem
        if($val['type'] == 'open') {
            $deepLevel++; // increase deep level
            $forEvalPrefix .= '[\''. $tagName .'\']';

            // begin used keys checks to allow multidimensionatity under the same tag
            (isset($usedKeys[$level][$tagName])) ? $usedKeys[$level][$tagName]++ : $usedKeys[$level][$tagName] = 0;
            $forEvalPrefix .= '['. $usedKeys[$level][$tagName] .']';
        }
        if($val['type'] == 'complete') {
            ($level > $deepLevel) ? $deepLevel++ : ''; // increase $deepLevel only if current level is bigger
            $tagValue = addslashes($val['value'] ); // format the value for evaluation as a string
            $forEvalSuffix = '[\''. $tagName .'\'] = \''. $tagValue .'\';'; // create a string to append to the current prefix
            $forEval = $forEvalPrefix . $forEvalSuffix; // (without "$php_used_prefix"...)
            eval($forEval); // write the string to the array structure
        }
        if($val['type'] == 'close') {
            unset($usedKeys[$deepLevel]); // Suppress tagname's keys useless
            $deepLevel--;
            $forEvalPrefix = substr($forEvalPrefix, 0, strrpos($forEvalPrefix, '[')); // cut off the used keys node
            $forEvalPrefix = substr($forEvalPrefix, 0, strrpos($forEvalPrefix, '[')); // cut off the end level of the array string prefix
        }
    }
echo '<pre>';
print_r ($xml_array);
echo '</pre>';
?>

MADmac ;-)
peter at elemental dot org 15-Jun-2005 08:46
Quick addendum to my post below... The code does *not* handle cases where multiple elements are used without attribute IDs, as is the case with the moldb example.  (It is probably worth noting that some of the other code below doesn't do this either, and is still more complex.)

It is not difficult to add that functionality, but I have yet to find an elegant way to integrate that feature, and since I don't need that functionality at the moment, I'm going leave that as an exercise to the reader.  ;-)

-p.
peter at elemental dot org 14-Jun-2005 04:09
Some of the code posted previously seemed absurdly complex, so I thought I'd see if I could simplify things a bit. Here's what I came up with.  (I'm still a PHP newbie, so perhaps I simplified too much.  ;-)  Untested for speed, but it *should* be pretty quick since it uses references instead of lookups or (gack) evals.

Enjoy!

/*
 *  Convert a string containing XML into a nested array
 *
 *  Takes a raw XML string as input
 *  Returns a nested array
 */

function xml2array ($xml_data)
{
    // parse the XML datastring
    $xml_parser = xml_parser_create ();
    xml_parse_into_struct ($xml_parser, $xml_data, $vals, $index);
    xml_parser_free ($xml_parser);

    // convert the parsed data into a PHP datatype
    $params = array();
    $ptrs[0] = & $params;
    foreach ($vals as $xml_elem) {
        $level = $xml_elem['level'] - 1;
        switch ($xml_elem['type']) {
        case 'open':
            $tag_or_id = (array_key_exists ('attributes', $xml_elem)) ? $xml_elem['attributes']['ID'] : $xml_elem['tag'];
            $ptrs[$level][$tag_or_id] = array ();
            $ptrs[$level+1] = & $ptrs[$level][$tag_or_id];
            break;
        case 'complete':
            $ptrs[$level][$xml_elem['tag']] = (isset ($xml_elem['value'])) ? $xml_elem['value'] : '';
            break;
        }
    }

    return ($params);

}
noob at noobsrule dot com 24-Jan-2005 10:59
This is my first time contributing but I found all the examples either didn't work or were beyond my comprehension.  I also wanted to maintain the XML multi-dimensionality so I could do loops based on keys I was expecting rather than numbers or some other whatnot.  This script is probably way inefficient, but should give you a multidimensional array with a depth that will match the XML source.  Great for situations when you aren't sure what you'll be getting back.  Its also only based on the values array of xml_parse_into_str() using the 3 tag types (open, complete, and close) -- hopefully it will make more sense to other noobs.

Basically it just constructs a string ($php_prefix) that is tweaked if it hits an "open" or "close" tag and evaluated if it hits a "complete" tag.

Thanks.

<?php

# initiate curl session...
$ch = curl_init( "http://yourtargethost" ) or die ( "could not initialize curl" );

# set curl options...
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $request_str );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 0 );
curl_setopt( $ch, CURLOPT_REFERER, https://foobar.com" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );

# execute curl commands...
$curl_result = curl_exec( $ch ) or die ( "could not execute the post" );
curl_close( $ch ); // close curl session

# pass the XML result into 2 arrays ( index and values )...
$p = xml_parser_create();
xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($p, $curl_result, $vals, $index);
xml_parser_free($p);

# create an empty used key tracker...
$used_keys = array();

# start a php array string (evaluated later)...
$php_prefix = "$"."my_array";

# loop through the values array...
foreach ($vals as $key => $val) {
    if( $val['type'] == "open" ) {
        $my_tag = $val['tag']; // pass the key tag into a more friendly looking variable...
        $php_prefix .= "['".$my_tag."']"; # add a new level to the array string...

        # begin used key checks to allow multidimensionality under the same tag, adds a number to the prefix if necessary...
        if( ! array_key_exists( $my_tag, $used_keys ) ) {
            $used_keys[$my_tag] = 0;
            $php_prefix .= "[".$used_keys[$my_tag]."]";
        }else {
            $used_keys[$my_tag]++; // increment the key tracker to avoid overwriting existing key...
            $php_prefix .= "[".$used_keys[$my_tag]."]";
        }
    } elseif( $val['type'] == "complete" ) {
        $my_value = addslashes( $val['value'] ); # format the value for evaluation as a string...
        $php_suffix = "['".$val['tag']."'] = \"".$my_value."\";"; # create a string with the tag and value to append to the current prefix (just used here)...
        $php_str = $php_prefix.$php_used_prefix.$php_suffix;
        eval( $php_str ); # write the string to the array structure...
    }
    if( $val['type'] == "close" ) {
        $php_prefix = substr( $php_prefix, 0, strrpos( $php_prefix, "[" ) ); # cut off the used keys node...
        $php_prefix = substr( $php_prefix, 0, strrpos( $php_prefix, "[" ) ); # cut off the end level of the array string prefix...
    }
}

echo "<pre>";
//print_r ($index);
//echo "<br><br><br>";
//print_r ($vals);
//echo "<br><br><br>";
print_r ($my_array);
echo "</pre>";

?>
dudus at onet dot pl 18-Jan-2005 06:33
This function return array from XML. Included attributes and tags in same level.
I wrote this function based on mmustafa code.

enjoy!
dUDA

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

<?
function XMLtoArray($XML)
{
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $XML, $vals);
    xml_parser_free($xml_parser);
    // wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie
    $_tmp='';
    foreach ($vals as $xml_elem)
    {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_level!=1 && $x_type == 'close')
        {
            if (isset($multi_key[$x_tag][$x_level]))
                $multi_key[$x_tag][$x_level]=1;
            else
                $multi_key[$x_tag][$x_level]=0;
        }
        if ($x_level!=1 && $x_type == 'complete')
        {
            if ($_tmp==$x_tag)
                $multi_key[$x_tag][$x_level]=1;
            $_tmp=$x_tag;
        }
    }
    // jedziemy po tablicy
    foreach ($vals as $xml_elem)
    {
        $x_tag=$xml_elem['tag'];
        $x_level=$xml_elem['level'];
        $x_type=$xml_elem['type'];
        if ($x_type == 'open')
            $level[$x_level] = $x_tag;
        $start_level = 1;
        $php_stmt = '$xml_array';
        if ($x_type=='close' && $x_level!=1)
            $multi_key[$x_tag][$x_level]++;
        while($start_level < $x_level)
        {
              $php_stmt .= '[$level['.$start_level.']]';
              if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])
                  $php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';
              $start_level++;
        }
        $add='';
        if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete'))
        {
            if (!isset($multi_key2[$x_tag][$x_level]))
                $multi_key2[$x_tag][$x_level]=0;
            else
                $multi_key2[$x_tag][$x_level]++;
             $add='['.$multi_key2[$x_tag][$x_level].']';
        }
        if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes',$xml_elem))
        {
            if ($x_type == 'open')
                $php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
            else
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\'value\'];';
            eval($php_stmt_main);
        }
        if (array_key_exists('attributes',$xml_elem))
        {
            if (isset($xml_elem['value']))
            {
                $php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\'content\'] = $xml_elem[\'value\'];';
                eval($php_stmt_main);
            }
            foreach ($xml_elem['attributes'] as $key=>$value)
            {
                $php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';
                eval($php_stmt_att);
            }
        }
    }
     return $xml_array;
}    // END XMLtoArray
?>
happyseb at free dot fr 24-Aug-2004 08:51
I would just add something about the solution proposed by "gordon at kanazawa dot ac dot jp".

Something went wrong about the fact that "cdata" are treated the same way as "complete" in the xml_get_children first and in the xml_get_child then.

When ?
with this method, something like this :
<tagA>
  <tagB>valueB</tagB>
  valueA
  <tagC>valueC</tagC>
</tagA>
is considered as the same thing as
<tagA>
  <tagB>valueB</tagB>
  <tagA>valueA</tagA>
  <tagC>valueC</tagC>
</tagA>

The algorithm is nomore bijective.

Even if it might not be perfect :-) i propose a little modification of the xml_get_child function :

function xml_get_child(&$v, $children=NULL) {
      $c = array(); // the "child"
      if (isset($v['tag']) && $v['type'] != 'cdata') $c['tag'] = $v['tag'];
      if (isset($v['value'])) $c['value'] = $v['value'];
      if (isset($v['attributes'])) $c['attributes'] = $v['attributes'];
      if (is_array($children)) $c['children'] = $children;
      return $c;
}

moreover, the following function will take the tree (made from the xml_get_tree function) as a parameter and build the xml content back

    /*
    // setTree
    // set xml Tree from a well-formed array
    // manage indentation
    // Parameters are :
    // $1 (needed) : Tree to transform
    // $2 (optional) : Indentation type (default is one tabulation)
    // $3 (optional) : First indent (default is empty string)
    */

    function setTree($Atree, $indentType = '    ', $Sindent = '')
    {
      if (! isset ($Atree['tag']) && isset ($Atree['value'])) return ($Sindent.trim($Atree['value'])."\r\n") ;
      else {
        $Stemp = $Sindent.'<'.$Atree['tag'].' ' ;
        if (isset ($Atree['attributes']) && is_array ($Atree['attributes'])) {
          foreach ($Atree['attributes'] as $Aattribute => $Svalue) $Stemp .= $Aattribute.'="'.$Svalue.'" ' ;
        }
        if (! isset ($Atree['children']) && ! isset ($Atree['value'])) $Stemp .= '/>'."\r\n" ;
        else {
          $Stemp .= '>'."\r\n" ;
          if (isset ($Atree['value'])) $Stemp .= $Sindent.$indentType.trim($Atree['value'])."\r\n" ;
          if (isset ($Atree['children']) && is_array ($Atree['children']))
            foreach ($Atree['children'] as $Achild) $Stemp .= $this->setTree($Achild, $indentType, $Sindent.$indentType) ;
          $Stemp .= $Sindent.'</'.$Atree['tag'].'>'."\r\n" ;
        }
        return ($Stemp) ;
      }
    }
sdh33 at cornell dot edu 13-Jun-2004 10:12
(The previous post I wrote was incorrect.  I fix that herein)
I used the algorithm from stephane for writing back to a file, but ran into the following problem.  My original XML looks like

<ENTRY id="1"> ... </ENTRY><ENTRY id="2"> ... </ENTRY>

This got saved back as

<1> ... </1><2> ... </2>,

which expat doesn't like.  So I propose the following modification:

function writeXmlToFile($data, $f, $niv = 0) {
  foreach($data as $name => $elem) {
    if (preg_match("/\A[0-9]/",$name)) {
      $open = "ENTRY id=\"$name\""; $name = "ENTRY";
    } else {
      $open = $name;
    }
    if(is_array($elem)) {
      fwrite($f, str_repeat("  ", $niv)."<".$open.">"."\n");
      writeXmlToFile($elem, $f, $niv + 1);
      fwrite($f, str_repeat("  ", $niv)."</".$name.">"."\n");
    } else {
      fwrite($f, str_repeat("  ", $niv)."<".$open.">".$elem."</".$name.">"."\n");
    }
  }
}
stephane dot dekeyzer at noemail dot com 08-Apr-2004 11:54
for writing the array of mmustafa back to a xml file, use this code:

function writeXmlFile($fileName, $struct){
  $f = fopen($fileName, "w");
  writeXmlToFile($struct, $f);
  fclose($f);
}

function writeXmlToFile($data, $f, $niv = 0){
  foreach($data as $name => $elem){
    if(is_array($elem)){
      fwrite($f, str_repeat("  ", $niv)."<".$name.">"."\n");
      writeXmlToFile($elem, $f, $niv + 1);
      fwrite($f, str_repeat("  ", $niv)."</".$name.">"."\n");
    }
    else{
      fwrite($f, str_repeat("  ", $niv)."<".$name.">".$elem."</".$name.">"."\n");
    }
  }
}
mmustafa at vsnl dot com 06-Jan-2004 12:19
A small and simple php code to convert the raw array returned by xml_parse_into_struct into a proper data structure ..

<?php
$file = "data.xml";
$xml_parser = xml_parser_create();

if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

$data = fread($fp, filesize($file));
fclose($fp);
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);

$params = array();
$level = array();
foreach ($vals as $xml_elem) {
  if ($xml_elem['type'] == 'open') {
    if (array_key_exists('attributes',$xml_elem)) {
      list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
    } else {
      $level[$xml_elem['level']] = $xml_elem['tag'];
    }
  }
  if ($xml_elem['type'] == 'complete') {
    $start_level = 1;
    $php_stmt = '$params';
    while($start_level < $xml_elem['level']) {
      $php_stmt .= '[$level['.$start_level.']]';
      $start_level++;
    }
    $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
    eval($php_stmt);
  }
}

echo "<pre>";
print_r ($params);
echo "</pre>";
?>

Converts an XML document like ..

<country id="ZZ">
<name>My Land</name>
<location>15E</location>
<area>40000</area>
<state1>
<name>Hi State</name>
<area>1000</area>
<population>2000</population>
<city1>
<location>13E</location>
<population>500</population>
<area>500</area>
</city1>
<city2>
<location>13E</location>
<population>500</population>
<area>5000</area>
</city2>
</state1>
<state2>
<name>Low State</name>
<area>3000</area>
<population>20000</population>
<city1>
<location>15E</location>
<population>5000</population>
<area>1500</area>
</city1>
</state2>
</country>

To a php datastructure like ..

Array
(
    [ZZ] => Array
        (
            [NAME] => My Land
            [LOCATION] => 15E
            [AREA] => 40000
            [STATE1] => Array
                (
                    [NAME] => Hi State
                    [AREA] => 1000
                    [POPULATION] => 2000
                    [CITY1] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 500
                        )

                    [CITY2] => Array
                        (
                            [LOCATION] => 13E
                            [POPULATION] => 500
                            [AREA] => 5000
                        )

                )

            [STATE2] => Array
                (
                    [NAME] => Low State
                    [AREA] => 3000
                    [POPULATION] => 20000
                    [CITY1] => Array
                        (
                            [LOCATION] => 15E
                            [POPULATION] => 5000
                            [AREA] => 1500
                        )

                )

        )

)
bisqwit at iki dot fi dot not dot for dot ads dot invalid 20-Nov-2002 08:33
I made my own xml2tree()-function.
The difference to the previously suggested ones on this manual page is that this creates a tree where the tags are keys.

Example input:

<tree>
 <leaf name="gruu"> pl?? </leaf>
 <animal type="cat" />
</tree>

Example output:

Array
( 'tree' => Array
     ( 0 => Array
          ( 'children' => Array
               ( 'leaf' => Array
                    ( 0 => Array
                         ( 'attrs' => Array('name' => 'gruu'),
                           'values' => Array(0 => ' pl?? ')
                    )    ),
                 'animal' => Array
                    ( 0 => Array
                         ( 'attrs' => Array('type' => 'cat')
)    )   )    )    )   )

function xml2tree2($string)
{
  $parser = xml_parser_create();
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, $string, $vals, $index);
  xml_parser_free($parser);

  $stack = array( array() );
  $stacktop = 0;
  $parent = array();
  foreach($vals as $val)
  {
    $type = $val['type'];
    if($type=='open' || $type=='complete')
    {
      // open tag
      $stack[$stacktop++] = $tagi;
      $tagi = array('tag' => $val['tag']);

      if(isset($val['attributes']))  $tagi['attrs'] = $val['attributes'];
      if(isset($val['value']))
        $tagi['values'][] = $val['value'];
    }
    if($type=='complete' || $type=='close')
    {
      // finish tag
      $tags[] = $oldtagi = $tagi;
      $tagi = $stack[--$stacktop];
      $oldtag = $oldtagi['tag'];
      unset($oldtagi['tag']);
      $tagi['children'][$oldtag][] = $oldtagi;
      $parent = $tagi;
    }
    if($type=='cdata')
    {
      $tagi['values'][] = $val['value'];
    }
  }
  return $parent['children'];
}

Ps: Note that the xml parsing for some reason chokes if the values contain <> (even inside ""). You need to escape them as &lt; and &gt;.
Same for & (for obvious reasons). Escape it as &amp;.
For example "&nbsp;" should be written as "&amp;nbsp;".
09-Aug-2002 01:20
This is based on a comment above by mh@mainlab.de.  This version makes more sense to me and I included a few comments that might make it more usefull for specific purposes.

// Look through $vals and $index,
// generated by parse_xml_data(),
// for $location.  $location resembles a unix path.
// E.g. "my/xml/path/to/my/data".
// Note: This is NOT a full-feature xml utility.
// Your path must be unique in the xml data
// and the tags must not contain slashes.
//
// returns: cdata from last element of $location
//          or NULL.
function get_xml_values($vals, $index, $location) {
  $location = explode('/', $location);
  $location_level = count($location);
  for ($n=0; $n<$location_level; ++$n) {
    $val_indexes=$index[$location[$n]];
    $good=0;
    for ($i=0; $i<count($val_indexes); ++$i) {
      $v = $vals[$val_indexes[$i]];
      // level is 1 based, n is 0 based:
      if ($v['level']-1 == $n) {
        if ($v['type'] == 'open') {
          // We found an open tag at the correct level.
          $good=1;
          break; // Remove break to avoid 'open' hiding
                 // 'complete' at last $n. (Speed Vs. Robustness:
                 // For now, I'm going with speed).
        }
        if ($v['type'] == 'complete') {
          // We found it, after finding all the prior elements:
          // You may want to change this to
          // return $v
          // so you can call $v['value'] and $v['attributes']
          return $v['value'];
        }
      }
    }
    if (!$good) {
      return NULL;
    }
  }
}
farinspace-at-hotmail-dot-com 20-Jul-2002 06:41
Wow, took a while to consume all of this. I am a noobie at XML, in fact i just really started working with it today. I went ahead and added to the above code by gdemartini@bol.com.br. I also added the update by nyk@cowham.net.

Added 'value' => $vals[$i]['value'] to the open case, as some nodes have both cdata as well as a children node. In previous versions of the functions the cdata of a node(a) that also had children would get stored in the children's array of the parent node(a). Now only children values are in the children array and the cdata is in the value key of the parent node(a).

Added 'value' => $vals[$i]['value'] to tree array as the vals array produced by PHP includes a value to the top most node if no children exist (for completeness).

Also, using xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE,1) will strip all white space from both around the XML tags as well as inside the cdata. I added a piece of code by waldo@wh-e.com to take care of this. All SPACE characters are now only stripped from around the XML tags and cdata spacing is retained.

CODE:
***************************************

function GetChildren($vals, &$i) {

    $children = array();

    while (++$i < sizeof($vals)) {

        // compair type
        switch ($vals[$i]['type']) {

            case 'cdata':
                $children[] = $vals[$i]['value'];
                break;
            case 'complete':
                $children[] = array(
                    'tag' => $vals[$i]['tag'],
                    'attributes' => $vals[$i]['attributes'],
                    'value' => $vals[$i]['value']
                );
                break;
            case 'open':
                $children[] = array(
                    'tag' => $vals[$i]['tag'],
                    'attributes' => $vals[$i]['attributes'],
                    'value' => $vals[$i]['value'],
                    'children' => GetChildren($vals, $i)
                );
                break;
            case 'close':
                return $children;
        }
    }
}

function GetXMLTree($file) {

    $data = implode('', file($file));

    // by: waldo@wh-e.com - trim space around tags not within
    $data = eregi_replace(">"."[[:space:]]+"."<","><",$data);

    // XML functions
    $p = xml_parser_create();

    // by: anony@mous.com - meets XML 1.0 specification
    xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
    xml_parse_into_struct($p, $data, &$vals, &$index);
    xml_parser_free($p);

    $i = 0;
    $tree = array();
    $tree[] = array(
        'tag' => $vals[$i]['tag'],
        'attributes' => $vals[$i]['attributes'],
        'value' => $vals[$i]['value'],
        'children' => GetChildren($vals, $i)
    );

    return $tree;
}

***************************************
dave at ovumdesign dot com 03-Apr-2002 03:32
Here is another variation on gdemartini@bol.com.br's nice tree algorithm. I have included nyk@cowham.net's "cdata" suggestion. I made a few changes to suppress unitialized variable warnings with error_reporting(E_ALL), and made a few stylistic changes.

There are two functional modifications as well. The first is the added option to expat to turn off "case folding", since XML is technically a case-sensitive language. The second is the returned tree - instead of returning a single-element list (an array with index 0 pointing to the top node) like the original algorithm, it returns the top node itself. This saves you an unnecessary level of indirection.

function xml_get_children($vals, &$i) {
    $children = array();
    if (isset($vals[$i]['value'])) $children[] = $vals[$i]['value'];

    while (++$i < count($vals)) {
        switch ($vals[$i]['type']) {
        case 'cdata':
            $children[] = $vals[$i]['value'];
            break;

        case 'complete':
            $children[] = array(
                'tag'        => $vals[$i]['tag'],
                'attributes' => isset($vals[$i]['attributes'])?
                                $vals[$i]['attributes'] : null,
                'value'      => $vals[$i]['value'],
            );
            break;

        case 'open':
            $children[] = array(
                'tag'        => $vals[$i]['tag'],
                'attributes' => isset($vals[$i]['attributes'])?
                                $vals[$i]['attributes'] : null,
                'children'   => xml_get_children($vals, $i),
            );
            break;

        case 'close':
            return $children;
        }
    }
}

function xml_get_tree($file) {
    $data = join('', file($file));

    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE,   1);
    xml_parse_into_struct($parser, $data, $vals, $index);
    xml_parser_free($parser);

    return array(
        'tag'        => $vals[0]['tag'],
        'attributes' => isset($vals[0]['attributes'])?
                        $vals[0]['attributes'] : null,
        'children'   => xml_get_children($vals, $i = 0),
    );
}

This function takes a tree returned by xml_get_tree() and simplifies it similarly to voncken@mailandnews.com and oknapp@soly.de's suggestions. It finds any nodes that expat considered "complete" (childless) and contain no attributes, and it moves the tag name (as the key) and value into an element in the parent node's "values" array.

For example:
$tree = xml_get_tree('moldb.xml');
$tree = xml_condense_tree($tree);
echo $tree['children'][1]['values']['name'];

Outputs:
Lysine

function xml_condense_tree($tree) {
    foreach ($tree['children'] as $index => $node) {
        if (isset($node['children'])) {
            $tree['children'][$index] = xml_condense_tree($node);

        } elseif (isset($node['value']) and !$node['attributes']) {
            $tree['values'][$node['tag']] = $node['value'];
            unset($tree['children'][$index]);
        }
    }

    if (!$tree['children']) unset($tree['children']);
    return $tree;
}

Enjoy,
Dave


Start parsing an XML document

  • « xml_parse_into_struct
  • xml_parser_create_ns »
  • PHP Manual
  • Funções para analisar XML
  • Start parsing an XML document

xml_parse

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

xml_parse — Start parsing an XML document

Descrição

xml_parse(XMLParser $parser, string $data, bool $is_final = false): int

xml_parse() parses an XML document. The handlers for the configured events are called as many times as necessary.

Parâmetros

parser

A reference to the XML parser to use.

data

Chunk of data to parse. A document may be parsed piece-wise by calling xml_parse() several times with new data, as long as the is_final parameter is set and true when the last data is parsed.

is_final

If set and true, data is the last piece of data sent in this parse.

Valor Retornado

Returns 1 on success or 0 on failure.

For unsuccessful parses, error information can be retrieved with
xml_get_error_code(),
xml_error_string(),
xml_get_current_line_number(),
xml_get_current_column_number() and
xml_get_current_byte_index().

Nota:

Some errors (such as entity errors) are reported at the end of the data, thus only if is_final is set and true.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

Exemplos

Exemplo #1 Chunked parsing of large XML documents

This example shows how large XML documents can be read and parsed in chunks, so that it not necessary to keep the whole document in memory. Error handling is omitted for brevity.

<?php
$stream = fopen('large.xml', 'r');
$parser = xml_parser_create();
// set up the handlers here
while (($data = fread($stream, 16384))) {
xml_parse($parser, $data); // parse the current chunk
}
xml_parse($parser, '', true); // finalize parsing
xml_parser_free($parser);
fclose($stream);

User Contributed Notes

Programmerdude 06-Aug-2014 07:26
Due to restrictions in libxml2 the maximum length of $data is 9.5MB. If you need to process more than 9.5MB you can do so by calling the function multiple times and setting $is_final on the last call.
alejandro dot anv at gmail dot com 13-Mar-2014 01:00
Here is my array2xml function. I made it because I coudn't find a generic recursive function that generates a prety formatted XML from any array.

Usage:

<?php echo xml2array('rootname',$myarray); ?>

or if you want to specify a spacing character(s) other than TAB:

<?php echo xml2array('rootname',$myarray,'   '); ?>

or if you want avoid spacing at all

<?php echo xml2array('rootname',$myarray,''); ?>

<?php
function array2xml($nombre,$valor,$tab="\t",$nivel=0){

if ($nivel==0) $r='<?xml version="1.0" encoding="ISO-8859-1"?>';

$arr=!is_numeric($nombre);
$spacing=str_repeat($tab,$nivel);
if ($tab!='') $newline="\n";
else $newline='';

if (is_array($valor)){

   if (count($valor)>0){
      $r.=$newline;
      //$r.=str_repeat($tab,$nivel);
      foreach($valor as $k=>$v){
         if ($arr) $r.="$spacing<$nombre>";

         if (is_array($v))  $r.=array2xml($k,$v,$tab,$nivel+$arr);
         else $r.="$spacing<$k>$v</$k>$newline";

         if ($arr) $r.="$spacing</$nombre>$newline";
         }//foreach
      }//count
   else $r.="$spacing<$nombre></$nombre>"; // it's an empty array
   }
else {
     if ($arr) $r.="$spacing<$nombre>";
     $r.=$valor;
     if ($arr) $r.="</$nombre>$newline";
     }

return $r;
}
?>
Ashok dot 893 at gmail dot com 25-Apr-2010 10:52
This is very simple way to convert all applicable objects into associative array.  This works with not only SimpleXML but any kind of object. The input can be either array or object. This function also takes an options parameter as array of indices to be excluded in the return array. And keep in mind, this returns only the array of non-static and accessible variables of the object since using the function get_object_vars().

<?php
function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
    $arrData = array();

    // if input is object, convert into array
    if (is_object($arrObjData)) {
        $arrObjData = get_object_vars($arrObjData);
    }

    if (is_array($arrObjData)) {
        foreach ($arrObjData as $index => $value) {
            if (is_object($value) || is_array($value)) {
                $value = objectsIntoArray($value, $arrSkipIndices); // recursive call
            }
            if (in_array($index, $arrSkipIndices)) {
                continue;
            }
            $arrData[$index] = $value;
        }
    }
    return $arrData;
}
?>

Usage:

<?php
$xmlUrl = "feed.xml"; // XML feed file/URL
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
print_r($arrXml);
?>
lz_speedy at web dot de 30-Dec-2008 10:20
Best seen xml2array function ever
<?php
function xml2array($url, $get_attributes = 1, $priority = 'tag')
{
    $contents = "";
    if (!function_exists('xml_parser_create'))
    {
        return array ();
    }
    $parser = xml_parser_create('');
    if (!($fp = @ fopen($url, 'rb')))
    {
        return array ();
    }
    while (!feof($fp))
    {
        $contents .= fread($fp, 8192);
    }
    fclose($fp);
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);
    if (!$xml_values)
        return; //Hmm...
    $xml_array = array ();
    $parents = array ();
    $opened_tags = array ();
    $arr = array ();
    $current = & $xml_array;
    $repeated_tag_index = array ();
    foreach ($xml_values as $data)
    {
        unset ($attributes, $value);
        extract($data);
        $result = array ();
        $attributes_data = array ();
        if (isset ($value))
        {
            if ($priority == 'tag')
                $result = $value;
            else
                $result['value'] = $value;
        }
        if (isset ($attributes) and $get_attributes)
        {
            foreach ($attributes as $attr => $val)
            {
                if ($priority == 'tag')
                    $attributes_data[$attr] = $val;
                else
                    $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
            }
        }
        if ($type == "open")
        {
            $parent[$level -1] = & $current;
            if (!is_array($current) or (!in_array($tag, array_keys($current))))
            {
                $current[$tag] = $result;
                if ($attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                $current = & $current[$tag];
            }
            else
            {
                if (isset ($current[$tag][0]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 2;
                    if (isset ($current[$tag . '_attr']))
                    {
                        $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                        unset ($current[$tag . '_attr']);
                    }
                }
                $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                $current = & $current[$tag][$last_item_index];
            }
        }
        elseif ($type == "complete")
        {
            if (!isset ($current[$tag]))
            {
                $current[$tag] = $result;
                $repeated_tag_index[$tag . '_' . $level] = 1;
                if ($priority == 'tag' and $attributes_data)
                    $current[$tag . '_attr'] = $attributes_data;
            }
            else
            {
                if (isset ($current[$tag][0]) and is_array($current[$tag]))
                {
                    $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                    if ($priority == 'tag' and $get_attributes and $attributes_data)
                    {
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag . '_' . $level]++;
                }
                else
                {
                    $current[$tag] = array (
                        $current[$tag],
                        $result
                    );
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $get_attributes)
                    {
                        if (isset ($current[$tag . '_attr']))
                        {
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset ($current[$tag . '_attr']);
                        }
                        if ($attributes_data)
                        {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                }
            }
        }
        elseif ($type == 'close')
        {
            $current = & $parent[$level -1];
        }
    }
    return ($xml_array);
}
?>

Returns a well formed array like the structure of the xml-document

<root>
 <child1>
  <child1child1/>
 </child1>
</root>

create an array like
array[root][child1][child1child1]

lg
neoyahuu at yahoo dot com 12-Dec-2007 08:18
Instead of passing a URL, we can pass the XML content to this class (either you
 want to use CURL, Socks or fopen to retrieve it first) and instead of using
 array, I'm using separator '|' to identify which data to get (in order to make
 it short to retrieve a complex XML data). Here is my class with built-in fopen
 which you can pass URL or you can pass the content instead :

p/s : thanks to this great help page.

<?php

class xx_xml {

    // XML parser variables
    var $parser;
    var $name;
    var $attr;
    var $data  = array();
    var $stack = array();
    var $keys;
    var $path;

    // either you pass url atau contents.
    // Use 'url' or 'contents' for the parameter
    var $type;

    // function with the default parameter value
    function xx_xml($url='http://www.example.com', $type='url') {
        $this->type = $type;
        $this->url  = $url;
        $this->parse();
    }

    // parse XML data
    function parse()
    {
        $data = '';
        $this->parser = xml_parser_create();
        xml_set_object($this->parser, $this);
        xml_set_element_handler($this->parser, 'startXML', 'endXML');
        xml_set_character_data_handler($this->parser, 'charXML');

        xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);

        if ($this->type == 'url') {
            // if use type = 'url' now we open the XML with fopen

            if (!($fp = @fopen($this->url, 'rb'))) {
                $this->error("Cannot open {$this->url}");
            }

            while (($data = fread($fp, 8192))) {
                if (!xml_parse($this->parser, $data, feof($fp))) {
                    $this->error(sprintf('XML error at line %d column %d',
                    xml_get_current_line_number($this->parser),
                    xml_get_current_column_number($this->parser)));
                }
            }
        } else if ($this->type == 'contents') {
            // Now we can pass the contents, maybe if you want
            // to use CURL, SOCK or other method.
            $lines = explode("\n",$this->url);
            foreach ($lines as $val) {
                if (trim($val) == '')
                    continue;
                $data = $val . "\n";
                if (!xml_parse($this->parser, $data)) {
                    $this->error(sprintf('XML error at line %d column %d',
                    xml_get_current_line_number($this->parser),
                    xml_get_current_column_number($this->parser)));
                }
            }
        }
    }

    function startXML($parser, $name, $attr)    {
        $this->stack[$name] = array();
        $keys = '';
        $total = count($this->stack)-1;
        $i=0;
        foreach ($this->stack as $key => $val)    {
            if (count($this->stack) > 1) {
                if ($total == $i)
                    $keys .= $key;
                else
                    $keys .= $key . '|'; // The saparator
            }
            else
                $keys .= $key;
            $i++;
        }
        if (array_key_exists($keys, $this->data))    {
            $this->data[$keys][] = $attr;
        }    else
            $this->data[$keys] = $attr;
        $this->keys = $keys;
    }

    function endXML($parser, $name)    {
        end($this->stack);
        if (key($this->stack) == $name)
            array_pop($this->stack);
    }

    function charXML($parser, $data)    {
        if (trim($data) != '')
            $this->data[$this->keys]['data'][] = trim(str_replace("\n", '', $data));
    }

    function error($msg)    {
        echo "<div align=\"center\">
            <font color=\"red\"><b>Error: $msg</b></font>
            </div>";
        exit();
    }
}

?>

And example of retrieving XML data:
p/s: example use to retrieve weather

<?php
include_once "xx_xml.class.php";

// Im using simple curl (the original is in class) to get the contents

$pageurl = "http://xml.weather.yahoo.com/forecastrss?p=MYXX0008&u=c";
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL, $pageurl );
$thecontents = curl_exec ( $ch );
curl_close($ch);

// We want to pass only a ready XML content instead of URL
// But if you want to use URL , skip the curl functions above and use this
// $xx4 = new xx_xml("url here",'url');

$xx4 = new xx_xml($thecontents,'contents');
// As you can see, we use saparator '|' instead of long array
$Code = $xx4->data ['rss|channel|item|yweather:condition']['code'] ;
$Celcius = $xx4->data ['rss|channel|item|yweather:condition']['temp'] ;
$Text = $xx4->data ['rss|channel|item|yweather:condition']['text'] ;
$Cityname = $xx4->data ['rss|channel|yweather:location']['city'] ;

?>

Hope this helps.
joris dot landman at chello dot nl 28-Jul-2007 07:42
This page has been a great help! I've adapted the examples below to make a class to parse an X(HT)ML file to a multidimensional array.

Spaces, tabs, breaks, etc. are included in the array as TEXT_NODE, since in XHTML they may be functional. A function to trim them can easily be added if so desired.

I've written my class to store multiple tags with the same name. In order to do this I've used nested arrays with the key NODES to store the order in which tags and data were parsed. These NODES arrays can be used as a blueprint to reconstruct the X(HT)ML part of the document in it's entirity, including formatting. (Doctype will have to be added for validity).

<?php

class my_xml_object {

    var $xml_data; # raw xml data from file
    function parse_xml_file($my_uri) {
        $this->xml_data = null; # clear previously parsed file and related variables
        if (is_file($my_uri) && is_readable($my_uri)) { # existing and readable uri?
            $my_file = fopen($my_uri, "r");
            while($my_xml_input = fread($my_file, filesize($my_uri))) {
                $this->xml_data .= $my_xml_input; # add data to xml_data
            }
            fclose($my_file);
            $this->parse_xml_data($this->xml_data); # parse data
        } else {
            trigger_error("supplied argument is not a URI to a (readable) file", E_USER_ERROR);
        }
    }

    var $xml_array = Array(); # xml array from parsed data
    function parse_xml_data($my_data) { # adapted from class by randlem@gmail.com, tgrabietz@bupnet.de, bbellwfu@gmail.com, Kyle Bresin - see http://nl2.php.net/xml_parse
        $this->xml_array = Array(0 => Array()); # clear previously parsed file and related variables; populate first element
        $my_parser = xml_parser_create(); # set up parser
        xml_set_object($my_parser, $this); # enable parser within object
        xml_set_element_handler($my_parser, "xml_tag_open", "xml_tag_close");
        xml_set_character_data_handler($my_parser, "xml_tag_data");
        if (!xml_parse($my_parser, $my_data)) {
            trigger_error("data can not be parsed", E_USER_ERROR); # inspect problems #die(sprintf("<br />\n<b>Error</b>:  %s on line <b>%d</b><br />\n", xml_error_string(xml_get_error_code($my_parser)), xml_get_current_line_number($my_parser)));
        }
        xml_parser_free($my_parser); # free parser
        return $this->xml_array; # return xml array
    }

    var $my_branch = Array();
    function xml_tag_open($my_parser, $my_name, $my_attributes) {
        array_push($this->my_branch, $my_name); # add tag name to branch
        $this->xml_array[] = Array(); # nest array in xml array for data
        if (count($my_attributes)) {
            $this->xml_array[count($this->xml_array) - 1]["ATTRIBUTES"] = $my_attributes; # nest attributes array
        }
    }

    function xml_tag_data($my_parser, $my_data) {
        $this->xml_array[count($this->my_branch)]["TEXT_NODE"][] = $my_data; # add data to nested array
        $this->xml_array[count($this->my_branch)]["NODES"][] = "TEXT_NODE"; # add text node to nested NODES array
    }

    function xml_tag_close($my_parser, $my_name) {
        $this->xml_array[count($this->my_branch) - 1][$this->my_branch[count($this->my_branch) - 1]][] = $this->xml_array[count($this->xml_array) - 1]; # nest arrays to follow document structure
        array_pop($this->xml_array); # pop off element that was nested
        $this->xml_array[count($this->my_branch) - 1]["NODES"][] = $my_name; # add tag node to nested NODES array
        array_pop($this->my_branch); # update branch
    }

?>
dgrimes at scvl dot com 29-Jun-2007 06:14
One note about magic quotes: magic_quotes_runtime needs to be disabled before parsing XML. It can cause strange errors during parsing. Just add the following at the top of your program:

set_magic_quotes_runtime(0);

If you need magic quotes you can use stripslashes or save the current magic quotes setting with get_magic_quotes_runtime() then disable and parse your XML and then restore the previous magic quotes setting.
php at b635 dot com 23-Jun-2007 10:17
The suggestions below have been a great help, but there was one thing I really needed...

I'm parsing Amazon XML data, and I wanted to be able to index into the array using something like:

<?php
  print "<p>" . $strAXML->arrOutput[ITEMLOOKUPRESPONSE][ITEMS][ITEM][SMALLIMAGE][URL];
?>

To solve this, I had to push all of the open tags onto a separate stack, add any tag data to the tail end of an attributed multi-dimensional array, and then pop the tag name off of the stack once it was closed...

<?php

class xml2array {

  var $arrOutput = array();
  var $arrName = array();
  var $objParser;
  var $strXmlData;

  function parse($strInputXML) {

    // standard XML parse object setup

    $this->objParser = xml_parser_create ();
    xml_set_object($this->objParser,$this);
    xml_set_element_handler($this->objParser, "tagOpen", "tagClosed");

    xml_set_character_data_handler($this->objParser, "tagData");

    $this->strXmlData = xml_parse($this->objParser,$strInputXML );
    if(!$this->strXmlData) {
      die(sprintf("XML error: %s at line %d",
        xml_error_string(xml_get_error_code($this->objParser)),
        xml_get_current_line_number($this->objParser)));
    }

    xml_parser_free($this->objParser);

    return $this->arrOutput;
  }

  function tagOpen($parser, $name, $attrs) {
    // push the current tag name to an array of still-open tag names
    array_push ($this->arrName, $name);

    // merge the array of current attributes to the open tag
    // NOTE: this does not currently handle multiple attributes with the same name
    // (i.e. it will overwrite them with the last values)

    $strEval = "\$this->arrOutput";
    foreach ($this->arrName as $value) {
      $strEval .= "[" . $value . "]";
    }
    $strEval = $strEval . " = array_merge (" . $strEval . ",\$attrs);";

    eval ($strEval);
  }

  function tagData($parser, $tagData) {

    // set the latest open tag equal to the tag data

    $strEval = "\$this->arrOutput";
    foreach ($this->arrName as $value) {
      $strEval .= "[" . $value . "]";
    }

    $strEval = $strEval . " = \$tagData;";

    eval ($strEval);
  }

  function tagClosed($parser, $name) {

    // pop this tag (and any subsequent tags) off the stack of open tag names

    for ($i = count ($this->arrName) - 1; $i > 0; $i--) {
      $currName = $this->arrName[$i];
      array_pop ($this->arrName);
      if ($currName == $name) {
        break;
      }
    }
  }

}

?>
james @at@ mercstudio dot Com dot nospam 02-Apr-2006 12:10
hi,

i've modified bbellwfu at gmail dot com to as below:

features added:
  - toXML (convert back array to xml string)
  - changed name, according to macromedia flash xml concept : children -> childrens, tagdata -> nodevalue, name -> nodename,
  - added pointer firstchild to childrens[0] (if exists)

some findings that i would like to share:
 - <![cdata[my value here]]> (does not work on property value
 - xml file must be htmlentity based (if not using cdata)
 - xml line feed on node data seems to be double line feed on windows (still figuring why)
 - xml line feed on attribute value seems to be ignored...

here's my code below :)

class u007xml
{
   var $arrOutput = array();
   var $resParser;
   var $strXmlData;

    function u007xml($tfile = "")
    {
        if(trim($tfile) != "") { $this->loadFile($tfile);}
    }

    function loadFile($tfile)
    {
        $this->thefile = $tfile;

        $th = file($tfile);
        $tdata = implode("\n", $th);

        return $this->parse($tdata);
    }

   function parse($strInputXML)
   {
        $this->resParser = xml_parser_create ();
        xml_set_object($this->resParser,$this);
        xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");

        xml_set_character_data_handler($this->resParser, "tagData");

        $this->strXmlData = xml_parse($this->resParser,$strInputXML );

        if(!$this->strXmlData) {
           die(sprintf("XML error: %s at line %d",
        xml_error_string(xml_get_error_code($this->resParser)),
        xml_get_current_line_number($this->resParser)));
        }

        xml_parser_free($this->resParser);

        return $this->arrOutput;
   }

   //called on each xml tree
   function tagOpen($parser, $name, $attrs) {
       $tag=array("nodename"=>$name,"attributes"=>$attrs);
       array_push($this->arrOutput,$tag);
   }

  //called on data for xml
   function tagData($parser, $tagData) {
       if(trim($tagData)) {
           if(isset($this->arrOutput[count($this->arrOutput)-1]['nodevalue'])) {
               $this->arrOutput[count($this->arrOutput)-1]['nodevalue'] .= $this->parseXMLValue($tagData);
           }
           else {
               $this->arrOutput[count($this->arrOutput)-1]['nodevalue'] = $this->parseXMLValue($tagData);
           }
       }
   }

  //called when finished parsing
   function tagClosed($parser, $name) {
       $this->arrOutput[count($this->arrOutput)-2]['childrens'][] = $this->arrOutput[count($this->arrOutput)-1];

       if(count ($this->arrOutput[count($this->arrOutput)-2]['childrens'] ) == 1)
       {
            $this->arrOutput[count($this->arrOutput)-2]['firstchild'] =& $this->arrOutput[count($this->arrOutput)-2]['childrens'][0];
       }
       array_pop($this->arrOutput);
   }

    function toArray()
    {
        //not used, we can call loadString or loadFile instead...
    }

    function parseXMLValue($tvalue)
    {
        $tvalue = htmlentities($tvalue);
        return $tvalue;
    }

    function toXML($tob = null)
    {
        //return back xml
        $result = "";

        if( $tob == null)
        {
            $tob = $this->arrOutput;
        }

        if(!isset($tob))
        {
            echo "XML Array empty...";
            return null;
        }

        for($c = 0; $c < count($tob); $c++)
        {
            $result .="<" . $tob[$c]["nodename"];

            while (list($key, $value) = each($tob[$c]["attributes"]))
            {
                $result .=" " . $key."=\"" . $this->parseXMLValue($value) . "\"";
            }

            $result .= ">";

            //assign node value
            if( isset($tob[$c]["nodevalue"]) )
            {
                $result .= $tob[$c]["nodevalue"];
            }

            if( count($tob[$c]["childrens"]) > 0 )
            {
                $result .= "\r\n" . $this->toXML(&$tob[$c]["childrens"]) . "";
            }

            $result .= "</" . $tob[$c]["nodename"] . ">\r\n";

        }//end of each array...

        return $result;
    }

    function displayXML()
    {
        print_r($this->arrOutput);
    }

    function getXML($tob = null)
    {
        return "<?xml version='1.0'?>\r\n" . $this->toXML($tob);
    }

}//end of u007xml class

//examples below:

$xx = new u007xml();
$xx->loadFile("xml3.xml");

//$xx->displayXML();

print $xx->getXML();
ben at autonomic dot net 16-Mar-2006 05:12
bbellwfu's code does not handle 'text nodes' properly.
Consider the innards of a tag like <root>xxx<tag2/>yyy</root>
The 'tagData' for root will be "xxxyyy" and you have lost all information about where "tag2" was in that sequence.

Quick and dirty hack.

Replace tagData with this code :
   function tagData($parser, $tagData) {
          $last_element=count($this->arrOutput)-1;
        $this->arrOutput[$last_element]['children'][] = array("textnode",$tagData);
   }

What this does is adds 'textnodes' as children of its containing parent, *in the right sequence* (rather like the internet browsers do it). This then lets you do some more sensible secondary work like recursively looking up internal references within the document...
Kyle Bresin 19-Jan-2006 03:15
Just wanted to note a small bug in bbellwfu's class (which is really great btw).

It fails to capture any datums which are equal to numerical zero.

The problem lies in the function tagData, the first if statement should be:

if(trim($tagData) != '') {
tim at alloutinteraction dot com 01-Oct-2005 07:29
I wanted to create a really simple XML parser, but I found the array management in xml_parse a bit daunting. So I flattened my XML and parsed it using string matching. It wouldn't be difficult to add xml depth (of 2 plus levels) by modifying the parsedXML array.

<?
// here's the raw html
$xmlRaw="<order>Order data</order><label>Label data</label><control>123</control>";
// here are the xml field names
$xmlFieldNames=array("order", "label", "control");
// for each xml field...
foreach ($xmlFieldNames as $xmlField) {
    if(strpos($xmlRaw,$xmlField)!==false){
        // I've broken 1 single line into 4 for display purposes
        $parsedXML[$xmlField]=substr($xmlRaw,
        strpos($xmlRaw,"<$xmlField>")+strlen("<$xmlField>"),
        strpos($xmlRaw,"</$xmlField>")-strlen("<$xmlField>")
        -strpos($xmlRaw,"<$xmlField>"));
    }
}
print_r($parsedXML);
// prints: Array ( [order] => Order data [label] => Label data [control] => 123 )

?>

Hope you find this useful (coded it while ill in bed with streaming cold, but felt much better afterwards!)

Tim (a lazy coder)
bbellwfu at gmail dot com 05-May-2005 02:51
Just improving a little bit on the code examples from tgrabietz and randlem below... everything in one pretty class, plus some checks in place so that the element data doesnt get split up (thanks to flobee on the xml_set_character_data_handler page)

<?php

/* Usage
 Grab some XML data, either from a file, URL, etc. however you want. Assume storage in $strYourXML;

 $objXML = new xml2Array();
 $arrOutput = $objXML->parse($strYourXML);
 print_r($arrOutput); //print it out, or do whatever!

*/
class xml2Array {

    var $arrOutput = array();
    var $resParser;
    var $strXmlData;

    function parse($strInputXML) {

            $this->resParser = xml_parser_create ();
            xml_set_object($this->resParser,$this);
            xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");

            xml_set_character_data_handler($this->resParser, "tagData");

            $this->strXmlData = xml_parse($this->resParser,$strInputXML );
            if(!$this->strXmlData) {
               die(sprintf("XML error: %s at line %d",
            xml_error_string(xml_get_error_code($this->resParser)),
            xml_get_current_line_number($this->resParser)));
            }

            xml_parser_free($this->resParser);

            return $this->arrOutput;
    }
    function tagOpen($parser, $name, $attrs) {
       $tag=array("name"=>$name,"attrs"=>$attrs);
       array_push($this->arrOutput,$tag);
    }

    function tagData($parser, $tagData) {
       if(trim($tagData)) {
            if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
                $this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
            }
            else {
                $this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
            }
       }
    }

    function tagClosed($parser, $name) {
       $this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this->arrOutput)-1];
       array_pop($this->arrOutput);
    }
}
?>

Will output something like...

<snippet>
Array
(
    [0] => Array
        (
            [name] => GETMESSAGESRESPONSE
            [attrs] => Array
                (
                )

            [children] => Array
                (
                    [0] => Array
                        (
                            [name] => STATUS
                            [attrs] => Array
                                (
                                )

                        )

</snippet>
alex dot garcia at noos dot fr 14-Mar-2005 01:47
Here is the inverse function which takes parsed xml array in entry and outputs xml string

enjoy !

function getXmlFromArray($root){

        if(count($root) > 0){

            $curr_name = $root['name'];
            $attribs = $root['attrs'];
            $curr_childs = $root['children'];
            $curr_data = $root['cdata'];

            $xml .= '<'.$curr_name;

            if(count($attribs) > 0){
                $i = 1;
                foreach($attribs as $key => $value){
                    $curr_attribs .= $key.'="'.$value.'"';
                    $i++;
                    if($i <= count($attribs)){
                        $curr_attribs .= ' ';
                    }
                }
                $xml .= ' '.$curr_attribs;
            }

            if($curr_data != ''){
                $xml .= '><![CDATA['.$curr_data.']]></'.$curr_name.'>';
            } else {
                if(count($curr_childs) > 0){
                    $xml .= '>';
                    foreach($curr_childs as $child){
                        $xml .= getXmlFromArray($child);
                    }
                    $xml .= '</'.$curr_name.'>';
                } else {
                    $xml .= '/>';
                }
            }

        }
        return $xml;
    }
tgrabietz at bupnet dot de 22-Sep-2004 08:05
it's like randlem at gmail dot com's great code, without using a "class container" but parsing cdata. The script returns the tree-structure in a single array.

<?php
$file = 'simple.xml';
$stack = array();

function startTag($parser, $name, $attrs)
{
   global $stack;
   $tag=array("name"=>$name,"attrs"=>$attrs);
   array_push($stack,$tag);

}

function cdata($parser, $cdata)
{
    global $stack,$i;

    if(trim($cdata))
    {
        $stack[count($stack)-1]['cdata']=$cdata;
    }
}

function endTag($parser, $name)
{
   global $stack;
   $stack[count($stack)-2]['children'][] = $stack[count($stack)-1];
   array_pop($stack);
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");
xml_set_character_data_handler($xml_parser, "cdata");

$data = xml_parse($xml_parser,file_get_contents($file));
if(!$data) {
   die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}

xml_parser_free($xml_parser);

print("<pre>\n");
print_r($stack);
print("</pre>\n");
?>
ByK 16-Sep-2004 08:12
modified from yours code. I think it's work!!.
class CXml
{
    var $xml_data;
    var $obj_data;
    var $pointer;

    function CXml() { }

    function Set_xml_data( &$xml_data )
    {
        $this->index = 0;
        $this->pointer[] = &$this->obj_data;

        //strip white space between tags
        $this->xml_data = eregi_replace(">"."[[:space:]]+"."<","><",$xml_data);
        $this->xml_parser = xml_parser_create( "UTF-8" );

        xml_parser_set_option( $this->xml_parser, XML_OPTION_CASE_FOLDING, false );
        xml_set_object( $this->xml_parser, &$this );
        xml_set_element_handler( $this->xml_parser, "_startElement", "_endElement");
        xml_set_character_data_handler( $this->xml_parser, "_cData" );

        xml_parse( $this->xml_parser, $this->xml_data, true );
        xml_parser_free( $this->xml_parser );
    }

    function _startElement( $parser, $tag, $attributeList )
    {
        foreach( $attributeList as $name => $value )
        {
            $value = $this->_cleanString( $value );
            $object->$name = $value;
        }
        //replaces the special characters with the underscore (_) in tag name
        $tag = preg_replace("/[:\-\. ]/", "_", $tag);
        eval( "\$this->pointer[\$this->index]->" . $tag . "[] = \$object;" );
        eval( "\$size = sizeof( \$this->pointer[\$this->index]->" . $tag . " );" );
        eval( "\$this->pointer[] = &\$this->pointer[\$this->index]->" . $tag . "[\$size-1];" );

        $this->index++;
    }

    function _endElement( $parser, $tag )
    {
        array_pop( $this->pointer );
        $this->index--;
    }

    function _cData( $parser, $data )
    {
        if (empty($this->pointer[$this->index])) {
            if (rtrim($data, "\n"))
                $this->pointer[$this->index] = $data;
        } else {
            $this->pointer[$this->index] .= $data;
        }
    }

    function _cleanString( $string )
    {
        return utf8_decode( trim( $string ) );
    }
}

$m_xml = new CXml();
$xml_data = file_get_contents( $filename );

$m_xml->Set_XML_data( $xml_data );

$newsid = $m_xml->obj_data->root[0]->NewsID[0];
randlem at gmail dot com 15-Sep-2004 08:43
Here's a handy way to generate a tree that can be can be decended easily.

<?php
$file = 'xmltest.xml';

$tag_tree = array();
$stack = array();

class tag {
    var $name;
    var $attrs;
    var $children;
    function tag($name, $attrs, $children) {
        $this->name = $name;
        $this->attrs = $attrs;
        $this->children = $children;
    }
}

function startTag($parser, $name, $attrs) {
    global $tag_tree, $stack;
    $tag = new tag($name,$attrs,'');
    array_push($stack,$tag);
}

function endTag($parser, $name) {
    global $stack;
    $stack[count($stack)-2]->children[] = $stack[count($stack)-1];
    array_pop($stack);
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startTag", "endTag");

$data = xml_parse($xml_parser,file_get_contents($file));
if(!$data) {
    die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}

xml_parser_free($xml_parser);

print("\n");
print_r($stack);
print("\n");
?>
michelek 26-Oct-2003 10:42
its maybe not better, but me thinks its more stright-forward

--INPUT:

<?xml version="1.0" encoding="UTF-8"?>
<world>
    <country name="sweden">
        <city name="stockholm">
            <user>Adam</user>
            <user>Eva</user>
        </city>
        <city name="g?teborg">
            <user>God</user>
        </city>
    </country>
    <country name="usa">
        <city name="new york">
            <user>Clinton</user>
            <user>Bush</user>
        </city>
    </country>
</world>

--CODE:
<?
/**
 * m_i_h_k_e_l_AT_w_w_DOT_e_e
 * 26.10.2003
**/
$filename = "m.m.xml";
$xmlC = new XmlC();
$xml_data = file_get_contents( $filename );

$xmlC->Set_XML_data( $xml_data );

echo( "<pre>\n" );
print_r( $xmlC->obj_data );
echo( "</pre>\n" );

class XmlC
{
  var $xml_data;
  var $obj_data;
  var $pointer;

  function XmlC()
  {
  }

  function Set_xml_data( &$xml_data )
  {
    $this->index = 0;
    $this->pointer[] = &$this->obj_data;

    $this->xml_data = $xml_data;
    $this->xml_parser = xml_parser_create( "UTF-8" );

    xml_parser_set_option( $this->xml_parser, XML_OPTION_CASE_FOLDING, false );
    xml_set_object( $this->xml_parser, &$this );
    xml_set_element_handler( $this->xml_parser, "_startElement", "_endElement");
    xml_set_character_data_handler( $this->xml_parser, "_cData" );

    xml_parse( $this->xml_parser, $this->xml_data, true );
    xml_parser_free( $this->xml_parser );
  }

  function _startElement( $parser, $tag, $attributeList )
  {
    foreach( $attributeList as $name => $value )
    {
      $value = $this->_cleanString( $value );
      $object->$name = $value;
    }
    eval( "\$this->pointer[\$this->index]->" . $tag . "[] = \$object;" );
    eval( "\$size = sizeof( \$this->pointer[\$this->index]->" . $tag . " );" );
    eval( "\$this->pointer[] = &\$this->pointer[\$this->index]->" . $tag . "[\$size-1];" );

    $this->index++;
  }

  function _endElement( $parser, $tag )
  {
    array_pop( $this->pointer );
    $this->index--;
  }

  function _cData( $parser, $data )
  {
    if( trim( $data ) )
    {
      $this->pointer[$this->index] = trim( $data );
    }
  }

  function _cleanString( $string )
  {
    return utf8_decode( trim( $string ) );
  }

}
?>
Adam Tylmad 11-Sep-2003 01:11
I've created a parser that returns an
object based on a xml document.

example:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<country name="sweden">
    <city name="stockholm">
        <user>Adam</user>
        <user>Eve</user>
    </city>
    <city name="g?teborg">
        <user>God</user>
    </city>
</country>
<country name="usa">
    <city name="new york">
        <user>Clinton</user>
        <user>Bush</user>
    </city>
</country>

generates the following object structure:
[country] => Array
(
    [0] => stdClass Object
        (
            [name] => sweden
            [city] => Array
                (
                    [0] => stdClass Object
                        (
                            [name] => stockholm
                            [user] => Array
                                (
                                    [0] => Adam
                                    [1] => Eve
                                )
                        )
                    [1] => stdClass Object
                        (
                            [name] => g?teborg
                            [user] => God
                        )
                )
        )
    [1] => stdClass Object
        (
            [name] => usa
            [city] => stdClass
                (
                    [name] => new york
                    [user] => Array
                        (
                            [0] => Clinton
                            [1] => Bush
                        )
                )
        )
)

Here is the code:

class XMLParser {
    var $path;
    var $result;

    function XMLParser($encoding, $data) {
        $this->path = "\$this->result";
        $this->index = 0;

        $xml_parser = xml_parser_create($encoding);
        xml_set_object($xml_parser, &$this);
        xml_set_element_handler($xml_parser, 'startElement', 'endElement');
        xml_set_character_data_handler($xml_parser, 'characterData');

        xml_parse($xml_parser, $data, true);
        xml_parser_free($xml_parser);
    }

        function startElement($parser, $tag, $attributeList) {
            eval("\$vars = get_object_vars(".$this->path.");");
            $this->path .= "->".$tag;
            if ($vars and array_key_exists($tag, $vars)) {
                 eval("\$data = ".$this->path.";");
                     if (is_array($data)) {
                           $index = sizeof($data);
                           $this->path .= "[".$index."]";
                     } else if (is_object($data)) {
                           eval($this->path." = array(".$this->path.");");
                           $this->path .= "[1]";
                     }
            }
            eval($this->path." = null;");

            foreach($attributeList as $name => $value)
                eval($this->path."->".$name. " = '".XMLParser::cleanString($value)."';");
        }

    function endElement($parser, $tag) {
        $this->path = substr($this->path, 0, strrpos($this->path, "->"));
    }

    function characterData($parser, $data) {
        eval($this->path." = '".trim($data)."';");
    }
}

enjoy! And please make it better if you can ;-)


Cria um analisador XML com suporte a espaço de nomes

  • « xml_parse
  • xml_parser_create »
  • PHP Manual
  • Funções para analisar XML
  • Cria um analisador XML com suporte a espaço de nomes

xml_parser_create_ns

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

xml_parser_create_ns — Cria um analisador XML com suporte a espaço de nomes

Descrição

xml_parser_create_ns(?string $encoding = null, string $separator = ":"): XMLParser

xml_parser_create_ns() cria um novo analisador XML com suporte a espaço de nomes do XML e retorna uma instância de XMLParser para ser usada pelas outras funções XML.

Parâmetros

encoding

A codificação de entrada é automaticamente detectada, de forma que o parâmetro encoding especifica somente a codificação de saída. O conjunto de caracteres de saída padrão é o UTF-8. As codificações suportadas são ISO-8859-1, UTF-8 e US-ASCII.

separator

Com um analisador ciente do espaço de nomes, os parâmetros de etiquetas passados às várias funções de manupulação consistirão do nome do espaço e do nome da etiqueta separados pela string especificada em separator.

Valor Retornado

Retorna uma nova instância de XMLParser.

Changelog

Versão | Descrição
8.0.0 | Esta função retorna uma instância de XMLParser agora; anteriormente, um recurso do tipo resource era retornado, ou false em caso de falha.
8.0.0 | encoding agora pode ser nulo.

Veja Também

  • xml_parser_create() - Cria um analisador XML
  • xml_parser_free() - Libera um analisador 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.


Cria um analisador XML

  • « xml_parser_create_ns
  • xml_parser_free »
  • PHP Manual
  • Funções para analisar XML
  • Cria um analisador XML

xml_parser_create

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

xml_parser_create — Cria um analisador XML

Descrição

xml_parser_create(?string $encoding = null): XMLParser

xml_parser_create() cria um novo analisador XML e retorna uma instância de XMLParser para ser usada pelas outras funções XML.

Parâmetros

encoding

A codificação de entrada é detectada automaticamente, de forma que o parâmetro encoding especifica apenas a codificação de saída. Se uma string vazia for passada, o analisador tenta identificar qual a codificação do documento verificando 3 ou 4 bytes do cabeçalho. O conjunto de caracteres de saída padrão é o UTF-8. As codificações suportadas são ISO-8859-1, UTF-8 e US-ASCII.

Valor Retornado

Retorna uma nova instância de XMLParser.

Changelog

Versão | Descrição
8.0.0 | Esta função retorna uma instância de XMLParser agora; anteriormente, um recurso do tipo resource era retornado, ou false em caso de falha.
8.0.0 | encoding agora pode ser nulo.

Veja Também

  • xml_parser_create_ns() - Cria um analisador XML com suporte a espaço de nomes
  • xml_parser_free() - Libera um analisador 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.


Libera um analisador XML

  • « xml_parser_create
  • xml_parser_get_option »
  • PHP Manual
  • Funções para analisar XML
  • Libera um analisador XML

xml_parser_free

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

xml_parser_free — Libera um analisador XML

Descrição

xml_parser_free(XMLParser $parser): bool

Nota:

Esta função não tem efeito. Antes do PHP 8.0.0, esta função era usada para fechar o recurso.

Libera o analisador XML informado em parser.

Cuidado

Além de chamar xml_parser_free() quando a análise está terminada, antes do PHP 8.0.0, era necessário também explicitamente remover a definição da referência ao analisador informado em parser para evitar vazamentos de memória, se o recurso do analisador fosse referenciado de um objeto, e este objeto referenciasse o recurso do analisador.

Parâmetros

parser
Uma referência para o analisador XML a ser liberado.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

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!


Obtém as opções de um analisador XML

  • « xml_parser_free
  • xml_parser_set_option »
  • PHP Manual
  • Funções para analisar XML
  • Obtém as opções de um analisador XML

xml_parser_get_option

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

xml_parser_get_option — Obtém as opções de um analisador XML

Descrição

xml_parser_get_option(XMLParser $parser, int $option): string|int|bool

Obtém um valor de opção de um analisador XML.

Parâmetros

parser
Uma referência para o analisador XML do qual a opção será obtida.
option
Qual opção buscar. XML_OPTION_CASE_FOLDING, XML_OPTION_SKIP_TAGSTART, XML_OPTION_SKIP_WHITE e XML_OPTION_TARGET_ENCODING estão disponíveis. Consulte xml_parser_set_option() para suas descrições.

Valor Retornado

Retorna o valor da opção.

Erros

Lança uma exceção ValueError quando um valor inválido é passado em option.

Antes do PHP 8.0.0, passar um valor inválido em option gerava um erro de nível E_WARNING e também fazia a função retornar false.

Changelog

Versão | Descrição
8.3.0 | A função agora retorna um booleano para opções booleanas.
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.
8.0.0 | Uma exceção ValueError agora é lançada se option for inválido.
7.1.24, 7.2.12, 7.3.0 | options agora suporta XML_OPTION_SKIP_TAGSTART e XML_OPTION_SKIP_WHITE.

User Contributed Notes

dnricky at hotmail dot com 24-Jun-2017 04:57
<?php
$xmlparser = xml_parser_create();

echo "XML_OPTION_CASE_FOLDING:" . xml_parser_get_option($xmlparser, XML_OPTION_CASE_FOLDING) . "<br />"; //Specifies if case-folding is enabled. Enabled by default. Can be 1 (TRUE) or 0 (FALSE)

echo "XML_OPTION_TARGET_ENCODING:" . xml_parser_get_option($xmlparser, XML_OPTION_TARGET_ENCODING ) . "<br />"; //Specifies which target encoding to use in this XML parser. By default, it is set to the same as the xml_parser_create() function. Supported target encodings are ISO-8859-1, US-ASCII and UTF-8.

xml_parser_free($xmlparser);
?>


Define opções em um analisador XML

  • « xml_parser_get_option
  • xml_set_character_data_handler »
  • PHP Manual
  • Funções para analisar XML
  • Define opções em um analisador XML

xml_parser_set_option

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

xml_parser_set_option — Define opções em um analisador XML

Descrição

xml_parser_set_option(XMLParser $parser, int $option, string|int|bool $value): bool

Define uma opção em uma analisador XML.

Parâmetros

parser

Uma referência ao analisador XML ao qual se deseja definir uma opção.

option

Qual a opção a definir. Veja abaixo.

As opções a seguir estão disponíveis:

Opções do analisador XML
Constante da opção | Tipo de dados | Descrição
XML_OPTION_CASE_FOLDING | bool | Controla se case-folding está habilitado para este analisador XML. Ativado por padrão.
XML_OPTION_SKIP_TAGSTART | integer | Especifica quantos caracteres devem ser ignorados no início do nome de uma etiqueta.
XML_OPTION_SKIP_WHITE | bool | Controla se deve-se ignorar valores constituídos por espaços em branco.
XML_OPTION_TARGET_ENCODING | string | Define qual codificação de destino será usada neste analisador XML. Por pradrão, é definida com a mesma codificação usada por xml_parser_create(). Codificações de destino suportadas são ISO-8859-1, US-ASCII e UTF-8.

value

O novo valor da opção.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros

Lança uma exceção ValueError quando um valor inválido é passado em option.

Antes do PHP 8.0.0, passar um valor inválido em option gerava um erro de nível E_WARNING e também fazia a função retornar false.

Changelog

Versão | Descrição
8.3.0 | O parâmetro value agora aceita booleanos. As opções XML_OPTION_CASE_FOLDING e XML_OPTION_SKIP_WHITE são agora opções booleanas.
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.
8.0.0 | Uma exceção ValueError agora é lançada se option for inválido.

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.


Set up character data handler

  • « xml_parser_set_option
  • xml_set_default_handler »
  • PHP Manual
  • Funções para analisar XML
  • Set up character data handler

xml_set_character_data_handler

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

xml_set_character_data_handler — Set up character data handler

Descrição

xml_set_character_data_handler(XMLParser $parser, callable $handler): true

Sets the character data handler function for the XML parser parser.

Parâmetros

parser

O analisador XML.

handler

Se null ou uma string vazia for passada, o manipulador será redefinido para seu estado padrão.

Se handler for um callable, o callable será definido como o manipulador.

Se handler for uma string, ela pode ser o nome de um método de um objet definido com xml_set_object().

The signature of the handler must be:

handler(XMLParser $parser, string $data): void
parser
O analisador XML que chama o manipulador.
data
Character data as a string.

Character data handler is called for every piece of a text in the XML document. It can be called multiple times inside each fragment (e.g. for non-ASCII strings).

Valor Retornado

Sempre retorna true.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

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.


Set up default handler

  • « xml_set_character_data_handler
  • xml_set_element_handler »
  • PHP Manual
  • Funções para analisar XML
  • Set up default handler

xml_set_default_handler

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

xml_set_default_handler — Set up default handler

Descrição

xml_set_default_handler(XMLParser $parser, callable $handler): true

Sets the default handler function for the XML parser parser.

Parâmetros

parser

O analisador XML.

handler

Se null ou uma string vazia for passada, o manipulador será redefinido para seu estado padrão.

Se handler for um callable, o callable será definido como o manipulador.

Se handler for uma string, ela pode ser o nome de um método de um objet definido com xml_set_object().

The signature of the handler must be:

handler(XMLParser $parser, string $data): void
parser
O analisador XML que chama o manipulador.
data
data contains the character data. This may be the XML declaration, document type declaration, entities or other data for which no other handler exists.

Valor Retornado

Sempre retorna true.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

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.


Set up start and end element handlers

  • « xml_set_default_handler
  • xml_set_end_namespace_decl_handler »
  • PHP Manual
  • Funções para analisar XML
  • Set up start and end element handlers

xml_set_element_handler

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

xml_set_element_handler — Set up start and end element handlers

Descrição

xml_set_element_handler(XMLParser $parser, callable $start_handler, callable $end_handler): true

Sets the element handler functions for the XML parser.

start_handler is called when a new XML element is opened. end_handler is called when an XML element is closed.

Parâmetros

parser

O analisador XML.

start_handler

Se null ou uma string vazia for passada, o manipulador será redefinido para seu estado padrão.

Se handler for um callable, o callable será definido como o manipulador.

Se handler for uma string, ela pode ser o nome de um método de um objet definido com xml_set_object().

The signature of the handler must be:

start_element_handler(XMLParser $parser, string $name, array $attributes): void
parser
O analisador XML que chama o manipulador.
name
Contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.
attributes
An associative array with the element's attributes. The array is empty if the element has no attributes. The keys of this array are the attribute names, the values are the attribute values. Attribute names are case-folded on the same criteria as element names. Attribute values are not case-folded. The order in which attributes is traversed is identical to the order in which the attributes were declared.

end_handler

Se null ou uma string vazia for passada, o manipulador será redefinido para seu estado padrão.

Se handler for um callable, o callable será definido como o manipulador.

Se handler for uma string, ela pode ser o nome de um método de um objet definido com xml_set_object().

The signature of the handler must be:

end_element_handler(XMLParser $parser, string $name): void
parser
O analisador XML que chama o manipulador.
name
Contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.

Valor Retornado

Sempre retorna true.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

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.


Set up end namespace declaration handler

  • « xml_set_element_handler
  • xml_set_external_entity_ref_handler »
  • PHP Manual
  • Funções para analisar XML
  • Set up end namespace declaration handler

xml_set_end_namespace_decl_handler

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

xml_set_end_namespace_decl_handler — Set up end namespace declaration handler

Descrição

xml_set_end_namespace_decl_handler(XMLParser $parser, callable $handler): true

Set a handler to be called when leaving the scope of a namespace declaration. This will be called, for each namespace declaration, after the handler for the end tag of the element in which the namespace was declared.

Cuidado

This event is not supported under libXML, so a registered handler wouldn't be called.

Parâmetros

parser

O analisador XML.

handler

Se null ou uma string vazia for passada, o manipulador será redefinido para seu estado padrão.

Se handler for um callable, o callable será definido como o manipulador.

Se handler for uma string, ela pode ser o nome de um método de um objet definido com xml_set_object().

The signature of the handler must be:

handler(XMLParser $parser, string|false $prefix)
parser
O analisador XML que chama o manipulador.
prefix
The prefix is a string used to reference the namespace within an XML object. false if no prefix exists.

Valor Retornado

Sempre retorna true.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

Veja Também

  • xml_set_start_namespace_decl_handler() - Set up start namespace declaration handler

User Contributed Notes

There are no user contributed notes for this page.


Set up external entity reference handler

  • « xml_set_end_namespace_decl_handler
  • xml_set_notation_decl_handler »
  • PHP Manual
  • Funções para analisar XML
  • Set up external entity reference handler

xml_set_external_entity_ref_handler

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

xml_set_external_entity_ref_handler — Set up external entity reference handler

Descrição

xml_set_external_entity_ref_handler(XMLParser $parser, callable $handler): true

Sets the external entity reference handler function for the XML parser parser.

Parâmetros

parser

O analisador XML.

handler

Se null ou uma string vazia for passada, o manipulador será redefinido para seu estado padrão.

Se handler for um callable, o callable será definido como o manipulador.

Se handler for uma string, ela pode ser o nome de um método de um objet definido com xml_set_object().

The signature of the handler must be:

handler(
XMLParser $parser,
string $open_entity_names,
string|false $base,
string $system_id,
string|false $public_id
): bool
parser
O analisador XML que chama o manipulador.
open_entity_names
A space-separated list of the names of the entities that are open for the parse of this entity (including the name of the referenced entity).
base
This is the base for resolving the system identifier (system_id) of the external entity.
system_id
The system identifier as specified in the entity declaration.
public_id
The public identifier as specified in the entity declaration, or an empty string if none was specified; the whitespace in the public identifier will have been normalized as required by the XML spec.

The handler should return true if the entity was handled, false otherwise. When returning false the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING.

Valor Retornado

Sempre retorna true.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.
7.3.0 | The return value of the handler is no longer ignored if the extension has been built against libxml. Formerly, the return value has been ignored, and parsing did never stop.

User Contributed Notes

There are no user contributed notes for this page.


Set up notation declaration handler

  • « xml_set_external_entity_ref_handler
  • xml_set_object »
  • PHP Manual
  • Funções para analisar XML
  • Set up notation declaration handler

xml_set_notation_decl_handler

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

xml_set_notation_decl_handler — Set up notation declaration handler

Descrição

xml_set_notation_decl_handler(XMLParser $parser, callable $handler): true

Sets the notation declaration handler function for the XML parser parser.

A notation declaration is part of the document's DTD and has the following format:

<!NOTATION <parameter>name</parameter>
{ <parameter>systemId</parameter> | <parameter>publicId</parameter>?>
See » section 4.7 of the XML 1.0 spec for the definition of notation declarations.

Parâmetros

parser

O analisador XML.

handler

Se null ou uma string vazia for passada, o manipulador será redefinido para seu estado padrão.

Se handler for um callable, o callable será definido como o manipulador.

Se handler for uma string, ela pode ser o nome de um método de um objet definido com xml_set_object().

The signature of the handler must be:

handler(
XMLParser $parser,
string $notation_name,
string|false $base,
string $system_id,
string|false $public_id
): void
parser
O analisador XML que chama o manipulador.
notation_name
This is the notation's name, as per the notation format described above.
base
This is the base for resolving the system identifier (system_id) of the notation declaration.
system_id
System identifier of the external notation declaration.
public_id
Public identifier of the external notation declaration.

Valor Retornado

Sempre retorna true.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

User Contributed Notes

There are no user contributed notes for this page.


Use XML Parser within an object

  • « xml_set_notation_decl_handler
  • xml_set_processing_instruction_handler »
  • PHP Manual
  • Funções para analisar XML
  • Use XML Parser within an object

xml_set_object

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

xml_set_object — Use XML Parser within an object

Descrição

xml_set_object(XMLParser $parser, object $object): true

This function allows to use parser inside object. All callback functions could be set with xml_set_element_handler() etc and assumed to be methods of object.

Parâmetros

parser

A reference to the XML parser to use inside the object.

object

The object where to use the XML parser.

Valor Retornado

Sempre retorna true.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

Exemplos

Exemplo #1 xml_set_object() example

<?php
class CustomXMLParser
{
private $parser;

function __construct()
{
$this->parser = xml_parser_create();

xml_set_object($this->parser, $this);
xml_set_element_handler($this->parser, "tag_open", "tag_close");
xml_set_character_data_handler($this->parser, "cdata");
}

function parse($data)
{
xml_parse($this->parser, $data);
}

function tag_open($parser, $tag, $attributes)
{
var_dump($tag, $attributes);
}

function cdata($parser, $cdata)
{
var_dump($cdata);
}

function tag_close($parser, $tag)
{
var_dump($tag);
}
}

$xml_parser = new CustomXMLParser();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
?>

O exemplo acima produzirá:

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.


Set up processing instruction (PI) handler

  • « xml_set_object
  • xml_set_start_namespace_decl_handler »
  • PHP Manual
  • Funções para analisar XML
  • Set up processing instruction (PI) handler

xml_set_processing_instruction_handler

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

xml_set_processing_instruction_handler — Set up processing instruction (PI) handler

Descrição

xml_set_processing_instruction_handler(XMLParser $parser, callable $handler): true

Sets the processing instruction (PI) handler function for the XML parser parser.

A processing instruction has the following format:

<?target
data
?>

Cuidado

PHP code is delimited by the <?php processing instruction. As such it is possible to have PHP code within an XML document. However, the PI end tag (?>) must not be part of the data. If a PI end tag exists as part of the embedded PHP code, the rest of the PHP code and the "real" PI end tag, will be treated as character data.

Parâmetros

parser

O analisador XML.

handler

Se null ou uma string vazia for passada, o manipulador será redefinido para seu estado padrão.

Se handler for um callable, o callable será definido como o manipulador.

Se handler for uma string, ela pode ser o nome de um método de um objet definido com xml_set_object().

The signature of the handler must be:

handler(XMLParser $parser, string $target, string $data): void
parser
O analisador XML que chama o manipulador.
target
The processing instruction target.
data
The processing instruction data.

Valor Retornado

Sempre retorna true.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

User Contributed Notes

There are no user contributed notes for this page.


Set up start namespace declaration handler

  • « xml_set_processing_instruction_handler
  • xml_set_unparsed_entity_decl_handler »
  • PHP Manual
  • Funções para analisar XML
  • Set up start namespace declaration handler

xml_set_start_namespace_decl_handler

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

xml_set_start_namespace_decl_handler — Set up start namespace declaration handler

Descrição

xml_set_start_namespace_decl_handler(XMLParser $parser, callable $handler): true

Set a handler to be called when a namespace is declared. Namespace declarations occur inside start tags. But the namespace declaration start handler is called before the start tag handler for each namespace declared in that start tag.

Parâmetros

parser

O analisador XML.

handler

Se null ou uma string vazia for passada, o manipulador será redefinido para seu estado padrão.

Se handler for um callable, o callable será definido como o manipulador.

Se handler for uma string, ela pode ser o nome de um método de um objet definido com xml_set_object().

The signature of the handler must be:

handler(XMLParser $parser, string|false $prefix, string $uri): void
parser
O analisador XML que chama o manipulador.
prefix
The prefix is a string used to reference the namespace within an XML object. false if no prefix exists.
uri
Uniform Resource Identifier (URI) of namespace.

Valor Retornado

Sempre retorna true.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

Veja Também

  • xml_set_end_namespace_decl_handler() - Set up end namespace declaration handler

User Contributed Notes

There are no user contributed notes for this page.


Set up unparsed entity declaration handler

  • « xml_set_start_namespace_decl_handler
  • XMLParser »
  • PHP Manual
  • Funções para analisar XML
  • Set up unparsed entity declaration handler

xml_set_unparsed_entity_decl_handler

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

xml_set_unparsed_entity_decl_handler — Set up unparsed entity declaration handler

Descrição

xml_set_unparsed_entity_decl_handler(XMLParser $parser, callable $handler): true

Sets the unparsed entity declaration handler function for the XML parser parser.

The handler will be called if the XML parser encounters an external entity declaration with an NDATA declaration, like the following:

<!ENTITY <parameter>name</parameter> {<parameter>publicId</parameter> | <parameter>systemId</parameter>}
        NDATA <parameter>notationName</parameter>

See » section 4.2.2 of the XML 1.0 spec for the definition of notation declared external entities.

Parâmetros

parser

O analisador XML.

handler

Se null ou uma string vazia for passada, o manipulador será redefinido para seu estado padrão.

Se handler for um callable, o callable será definido como o manipulador.

Se handler for uma string, ela pode ser o nome de um método de um objet definido com xml_set_object().

The signature of the handler must be:

handler(
XMLParser $parser,
string $entity_name,
string|false $base,
string $system_id,
string|false $public_id,
string|false $notation_name
): void
parser
O analisador XML que chama o manipulador.
entity_name
The name of the entity that is about to be defined.
base
This is the base for resolving the system identifier (systemId) of the external entity.
system_id
System identifier for the external entity.
public_id
Public identifier for the external entity.
notation_name
Name of the notation of this entity (see xml_set_notation_decl_handler()).

Valor Retornado

Sempre retorna true.

Changelog

Versão | Descrição
8.0.0 | O parâmetro parser agora espera uma instância de XMLParser; anteriormente, um resource xml válido era esperado.

User Contributed Notes

There are no user contributed notes for this page.


The XMLParser class

(PHP 8)

Introdução

A fully opaque class which replaces xml resources as of PHP 8.0.0.

Sinopse da classe

final class XMLParser {
}

User Contributed Notes

There are no user contributed notes for this page.


XMLReader

  • Introdução
  • Instalação/Configuração
    • Dependências
    • Instalação
    • Configurações em Execução
    • Tipos de Recurso
  • XMLReader — The XMLReader class
    • XMLReader::close — Close the XMLReader input
    • XMLReader::expand — Returns a copy of the current node as a DOM object
    • XMLReader::getAttribute — Get the value of a named attribute
    • XMLReader::getAttributeNo — Get the value of an attribute by index
    • XMLReader::getAttributeNs — Get the value of an attribute by localname and URI
    • XMLReader::getParserProperty — Indicates if specified property has been set
    • XMLReader::isValid — Indicates if the parsed document is valid
    • XMLReader::lookupNamespace — Lookup namespace for a prefix
    • XMLReader::moveToAttribute — Move cursor to a named attribute
    • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs — Move cursor to a named attribute
    • XMLReader::moveToElement — Position cursor on the parent Element of current Attribute
    • XMLReader::moveToFirstAttribute — Position cursor on the first Attribute
    • XMLReader::moveToNextAttribute — Position cursor on the next Attribute
    • XMLReader::next — Move cursor to next node skipping all subtrees
    • XMLReader::open — Set the URI containing the XML to parse
    • XMLReader::read — Move to next node in document
    • XMLReader::readInnerXml — Retrieve XML from current node
    • XMLReader::readOuterXml — Retrieve XML from current node, including itself
    • XMLReader::readString — Reads the contents of the current node as a string
    • XMLReader::setParserProperty — Set parser options
    • XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema
    • XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema
    • XMLReader::setSchema — Validate document against XSD
    • XMLReader::XML — Set the data containing the XML to parse

User Contributed Notes

There are no user contributed notes for this page.


Introdução

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.

Codificação

It is important to note that internally, libxml uses the UTF-8 encoding and as such, the encoding of the retrieved contents will always be in UTF-8 encoding.

User Contributed Notes

There are no user contributed notes for this page.


Instalação

The XMLReader ships with PHP source. Esta extensão está habilitada por padrão. Ela pode ser desabilitada usando a seguinte opção em tempo de compilação: --disable-xmlreader

User Contributed Notes

Miguel Cruz 11-Jun-2012 01:06
If you are having trouble loading this extension (perhaps with a log message like 'Undefined symbol "dom_node_class_entry"'), make sure that you have xmlreader.so listed AFTER dom.so in php.ini.
alvaro at digdib dot com 02-Jan-2009 02:33
Gentoo users: emerge does not compile dev-lang/php with --enable-xmlreader by default. To enable this option, add the flag xmlreader to your USE variable and recompile php.


The XMLReader class

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

Introdução

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.

Sinopse da classe

class XMLReader {
/* Constantes */
public const int NONE;
public const int ELEMENT;
public const int ATTRIBUTE;
public const int TEXT;
public const int CDATA;
public const int ENTITY_REF;
public const int ENTITY;
public const int PI;
public const int COMMENT;
public const int DOC;
public const int DOC_TYPE;
public const int DOC_FRAGMENT;
public const int NOTATION;
public const int WHITESPACE;
public const int SIGNIFICANT_WHITESPACE;
public const int END_ELEMENT;
public const int END_ENTITY;
public const int XML_DECLARATION;
public const int LOADDTD;
public const int DEFAULTATTRS;
public const int VALIDATE;
public const int SUBST_ENTITIES;
/* Propriedades */
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
}

Propriedades

attributeCount

The number of attributes on the node

baseURI

The base URI of the node

depth

Depth of the node in the tree, starting at 0

hasAttributes

Indicates if node has attributes

hasValue

Indicates if node has a text value

isDefault

Indicates if attribute is defaulted from DTD

isEmptyElement

Indicates if node is an empty element tag

localName

The local name of the node

name

The qualified name of the node

namespaceURI

The URI of the namespace associated with the node

nodeType

The node type for the node

prefix

The prefix of the namespace associated with the node

value

The text value of the node

xmlLang

The xml:lang scope which the node resides

Constantes pré-definidas

XMLReader Node Types

XMLReader::NONE

No node type

XMLReader::ELEMENT

Start element

XMLReader::ATTRIBUTE

Attribute node

XMLReader::TEXT

Text node

XMLReader::CDATA

CDATA node

XMLReader::ENTITY_REF

Entity Reference node

XMLReader::ENTITY

Entity Declaration node

XMLReader::PI

Processing Instruction node

XMLReader::COMMENT

Comment node

XMLReader::DOC

Document node

XMLReader::DOC_TYPE

Document Type node

XMLReader::DOC_FRAGMENT

Document Fragment node

XMLReader::NOTATION

Notation node

XMLReader::WHITESPACE

Whitespace node

XMLReader::SIGNIFICANT_WHITESPACE

Significant Whitespace node

XMLReader::END_ELEMENT

End Element

XMLReader::END_ENTITY

End Entity

XMLReader::XML_DECLARATION

XML Declaration node

XMLReader Parser Options

XMLReader::LOADDTD

Load DTD but do not validate

XMLReader::DEFAULTATTRS

Load DTD and default attributes but do not validate

XMLReader::VALIDATE

Load DTD and validate while parsing

XMLReader::SUBST_ENTITIES

Substitute entities and expand references

Índice

  • XMLReader::close — Close the XMLReader input
  • XMLReader::expand — Returns a copy of the current node as a DOM object
  • XMLReader::getAttribute — Get the value of a named attribute
  • XMLReader::getAttributeNo — Get the value of an attribute by index
  • XMLReader::getAttributeNs — Get the value of an attribute by localname and URI
  • XMLReader::getParserProperty — Indicates if specified property has been set
  • XMLReader::isValid — Indicates if the parsed document is valid
  • XMLReader::lookupNamespace — Lookup namespace for a prefix
  • XMLReader::moveToAttribute — Move cursor to a named attribute
  • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs — Move cursor to a named attribute
  • XMLReader::moveToElement — Position cursor on the parent Element of current Attribute
  • XMLReader::moveToFirstAttribute — Position cursor on the first Attribute
  • XMLReader::moveToNextAttribute — Position cursor on the next Attribute
  • XMLReader::next — Move cursor to next node skipping all subtrees
  • XMLReader::open — Set the URI containing the XML to parse
  • XMLReader::read — Move to next node in document
  • XMLReader::readInnerXml — Retrieve XML from current node
  • XMLReader::readOuterXml — Retrieve XML from current node, including itself
  • XMLReader::readString — Reads the contents of the current node as a string
  • XMLReader::setParserProperty — Set parser options
  • XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema
  • XMLReader::setSchema — Validate document against XSD
  • XMLReader::XML — Set the data containing the XML to parse

User Contributed Notes

eef dot vreeland at gmail dot com 10-Aug-2017 05:43
Please discard my previous note; I pressed 'Add Note' too quickly

About (non-)self-closing tags:

 A) <tag></tag>
    $xmlRdr->isEmptyElement => false
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => false

 B) <tag />
    $xmlRdr->isEmptyElement => true
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => false

 C) <tag attribute="value"></tag>
    $xmlRdr->isEmptyElement => false
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => true

 D) <tag attribute="value" />
    $xmlRdr->isEmptyElement => true
    $xmlRdr->hasValue       => false
    $xmlRdr->value          => ''
    $xmlRdr->hasAttributes  => true

... and always use the '===' operator when testing properties
eef dot vreeland at gmail dot com 10-Aug-2017 05:08
Note that when:

A) <tag></tag>
   $xmlRdr->isEmptyElement => false
   $xmlRdr->hasValue       => true
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => false

B) <tag />
   $xmlRdr->isEmptyElement => true
   $xmlRdr->hasValue       => false
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => false

C) <tag attribute="value"></tag>
   $xmlRdr->isEmptyElement => false
   $xmlRdr->hasValue       => false
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => true

D) <tag attribute="value" />
   $xmlRdr->isEmptyElement => true
   $xmlRdr->hasValue       => false
   $xmlRdr->value          => ''
   $xmlRdr->hasAttributes  => true
Sean Colin Ruiz 08-Jan-2017 03:11
As japos mentioned. Take care how you use isEmptyElement. After you are done looping through the attributes: isEmptyElement will be false.  You can use moveToElement() to move the cursor back to the element and then you can use isEmptyElement like normal again.
dkrnl at yandex dot ru 04-Oct-2013 04:10
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

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

<?php

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

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

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

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

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

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

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

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

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

}
?>
kula_shakerz 03-Apr-2013 02:27
Found this in the IXmlReader docs at msdn but it's also valid for XMLReader in PHP.

You should save the value of $isEmptyElement before processing attributes, or call moveToElement to make $isEmptyElement valid after processing attributes.

$isEmptyElement returns FALSE when XMLReader is positioned on an attribute node, even if attribute's parent element is empty.
Mike De Smet 25-Sep-2012 04:35
For those of you getting xml files that do not contain duplicate elements (in the same element), the following converter converts to arrays with key/value mapping (thus overwriting duplicate elements!):

Note this is untested with attributes although I built in support.

<?php
    function xml2assoc($xml, array &$target = array()) {
        while ($xml->read()) {
            switch ($xml->nodeType) {
                case XMLReader::END_ELEMENT:
                    return $target;
                case XMLReader::ELEMENT:
                    $name = $xml->name;
                    $target[$name] = $xml->hasAttributes ? array() : '';
                    if (!$xml->isEmptyElement) {
                        $target[$name] = array();
                        xml2assoc($xml, $target[$name]);
                    }

                    if ($xml->hasAttributes)
                        while($xml->moveToNextAttribute())
                            $target[$name]['@'.$xml->name] = $xml->value;
                    break;
                case XMLReader::TEXT:
                case XMLReader::CDATA:
                    $target = $xml->value;
            }
        }
        return $target;
    }
?>
casella dot email at google dot mail dot com 22-Sep-2012 03:59
To verify that all nodes are read without error/warning you can use this code:
<?php
$endofxml = false;
$xml_url = "example.xml";
$reader = new XMLReader();
if(!$reader->open($xml_url)){
    print "Error to open XML: $xml_url\n";
} else {
    while ($reader->read()) {
        $firstnode = (!isset($firstnode)) ? $reader->name : $firstnode;
/*
DO SOMETHING
*/
        if ($reader->nodeType == XMLReader::END_ELEMENT && $reader->name == $firstnode) {
            $endofxml = true;
        }
    }
}
if($endofxml) {
    print "no error found";
} else {
    print "error found";
}
?>

This code is useful to trap $reader->read() error/warning.
lee8oi at gmail dot com 21-Mar-2012 01:54
Sometimes you have an unusual URL that doesn't actually point to an xml file but still returns xml as output (Like the Battlefield Heroes generated syndication urls). Using get_file_contents(url) you can retrieve the xml data from these urls and pass it as a variable for processing as an XML String.

Unfortunately simpleXML or xml DOM cannot process all xml strings. Some have error boxes added to the end of them (such as Battlefield Heroes syndicated news). These boxes cause an end of file sort of error and closes out the script. XMLReader grabs data from these strings without error.
japos dot trash at googlemail dot com 09-Oct-2010 02:17
Take care about how to use XMLReader::$isElementEmpty. I don't know if it is a bug or not, but $isElementEmpty is set for the current context and NOT just for the element. If you move your cursor to an attribute, $isElementEmpty will ALWAYS be false.

<?php
 $xml = new XMLReader();
 $xml->XML('<tag attr="value" />');
 $xml->read();
 var_dump($xml->isEmptyElement);
 $xml->moveToNextAttribute();
 var_dump($xml->isEmptyElement);
?>

will output

(bool) true
(bool) false

So be sure to store $isEmptyElement before moving the cursor.
jart (at) mail.ru 23-Sep-2010 06:59
Guys, I hope this example will help
you can erase prints showing the process-
and it will be a piece of nice code.

<?php
function xml2assoc($xml, $name)
{
    print "<ul>";

    $tree = null;
    print("I'm inside " . $name . "<br>");

    while($xml->read())
    {
        if($xml->nodeType == XMLReader::END_ELEMENT)
        {
            print "</ul>";
            return $tree;
        }

        else if($xml->nodeType == XMLReader::ELEMENT)
        {
            $node = array();

            print("Adding " . $xml->name ."<br>");
            $node['tag'] = $xml->name;

            if($xml->hasAttributes)
            {
                $attributes = array();
                while($xml->moveToNextAttribute())
                {
                    print("Adding attr " . $xml->name ." = " . $xml->value . "<br>");
                    $attributes[$xml->name] = $xml->value;
                }
                $node['attr'] = $attributes;
            }

            if(!$xml->isEmptyElement)
            {
                $childs = xml2assoc($xml, $node['tag']);
                $node['childs'] = $childs;
            }

            print($node['tag'] . " added <br>");
            $tree[] = $node;
        }

        else if($xml->nodeType == XMLReader::TEXT)
        {
            $node = array();
            $node['text'] = $xml->value;
            $tree[] = $node;
            print "text added = " . $node['text'] . "<br>";
        }
    }

    print "returning " . count($tree) . " childs<br>";
    print "</ul>";

    return $tree;
}

echo "<PRE>";

$xml = new XMLReader();
$xml->open('test.xml');
$assoc = xml2assoc($xml, "root");
$xml->close();

print_r($assoc);
echo "</PRE>";

?>

It reads this xml:

<test>
    <hallo volume="loud"> me <br/> lala </hallo>
    <hallo> me </hallo>
</test>
jnettles at inccrra dot org 02-Oct-2009 09:51
Just in case someone is confused, if you're wanting to simply pass a string of XML instead of an entire file, you would do this.

<?php
$foo = new XMLReader();
$foo->xml($STRING);
?>

.... where $STRING holds your XML. You cannot pass it like $foo = $STRING or $foo->xml = $STRING.
james dot ellis at example dot com 25-Mar-2009 03:16
The "XML2Assoc" functions noted here should be used with caution... basically they are duplicating the functionality already present in SimpleXML. They may work but they won't scale.

Their are two main uses cases for parsing XML, each suited to either XMLReader or SimpleXML.

1. SimpleXML is an excellent tool for easy access to an XML document tree using native PHP data types. It starts to flounder with massive (> 50M or so) XML documents, as it reads the entire document into memory before it can be processed. SimpleXML will just laugh at you then die when your server runs out of memory (or it will cause a load spike).

2. Aside from the reasoning behind massive XML documents, if you have to deal with massive XML documents, use XMLReader to process them. Don't try and gather an entire XML document into a PHP data structure using XMLReader and a PHP xml2assoc() function, you are reinventing the SimpleXML wheel.
When parsing massive XML documents using XMLReader, gather the data you need to perform an operation then perform it before skipping to the next node. Do not build massive data structures from a massive XML document, your server (and it's admins) will not like you.
PxL 23-Jan-2009 03:36
A basic parser

<?php
function xml2assoc($xml) {
    $arr = array();
    if (!preg_match_all('|\<\s*?(\w+).*?\>(.*)\<\/\s*\\1.*?\>|s', $xml, $m)) return $xml;
    if (is_array($m[1]))
        for ($i = 0;$i < sizeof($m[1]); $i++) $arr[$m[1][$i]] = xml2assoc($m[2][$i]);
    else $arr[$m[1]] = xml2assoc($m[2]);

    return $arr;
}
?>
boukeversteegh at gmail dot com 18-Jan-2009 02:06
XML to ASSOCIATIVE ARRAY

Improved algorithm based on Sergey Aikinkulov's. The problem was that it would overwrite nodes if they had the same tag name. Because of that <a><b/><b/><a> would be read as if <a><b/><a/>. This algorithm handles it better and outputs an easy to understand array:

<?php
function xml2assoc($xml) {
    $tree = null;
    while($xml->read())
        switch ($xml->nodeType) {
            case XMLReader::END_ELEMENT: return $tree;
            case XMLReader::ELEMENT:
                $node = array('tag' => $xml->name, 'value' => $xml->isEmptyElement ? '' : xml2assoc($xml));
                if($xml->hasAttributes)
                    while($xml->moveToNextAttribute())
                        $node['attributes'][$xml->name] = $xml->value;
                $tree[] = $node;
            break;
            case XMLReader::TEXT:
            case XMLReader::CDATA:
                $tree .= $xml->value;
        }
    return $tree;
}

?>

Usage:

myxml.xml:
------
<PERSON>
    <NAME>John</NAME>
    <PHONE type="home">555-555-555</PHONE>
</PERSON>
----

<?
    $xml = new XMLReader();
    $xml->open('myxml.xml');
    $assoc = xml2assoc($xml);
    $xml->close();
    print_r($assoc);
?>

Outputs:
Array
(
    [0] => Array
        (
            [tag] => PERSON
            [value] => Array
                (
                    [0] => Array
                        (
                            [tag] => NAME
                            [value] => John
                        )

                    [1] => Array
                        (
                            [tag] => PHONE
                            [value] => 555-555-555
                            [attributes] => Array
                                (
                                    [type] => home
                                )

                        )

                )

        )

)

For reasons that have to do with recursion, it returns an array with the ROOT xml node as the first childNode, rather than to return only the ROOT node.
andrei_antal at yahoo dot com 08-Jan-2009 08:25
<?php
//Pull certain elements
 $reader = new XMLReader();
  $reader->open($xmlfile);
while ($reader->read()) {
 switch ($reader->nodeType) {
   case (XMLREADER::ELEMENT):

if ($reader->name == "Code")
     {
       $reader->read();
       $code = trim($reader->value);
       echo "$code\n";
       break;
     }

 if ($reader->name == "Name")
     {
       $reader->read();
       $customername = trim( $reader->value );
       echo "$name\n";
       break;
     }

 if ($reader->name == "Camp")
    {
      $camp = trim($reader->getAttribute("ID"));
       echo "$camp\n";
      break;
    }
  }
}
?>
godseth at o2 dot pl 28-Nov-2008 02:34
Thanks rein_baarsma33 AT hotmail DOT com for bugfixes.

This is my new child of XML parsing method  based on my and yours modification.

XML2ASSOC Is a complete solution for parsing ordinary XML

<?php
/**
 * XML2Assoc Class to creating
 * PHP Assoc Array from XML File
 *
 * @author godseth (AT) o2.pl & rein_baarsma33 (AT) hotmail.com (Bugfixes in parseXml Method)
 * @uses XMLReader
 *
 */

class Xml2Assoc {

    /**
     * Optimization Enabled / Disabled
     *
     * @var bool
     */
    protected $bOptimize = false;

    /**
     * Method for loading XML Data from String
     *
     * @param string $sXml
     * @param bool $bOptimize
     */

    public function parseString( $sXml , $bOptimize = false) {
        $oXml = new XMLReader();
        $this -> bOptimize = (bool) $bOptimize;
        try {

            // Set String Containing XML data
            $oXml->XML($sXml);

            // Parse Xml and return result
            return $this->parseXml($oXml);

        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    /**
     * Method for loading Xml Data from file
     *
     * @param string $sXmlFilePath
     * @param bool $bOptimize
     */
    public function parseFile( $sXmlFilePath , $bOptimize = false ) {
        $oXml = new XMLReader();
        $this -> bOptimize = (bool) $bOptimize;
        try {
            // Open XML file
            $oXml->open($sXmlFilePath);

            // // Parse Xml and return result
            return $this->parseXml($oXml);

        } catch (Exception $e) {
            echo $e->getMessage(). ' | Try open file: '.$sXmlFilePath;
        }
    }

    /**
     * XML Parser
     *
     * @param XMLReader $oXml
     * @return array
     */
    protected function parseXml( XMLReader $oXml ) {

        $aAssocXML = null;
        $iDc = -1;

        while($oXml->read()){
            switch ($oXml->nodeType) {

                case XMLReader::END_ELEMENT:

                    if ($this->bOptimize) {
                        $this->optXml($aAssocXML);
                    }
                    return $aAssocXML;

                case XMLReader::ELEMENT:

                    if(!isset($aAssocXML[$oXml->name])) {
                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name] = '';
                            } else {
                                $aAssocXML[$oXml->name] = $this->parseXML($oXml);
                            }
                        }
                    } elseif (is_array($aAssocXML[$oXml->name])) {
                        if (!isset($aAssocXML[$oXml->name][0]))
                        {
                            $temp = $aAssocXML[$oXml->name];
                            foreach ($temp as $sKey=>$sValue)
                            unset($aAssocXML[$oXml->name][$sKey]);
                            $aAssocXML[$oXml->name][] = $temp;
                        }

                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name][] = '';
                            } else {
                                $aAssocXML[$oXml->name][] = $this->parseXML($oXml);
                            }
                        }
                    } else {
                        $mOldVar = $aAssocXML[$oXml->name];
                        $aAssocXML[$oXml->name] = array($mOldVar);
                        if($oXml->hasAttributes) {
                            $aAssocXML[$oXml->name][] = $oXml->isEmptyElement ? '' : $this->parseXML($oXml);
                        } else {
                            if($oXml->isEmptyElement) {
                                $aAssocXML[$oXml->name][] = '';
                            } else {
                                $aAssocXML[$oXml->name][] = $this->parseXML($oXml);
                            }
                        }
                    }

                    if($oXml->hasAttributes) {
                        $mElement =& $aAssocXML[$oXml->name][count($aAssocXML[$oXml->name]) - 1];
                        while($oXml->moveToNextAttribute()) {
                            $mElement[$oXml->name] = $oXml->value;
                        }
                    }
                    break;
                case XMLReader::TEXT:
                case XMLReader::CDATA:

                    $aAssocXML[++$iDc] = $oXml->value;

            }
        }

        return $aAssocXML;
    }

    /**
     * Method to optimize assoc tree.
     * ( Deleting 0 index when element
     *  have one attribute / value )
     *
     * @param array $mData
     */
    public function optXml(&$mData) {
        if (is_array($mData)) {
            if (isset($mData[0]) && count($mData) == 1 ) {
                $mData = $mData[0];
                if (is_array($mData)) {
                    foreach ($mData as &$aSub) {
                        $this->optXml($aSub);
                    }
                }
            } else {
                foreach ($mData as &$aSub) {
                    $this->optXml($aSub);
                }
            }
        }
    }

}

?>

[EDIT BY danbrown AT php DOT net:  Fixes were also provided by "Alex" and (qdog AT qview DOT org) in user notes on this page (since removed).]
Sergey Aikinkulov 19-Jun-2008 03:51
Next version xml2assoc with some improve fixes:
 - no doubled data
 - no buffer arrays

<?php
/*
    Read XML structure to associative array
    --
    Using:
    $xml = new XMLReader();
    $xml->open([XML file]);
    $assoc = xml2assoc($xml);
    $xml->close();
*/
    function xml2assoc($xml) {
      $assoc = null;
      while($xml->read()){
        switch ($xml->nodeType) {
          case XMLReader::END_ELEMENT: return $assoc;
          case XMLReader::ELEMENT:
            $assoc[$xml->name][] = array('value' => $xml->isEmptyElement ? '' : xml2assoc($xml));
            if($xml->hasAttributes){
              $el =& $assoc[$xml->name][count($assoc[$xml->name]) - 1];
              while($xml->moveToNextAttribute()) $el['attributes'][$xml->name] = $xml->value;
            }
            break;
          case XMLReader::TEXT:
          case XMLReader::CDATA: $assoc .= $xml->value;
        }
      }
      return $assoc;
    }
?>
desk_ocean at msn dot com 16-Mar-2008 10:03
make some modify from Sergey Aikinkulov's note

<?php
function xml2assoc(&$xml){
    $assoc = NULL;
    $n = 0;
    while($xml->read()){
        if($xml->nodeType == XMLReader::END_ELEMENT) break;
        if($xml->nodeType == XMLReader::ELEMENT and !$xml->isEmptyElement){
            $assoc[$n]['name'] = $xml->name;
            if($xml->hasAttributes) while($xml->moveToNextAttribute()) $assoc[$n]['atr'][$xml->name] = $xml->value;
            $assoc[$n]['val'] = xml2assoc($xml);
            $n++;
        }
        else if($xml->isEmptyElement){
            $assoc[$n]['name'] = $xml->name;
            if($xml->hasAttributes) while($xml->moveToNextAttribute()) $assoc[$n]['atr'][$xml->name] = $xml->value;
            $assoc[$n]['val'] = "";
            $n++;
        }
        else if($xml->nodeType == XMLReader::TEXT) $assoc = $xml->value;
    }
    return $assoc;
}
?>

add else if($xml->isEmptyElement)
may be some xml has emptyelement
itari 15-Feb-2008 08:30
<?php
function parseXML($node,$seq,$path) {
global $oldpath;
    if (!$node->read())
      return;
    if ($node->nodeType != 15) {
      print '<br/>'.$node->depth;
      print '-'.$seq++;
      print '  '.$path.'/'.($node->nodeType==3?'text() = ':$node->name);
      print $node->value;
      if ($node->hasAttributes) {
        print ' [hasAttributes: ';
        while ($node->moveToNextAttribute()) print '@'.$node->name.' = '.$node->value.' ';
        print ']';
        }
      if ($node->nodeType == 1) {
        $oldpath=$path;
        $path.='/'.$node->name;
        }
      parseXML($node,$seq,$path);
      }
    else parseXML($node,$seq,$oldpath);
}

$source = "<tag1>this<tag2 id='4' name='foo'>is</tag2>a<tag2 id='5'>common</tag2>record</tag1>";
$xml = new XMLReader();
$xml->XML($source);
print htmlspecialchars($source).'<br/>';
parseXML($xml,0,'');
?>

Output:

<tag1>this<tag2 id='4' name='foo'>is</tag2>a<tag2 id='5'>common</tag2>record</tag1>

0-0 /tag1
1-1 /tag1/text() = this
1-2 /tag1/tag2 [hasAttributes: @id = 4 @name = foo ]
2-3 /tag1/text() = is
1-4 /text() = a
1-5 /tag2 [hasAttributes: @id = 5 ]
2-6 /text() = common
1-7 /text() = record
orion at ftf-hq dot dk 15-Feb-2006 04:50
Some more documentation (i.e. examples) would be nice :-)

This is how I read some mysql parameters in an xml file:

<?php
    $xml = new XMLReader();
    $xml->open("config.xml");
    $xml->setParserProperty(2,true); // This seems a little unclear to me - but it worked :)

    while ($xml->read()) {
        switch ($xml->name) {
        case "mysql_host":
            $xml->read();
            $conf["mysql_host"] = $xml->value;
            $xml->read();
            break;
        case "mysql_username":
            $xml->read();
            $conf["mysql_user"] = $xml->value;
            $xml->read();
            break;
        case "mysql_password":
            $xml->read();
            $conf["mysql_pass"] = $xml->value;
            $xml->read();
            break;
        case "mysql_database":
            $xml->read();
            $conf["mysql_db"] = $xml->value;
            $xml->read();
            break;
        }
    }

    $xml->close();
?>

The XML file used:
<?xml version='1.0'?>
<MySQL_INIT>
   <mysql_host>localhost</mysql_host>
   <mysql_database>db_database</mysql_database>
   <mysql_username>root</mysql_username>
   <mysql_password>password</mysql_password>
</MySQL_INIT>


Close the XMLReader input

  • « XMLReader
  • XMLReader::expand »
  • PHP Manual
  • XMLReader
  • Close the XMLReader input

XMLReader::close

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

XMLReader::close — Close the XMLReader input

Descrição

public XMLReader::close(): true

Closes the input the XMLReader object is currently parsing.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Sempre retorna true.

Veja Também

  • XMLReader::open() - Set the URI containing the XML to parse
  • XMLReader::xml() - Set the data containing the XML to parse

User Contributed Notes

There are no user contributed notes for this page.


Returns a copy of the current node as a DOM object

  • « XMLReader::close
  • XMLReader::getAttribute »
  • PHP Manual
  • XMLReader
  • Returns a copy of the current node as a DOM object

XMLReader::expand

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

XMLReader::expand — Returns a copy of the current node as a DOM object

Descrição

public XMLReader::expand(?DOMNode $baseNode = null): DOMNode|false

This method copies the current node and returns the appropriate DOM object.

Parâmetros

baseNode

A DOMNode defining the target DOMDocument for the created DOM object.

Valor Retornado

The resulting DOMNode or false on 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


Get the value of a named attribute

  • « XMLReader::expand
  • XMLReader::getAttributeNo »
  • PHP Manual
  • XMLReader
  • Get the value of a named attribute

XMLReader::getAttribute

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

XMLReader::getAttribute — Get the value of a named attribute

Descrição

public XMLReader::getAttribute(string $name): ?string

Returns the value of a named attribute or null if the attribute does not exist or not positioned on an element node.

Parâmetros

name

The name of the attribute.

Valor Retornado

The value of the attribute, or null if no attribute with the given name is found or not positioned on an element node.

Changelog

Versão | Descrição
8.0.0 | This function can no longer return false.

Veja Também

  • XMLReader::getAttributeNo() - Get the value of an attribute by index
  • XMLReader::getAttributeNs() - Get the value of an attribute by localname and URI

User Contributed Notes

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.


Get the value of an attribute by index

  • « XMLReader::getAttribute
  • XMLReader::getAttributeNs »
  • PHP Manual
  • XMLReader
  • Get the value of an attribute by index

XMLReader::getAttributeNo

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

XMLReader::getAttributeNo — Get the value of an attribute by index

Descrição

public XMLReader::getAttributeNo(int $index): ?string

Returns the value of an attribute based on its position or an empty string if attribute does not exist or not positioned on an element node.

Parâmetros

index

The position of the attribute.

Valor Retornado

The value of the attribute, or null if no attribute exists at index or is not positioned on the element.

Veja Também

  • XMLReader::getAttribute() - Get the value of a named attribute
  • XMLReader::getAttributeNs() - Get the value of an attribute by localname and URI

User Contributed Notes

There are no user contributed notes for this page.


Get the value of an attribute by localname and URI

  • « XMLReader::getAttributeNo
  • XMLReader::getParserProperty »
  • PHP Manual
  • XMLReader
  • Get the value of an attribute by localname and URI

XMLReader::getAttributeNs

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

XMLReader::getAttributeNs — Get the value of an attribute by localname and URI

Descrição

public XMLReader::getAttributeNs(string $name, string $namespace): ?string

Returns the value of an attribute by name and namespace URI or an empty string if attribute does not exist or not positioned on an element node.

Parâmetros

name

The local name.

namespace

The namespace URI.

Valor Retornado

The value of the attribute, or null if no attribute with the given name and namespace is found or not positioned of element.

Changelog

Versão | Descrição
8.0.0 | This function can no longer return false.

Veja Também

  • XMLReader::getAttribute() - Get the value of a named attribute
  • XMLReader::getAttributeNo() - Get the value of an attribute by index

User Contributed Notes

There are no user contributed notes for this page.


Indicates if specified property has been set

  • « XMLReader::getAttributeNs
  • XMLReader::isValid »
  • PHP Manual
  • XMLReader
  • Indicates if specified property has been set

XMLReader::getParserProperty

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

XMLReader::getParserProperty — Indicates if specified property has been set

Descrição

public XMLReader::getParserProperty(int $property): bool

Indicates if specified property has been set.

Parâmetros

property

One of the parser option constants.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • XMLReader::setParserProperty() - Set parser options

User Contributed Notes

There are no user contributed notes for this page.


Indicates if the parsed document is valid

  • « XMLReader::getParserProperty
  • XMLReader::lookupNamespace »
  • PHP Manual
  • XMLReader
  • Indicates if the parsed document is valid

XMLReader::isValid

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

XMLReader::isValid — Indicates if the parsed document is valid

Descrição

public XMLReader::isValid(): bool

Returns a boolean indicating if the document being parsed is currently valid.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Exemplos

Exemplo #1 Validating XML

<?php
$xml = XMLReader::open('test.xml');

// The validate parser option must be enabled for
// this method to work properly
$xml->setParserProperty(XMLReader::VALIDATE, true);

var_dump($xml->isValid());
?>

Notas

Nota: This checks the current node, not the entire document.

Veja Também

  • XMLReader::setParserProperty() - Set parser options
  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD

User Contributed Notes

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


Lookup namespace for a prefix

  • « XMLReader::isValid
  • XMLReader::moveToAttribute »
  • PHP Manual
  • XMLReader
  • Lookup namespace for a prefix

XMLReader::lookupNamespace

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

XMLReader::lookupNamespace — Lookup namespace for a prefix

Descrição

public XMLReader::lookupNamespace(string $prefix): ?string

Lookup in scope namespace for a given prefix.

Parâmetros

prefix

String containing the prefix.

Valor Retornado

The value of the namespace, or null if no namespace exists.

Changelog

Versão | Descrição
8.0.0 | This function can no longer return false.

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to a named attribute

  • « XMLReader::lookupNamespace
  • XMLReader::moveToAttributeNo »
  • PHP Manual
  • XMLReader
  • Move cursor to a named attribute

XMLReader::moveToAttribute

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

XMLReader::moveToAttribute — Move cursor to a named attribute

Descrição

public XMLReader::moveToAttribute(string $name): bool

Positions cursor on the named attribute.

Parâmetros

name

The name of the attribute.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to an attribute by index

  • « XMLReader::moveToAttribute
  • XMLReader::moveToAttributeNs »
  • PHP Manual
  • XMLReader
  • Move cursor to an attribute by index

XMLReader::moveToAttributeNo

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

XMLReader::moveToAttributeNo — Move cursor to an attribute by index

Descrição

public XMLReader::moveToAttributeNo(int $index): bool

Positions cursor on attribute based on its position.

Parâmetros

index

The position of the attribute.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to a named attribute

  • « XMLReader::moveToAttributeNo
  • XMLReader::moveToElement »
  • PHP Manual
  • XMLReader
  • Move cursor to a named attribute

XMLReader::moveToAttributeNs

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

XMLReader::moveToAttributeNs — Move cursor to a named attribute

Descrição

public XMLReader::moveToAttributeNs(string $name, string $namespace): bool

Positions cursor on the named attribute in specified namespace.

Parâmetros

name

The local name.

namespace

The namespace URI.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Position cursor on the parent Element of current Attribute

  • « XMLReader::moveToAttributeNs
  • XMLReader::moveToFirstAttribute »
  • PHP Manual
  • XMLReader
  • Position cursor on the parent Element of current Attribute

XMLReader::moveToElement

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

XMLReader::moveToElement — Position cursor on the parent Element of current Attribute

Descrição

public XMLReader::moveToElement(): bool

Moves cursor to the parent Element of current Attribute.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns true if successful and false if it fails or not positioned on Attribute when this method is called.

Veja Também

  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

Sean Colin Ruiz 08-Jan-2017 08:54
On an element like this: <self_closing attribute="1" /> isEmptyElement will return FALSE after you have iterated through the attributes.  So you need to use implicitly call moveToElement(), in order to move the cursor back to the parent element and use isEmptyElement again.


Position cursor on the first Attribute

  • « XMLReader::moveToElement
  • XMLReader::moveToNextAttribute »
  • PHP Manual
  • XMLReader
  • Position cursor on the first Attribute

XMLReader::moveToFirstAttribute

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

XMLReader::moveToFirstAttribute — Position cursor on the first Attribute

Descrição

public XMLReader::moveToFirstAttribute(): bool

Moves cursor to the first Attribute.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToNextAttribute() - Position cursor on the next Attribute

User Contributed Notes

There are no user contributed notes for this page.


Position cursor on the next Attribute

  • « XMLReader::moveToFirstAttribute
  • XMLReader::next »
  • PHP Manual
  • XMLReader
  • Position cursor on the next Attribute

XMLReader::moveToNextAttribute

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

XMLReader::moveToNextAttribute — Position cursor on the next Attribute

Descrição

public XMLReader::moveToNextAttribute(): bool

Moves cursor to the next Attribute if positioned on an Attribute or moves to first attribute if positioned on an Element.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute

User Contributed Notes

There are no user contributed notes for this page.


Move cursor to next node skipping all subtrees

  • « XMLReader::moveToNextAttribute
  • XMLReader::open »
  • PHP Manual
  • XMLReader
  • Move cursor to next node skipping all subtrees

XMLReader::next

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

XMLReader::next — Move cursor to next node skipping all subtrees

Descrição

public XMLReader::next(?string $name = null): bool

Positions cursor on the next node skipping all subtrees. If no such node exists, the cursor is moved to the end of the document.

Parâmetros

name

The name of the next node to move to.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | name is nullable now.

Veja Também

  • XMLReader::moveToNextAttribute() - Position cursor on the next Attribute
  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute

User Contributed Notes

Quiet Noise 13-Apr-2019 01:39
next() without parameters will bring you to the next sibling node on the same depth as the depth where the current cursor is.
Examples:
1. If you are on an opening ELEMENT node next() will bring you to the new line node next to the closing tag of that element (i.e. if you have each tag in separate line) or it will bring you to the opening tag of next node on the same depth.
2. If you are on a TEXT node next() will bring you to the opening tag if there is one next to it.

If there are no more nodes on the given depth next() will bring you to the closing tag (END_ELEMENT) of the wrapping parent.
ppp dot BOTSNEEDNOTAPPLY at salesfloor dot net 08-Sep-2015 09:48
This method appears to follow these rules:

 - if $localName names a sibling node, the cursor is moved to that node;
 - if $localName names an ancestor node, the cursor is moved to the end of that node;
 - if $localName names a node that is a sibling of any of the current node's ancestors, the cursor is moved to that node;
 - otherwise the cursor is moved outside the document.

Note especially that this method never moves the cursor to child nodes.

For example, given this XML document

<?xml version="1.0" encoding="UTF-8"?>
<root id="root" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <aaa id="1">
    <bbb id="1.1"></bbb>
    <bbb id="1.2"></bbb>
  </aaa>
  <ccc id="2" />
  <aaa id="3">
    <ddd id="3.1">
      <aaa id="3.1.1"></aaa>
    </ddd>
    <aaa id="3.2"></aaa>
  </aaa>
  <aaa id="4">
    <eee id="4.1"></eee>
  </aaa>
</root>

going from <root id="root"> to "bbb" places the cursor outside the document;
going from <aaa id="1"> to "bbb" places the cursor outside the document;
going from <aaa id="1"> to "aaa" places the cursor on <aaa id="3">;
going from <bbb id="1.1"> to "bbb" places the cursor on <bbb id="1.2">;
going from <bbb id="1.2"> to "bbb" places the cursor outside the document;
going from <bbb id="1.1"> to "ddd" places the cursor outside the document;
going from <bbb id="1.1"> to "aaa" places the cursor on </aaa>;
going from <bbb id="1.1"> to "ccc" places the cursor on <ccc id="2">;
going from <bbb id="1.1"> to "nonsuch" places the cursor outside the document;
going from <bbb id="1.1"> to "root" places the cursor on </root>;
going from <ddd id="3.1"> to "aaa" places the cursor on <aaa id="3.2">;
going from <ddd id="3.1"> to "eee" places the cursor outside the document;

Try it yourself:

<?php

$document = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root id="root" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <aaa id="1">
    <bbb id="1.1"></bbb>
    <bbb id="1.2"></bbb>
  </aaa>
  <ccc id="2" />
  <aaa id="3">
    <ddd id="3.1">
      <aaa id="3.1.1"></aaa>
    </ddd>
    <aaa id="3.2"></aaa>
  </aaa>
  <aaa id="4">
    <eee id="4.1"></eee>
  </aaa>
</root>
XML;

$filename = "/tmp/xmlreader.php.xml";
file_put_contents($filename, $document);

echo "given this XML document\n\n$document\n\n";

showNext("root", "bbb");
showNext("1", "bbb");
showNext("1", "aaa");
showNext("1.1", "bbb");
showNext("1.2", "bbb");
showNext("1.1", "ddd");
showNext("1.1", "aaa");
showNext("1.1", "ccc");
showNext("1.1", "nonsuch");
showNext("1.1", "root");
showNext("3.1", "aaa");
showNext("3.1", "eee");

function showNext($from, $to) {
  global $filename;

  $xml = new \XmlReader();
  $xml->open("file://$filename");
  while ($xml->read()) {
    if ($xml->nodeType === \XmlReader::ELEMENT) {
      if ($xml->getAttribute("id") == $from) {
        echo "going from <$xml->name id=\"$from\">";
        break;
      }
    }
  }

  $xml->next($to);
  $destination = "";
  if($xml->nodeType === \XmlReader::NONE) {
    if(!$xml->read()) {
      $destination = "outside the document";
    }
  }

  if(!$destination) {
    if ($xml->nodeType === \XmlReader::END_ELEMENT) {
      $destination = "on </$xml->name>";
    } else if ($xml->nodeType === \XmlReader::ELEMENT) {
      $destination = "on <$xml->name id=\"" . $xml->getAttribute("id") . "\">";
    }
  }

  echo " to \"$to\" places the cursor $destination;\n";

  $xml->close();
}
?>
gholson19 at gmail dot com 13-May-2015 09:21
To skip over deletion nodes in the xml extracted from a word document, do something like this:

if ($paragraph->nodeType == XMLREADER::ELEMENT && $paragraph->name === 'w:del'){$paragraph->next();}


Set the URI containing the XML to parse

  • « XMLReader::next
  • XMLReader::read »
  • PHP Manual
  • XMLReader
  • Set the URI containing the XML to parse

XMLReader::open

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

XMLReader::open — Set the URI containing the XML to parse

Descrição

public static XMLReader::open(string $uri, ?string $encoding = null, int $flags = 0): bool|XMLReader

Set the URI containing the XML document to be parsed.

Parâmetros

uri

URI pointing to the document.

encoding

The document encoding or null.

flags

A bitmask of the LIBXML_* constants.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha. If called statically, returns an XMLReader ou false em caso de falha.

Erros

This method may be called statically, but prior to PHP 8.0.0, will issue an E_DEPRECATED error in this case.

Changelog

Versão | Descrição
8.0.0 | XMLReader::open() is now declared as static method, but can still be called on an XMLReader instance.

Veja Também

  • XMLReader::xml() - Set the data containing the XML to parse
  • XMLReader::close() - Close the XMLReader input

User Contributed Notes

den at nurfuerspam dot de 29-Apr-2017 10:08
If you like to read the XML from HTTP whit a POST request, you can use libxml_set_streams_context.
Example:

<?php

$param = array('http' => array(
    'method' => 'POST',
    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
    'content' => http_build_query(array(
        'post_param1' => 'value1',
        'post_param2' => 'value2',
    )),
));
libxml_set_streams_context(stream_context_create($param));
$reader = XMLReader::open('https://example.com/get.php?get_param=value3');

?>
dave at sophoservices dot com 02-Dec-2016 07:43
When using the XmlReader to read local XML files, remember it the open function requests a URI. Add 'file://' to the front of the FULL path to the XML. Otherwise you may get:

PHP Warning:  XMLReader::open(): Unable to open source data in ...
mood(_a_)twolate.com 14-Oct-2016 11:03
For some reasons, the open() method keep throwing me this error :

PHP Warning:  XMLReader::open(): Unable to open source data in /var/www/nota/ethamap/fat_xml.php

It doesn't make sense as the xml file target hosted on my server is perfectly reachable. Adding this line before invoking open() fixed it :

libxml_disable_entity_loader(false);

Please view https://bugs.php.net/bug.php?id=62577
It is somehow related.
alvaro at demogracia dot com 14-Nov-2014 12:35
XML can optionally declare its own encoding:

    <?xml version="1.0" encoding="UTF-8"?>

You can use the $encoding parameter to provide this information (if missing) or override it (if wrong).

Output is always UTF-8 (that's how libxml works).
crungmungus at gmail dot com 15-Sep-2008 05:11
Windows users remember to enable php_openssl.dll in your php.ini if you want to be able to use this function (and others) with a HTTPS URL.


Move to next node in document

  • « XMLReader::open
  • XMLReader::readInnerXml »
  • PHP Manual
  • XMLReader
  • Move to next node in document

XMLReader::read

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

XMLReader::read — Move to next node in document

Descrição

public XMLReader::read(): bool

Moves cursor to the next node in the document.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::next() - Move cursor to next node skipping all subtrees

User Contributed Notes

peter at 3xe dot co dot uk 13-Oct-2016 12:08
Another approach to the 'also reads closing tags' gotcha:

<?php
$reader = new XMLReader();
$reader->open('users.xml');

while ($reader->read()) {
  if ($reader->nodeType == XMLReader::END_ELEMENT) {
    continue; //skips the rest of the code in this iteration
  }
  //do something with desired node type
  if($reader->name == 'user') {
    //...
  }
}
?>
Anonymous 20-Mar-2015 09:49
> I would have liked to use the next() function instead, but as I needed to parse 2 different subtrees, I couldn't figure out how to find all the columns, reset the pointer, and then find all the rows.

I just use:

$reader->close();
$reader->open($url);

to reset the pointer.
ecziegler at gmail 29-Jan-2014 12:27
If like myself you have been turning the interwebz upside down looking for a solution for this issue:
PHP Warning:  XMLReader::read(): /tmp/xml_feed.xml:4183934: parser error : Input is not proper UTF-8, indicate encoding !

For some reason, this warning breaks the execution - is it a fatal error in disguise?

After days of frustration I found it!!!!
tidy -xml -o output.xml -utf8 -f error.log input.xml

You can invoque tidy using exec, It takes several seconds to convert a 250Mb feed, but it worthy the time.

In my case the issue was with latin1 charset, and for some reason I had to pass the xml through tidy 2 times - first time around creates new errors, second time it fixes everything.

I know invalid xml should be fixed by xml creators, but it works differently in the real world.
Nate 27-Jun-2011 10:49
It is interesting to note that this function will stop on closing tags as well.  I have an XML document similar to the following:

<root>
  <columns>
    <column>columnX</column>
    <column>columnY</column>
  </columns>
  <table>
    <row>
      <columnX>38</columnX>
      <columnY>50</columnY>
    </row>
    <row>
      <columnX>82</columnY>
      <columnY>28</columnY>
    </row>
    ...
  </table>
</root>

I need to parse the <columns> object to know what attributes to check for from each <row> node.  Therefore I was doing the following:

<?php
while ($xml->read()) {
  if ($xml->name === 'column') {
   //parse column node to into $columns array
  }
  elseif ($xml->name === 'row') {
    //parse row node, using constructed $columns array
  }
}
?>

This kind of worked in that I ended up with an array of all the data I wanted, but the array I constructed was twice as large as I expected and every other entry was empty.  Took me a while to debug, but finally figured out that checking <?php $xml->name === 'row' ?> matches both <row> and </row>, so the check should really be something more like:

<?php

if ($xml->name === 'row' && $xml->nodeType == XMLReader::ELEMENT) {
  // parse row node
}

?>

I would have liked to use the next() function instead, but as I needed to parse 2 different subtrees, I couldn't figure out how to find all the columns, reset the pointer, and then find all the rows.
andy at siliconrockstar dot com 16-May-2011 01:01
A very simple way to avoid typing $reader->read() multiple times when you want to skip some nodes:

<?php
class smartXMLReader extends XMLReader {
    public function readTimes($count) {
        $i = 0;
        while($i < $count){
            $this->read();
            $i++;
        }
    }
}
?>

Using this smartXMLReader,

<?php
$reader->readTimes(3);
?>

is equivalent to

<?php
$reader->read();
$reader->read();
$reader->read();
?>

Makes getting around in your XML document a bit easier :)
jirka at kosek dot cz 08-Feb-2006 01:01
libxml2 contains much more useful method readString() that will read and return whole text content of element. You can call it after receiving start tag (XMLReader::ELEMENT). You can use this PHP code to emulate this method until PHP will directly call underlying libxml2 implementation.

<?php
class XMLReader2 extends XMLReader
{
  function readString()
  {
        $depth = 1;
        $text = "";

        while ($this->read() && $depth != 0)
        {
            if (in_array($this->nodeType, array(XMLReader::TEXT, XMLReader::CDATA, XMLReader::WHITESPACE, XMLReader::SIGNIFICANT_WHITESPACE)))
                $text .= $this->value;
            if ($this->nodeType == XMLReader::ELEMENT) $depth++;
            if ($this->nodeType == XMLReader::END_ELEMENT) $depth--;
        }
        return $text;
    }
}
?>

Just use XMLReader2 instead of XMLReader.


Retrieve XML from current node

  • « XMLReader::read
  • XMLReader::readOuterXml »
  • PHP Manual
  • XMLReader
  • Retrieve XML from current node

XMLReader::readInnerXml

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

XMLReader::readInnerXml — Retrieve XML from current node

Descrição

public XMLReader::readInnerXml(): string

Reads the contents of the current node, including child nodes and markup.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns the contents of the current node as a string. Empty string on failure.

Notas

Cuidado

Esta função só estará disponível quando o PHP for compilado com a libxml 20620 ou superior.

Veja Também

  • XMLReader::readString() - Reads the contents of the current node as a string
  • XMLReader::readOuterXml() - Retrieve XML from current node, including itself
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

User Contributed Notes

There are no user contributed notes for this page.


Retrieve XML from current node, including itself

  • « XMLReader::readInnerXml
  • XMLReader::readString »
  • PHP Manual
  • XMLReader
  • Retrieve XML from current node, including itself

XMLReader::readOuterXml

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

XMLReader::readOuterXml — Retrieve XML from current node, including itself

Descrição

public XMLReader::readOuterXml(): string

Reads the contents of the current node, including the node itself.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns the contents of current node, including itself, as a string. Empty string on failure.

Notas

Cuidado

Esta função só estará disponível quando o PHP for compilado com a libxml 20620 ou superior.

Veja Também

  • XMLReader::readString() - Reads the contents of the current node as a string
  • XMLReader::readInnerXml() - Retrieve XML from current node
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

User Contributed Notes

ralf dot horlebein at web dot de 21-Jul-2014 10:57
Please note that empty tags like <span></span> will be automatically converted to the short notation <span />.  This could cause trouble in some cases.
simon at avalon dot net dot nz 16-Mar-2011 04:35
Be aware that when you extract a piece of XML from a larger XML document using the readOuterXML() function, it tries to determine the namespaces (as defined in the original XML document) that apply to the new piece, and inserts them into the appropriate tags as xmlns attributes. This can be disconcerting, but it should be a benign alteration in most cases, and I understand that it causes the new chunk of XML to be correctly formatted so it is valid in it's own right.

As far as I'm aware it's not possible to change this behaviour.


Reads the contents of the current node as a string

  • « XMLReader::readOuterXml
  • XMLReader::setParserProperty »
  • PHP Manual
  • XMLReader
  • Reads the contents of the current node as a string

XMLReader::readString

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

XMLReader::readString — Reads the contents of the current node as a string

Descrição

public XMLReader::readString(): string

Reads the contents of the current node as a string.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns the content of the current node as a string. Empty string on failure.

Notas

Cuidado

Esta função só estará disponível quando o PHP for compilado com a libxml 20620 ou superior.

Veja Também

  • XMLReader::readOuterXml() - Retrieve XML from current node, including itself
  • XMLReader::readInnerXml() - Retrieve XML from current node
  • XMLReader::expand() - Returns a copy of the current node as a DOM object

User Contributed Notes

alexander_behling at web dot de 25-Jan-2018 03:37
Important:
When using it use -> instead of ::.
You have to use :: only on static functions and then you have not to create a class object.
Lea Hayes 07-Jun-2011 01:51
I would like to reiterate that this does not work when compiled with versions of libxml lower than 20620. I found that it just presents a blank page.

<?php $string = $reader->readString(); ?>

I worked around this issue by adding the following helper function:

<?php
function read_string($reader) {
    $node = $reader->expand();
    return $node->textContent;
}
?>

And then using:

<?php $string = read_string($reader); ?>
Michael Rusch 18-May-2009 10:27
For those who, like me, are having trouble figuring out the difference between getString() an getInnerXML(), the difference is that getString() does NOT include markup.  So, for:

<foo>bar<baz>Hello, world!</baz></foo>

getString() on the <foo> node would return

bar Hello, world!

whereas getInnerXML() would return

bar<baz>Hello, world!</baz>


Set parser options

  • « XMLReader::readString
  • XMLReader::setRelaxNGSchema »
  • PHP Manual
  • XMLReader
  • Set parser options

XMLReader::setParserProperty

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

XMLReader::setParserProperty — Set parser options

Descrição

public XMLReader::setParserProperty(int $property, bool $value): bool

Set parser options. The options must be set after
XMLReader::open() or
XMLReader::xml() are called and before
the first XMLReader::read() call.

Parâmetros

property

One of the parser option constants.

value

If set to true the option will be enabled otherwise will be disabled.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

User Contributed Notes

There are no user contributed notes for this page.


Set the filename or URI for a RelaxNG Schema

  • « XMLReader::setParserProperty
  • XMLReader::setRelaxNGSchemaSource »
  • PHP Manual
  • XMLReader
  • Set the filename or URI for a RelaxNG Schema

XMLReader::setRelaxNGSchema

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

XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema

Descrição

public XMLReader::setRelaxNGSchema(?string $filename): bool

Set the filename or URI for the RelaxNG Schema to use for validation.

Parâmetros

filename

filename or URI pointing to a RelaxNG Schema.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD
  • XMLReader::isValid() - Indicates if the parsed document is valid

User Contributed Notes

remy dot damour at laposte dot net 30-Dec-2008 04:40
Make sure to load your data prior to calling ->setRelaxNGSchema() otherwise you will get an error.

<?php
$xml_reader = new XMLReader();
$xml_reader->setRelaxNGSchema($rng_schema);
$xml_reader->xml($xml_data);
?>
Above code generates the following warning: "Warning: XMLReader::setRelaxNGSchemaSource()
[xmlreader.setrelaxngschemasource]: Unable to set schema. This must be
set prior to reading or schema contains errors."

whereas the following does not generate a warning:
<?php
$xml_reader = new XMLReader();
$xml_reader->xml($xml_data); // or $xml_reader->xml($xml_file);
$xml_reader->setRelaxNGSchema($rng_schema);
?>

cf. http://bugs.php.net/bug.php?id=46978


Set the data containing a RelaxNG Schema

  • « XMLReader::setRelaxNGSchema
  • XMLReader::setSchema »
  • PHP Manual
  • XMLReader
  • Set the data containing a RelaxNG Schema

XMLReader::setRelaxNGSchemaSource

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

XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema

Descrição

public XMLReader::setRelaxNGSchemaSource(?string $source): bool

Set the data containing a RelaxNG Schema to use for validation.

Parâmetros

source

String containing the RelaxNG Schema.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD
  • XMLReader::isValid() - Indicates if the parsed document is valid

User Contributed Notes

remy dot damour at laposte dot net 30-Dec-2008 04:43
If you get the following warning message when calling ->setRelaxNGSchemaSource(): "Warning: XMLReader::setRelaxNGSchemaSource()
[xmlreader.setrelaxngschemasource]: Unable to set schema. This must be
set prior to reading or schema contains errors."

Make sure to load data using XMLReader::open() or XMLReader::xml() prior to calling XMLReader::setRelaxNGSchemaSource().

Cf. comment on XMLReader::setRelaxNGSchema for more details.
anzenews at volja dot net 21-Jan-2008 12:18
This function and setRelaxNGSchema() seem picky about when they are called - right after the call to open(). For example:

<?php
  $schema="/path/to/schema.rng";
  $xmlfile="/path/to/xml.xml";

  $xml = new XMLReader();
  $xml->open($xmlfile);
  $xml->setRelaxNGSchemaSource(file_get_contents($schema));

  while ($xml->read()) {
   // ...
  }

  $xml->close();
?>


Validate document against XSD

  • « XMLReader::setRelaxNGSchemaSource
  • XMLReader::XML »
  • PHP Manual
  • XMLReader
  • Validate document against XSD

XMLReader::setSchema

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

XMLReader::setSchema — Validate document against XSD

Descrição

public XMLReader::setSchema(?string $filename): bool

Use W3C XSD schema to validate the document as it is processed. Activation is only possible before the first Read().

Parâmetros

filename

The filename of the XSD schema.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros

Issues E_WARNING if libxml was built without schema support, the schema contains errors or if XMLReader::read() has already been called.

Notas

Cuidado

Esta função só estará disponível quando o PHP for compilado com a libxml 20620 ou superior.

Veja Também

  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::isValid() - Indicates if the parsed document is valid

User Contributed Notes

There are no user contributed notes for this page.


Set the data containing the XML to parse

  • « XMLReader::setSchema
  • XMLWriter »
  • PHP Manual
  • XMLReader
  • Set the data containing the XML to parse

XMLReader::XML

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

XMLReader::XML — Set the data containing the XML to parse

Descrição

public static XMLReader::XML(string $source, ?string $encoding = null, int $flags = 0): bool|XMLReader

Set the data containing the XML to parse.

Parâmetros

source

String containing the XML to be parsed.

encoding

The document encoding or null.

flags

A bitmask of the LIBXML_* constants.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha. If called statically, returns an XMLReader ou false em caso de falha.

Erros

This method may be called statically, but prior to PHP 8.0.0, will issue an E_DEPRECATED error in this case.

Changelog

Versão | Descrição
8.0.0 | XMLReader::XML() is now declared as static method, but can still be called on an XMLReader instance.

Veja Também

  • XMLReader::open() - Set the URI containing the XML to parse
  • XMLReader::close() - Close the XMLReader input

User Contributed Notes

There are no user contributed notes for this page.


XMLWriter

  • Introdução
  • Instalação/Configuração
    • Dependências
    • Instalação
    • Configurações em Execução
    • Tipos de Recurso
  • Constantes pré-definidas
  • Exemplos
    • Creating a simple XML document
    • Working with XML namespaces
    • Working with the OO API
  • XMLWriter — The XMLWriter class
    • XMLWriter::endAttribute — End attribute
    • XMLWriter::endCdata — End current CDATA
    • XMLWriter::endComment — Create end comment
    • XMLWriter::endDocument — End current document
    • XMLWriter::endDtd — End current DTD
    • XMLWriter::endDtdAttlist — End current DTD AttList
    • XMLWriter::endDtdElement — End current DTD element
    • XMLWriter::endDtdEntity — End current DTD Entity
    • XMLWriter::endElement — End current element
    • XMLWriter::endPi — End current PI
    • XMLWriter::flush — Flush current buffer
    • XMLWriter::fullEndElement — End current element
    • XMLWriter::openMemory — Create new xmlwriter using memory for string output
    • XMLWriter::openUri — Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory — Returns current buffer
    • XMLWriter::setIndent — Toggle indentation on/off
    • XMLWriter::setIndentString — Set string used for indenting
    • XMLWriter::startAttribute — Create start attribute
    • XMLWriter::startAttributeNs — Create start namespaced attribute
    • XMLWriter::startCdata — Create start CDATA tag
    • XMLWriter::startComment — Create start comment
    • XMLWriter::startDocument — Create document tag
    • XMLWriter::startDtd — Create start DTD tag
    • XMLWriter::startDtdAttlist — Create start DTD AttList
    • XMLWriter::startDtdElement — Create start DTD element
    • XMLWriter::startDtdEntity — Create start DTD Entity
    • XMLWriter::startElement — Create start element tag
    • XMLWriter::startElementNs — Create start namespaced element tag
    • XMLWriter::startPi — Create start PI tag
    • XMLWriter::text — Write text
    • XMLWriter::writeAttribute — Write full attribute
    • XMLWriter::writeAttributeNs — Write full namespaced attribute
    • XMLWriter::writeCdata — Write full CDATA tag
    • XMLWriter::writeComment — Write full comment tag
    • XMLWriter::writeDtd — Write full DTD tag
    • XMLWriter::writeDtdAttlist — Write full DTD AttList tag
    • XMLWriter::writeDtdElement — Write full DTD element tag
    • XMLWriter::writeDtdEntity — Write full DTD Entity tag
    • XMLWriter::writeElement — Write full element tag
    • XMLWriter::writeElementNs — Write full namespaced element tag
    • XMLWriter::writePi — Writes a PI
    • XMLWriter::writeRaw — Write a raw XML text

User Contributed Notes

lingtalfi 08-Oct-2015 08:35
The single quote predefined entity is not escaped.
The other predefined entities are but not the single quote, so you will have to do it yourself.

That's what you would expect:

Ampersand     &     &amp;
Single Quote     '     &apos;
Double Quote     "     &quot;
Greater Than     >     &gt;
Less Than     <     &lt;

That's what you get with \XmlWriter:

Ampersand     &     &amp;
Single Quote     '     '
Double Quote     "     &quot;
Greater Than     >     &gt;
Less Than     <     &lt;
Alexey Zakhlestin 09-Jun-2008 03:47
important: XMLWriter expects UTF-8 data from you. It can output xml in various encodings, but input should be strictly utf-8!


Introdução

This is the XMLWriter extension. It wraps the libxml xmlWriter API.

This extension represents a writer that provides a non-cached, forward-only means of generating streams or files containing XML data.

This extension can be used in an object-oriented style or a procedural one. Every method documented describes the alternative procedural call.

User Contributed Notes

There are no user contributed notes for this page.


Instalação

The XMLWriter ships with PHP source. Esta extensão está habilitada por padrão. Ela pode ser desabilitada usando a seguinte opção em tempo de compilação: --disable-xmlwriter

User Contributed Notes

There are no user contributed notes for this page.


Tipos de Recurso

Prior to PHP 8.0.0, there was one resource type used by the procedural version of the XMLWriter extension: returned by xmlwriter_open_memory() or xmlwriter_open_uri().

User Contributed Notes

There are no user contributed notes for this page.


Exemplos

Índice

  • Creating a simple XML document
  • Working with XML namespaces
  • Working with the OO API

User Contributed Notes

There are no user contributed notes for this page.


Creating a simple XML document

This example shows how to use XMLWriter to create a XML document in memory.

Exemplo #1 Creating a simple XML document

<?php

$xw = xmlwriter_open_memory();
xmlwriter_set_indent($xw, 1);
$res = xmlwriter_set_indent_string($xw, ' ');

xmlwriter_start_document($xw, '1.0', 'UTF-8');

// A first element
xmlwriter_start_element($xw, 'tag1');

// Attribute 'att1' for element 'tag1'
xmlwriter_start_attribute($xw, 'att1');
xmlwriter_text($xw, 'valueofatt1');
xmlwriter_end_attribute($xw);

xmlwriter_write_comment($xw, 'this is a comment.');

// Start a child element
xmlwriter_start_element($xw, 'tag11');
xmlwriter_text($xw, 'This is a sample text, ä');
xmlwriter_end_element($xw); // tag11

xmlwriter_end_element($xw); // tag1

// CDATA
xmlwriter_start_element($xw, 'testc');
xmlwriter_write_cdata($xw, "This is cdata content");
xmlwriter_end_element($xw); // testc

xmlwriter_start_element($xw, 'testc');
xmlwriter_start_cdata($xw);
xmlwriter_text($xw, "test cdata2");
xmlwriter_end_cdata($xw);
xmlwriter_end_element($xw); // testc

// A processing instruction
xmlwriter_start_pi($xw, 'php');
xmlwriter_text($xw, '$foo=2;echo $foo;');
xmlwriter_end_pi($xw);

xmlwriter_end_document($xw);

echo xmlwriter_output_memory($xw);

O exemplo acima produzirá:

<?xml version="1.0" encoding="UTF-8"?>
<tag1 att1="valueofatt1">
 <!--this is a comment.-->
 <tag11>This is a sample text, ä</tag11>
</tag1>
<testc><![CDATA[This is cdata content]]></testc>
<testc><![CDATA[test cdata2]]></testc>
<?php $foo=2;echo $foo;?>

User Contributed Notes

There are no user contributed notes for this page.


Working with XML namespaces

This example shows how to create namespaced XML elements.

Exemplo #1 Working with XML namespaces

<?php

$xw = xmlwriter_open_memory();
xmlwriter_set_indent($xw, 1);
$res = xmlwriter_set_indent_string($xw, ' ');

xmlwriter_start_document($xw, '1.0', 'UTF-8');
// A first element
xmlwriter_start_element_ns($xw,'prefix', 'books', 'uri');
xmlwriter_start_attribute($xw, 'isbn');

xmlwriter_start_attribute_ns($xw, 'prefix', 'isbn', 'uri');
xmlwriter_end_attribute($xw);

xmlwriter_end_attribute($xw);

xmlwriter_text($xw, 'book1');
xmlwriter_end_element($xw);

xmlwriter_end_document($xw);

echo xmlwriter_output_memory($xw);

O exemplo acima produzirá:

<?xml version="1.0" encoding="UTF-8"?>
<prefix:books isbn="" prefix:isbn="" xmlns:prefix="uri">book1</prefix:books>

User Contributed Notes

There are no user contributed notes for this page.


Working with the OO API

This example shows how to work with XMLWriter's object-oriented API.

Exemplo #1 Working with the OO API

<?php

$xw = new XMLWriter();
$xw->openMemory();
$xw->startDocument("1.0");
$xw->startElement("book");
$xw->text("example");
$xw->endElement();
$xw->endDocument();
echo $xw->outputMemory();

O exemplo acima produzirá:

<?xml version="1.0"?>
<book>example</book>

User Contributed Notes

There are no user contributed notes for this page.


The XMLWriter class

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

Introdução

Sinopse da classe

class XMLWriter {
/* Métodos */
public endAttribute(): bool
public endCdata(): bool
public endComment(): bool
public endDocument(): bool
public endDtd(): bool
public endDtdAttlist(): bool
public endDtdElement(): bool
public endDtdEntity(): bool
public endElement(): bool
public endPi(): bool
public flush(bool $empty = true): string|int
public fullEndElement(): bool
public openMemory(): bool
public openUri(string $uri): bool
public outputMemory(bool $flush = true): string
public setIndent(bool $enable): bool
public setIndentString(string $indentation): bool
public startAttribute(string $name): bool
public startAttributeNs(?string $prefix, string $name, ?string $namespace): bool
public startCdata(): bool
public startComment(): bool
public startDocument(?string $version = "1.0", ?string $encoding = null, ?string $standalone = null): bool
public startDtd(string $qualifiedName, ?string $publicId = null, ?string $systemId = null): bool
public startDtdAttlist(string $name): bool
public startDtdElement(string $qualifiedName): bool
public startDtdEntity(string $name, bool $isParam): bool
public startElement(string $name): bool
public startElementNs(?string $prefix, string $name, ?string $namespace): bool
public startPi(string $target): bool
public text(string $content): bool
public writeAttribute(string $name, string $value): bool
public writeAttributeNs(
?string $prefix,
string $name,
?string $namespace,
string $value
): bool
public writeCdata(string $content): bool
public writeComment(string $content): bool
public writeDtd(
string $name,
?string $publicId = null,
?string $systemId = null,
?string $content = null
): bool
public writeDtdAttlist(string $name, string $content): bool
public writeDtdElement(string $name, string $content): bool
public writeDtdEntity(
string $name,
string $content,
bool $isParam = false,
?string $publicId = null,
?string $systemId = null,
?string $notationData = null
): bool
public writeElement(string $name, ?string $content = null): bool
public writeElementNs(
?string $prefix,
string $name,
?string $namespace,
?string $content = null
): bool
public writePi(string $target, string $content): bool
public writeRaw(string $content): bool
}

Índice

  • XMLWriter::endAttribute — End attribute
  • XMLWriter::endCdata — End current CDATA
  • XMLWriter::endComment — Create end comment
  • XMLWriter::endDocument — End current document
  • XMLWriter::endDtd — End current DTD
  • XMLWriter::endDtdAttlist — End current DTD AttList
  • XMLWriter::endDtdElement — End current DTD element
  • XMLWriter::endDtdEntity — End current DTD Entity
  • XMLWriter::endElement — End current element
  • XMLWriter::endPi — End current PI
  • XMLWriter::flush — Flush current buffer
  • XMLWriter::fullEndElement — End current element
  • XMLWriter::openMemory — Create new xmlwriter using memory for string output
  • XMLWriter::openUri — Create new xmlwriter using source uri for output
  • XMLWriter::outputMemory — Returns current buffer
  • XMLWriter::setIndent — Toggle indentation on/off
  • XMLWriter::setIndentString — Set string used for indenting
  • XMLWriter::startAttribute — Create start attribute
  • XMLWriter::startAttributeNs — Create start namespaced attribute
  • XMLWriter::startCdata — Create start CDATA tag
  • XMLWriter::startComment — Create start comment
  • XMLWriter::startDocument — Create document tag
  • XMLWriter::startDtd — Create start DTD tag
  • XMLWriter::startDtdAttlist — Create start DTD AttList
  • XMLWriter::startDtdElement — Create start DTD element
  • XMLWriter::startDtdEntity — Create start DTD Entity
  • XMLWriter::startElement — Create start element tag
  • XMLWriter::startElementNs — Create start namespaced element tag
  • XMLWriter::startPi — Create start PI tag
  • XMLWriter::text — Write text
  • XMLWriter::writeAttribute — Write full attribute
  • XMLWriter::writeAttributeNs — Write full namespaced attribute
  • XMLWriter::writeCdata — Write full CDATA tag
  • XMLWriter::writeComment — Write full comment tag
  • XMLWriter::writeDtd — Write full DTD tag
  • XMLWriter::writeDtdAttlist — Write full DTD AttList tag
  • XMLWriter::writeDtdElement — Write full DTD element tag
  • XMLWriter::writeDtdEntity — Write full DTD Entity tag
  • XMLWriter::writeElement — Write full element tag
  • XMLWriter::writeElementNs — Write full namespaced element tag
  • XMLWriter::writePi — Writes a PI
  • XMLWriter::writeRaw — Write a raw XML text

User Contributed Notes

There are no user contributed notes for this page.


End attribute

  • « XMLWriter
  • XMLWriter::endCdata »
  • PHP Manual
  • XMLWriter
  • End attribute

XMLWriter::endAttribute

xmlwriter_end_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endAttribute -- xmlwriter_end_attribute — End attribute

Descrição

Estilo orientado a objetos

public XMLWriter::endAttribute(): bool

Estilo procedural

xmlwriter_end_attribute(XMLWriter $writer): bool

Ends the current attribute.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


End current CDATA

  • « XMLWriter::endAttribute
  • XMLWriter::endComment »
  • PHP Manual
  • XMLWriter
  • End current CDATA

XMLWriter::endCdata

xmlwriter_end_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endCdata -- xmlwriter_end_cdata — End current CDATA

Descrição

Estilo orientado a objetos

public XMLWriter::endCdata(): bool

Estilo procedural

xmlwriter_end_cdata(XMLWriter $writer): bool

Ends the current CDATA section.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startCdata() - Create start CDATA tag
  • XMLWriter::writeCdata() - Write full CDATA tag

User Contributed Notes

There are no user contributed notes for this page.


Create end comment

  • « XMLWriter::endCdata
  • XMLWriter::endDocument »
  • PHP Manual
  • XMLWriter
  • Create end comment

XMLWriter::endComment

xmlwriter_end_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::endComment -- xmlwriter_end_comment — Create end comment

Descrição

Estilo orientado a objetos

public XMLWriter::endComment(): bool

Estilo procedural

xmlwriter_end_comment(XMLWriter $writer): bool

Ends the current comment.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::writeComment() - Write full comment tag

User Contributed Notes

There are no user contributed notes for this page.


End current document

  • « XMLWriter::endComment
  • XMLWriter::endDtd »
  • PHP Manual
  • XMLWriter
  • End current document

XMLWriter::endDocument

xmlwriter_end_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDocument -- xmlwriter_end_document — End current document

Descrição

Estilo orientado a objetos

public XMLWriter::endDocument(): bool

Estilo procedural

xmlwriter_end_document(XMLWriter $writer): bool

Ends the current document.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startDocument() - Create document tag

User Contributed Notes

Sbastien 13-Mar-2022 09:44
XMLWriter::endDocument() closes properly all remaining elements not yet closed.

Without XMLWriter::endDocument() :

<?php
$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->startDocument();
$xml->startElement('a');
$xml->startElement('b');
$xml->startElement('c');
$xml->startAttribute('foo');
exit;

/*
Outputs :
<?xml version="1.0"?>
<a><b><c foo="
*/
?>

With XMLWriter::endDocument() :

<?php
$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->startDocument();
$xml->startElement('a');
$xml->startElement('b');
$xml->startElement('c');
$xml->startAttribute('foo');
$xml->endDocument();
exit;

/*
Outputs :
<?xml version="1.0"?>
<a><b><c foo=""/></b></a>
*/
?>


End current DTD

  • « XMLWriter::endDocument
  • XMLWriter::endDtdAttlist »
  • PHP Manual
  • XMLWriter
  • End current DTD

XMLWriter::endDtd

xmlwriter_end_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtd -- xmlwriter_end_dtd — End current DTD

Descrição

Estilo orientado a objetos

public XMLWriter::endDtd(): bool

Estilo procedural

xmlwriter_end_dtd(XMLWriter $writer): bool

Ends the DTD of the document.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startDtd() - Create start DTD tag
  • XMLWriter::writeDtd() - Write full DTD tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD AttList

  • « XMLWriter::endDtd
  • XMLWriter::endDtdElement »
  • PHP Manual
  • XMLWriter
  • End current DTD AttList

XMLWriter::endDtdAttlist

xmlwriter_end_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdAttlist -- xmlwriter_end_dtd_attlist — End current DTD AttList

Descrição

Estilo orientado a objetos

public XMLWriter::endDtdAttlist(): bool

Estilo procedural

xmlwriter_end_dtd_attlist(XMLWriter $writer): bool

Ends the current DTD attribute list.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startDtdAttlist() - Create start DTD AttList
  • XMLWriter::writeDtdAttlist() - Write full DTD AttList tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD element

  • « XMLWriter::endDtdAttlist
  • XMLWriter::endDtdEntity »
  • PHP Manual
  • XMLWriter
  • End current DTD element

XMLWriter::endDtdElement

xmlwriter_end_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdElement -- xmlwriter_end_dtd_element — End current DTD element

Descrição

Estilo orientado a objetos

public XMLWriter::endDtdElement(): bool

Estilo procedural

xmlwriter_end_dtd_element(XMLWriter $writer): bool

Ends the current DTD element.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startDtdElement() - Create start DTD element
  • XMLWriter::writeDtdElement() - Write full DTD element tag

User Contributed Notes

There are no user contributed notes for this page.


End current DTD Entity

  • « XMLWriter::endDtdElement
  • XMLWriter::endElement »
  • PHP Manual
  • XMLWriter
  • End current DTD Entity

XMLWriter::endDtdEntity

xmlwriter_end_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdEntity -- xmlwriter_end_dtd_entity — End current DTD Entity

Descrição

Estilo orientado a objetos

public XMLWriter::endDtdEntity(): bool

Estilo procedural

xmlwriter_end_dtd_entity(XMLWriter $writer): bool

Ends the current DTD entity.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startDtdEntity() - Create start DTD Entity
  • XMLWriter::writeDtdEntity() - Write full DTD Entity tag

User Contributed Notes

There are no user contributed notes for this page.


End current element

  • « XMLWriter::endDtdEntity
  • XMLWriter::endPi »
  • PHP Manual
  • XMLWriter
  • End current element

XMLWriter::endElement

xmlwriter_end_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endElement -- xmlwriter_end_element — End current element

Descrição

Estilo orientado a objetos

public XMLWriter::endElement(): bool

Estilo procedural

xmlwriter_end_element(XMLWriter $writer): bool

Ends the current element.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


End current PI

  • « XMLWriter::endElement
  • XMLWriter::flush »
  • PHP Manual
  • XMLWriter
  • End current PI

XMLWriter::endPi

xmlwriter_end_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::endPi -- xmlwriter_end_pi — End current PI

Descrição

Estilo orientado a objetos

public XMLWriter::endPi(): bool

Estilo procedural

xmlwriter_end_pi(XMLWriter $writer): bool

Ends the current processing instruction.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startPi() - Create start PI tag
  • XMLWriter::writePi() - Writes a PI

User Contributed Notes

There are no user contributed notes for this page.


Flush current buffer

  • « XMLWriter::endPi
  • XMLWriter::fullEndElement »
  • PHP Manual
  • XMLWriter
  • Flush current buffer

XMLWriter::flush

xmlwriter_flush

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::flush -- xmlwriter_flush — Flush current buffer

Descrição

Estilo orientado a objetos

public XMLWriter::flush(bool $empty = true): string|int

Estilo procedural

xmlwriter_flush(XMLWriter $writer, bool $empty = true): string|int

Flushes the current buffer.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

empty

Whether to empty the buffer or not. Default is true.

Valor Retornado

If you opened the writer in memory, this function returns the generated XML buffer, Else, if using URI, this function will write the buffer and return the number of written bytes.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.
8.0.0 | This function can no longer return false.

User Contributed Notes

Sbastien 13-Mar-2022 09:29
XMLWriter::flush() basic usage with XMLWriter::openMemory() :

<?php
$xml = new XMLWriter();
$xml->openMemory();
$xml->startDocument();
$xml->writeElement('message', 'Hello World!');
$xml->endDocument();
echo $xml->flush();

/*
Produces :

<?xml version="1.0"?>
<message>Hello World!</message>
*/
?>


End current element

  • « XMLWriter::flush
  • XMLWriter::openMemory »
  • PHP Manual
  • XMLWriter
  • End current element

XMLWriter::fullEndElement

xmlwriter_full_end_element

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4)

XMLWriter::fullEndElement -- xmlwriter_full_end_element — End current element

Descrição

Estilo orientado a objetos

public XMLWriter::fullEndElement(): bool

Estilo procedural

xmlwriter_full_end_element(XMLWriter $writer): bool

End the current xml element. Writes an end tag even if the element is empty.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::endElement() - End current element

User Contributed Notes

There are no user contributed notes for this page.


Create new xmlwriter using memory for string output

  • « XMLWriter::fullEndElement
  • XMLWriter::openUri »
  • PHP Manual
  • XMLWriter
  • Create new xmlwriter using memory for string output

XMLWriter::openMemory

xmlwriter_open_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openMemory -- xmlwriter_open_memory — Create new xmlwriter using memory for string output

Descrição

Estilo orientado a objetos

public XMLWriter::openMemory(): bool

Estilo procedural

xmlwriter_open_memory(): XMLWriter|false

Creates a new XMLWriter using memory for string output.

Parâmetros

Valor Retornado

Estilo orientado a objetos: Retorna true em caso de sucesso ou false em caso de falha.

Estilo procedural: Returns a new XMLWriter for later use with the xmlwriter functions on success, ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | This function returns now an XMLWriter instance on success. Previouly, a resource has been returned in this case.

Veja Também

  • XMLWriter::openUri() - Create new xmlwriter using source uri for output

User Contributed Notes

There are no user contributed notes for this page.


Create new xmlwriter using source uri for output

  • « XMLWriter::openMemory
  • XMLWriter::outputMemory »
  • PHP Manual
  • XMLWriter
  • Create new xmlwriter using source uri for output

XMLWriter::openUri

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::openUri -- xmlwriter_open_uri — Create new xmlwriter using source uri for output

Descrição

Estilo orientado a objetos

public XMLWriter::openUri(string $uri): bool

Estilo procedural

xmlwriter_open_uri(string $uri): XMLWriter|false

Creates a new XMLWriter using uri for the output.

Parâmetros

uri

The URI of the resource for the output.

Valor Retornado

Estilo orientado a objetos: Retorna true em caso de sucesso ou false em caso de falha.

Estilo procedural: Returns a new XMLWriter instance for later use with the xmlwriter functions on success, ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | This function returns now an XMLWriter instance on success. Previouly, a resource has been returned in this case.

Exemplos

Exemplo #1 Direct output of XML

It is possible to directly output XML by using the php://output stream wrapper.

<?php
$out =new XMLWriter();
$out->openURI('php://output');
?>

Notas

Nota:

On Windows, files opened with this function are locked until the writer is released.

Veja Também

  • XMLWriter::openMemory() - Create new xmlwriter using memory for string output

User Contributed Notes

There are no user contributed notes for this page.


Returns current buffer

  • « XMLWriter::openUri
  • XMLWriter::setIndent »
  • PHP Manual
  • XMLWriter
  • Returns current buffer

XMLWriter::outputMemory

xmlwriter_output_memory

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::outputMemory -- xmlwriter_output_memory — Returns current buffer

Descrição

Estilo orientado a objetos

public XMLWriter::outputMemory(bool $flush = true): string

Estilo procedural

xmlwriter_output_memory(XMLWriter $writer, bool $flush = true): string

Returns the current buffer.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

flush

Whether to flush the output buffer or not. Default is true.

Valor Retornado

Returns the current buffer as a string.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::flush() - Flush current buffer

User Contributed Notes

There are no user contributed notes for this page.


Toggle indentation on/off

  • « XMLWriter::outputMemory
  • XMLWriter::setIndentString »
  • PHP Manual
  • XMLWriter
  • Toggle indentation on/off

XMLWriter::setIndent

xmlwriter_set_indent

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndent -- xmlwriter_set_indent — Toggle indentation on/off

Descrição

Estilo orientado a objetos

public XMLWriter::setIndent(bool $enable): bool

Estilo procedural

xmlwriter_set_indent(XMLWriter $writer, bool $enable): bool

Toggles indentation on or off.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

enable

Whether indentation is enabled.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Exemplos

Exemplo #1 XMLWriter::setIndent() and mixed Content

Enabling indentation is not suitable for mixed content, because the indent string is also inserted before inline elements.

<?php
$writer = new XMLWriter();
$writer->openMemory();
$writer->setIndent(2);
$writer->startDocument();
$writer->startElement('p');
$writer->text('before');
$writer->writeElement('a', 'element');
$writer->text('after');
$writer->endElement();
$writer->endDocument();
echo $writer->outputMemory();
?>

O exemplo acima produzirá:

<?xml version="1.0"?>
<p>before <a>element</a>
after</p>

Notas

Nota:

The indent is reset when an xmlwriter is opened.

Veja Também

  • XMLWriter::setIndentString() - Set string used for indenting

User Contributed Notes

info at ensostudio dot ru 04-Apr-2021 01:04
NOTE: $enable can be integer as in example, or boolean.


Set string used for indenting

  • « XMLWriter::setIndent
  • XMLWriter::startAttribute »
  • PHP Manual
  • XMLWriter
  • Set string used for indenting

XMLWriter::setIndentString

xmlwriter_set_indent_string

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndentString -- xmlwriter_set_indent_string — Set string used for indenting

Descrição

Estilo orientado a objetos

public XMLWriter::setIndentString(string $indentation): bool

Estilo procedural

xmlwriter_set_indent_string(XMLWriter $writer, string $indentation): bool

Sets the string which will be used to indent each element/attribute of the resulting xml.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

indentation

The indentation string.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Notas

Nota:

The indent is reset when an xmlwriter is opened.

Veja Também

  • XMLWriter::setIndent() - Toggle indentation on/off

User Contributed Notes

There are no user contributed notes for this page.


Create start attribute

  • « XMLWriter::setIndentString
  • XMLWriter::startAttributeNs »
  • PHP Manual
  • XMLWriter
  • Create start attribute

XMLWriter::startAttribute

xmlwriter_start_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttribute -- xmlwriter_start_attribute — Create start attribute

Descrição

Estilo orientado a objetos

public XMLWriter::startAttribute(string $name): bool

Estilo procedural

xmlwriter_start_attribute(XMLWriter $writer, string $name): bool

Starts an attribute.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

name

The attribute name.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Exemplos

Exemplo #1 Basic XMLWriter::startAttribute() Usage

<?php
$writer = new XMLWriter;
$writer->openURI('php://output');
$writer->startDocument('1.0', 'UTF-8');
$writer->startElement('element');
$writer->startAttribute('attribute');
$writer->text('value');
$writer->endAttribute();
$writer->endElement();
$writer->endDocument();

O exemplo acima produzirá algo semelhante a:

<?xml version="1.0" encoding="UTF-8"?>
<element attribute="value"/>

Veja Também

  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


Create start namespaced attribute

  • « XMLWriter::startAttribute
  • XMLWriter::startCdata »
  • PHP Manual
  • XMLWriter
  • Create start namespaced attribute

XMLWriter::startAttributeNs

xmlwriter_start_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttributeNs -- xmlwriter_start_attribute_ns — Create start namespaced attribute

Descrição

Estilo orientado a objetos

public XMLWriter::startAttributeNs(?string $prefix, string $name, ?string $namespace): bool

Estilo procedural

xmlwriter_start_attribute_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace
): bool

Starts a namespaced attribute.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

prefix

The namespace prefix.

name

The attribute name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.
8.0.0 | prefix is nullable now.

Veja Também

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute

User Contributed Notes

There are no user contributed notes for this page.


Create start CDATA tag

  • « XMLWriter::startAttributeNs
  • XMLWriter::startComment »
  • PHP Manual
  • XMLWriter
  • Create start CDATA tag

XMLWriter::startCdata

xmlwriter_start_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startCdata -- xmlwriter_start_cdata — Create start CDATA tag

Descrição

Estilo orientado a objetos

public XMLWriter::startCdata(): bool

Estilo procedural

xmlwriter_start_cdata(XMLWriter $writer): bool

Starts a CDATA.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::endCdata() - End current CDATA
  • XMLWriter::writeCdata() - Write full CDATA tag

User Contributed Notes

There are no user contributed notes for this page.


Create start comment

  • « XMLWriter::startCdata
  • XMLWriter::startDocument »
  • PHP Manual
  • XMLWriter
  • Create start comment

XMLWriter::startComment

xmlwriter_start_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)

XMLWriter::startComment -- xmlwriter_start_comment — Create start comment

Descrição

Estilo orientado a objetos

public XMLWriter::startComment(): bool

Estilo procedural

xmlwriter_start_comment(XMLWriter $writer): bool

Starts a comment.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::endComment() - Create end comment
  • XMLWriter::writeComment() - Write full comment tag

User Contributed Notes

There are no user contributed notes for this page.


Create document tag

  • « XMLWriter::startComment
  • XMLWriter::startDtd »
  • PHP Manual
  • XMLWriter
  • Create document tag

XMLWriter::startDocument

xmlwriter_start_document

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDocument -- xmlwriter_start_document — Create document tag

Descrição

Estilo orientado a objetos

public XMLWriter::startDocument(?string $version = "1.0", ?string $encoding = null, ?string $standalone = null): bool

Estilo procedural

xmlwriter_start_document(
XMLWriter $writer,
?string $version = "1.0",
?string $encoding = null,
?string $standalone = null
): bool

Starts a document.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

version

The version number of the document as part of the XML declaration.

encoding

The encoding of the document as part of the XML declaration.

standalone

yes or no.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::endDocument() - End current document

User Contributed Notes

Sbastien 13-Mar-2022 09:52
XMLWriter::startDocument() writes the XML declaration.

Without XMLWriter::startDocument() :

<?php

$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->writeElement('message', 'Hello World!');
exit;

/*
Outputs :
<message>Hello World!</message>
*/
?>

With XMLWriter::startDocument() :

<?php

$xml = new XMLWriter();
$xml->openUri('php://stdout');
$xml->startDocument();
$xml->writeElement('message', 'Hello World!');
exit;

/*
Outputs :
<?xml version="1.0"?>
<message>Hello World!</message>
*/
?>


Create start DTD tag

  • « XMLWriter::startDocument
  • XMLWriter::startDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Create start DTD tag

XMLWriter::startDtd

xmlwriter_start_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtd -- xmlwriter_start_dtd — Create start DTD tag

Descrição

Estilo orientado a objetos

public XMLWriter::startDtd(string $qualifiedName, ?string $publicId = null, ?string $systemId = null): bool

Estilo procedural

xmlwriter_start_dtd(
XMLWriter $writer,
string $qualifiedName,
?string $publicId = null,
?string $systemId = null
): bool

Starts a DTD.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::endDtd() - End current DTD
  • XMLWriter::writeDtd() - Write full DTD tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD AttList

  • « XMLWriter::startDtd
  • XMLWriter::startDtdElement »
  • PHP Manual
  • XMLWriter
  • Create start DTD AttList

XMLWriter::startDtdAttlist

xmlwriter_start_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdAttlist -- xmlwriter_start_dtd_attlist — Create start DTD AttList

Descrição

Estilo orientado a objetos

public XMLWriter::startDtdAttlist(string $name): bool

Estilo procedural

xmlwriter_start_dtd_attlist(XMLWriter $writer, string $name): bool

Starts a DTD attribute list.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

name

The attribute list name.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::endDtdAttlist() - End current DTD AttList
  • XMLWriter::writeDtdAttlist() - Write full DTD AttList tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD element

  • « XMLWriter::startDtdAttlist
  • XMLWriter::startDtdEntity »
  • PHP Manual
  • XMLWriter
  • Create start DTD element

XMLWriter::startDtdElement

xmlwriter_start_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdElement -- xmlwriter_start_dtd_element — Create start DTD element

Descrição

Estilo orientado a objetos

public XMLWriter::startDtdElement(string $qualifiedName): bool

Estilo procedural

xmlwriter_start_dtd_element(XMLWriter $writer, string $qualifiedName): bool

Starts a DTD element.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::endDtdElement() - End current DTD element
  • XMLWriter::writeDtdElement() - Write full DTD element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start DTD Entity

  • « XMLWriter::startDtdElement
  • XMLWriter::startElement »
  • PHP Manual
  • XMLWriter
  • Create start DTD Entity

XMLWriter::startDtdEntity

xmlwriter_start_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdEntity -- xmlwriter_start_dtd_entity — Create start DTD Entity

Descrição

Estilo orientado a objetos

public XMLWriter::startDtdEntity(string $name, bool $isParam): bool

Estilo procedural

xmlwriter_start_dtd_entity(XMLWriter $writer, string $name, bool $isParam): bool

Starts a DTD entity.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

name

The name of the entity.

isParam

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::endDtdEntity() - End current DTD Entity
  • XMLWriter::writeDtdEntity() - Write full DTD Entity tag

User Contributed Notes

There are no user contributed notes for this page.


Create start element tag

  • « XMLWriter::startDtdEntity
  • XMLWriter::startElementNs »
  • PHP Manual
  • XMLWriter
  • Create start element tag

XMLWriter::startElement

xmlwriter_start_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startElement -- xmlwriter_start_element — Create start element tag

Descrição

Estilo orientado a objetos

public XMLWriter::startElement(string $name): bool

Estilo procedural

xmlwriter_start_element(XMLWriter $writer, string $name): bool

Starts an element.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

name

The element name.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start namespaced element tag

  • « XMLWriter::startElement
  • XMLWriter::startPi »
  • PHP Manual
  • XMLWriter
  • Create start namespaced element tag

XMLWriter::startElementNs

xmlwriter_start_element_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startElementNs -- xmlwriter_start_element_ns — Create start namespaced element tag

Descrição

Estilo orientado a objetos

public XMLWriter::startElementNs(?string $prefix, string $name, ?string $namespace): bool

Estilo procedural

xmlwriter_start_element_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace
): bool

Starts a namespaced element.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The element name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNs() - Write full namespaced element tag

User Contributed Notes

There are no user contributed notes for this page.


Create start PI tag

  • « XMLWriter::startElementNs
  • XMLWriter::text »
  • PHP Manual
  • XMLWriter
  • Create start PI tag

XMLWriter::startPi

xmlwriter_start_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::startPi -- xmlwriter_start_pi — Create start PI tag

Descrição

Estilo orientado a objetos

public XMLWriter::startPi(string $target): bool

Estilo procedural

xmlwriter_start_pi(XMLWriter $writer, string $target): bool

Starts a processing instruction tag.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

target

The target of the processing instruction.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::endPi() - End current PI
  • XMLWriter::writePi() - Writes a PI

User Contributed Notes

There are no user contributed notes for this page.


Write text

  • « XMLWriter::startPi
  • XMLWriter::writeAttribute »
  • PHP Manual
  • XMLWriter
  • Write text

XMLWriter::text

xmlwriter_text

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::text -- xmlwriter_text — Write text

Descrição

Estilo orientado a objetos

public XMLWriter::text(string $content): bool

Estilo procedural

xmlwriter_text(XMLWriter $writer, string $content): bool

Writes a text.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

content

The contents of the text. The characters <, >, & and " are written as entity references (i.e. &lt;, &gt;, &amp; and &quot;, respectively). All other characters including ' are written literally. To write the special XML characters literally, or to write literal entity references, xmlwriter_write_raw() has to be used.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

User Contributed Notes

There are no user contributed notes for this page.


Write full attribute

  • « XMLWriter::text
  • XMLWriter::writeAttributeNs »
  • PHP Manual
  • XMLWriter
  • Write full attribute

XMLWriter::writeAttribute

xmlwriter_write_attribute

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttribute -- xmlwriter_write_attribute — Write full attribute

Descrição

Estilo orientado a objetos

public XMLWriter::writeAttribute(string $name, string $value): bool

Estilo procedural

xmlwriter_write_attribute(XMLWriter $writer, string $name, string $value): bool

Writes a full attribute.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

name

The name of the attribute.

value

The value of the attribute.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Exemplos

Exemplo #1 Intermixing Sub-elements and Attributes

If writing sub-elements and attributes is intermixed, any attempt to write attributes after the first sub-element will fail and return false.

<?php
$xml = new XMLWriter();
$xml->openMemory();

$xml->startElement('element');
$xml->writeAttribute('attr1', '0');
$xml->writeElement('subelem', '0');
var_dump($xml->writeAttribute('attr2', '0'));
$xml->endElement();

echo $xml->flush();
?>

O exemplo acima produzirá:

bool(false)
<element attr1="0"><subelem>0</subelem></element>

Veja Também

  • XMLWriter::writeAttributeNs() - Write full namespaced attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute

User Contributed Notes

There are no user contributed notes for this page.


Write full namespaced attribute

  • « XMLWriter::writeAttribute
  • XMLWriter::writeCdata »
  • PHP Manual
  • XMLWriter
  • Write full namespaced attribute

XMLWriter::writeAttributeNs

xmlwriter_write_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttributeNs -- xmlwriter_write_attribute_ns — Write full namespaced attribute

Descrição

Estilo orientado a objetos

public XMLWriter::writeAttributeNs(
?string $prefix,
string $name,
?string $namespace,
string $value
): bool

Estilo procedural

xmlwriter_write_attribute_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace,
string $value
): bool

Writes a full namespaced attribute.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The attribute name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

value

The attribute value.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute

User Contributed Notes

There are no user contributed notes for this page.


Write full CDATA tag

  • « XMLWriter::writeAttributeNs
  • XMLWriter::writeComment »
  • PHP Manual
  • XMLWriter
  • Write full CDATA tag

XMLWriter::writeCdata

xmlwriter_write_cdata

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeCdata -- xmlwriter_write_cdata — Write full CDATA tag

Descrição

Estilo orientado a objetos

public XMLWriter::writeCdata(string $content): bool

Estilo procedural

xmlwriter_write_cdata(XMLWriter $writer, string $content): bool

Writes a full CDATA.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

content

The contents of the CDATA.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Exemplos

Exemplo #1 Basic xmlwriter_write_cdata() Usage

<?php
// set up the document
$xml = new XmlWriter();
$xml->openMemory();
$xml->setIndent(true);
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('mydoc');
$xml->startElement('myele');

// CData output
$xml->startElement('mycdataelement');
$xml->writeCData("text for inclusion as CData");
$xml->endElement();

// end the document and output
$xml->endElement();
$xml->endElement();
echo $xml->outputMemory(true);
?>

O exemplo acima produzirá:

<mydoc>
 <myele>
  <mycdataelement><![CDATA[text for inclusion as CData]?]></mycdataelement>
 </myele>
</mydoc>

Veja Também

  • XMLWriter::startCdata() - Create start CDATA tag
  • XMLWriter::endCdata() - End current CDATA

User Contributed Notes

There are no user contributed notes for this page.


Write full comment tag

  • « XMLWriter::writeCdata
  • XMLWriter::writeDtd »
  • PHP Manual
  • XMLWriter
  • Write full comment tag

XMLWriter::writeComment

xmlwriter_write_comment

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeComment -- xmlwriter_write_comment — Write full comment tag

Descrição

Estilo orientado a objetos

public XMLWriter::writeComment(string $content): bool

Estilo procedural

xmlwriter_write_comment(XMLWriter $writer, string $content): bool

Writes a full comment.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

content

The contents of the comment.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::endComment() - Create end comment

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD tag

  • « XMLWriter::writeComment
  • XMLWriter::writeDtdAttlist »
  • PHP Manual
  • XMLWriter
  • Write full DTD tag

XMLWriter::writeDtd

xmlwriter_write_dtd

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtd -- xmlwriter_write_dtd — Write full DTD tag

Descrição

Estilo orientado a objetos

public XMLWriter::writeDtd(
string $name,
?string $publicId = null,
?string $systemId = null,
?string $content = null
): bool

Estilo procedural

xmlwriter_write_dtd(
XMLWriter $writer,
string $name,
?string $publicId = null,
?string $systemId = null,
?string $content = null
): bool

Writes a full DTD.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

name

The DTD name.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

content

The content of the DTD.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startDtd() - Create start DTD tag
  • XMLWriter::endDtd() - End current DTD

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD AttList tag

  • « XMLWriter::writeDtd
  • XMLWriter::writeDtdElement »
  • PHP Manual
  • XMLWriter
  • Write full DTD AttList tag

XMLWriter::writeDtdAttlist

xmlwriter_write_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdAttlist -- xmlwriter_write_dtd_attlist — Write full DTD AttList tag

Descrição

Estilo orientado a objetos

public XMLWriter::writeDtdAttlist(string $name, string $content): bool

Estilo procedural

xmlwriter_write_dtd_attlist(XMLWriter $writer, string $name, string $content): bool

Writes a DTD attribute list.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

name

The name of the DTD attribute list.

content

The content of the DTD attribute list.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startDtdAttlist() - Create start DTD AttList
  • XMLWriter::endDtdAttlist() - End current DTD AttList

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD element tag

  • « XMLWriter::writeDtdAttlist
  • XMLWriter::writeDtdEntity »
  • PHP Manual
  • XMLWriter
  • Write full DTD element tag

XMLWriter::writeDtdElement

xmlwriter_write_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdElement -- xmlwriter_write_dtd_element — Write full DTD element tag

Descrição

Estilo orientado a objetos

public XMLWriter::writeDtdElement(string $name, string $content): bool

Estilo procedural

xmlwriter_write_dtd_element(XMLWriter $writer, string $name, string $content): bool

Writes a full DTD element.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

name

The name of the DTD element.

content

The content of the element.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startDtdElement() - Create start DTD element
  • XMLWriter::endDtdElement() - End current DTD element

User Contributed Notes

There are no user contributed notes for this page.


Write full DTD Entity tag

  • « XMLWriter::writeDtdElement
  • XMLWriter::writeElement »
  • PHP Manual
  • XMLWriter
  • Write full DTD Entity tag

XMLWriter::writeDtdEntity

xmlwriter_write_dtd_entity

(PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdEntity -- xmlwriter_write_dtd_entity — Write full DTD Entity tag

Descrição

Estilo orientado a objetos

public XMLWriter::writeDtdEntity(
string $name,
string $content,
bool $isParam = false,
?string $publicId = null,
?string $systemId = null,
?string $notationData = null
): bool

Estilo procedural

xmlwriter_write_dtd_entity(
XMLWriter $writer,
string $name,
string $content,
bool $isParam = false,
?string $publicId = null,
?string $systemId = null,
?string $notationData = null
): bool

Writes a full DTD entity.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

name

The name of the entity.

content

The content of the entity.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.
8.0.0 | publicId, systemId and notationData are nullable now.

Veja Também

  • XMLWriter::startDtdEntity() - Create start DTD Entity
  • XMLWriter::endDtdEntity() - End current DTD Entity

User Contributed Notes

There are no user contributed notes for this page.


Write full element tag

  • « XMLWriter::writeDtdEntity
  • XMLWriter::writeElementNs »
  • PHP Manual
  • XMLWriter
  • Write full element tag

XMLWriter::writeElement

xmlwriter_write_element

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElement -- xmlwriter_write_element — Write full element tag

Descrição

Estilo orientado a objetos

public XMLWriter::writeElement(string $name, ?string $content = null): bool

Estilo procedural

xmlwriter_write_element(XMLWriter $writer, string $name, ?string $content = null): bool

Writes a full element tag.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

name

The element name.

content

The element contents.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNs() - Write full namespaced element tag

User Contributed Notes

There are no user contributed notes for this page.


Write full namespaced element tag

  • « XMLWriter::writeElement
  • XMLWriter::writePi »
  • PHP Manual
  • XMLWriter
  • Write full namespaced element tag

XMLWriter::writeElementNs

xmlwriter_write_element_ns

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElementNs -- xmlwriter_write_element_ns — Write full namespaced element tag

Descrição

Estilo orientado a objetos

public XMLWriter::writeElementNs(
?string $prefix,
string $name,
?string $namespace,
?string $content = null
): bool

Estilo procedural

xmlwriter_write_element_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace,
?string $content = null
): bool

Writes a full namespaced element tag.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

prefix

The namespace prefix. If prefix is null, the namespace will be omitted.

name

The element name.

namespace

The namespace URI. If namespace is null, the namespace declaration will be omitted.

content

The element contents.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startElementNs() - Create start namespaced element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag

User Contributed Notes

There are no user contributed notes for this page.


Writes a PI

  • « XMLWriter::writeElementNs
  • XMLWriter::writeRaw »
  • PHP Manual
  • XMLWriter
  • Writes a PI

XMLWriter::writePi

xmlwriter_write_pi

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)

XMLWriter::writePi -- xmlwriter_write_pi — Writes a PI

Descrição

Estilo orientado a objetos

public XMLWriter::writePi(string $target, string $content): bool

Estilo procedural

xmlwriter_write_pi(XMLWriter $writer, string $target, string $content): bool

Writes a processing instruction.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

target

The target of the processing instruction.

content

The content of the processing instruction.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::startPi() - Create start PI tag
  • XMLWriter::endPi() - End current PI

User Contributed Notes

There are no user contributed notes for this page.


Write a raw XML text

  • « XMLWriter::writePi
  • XSL »
  • PHP Manual
  • XMLWriter
  • Write a raw XML text

XMLWriter::writeRaw

xmlwriter_write_raw

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4)

XMLWriter::writeRaw -- xmlwriter_write_raw — Write a raw XML text

Descrição

Estilo orientado a objetos

public XMLWriter::writeRaw(string $content): bool

Estilo procedural

xmlwriter_write_raw(XMLWriter $writer, string $content): bool

Writes a raw xml text.

Parâmetros

writer

Apenas para chamadas procedurais. A instância de XMLWriter que está sendo modificada. Este objeto é retornado de uma chamada a xmlwriter_open_uri() ou xmlwriter_open_memory().

content

The text string to write.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Changelog

Versão | Descrição
8.0.0 | O parâmetro writer agora espera uma instância de XMLWriter; anteriormente, um resource era esperado.

Veja Também

  • XMLWriter::text() - Write text

User Contributed Notes

There are no user contributed notes for this page.


XSL

  • Introdução
  • Instalação/Configuração
    • Dependências
    • Instalação
    • Configurações em Execução
    • Tipos de Recurso
  • Constantes pré-definidas
  • Exemplos
    • Arquivos de exemplo collection.xml e collection.xsl
    • Tratamento de erros com funções de tratamento de erros libxml
  • XSLTProcessor — A classe XSLTProcessor
    • XSLTProcessor::__construct — Cria um novo objeto XSLTProcessor
    • XSLTProcessor::getParameter — Obtém o valor de um parâmetro
    • XSLTProcessor::getSecurityPrefs — Obtém as preferências de segurança
    • XSLTProcessor::hasExsltSupport — Verifica se o PHP tem suporte a EXSLT
    • XSLTProcessor::importStylesheet — Importa folha de estilos
    • XSLTProcessor::registerPHPFunctions — Habilita o uso de funções do PHP como funções XSLT
    • XSLTProcessor::removeParameter — Remove parâmetro
    • XSLTProcessor::setParameter — Define um valor para um parâmetro
    • XSLTProcessor::setProfiling — Define o arquivo de saída de perfil
    • XSLTProcessor::setSecurityPrefs — Define preferências de segurança
    • XSLTProcessor::transformToDoc — Transforma em um documento
    • XSLTProcessor::transformToURI — Transforma em URI
    • XSLTProcessor::transformToXml — Transforma em 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));
?>


Introdução

A extensão XSL implementa o padrão XSL, executando » transformações XSLT usando a » biblioteca libxslt

User Contributed Notes

There are no user contributed notes for this page.


Dependências

Esta extensão requer a extensão PHP libxml. Isso significa que ao compilar o PHP é preciso passar a flag de configuração --with-libxml, ou antes do PHP 7.4, --enable-libxml, embora isso seja feito implicitamente pois a libxml está habilitada por padrão.

Esta extensão usa libxslt que pode ser encontrada em » http://xmlsoft.org/XSLT/. Versão da libxslt 1.1.0 ou maior é requerido.

User Contributed Notes

There are no user contributed notes for this page.


Instalação

PHP inclue a extensão XSL por padrão e pode ser habilitada adicionando o argumento --with-xsl[=DIR] na linha de configuração DIR sendo o diretório da instalação da libxslt.

User Contributed Notes

There are no user contributed notes for this page.


Constantes pré-definidas

As contantes abaixo são definidas por esta extensão e só estarão disponíveis quando a extensão tiver sido compilada no PHP ou tiver sido carregada dinamicamente em tempo de execução.

XSL_CLONE_AUTO (int)
XSL_CLONE_NEVER (int)
XSL_CLONE_ALWAYS (int)
LIBXSLT_VERSION (int)
Versão da libxslt como 10117.
LIBXSLT_DOTTED_VERSION (string)
Versão da libxslt como 1.1.17.
LIBEXSLT_VERSION (int)
Versão da libexslt como 813.
LIBEXSLT_DOTTED_VERSION (string)
Versão da libexslt com 1.1.17.
XSL_SECPREF_NONE (int)
Desativa todas as restrições de segurança.
XSL_SECPREF_READ_FILE (int)
Não permite a leitura de arquivos.
XSL_SECPREF_WRITE_FILE (int)
Não permite gravação de arquivos.
XSL_SECPREF_CREATE_DIRECTORY (int)
Não permite a criação de diretórios.
XSL_SECPREF_READ_NETWORK (int)
Não permite a leitura de arquivos de rede.
XSL_SECPREF_WRITE_NETWORK (int)
Não permite a gravação de arquivos de rede.
XSL_SECPREF_DEFAULT (int)
Proíbe todo acesso de gravação, ou seja, uma 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.


Exemplos

Índice

  • Arquivos de exemplo collection.xml e collection.xsl
  • Tratamento de erros com funções de tratamento de erros libxml

User Contributed Notes

There are no user contributed notes for this page.


Arquivos de exemplo collection.xml e collection.xsl

Muitos exemplos nesta referência requerem um arquivo XML e um XSL. Serão usados os arquivos collection.xml e collection.xsl que contêm o seguinte:

Exemplo #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>

Exemplo #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.


Tratamento de erros com funções de tratamento de erros libxml

libxml oferece uma série de funções para tratamento de erros, que podem ser empregadas para capturar e lidar com erros no processamento XSLT.

Exemplo #1 fruits.xml

Um arquivo XML válido.

<fruits>
 <fruit>Apple</fruit>
 <fruit>Banana</fruit>
 <fruit>Cherry</fruit>
</fruits>

Exemplo #2 fruits.xsl

Contém uma expressão de seleção invá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>

Exemplo #3 Erros de agrupamento e impressão

O exemplo abaixo captura e exibe erros de libxml gerados ao chamar XSLTProcessor::importStyleSheet() com uma folha de estilo contendo um erro.

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

?>

O exemplo acima produzirá algo semelhante 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.


A classe XSLTProcessor

(PHP 5, PHP 7, PHP 8)

Introdução

Sinopse da classe

class XSLTProcessor {
/* Métodos */
public getParameter(string $namespace, string $name): string|false
public getSecurityPrefs(): int
public hasExsltSupport(): bool
public importStylesheet(object $stylesheet): bool
public registerPHPFunctions(array|string|null $functions = null): void
public removeParameter(string $namespace, string $name): bool
public setParameter(string $namespace, string $name, string $value): bool
public setParameter(string $namespace, array $options): bool
public setProfiling(?string $filename): true
public setSecurityPrefs(int $preferences): int
public transformToDoc(object $document, ?string $returnClass = null): object|false
public transformToUri(object $document, string $uri): int
public transformToXml(object $document): string|null|false
}

Índice

  • XSLTProcessor::__construct — Cria um novo objeto XSLTProcessor
  • XSLTProcessor::getParameter — Obtém o valor de um parâmetro
  • XSLTProcessor::getSecurityPrefs — Obtém as preferências de segurança
  • XSLTProcessor::hasExsltSupport — Verifica se o PHP tem suporte a EXSLT
  • XSLTProcessor::importStylesheet — Importa folha de estilos
  • XSLTProcessor::registerPHPFunctions — Habilita o uso de funções do PHP como funções XSLT
  • XSLTProcessor::removeParameter — Remove parâmetro
  • XSLTProcessor::setParameter — Define um valor para um parâmetro
  • XSLTProcessor::setProfiling — Define o arquivo de saída de perfil
  • XSLTProcessor::setSecurityPrefs — Define preferências de segurança
  • XSLTProcessor::transformToDoc — Transforma em um documento
  • XSLTProcessor::transformToURI — Transforma em URI
  • XSLTProcessor::transformToXml — Transforma em 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


Cria um novo objeto XSLTProcessor

  • « XSLTProcessor
  • XSLTProcessor::getParameter »
  • PHP Manual
  • XSLTProcessor
  • Cria um novo objeto XSLTProcessor

XSLTProcessor::__construct

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::__construct — Cria um novo objeto XSLTProcessor

Descrição

XSLTProcessor::__construct()

Cria um novo objeto XSLTProcessor.

Parâmetros

Esta função não possui parâmetros.

Exemplos

Exemplo #1 Criando um 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.


Obtém o valor de um parâmetro

  • « XSLTProcessor::__construct
  • XSLTProcessor::getSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Obtém o valor de um parâmetro

XSLTProcessor::getParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::getParameter — Obtém o valor de um parâmetro

Descrição

public XSLTProcessor::getParameter(string $namespace, string $name): string|false

Obtém um parâmetro se anteriormente definido por XSLTProcessor::setParameter().

Parâmetros

namespace

O namespace URI do parâmetro XSLT.

name

O nome local do parâmetro XSLT.

Valor Retornado

O valor do parâmetro (em string), ou false se não estiver definido.

Veja Também

  • XSLTProcessor::setParameter() - Define um valor para um parâmetro
  • XSLTProcessor::removeParameter() - Remove parâmetro

User Contributed Notes

There are no user contributed notes for this page.


Obtém as preferências de segurança

  • « XSLTProcessor::getParameter
  • XSLTProcessor::hasExsltSupport »
  • PHP Manual
  • XSLTProcessor
  • Obtém as preferências de segurança

XSLTProcessor::getSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::getSecurityPrefs — Obtém as preferências de segurança

Descrição

public XSLTProcessor::getSecurityPrefs(): int

Obtém as preferências de segurança.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Uma máscara de bits consistindo da combinação de XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK e XSL_SECPREF_WRITE_NETWORK.

User Contributed Notes

There are no user contributed notes for this page.


Verifica se o PHP tem suporte a EXSLT

  • « XSLTProcessor::getSecurityPrefs
  • XSLTProcessor::importStylesheet »
  • PHP Manual
  • XSLTProcessor
  • Verifica se o PHP tem suporte a EXSLT

XSLTProcessor::hasExsltSupport

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

XSLTProcessor::hasExsltSupport — Verifica se o PHP tem suporte a EXSLT

Descrição

public XSLTProcessor::hasExsltSupport(): bool

Este método verifica se o PHP foi construído com a » biblioteca EXSLT.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Exemplos

Exemplo #1 Testando o suporte a EXSLT

<?php

$proc = new XSLTProcessor;
if (!$proc->hasExsltSupport()) {
die('EXSLT support not available');
}

// trabalhar com EXSLT a partir daqui ..

?>

User Contributed Notes

There are no user contributed notes for this page.


Importa folha de estilos

  • « XSLTProcessor::hasExsltSupport
  • XSLTProcessor::registerPHPFunctions »
  • PHP Manual
  • XSLTProcessor
  • Importa folha de estilos

XSLTProcessor::importStylesheet

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::importStylesheet — Importa folha de estilos

Descrição

public XSLTProcessor::importStylesheet(object $stylesheet): bool

Este método importa a folha de estilos no XSLTProcessor para transformações.

Parâmetros

stylesheet

A folha de estilos importada como um objeto DOMDocument ou SimpleXMLElement.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

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!


Habilita o uso de funções do PHP como funções XSLT

  • « XSLTProcessor::importStylesheet
  • XSLTProcessor::removeParameter »
  • PHP Manual
  • XSLTProcessor
  • Habilita o uso de funções do PHP como funções XSLT

XSLTProcessor::registerPHPFunctions

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

XSLTProcessor::registerPHPFunctions — Habilita o uso de funções do PHP como funções XSLT

Descrição

public XSLTProcessor::registerPHPFunctions(array|string|null $functions = null): void

Este método habilita o uso de funções PHP como funções XSLT nas folhas de estilo XSL.

Parâmetros

functions

Use este parâmetro para permitir que apenas certas funções sejam chamadas a partir do XSLT.

Este parâmetro pode ser uma string (nome de função) ou um array de funções.

Valor Retornado

Nenhum valor é retornado.

Exemplos

Exemplo #1 Simples chamada de função do PHP a partir de uma folha 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 = new DOMDocument();
$xmldoc->loadXML($xml);
$xsldoc = new DOMDocument();
$xsldoc->loadXML($xsl);

$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML($xmldoc);
?>

User Contributed Notes

Matthew, info at mathias-schaefer dot de 25-Nov-2010 08:34
=> there is no instance of your class needed, you have to take care about the namespace (using 5.3).

<!-- xsl:
<xsl:value-of select="php:function ('My\Name\Space\MyClassName::methodName',1+2)"/>
--->

<?php
namespace My\Name\Space;

   class MyClassName
   {
      static public function methodName($someArgument)
      {
         return "resultis:".$someArgument;
      }
   }
?>

<!-- result:
resultis:3
-->

=> no to-string conversion of the argument needed
=> returning numbers is also possible (maybe DOM nodes too)

Keep on hackin'
Demerit 10-Aug-2010 07:58
Let's get the terminology correct here, folks.

If you are calling a function that is residing within a class, reference it by its INSTANCE name, NOT its class name.

class.my_class.php:

<?php
class class_name {
static function function_name($in){
return ($out);
}
}
?>

calling_document.php:

<?php
require_once('class.my_class.php');
$instance_name=new class_name();
?>

my_xslt.xsl:

<xsl:value-of select="php:function ('instance_name::function_name','garbage')" />

BTW, in 5.1.6 double-colon (::) is the only thing that works when calling a function that resides within a class. However, you must declare your function as static. Using -> as some have suggested (e.g., php:function ('instance_name->function_name','garbage')) doesn't work at all, no matter how you declare your function.
Nic Luciano 22-Jul-2009 11:09
Ritch said "If you wish to use a function from inside a class use the double colon (::) notation..."

Also note that the class function must be declared as static.
Ariz Jacinto 08-Jul-2008 02:21
If you want to use replace() function similar to XPath 2.0[1]  and you want to avoid a long XSLT function similar to this one[2], you can use PHP's str_replace() instead:

   <xsl:value-of select="php:functionString('str_replace','pattern', 'replacement' , . )">

Links:
  [1] http://www.w3.org/TR/2004/WD-xpath-functions-20041029/#func-replace
  [2] http://aspn.activestate.com/ASPN/Cookbook/XSLT/Recipe/65426

_
thsoft at vipmail dot hu 27-Dec-2007 02:22
Unfortunately, you can't pass arrays to PHP from XLST.
But you can pass an arbitrary number of arguments to a PHP function and then get them with func_get_args() as an array.
[There's no sense writing a function that is identical to the array() construct, because a function's return value is converted to a string when passed as an argument to another function. This means deep arrays cannot be handled this way.]
thsoft at vipmail dot hu 31-Jan-2007 03:20
The correct way to receive DOM nodes (let it be element, document, document fragment etc.) returned from PHP is to use <xsl:copy-of select="php:function...

I found the idea and an example here: http://bugs.php.net/bug.php?id=29409

For the technical details about the reason, see http://www.w3.org/TR/xslt#copy-of
phil at worldpoolfederation dot com 01-Dec-2006 03:22
Not true

Use :: to call static functions
Use -> to call non static functions

You must define a function as static in php 5.1 to be able to call it statically.
mark at thirst dot org 10-Oct-2006 07:25
Ritch said "If you wish to use a function from inside a class use the double colon (::) notation..."   This worked in 5.0.4 but no longer works in 5.1.6.
franp at free dot fr 02-Sep-2006 01:45
Note that if you want your output to validate against some xhtml dtd, you must add the following attribute to the xsl:stylesheet element of the xslt stylesheet :
exclude-result-prefixes="php".

Otherwise, you get an "invalid attribute xmlns:php" error.
taylorbarstow at that google mail thingy 26-May-2006 05:33
Add-on to my previous note (below) about returning nodesets to XSLT from PHP functions:

You don't have to return a DOMDocument, DOMElement works just as well.  Plus, retuning a DOMElement gets around the problem of discarding the root node which I discuss below and which is also touched on by "Ingram".
heinemann dot juergen at hjcms dot de 08-Mar-2006 02:23
You can find mor Examples at PHP Sources php-5.*/ext/xsl/tests
<?php

$xform = <<<EOT
<?xml version = '1.0' encoding = 'utf-8' ?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:php="http://php.net/xsl"
    xsl:extension-element-prefixes="php"
>
<xsl:output method="xml" indent="yes" encoding="utf-8" />
<xsl:namespace-alias stylesheet-prefix="php" result-prefix="xsl" />
<xsl:template match="root">
<html>
<head>
    <title>Dateformat</title>
</head>
<body>
<xsl:for-each select="datenode">
    <li>
        <xsl:value-of select="php:functionString('convertDate', . )" />
    </li>
    </xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
EOT;

function convertDate( $i )
{
    setlocale( LC_TIME, 'de_DE' );
    return utf8_encode( strftime( '%B %d %A %Y %H:%M:%S CET', $i ) );
}

$xsl = new XSLTProcessor;
$xsl->registerPHPFunctions();
$xsl->setParameter( 'DOCTYPE', 'PUBLIC', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd' );
$xsl->setParameter( 'html', 'xmlns', 'http://www.w3.org/1999/xhtml' );

$xdom = new DomDocument( '1.0', 'utf-8' );
$xdom->loadXML( $xform );

$xsl->importStyleSheet( $xdom );
unset( $xdom );

$dom = new DomDocument( '1.0', 'utf-8' );
$r = $dom->appendChild( $dom->createElement( 'root' ) );
foreach ( range( 1, 12 ) AS $i ) {
    $r->appendChild( $dom->createElement( 'datenode', mktime( date('G'), date('i'), date('s'), $i, date('d'), date('Y') ) ) );
}

header( "Content-Type: text/html; CHARSET=Windows-1252;" );
header( "Content-Encoding: utf-8" );
echo $xsl->transformToXML( $dom );

?>
Ingram 28-Feb-2006 12:33
Upon testing returning of a nodeset contributed by

taylorbarstow at that google mail thingy

(which works excellently, TY!)

I found that with using:

===
"Presumably, it's worth creating a template to do the discard:

<xsl:template select="*" mode="discardRoot">
   <xsl:apply-templates select="./*" />
</xsl:template>

Which you can call like so:

<xsl:apply-templates select="php:function('getNodeSet')" mode="discardRoot" /> "
===

I could only output the text and not any of the tags after applying templates - i.e. it stripped all elements around text.

Instead using:

===
<xsl:template match="/">
   <xsl:for-each select="php:function('getNodeSet')" />
     <xsl:apply-templates />
   </xsl:for-each>
</xsl:template>

which effectively discards the root node.
===

Worked fine and allowed me to apply-templates without problem on the returned nodeset.
hopeseekr at gmail dot com 01-Feb-2006 12:17
One of the peskiest things I had problems with was encoding URL parameters.  I mean, pretend you want to populate a link with "search+terms" instead of just "search terms".  I was including two seperate URLs in the XML and that was ludicrous.

Below is a far more elegant PHP+XSLT solution.  You will also see it uses two *undocumented* features of registerPHPFunctions(), namely php:functionString() and the passing of parameters to the function.  I figured this out by trial and error; I really hope this note helps you as it *greatly* expands the power of php functions in XSLT!

<?php
/* --- XML input --- */
<search_results>
   <query>concert tickets</query>
</search_results>

/* --- XSL code --- */
<!-- Display query -->
<xsl:template match="search_results">
   <!-- Get URL-encoded string via PHP -->
   <xsl:variable name="safeurl" as="xs:string" select="php:functionString('urlencode', query)" />
   <p>Your search for <em><xsl:value-of select="query"/></em> can be continued at <a href="http://www.tixtix.com/search.php?q={$safeurl}">our search engine</a></p>
</xsl:template>

/* --- XHTML output --- */
<p>Your search for <em>concert tickets</em> can be continued at <a href="http://www.tixtix.com/search.php?q=space+cowboy">our search engine</a></p>
?>

Cool, huh?
taylorbarstow at that google mail thingy 01-Dec-2005 07:14
From a PHP function, you can pass a nodeset back to XSL using a DOMDocument.  For example:

<?php

function getNodeSet() {
   $xml =
       "<test>" .
       "<a-node>This is a node</a-node>" .
       "<a-node>This is another node</a-node>" .
       "</test>";
   $doc = new DOMDocument;
   $doc->loadXml($xml);
   return $doc;
}

?>

The only problem I've found is that the root level node in your returned DOM document acts like the root level node of your original.   SO, it's easy to introduce an infinite loop like so:

<xsl:template match="/">
   <xsl:apply-templates select="php:function('getNodeSet')" />
</xsl:template>

To avoid this, I've been using a construct like:

<xsl:template match="/">
   <xsl:for-each select="php:function('getNodeSet')" />
      <xsl:apply-templates />
   </xsl:for-each>
</xsl:template>

which effectively discards the root node.  Presumably, it's worth creating a template to do the discard:

<xsl:template select="*" mode="discardRoot">
   <xsl:apply-templates select="./*" />
</xsl:template>

Which you can call like so:

<xsl:apply-templates select="php:function('getNodeSet')" mode="discardRoot" />
Ritch at Bugsoftware dot co dot uk 22-Jun-2005 03:18
If you wish to use a function from inside a class use the double colon (::) notation, for example;

php:functionString('classname::function')

The funtion is fired off as a static and as such acts like a function in the global namespace.
benbarnett 04-Mar-2005 04:34
You can use the php:functionString() in the XSL, which will automatically convert output to a string!
zac at zacbowling dot com 27-Oct-2004 01:48
One thing I have told a lot of people to do if they are having
issues with this function is to check for any 'xmlns' attributes
that get generated and added to your xml pages by some
types of popular software.

<?php
$file = "http://data.map***.net/m***ck.asmx/GetMessages?IMEI=$id";

$docxml = file_get_contents($file);

//You may have to do something like this where
//I remove any instance of xmlns tags that get
//returned by my ASP.NET SOAP responses.

$docxml =
 str_replace("xmlns=\"http://data.map***.net/m***ck.asmx?WSDL\"",
  "",$docxml);

$xslt = new xsltProcessor;

//You don't remove them then this function will blow up.
$xslt->registerPHPFunctions();
$xslt->importStyleSheet(DomDocument::load('../xsl/message.xsl'));
print $xslt->transformToXML(DomDocument::loadXML($docxml));

?>

Also a few cool tricks with this function is that you can call
built in PHP functions. For example:

<xsl:value-of
  select="php:function('nl2br',string(MessageContent/Message))"
  disable-output-escaping="yes"/>

That XSL value will now return your normal string but replace
all your new line charactors in your xml with '<br />'s.

Also note the 'disable-output-escaping="yes"' statement. If
you don't call this, then the output of that bind will be ran
thru basicly a "htmlencode()" type function.

Last but not least, take a look at the 'string()' function I
called in XSL before passing it back. That is because without
calling that, when it runs it will try and pass the node object,
and not its value (which is what you most likely only want).

This function is very awsome and could lead to some very
interesting code development. Skins could be loaded
remotely. You could write an RSS viewer in PHP without much
code. You could parse XHTML pages into another view (either
localy or remotely). Then you can take that same XML
content and throw it against ASP.NET, Java, or even a
command line processing tool using that same exact XSL
style sheet and generate the front ends for you page without
much change. I'm very excited.

Happy codding.
junkmail at eighteyes dot com 08-Oct-2004 02:52
When writing a stylesheet that uses a callback function be sure to include a namespace declaration for php, as follows:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:php="http://php.net/xsl" version='1.0'>
begemot at php dot com dot ua 28-Sep-2004 06:24
I think it help  your.
<?php

function dateLang () {
        return strftime("%A");
}

$xsl = new DomDocument();
$xsl->load("datetime.xsl");
$inputdom = new DomDocument();
$inputdom->load("today.xml");

$proc = new XsltProcessor();
$proc->registerPhpFunctions();

// Load the documents and process using $xslt
$xsl = $proc->importStylesheet($xsl);

/* transform and output the xml document */
$newdom = $proc->transformToDoc($inputdom);

print $newdom->saveXML();

?>

Here's the XSLT stylesheet, datetime.xsl, that will call that function:

<?xml version="1.0" encoding="iso-8859-1" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl">
<xsl:template match="/">
  <xsl:value-of select="php:function('dateLang')" />
</xsl:template>
</xsl:stylesheet>

And here's an absolute minimal XML file, today.xml, to pass through the stylesheet (although articles.xml would achieve the same result):

<?xml version="1.0" encoding="iso-8859-1" ?>
<today></today>
zac at zacbowling dot com 26-Aug-2004 09:48
One thing to note about this function. A lot of values need to be converted to a XSLT string using the "string()" function in XLS before you pass them to your functions, and when you return them make sure that if they are strings that you call the "strval()" in php before doing so. This saved me hours.

Hope that helps.

Zac Bowling


Remove parâmetro

  • « XSLTProcessor::registerPHPFunctions
  • XSLTProcessor::setParameter »
  • PHP Manual
  • XSLTProcessor
  • Remove parâmetro

XSLTProcessor::removeParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::removeParameter — Remove parâmetro

Descrição

public XSLTProcessor::removeParameter(string $namespace, string $name): bool

Remove um parâmetro, se definido. Isto irá fazer o processador usar o valor padrão para o parâmetro como especificado no stylesheet.

Parâmetros

namespace

A URI de espaço de nomes do parâmetro XSLT.

name

O nome local do parâmetro XSLT.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Veja Também

  • XSLTProcessor::setParameter() - Define um valor para um parâmetro
  • XSLTProcessor::getParameter() - Obtém o valor de um parâmetro

User Contributed Notes

There are no user contributed notes for this page.


Define um valor para um parâmetro

  • « XSLTProcessor::removeParameter
  • XSLTProcessor::setProfiling »
  • PHP Manual
  • XSLTProcessor
  • Define um valor para um parâmetro

XSLTProcessor::setParameter

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::setParameter — Define um valor para um parâmetro

Descrição

public XSLTProcessor::setParameter(string $namespace, string $name, string $value): bool
public XSLTProcessor::setParameter(string $namespace, array $options): bool

Define o valor para um ou mais parâmetros para ser usados em transformações subsequentes com XSLTProcessor. Se o parâmetro não existir na folha de estilos, ele será ignorado.

Parâmetros

namespace

A URI de espaço de nomes do parâmetro XSLT.

name

O nome local do parâmetro XSLT.

value

O novo valor do parâmetro XSLT.

options

Um array de pares name => value.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Exemplos

Exemplo #1 Modificando o parâmetro 'owner' antes da transformação

<?php

$collections = array(
'Marc Rutkowski' => 'marc',
'Olivier Parmentier' => 'olivier'
);

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configura o transformador
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // anexa as regras xsl

foreach ($collections as $name => $file) {
// Carrega a fonte XML
$xml = new DOMDocument;
$xml->load('collection_' . $file . '.xml');

$proc->setParameter('', 'owner', $name);
$proc->transformToURI($xml, 'file:///tmp/' . $file . '.html');
}

?>

Veja Também

  • XSLTProcessor::getParameter() - Obtém o valor de um parâmetro
  • XSLTProcessor::removeParameter() - Remove 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.


Define o arquivo de saída de perfil

  • « XSLTProcessor::setParameter
  • XSLTProcessor::setSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Define o arquivo de saída de perfil

XSLTProcessor::setProfiling

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

XSLTProcessor::setProfiling — Define o arquivo de saída de perfil

Descrição

public XSLTProcessor::setProfiling(?string $filename): true

Define o arquivo para o qual serão gravadas informações de perfil ao processar uma folha de estilos.

Parâmetros

filename

Caminho para o arquivo onde serão gravadas as informações de perfil.

Valor Retornado

Sempre retorna true.

Exemplos

Exemplo #1 Exemplo de saída de perfil

<?php
// Carrega a fonte XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configura o transformador
$proc = new XSLTProcessor;
$proc->setProfiling('profiling.txt');
$proc->importStyleSheet($xsl); // anexa as regras xsl

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);
?>

O código acima produzirá as seguintes informações no arquivo de perfil:

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.


Define preferências de segurança

  • « XSLTProcessor::setProfiling
  • XSLTProcessor::transformToDoc »
  • PHP Manual
  • XSLTProcessor
  • Define preferências de segurança

XSLTProcessor::setSecurityPrefs

(PHP >= 5.4.0, PHP 7, PHP 8)

XSLTProcessor::setSecurityPrefs — Define preferências de segurança

Descrição

public XSLTProcessor::setSecurityPrefs(int $preferences): int

Define as preferências de segurança.

Parâmetros

preferences

As novas preferências de segurança. As constantes seguidas podem ser unidas pela operação binária OR: XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK e XSL_SECPREF_WRITE_NETWORK. Alternativamente, XSL_SECPREF_NONE ou XSL_SECPREF_DEFAULT podem ser passadas.

Valor Retornado

Retorna as preferências de segurança antigas..

User Contributed Notes

There are no user contributed notes for this page.


Transforma em um documento

  • « XSLTProcessor::setSecurityPrefs
  • XSLTProcessor::transformToURI »
  • PHP Manual
  • XSLTProcessor
  • Transforma em um documento

XSLTProcessor::transformToDoc

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToDoc — Transforma em um documento

Descrição

public XSLTProcessor::transformToDoc(object $document, ?string $returnClass = null): object|false

Transforma o nó de origem em um documento (ex.: DOMDocument) aplicando a folha de estilos fornecida pelo método XSLTProcessor::importStylesheet().

Parâmetros

document

O objeto DOMDocument, SimpleXMLElement, ou outro compatível com libxml a ser transformado.

returnClass

Este parâmetro opcional pode ser usado para que XSLTProcessor::transformToDoc() retorne um objeto da classe especificada. Esta classe deve estender ou ser da mesma classe de document.

Valor Retornado

O documento resultante ou false em caso de erro.

Exemplos

Exemplo #1 Transformando em um DOMDocument

<?php

// Carrega a fonte XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configura o transformador
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // anexa as regras xsl

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

O exemplo acima produzirá:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

Veja Também

  • XSLTProcessor::transformToUri() - Transforma em URI
  • XSLTProcessor::transformToXml() - Transforma em 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.


Transforma em URI

  • « XSLTProcessor::transformToDoc
  • XSLTProcessor::transformToXml »
  • PHP Manual
  • XSLTProcessor
  • Transforma em URI

XSLTProcessor::transformToURI

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToURI — Transforma em URI

Descrição

public XSLTProcessor::transformToUri(object $document, string $uri): int

Transforma o nó de origem em uma URI aplicando a folha de estilos fornecida pelo método XSLTProcessor::importStylesheet().

Parâmetros

document

O objeto DOMDocument ou SimpleXMLElement a ser transformado.

uri

A URI alvo para a transformação.

Valor Retornado

Retorna o número de bytes escritos ou false se um erro ocorrer.

Exemplos

Exemplo #1 Transformando em um arquivo HTML

<?php

// Carrega a fonte XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configura o transformador
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // anexa as regras xsl

$proc->transformToURI($xml, 'file:///tmp/out.html');

?>

Veja Também

  • XSLTProcessor::transformToDoc() - Transforma em um documento
  • XSLTProcessor::transformToXml() - Transforma em 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 em XML

  • « XSLTProcessor::transformToURI
  • Extensões GUI »
  • PHP Manual
  • XSLTProcessor
  • Transforma em XML

XSLTProcessor::transformToXml

(PHP 5, PHP 7, PHP 8)

XSLTProcessor::transformToXml — Transforma em XML

Descrição

public XSLTProcessor::transformToXml(object $document): string|null|false

Transforma o nó de origem em uma string aplicando a folha de estilos fornecida pelo método xsltprocessor::importStylesheet().

Parâmetros

document

O objeto DOMDocument ou SimpleXMLElement a ser transformado.

Valor Retornado

O resultado da transformação como uma string ou false em caso de erro.

Exemplos

Exemplo #1 Transformando em uma string

<?php

// Carrega a fonte XML
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configura o transformador
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // anexa as regras xsl

echo $proc->transformToXML($xml);

?>

O exemplo acima produzirá:

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>

Veja Também

  • XSLTProcessor::transformToDoc() - Transforma em um documento
  • XSLTProcessor::transformToUri() - Transforma em 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.


Extensões GUI

  • UI
    • Introdução
    • Instalação/Configuração
    • 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 Funções
    • 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

  • Introdução
  • Instalação/Configuração
    • Dependências
    • Instalação
  • UI\Point — Represents a position (x,y)
    • UI\Point::at — Size Coercion
    • UI\Point::__construct — Construct a new Point
    • UI\Point::getX — Retrieves X
    • UI\Point::getY — Retrieves Y
    • UI\Point::setX — Set X
    • UI\Point::setY — Set Y
  • UI\Size — Represents dimensions (width, height)
    • UI\Size::__construct — Construct a new Size
    • UI\Size::getHeight — Retrieves Height
    • UI\Size::getWidth — Retrives Width
    • UI\Size::of — Point Coercion
    • UI\Size::setHeight — Set Height
    • UI\Size::setWidth — Set Width
  • UI\Window — Window
    • UI\Window::add — Add a Control
    • UI\Window::__construct — Construct a new Window
    • UI\Window::error — Show Error Box
    • UI\Window::getSize — Get Window Size
    • UI\Window::getTitle — Get Title
    • UI\Window::hasBorders — Border Detection
    • UI\Window::hasMargin — Margin Detection
    • UI\Window::isFullScreen — Full Screen Detection
    • UI\Window::msg — Show Message Box
    • UI\Window::onClosing — Closing Callback
    • UI\Window::open — Open Dialog
    • UI\Window::save — Save Dialog
    • UI\Window::setBorders — Border Use
    • UI\Window::setFullScreen — Full Screen Use
    • UI\Window::setMargin — Margin Use
    • UI\Window::setSize — Set Size
    • UI\Window::setTitle — Window Title
  • UI\Control — Control
    • UI\Control::destroy — Destroy Control
    • UI\Control::disable — Disable Control
    • UI\Control::enable — Enable Control
    • UI\Control::getParent — Get Parent Control
    • UI\Control::getTopLevel — Get Top Level
    • UI\Control::hide — Hide Control
    • UI\Control::isEnabled — Determine if Control is enabled
    • UI\Control::isVisible — Determine if Control is visible
    • UI\Control::setParent — Set Parent Control
    • UI\Control::show — Control Show
  • UI\Menu — Menu
    • UI\Menu::append — Append Menu Item
    • UI\Menu::appendAbout — Append About Menu Item
    • UI\Menu::appendCheck — Append Checkable Menu Item
    • UI\Menu::appendPreferences — Append Preferences Menu Item
    • UI\Menu::appendQuit — Append Quit Menu Item
    • UI\Menu::appendSeparator — Append Menu Item Separator
    • UI\Menu::__construct — Construct a new Menu
  • UI\MenuItem — Menu Item
    • UI\MenuItem::disable — Disable Menu Item
    • UI\MenuItem::enable — Enable Menu Item
    • UI\MenuItem::isChecked — Detect Checked
    • UI\MenuItem::onClick — On Click Callback
    • UI\MenuItem::setChecked — Set Checked
  • UI\Area — Area
    • UI\Area::onDraw — Draw Callback
    • UI\Area::onKey — Key Callback
    • UI\Area::onMouse — Mouse Callback
    • UI\Area::redraw — Redraw Area
    • UI\Area::scrollTo — Area Scroll
    • UI\Area::setSize — Set Size
  • UI\Executor — Execution Scheduler
    • UI\Executor::__construct — Construct a new Executor
    • UI\Executor::kill — Stop Executor
    • UI\Executor::onExecute — Execution Callback
    • UI\Executor::setInterval — Interval Manipulation
  • UI\Controls\Tab — Tab Control
    • UI\Controls\Tab::append — Append Page
    • UI\Controls\Tab::delete — Delete Page
    • UI\Controls\Tab::hasMargin — Margin Detection
    • UI\Controls\Tab::insertAt — Insert Page
    • UI\Controls\Tab::pages — Page Count
    • UI\Controls\Tab::setMargin — Set Margin
  • UI\Controls\Check — Check Control
    • UI\Controls\Check::__construct — Construct a new Check
    • UI\Controls\Check::getText — Get Text
    • UI\Controls\Check::isChecked — Checked Detection
    • UI\Controls\Check::onToggle — Toggle Callback
    • UI\Controls\Check::setChecked — Set Checked
    • UI\Controls\Check::setText — Set Text
  • UI\Controls\Button — Button Control
    • UI\Controls\Button::__construct — Construct a new Button
    • UI\Controls\Button::getText — Get Text
    • UI\Controls\Button::onClick — Click Handler
    • UI\Controls\Button::setText — Set Text
  • UI\Controls\ColorButton — ColorButton Control
    • UI\Controls\ColorButton::getColor — Get Color
    • UI\Controls\ColorButton::onChange — Change Handler
    • UI\Controls\ColorButton::setColor — Set Color
  • UI\Controls\Label — Label Control
    • UI\Controls\Label::__construct — Construct a new Label
    • UI\Controls\Label::getText — Get Text
    • UI\Controls\Label::setText — Set Text
  • UI\Controls\Entry — Entry Control
    • UI\Controls\Entry::__construct — Construct a new Entry
    • UI\Controls\Entry::getText — Get Text
    • UI\Controls\Entry::isReadOnly — Detect Read Only
    • UI\Controls\Entry::onChange — Change Handler
    • UI\Controls\Entry::setReadOnly — Set Read Only
    • UI\Controls\Entry::setText — Set Text
  • UI\Controls\MultilineEntry — MultilineEntry Control
    • UI\Controls\MultilineEntry::append — Append Text
    • UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry
    • UI\Controls\MultilineEntry::getText — Get Text
    • UI\Controls\MultilineEntry::isReadOnly — Read Only Detection
    • UI\Controls\MultilineEntry::onChange — Change Handler
    • UI\Controls\MultilineEntry::setReadOnly — Set Read Only
    • UI\Controls\MultilineEntry::setText — Set Text
  • UI\Controls\Spin — Spin Control
    • UI\Controls\Spin::__construct — Construct a new Spin
    • UI\Controls\Spin::getValue — Get Value
    • UI\Controls\Spin::onChange — Change Handler
    • UI\Controls\Spin::setValue — Set Value
  • UI\Controls\Slider — Slider Control
    • UI\Controls\Slider::__construct — Construct a new Slider
    • UI\Controls\Slider::getValue — Get Value
    • UI\Controls\Slider::onChange — Change Handler
    • UI\Controls\Slider::setValue — Set Value
  • UI\Controls\Progress — Progress Control
    • UI\Controls\Progress::getValue — Get Value
    • UI\Controls\Progress::setValue — Set Value
  • UI\Controls\Separator — Control Separator
    • UI\Controls\Separator::__construct — Construct a new Separator
  • UI\Controls\Combo — Combo Control
    • UI\Controls\Combo::append — Append Option
    • UI\Controls\Combo::getSelected — Get Selected Option
    • UI\Controls\Combo::onSelected — Selected Handler
    • UI\Controls\Combo::setSelected — Set Selected Option
  • UI\Controls\EditableCombo — EdiableCombo Control
    • UI\Controls\EditableCombo::append — Append Option
    • UI\Controls\EditableCombo::getText — Get Text
    • UI\Controls\EditableCombo::onChange — Change Handler
    • UI\Controls\EditableCombo::setText — Set Text
  • UI\Controls\Radio — Radio Control
    • UI\Controls\Radio::append — Append Option
    • UI\Controls\Radio::getSelected — Get Selected Option
    • UI\Controls\Radio::onSelected — Selected Handler
    • UI\Controls\Radio::setSelected — Set Selected Option
  • UI\Controls\Picker — Picker Control
    • UI\Controls\Picker::__construct — Construct a new Picker
  • UI\Controls\Form — Control Form (Arrangement)
    • UI\Controls\Form::append — Append Control
    • UI\Controls\Form::delete — Delete Control
    • UI\Controls\Form::isPadded — Padding Detection
    • UI\Controls\Form::setPadded — Set Padding
  • UI\Controls\Grid — Control Grid (Arrangement)
    • UI\Controls\Grid::append — Append Control
    • UI\Controls\Grid::isPadded — Padding Detection
    • UI\Controls\Grid::setPadded — Set Padding
  • UI\Controls\Group — Control Group (Arrangement)
    • UI\Controls\Group::append — Append Control
    • UI\Controls\Group::__construct — Construct a new Group
    • UI\Controls\Group::getTitle — Get Title
    • UI\Controls\Group::hasMargin — Margin Detection
    • UI\Controls\Group::setMargin — Set Margin
    • UI\Controls\Group::setTitle — Set Title
  • UI\Controls\Box — Control Box (Arrangement)
    • UI\Controls\Box::append — Append Control
    • UI\Controls\Box::__construct — Construct a new Box
    • UI\Controls\Box::delete — Delete Control
    • UI\Controls\Box::getOrientation — Get Orientation
    • UI\Controls\Box::isPadded — Padding Detection
    • UI\Controls\Box::setPadded — Set Padding
  • UI\Draw\Pen — Draw Pen
    • UI\Draw\Pen::clip — Clip a Path
    • UI\Draw\Pen::fill — Fill a Path
    • UI\Draw\Pen::restore — Restore
    • UI\Draw\Pen::save — Save
    • UI\Draw\Pen::stroke — Stroke a Path
    • UI\Draw\Pen::transform — Matrix Transform
    • UI\Draw\Pen::write — Draw Text at Point
  • UI\Draw\Path — Draw Path
    • UI\Draw\Path::addRectangle — Draw a Rectangle
    • UI\Draw\Path::arcTo — Draw an Arc
    • UI\Draw\Path::bezierTo — Draw Bezier Curve
    • UI\Draw\Path::closeFigure — Close Figure
    • UI\Draw\Path::__construct — Construct a new Path
    • UI\Draw\Path::end — Finalize Path
    • UI\Draw\Path::lineTo — Draw a Line
    • UI\Draw\Path::newFigure — Draw Figure
    • UI\Draw\Path::newFigureWithArc — Draw Figure with Arc
  • UI\Draw\Matrix — Draw Matrix
    • UI\Draw\Matrix::invert — Invert Matrix
    • UI\Draw\Matrix::isInvertible — Invertible Detection
    • UI\Draw\Matrix::multiply — Multiply Matrix
    • UI\Draw\Matrix::rotate — Rotate Matrix
    • UI\Draw\Matrix::scale — Scale Matrix
    • UI\Draw\Matrix::skew — Skew Matrix
    • UI\Draw\Matrix::translate — Translate Matrix
  • UI\Draw\Color — Color Representation
    • UI\Draw\Color::__construct — Construct new Color
    • UI\Draw\Color::getChannel — Color Manipulation
    • UI\Draw\Color::setChannel — Color Manipulation
  • UI\Draw\Stroke — Draw Stroke
    • UI\Draw\Stroke::__construct — Construct a new Stroke
    • UI\Draw\Stroke::getCap — Get Line Cap
    • UI\Draw\Stroke::getJoin — Get Line Join
    • UI\Draw\Stroke::getMiterLimit — Get Miter Limit
    • UI\Draw\Stroke::getThickness — Get Thickness
    • UI\Draw\Stroke::setCap — Set Line Cap
    • UI\Draw\Stroke::setJoin — Set Line Join
    • UI\Draw\Stroke::setMiterLimit — Set Miter Limit
    • UI\Draw\Stroke::setThickness — Set Thickness
  • UI\Draw\Brush — Brushes
    • UI\Draw\Brush::__construct — Construct a new Brush
    • UI\Draw\Brush::getColor — Get Color
    • UI\Draw\Brush::setColor — Set Color
  • UI\Draw\Brush\Gradient — Gradient Brushes
    • UI\Draw\Brush\Gradient::addStop — Stop Manipulation
    • UI\Draw\Brush\Gradient::delStop — Stop Manipulation
    • UI\Draw\Brush\Gradient::setStop — Stop Manipulation
  • UI\Draw\Brush\LinearGradient — Linear Gradient
    • UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient
  • UI\Draw\Brush\RadialGradient — Radial Gradient
    • UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient
  • UI\Draw\Text\Layout — Represents Text Layout
    • UI\Draw\Text\Layout::__construct — Construct a new Text Layout
    • UI\Draw\Text\Layout::setColor — Set Color
    • UI\Draw\Text\Layout::setWidth — Set Width
  • UI\Draw\Text\Font — Represents a Font
    • UI\Draw\Text\Font::__construct — Construct a new Font
    • UI\Draw\Text\Font::getAscent — Font Metrics
    • UI\Draw\Text\Font::getDescent — Font Metrics
    • UI\Draw\Text\Font::getLeading — Font Metrics
    • UI\Draw\Text\Font::getUnderlinePosition — Font Metrics
    • UI\Draw\Text\Font::getUnderlineThickness — Font Metrics
  • UI\Draw\Text\Font\Descriptor — Font Descriptor
    • UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor
    • UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family
    • UI\Draw\Text\Font\Descriptor::getItalic — Style Detection
    • UI\Draw\Text\Font\Descriptor::getSize — Size Detection
    • UI\Draw\Text\Font\Descriptor::getStretch — Style Detection
    • UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection
  • UI Funções
    • UI\Draw\Text\Font\fontFamilies — Retrieve Font Families
    • UI\quit — Quit UI Loop
    • UI\run — Enter UI Loop
  • UI\Draw\Text\Font\Weight — Font Weight Settings
  • UI\Draw\Text\Font\Italic — Italic Font Settings
  • UI\Draw\Text\Font\Stretch — Font Stretch Settings
  • UI\Draw\Line\Cap — Line Cap Settings
  • UI\Draw\Line\Join — Line Join Settings
  • UI\Key — Key Identifiers
  • UI\Exception\InvalidArgumentException — InvalidArgumentException
  • UI\Exception\RuntimeException — RuntimeException

User Contributed Notes

There are no user contributed notes for this page.


Introdução

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.


Instalação/Configuração

Índice

  • Dependências
  • Instalação

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


Dependências

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.


Instalação

Esta extensão » PECL não é distribuída com o PHP.

Informações para instalar esta extensão PECL podem ser encontradas no capítulo Instalação de Extensões PECL do manual. Informações adicionais, como novas versões, downloads, arquivos fontes, informações do mantenedor e um CHANGELOG, podem ser encontradas aqui: » https://pecl.php.net/package/ui.

Binários do Windows (arquivos DLL) para esta extensão PECL estão disponíveis no site do PECL.

User Contributed Notes

There are no user contributed notes for this page.


Represents a position (x,y)

(UI 0.9.9)

Introdução

Points are used throughout UI to represent co-ordinates on a screen, control, or area.

Sinopse da classe

final class UI\Point {
/* Propriedades */
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)
}

Propriedades

x

Holds the X co-ordinate, can be read/written directly

y

Holds the Y co-ordinate, can be read/written directly

Índice

  • UI\Point::at — Size Coercion
  • UI\Point::__construct — Construct a new Point
  • UI\Point::getX — Retrieves X
  • UI\Point::getY — Retrieves Y
  • UI\Point::setX — Set X
  • UI\Point::setY — Set Y

User Contributed Notes

There are no user contributed notes for this page.


Size Coercion

  • « UI\Point
  • UI\Point::__construct »
  • PHP Manual
  • UI\Point
  • Size Coercion

UI\Point::at

(UI 1.0.2)

UI\Point::at — Size Coercion

Descrição

public static UI\Point::at(float $point): UI\Point
public static UI\Point::at(UI\Size $size): UI\Point

Shall return a UI\Point object where x and y are equal to those supplied, either in float or UI\Size form

Parâmetros

point

The value for x and y

size

The Size to convert

Valor Retornado

The resulting Point

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Point

  • « UI\Point::at
  • UI\Point::getX »
  • PHP Manual
  • UI\Point
  • Construct a new Point

UI\Point::__construct

(UI 0.9.9)

UI\Point::__construct — Construct a new Point

Descrição

public UI\Point::__construct(float $x, float $y)

Construct a new Point using new co-ordinates

Parâmetros

x

The new X co-ordinate

y

The new Y co-ordinate

User Contributed Notes

There are no user contributed notes for this page.


Retrieves X

  • « UI\Point::__construct
  • UI\Point::getY »
  • PHP Manual
  • UI\Point
  • Retrieves X

UI\Point::getX

(UI 0.9.9)

UI\Point::getX — Retrieves X

Descrição

public UI\Point::getX(): float

Retrieves the X co-ordinate

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

The current X co-ordinate

User Contributed Notes

There are no user contributed notes for this page.


Retrieves Y

  • « UI\Point::getX
  • UI\Point::setX »
  • PHP Manual
  • UI\Point
  • Retrieves Y

UI\Point::getY

(UI 0.9.9)

UI\Point::getY — Retrieves Y

Descrição

public UI\Point::getY(): float

Retrieves the Y co-ordinate

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

The current Y co-ordinate

User Contributed Notes

There are no user contributed notes for this page.


Set X

  • « UI\Point::getY
  • UI\Point::setY »
  • PHP Manual
  • UI\Point
  • Set X

UI\Point::setX

(UI 0.9.9)

UI\Point::setX — Set X

Descrição

public UI\Point::setX(float $point)

Set the X co-ordinate

Parâmetros

point

The new X co-ordinate

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Set Y

  • « UI\Point::setX
  • UI\Size »
  • PHP Manual
  • UI\Point
  • Set Y

UI\Point::setY

(UI 0.9.9)

UI\Point::setY — Set Y

Descrição

public UI\Point::setY(float $point)

Set the Y co-ordinate

Parâmetros

point

The new Y co-ordinate

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Represents dimensions (width, height)

(UI 0.9.9)

Introdução

Sizes are used throughout UI to represent the size of a screen, control, or area.

Sinopse da classe

final class UI\Size {
/* Propriedades */
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)
}

Propriedades

width

Holds the width, can be read/written directly

height

Holds the height, can be read/written directly

Índice

  • UI\Size::__construct — Construct a new Size
  • UI\Size::getHeight — Retrieves Height
  • UI\Size::getWidth — Retrives Width
  • UI\Size::of — Point Coercion
  • UI\Size::setHeight — Set Height
  • UI\Size::setWidth — Set Width

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Size

  • « UI\Size
  • UI\Size::getHeight »
  • PHP Manual
  • UI\Size
  • Construct a new Size

UI\Size::__construct

(UI 0.9.9)

UI\Size::__construct — Construct a new Size

Descrição

public UI\Size::__construct(float $width, float $height)

Construct a new Size using new width and height

Parâmetros

width

The new width

height

The new height

User Contributed Notes

There are no user contributed notes for this page.


Retrieves Height

  • « UI\Size::__construct
  • UI\Size::getWidth »
  • PHP Manual
  • UI\Size
  • Retrieves Height

UI\Size::getHeight

(UI 0.9.9)

UI\Size::getHeight — Retrieves Height

Descrição

public UI\Size::getHeight(): float

Retrieves the Height

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

The current Height

User Contributed Notes

There are no user contributed notes for this page.


Retrives Width

  • « UI\Size::getHeight
  • UI\Size::of »
  • PHP Manual
  • UI\Size
  • Retrives Width

UI\Size::getWidth

(UI 0.9.9)

UI\Size::getWidth — Retrives Width

Descrição

public UI\Size::getWidth(): float

Retrieves the Width

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

The current Width

User Contributed Notes

There are no user contributed notes for this page.


Point Coercion

  • « UI\Size::getWidth
  • UI\Size::setHeight »
  • PHP Manual
  • UI\Size
  • Point Coercion

UI\Size::of

(UI 1.0.2)

UI\Size::of — Point Coercion

Descrição

public static UI\Size::of(float $size): UI\Size
public static UI\Size::of(UI\Point $point): UI\Size

Shall return a UI\Size object where width and height are equal to those supplied, either in float or UI\Point form

Parâmetros

size

The value for width and height

point

The Point to convert

Valor Retornado

The resulting Size

User Contributed Notes

There are no user contributed notes for this page.


Set Height

  • « UI\Size::of
  • UI\Size::setWidth »
  • PHP Manual
  • UI\Size
  • Set Height

UI\Size::setHeight

(UI 0.9.9)

UI\Size::setHeight — Set Height

Descrição

public UI\Size::setHeight(float $size)

Set new Height

Parâmetros

size

The new Height

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Set Width

  • « UI\Size::setHeight
  • UI\Window »
  • PHP Manual
  • UI\Size
  • Set Width

UI\Size::setWidth

(UI 0.9.9)

UI\Size::setWidth — Set Width

Descrição

public UI\Size::setWidth(float $size)

Set new Width

Parâmetros

size

The new Width

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Window

(UI 0.9.9)

Introdução

Represents a UI Window

Sinopse da classe

class UI\Window extends UI\Control {
/* Propriedades */
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 herdados */
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()
}

Propriedades

controls

Contains controls, should not be manipulated directly

Índice

  • UI\Window::add — Add a Control
  • UI\Window::__construct — Construct a new Window
  • UI\Window::error — Show Error Box
  • UI\Window::getSize — Get Window Size
  • UI\Window::getTitle — Get Title
  • UI\Window::hasBorders — Border Detection
  • UI\Window::hasMargin — Margin Detection
  • UI\Window::isFullScreen — Full Screen Detection
  • UI\Window::msg — Show Message Box
  • UI\Window::onClosing — Closing Callback
  • UI\Window::open — Open Dialog
  • UI\Window::save — Save Dialog
  • UI\Window::setBorders — Border Use
  • UI\Window::setFullScreen — Full Screen Use
  • UI\Window::setMargin — Margin Use
  • UI\Window::setSize — Set Size
  • UI\Window::setTitle — Window Title

User Contributed Notes

everton3x at gmail dot com 03-Feb-2017 12:58
This is a example to wizard layout in UI library:

<?php

/*
 * Wizard sample layout builded with PHP UI
 */

use UI\Window;
use UI\Size;
use UI\Controls\Button;
use UI\Controls\Grid;
use UI\Controls\Box;
use UI\Controls\Form;
use UI\Controls\Entry;
use UI\Controls\Label;

/*
 * The window
 */
$window = new Window('Wizard Sample Layout', new Size(640, 480), TRUE);
$window->setMargin(true);

/*
 * Wizard content (sample)
 */
$content = new Form();
$content->setPadded(true);
$content->append('User:', new Entry());
$content->append('Password:', new Entry(Entry::Password));

/*
 * Layout to title, content and buttons
 */
$grid = new Grid();
$grid->setPadded(false);

/*
 * Title
 */
$grid->append(new Label('Wizard Sample'), 0, 0, 6, 1, true, Grid::Fill, false, Grid::Fill);

/*
 * Append content
 */
$grid->append($content, 0, 1, 6, 1, false, Grid::Fill, true, Grid::Fill);

/*
 * Left buttons
 */
$left_box = new Box(Box::Horizontal);
$left_box->append(new Button('&About'));
$left_box->append(new Button('&Help'));

/*
 * Right buttons
 */
$right_box = new Box(Box::Horizontal);
$right_box->append(new Button('&Back'));
$right_box->append(new Button('&Forward'));
$right_box->append(new Button('&Close'));

/**
 * Append buttons
 */
$grid->append($left_box, 0, 2, 1, 1, true, Grid::Start, false, Grid::Fill);
$grid->append($right_box, 5, 2, 1, 1, true, Grid::End, false, Grid::Fill);

/*
 * Append layout and show.
 */
$window->add($grid);

$window->show();

UI\run();

?>


Add a Control

  • « UI\Window
  • UI\Window::__construct »
  • PHP Manual
  • UI\Window
  • Add a Control

UI\Window::add

(UI 0.9.9)

UI\Window::add — Add a Control

Descrição

public UI\Window::add(UI\Control $control)

Shall add a Control to this Window

Parâmetros

control

The Control to add

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Window

  • « UI\Window::add
  • UI\Window::error »
  • PHP Manual
  • UI\Window
  • Construct a new Window

UI\Window::__construct

(UI 0.9.9)

UI\Window::__construct — Construct a new Window

Descrição

public UI\Window::__construct(string $title, Size $size, bool $menu = false)

Shall construct a new Window

Parâmetros

title

The title of the Window

size

The size of the Window

menu

Menu switch

User Contributed Notes

There are no user contributed notes for this page.


Show Error Box

  • « UI\Window::__construct
  • UI\Window::getSize »
  • PHP Manual
  • UI\Window
  • Show Error Box

UI\Window::error

(UI 0.9.9)

UI\Window::error — Show Error Box

Descrição

public UI\Window::error(string $title, string $msg)

Shall show an error box

Parâmetros

title

The title of the error box

msg

The message for the error box

User Contributed Notes

There are no user contributed notes for this page.


Get Window Size

  • « UI\Window::error
  • UI\Window::getTitle »
  • PHP Manual
  • UI\Window
  • Get Window Size

UI\Window::getSize

(UI 0.9.9)

UI\Window::getSize — Get Window Size

Descrição

public UI\Window::getSize(): UI\Size

Shall return the size of this Window

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Get Title

  • « UI\Window::getSize
  • UI\Window::hasBorders »
  • PHP Manual
  • UI\Window
  • Get Title

UI\Window::getTitle

(UI 0.9.9)

UI\Window::getTitle — Get Title

Descrição

public UI\Window::getTitle(): string

Shall retrieve the title of this Window

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Border Detection

  • « UI\Window::getTitle
  • UI\Window::hasMargin »
  • PHP Manual
  • UI\Window
  • Border Detection

UI\Window::hasBorders

(UI 0.9.9)

UI\Window::hasBorders — Border Detection

Descrição

public UI\Window::hasBorders(): bool

Shall detect if borders are used on this Window

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Margin Detection

  • « UI\Window::hasBorders
  • UI\Window::isFullScreen »
  • PHP Manual
  • UI\Window
  • Margin Detection

UI\Window::hasMargin

(UI 0.9.9)

UI\Window::hasMargin — Margin Detection

Descrição

public UI\Window::hasMargin(): bool

Shall detect if margins are used on this Window

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Full Screen Detection

  • « UI\Window::hasMargin
  • UI\Window::msg »
  • PHP Manual
  • UI\Window
  • Full Screen Detection

UI\Window::isFullScreen

(UI 0.9.9)

UI\Window::isFullScreen — Full Screen Detection

Descrição

public UI\Window::isFullScreen(): bool

Shall detect if this Window us using the whole screen

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Show Message Box

  • « UI\Window::isFullScreen
  • UI\Window::onClosing »
  • PHP Manual
  • UI\Window
  • Show Message Box

UI\Window::msg

(UI 0.9.9)

UI\Window::msg — Show Message Box

Descrição

public UI\Window::msg(string $title, string $msg)

Shall show a message box

Parâmetros

title

The title of the message box

msg

The message

User Contributed Notes

There are no user contributed notes for this page.


Closing Callback

  • « UI\Window::msg
  • UI\Window::open »
  • PHP Manual
  • UI\Window
  • Closing Callback

UI\Window::onClosing

(UI 0.9.9)

UI\Window::onClosing — Closing Callback

Descrição

protected UI\Window::onClosing(): int

Should gracefully destroy this Window

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Open Dialog

  • « UI\Window::onClosing
  • UI\Window::save »
  • PHP Manual
  • UI\Window
  • Open Dialog

UI\Window::open

(UI 0.9.9)

UI\Window::open — Open Dialog

Descrição

public UI\Window::open(): string

Shall show an open file dialog

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns the name of the file selected for opening

User Contributed Notes

There are no user contributed notes for this page.


Save Dialog

  • « UI\Window::open
  • UI\Window::setBorders »
  • PHP Manual
  • UI\Window
  • Save Dialog

UI\Window::save

(UI 0.9.9)

UI\Window::save — Save Dialog

Descrição

public UI\Window::save(): string

Shall show a save dialog

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns the file name selecting for saving

User Contributed Notes

There are no user contributed notes for this page.


Border Use

  • « UI\Window::save
  • UI\Window::setFullScreen »
  • PHP Manual
  • UI\Window
  • Border Use

UI\Window::setBorders

(UI 0.9.9)

UI\Window::setBorders — Border Use

Descrição

public UI\Window::setBorders(bool $borders)

Shall enable or disable the use of borders on this Window

Parâmetros

borders

User Contributed Notes

There are no user contributed notes for this page.


Full Screen Use

  • « UI\Window::setBorders
  • UI\Window::setMargin »
  • PHP Manual
  • UI\Window
  • Full Screen Use

UI\Window::setFullScreen

(UI 0.9.9)

UI\Window::setFullScreen — Full Screen Use

Descrição

public UI\Window::setFullScreen(bool $full)

Shall enable or disable the use of the full screen for this Window

Aviso

Esta função não está documentada; apenas a lista de argumentos está disponível.

Parâmetros

full

User Contributed Notes

There are no user contributed notes for this page.


Margin Use

  • « UI\Window::setFullScreen
  • UI\Window::setSize »
  • PHP Manual
  • UI\Window
  • Margin Use

UI\Window::setMargin

(UI 0.9.9)

UI\Window::setMargin — Margin Use

Descrição

public UI\Window::setMargin(bool $margin)

Shall enable or disable the use of margins for this Window

Parâmetros

margin

User Contributed Notes

There are no user contributed notes for this page.


Set Size

  • « UI\Window::setMargin
  • UI\Window::setTitle »
  • PHP Manual
  • UI\Window
  • Set Size

UI\Window::setSize

(UI 0.9.9)

UI\Window::setSize — Set Size

Descrição

public UI\Window::setSize(UI\Size $size)

Shall set the size of this Window

Parâmetros

size

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Window Title

  • « UI\Window::setSize
  • UI\Control »
  • PHP Manual
  • UI\Window
  • Window Title

UI\Window::setTitle

(UI 0.9.9)

UI\Window::setTitle — Window Title

Descrição

public UI\Window::setTitle(string $title)

Shall set the title for this Window

Parâmetros

title

The new title

User Contributed Notes

There are no user contributed notes for this page.


Control

(UI 0.9.9)

Introdução

This is the closed base class for all UI Controls.

Sinopse da classe

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

Índice

  • 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

Descrição

public UI\Control::destroy()

Shall destroy this Control

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Control::disable()

Shall disable this Control

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Control::enable()

Shall enable this Control

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Control::getParent(): UI\Control

Shall return the parent Control

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Control::getTopLevel(): int

Aviso

Esta função não está documentada; apenas a lista de argumentos está disponível.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Control::hide()

Shall hide this Control

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Control::isEnabled(): bool

Shall detect if this Control is enabled

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Control::isVisible(): bool

Shall detect if this Control is visible

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Control::setParent(UI\Control $parent)

Shall set the parent Control of this Control

Parâmetros

parent

The parent Control

Valor Retornado

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

Descrição

public UI\Control::show()

Shall show this Control

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Menu

(UI 0.9.9)

Introdução

Menus must be constructed before the first Window, and can be shown on any Window

Sinopse da classe

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

Índice

  • UI\Menu::append — Append Menu Item
  • UI\Menu::appendAbout — Append About Menu Item
  • UI\Menu::appendCheck — Append Checkable Menu Item
  • UI\Menu::appendPreferences — Append Preferences Menu Item
  • UI\Menu::appendQuit — Append Quit Menu Item
  • UI\Menu::appendSeparator — Append Menu Item Separator
  • UI\Menu::__construct — Construct a new Menu

User Contributed Notes

There are no user contributed notes for this page.


Append Menu Item

  • « UI\Menu
  • UI\Menu::appendAbout »
  • PHP Manual
  • UI\Menu
  • Append Menu Item

UI\Menu::append

(UI 0.9.9)

UI\Menu::append — Append Menu Item

Descrição

public UI\Menu::append(string $name, string $type = UI\MenuItem::class): UI\MenuItem

Shall append a new Menu Item

Parâmetros

name

The name (text) for the new item

type

The type for the new item

Valor Retornado

A constructed object of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append About Menu Item

  • « UI\Menu::append
  • UI\Menu::appendCheck »
  • PHP Manual
  • UI\Menu
  • Append About Menu Item

UI\Menu::appendAbout

(UI 0.9.9)

UI\Menu::appendAbout — Append About Menu Item

Descrição

public UI\Menu::appendAbout(string $type = UI\MenuItem::class): UI\MenuItem

Shall append an About menu item

Parâmetros

type

The type for the new item

Valor Retornado

A constructed About menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Checkable Menu Item

  • « UI\Menu::appendAbout
  • UI\Menu::appendPreferences »
  • PHP Manual
  • UI\Menu
  • Append Checkable Menu Item

UI\Menu::appendCheck

(UI 0.9.9)

UI\Menu::appendCheck — Append Checkable Menu Item

Descrição

public UI\Menu::appendCheck(string $name, string $type = UI\MenuItem::class): UI\MenuItem

Shall append a checkable menu item

Parâmetros

name

The name (text) for the new item

type

The type for the new item

Valor Retornado

A constructed checkable menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Preferences Menu Item

  • « UI\Menu::appendCheck
  • UI\Menu::appendQuit »
  • PHP Manual
  • UI\Menu
  • Append Preferences Menu Item

UI\Menu::appendPreferences

(UI 0.9.9)

UI\Menu::appendPreferences — Append Preferences Menu Item

Descrição

public UI\Menu::appendPreferences(string $type = UI\MenuItem::class): UI\MenuItem

Shall append a Preferences menu item

Parâmetros

type

The type for the new item

Valor Retornado

A constructed Preferences menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Quit Menu Item

  • « UI\Menu::appendPreferences
  • UI\Menu::appendSeparator »
  • PHP Manual
  • UI\Menu
  • Append Quit Menu Item

UI\Menu::appendQuit

(UI 0.9.9)

UI\Menu::appendQuit — Append Quit Menu Item

Descrição

public UI\Menu::appendQuit(string $type = UI\MenuItem::class): UI\MenuItem

Shall append a Quit menu item

Parâmetros

type

The type for the new item

Valor Retornado

A constructed Quit menu item of the given type

User Contributed Notes

There are no user contributed notes for this page.


Append Menu Item Separator

  • « UI\Menu::appendQuit
  • UI\Menu::__construct »
  • PHP Manual
  • UI\Menu
  • Append Menu Item Separator

UI\Menu::appendSeparator

(UI 0.9.9)

UI\Menu::appendSeparator — Append Menu Item Separator

Descrição

public UI\Menu::appendSeparator()

Shall append a separator

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Menu

  • « UI\Menu::appendSeparator
  • UI\MenuItem »
  • PHP Manual
  • UI\Menu
  • Construct a new Menu

UI\Menu::__construct

(UI 0.9.9)

UI\Menu::__construct — Construct a new Menu

Descrição

public UI\Menu::__construct(string $name)

Shall construct a new Menu

Parâmetros

name

The name (text) for the menu

User Contributed Notes

There are no user contributed notes for this page.


Menu Item

(UI 0.9.9)

Introdução

Menu Items should only be created by the Menu

Sinopse da classe

class UI\MenuItem {
/* Métodos */
public disable()
public enable()
public isChecked(): bool
protected onClick()
public setChecked(bool $checked)
}

Índice

  • UI\MenuItem::disable — Disable Menu Item
  • UI\MenuItem::enable — Enable Menu Item
  • UI\MenuItem::isChecked — Detect Checked
  • UI\MenuItem::onClick — On Click Callback
  • UI\MenuItem::setChecked — Set Checked

User Contributed Notes

There are no user contributed notes for this page.


Disable Menu Item

  • « UI\MenuItem
  • UI\MenuItem::enable »
  • PHP Manual
  • UI\MenuItem
  • Disable Menu Item

UI\MenuItem::disable

(UI 0.9.9)

UI\MenuItem::disable — Disable Menu Item

Descrição

public UI\MenuItem::disable()

Shall disable this Menu Item

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


Enable Menu Item

  • « UI\MenuItem::disable
  • UI\MenuItem::isChecked »
  • PHP Manual
  • UI\MenuItem
  • Enable Menu Item

UI\MenuItem::enable

(UI 0.9.9)

UI\MenuItem::enable — Enable Menu Item

Descrição

public UI\MenuItem::enable()

Shall enable this Menu Item

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


Detect Checked

  • « UI\MenuItem::enable
  • UI\MenuItem::onClick »
  • PHP Manual
  • UI\MenuItem
  • Detect Checked

UI\MenuItem::isChecked

(UI 0.9.9)

UI\MenuItem::isChecked — Detect Checked

Descrição

public UI\MenuItem::isChecked(): bool

Shall detect if this Menu Item is checked

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


On Click Callback

  • « UI\MenuItem::isChecked
  • UI\MenuItem::setChecked »
  • PHP Manual
  • UI\MenuItem
  • On Click Callback

UI\MenuItem::onClick

(UI 0.9.9)

UI\MenuItem::onClick — On Click Callback

Descrição

protected UI\MenuItem::onClick()

Shall be executed when this Menu Item is clicked

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


Set Checked

  • « UI\MenuItem::onClick
  • UI\Area »
  • PHP Manual
  • UI\MenuItem
  • Set Checked

UI\MenuItem::setChecked

(UI 0.9.9)

UI\MenuItem::setChecked — Set Checked

Descrição

public UI\MenuItem::setChecked(bool $checked)

Shall set the checked status of this Menu Item

Parâmetros

checked

The new status

User Contributed Notes

There are no user contributed notes for this page.


Area

(UI 0.9.9)

Introdução

An Area represents a canvas which can be used to draw, and respond to mouse and key events.

Sinopse da classe

class UI\Area extends UI\Control {
/* Constantes */
const int Ctrl;
const int Alt;
const int Shift;
const int Super;
const int Down;
const int Up;
/* Mé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 herdados */
public UI\Control::destroy()
public UI\Control::disable()
public UI\Control::enable()
public UI\Control::getParent(): UI\Control
public UI\Control::getTopLevel(): int
public UI\Control::hide()
public UI\Control::isEnabled(): bool
public UI\Control::isVisible(): bool
public UI\Control::setParent(UI\Control $parent)
public UI\Control::show()
}

Constantes pré-definidas

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

Índice

  • 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

Descrição

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

Descrição

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

Valor Retornado

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

Descrição

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

Descrição

public UI\Area::redraw()

Requests that this Area is redrawn

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

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

Descrição

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)

Introdução

This facility schedules repetitive execution of a callback, useful for animations and other such activities.

Sinopse da classe

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
}

Índice

  • 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

Descrição

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

Descrição

public UI\Executor::kill(): void

Shall stop an executor, the executor cannot be restarted

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

abstract protected UI\Executor::onExecute(): void

Shall be repetitively queued for execution in the main thread

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

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

Valor Retornado

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Tab Control

(UI 0.9.9)

Introdução

A Tab can contain many pages of Controls, each with a title, each selectable by the user.

Sinopse da classe

class UI\Controls\Tab extends UI\Control {
/* Propriedades */
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 herdados */
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()
}

Propriedades

controls

Contains controls, should not be manipulated directly

Índice

  • 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

Descrição

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

Valor Retornado

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

Descrição

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

Valor Retornado

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

Descrição

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

Valor Retornado

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

Descrição

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

Descrição

public UI\Controls\Tab::pages(): int

Shall return the number of pages in this Tab

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

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)

Introdução

A Check is a labelled checkable box

Sinopse da classe

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 herdados */
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()
}

Índice

  • 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

Descrição

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

Descrição

public UI\Controls\Check::getText(): string

Shall return the text (label) for this Check

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Controls\Check::isChecked(): bool

Shall detect the status of this Check

Parâmetros

Esta função não possui 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

Descrição

protected UI\Controls\Check::onToggle()

Shall be executed when the status of this Check is changed

Parâmetros

Esta função não possui 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

Descrição

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

Descrição

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)

Introdução

Represents a labelled clickable button

Sinopse da classe

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 herdados */
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()
}

Índice

  • 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

Descrição

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

Descrição

public UI\Controls\Button::getText(): string

Shall retrieve the text (label) for this Button

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

protected UI\Controls\Button::onClick()

Shall be executed when this Button is clicked

Parâmetros

Esta função não possui 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

Descrição

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)

Introdução

A Color Button is a button which displays a color picker when clicked

Sinopse da classe

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 herdados */
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()
}

Índice

  • 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

Descrição

public UI\Controls\ColorButton::getColor(): UI\Color

Shall retrieve the currently selected Color

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

protected UI\Controls\ColorButton::onChange()

Shall be executed when the selected Color is changed

Parâmetros

Esta função não possui 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

Descrição

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)

Introdução

A Label is a single line of text, meant to identify, for the user, some element of the interface.

Sinopse da classe

class UI\Controls\Label extends UI\Control {
/* Constructor */
public __construct(string $text)
/* Métodos */
public getText(): string
public setText(string $text)
/* Métodos herdados */
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()
}

Índice

  • 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

Descrição

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

Descrição

public UI\Controls\Label::getText(): string

Shall return the current text for this Label

Aviso

Esta função não está documentada; apenas a lista de argumentos está disponível.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

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)

Introdução

An Entry is a text entry control, suitable for entering plain text, passwords, or search terms.

Sinopse da classe

class UI\Controls\Entry extends UI\Control {
/* Constantes */
const int Normal;
const int Password;
const int Search;
/* Constructor */
public __construct(int $type = UI\Controls\Entry::Normal)
/* Métodos */
public getText(): string
public isReadOnly(): bool
protected onChange()
public setReadOnly(bool $readOnly)
public setText(string $text)
/* Métodos herdados */
public UI\Control::destroy()
public UI\Control::disable()
public UI\Control::enable()
public UI\Control::getParent(): UI\Control
public UI\Control::getTopLevel(): int
public UI\Control::hide()
public UI\Control::isEnabled(): bool
public UI\Control::isVisible(): bool
public UI\Control::setParent(UI\Control $parent)
public UI\Control::show()
}

Constantes pré-definidas

UI\Controls\Entry::Normal

A normal single line entry

UI\Controls\Entry::Password

A password entry

UI\Controls\Entry::Search

A search entry

Índice

  • 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

Descrição

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

Descrição

public UI\Controls\Entry::getText(): string

Shall return the current text from this Entry

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Controls\Entry::isReadOnly(): bool

Shall detect if this Entry is read only

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

protected UI\Controls\Entry::onChange()

Shall be executed when the text in this Entry changes

Parâmetros

Esta função não possui 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

Descrição

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

Descrição

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)

Introdução

A Multiline Entry is a text entry control able to hold multiple lines of text, with or without wrapping.

Sinopse da classe

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 herdados */
public UI\Control::destroy()
public UI\Control::disable()
public UI\Control::enable()
public UI\Control::getParent(): UI\Control
public UI\Control::getTopLevel(): int
public UI\Control::hide()
public UI\Control::isEnabled(): bool
public UI\Control::isVisible(): bool
public UI\Control::setParent(UI\Control $parent)
public UI\Control::show()
}

Constantes pré-definidas

UI\Controls\MultilineEntry::Wrap

Allow lines to wrap

UI\Controls\MultilineEntry::NoWrap

Do not allow lines to wrap

Índice

  • 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

Descrição

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

Descrição

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

Descrição

public UI\Controls\MultilineEntry::getText(): string

Shall return the text in this Multiline Entry

Parâmetros

Esta função não possui 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

Descrição

public UI\Controls\MultilineEntry::isReadOnly(): bool

Shall detect if this Multiline Entry is read only

Parâmetros

Esta função não possui 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

Descrição

protected UI\Controls\MultilineEntry::onChange()

Shall be executed when the text in this Multiline Entry is changed

Parâmetros

Esta função não possui 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

Descrição

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

Descrição

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)

Introdução

A Spin box is a text box with an up-down control which changes the integer value in the box, within a defined range

Sinopse da classe

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 herdados */
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()
}

Índice

  • 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

Descrição

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

Descrição

public UI\Controls\Spin::getValue(): int

Get the value in this Spin

Parâmetros

Esta função não possui 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

Descrição

protected UI\Controls\Spin::onChange()

Shall be executed when the value in this Spin changes

Parâmetros

Esta função não possui 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

Descrição

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)

Introdução

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.

Sinopse da classe

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 herdados */
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()
}

Índice

  • 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

Descrição

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

Descrição

public UI\Controls\Slider::getValue(): int

Get the value from this Slider

Parâmetros

Esta função não possui 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

Descrição

protected UI\Controls\Slider::onChange()

Shall be executed when the value of this Slider changes

Parâmetros

Esta função não possui 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

Descrição

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)

Introdução

A Progress control is a familiar Progress bar: It represents progress as a percentage, with a possible range of 0 to 100 (inclusive).

Sinopse da classe

class UI\Controls\Progress extends UI\Control {
/* Métodos */
public getValue(): int
public setValue(int $value)
/* Métodos herdados */
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()
}

Índice

  • 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

Descrição

public UI\Controls\Progress::getValue(): int

Shall retrieve the current value of this Progress bar

Parâmetros

Esta função não possui 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

Descrição

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)

Introdução

A Separator represents a control separator, it has no other function.

Sinopse da classe

class UI\Controls\Separator extends UI\Control {
/* Constantes */
const int Horizontal;
const int Vertical;
/* Constructor */
public __construct(int $type = UI\Controls\Separator::Horizontal)
/* Métodos herdados */
public UI\Control::destroy()
public UI\Control::disable()
public UI\Control::enable()
public UI\Control::getParent(): UI\Control
public UI\Control::getTopLevel(): int
public UI\Control::hide()
public UI\Control::isEnabled(): bool
public UI\Control::isVisible(): bool
public UI\Control::setParent(UI\Control $parent)
public UI\Control::show()
}

Constantes pré-definidas

UI\Controls\Separator::Horizontal

A Horizontal Separator

UI\Controls\Separator::Vertical

A Vertical Separator

Índice

  • 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

Descrição

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)

Introdução

A Combo control represents a list of options, like the familiar select HTML element.

Sinopse da classe

class UI\Controls\Combo extends UI\Control {
/* Métodos */
public append(string $text)
public getSelected(): int
protected onSelected()
public setSelected(int $index)
/* Métodos herdados */
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()
}

Índice

  • 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

Descrição

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

Descrição

public UI\Controls\Combo::getSelected(): int

Shall retrieve the index of the option selected in this Combo

Parâmetros

Esta função não possui 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

Descrição

protected UI\Controls\Combo::onSelected()

Shall be executed when an option is selected in this Combo

Parâmetros

Esta função não possui 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

Descrição

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)

Introdução

An Editable Combo is a Combo which allows the user to enter custom options

Sinopse da classe

class UI\Controls\EditableCombo extends UI\Control {
/* Métodos */
public append(string $text)
public getText(): string
protected onChange()
public setText(string $text)
/* Métodos herdados */
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()
}

Índice

  • 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

Descrição

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

Descrição

public UI\Controls\EditableCombo::getText(): string

Get the value of the currently selected option in this Editable Combo

Parâmetros

Esta função não possui 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

Descrição

protected UI\Controls\EditableCombo::onChange()

Shall be executed when the value of this Editable Combobox changes

Parâmetros

Esta função não possui 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

Descrição

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)

Introdução

A Radio is similar to the radio input type familiar from HTML

Sinopse da classe

class UI\Controls\Radio extends UI\Control {
/* Métodos */
public append(string $text)
public getSelected(): int
protected onSelected()
public setSelected(int $index)
/* Métodos herdados */
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()
}

Índice

  • 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

Descrição

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

Descrição

public UI\Controls\Radio::getSelected(): int

Shall retrieve the index of the currently selected option in this Radio

Parâmetros

Esta função não possui 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

Descrição

protected UI\Controls\Radio::onSelected()

Shall be executed when the option selected in this Radio changes

Parâmetros

Esta função não possui 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

Descrição

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)

Introdução

A Picker represents a button which when clicked presents a native Date/Time/DateTime Picker interface to the user.

Sinopse da classe

class UI\Controls\Picker extends UI\Control {
/* Constantes */
const int Date;
const int Time;
const int DateTime;
/* Constructor */
public __construct(int $type = UI\Controls\Picker::Date)
/* Métodos herdados */
public UI\Control::destroy()
public UI\Control::disable()
public UI\Control::enable()
public UI\Control::getParent(): UI\Control
public UI\Control::getTopLevel(): int
public UI\Control::hide()
public UI\Control::isEnabled(): bool
public UI\Control::isVisible(): bool
public UI\Control::setParent(UI\Control $parent)
public UI\Control::show()
}

Constantes pré-definidas

UI\Controls\Picker::Date

A Date Picker

UI\Controls\Picker::Time

A Time Picker

UI\Controls\Picker::DateTime

A Date and Time Picker

Índice

  • 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

Descrição

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)

Introdução

A Form is a control which allows the arrangement of other controls into a familiar layout (the form).

Sinopse da classe

class UI\Controls\Form extends UI\Control {
/* Propriedades */
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 herdados */
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()
}

Propriedades

controls

Contains controls, should not be manipulated directly

Índice

  • 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

Descrição

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

Valor Retornado

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

Descrição

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

Valor Retornado

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

Descrição

public UI\Controls\Form::isPadded(): bool

Shall detect if padding is enabled on this Form

Parâmetros

Esta função não possui 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

Descrição

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)

Introdução

A Grid is a control which is allows the arrangement of children into a grid

Sinopse da classe

class UI\Controls\Grid extends UI\Control {
/* Constantes */
const int Fill;
const int Start;
const int Center;
const int End;
const int Leading;
const int Top;
const int Trailing;
const int Bottom;
/* Propriedades */
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 herdados */
public UI\Control::destroy()
public UI\Control::disable()
public UI\Control::enable()
public UI\Control::getParent(): UI\Control
public UI\Control::getTopLevel(): int
public UI\Control::hide()
public UI\Control::isEnabled(): bool
public UI\Control::isVisible(): bool
public UI\Control::setParent(UI\Control $parent)
public UI\Control::show()
}

Constantes pré-definidas

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

Propriedades

controls

Contains controls, should not be manipulated directly

Índice

  • 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

Descrição

public UI\Controls\Grid::append(
UI\Control $control,
int $left,
int $top,
int $xspan,
int $yspan,
bool $hexpand,
int $halign,
bool $vexpand,
int $valign
)

Aviso

Esta função não está documentada; apenas a lista de argumentos está disponível.

Parâmetros

control

The Control to append

left

top

xspan

yspan

hexpand

halign

vexpand

valign

Valor Retornado

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

Descrição

public UI\Controls\Grid::isPadded(): bool

Shall detect if padding is enabled on this Grid

Parâmetros

Esta função não possui 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

Descrição

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)

Introdução

A Group is a titled container for child controls

Sinopse da classe

class UI\Controls\Group extends UI\Control {
/* Propriedades */
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 herdados */
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()
}

Propriedades

controls

Contains controls, should not be manipulated directly

Índice

  • 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

(Não há informação de versão disponível, talvez apenas no Git)

UI\Controls\Group::append — Append Control

Descrição

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

Descrição

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

Descrição

public UI\Controls\Group::getTitle(): string

Shall return the current title for this Group

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Controls\Group::hasMargin(): bool

Shall detect if this Group has a margin

Parâmetros

Esta função não possui 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

Descrição

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

Descrição

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)

Introdução

A Box allows the arrangement of other controls

Sinopse da classe

class UI\Controls\Box extends UI\Control {
/* Constantes */
const int Vertical;
const int Horizontal;
/* Propriedades */
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 herdados */
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()
}

Propriedades

controls

Contains controls, should not be manipulated directly

Constantes pré-definidas

UI\Controls\Box::Vertical

UI\Controls\Box::Horizontal

Índice

  • 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

Descrição

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

Valor Retornado

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

Descrição

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

Descrição

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

Valor Retornado

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

Descrição

public UI\Controls\Box::getOrientation(): int

Shall retrieve the orientation of this Box

Parâmetros

Esta função não possui 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

Descrição

public UI\Controls\Box::isPadded(): bool

Shall detect if padding is enabled on this Box

Parâmetros

Esta função não possui 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

Descrição

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)

Introdução

The Pen is passed to the Area Draw event handler, it is used for clipping, filling, stroking, and writing to Draw Paths.

Sinopse da classe

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

Índice

  • UI\Draw\Pen::clip — Clip a Path
  • UI\Draw\Pen::fill — Fill a Path
  • UI\Draw\Pen::restore — Restore
  • UI\Draw\Pen::save — Save
  • UI\Draw\Pen::stroke — Stroke a Path
  • UI\Draw\Pen::transform — Matrix Transform
  • UI\Draw\Pen::write — Draw Text at Point

User Contributed Notes

There are no user contributed notes for this page.


Clip a Path

  • « UI\Draw\Pen
  • UI\Draw\Pen::fill »
  • PHP Manual
  • UI\Draw\Pen
  • Clip a Path

UI\Draw\Pen::clip

(UI 0.9.9)

UI\Draw\Pen::clip — Clip a Path

Descrição

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.


Fill a Path

  • « UI\Draw\Pen::clip
  • UI\Draw\Pen::restore »
  • PHP Manual
  • UI\Draw\Pen
  • Fill a Path

UI\Draw\Pen::fill

(UI 0.9.9)

UI\Draw\Pen::fill — Fill a Path

Descrição

public UI\Draw\Pen::fill(UI\Draw\Path $path, UI\Draw\Brush $with)
public UI\Draw\Pen::fill(UI\Draw\Path $path, UI\Draw\Color $with)
public UI\Draw\Pen::fill(UI\Draw\Path $path, int $with)

Shall fill the given path

Parâmetros

path

The path to fill

with

The color or brush to fill with

User Contributed Notes

There are no user contributed notes for this page.


Restore

  • « UI\Draw\Pen::fill
  • UI\Draw\Pen::save »
  • PHP Manual
  • UI\Draw\Pen
  • Restore

UI\Draw\Pen::restore

(UI 0.9.9)

UI\Draw\Pen::restore — Restore

Descrição

public UI\Draw\Pen::restore()

Shall restore a previously saved Pen

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


Save

  • « UI\Draw\Pen::restore
  • UI\Draw\Pen::stroke »
  • PHP Manual
  • UI\Draw\Pen
  • Save

UI\Draw\Pen::save

(UI 0.9.9)

UI\Draw\Pen::save — Save

Descrição

public UI\Draw\Pen::save()

Shall save the Pen

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


Stroke a Path

  • « UI\Draw\Pen::save
  • UI\Draw\Pen::transform »
  • PHP Manual
  • UI\Draw\Pen
  • Stroke a Path

UI\Draw\Pen::stroke

(UI 0.9.9)

UI\Draw\Pen::stroke — Stroke a Path

Descrição

public UI\Draw\Pen::stroke(UI\Draw\Path $path, UI\Draw\Brush $with, UI\Draw\Stroke $stroke)
public UI\Draw\Pen::stroke(UI\Draw\Path $path, UI\Draw\Color $with, UI\Draw\Stroke $stroke)
public UI\Draw\Pen::stroke(UI\Draw\Path $path, int $with, UI\Draw\Stroke $stroke)

Shall stroke the given path

Parâmetros

path

The path to stroke

with

The color or brush to stroke with

stroke

The configuration of the stroke

User Contributed Notes

There are no user contributed notes for this page.


Matrix Transform

  • « UI\Draw\Pen::stroke
  • UI\Draw\Pen::write »
  • PHP Manual
  • UI\Draw\Pen
  • Matrix Transform

UI\Draw\Pen::transform

(UI 0.9.9)

UI\Draw\Pen::transform — Matrix Transform

Descrição

public UI\Draw\Pen::transform(UI\Draw\Matrix $matrix)

Shall perform matrix transformation

Parâmetros

matrix

The matrix to use

User Contributed Notes

There are no user contributed notes for this page.


Draw Text at Point

  • « UI\Draw\Pen::transform
  • UI\Draw\Path »
  • PHP Manual
  • UI\Draw\Pen
  • Draw Text at Point

UI\Draw\Pen::write

(UI 0.9.9)

UI\Draw\Pen::write — Draw Text at Point

Descrição

public UI\Draw\Pen::write(UI\Point $point, UI\Draw\Text\Layout $layout)

Shall draw the given text layout at the given point

Parâmetros

point

The point to perform the drawing

layout

The layout of the text to draw

User Contributed Notes

There are no user contributed notes for this page.


Draw Path

(UI 0.9.9)

Introdução

A Draw Path guides a Draw Pen, telling the Pen where to draw on an Area.

Sinopse da classe

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 pré-definidas

UI\Draw\Path::Winding

This is the default draw path mode

UI\Draw\Path::Alternate

This is the alternate draw path mode

Índice

  • UI\Draw\Path::addRectangle — Draw a Rectangle
  • UI\Draw\Path::arcTo — Draw an Arc
  • UI\Draw\Path::bezierTo — Draw Bezier Curve
  • UI\Draw\Path::closeFigure — Close Figure
  • UI\Draw\Path::__construct — Construct a new Path
  • UI\Draw\Path::end — Finalize Path
  • UI\Draw\Path::lineTo — Draw a Line
  • UI\Draw\Path::newFigure — Draw Figure
  • UI\Draw\Path::newFigureWithArc — Draw Figure with Arc

User Contributed Notes

There are no user contributed notes for this page.


Draw a Rectangle

  • « UI\Draw\Path
  • UI\Draw\Path::arcTo »
  • PHP Manual
  • UI\Draw\Path
  • Draw a Rectangle

UI\Draw\Path::addRectangle

(UI 0.9.9)

UI\Draw\Path::addRectangle — Draw a Rectangle

Descrição

public UI\Draw\Path::addRectangle(UI\Point $point, UI\Size $size)

Shall map the path of a rectangle of the given size, at the given point

Parâmetros

point

The point to begin the shape

size

The size of the rectangle

User Contributed Notes

There are no user contributed notes for this page.


Draw an Arc

  • « UI\Draw\Path::addRectangle
  • UI\Draw\Path::bezierTo »
  • PHP Manual
  • UI\Draw\Path
  • Draw an Arc

UI\Draw\Path::arcTo

(UI 0.9.9)

UI\Draw\Path::arcTo — Draw an Arc

Descrição

public UI\Draw\Path::arcTo(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Shall map the path for an arc

Parâmetros

point

The point to begin mapping

radius

The radius of the arc

angle

The angle of the arc

sweep

The sweep of the arc

negative

Valor Retornado

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

Descrição

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.


Close Figure

  • « UI\Draw\Path::bezierTo
  • UI\Draw\Path::__construct »
  • PHP Manual
  • UI\Draw\Path
  • Close Figure

UI\Draw\Path::closeFigure

(UI 0.9.9)

UI\Draw\Path::closeFigure — Close Figure

Descrição

public UI\Draw\Path::closeFigure()

Shall close the current figure

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Path

  • « UI\Draw\Path::closeFigure
  • UI\Draw\Path::end »
  • PHP Manual
  • UI\Draw\Path
  • Construct a new Path

UI\Draw\Path::__construct

(UI 0.9.9)

UI\Draw\Path::__construct — Construct a new Path

Descrição

public UI\Draw\Path::__construct(int $mode = UI\Draw\Path::Winding)

Shall construct a new path in the given mode

Parâmetros

mode

Path::Winding or Path::Alternate

User Contributed Notes

There are no user contributed notes for this page.


Finalize Path

  • « UI\Draw\Path::__construct
  • UI\Draw\Path::lineTo »
  • PHP Manual
  • UI\Draw\Path
  • Finalize Path

UI\Draw\Path::end

(UI 0.9.9)

UI\Draw\Path::end — Finalize Path

Descrição

public UI\Draw\Path::end()

Shall finalize this Path

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


Draw a Line

  • « UI\Draw\Path::end
  • UI\Draw\Path::newFigure »
  • PHP Manual
  • UI\Draw\Path
  • Draw a Line

UI\Draw\Path::lineTo

(UI 0.9.9)

UI\Draw\Path::lineTo — Draw a Line

Descrição

public UI\Draw\Path::lineTo(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Shall map the path for a line

Parâmetros

point

The point to begin mapping

radius

angle

sweep

negative

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Draw Figure

  • « UI\Draw\Path::lineTo
  • UI\Draw\Path::newFigureWithArc »
  • PHP Manual
  • UI\Draw\Path
  • Draw Figure

UI\Draw\Path::newFigure

(UI 0.9.9)

UI\Draw\Path::newFigure — Draw Figure

Descrição

public UI\Draw\Path::newFigure(UI\Point $point)

Shall map a new figure at the given point

Parâmetros

point

The point to begin mapping

User Contributed Notes

There are no user contributed notes for this page.


Draw Figure with Arc

  • « UI\Draw\Path::newFigure
  • UI\Draw\Matrix »
  • PHP Manual
  • UI\Draw\Path
  • Draw Figure with Arc

UI\Draw\Path::newFigureWithArc

(UI 0.9.9)

UI\Draw\Path::newFigureWithArc — Draw Figure with Arc

Descrição

public UI\Draw\Path::newFigureWithArc(
UI\Point $point,
float $radius,
float $angle,
float $sweep,
float $negative
)

Parâmetros

point

radius

angle

sweep

negative

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Draw Matrix

(UI 0.9.9)

Introdução

Sinopse da classe

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

Índice

  • UI\Draw\Matrix::invert — Invert Matrix
  • UI\Draw\Matrix::isInvertible — Invertible Detection
  • UI\Draw\Matrix::multiply — Multiply Matrix
  • UI\Draw\Matrix::rotate — Rotate Matrix
  • UI\Draw\Matrix::scale — Scale Matrix
  • UI\Draw\Matrix::skew — Skew Matrix
  • UI\Draw\Matrix::translate — Translate Matrix

User Contributed Notes

There are no user contributed notes for this page.


Invert Matrix

  • « UI\Draw\Matrix
  • UI\Draw\Matrix::isInvertible »
  • PHP Manual
  • UI\Draw\Matrix
  • Invert Matrix

UI\Draw\Matrix::invert

(UI 0.9.9)

UI\Draw\Matrix::invert — Invert Matrix

Descrição

public UI\Draw\Matrix::invert()

Shall invert this matrix

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


Invertible Detection

  • « UI\Draw\Matrix::invert
  • UI\Draw\Matrix::multiply »
  • PHP Manual
  • UI\Draw\Matrix
  • Invertible Detection

UI\Draw\Matrix::isInvertible

(UI 0.9.9)

UI\Draw\Matrix::isInvertible — Invertible Detection

Descrição

public UI\Draw\Matrix::isInvertible(): bool

Shall detect if this Matrix may be inverted

Parâmetros

Esta função não possui parâmetros.

User Contributed Notes

There are no user contributed notes for this page.


Multiply Matrix

  • « UI\Draw\Matrix::isInvertible
  • UI\Draw\Matrix::rotate »
  • PHP Manual
  • UI\Draw\Matrix
  • Multiply Matrix

UI\Draw\Matrix::multiply

(UI 0.9.9)

UI\Draw\Matrix::multiply — Multiply Matrix

Descrição

public UI\Draw\Matrix::multiply(UI\Draw\Matrix $matrix): UI\Draw\Matrix

Shall multiply this matrix with the given matrix

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

The new Matrix

User Contributed Notes

There are no user contributed notes for this page.


Rotate Matrix

  • « UI\Draw\Matrix::multiply
  • UI\Draw\Matrix::scale »
  • PHP Manual
  • UI\Draw\Matrix
  • Rotate Matrix

UI\Draw\Matrix::rotate

(UI 0.9.9)

UI\Draw\Matrix::rotate — Rotate Matrix

Descrição

public UI\Draw\Matrix::rotate(UI\Point $point, float $amount)

Shall rotate this Matrix

Parâmetros

point

amount

User Contributed Notes

There are no user contributed notes for this page.


Scale Matrix

  • « UI\Draw\Matrix::rotate
  • UI\Draw\Matrix::skew »
  • PHP Manual
  • UI\Draw\Matrix
  • Scale Matrix

UI\Draw\Matrix::scale

(UI 0.9.9)

UI\Draw\Matrix::scale — Scale Matrix

Descrição

public UI\Draw\Matrix::scale(UI\Point $center, UI\Point $point)

Shall scale this Matrix

Parâmetros

center

point

User Contributed Notes

There are no user contributed notes for this page.


Skew Matrix

  • « UI\Draw\Matrix::scale
  • UI\Draw\Matrix::translate »
  • PHP Manual
  • UI\Draw\Matrix
  • Skew Matrix

UI\Draw\Matrix::skew

(UI 0.9.9)

UI\Draw\Matrix::skew — Skew Matrix

Descrição

public UI\Draw\Matrix::skew(UI\Point $point, UI\Point $amount)

Shall skew this Matrix

Parâmetros

point

amount

User Contributed Notes

There are no user contributed notes for this page.


Translate Matrix

  • « UI\Draw\Matrix::skew
  • UI\Draw\Color »
  • PHP Manual
  • UI\Draw\Matrix
  • Translate Matrix

UI\Draw\Matrix::translate

(UI 0.9.9)

UI\Draw\Matrix::translate — Translate Matrix

Descrição

public UI\Draw\Matrix::translate(UI\Point $point)

Shall translate this Matrix

Parâmetros

point

User Contributed Notes

There are no user contributed notes for this page.


Color Representation

(UI 0.9.9)

Introdução

Represents RGBA colours, individual channels are accessible via public properties.

Sinopse da classe

class UI\Draw\Color {
/* Constantes */
const int Red;
const int Green;
const int Blue;
const int Alpha;
/* Propriedades */
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
}

Propriedades

r

Provides access to the red channel

g

Provides access to the green channel

b

Provides access to the blue channel

a

Provides access to the alpha channel

Constantes pré-definidas

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

Índice

  • UI\Draw\Color::__construct — Construct new Color
  • UI\Draw\Color::getChannel — Color Manipulation
  • UI\Draw\Color::setChannel — Color Manipulation

User Contributed Notes

There are no user contributed notes for this page.


Construct new Color

  • « UI\Draw\Color
  • UI\Draw\Color::getChannel »
  • PHP Manual
  • UI\Draw\Color
  • Construct new Color

UI\Draw\Color::__construct

(UI 0.9.9)

UI\Draw\Color::__construct — Construct new Color

Descrição

public UI\Draw\Color::__construct(UI\Draw\Color $color = ?)
public UI\Draw\Color::__construct(int $color = ?)

Shall construct a new color

Parâmetros

color

May be UI\Draw\Color or RRGGBBAA

User Contributed Notes

There are no user contributed notes for this page.


Color Manipulation

  • « UI\Draw\Color::__construct
  • UI\Draw\Color::setChannel »
  • PHP Manual
  • UI\Draw\Color
  • Color Manipulation

UI\Draw\Color::getChannel

(UI 0.9.9)

UI\Draw\Color::getChannel — Color Manipulation

Descrição

public UI\Draw\Color::getChannel(int $channel): float

Shall retrieve the value for a channel

Parâmetros

channel

Constant channel identity

Valor Retornado

The current value of the requested channel

User Contributed Notes

There are no user contributed notes for this page.


Color Manipulation

  • « UI\Draw\Color::getChannel
  • UI\Draw\Stroke »
  • PHP Manual
  • UI\Draw\Color
  • Color Manipulation

UI\Draw\Color::setChannel

(UI 0.9.9)

UI\Draw\Color::setChannel — Color Manipulation

Descrição

public UI\Draw\Color::setChannel(int $channel, float $value): void

Shall set the selected channel to the given value

Parâmetros

channel

Constant channel identity

value

The new value for the selected channel

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Draw Stroke

(UI 0.9.9)

Introdução

Holds the configuration for the Pen to perform a stroke

Sinopse da classe

class UI\Draw\Stroke {
/* Constructor */
public __construct(
int $cap = UI\Draw\Line\Cap::Flat,
int $join = UI\Draw\Line\Join::Miter,
float $thickness = 1,
float $miterLimit = 10
)
/* Mé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)
}

Índice

  • UI\Draw\Stroke::__construct — Construct a new Stroke
  • UI\Draw\Stroke::getCap — Get Line Cap
  • UI\Draw\Stroke::getJoin — Get Line Join
  • UI\Draw\Stroke::getMiterLimit — Get Miter Limit
  • UI\Draw\Stroke::getThickness — Get Thickness
  • UI\Draw\Stroke::setCap — Set Line Cap
  • UI\Draw\Stroke::setJoin — Set Line Join
  • UI\Draw\Stroke::setMiterLimit — Set Miter Limit
  • UI\Draw\Stroke::setThickness — Set Thickness

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Stroke

  • « UI\Draw\Stroke
  • UI\Draw\Stroke::getCap »
  • PHP Manual
  • UI\Draw\Stroke
  • Construct a new Stroke

UI\Draw\Stroke::__construct

(UI 0.9.9)

UI\Draw\Stroke::__construct — Construct a new Stroke

Descrição

public UI\Draw\Stroke::__construct(
int $cap = UI\Draw\Line\Cap::Flat,
int $join = UI\Draw\Line\Join::Miter,
float $thickness = 1,
float $miterLimit = 10
)

Shall construct a new Stroke

Parâmetros

cap

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

thickness

The thickness of the stroke

miterLimit

Miter limit (default is sensible for all supported platforms)

User Contributed Notes

There are no user contributed notes for this page.


Get Line Cap

  • « UI\Draw\Stroke::__construct
  • UI\Draw\Stroke::getJoin »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Line Cap

UI\Draw\Stroke::getCap

(UI 0.9.9)

UI\Draw\Stroke::getCap — Get Line Cap

Descrição

public UI\Draw\Stroke::getCap(): int

Shall retrieve the line cap setting of this Stroke

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

User Contributed Notes

There are no user contributed notes for this page.


Get Line Join

  • « UI\Draw\Stroke::getCap
  • UI\Draw\Stroke::getMiterLimit »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Line Join

UI\Draw\Stroke::getJoin

(UI 0.9.9)

UI\Draw\Stroke::getJoin — Get Line Join

Descrição

public UI\Draw\Stroke::getJoin(): int

Shall retrieve the line join setting of this Stroke

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

User Contributed Notes

There are no user contributed notes for this page.


Get Miter Limit

  • « UI\Draw\Stroke::getJoin
  • UI\Draw\Stroke::getThickness »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Miter Limit

UI\Draw\Stroke::getMiterLimit

(UI 0.9.9)

UI\Draw\Stroke::getMiterLimit — Get Miter Limit

Descrição

public UI\Draw\Stroke::getMiterLimit(): float

Shall retrieve the miter limit of this Stroke

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

The current miter limit

User Contributed Notes

There are no user contributed notes for this page.


Get Thickness

  • « UI\Draw\Stroke::getMiterLimit
  • UI\Draw\Stroke::setCap »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Thickness

UI\Draw\Stroke::getThickness

(UI 0.9.9)

UI\Draw\Stroke::getThickness — Get Thickness

Descrição

public UI\Draw\Stroke::getThickness(): float

Shall retrieve the thickness of this Stroke

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

The current thickness

User Contributed Notes

There are no user contributed notes for this page.


Set Line Cap

  • « UI\Draw\Stroke::getThickness
  • UI\Draw\Stroke::setJoin »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Line Cap

UI\Draw\Stroke::setCap

(UI 0.9.9)

UI\Draw\Stroke::setCap — Set Line Cap

Descrição

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.


Set Line Join

  • « UI\Draw\Stroke::setCap
  • UI\Draw\Stroke::setMiterLimit »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Line Join

UI\Draw\Stroke::setJoin

(UI 0.9.9)

UI\Draw\Stroke::setJoin — Set Line Join

Descrição

public UI\Draw\Stroke::setJoin(int $join)

Shall set the line join setting for this Stroke

Parâmetros

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Set Miter Limit

  • « UI\Draw\Stroke::setJoin
  • UI\Draw\Stroke::setThickness »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Miter Limit

UI\Draw\Stroke::setMiterLimit

(UI 0.9.9)

UI\Draw\Stroke::setMiterLimit — Set Miter Limit

Descrição

public UI\Draw\Stroke::setMiterLimit(float $limit)

Set the miter limit for this Stroke

Parâmetros

limit

The new limit

User Contributed Notes

There are no user contributed notes for this page.


Set Thickness

  • « UI\Draw\Stroke::setMiterLimit
  • UI\Draw\Brush »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Thickness

UI\Draw\Stroke::setThickness

(UI 0.9.9)

UI\Draw\Stroke::setThickness — Set Thickness

Descrição

public UI\Draw\Stroke::setThickness(float $thickness)

Shall set the thickness for this Stroke

Parâmetros

thickness

The new thickness

User Contributed Notes

There are no user contributed notes for this page.


Brushes

(UI 0.9.9)

Introdução

Represents a solid color brush

Sinopse da classe

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
}

Índice

  • 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

Descrição

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

Descrição

public UI\Draw\Brush::getColor(): UI\Draw\Color

Shall return a UI\Draw\Color for this brush

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

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

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Gradient Brushes

(UI 2.0.0)

Introdução

Abstract for gradient brushes

Sinopse da classe

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 herdados */
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
}

Índice

  • 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

Descrição

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

Valor Retornado

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

Descrição

public UI\Draw\Brush\Gradient::delStop(int $index): int

Aviso

Esta função não está documentada; apenas a lista de argumentos está disponível.

Parâmetros

index

Valor Retornado

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

Descrição

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

Valor Retornado

Indication of success

User Contributed Notes

There are no user contributed notes for this page.


Linear Gradient

(UI 2.0.0)

Introdução

Sinopse da classe

class UI\Draw\Brush\LinearGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct(UI\Point $start, UI\Point $end)
/* Métodos herdados */
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
}

Índice

  • 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

Descrição

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)

Introdução

Sinopse da classe

class UI\Draw\Brush\RadialGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct(UI\Point $start, UI\Point $outer, float $radius)
/* Métodos herdados */
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
}

Índice

  • 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

Descrição

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)

Introdução

A Text Layout represents the layout of text which will be drawn by the Pen

Sinopse da classe

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

Índice

  • UI\Draw\Text\Layout::__construct — Construct a new Text Layout
  • UI\Draw\Text\Layout::setColor — Set Color
  • UI\Draw\Text\Layout::setWidth — Set Width

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Text Layout

  • « UI\Draw\Text\Layout
  • UI\Draw\Text\Layout::setColor »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Construct a new Text Layout

UI\Draw\Text\Layout::__construct

(UI 0.9.9)

UI\Draw\Text\Layout::__construct — Construct a new Text Layout

Descrição

public UI\Draw\Text\Layout::__construct(string $text, UI\Draw\Text\Font $font, float $width)

Shall construct a new Text Layout

Parâmetros

text

The text for the layout

font

The font to use for writing

width

The width of the layout

User Contributed Notes

There are no user contributed notes for this page.


Set Color

  • « UI\Draw\Text\Layout::__construct
  • UI\Draw\Text\Layout::setWidth »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Set Color

UI\Draw\Text\Layout::setColor

(UI 0.9.9)

UI\Draw\Text\Layout::setColor — Set Color

Descrição

public UI\Draw\Text\Layout::setColor(UI\Draw\Color $color, int $start = 0, int $end = ?)
public UI\Draw\Text\Layout::setColor(int $color, int $start = 0, int $end = ?)

Shall set the Color for all of, or a range of the text in the Layout

Parâmetros

color

The color to use

start

The starting character

end

The ending character, by default the end of the string

User Contributed Notes

There are no user contributed notes for this page.


Set Width

  • « UI\Draw\Text\Layout::setColor
  • UI\Draw\Text\Font »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Set Width

UI\Draw\Text\Layout::setWidth

(UI 0.9.9)

UI\Draw\Text\Layout::setWidth — Set Width

Descrição

public UI\Draw\Text\Layout::setWidth(float $width)

Shall set the width of this Text Layout

Parâmetros

width

The new width

User Contributed Notes

There are no user contributed notes for this page.


Represents a Font

(UI 0.9.9)

Introdução

Loads a described font

Sinopse da classe

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
}

Índice

  • UI\Draw\Text\Font::__construct — Construct a new Font
  • UI\Draw\Text\Font::getAscent — Font Metrics
  • UI\Draw\Text\Font::getDescent — Font Metrics
  • UI\Draw\Text\Font::getLeading — Font Metrics
  • UI\Draw\Text\Font::getUnderlinePosition — Font Metrics
  • UI\Draw\Text\Font::getUnderlineThickness — Font Metrics

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Font

  • « UI\Draw\Text\Font
  • UI\Draw\Text\Font::getAscent »
  • PHP Manual
  • UI\Draw\Text\Font
  • Construct a new Font

UI\Draw\Text\Font::__construct

(UI 0.9.9)

UI\Draw\Text\Font::__construct — Construct a new Font

Descrição

public UI\Draw\Text\Font::__construct(UI\Draw\Text\Font\Descriptor $descriptor)

Shall construct a new Font using the given descriptor

Parâmetros

descriptor

The descriptor for the Font

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • « UI\Draw\Text\Font::__construct
  • UI\Draw\Text\Font::getDescent »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getAscent

(UI 1.0.3)

UI\Draw\Text\Font::getAscent — Font Metrics

Descrição

public UI\Draw\Text\Font::getAscent(): float

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • « UI\Draw\Text\Font::getAscent
  • UI\Draw\Text\Font::getLeading »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getDescent

(UI 1.0.3)

UI\Draw\Text\Font::getDescent — Font Metrics

Descrição

public UI\Draw\Text\Font::getDescent(): float

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • « UI\Draw\Text\Font::getDescent
  • UI\Draw\Text\Font::getUnderlinePosition »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getLeading

(UI 1.0.3)

UI\Draw\Text\Font::getLeading — Font Metrics

Descrição

public UI\Draw\Text\Font::getLeading(): float

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • « UI\Draw\Text\Font::getLeading
  • UI\Draw\Text\Font::getUnderlineThickness »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getUnderlinePosition

(UI 1.0.3)

UI\Draw\Text\Font::getUnderlinePosition — Font Metrics

Descrição

public UI\Draw\Text\Font::getUnderlinePosition(): float

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Font Metrics

  • « UI\Draw\Text\Font::getUnderlinePosition
  • UI\Draw\Text\Font\Descriptor »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getUnderlineThickness

(UI 1.0.3)

UI\Draw\Text\Font::getUnderlineThickness — Font Metrics

Descrição

public UI\Draw\Text\Font::getUnderlineThickness(): float

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Font Descriptor

(UI 0.9.9)

Introdução

Describes a font

Sinopse da classe

class UI\Draw\Text\Font\Descriptor {
/* Constructor */
public __construct(
string $family,
float $size,
int $weight = UI\Draw\Text\Font\Weight::Normal,
int $italic = UI\Draw\Text\Font\Italic::Normal,
int $stretch = UI\Draw\Text\Font\Stretch::Normal
)
/* Métodos */
public getFamily(): string
public getItalic(): int
public getSize(): float
public getStretch(): int
public getWeight(): int
}

Índice

  • 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

Descrição

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

Descrição

public UI\Draw\Text\Font\Descriptor::getFamily(): string

Shall return the requested font family

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Draw\Text\Font\Descriptor::getItalic(): int

Shall return constant setting

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Draw\Text\Font\Descriptor::getSize(): float

Shall return the requested size

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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

Descrição

public UI\Draw\Text\Font\Descriptor::getStretch(): int

Shall return requested stretch

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Weight Detection

  • « UI\Draw\Text\Font\Descriptor::getStretch
  • UI Funções »
  • 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

Descrição

public UI\Draw\Text\Font\Descriptor::getWeight(): int

Shall return requested weight

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


UI Funções

Índice

  • UI\Draw\Text\Font\fontFamilies — Retrieve Font Families
  • UI\quit — Quit UI Loop
  • UI\run — Enter UI Loop

User Contributed Notes

There are no user contributed notes for this page.


Retrieve Font Families

  • « UI Funções
  • UI\quit »
  • PHP Manual
  • UI Funções
  • Retrieve Font Families

UI\Draw\Text\Font\fontFamilies

(UI 0.9.9)

UI\Draw\Text\Font\fontFamilies — Retrieve Font Families

Descrição

UI\Draw\Text\Font\fontFamilies(): array

Returns an array of valid font families for the current system

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Returns an array of valid font families for the current system.

User Contributed Notes

There are no user contributed notes for this page.


Quit UI Loop

  • « UI\Draw\Text\Font\fontFamilies
  • UI\run »
  • PHP Manual
  • UI Funções
  • Quit UI Loop

UI\quit

(UI 2.0.0)

UI\quit — Quit UI Loop

Descrição

UI\quit(): void

Shall cause the main loop to be exited

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

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 Funções
  • Enter UI Loop

UI\run

(UI 2.0.0)

UI\run — Enter UI Loop

Descrição

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

Valor Retornado

User Contributed Notes

There are no user contributed notes for this page.


Font Weight Settings

(UI 0.9.9)

Introdução

Sinopse da classe

final class UI\Draw\Text\Font\Weight {
/* Constantes */
const int Thin;
const int UltraLight;
const int Light;
const int Book;
const int Normal;
const int Medium;
const int SemiBold;
const int Bold;
const int UltraBold;
const int Heavy;
const int UltraHeavy;
}

User Contributed Notes

There are no user contributed notes for this page.


Italic Font Settings

(UI 0.9.9)

Introdução

Sinopse da classe

final class UI\Draw\Text\Font\Italic {
/* Constantes */
const int Normal = 0;
const int Oblique = 1;
const int Italic = 2;
}

User Contributed Notes

There are no user contributed notes for this page.


Font Stretch Settings

(UI 0.9.9)

Introdução

Sinopse da classe

final class UI\Draw\Text\Font\Stretch {
/* Constantes */
const int UltraCondensed = 0;
const int ExtraCondensed = 1;
const int Condensed = 2;
const int SemiCondensed = 3;
const int Normal = 4;
const int SemiExpanded = 5;
const int Expanded = 6;
const int ExtraExpanded = 7;
const int UltraExpanded = 8;
}

User Contributed Notes

There are no user contributed notes for this page.


Line Cap Settings

(UI 0.9.9)

Introdução

Sinopse da classe

final class UI\Draw\Line\Cap {
/* Constantes */
const int Flat;
const int Round;
const int Square;
}

User Contributed Notes

There are no user contributed notes for this page.


Line Join Settings

(UI 0.9.9)

Introdução

Sinopse da classe

final class UI\Draw\Line\Join {
/* Constantes */
const int Miter;
const int Round;
const int Bevel;
}

User Contributed Notes

There are no user contributed notes for this page.


Key Identifiers

(UI 1.0.0)

Introdução

Sinopse da classe

final class UI\Key {
/* Constantes */
const int Escape;
const int Insert;
const int Delete;
const int Home;
const int End;
const int PageUp;
const int PageDown;
const int Up;
const int Down;
const int Left;
const int Right;
const int F1;
const int F2;
const int F3;
const int F4;
const int F5;
const int F6;
const int F7;
const int F8;
const int F9;
const int F10;
const int F11;
const int F12;
const int N0;
const int N1;
const int N2;
const int N3;
const int N4;
const int N5;
const int N6;
const int N7;
const int N8;
const int N9;
const int NDot;
const int NEnter;
const int NAdd;
const int NSubtract;
const int NMultiply;
const int NDivide;
}

User Contributed Notes

There are no user contributed notes for this page.


InvalidArgumentException

(UI 1.0.3)

Introdução

Sinopse da classe

class UI\Exception\InvalidArgumentException extends InvalidArgumentException implements Throwable {
/* Propriedades herdadas */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Métodos herdados */
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)

Introdução

Sinopse da classe

class UI\Exception\RuntimeException extends RuntimeException implements Throwable {
/* Propriedades herdadas */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* Métodos herdados */
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: Perguntas Mais Frequentes

  • Informações Gerais
  • Listas de Discussão
  • Obtendo o PHP
  • Questões sobre banco de dados
  • Instalação
  • Problemas de Compilação
  • Utilizando o PHP
  • Gerando hash de senha — Gerando hash seguro de senha
  • PHP e HTML
  • PHP e COM
  • Questões Diversas

User Contributed Notes

There are no user contributed notes for this page.


Informações Gerais

Essa seção trata das questões mais gerais sobre o PHP: o que é e o que faz.

  1. O que é o PHP?
  2. O que a sigla PHP significa?
  3. Qual é a relação entre as versões?
  4. Posso executar várias versões do PHP ao mesmo tempo?
  5. Acho que encontrei um bug! A quem eu devo dizer?
O que é o PHP?

Do prefácio do manual:

PHP é uma linguagem de script embutida no HTML. Muito da sua sintaxe é emprestada de C, Java e Perl com algumas características específicas do PHP adicionadas. O objetivo da linguagem é permitir que desenvolvedores web escrevam páginas geradas dinamicamente de forma rápida.

O que a sigla PHP significa?

PHP significa PHP: Hypertext Preprocessor. Isso confunde muitas pessoas porque a primeira palavra do acrônimo é o acrônimo. Esse tipo de acrônimo é chamado de acrônimo recursivo. Para mais informações, os curiosos podem visitar o » Dicionário On-Line Gratuito de Computação ou o » item na Wikipedia sobre acrónimos recursivos.

Qual é a relação entre as versões?

PHP/FI 2.0 é uma versão mais antiga e não mais suportada do PHP. PHP 3 é o sucessor do PHP/FI 2.0 e é bem melhor. PHP 8 é a geração atual do PHP, que usa a Zend Engine 4, a qual, entre outras coisas, oferece muitas funcionalidades adicionais de POO.

Posso executar várias versões do PHP ao mesmo tempo?

Sim. Veja o arquivo INSTALL que vem incluso na distribuição dos fontes do PHP.

Acho que encontrei um bug! A quem eu devo dizer?

Você deve ir ao Banco de Dados de Bugs do PHP e assegurar-se de que o bug não é conhecido. Se você não encontrá-lo no banco, use o formulário para relatar o bug. É importante usar o banco de bugs ao invés de apenas enviar um e-mail para uma das listas de discussão porque o bug terá um número de rastreamento atribuído a ele e será possível voltar depois e checar o status do bug. O banco de bugs pode ser encontrado em » https://github.com/php/php-src/issues.

User Contributed Notes

There are no user contributed notes for this page.


Listas de Discussão

Essa seção responde algumas perguntas relacionadas a como entrar em contato com a comunidade PHP. A melhor maneira é através das listas de discussão via e-mail.

  1. Existe alguma lista de discussão do PHP?
  2. Existem outras comunidades?
  3. Posso iniciar minha própria lista de discussões de PHP?
  4. Ajuda! Não consigo me inscrever ou sair de nenhuma das listas de discussão!
  5. Existe um histórico das listas de discussão em algum lugar?
  6. O que posso perguntar na lista de discussão?
  7. Que informação devo incluir quando faço perguntas na lista?
Existe alguma lista de discussão do PHP?

É claro! Existem várias listas de discussão sobre vários assuntos. Uma listagem das principais listas de discussão pode ser encontrada na nossa » listas de discussão por email.

A lista de discussão mais geral é php-general. Para participar, mande um e-mail em branco para » php-general-subscribe@lists.php.net. Para sair da lista, mande um e-mail para » php-general-unsubscribe@lists.php.net.

Você pode se inscrever e sair das listas usando nossa interface web disponível em » listas de discussão, além de instruções incluídas no rodapé de cada e-mail da lista.

Existem outras comunidades?

Existem incontáveis comunidades voltadas ao PHP ao redor do mundo. Nós temos links, para algumas delas (e informação de como aprender mais) em nossa página de » Suporte

Posso iniciar minha própria lista de discussões de PHP?

Com certeza! Aliás, nós não só permitimos como encorajamos você a iniciar uma lista de discussões! Ajudar os outros dividindo seu conhecimento e experiência com o PHP amplia o crescimento da comunidade e o desenvolvimento global do PHP, além da própria linguagem.

Ajuda! Não consigo me inscrever ou sair de nenhuma das listas de discussão!

Se você tiver problemas se inscrevendo ou saindo de uma lista de discussão, pode ser porque o software da lista não consegue definir o endereço de e-mail correto para usar. Se seu endereço de e-mail for joeblow@example.com, você pode mandar sua requisição de inscrição para php-general-subscribe-joeblow=example.com@lists.php.net, ou sua requisição de saída para php-general-unsubscribe-joeblow=example.com@lists.php.net. Use endereços similares para as outras listas de discussão.

A causa mais comum para as pessoas terem dificuldades em se inscrever ou sair de uma lista de discussão é por causa do uso de e-mails encaminhados. Por exemplo se seu e-mail for danbrown@example.com, mas você se inscrever usando um e-mail com encaminhamento como php-lists@example.com que repassa depois a danbrown@example.com, tentar remover da lista o e-mail danbrown@example.com não vai funcionar pois este e-mail não é conhecido nos nossos sistemas. Ao invés disso você vai precisar pedir pra sair de uma lista com o e-mail que está recebendo as listas - neste exemplo php-list@example.com.

Existe um histórico das listas de discussão em algum lugar?

Sim, você encontrará uma lista de sites com o histórico na página de » listas de email. Você também vai encontrar dezenas de arquivos e/ou referências para nossas listas de discussões usando seu mecanismo de busca preferido ao procurar por "php mailing list archives".

Os artigos da lista de discussão também são arquivados como mensagens de notícia. Você pode acessar o servidor de notícias em » news://news.php.net/ com um cliente de notícias. Também existe uma interface web experimental para o servidor de notícias em » http://news.php.net/

O que posso perguntar na lista de discussão?

Uma vez que o PHP está crescendo em popularidade todo dia, o tráfego na lista de discussão php-general cresceu e até agora a lista recebe entre 75 a 200 mensagens por dia. Por isso é do interesse de todos que você use a lista como último recurso quando você procurou em todos os outros lugares.

Antes de postar em uma lista verifique nessa FAQ e no manual se não consegue encontrar a informação aqui. Se não encontrar então tente os arquivos das listas (veja acima). Se está tendo problemas instalando ou configurando o PHP primeiro leia toda a documentação incluída e os README's. Se ainda não conseguir encontrar a informação que lhe ajude, você é bem vindo a utilizar a lista apropriada.

Para garantir que você receba as melhores respostas (e para reduzir a probabilidade de frustrar seus colegas desenvolvedores) envie sua pergunta para a lista apropriada. Por exemplo, se você está tendo dificuldades para instalar PHP, você deve enviar sua pergunta para a lista de discussão php-install. Uma ressalva: algumas listas têm nomes semelhantes mas usos completamente diferentes; uma pergunta sobre os scripts PHP no Windows deve ser direcionado para a lista de usuários do Windows PHP, not para a lista do Windows Internals.

Antes de perguntar, você deve ler o arquivo » Como Fazer Perguntas de Maneira Inteligente que é uma boa idéia para todo mundo.

Que informação devo incluir quando faço perguntas na lista?

Mensagens como "Não consigo colocar o PHP para funcionar! Me ajude! O que está errado?" são inúteis. Se você tiver problemas fazendo o PHP funcionar, você deve incluir que sistema operacional você está usando, qual a versão do PHP você está tentando instalar, como você obteve (pré-compilado, CVS, RPM e por aí vai), o que você fez até agora, onde ficou preso e a mensagem de erro exata.

Isso vale para qualquer outro problema também. Você deve incluir informações sobre o que você fez, o que você está tentando fazer e quaisquer mensagens de erro encontradas no processo. Se você tiver problemas com nosso código fonte, você precisa incluir a parte do código que não está funcionando, indicando a linha apresenta o problema através do posicionamento de um comentário de código. Não inclua mais código que o necessário! Isso torna a mensagem difícil de ler e muitas pessoas podem simplesmente ignorar ela por isso. Se você não tiver certeza sobre quanta informação incluir na mensagem, é melhor incluir muito do que pouco.

Outra coisa importante a lembrar é resumir o problema no assunto da mensagem. Um assunto como "SOCCOOORRROO!!!" ou "Qual é o problema aqui" será ignorada pela maioria dos leitores.

E finalmente, você é encorajado a ler o artigo sobre » Como Fazer Perguntas de Maneira Inteligente já que irá ser de grande ajuda para todo mundo, especialmente você.

User Contributed Notes

There are no user contributed notes for this page.


Obtendo o PHP

Essa seção tem detalhes sobre localizações de download do PHP e problemas com Sistemas Operacionais.

  1. Onde posso obter o PHP?
  2. Existem versões binárias pré-compiladas?
  3. Onde posso pegar as bibliotecas necessárias para compilar alguma das extensões opcionais do PHP?
  4. Como faço essas bibliotecas funcionarem?
  5. Eu peguei a última versão do código-fonte do PHP do repositório Git na minha máquina Windows, o que eu preciso para compilá-lo?
  6. Onde eu acho o Arquivo de Capacidades do Navegador (Browser Capabilities File)?
  7. O que significa thread safety quando estou fazendo o download do PHP?
Onde posso obter o PHP?

Você pode baixar o PHP de qualquer um dos membros da rede de sites do PHP. Esses podem ser encontrados em » https://www.php.net/. Você pode usar também um Git anônimo para pegar a última versão do fonte. Para mais informações, vá até » https://www.php.net/git.php.

Existem versões binárias pré-compiladas?

Nós só distribuímos binários pré-compilados para sistemas Windows, como não somos capazes de compilar o PHP para cada uma das plataformas Linux/Unix com cada combinação de extensão. Perceba também, que muitas distribuições Linux vem com o PHP instalado atualmente. Binários do Windows podem ser baixados da nossa página de » Downloads, para binários do Linux, por favor visite o website de sua distribuição.

Onde posso pegar as bibliotecas necessárias para compilar alguma das extensões opcionais do PHP?

Nota: Aquelas marcadas com um * são do melhor de nosso conhecimento não thread safe; elas não são recomendadas para utilização em um ambiente multi-thread.

  • » LDAP (Unix).
  • » LDAP (Unix/Win) : Diretório Mozilla (LDAP) SDK
  • » servidor LDAP livre.
  • » Berkeley DB2 (Unix/Win) : http://www.sleepycat.com/.
  • » SNMP* (Unix): .
  • » GD* (Unix/Win).
  • » mSQL* (Unix).
  • » PostgreSQL (Unix).
  • » IMAP* (Win/Unix).
  • » Sybase-CT* (Linux, libc5) : Disponível localmente.
  • » FreeType (libttf):.
  • » ZLib (Unix/Win32).
  • » expat XML parser (Unix/Win32).
  • » PDFLib.
  • » mcrypt.
  • » mhash.
  • » t1lib.
  • » dmalloc.
  • » aspell.
  • » readline.

Como faço essas bibliotecas funcionarem?

Você precisará seguir as instruções disponíveis com a biblioteca. Algumas dessas bibliotecas são detectadas automaticamente quando você executar o script 'configure' do PHP (como a biblioteca GD), e outras você terá que habilitar usando opções '--with-EXTENSION' do 'configure'. Execute 'configure --help' para listar essas opções.

Eu peguei a última versão do código-fonte do PHP do repositório Git na minha máquina Windows, o que eu preciso para compilá-lo?

Veja a Wiki do PHP para instruções atualizadas: » Instruções passo-a-passo

Onde eu acho o Arquivo de Capacidades do Navegador (Browser Capabilities File)?

Você pode achar um arquivo browscap.ini em » http://browscap.org/.

O que significa thread safety quando estou fazendo o download do PHP?

Thread Safety significa que o binário pode trabalhar em um contexto de servidor web multithread, como o Apache 2 no Windows. Thread Safety funciona criando uma cópia local em cada thread, de modo que os dados não colidirão com outra thread.

Então como eu escolho? Se você escolher rodar PHP como binário CGI, então você não precisa do thread safe, porque o binário é chamado a cada requisição. Para servidores web multithread, como o IIS5 e IIS6, você deve usar a versão thread do PHP.

User Contributed Notes

There are no user contributed notes for this page.


Questões sobre banco de dados

Esta seção possui questões comuns sobre a relação entre o PHP e bases de dados. Sim, o PHP pode acessar virtualmente qualquer base de dados disponível atualmente.

  1. Eu ouvi que é possível acessar o Microsoft SQL Server através do PHP. Como?
  2. Consigo acessar bases de dados Microsoft Access?
Eu ouvi que é possível acessar o Microsoft SQL Server através do PHP. Como?

Em máquinas Unix você pode utilizar o PDO_ODBC ou a API ODBC Unificada.

Em máquinas Windows você também pode utilizar PDO_SQLSRV ou SQLSRV.

Veja também a resposta da questão seguinte.

Consigo acessar bases de dados Microsoft Access?

Se você estiver rodando PHP em uma box Unix e quiser conversar com o Microsoft Access em uma box Windows será necessário instalar os drivers ODBC para Unix. » OpenLink Software possui drivers para sistemas baseados em Unix que podem fazer isto.

Outra alternativa é usar um servidor SQL que possua drivers Windows ODBC e utilizá-los para armazenar os dados, que você pode então acessar através do Microsoft Access (usando ODBC) e do PHP (usando os drivers já existentes), ou usando um formato de arquivo intermediário que o Microsoft Access e o PHP consigam entender, como arquivos comuns ou bases de dados dBase. Neste ponto Tim Hayes, da OpenLink Software, escreve:

Usar outra base de dados como intermediária não é uma boa ideia, quando você pode usar o ODBC do PHP diretamente para a base de dados - por exemplo, com os drivers fornecidos pela OpenLink. Se você precisar utilizar um formato de arquivo intermediário, a OpenLink lançou o Virtuoso (uma engine de base de dados virtual) para NT, Linux e outras plataformas Unix. Por favor visite » nossa página para um download gratuito.

Uma opção que se mostrou funcional é utilizar MySQL e seus drivers MyODBC no Windows e sincronizar as bases de dados. Steve Lawrence disse:

  • Instale o MySQL em sua plataforma normalmente. A ultima versão está disponível em » http://www.mysql.com/ Nenhuma configuração especial é necessária, exceto quando você configura um banco de dados, e configura uma conta de usuário, quando você deve colocar % no campo host, ou o hostname da máquina Windows com a qual você deseja acessar o MySQL. Anote o nome do seu servidor, o usuário e a senha.
  • Baixe o driver MyODBC para Windows através do site oficial do MySQL. Instale-o em sua máquina Windows. Você pode testar a operação com os utilitários inclusos no programa.
  • Crie um usuário ou dsn de sistema em seu ODBC Administrator, localizado no painel de controle. Crie um nome dsn, entre com seu hostname, usuário, senha, porta, etc. para sua base de dados MySQL configurada no passo 1.
  • Instale o Access com uma instalação completa, isto dá certeza de que você instalou os add-ins necessários... você precisará, ao menos, ter suporte à ODBC e ao gerenciador de tabelas ligadas (linked table manager).
  • Agora a parte divertida! Crie uma nova base de dados Access. Clique com o botão direito na janela de tabelas e selecione Link Tables, ou sob o menu File selecione Get External Data e depois Link Tables. Quando a caixa de navegação de arquivos aparecer, selecione arquivos do tipo: ODBC. Selecione System dsn e o nome do dsn criado no passo 3. Selecione a tabela para ligar, pressione OK, e presto! Agora você consegue abrir a tabela e adicionar/remover/editar dados em seu servidor MySQL! Você também pode construir queries, importar/exportar tabelas para MySQL, construir forumlários e relatórios, etc.

Dicas e Truques:

  • Você pode construir suas tabelas no Access e exportá-las para o MySQL, e então conectá-las de volta. Isto torna o processo de criação de tabelas mais rápido.
  • Quando criar tabelas no Access você deve definir uma chave primária para ter acesso à escrita na tabela no Access. Certifique-se de que criou uma chave primária no MySQL antes de conectá-lo ao Access.
  • Se você alterar a tabela no MySQL, você deve conectá-la novamente no Access. Vá para tools > add-ins > linked table manager, vá até seu ODBC DSN, e selecione a tabela para conectá-la novamente a partir de lá. Você também pode mover seu fonte dsn por ali, apenas selecione o checkbox "always prompt for new location" antes de pressionar OK.

User Contributed Notes

doug at unlikelysource dot com 31-Mar-2017 08:53
To enable SQL Server access from ubuntu 16.04:

* Run these commands:
```
sudo curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > mssql-release.list
sudo mv mssql-release.list /etc/apt/sources.list.d
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install msodbcsql unixodbc-dev
sudo apt-get install php7.1-dev
sudo apt-get install autoconf
sudo pecl install pdo_sqlsrv-4.1.6.1
```

*  Confirm ODBC driver installation:
```
odbcinst -q -d -n "ODBC Driver 13 for SQL Server"
```

* Update the php.ini file: run` php --ini` to find the path to your php.ini file
* Add this line to /path/to/php.ini
```
extension=pdo_sqlsrv.so
```
* Run `php -i` to confirm SQLSRV support was added
* NOTE: extensions (on my computer) were installed here:
`/usr/local/lib/php/extensions/no-debug-non-zts-20160303/`

* Test user access directly on the Windows server running MSSQL:
```
sqlcmd -S ip_address -U username -P password -d database -q "select * from table_name"
```
* On the Windows server: open port 1433 in your firewall

* Install the FreeTds utils to test the connection:
```
sudo apt-get install freetds-bin
tsql -H mssql.host.ip.address -U username -P password -D database -p 1433
```

* Formulate the correct DSN (Data Source Name):
    See: http://php.net/manual/en/ref.pdo-sqlsrv.connection.php

* Sample PHP Code:
```
<?php
// Database params
$tcp  = '192.168.3.126';
$port = 1433;
$user = "test";
$password = "Password123";
$database = "test";

// Open connection
try {
    // Database connect -- use one of the two statements below
    $dsn =  'sqlsrv:Server=tcp:' . $tcp . ',' . $port . ';Database=' . $database;
    $dbh = new PDO( $dsn, $user, $password, array());
    // SQL prepare
    $sql = "SELECT * FROM prospects";
    $sth = $dbh->prepare($sql);
    // Execute
    $sth->execute();
    // Fetch results
    $row = $sth->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        $output = '<pre>';
        $output .= implode("\t", array_keys($row)) . PHP_EOL;
        $output .= implode("\t", $row) . PHP_EOL;
        while ($row = $sth->fetch(PDO::FETCH_NUM)) {
            $output .= implode("\t", $row) . PHP_EOL;
        }
    }
} catch (PDOException $e) {
    $output .= $e->getMessage();
}
$output .= '</pre>';
echo $output;
```
knb at gfz-potsdam dot de 11-Oct-2004 02:53
This is a crucial piece of information for SYBASE users:

If you are using the free, but old, 11.x client libs from sybase,
 then compile with option  "--with-sybase-ct=$SYBASE"
substitute $SYBASE with the appropriate directory name.

option --with-sybase (without ct) can somehow be used to talk to old MS-SQL servers, but only with the 11.x client libs.

If you are using free, or have legally obtained, 12.x client libs from sybase, then compile with option  "--with-sybase-ct=$SYBASE/$SYBASE_OCS"
substitute $SYBASE/$SYBASE_OCS with the appropriate directory name.


Instalação

Esta seção contém perguntas comuns sobre a maneira de instalar o PHP. O PHP está disponível para quase todos os sistemas operacionais, e praticamente qualquer servidor web.

Para instalar o PHP, siga as instruções em Instalação e Configuração.

  1. Por que não devemos usar o Apache2 com um módulo MPM com threads em um ambiente de produção?
  2. Unix/Windows: Onde deveria estar localizado meu arquivo php.ini?
  3. Unix: Eu instalei o PHP, mas toda vez que carrego um documento, recebo a mensagem 'Document Contains No Data'! O que está acontecendo?
  4. Unix: Eu instalei o PHP usando RPMS, mas o Apache não está processando as páginas PHP! O que está acontecendo aqui?
  5. Unix: Eu corrigi o Apache com o patch das extensões FrontPage, e repentinamente o PHP parou de funcionar. O PHP é incompatível com as extensões FrontPage do Apache?
  6. Unix/Windows: Eu tenho o PHP instalado, mas quando tento acessar um arquivo de script PHP através do meu browser, recebo uma tela em branco.
  7. Unix/Windows: Eu instalei o PHP, mas quando tento acessar um arquivo de script PHP através do meu browser, recebo um erro 500 do servidor.
  8. Alguns sistemas operacionais: Eu instalei o PHP sem erros, mas quando eu tento iniciar o Apache recebo erros de undefined symbol: [mybox:user /src/php5] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress
  9. Windows: Eu instalei o PHP, mas quando tento acessar um arquivo de script PHP através do meu browser, eu recebo o erro: cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
  10. Windows: Eu segui todas as instruções, mas ainda não consegui fazer o PHP e o IIS trabalharem juntos!
  11. Quando executo o PHP como CGI com o IIS, PWS, OmniHTTPD ou Xitami, recebo o seguinte erro: Security Alert! PHP CGI cannot be accessed directly..
  12. Como eu sei se meu php.ini está sendo encontrado e lido? Parece que ele não está, já que as minhas alterações não estão sendo efetuadas.
  13. Como eu adiciono meu diretório PHP ao PATH do Windows?
  14. Como eu torno o arquivo php.ini disponível para o PHP no Windows?
  15. É possível usar a negociação de conteúdo do Apache (opção MultiViews) com o PHP?
  16. O PHP é limitado a processar apenas os métodos de requisições GET e POST?
Por que não devemos usar o Apache2 com um módulo MPM com threads em um ambiente de produção?

O PHP é como uma cola. É a cola usada para construir aplicações web legais unindo dezenas de bibliotecas de terceiros e fazendo tudo aparecer como uma entidade coerente através de uma interface de linguagem intuitiva e fácil de aprender. A flexibilidade e poder do PHP dependem da estabilidade e robustez da plataforma subjacente. Ele precisa de um sistema operacional funcionando, um servidor web funcionando e bibliotecas de terceiros funcionando para juntar. Quando qualquer um desses elementos pára de funcionar o PHP precisa de meios de identificar e remediar os problemas rapidamente. Quando tornamos a arquitetura subjacente mais complexa por não ter threads de execução completamente separadas, segmentos de memória completamente separados e uma sandbox sólida na qual executar cada requisição, mais problemas são introduzidos ao sistema do PHP.

Se quiser utilizar um módulo MPM com threads, veja uma configuração FastCGI onde o PHP seja executado em seu próprio espaço de memória.

Unix/Windows: Onde deveria estar localizado meu arquivo php.ini?

Por padrão no Unix ele deve estar em /usr/local/lib que é o <install-path>/lib. A maioria das pessoas vai querer mudar isso em tempo de compilação com a flag --with-config-file-path. Poderíamos, por exemplo, configurá-la com algo como:

--with-config-file-path=/etc
E então poderíamos copiar php.ini-development do local de origem da instalação para /etc/php.ini e editá-lo para fazer quaisquer alterações locais que desejássemos.

--with-config-file-scan-dir=PATH

No Windows, o caminho padrão para o arquivo php.ini é o diretório Windows. Se estivermos usando o servidor web Apache, o php.ini primeiro é procurado no diretório de instalação do Apache, por exemplo, c:\program files\apache group\apache. Desta maneira, poderíamos ter diferentes arquivos php.ini para diferentes versões do Apache na mesma máquina.

Veja também o capítulo sobre o arquivo de configuração.

Unix: Eu instalei o PHP, mas toda vez que carrego um documento, recebo a mensagem 'Document Contains No Data'! O que está acontecendo?

Isso provavelmente significa que o PHP está tendo algum tipo de problema e está sofrendo um core dump (fim com despejo de memória). Olhe nos logs de erro do servidor web para ver se este é o caso, e então tente reproduzir o problema com um pequeno caso de teste. Se você souber como usar 'gdb', é muito útil quando você pode fornecer um backtrace com seu relatório de erros para ajudar os desenvolvedores a identificar o problema. Se estiver usando o PHP como um módulo do Apache tente algo como:

  • Pare seus processos httpd

  • gdb httpd

  • Pare seus processos httpd

  • > execute -X -f /caminho/para/httpd.conf

  • Então acesse o URL que está causando problemas com seu browser.

  • > execute -X -f /caminho/para/httpd.conf

  • Se estiver ocorrendo um core dump, o gdb deverá informar sobre isso agora

  • type: bt

  • Você deve incluir o backtrace no seu relatório de erros. Envie o relatório para » https://github.com/php/php-src/issues

Se o seu script usa as funções de expressões regulares ( preg_match() e demais), você deve ter certeza de que compilou o PHP e o Apache com a mesma versão do pacote de expressões regulares. Isso deve acontecer automaticamente com o PHP e Apache 1.3.x.

Unix: Eu instalei o PHP usando RPMS, mas o Apache não está processando as páginas PHP! O que está acontecendo aqui?

Supondo que você instalou tanto o Apache quanto o PHP a partir dos pacotes RPM, você precisa descomentar ou adicionar algumas ou todas as linhas a seguir ao seu arquivo httpd.conf:

# Módulos extra
AddModule mod_php.c
AddModule mod_perl.c

# Módulos extra
LoadModule php_module         modules/mod_php.so
LoadModule php5_module        modules/libphp5.so
LoadModule perl_module        modules/libperl.so
E adicionar:
AddType application/x-httpd-php .php
... às propriedades globais, ou às propriedades do VirtualDomain ao qual você deseja adicionar o suporte ao PHP.

Unix: Eu corrigi o Apache com o patch das extensões FrontPage, e repentinamente o PHP parou de funcionar. O PHP é incompatível com as extensões FrontPage do Apache?

Não, O PHP funciona bem com as extensões FrontPage. O problema é que o patch do FrontPage modifica diversas estruturas do Apache, das quais o PHP depende. Recompilar o PHP (usando 'make clean ; make') depois de aplicar o patch FP deve resolver o problema.

Unix/Windows: Eu tenho o PHP instalado, mas quando tento acessar um arquivo de script PHP através do meu browser, recebo uma tela em branco.

Faça um 'view source' no navegador web e provavelmente descobrirá que pode ver o código fonte do seu script PHP. Isto significa que o seu servidor web não enviou o script para o interpretador do PHP. Algo está errado com as configurações do seu servidor - verifique novamente as configurações de seu servidor, com base nas instruções de instalação do PHP.

Unix/Windows: Eu instalei o PHP, mas quando tento acessar um arquivo de script PHP através do meu browser, recebo um erro 500 do servidor.

Alguma coisa deu errado quando o servidor tentou executar o PHP. Para conseguir ver uma mensagem de erro razoável, na linha de comando, mude para o diretório que contém o executável do PHP (php.exe no Windows) e execute php -i. Se o PHP tiver algum problema para rodar, então uma mensagem de erro apropriada será exibida, o que lhe dará pistas do que precisa ser feito em seguida. Se você receber uma tela cheia de códigos HTML (a saída da função phpinfo()) então o PHP está funcionando, e seu problema pode ser relacionado à configuração do seu servidor, que você deve verificar novamente.

Alguns sistemas operacionais: Eu instalei o PHP sem erros, mas quando eu tento iniciar o Apache recebo erros de undefined symbol:
[mybox:user /src/php5] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

Isto não tem nada a ver com o PHP, mas com as bibliotecas do cliente MySQL. Algumas necessitam de --with-zlib, outras não. Isso também é abordado nas FAQ do MySQL.

Windows: Eu instalei o PHP, mas quando tento acessar um arquivo de script PHP através do meu browser, eu recebo o erro:
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

Esta mensagem de erro significa que o PHP falhou em gerar qualquer saída. Para começar a ver uma mensagem de erro razoável, na linha de comando, mude para o diretório que contém o executável PHP (php.exe no Windows) e execute php -i. Se o PHP estiver com algum problema para rodar, então uma mensagem de erro adequada será exibida, o que lhe dará uma ideia do que precisa ser feito em seguida. Se você receber uma tela cheia de códigos HTML (a saída da função phpinfo()) então o PHP está funcionando.

Uma vez que o PHP esteja funcionando na linha do comando, tente acessar o script via navegador novamente. Se ele ainda falhar, então pode ser um dos seguintes:

  • As permissões de arquivo no seu script PHP, php.exe, php5ts.dll, php.ini ou qualquer extensão do PHP que você está tentando carregar são tais que o usuário anônimo ISUR_<machinename> não pode acessá-los.
  • O arquivo de script não existe (ou provavelmente não está onde você acha que ele está em relação ao seu diretório root web). Note que com o IIS você pode interceptar o erro marcando a opção 'verificar se o arquivo existe' quando configurar os mapeamentos de script no Gerenciador de Serviços de Internet. Se um arquivo de script não existe então o servidor web irá retornar um erro 404. Há também o benefício adicional que o IIS fará qualquer autenticação exigida para você com base nas permissões NTLanMan no seu arquivo de script.
Windows: Eu segui todas as instruções, mas ainda não consegui fazer o PHP e o IIS trabalharem juntos!

Certifique-se de que qualquer usuário que precise executar um script PHP tem permissão para executar o php.exe! O IIS usa um usuário anônimo que é adicionado no momento que o IIS é instalado. Este usuário precisa de permissões para o php.exe. Além disso, qualquer usuário autenticado também precisará ter permissão para executar o php.exe. E para o IIS4 você precisa dizer que o PHP é um engine de script. Além disso, você também vai querer ler esta FAQ.

Quando executo o PHP como CGI com o IIS, PWS, OmniHTTPD ou Xitami, recebo o seguinte erro: Security Alert! PHP CGI cannot be accessed directly..

Você deve definir a diretiva cgi.force_redirect para 0. O padrão é 1, então certifique-se que a directiva não está comentada (com um ;). Como todas as diretivas, esta é definida no php.ini

Pelo fato do padrão ser 1, é fundamental que você tenha certeza de que o arquivo php.ini correto está sendo lido. Leia esta FAQ para detalhes.

Como eu sei se meu php.ini está sendo encontrado e lido? Parece que ele não está, já que as minhas alterações não estão sendo efetuadas.

Para ter certeza de que seu php.ini está sendo lido pelo PHP, faça uma chamada à função phpinfo(). Próximo ao topo, haverá uma lista chamada Configuration File (php.ini). Esta irá lhe dizer onde o PHP está procurando o php.ini e se ele está sendo lido ou não. Se houver apenas um diretório do PATH, então ele não está sendo lido e você deve colocar seu php.ini neste diretório. Se o php.ini está incluso dentro do PATH, ele está sendo lido.

Se o php.ini está sendo lido e seu PHP está sendo executado como um módulo, então certifique-se de reiniciar seu servidor web depois de fazer alterações no php.ini.

Veja também php_ini_loaded_file().

Como eu adiciono meu diretório PHP ao PATH do Windows?

No Windows:

  • Vá até o Painel de Controle e abra o ícone de Sistema (Iniciar ? Painel de Controle)

  • Vá até a aba Avançado

  • Clique no botão 'Variáveis de Ambiente'

  • Procure o painel 'Variáveis do Sistema'

  • Encontre o item Path (talvez você precise rolar a lista para encontrá-lo)

  • Dê um duplo clique no item Path

  • Adicione seu diretório do PHP ao final, incluindo ';' antes (por exemplo, ;C:\php)

  • Aperte OK e reinicie seu computador

Nota: Certifique-se de reiniciar depois de seguir os passos acima para garantir que as alterações ao PATH sejam aplicadas.

Como eu torno o arquivo php.ini disponível para o PHP no Windows?

Existem várias maneiras de fazer isso. Se você estiver usando o Apache, consulte a documentação do Apache, caso contrário, você deve definir a variável de ambiente PHPRC.

É possível usar a negociação de conteúdo do Apache (opção MultiViews) com o PHP?

Se os links para arquivos PHP incluem extensões, tudo funcionará perfeitamente. Esta FAQ é apenas para o caso em que links para arquivos PHP não incluem a extensão e você quer usar a negociação de conteúdo para selecionar arquivos PHP a partir de URLs sem nenhuma extensão. Neste caso, substitua a linha AddType application/x-httpd-php .php por:

AddHandler php5-script php
AddType text/html php
Esta solução não funciona para o Apache 1, pois o módulo PHP não captura php-script.

O PHP é limitado a processar apenas os métodos de requisições GET e POST?

Não, é possível lidar com qualquer método de requisição, por exemplo, CONNECT. Status de respostas adequados podem ser enviados com header(). Se somente os métodos GET e POST devem ser manipulados, isso pode ser alcançado com esta configuração do 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 Compilação

Esta seção reúne os erros mais comuns que ocorrem na compilação.

  1. Eu peguei a última versão do PHP usando o serviço anônimo do GIT, mas não há nenhum script de configuração!
  2. Estou tendo problemas para configurar o PHP para trabalhar com Apache. Diz que não consegue encontrar httpd.h, mas está bem onde eu disse que está!
  3. Se enquanto estiver configurando o (./configure) do PHP, você se deparar com um erro semelhante ao seguinte: checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up
  4. Quando tento iniciar o Apache, recebo a seguinte mensagem: fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found
  5. Quando eu executo configure, ele diz que não pode encontrar os arquivos de inclusão ou a biblioteca GD, gdbm, ou algum outro pacote!
  6. Quando se está compilando o arquivo language-parser.tab.c, ele me devolve um erro que diz yytname undeclared.
  7. Quando eu executo make, parace rodar bem mas então falha quando tenta ligar a aplicação final, queixando-se que não consegue encontrar alguns arquivos.
  8. Quando linkando o PHP, ele reclama de um número de referências indefinidas.
  9. Eu segui todos os passos da instalação do módulo da versão do Apache no Unix, e meus scripts PHP estão sendo mostrados no meu navegador ou me é solicitado salvar os arquivos.
  10. Lá diz para usar: --activate-module=src/modules/php4/libphp4.a, mas esse arquivo não existe, então mudei para --activate-module=src/modules/php4/libmodphp4.a e não funciona!? O que está acontecendo?
  11. Quando tento compilar o Apache com o PHP como um módulo estático usando --activate-module=src/modules/php4/libphp4.a ele me diz que o meu compilador não é compatível com ANSI.
  12. Quando tento compilar o PHP usando --with-apxs recebo mensagens de erro estranhas.
  13. Durante make, eu recebo erros no microtime, e um monte de RUSAGE_.
  14. Ao compilar o PHP com MySQL, o configure vai bem, mas durante o make recebo um erro semelhante ao seguinte: 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', o que está errado ?
  15. Eu quero atualizar o meu PHP. Onde posso encontrar a linha ./configure que foi usada para compilar a minha instalação atual do PHP?
  16. Quando compilo o PHP com a biblioteca GD retorna erros de compilação ou segfaults na execução.
  17. Ao compilar o PHP eu recebo erros aparentemente aleatórios, como se ele travasse. Estou usando o Solaris, se isso importa.
Eu peguei a última versão do PHP usando o serviço anônimo do GIT, mas não há nenhum script de configuração!

Você precisa ter o pacote GNU autoconf instalado para que possa gerar o script configure a partir do configure.in. Basta executar ./buildconf no diretório raiz após a obtenção do código fonte do servidor do GIT. (Além disso, a menos que você execute com configure com a opção --enable-maintainer-mode, o script configure não será automaticamente recompilado quando o arquivo configure.in for atualizado, então você deve certificar-se de fazer isso manualmente quando você perceber que o configure.in mudou. Um sintoma disso é encontrar coisas como @VARIABLE@ em seu Makefile após configure ou config.statustiver sido executado.)

Estou tendo problemas para configurar o PHP para trabalhar com Apache. Diz que não consegue encontrar httpd.h, mas está bem onde eu disse que está!

Você precisa informar ao script configure/setup a localização do diretório raíz do Apache. Isto significa que você precisa especificar --with-apache=/caminho/para/apache e não --with-apache=/caminho/para/apache/src.

Se enquanto estiver configurando o (./configure) do PHP, você se deparar com um erro semelhante ao seguinte:

checking lex output file root... ./configure: lex: command not found
configure: error: cannot find output from lex; giving up

Não deixe de ler as instruções de instalação cuidadosamente e note que você precisa de ambos flex e bison instalados para compilar o PHP. Dependendo da sua configuração você irá instalar bison e flex a partir de uma fonte ou pacote, como um RPM.

Quando tento iniciar o Apache, recebo a seguinte mensagem:

fatal: relocation error: file /path/to/libphp4.so:
symbol ap_block_alarms: referenced symbol not found

Esse erro geralmente aparece quando um compila o core do Apache como uma biblioteca DSO para uso compartilhado. Tente reconfigurar o apache, certificando-se de usar pelo menos um dos seguintes parâmetros:

--enable-shared=max --enable-rule=SHARED_CORE

Para obter mais informações, leia o arquivo INSTALL que se encontra na pasta raíz do Apache ou a » página sobre DSO no manual do Apache.

Quando eu executo configure, ele diz que não pode encontrar os arquivos de inclusão ou a biblioteca GD, gdbm, ou algum outro pacote!

Você pode fazer o script configure procurar por arquivos de cabeçalho e bibliotecas em locais diferentes, especificando parâmetros adicionais para passar para o pré-processador C e linker, tais como:

    CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
If you're using a csh-variant for your login shell (why?), it would be:
    env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

Quando se está compilando o arquivo language-parser.tab.c, ele me devolve um erro que diz yytname undeclared.

Você precisa atualizar sua versão do Bison. Você pode encontrar a última versão em » http://www.gnu.org/software/bison/bison.html.

Quando eu executo make, parace rodar bem mas então falha quando tenta ligar a aplicação final, queixando-se que não consegue encontrar alguns arquivos.

Algumas versões antigas do make que não colocam corretamente a versão compilada dos arquivos nos diretórios das funções dentro do mesmo diretório. Tente rodar cp *.o functions e então execute novamente make para ver se isso ajuda. Se não ajudar, você realmente deve atualizar para uma versão mais recente do GNU make.

Quando linkando o PHP, ele reclama de um número de referências indefinidas.

Confira a linha do link e tenha certeza que todas as bibliotecas apropriadas estão sendo incluídas no final. É comum que talvez você tenha esquecido os '-ldl' e qualquer biblioteca requerida para qualquer suporte de banco de dados que você incluiu.

Algumas pessoas também reportaram que elas precisaram adicionar '-ldl' imediatamente seguindo libphp4.a quando linkando com o Apache.

Eu segui todos os passos da instalação do módulo da versão do Apache no Unix, e meus scripts PHP estão sendo mostrados no meu navegador ou me é solicitado salvar os arquivos.

Isso significa que o módulo do PHP não está sendo chamado por alguma razão. Três coisas para se verificar antes de pedir por mais ajuda:

  • Tenha certeza que o binário httpd que você está executando é o que você acabou de compilar. Para fazer isso, tente executar: /path/to/binary/httpd -l Se você não vê mod_php4.c na lista, então você não está executando o binário correto. Encontre e instale o binário correto.
  • Certifique-se de ter adicionado o Mime Type correto em um dos seus arquivos Apache .conf. Deveria ser: AddType application/x-httpd-php .php Também certifique-se que esta linha AddType não esteja escondida dentro de um bloco <Virtualhost> ou <Directory> que possam impedí-la de ser aplicada para a localização de seu script de teste.
  • Finalmente, a localização padrão dos arquivos de configuração do Apache mudou entre o Apache 1.2 e Apache 1.3. Você deve verificar para ter certeza que o arquivo de configuração que você está adicionando à linha do AddType realmente está sendo lido. Você pode colocar um erro de sintaxe óbvio em seu arquivo httpd.conf ou alguma outra mudança evidente que diga se o arquivo está sendo lido corretamente.

Lá diz para usar: --activate-module=src/modules/php4/libphp4.a, mas esse arquivo não existe, então mudei para --activate-module=src/modules/php4/libmodphp4.a e não funciona!? O que está acontecendo?

Note que o arquivo libphp4.a não é para existir. O processo apache irá criá-lo!

Quando tento compilar o Apache com o PHP como um módulo estático usando --activate-module=src/modules/php4/libphp4.a ele me diz que o meu compilador não é compatível com ANSI.

Esta é uma mensagem de erro enganosa do Apache que foi corrigida nas versões mais recentes.

Quando tento compilar o PHP usando --with-apxs recebo mensagens de erro estranhas.

Há três coisas para verificar aqui. Em primeiro lugar, por alguma razão o Apache quando compila o script Perl apxs, às vezes acaba sendo compilado sem o compilador e os parâmetros corretos. Procure pelo seu script apxs (tente o comando which apxs), às vezes é encontrado em /usr/local/apache/bin/apxs ou /usr/sbin/apxs. Abra-o e verifique se existem linhas semelhantes 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
Se é isso que você vê, você encontrou o seu problema. Elas podem conter apenas espaços ou outros valores incorretos, como 'q()'. Altere estas linhas de modo que fiquem assim:
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
O segundo problema possível só deve ser um problema no Red Hat 6.1 e 6.2. O script apxs do Red Hat está quebrado. Procure por esta linha:
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
Se você vê a linha acima, mude para isto:
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
Finalmente, se você reconfigurar/reinstalar o Apache, adicione make clean ao processo após o ./configure e antes de make.

Durante make, eu recebo erros no microtime, e um monte de RUSAGE_.

Enquanto é executada a porção make da instalação, se você encontrar problemas que parecem semelhantes a estes:

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

Seu sistema está quebrado. É preciso corrigir os arquivos /usr/include instalando o pacote glibc-devel que corresponde ao seu glibc. Isto não tem absolutamente nada a ver com o PHP. Para provar isso a si mesmo, tente este teste simples:

$ cat >test.c <<X
#include <sys/resource.h>
X
$ gcc -E test.c >/dev/null
Se isso mostrar erros, você saberá que os arquivos include estão bagunçados.

Ao compilar o PHP com MySQL, o configure vai bem, mas durante o make recebo um erro semelhante ao seguinte: 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', o que está errado ?

Primeiramente, é importante perceber que este é um Warning e não um erro fatal. Porque esta é muitas vezes a última saída durante o make, ela pode parecer um erro fatal, mas não é. Claro que, se você definir o seu compilador para parar em warnings, ele vai parar. Além disso tenha sempre em mente que o suporte ao MySQL está habilitado por padrão.

Nota:

A partir do PHP 4.3.2, você também verá o seguinte texto depois que a compilação (make) for concluída:

Build complete.
(It is safe to ignore warnings about tempnam and tmpnam).

Eu quero atualizar o meu PHP. Onde posso encontrar a linha ./configure que foi usada para compilar a minha instalação atual do PHP?

Ou você olha no arquivo config.nice, na pasta raíz atual da sua instalação do PHP, ou, se este não estiver disponível, basta executar um script

<?php phpinfo(); ?>
No topo da saída a linha ./configure que foi usada para compilar esta instalação do PHP é mostrada.

Quando compilo o PHP com a biblioteca GD retorna erros de compilação ou segfaults na execução.

Certifique-se de que sua biblioteca GD e o PHP estejam ligadas à mesmas bibliotecas dependentes (libpng por exemplo).

Ao compilar o PHP eu recebo erros aparentemente aleatórios, como se ele travasse. Estou usando o Solaris, se isso importa.

Usar utilitários que não são GNU ao compilar o PHP pode causar problemas. Certifique-se de usar as ferramentas GNU, a fim de ter certeza de que a compilação do PHP funcionará. Por exemplo, no Solaris, usando tanto o SunOS BSD-compatible quanto versões do Solaris sed não vai funcionar, mas usando as versões GNU ou Sun POSIX (XPG4) do sed irá funcionar. Links: » GNU sed, » GNU flex, e » 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.


Utilizando o PHP

Esta seção reúne vários erros comuns que você pode encontrar enquanto estiver escrevendo scripts PHP.

  1. Não consigo me lembrar da ordem dos parâmetros das funções PHP. Eles são aleatórios?
  2. Eu gostaria de escrever um script PHP genérico que fosse capaz de manipular dados provenientes de qualquer formulário. Como eu sei quais variáveis do método POST estão disponíveis?
  3. Preciso converter todas as aspas simples (') para uma barra invertida seguida por uma aspa simples (\'). Como eu posso fazer isso utilizando expressões regulares? Gostaria de converter também " para \" e \ para \\.
  4. Quando eu faço o seguinte, a saída é exibida na ordem errada: <?php function myfunc($argument) { echo $argument + 10; } $variable = 10; echo "myfunc($variable) = " . myfunc($variable); ?> o que está acontecendo?
  5. Ei, o que aconteceu com as minhas novas linhas? <pre> <?php echo "Esta deve ser a primeira linha."; ?> <?php echo "Esta deveria ser uma nova linha."; ?> </pre>
  6. Recebi a mensagem 'Warning: Cannot send session cookie - headers already sent...' ou 'Cannot add header information - headers already sent...'.
  7. Preciso acessar informações no cabeçalho de requisição diretamente. Como eu faço isso?
  8. Quando eu tento utilizar autenticação com o IIS eu recebo a mensagem 'No Input file specified'.
  9. Windows: Não consigo acessar arquivos compartilhados em outro computador utilizando IIS.
  10. Como faço para misturar XML e PHP? Ele reclama das minhas tags <?xml!
  11. Onde posso encontrar uma lista completa das variáveis que estão disponíveis para mim no PHP?
  12. Como posso gerar arquivos PDF sem utilizar bibliotecas não-livres e comerciais como PDFLib? Eu gostaria de alguma que fosse livre e não precisasse de bibliotecas PDF externas.
  13. Algumas diretivas PHP podem receber valores em bytes de forma abreviada (1K), ao contrário de apenas valores int. Quais são todas as opções disponíveis de bytes de forma abreviada?
Não consigo me lembrar da ordem dos parâmetros das funções PHP. Eles são aleatórios?

O PHP é uma "cola" que reúne centenas de bibliotecas externas, então às vezes isso fica desorganizado. No entanto, uma regra simples é a seguinte:

Os parâmetros de funções de Array são ordenados como "needle, haystack" ao passo que funções de String são o contrário, logo "haystack, needle".

Eu gostaria de escrever um script PHP genérico que fosse capaz de manipular dados provenientes de qualquer formulário. Como eu sei quais variáveis do método POST estão disponíveis?

O PHP disponibiliza muitas variáveis predefinidas, como a superglobal $_POST. Você pode iterar através de $_POST, já que ele é um array associativo com todos os valores enviados com o método POST. Por exemplo, vamos iterar através de POST com foreach, verificar se há valores vazios com empty() e imprimi-los na tela.

<?php
$empty = $post = array();
foreach ($_POST as $varname => $varvalue) {
if (empty($varvalue)) {
$empty[$varname] = $varvalue;
} else {
$post[$varname] = $varvalue;
}
}

print "<pre>";
if (empty($empty)) {
print "Nenhum dos valores enviados com POST estão vazios, enviado:\n";
var_dump($post);
} else {
print "Temos " . count($empty) . " valores vazios\n";
print "Enviado:\n"; var_dump($post);
print "Vazio:\n"; var_dump($empty);
exit;
}
?>

Preciso converter todas as aspas simples (') para uma barra invertida seguida por uma aspa simples (\'). Como eu posso fazer isso utilizando expressões regulares? Gostaria de converter também " para \" e \ para \\.

Considerando que isso seja para um banco de dados, utilize o mecanismo de escape que vem com o banco de dados. Por exemplo, utilize mysql_real_escape_string() com MySQL e pg_escape_string() com PostgreSQL. Existem também as funções genéricas addslashes() e stripslashes(), que são mais comuns com códigos PHP antigos.

Quando eu faço o seguinte, a saída é exibida na ordem errada:
<?php
function myfunc($argument)
{
echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?>
o que está acontecendo?

Para ser capaz de utilizar os resultados de suas funções em uma expressão (como concatenar com uma string no exemplo acima), você precisa utilizar return para retornar o valor e não echo.

Ei, o que aconteceu com as minhas novas linhas?
<pre>
<?php echo "Esta deve ser a primeira linha."; ?>
<?php echo "Esta deveria ser uma nova linha."; ?>
</pre>

No PHP, um bloco de código é fechado com "?>" ou "?>\n" (onde \n significa uma nova linha). Logo, no exemplo anterior, as sentenças serão exibidas na mesma linha porque o PHP omite o caractere de nova linha após o final do bloco de código. Isso significa que você precisa inserir uma nova linha depois de cada bloco de código PHP para exibi-las em uma nova linha.

Por que o PHP faz isso? Porque quando está formatando HTML, isto normalmente torna sua vida mais fácil porque não se quer esta nova linha, senão você teria que criar linhas extremamente longas ou tornar o código fonte ilegível para alcançar este efeito.

Recebi a mensagem 'Warning: Cannot send session cookie - headers already sent...' ou 'Cannot add header information - headers already sent...'.

As funções header(), setcookie() e as funções de sessão precisam adicionar os cabeçalhos ao stream de saída, mas os cabeçalhos só podem ser enviados antes de qualquer outro conteúdo. Não pode haver nenhuma saída antes de utilizar estas funções como HTML. A função headers_sent() irá verificar se o seu script já enviou cabeçalhos e veja também as funções de Controle de Saída.

Preciso acessar informações no cabeçalho de requisição diretamente. Como eu faço isso?

A função getallheaders() fará isso se você estiver rodando o PHP como um módulo do Apache. Logo, o fragmento de código abaixo sempre exibirá todos os cabeçalhos de requisição:

<?php
$headers = getallheaders();
foreach ($headers as $name => $content) {
echo "headers[$name] = $content<br />\n";
}
?>

Veja também
apache_lookup_uri(),
apache_response_headers() e
fsockopen()

Quando eu tento utilizar autenticação com o IIS eu recebo a mensagem 'No Input file specified'.

O modelo de segurança do IIS é o culpado aqui. Este é um problema comum a todos os programas CGI rodando no IIS. A solução é criar um arquivo HTML (não interpretado pelo PHP) como uma página de entrada para o diretório autenticado. Então utilizar a tag META para redirecionar para a página PHP ou fornecer um link para a página PHP. O PHP irá então reconhecer a autenticação corretamente. Com o módulo ISAPI, este não é um problema. Isto não deve afetar outros servidores web NT. Para mais informações veja: » http://support.microsoft.com/kb/q160422/ e a seção do manual em Autenticação HTTP .

Windows: Não consigo acessar arquivos compartilhados em outro computador utilizando IIS.

Você terá que alterar o Go to Internet Information Services. Localize o arquivo PHP e vá até as suas propriedades. Vá até a aba File Security, Edit -< Anonymous access and authentication control.

Pode-se corrigir o problema desabilitando Anonymous Access e deixando Integrated Window Authentication habilitado, ou habilitando Anonymous Access e editando o usuário para que ele não possa ter o direito de acesso.

Como faço para misturar XML e PHP? Ele reclama das minhas tags <?xml!

Para utilizar <?xml diretamente no seu código PHP, você terá que desabilitar as short tags definindo a diretiva PHP short_open_tags como 0. Você não pode configurar esta diretiva com a função ini_set(). Independentemente de short_open_tags estar ativada ou não, você pode fazer algo como: <?php echo '<?xml'; ?>. O padrão para esta diretiva é On.

Onde posso encontrar uma lista completa das variáveis que estão disponíveis para mim no PHP?

Leia a página do manual variáveis predefinidas dado que ele inclui uma lista parcial das variáveis predefinidas disponíveis para o seu script. Uma lista completa das variáveis disponíveis (e muito mais informação) pode ser vista chamando a função phpinfo(). Não deixe de ler a seção do manual variáveis de fontes externas uma vez que descreve cenários comuns para variáveis externas como aquelas originadas de um formulário HTML, cookie ou da URL.

Como posso gerar arquivos PDF sem utilizar bibliotecas não-livres e comerciais como PDFLib? Eu gostaria de alguma que fosse livre e não precisasse de bibliotecas PDF externas.

Existem algumas poucas alternativas escritas em PHP como » FPDF e » TCPDF.

Algumas diretivas PHP podem receber valores em bytes de forma abreviada (1K), ao contrário de apenas valores int. Quais são todas as opções disponíveis de bytes de forma abreviada?

As opções disponíveis são K (para Kilobytes), M (para Megabytes) e G (para Gigabytes), tanto em maiúsculas ou minúsculas. Qualquer outra coisa é tratada como bytes. 1M é igual a um Megabyte ou 1048576 bytes. 1K é igual a um Kilobyte ou 1024 bytes. Essas notações abreviadas podem ser utilizadas no php.ini e na função ini_set(). Importante observar que os valores são truncados para int apenas, ou seja, 0.5M será interpretado como 0.

Nota: kilobyte versus kibibyte

A notação do PHP descreve um kilobyte equivalente a 1024 bytes, enquanto que o padrão IEC considera que este deve ser um kibibyte. Resumindo: k e 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.


Gerando hash seguro de senha

Esta seção explica as razões por trás do uso de funções de hash para proteger senhas, bem como fazê-lo de forma eficaz.

  1. Por que eu deveria gerar hash das senhas fornecidas pelos usuários da minha aplicação?
  2. Por que são comuns funções de hash tais como md5 e sha1 inadequados para senhas?
  3. Como devo criptografar minhas senhas, se as funções hash comuns não são adequadas?
  4. O que é um salt?
  5. Como faço para armazenar meus salts?
Por que eu deveria gerar hash das senhas fornecidas pelos usuários da minha aplicação?

Gerar hash de senha é uma das considerações mais básicas de segurança que deve ser feita ao projetar qualquer aplicativo que aceita senhas dos usuários. Sem gerar hash, todas as senhas armazenadas em seu banco de dados da aplicação podem ser roubadas, e então imediatamente usada para comprometer não só a sua aplicação, mas também as contas de seus usuários em outros serviços, se eles não usarem senhas únicas.

Aplicando um algoritmo de hash para a senha de seus usuários antes de armazenar em seu banco de dados, dificulta um atacante determinar a senha original, enquanto ainda é possível de comparar o hash resultante para a senha original no futuro.

É importante observar, entretanto, que hash de senhas só protege de comprometer em seu armazenamento de dados, mas não necessariamente protege de serem interceptadas por um código malicioso injetado em sua própria aplicação.

Por que são comuns funções de hash tais como md5() e sha1() inadequados para senhas?

Algoritmos de hash como MD5, SHA1 e SHA256 são projetados para serem muito rápidos e eficientes. Com técnicas modernas e equipamento de informática, tornou-se trivial de "força bruta" a saída desses algoritmos, a fim de determinar a entrada original.

Por causa da rapidez com que um computador moderno pode "inverter" esses algoritmos de hash, muitos profissionais de segurança sugerem fortemente contra a sua utilização para hash da senha.

Como devo criptografar minhas senhas, se as funções hash comuns não são adequadas?

Quando gerar hash de senhas, as duas considerações mais importantes o custo do cálculo, e do salt. O algoritmo de hash computacionalmente mais caro, mais tempo vai demorar para a força bruta produzir um resultado.

O PHP fornece uma API de hash de senha nativo que lida de forma segura tanto gerando hash e verificando senhas de forma segura.

Outra opção é a função crypt(), que suporta vários algoritmos de hash. Quando utilizar esta função, você tem a garantia de que o algoritmo que você selecionou está disponível, como PHP contém implementações nativas de cada algoritmo suportado, no caso de um ou mais não são suportados pelo seu sistema.

O algoritmo sugerido para usar ao gerar hash de senhas é Blowfish, que também é o padrão usado pela API de hash da senha, pois é significativamente mais caro computacionalmente que MD5 ou SHA1, enquanto continua a ser escalável.

Note que se você estiver usando crypt() para verificar uma senha, você terá que tomar cuidado para evitar ataques de tempo usando uma string de comparação de tempo constante. Nem operadores == e === do PHP nem strcmp() realizam comparações de seqüências de tempo constante. Como password_verify() vai fazer isso por você, você será fortemente incentivado a usar a API de hash de senha nativa sempre que possível.

O que é um salt?

Um salt de criptografia são dados que são aplicado durante o processo de hash, a fim de eliminar a possibilidade da saída ser analisada se numa lista de pares pré-calculadas de hashes e sua entrada, conhecida como uma tabela rainbow.

Em termos mais simples, um salt é um pouco de informação adicional, que faz com que seus hashes sejam significativamente mais difíceis de decifrar. Há uma série de serviços on-line que fornecem listas extensas de hashes pré-calculado, bem como a entrada original para os hashes. O uso de um salt faz com que seja improvável ou impossível encontrar o hash resultante em uma dessas listas.

password_hash() será criado um salt aleatório se não for fornecido, e isso geralmente é a abordagem mais fácil e mais segura.

Como faço para armazenar meus salts?

Ao usar password_hash() ou crypt(), o valor de retorno inclui salt como parte do hash gerado. Este valor deve ser armazenado na íntegra no seu banco de dados, uma vez que inclui informações sobre a função hash que foi usado e pode, então, ser dada diretamente para password_verify() ou crypt() ao verificar senhas.

O diagrama a seguir mostra o formato de um valor de retorno de crypt() ou password_hash(). Como você pode ver, eles são auto-suficientes, com todas as informações sobre o algoritmo e salt necessário para futura verificação da senha.

Os componentes do valor retornado pelo password_hash e crypt: em ordem, o algoritmo escolhido, as opções do algoritmo, o salt utilizado, e o hash da senha.

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 e HTML

PHP e HTML possuem muita interação: PHP pode gerar HTML, e o HTML pode passar informações para o PHP. Antes de ler esses faqs, é importante que você aprenda como recuperar variáveis de fontes externas. A página do manual neste tópico inclui muitos exemplos.

  1. Que codificação/decodificação é preciso quando eu passo um valor através de um formulário/URL?
  2. Estou tentando usar uma tag <input type="image">, mas as variáveis $foo.x e $foo.y não estão disponíveis. $_GET['foo.x'] não existem também. Onde elas estão?
  3. Como eu crio arrays em um HTML <form>?
  4. Como eu faço para obter os resultados de uma múltipla seleção de uma tag HTML?
  5. Como eu posso passar uma variável do Javascript para o PHP?
Que codificação/decodificação é preciso quando eu passo um valor através de um formulário/URL?

Existem muitos estágios para o qual a codificação é importante. Assumindo que você tenha uma string $data, o qual contém a string que você quer passar de um jeito não codificado, esses são os estágios relevantes:

  • Interpretação HTML. A fim de especificar uma string aleatória, você precisa incluí-la entre aspas, e converter todo o valor dos caracteres especiais para a realidade HTML usando htmlspecialchars().

  • URL: Uma URL consiste de diversas partes. Se você quer que seus dados sejam interpretados como um item, você precisa codificá-los com urlencode().

Exemplo #1 Um elemento oculto de formulário HTML

<?php
echo "<input type='hidden' value='" . htmlspecialchars($data) . "' />\n";
?>

Nota: É errado urlencode() $data, porque é a responsabilidade do navegador em urlencode() os dados. Todos os navegadores populares o fazem isso corretamente. Note que isso irá acontecer independentemente do método (i.e., GET ou POST).Você só vai perceber isso em caso de solicitação GET, porque as requisições POST são normalmente escondidas.

Exemplo #2 Dados a serem editados pelo usuário

<?php
echo "<textarea name='mydata'>\n";
echo htmlspecialchars($data)."\n";
echo "</textarea>";
?>

Nota: Os dados são mostrados no navegador como pretendido, porque o navegador irá interpretar os símbolos de escape do HTML. Em consequência do envio, tando via GET como POST, os dados vão ser urlencoded pelo navegador para transferência, e urldecoded diretamente pelo PHP. Resumindo, você não precisa fazer qualquer urlencoded/urldecoded pelo php, tudo é feito automaticamente.

Exemplo #3 Em uma URL

<?php
echo "<a href='" . htmlspecialchars("/nextpage.php?stage=23&data=" .
urlencode($data)) . "'>\n";
?>

Nota: De fato você está fingindo uma requisição HTML GET, portanto é necessário urlencode() os dados manualmente.

Nota: Você precisa htmlspecialchars() toda a URL, porque a URL ocorre como um valor de um atributo-HTML. Neste caso, o navegador irá primeiramente un-htmlspecialchars() o valor, e então passar a URL. O PHP vai entender a URL corretamente, porque você codificou os dados com urlencode(). Você vai notar que & na URL é substituído por &amp;. Embora a maioria dos navegadores vão se recuperar se vecê esquecer disso, isso nem sempre é possível. Então, mesmo se a URL não é dinâmica, você precisa htmlspecialchars() a URL.

Estou tentando usar uma tag <input type="image">, mas as variáveis $foo.x e $foo.y não estão disponíveis. $_GET['foo.x'] não existem também. Onde elas estão?

Ao enviar um formulário, é possível usar uma imagem em vez de um botão submit padrão, como na tag:

<input type="image" src="image.gif" name="foo" />
Quando o usuário clica em qualquer lugar na imagem, o formulário que o acompanha será transmitido para o servidor com duas variáveis adicionais: foo.x e foo.y.

Porque foo.x e foo.y faria nome de variáveis inválidas no PHP, elas são automaticamente convertidas para foo_x e foo_y. Ou seja, os períodos são substituídos por sublinhados. Então, você teria acesso a essas variáveis como qualquer outro descrito na seção sobre como recuperar variáveis de fontes externas. Por exemplo, $_GET['foo_x'].

Nota:

Os espaços nos nomes das variáveis requisitadas são convertidas para sublinhado.

Como eu crio arrays em um HTML <form>?

Para obter o resultado do seu <form> enviado como um array para seu script PHP você nomeia os elementos <input>, <select> ou <textarea> como estes:

<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
Observe os colchetes após o nome da variável, é isso que torna uma variável um array. Você pode agrupar os elementos dentro de diferentes arrays, atribuindo o mesmo nome a diferentes elementos:
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyOtherArray[]" />
<input name="MyOtherArray[]" />
Isso produz dois arrays, MyArray e MyOtherArray, que serão enviados para o script PHP. Também é possível atribuir chaves específicas para seus arrays:
<input name="AnotherArray[]" />
<input name="AnotherArray[]" />
<input name="AnotherArray[email]" />
<input name="AnotherArray[phone]" />
O array AnotherArray irá conter agora as chaves 0, 1, email e phone.

Nota:

Especificar uma chave de array é opcional no HTML. Se você não especificar as chaves, o array preenche na ordem em que os elementos aparecem no formulário. Nosso primeiro exemplo irá conter as chaves 0, 1, 2 e 3.

Veja também: Funções de Array e Variáveis de fontes Externas.

Como eu faço para obter os resultados de uma múltipla seleção de uma tag HTML?

A seleção de múltiplas tags em uma construção HTML permite os usuários selecionar múltiplos itens de uma lista. Esses itens são então passados ao manipilador de ações para o formulário. O problema é que eles são todos passados com o mesmo nome widget. I.e.

<select name="var" multiple="yes">
Cada opção selecionada chegará ao manipulador de ações como:
var=option1
var=option2
var=option3
Cada opção irá substituir o conteúdo da variável anterior $var. A solução é usar a característica "array de elementos do formulário" do PHP. A seguir devem ser usados:
<select name="var[]" multiple="yes">
Isso diz ao PHP para tratar $var como um array e cada atribuição de um valor para [var] acrescenta um item ao array. O primeiro item se torna $var[0], o próximo $var[1], etc. A função count() pode ser chamado para determinar quantas opções foram selecionadas, e a função sort() pode ser usada para classificar o array de opções se necessário.

Note que se você está usando JavaScript o [] no nome do elemento pode lhe causar problemas quando você tenta se referir ao elemento pelo nome. Ao invés use o ID numérico do elemento do formulário, ou coloque o nome da variável entre aspas simples e use isso como um índice para os elementos do array, por exemplo:

variable = document.forms[0].elements['var[]'];

Como eu posso passar uma variável do Javascript para o PHP?

Uma vez que o Javascript é (normalmente) uma tecnologia da parte do cliente, e o PHP é (normalmente) uma tecnologia da parte do servidor, e uma vez que o HTTP é um protocolo "sem lado", as duas linguagens não podem compartilhar variáveis diretamente.

É , no entanto, possível passar variáveis entre as duas. Uma maneira de realizar isso é gerar um código Javascript com PHP, e ter um navegador que se atualize, passando variáveis específicas de volta para o script PHP. O exemplo abaixo mostra precisamente como fazer isso -- isso permite ao código PHP capturar a altura e largura da tela, algo que normalmente só é possível no lado do cliente.

Exemplo #4 Gerando Javascript com PHP

<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
// output the geometry variables
echo "Screen width is: ". $_GET['width'] ."<br />\n";
echo "Screen height is: ". $_GET['height'] ."<br />\n";
} else {
// pass the geometry variables
// (preserve the original query string
// -- post variables will need to handled differently)

echo "<script language='javascript'>\n";
echo " location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
. "&width=\" + screen.width + \"&height=\" + screen.height;\n";
echo "</script>\n";
exit();
}
?>

User Contributed Notes

There are no user contributed notes for this page.


PHP e COM

PHP pode ser usado para acessar objetos COM e DCOM em plataformas Win32.

  1. Eu construi uma DLL para calcular algo. Existe uma maneira de executar essa DLL no PHP ?
  2. O que 'Unsupported variant type: xxxx (0xxxxx)' significa ?
  3. É possível manipular objetos visuais no PHP ?
  4. Posso guardar um objeto COM em uma sessão ?
  5. Como eu trato erros de COM ?
  6. Posso gerar arquivos DLL de scripts PHP como eu posso no Perl ?
  7. O que significa 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' ?
  8. Como posso executar um objeto COM de um servidor remoto ?
  9. Eu vejo o erro 'DCOM is disabled in C:\path...\scriptname.php on line 6', o que posso fazer ?
  10. É possível carregar/manipular um objeto ActiveX em uma página com o PHP ?
  11. É possível pegar uma instância sendo executada de um componente ?
  12. Existe alguma maneria de lidar com um evento enviado de um objeto COM ?
  13. Estou tendo problemas quando tento invocar um método de um objeto COM que expõe mais de uma interface. O que posso fazer ?
  14. Então PHP funciona com COM, e com COM+ ?
  15. Se o PHP pode manipular objetos COM, podemos imaginar usar MTS para administrar recursos de componentes, em conjunção com PHP ?
Eu construi uma DLL para calcular algo. Existe uma maneira de executar essa DLL no PHP ?

Se for uma DLL simples, ainda não tem como executá-la no PHP. Se a DLL contem um serviço COM você pode acessá-lo se ele implementar a interface IDispatch.

O que 'Unsupported variant type: xxxx (0xxxxx)' significa ?

Existem dezenas de tipos VARIANT e combinações dos mesmos. A maioria deles já são suportados mas alguns ainda tem que ser implementados. Arrays não são completamente suportados. Apenas arrays indexados com uma única dimensão podem ser passados entre o PHP e COM. Se você achar outros tipos que não são suportados, por favor relate-os como um bug (se não tiverem sido relatados ainda) e passe o máximo de informação disponível.

É possível manipular objetos visuais no PHP ?

Geralmente é, mas como o PHP é principalmente usado como linguagem de script pra web, ele é executado no contexto dos servidores web, então objetos visuais nunca aparecerão no desktop do servidor. Se você usa o PHP para script de aplicações, ex.: em conjunto com PHP-GTK não há limitação no acesso e manipulação de objetos visuais através de COM.

Posso guardar um objeto COM em uma sessão ?

Não, não pode. Instâncias COM são tratadas como recursos (resources) e, portanto, só estão disponíveis no contexto de um script único.

Como eu trato erros de COM ?

A extensão COM dispara exceções do tipo com_exception, que você pode pegar e então inspecionar o membro code para determinar o que fazer depois.

Posso gerar arquivos DLL de scripts PHP como eu posso no Perl ?

Não, infelizmente não existe tal ferramenta disponível para o PHP.

O que significa 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' ?

Esse erro pode ter várias razões:

  • o CLSID está errado
  • a DLL requisitada não existe ou não pode ser lida
  • o componente requisitado não implementa a interface IDispatch

Como posso executar um objeto COM de um servidor remoto ?

Exatamente como você executa objetos locais. Você só tem que passar o IP da máquina remota como segundo parâmetro para o construtor COM.

Tenha certeza de marcar com.allow_dcom =true no seu php.ini.

Eu vejo o erro 'DCOM is disabled in C:\path...\scriptname.php on line 6', o que posso fazer ?

Edite seu arquivo php.ini e marque com.allow_dcom =true.

É possível carregar/manipular um objeto ActiveX em uma página com o PHP ?

Isso não tem nada a ver com o PHP. Objetos ActiveX são carregados no lado do cliente se eles forem requisitados pelo documento HTML. Não há relação com o script PHP e, portanto, nenhuma interação direta possível com o lado do servidor.

É possível pegar uma instância sendo executada de um componente ?

É possível com a ajuda de monikers. Se você quiser referências múltiplas para a mesma instância você pode criar uma instância como mostrado abaixo:

<?php
$word = new COM("C:\docs\word.doc");
?>

Isso criará uma nova instância se nenhuma instância sendo executada estiver disponível e retornará um handle para ela, se disponível.

Existe alguma maneria de lidar com um evento enviado de um objeto COM ?

Você pode definir um interceptador de eventos usando com_event_sink(). Você pode usar com_print_typeinfo() para que o PHP gere um esqueleto para a classe interceptadora de eventos.

Estou tendo problemas quando tento invocar um método de um objeto COM que expõe mais de uma interface. O que posso fazer ?

A resposta é tão simples quanto insatisfatória. Eu não sei exatamente, mas acho que não há nada a fazer. Se alguém tem informação específica sobre isso, por favor » me avise (mande e-mails em inglês) :)

Então PHP funciona com COM, e com COM+ ?

COM+ extende COM por meio de um framework para manusear componentes através de MTS e MSMQ, mas não há nada de especial que o PHP precise suportar para usar tais componentes.

Se o PHP pode manipular objetos COM, podemos imaginar usar MTS para administrar recursos de componentes, em conjunção com PHP ?

O PHP em si não lida com transações ainda. Por isso, se um erro ocorre, nenhum rollback é iniciado. Se você usar componentes que suportem transações você pode implementar a administração de transações por conta própria.

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.


Questões Diversas

Aqui estão algumas questões que nós não pudemos colocar em outra categoria. Aqui você encontra elas.

  1. Como eu posso utilizar os manuais compactados com o bz2 no Windows?
Como eu posso utilizar os manuais compactados com o bz2 no Windows?

Se você não tiver uma ferramenta de arquivos para trabalhar com arquivos bz2 » download a ferramenta de linha de comando da Redhat (por favor veja maiores informações abaixo).

Se você não gostar de usar uma ferramenta de linha de comando, você pode tentar ferramentas gratuitas como » Stuffit Expander, » UltimateZip, » 7-Zip, ou » Quick Zip. Se você tiver ferramentas como » WinRAR ou » Power Archiver, você pode facilmente descomprimir arquivos bz2 com elas. Se você usa o Total Commander, (anteriormente Windows Commander), um plugin para o bz2 esta disponível gratuitamente em » Total Commander.

A ferramenta de linha de comando bzip2 da Redhat:

Usuários Win2k Sp2 obtenha a versão 1.0.2, todos os outros usuários de windows a versão 1.00. Após o download renomeie o executável para bzip2.exe. Para sua conveniência, coloque em um diretório que esteja no seu path, ex. C:\Windows, onde C representa o drive que você instalou o Windows.

Nota: lang significa a sua língua( Português do Brasil: pt_BR) e x para o formato desejado, ex.: pdf. Para descompactar php_manual_lang.x.bz2 siga estas instruções simples:

  • abra uma janela com o prompt de comando
  • Use o comando cd para a pasta onde você guardou o php_manual_lang.x.bz2
  • digite bzip2 -d php_manual_lang.x.bz2, descompactando php_manual_lang.x na mesma pasta

Caso você tenha feito o download de php_manual_lang.tar.bz2 com vários arquivos html nele, o procedimento é o mesmo. A única diferença é que você obtém um arquivo php_manual_lang.tar. O formato tar format é conhecido e tratado com as ferramentas de arquivos mais comuns para o Windows, por exemplo » WinZip.

User Contributed Notes

There are no user contributed notes for this page.


Apêndices

  • História do PHP e Projetos Relacionados
    • História do PHP
    • História de projetos relacionado ao PHP
    • Livros sobre PHP
    • Publicações sobre PHP
  • Migrando do PHP 8.2.x para o PHP 8.3.x
    • Novas Funcionalidades
    • Novas Classes e Interfaces
    • Novas Funções
    • Novas Constantes Globais
    • Alterações incompatíveis com versões anteriores
    • Recursos Obsoletos
    • Outras mudanças
    • Suporte do Windows
  • Migrando do PHP 8.1.x para o PHP 8.2.x
    • Novas Funcionalidades
    • Novas Funções
    • Novas Constantes Globais
    • Alterações incompatíveis com versões anteriores
    • Funcionalidades Preteridas
    • Outras mudanças
    • Suporte do Windows
  • Migrando do PHP 8.0.x para o PHP 8.1.x
    • Novas Funcionalidades
    • Novas Classes e Interfaces
    • Novas Funções
    • Novas Constantes Globais
    • Alterações incompatíveis com versões anteriores
    • Funcionalidades depreciadas
    • Outras Mudanças
  • Migrando do PHP 7.4.x para o PHP 8.0.x
    • Novas Funcionalidades
    • Alterações incompatíveis com versões anteriores
    • Recursos depreciados
    • Outras mudanças
  • Migrando do PHP 7.3.x para o PHP 7.4.x
    • Novos Recursos
    • Novas Classes e Interfaces
    • Novas Funções
    • Novas Constantes Globais
    • Alterações incompatíveis com versões anteriores
    • Recursos depreciados
    • Extensões Removidas
    • Outras mudanças
    • Suporte do Windows
  • Migrando do PHP 7.2.x para o PHP 7.3.x
    • Novas Funcionalidades
    • Novas Funções
    • Novas Constantes Globais
    • Alterações incompatíveis com versões anteriores
    • Recursos depreciados
    • Outras mudanças
    • Suporte do Windows
  • Migrando do PHP 7.1.x para o PHP 7.2.x
    • New features
    • New functions
    • Novas constantes globais
    • Backward incompatible changes
    • Recursos depreciados na versão PHP 7.2.x
    • Other changes
  • Migrando do PHP 7.0.x para o PHP 7.1.x
    • New features
    • New functions
    • New global constants
    • Backward incompatible changes
    • Deprecated features in PHP 7.1.x
    • Changed functions
    • Other changes
    • Windows Support
  • Migrando do PHP 5.6.x para o PHP 7.0.x
    • Mudanças incompatíveis com versões anteriores
    • Novos Recursos
    • Recursos depreciados no PHP 7.0.x
    • Funções alteradas
    • Novas funções
    • Novas Classes e Interfaces
    • Novas Constantes Globais
    • Modificações nos Módulos SAPI
    • Extensões e SAPIs removidas
    • Outras mudanças
  • Migrando do PHP 5.5.x para o PHP 5.6.x
    • Backward incompatible changes
    • New features
    • Deprecated features in PHP 5.6.x
    • Changed functions
    • New functions
    • OpenSSL changes in PHP 5.6.x
    • Other changes to extensions
    • Novas constantes globais
  • Depurando em PHP
    • Sobre o depurador em PHP
  • Opções do script Configure
    • Lista de opções do script configure
  • php.ini directives
    • Lista de diretivas do php.ini
    • Lista das seções do php.ini
    • Descrição das principais diretivas do php.ini
  • Categorização/Lista das Extensões
    • Em ordem alfabética
    • Sociedade
    • Estado
  • Lista de funções sinônimas (aliases)
  • Lista de Palavras Reservadas do PHP
    • Lista de Palavras-chave (Keywords)
    • Classes Predefinidas
    • Constantes Pré-definidas
    • Lista de outras palavras reservadas
  • Lista de tipos de recursos no PHP
  • Lista de Filtros Disponíveis
    • Filtros de String
    • Fitros de Conversão
    • Filtros de Compressão
    • Filtros de Criptografia
  • Lista de Transportes via Socket Suportados
    • Domínios da Internet: TCP, UDP, SSL, e TLS
    • Domínio Unix: Unix e UDG
  • Tabela de comparações de tipos do PHP
  • Lista de Tokens do Parser
  • Guia de nomenclatura em espaço de usuário
    • Escopo Global
    • Regras
    • Dicas
  • Sobre o manual
    • Formatos
    • Sobre as notas dos usuários
    • Como ler uma definição de função (protótipo)
    • Versões do PHP documentadas neste manual
    • Como encontrar mais informações sobre o PHP
    • Como ajudar a melhorar a documentação
    • Como nós geramos os formatos
    • Traduções
  • Creative Commons Attribution 3.0
  • Lista de índices
    • Lista de Funções e Métodos
    • Lista de exemplos
  • Changelog

User Contributed Notes

There are no user contributed notes for this page.


História do PHP e Projetos Relacionados

Índice

  • História do PHP
  • História de projetos relacionado ao PHP
  • Livros sobre PHP
  • Publicações sobre PHP

PHP já percorreu um longo caminho desde seu nascimento em meados da década de 1990. De origens humildes para se tornar uma das mais proeminentes linguagens que alimentam a web, a evolução do PHP é um conto de fadas geek. Lembre-se, esse crescimento explosivo não foi fácil. Aqueles que se interessam em ver brevemente como PHP cresceu para se tornar o que é hoje, continue lendo. Se gostaria de tocar um pedaço da história da internet, você pode encontrar antigas releases do PHP no » Museu 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


História do PHP

PHP Tools, FI, Kit de Construção, e PHP/FI

O PHP como é conhecido hoje, é na verdade o sucessor para um produto chamado PHP/FI. Criado em 1994 por Rasmus Lerdof, a primeira encarnação do PHP foi um simples conjunto de binários Common Gateway Interface (CGI) escrito em linguagem de programação C. Originalmente usado para acompanhamento de visitas para seu currículo online, ele nomeou o conjunto de scripts de "Personal Home Page Tools" mais frequentemente referenciado como "PHP Tools." Ao longo do tempo, mais funcionalidades foram desejadas, e Rasmus reescreveu o PHP Tools, produzindo uma maior e rica implementação. Este novo modelo foi capaz de interações com Banco de Dados e mais, fornecendo uma estrutura no qual os usuários poderiam desenvolver simples e dinâmicas aplicações web, como um livros de visitas. Em Junho de 1995, Rasmus » liberou o código fonte do PHP Tools para o público, o que permitiu que desenvolvedores usassem da forma como desejassem. Isso permitiu - e encorajou - usuários a fornecerem correções para bugs no código, e em geral, aperfeiçoá-lo.

Em Setembro do mesmo ano, Rasmus expandiu o PHP e - por um breve período - mudou o nome PHP. Agora referindo-se a ferramenta como FI, abreviação para "Forms Interpreter", a nova implementação incluiu algumas funcionalidades básicas do PHP como bem conhecemos hoje. Tinha variáveis no estilo Perl, interpretação automática de variáveis de formulários, e sintaxe HTML embutida. A sintaxe em si era muito similar com a do Perl, porém muito mais limitada, simples, e um pouco inconsistente. De fato, para embutir o código em um arquivo HTML, desenvolvedores tinham que usar comentários HTML. Embora este método não sido inteiramente bem-recebido, FI continuou a desfrutar um crescimento e aceitação como uma ferramente CGI --- mas ainda não como uma linguagem. Contudo, isso começou a mudar no mês seguinte; em Outubro, 1995 Rasmus liberou um completa reescrita do código. Trazendo de volta o nome PHP, estava agora (brevemente) nomeado "Personal Home Page Contruction Kit" e foi o primeiro lançamento a vangloriar-se que era, na época, considerado um avançado script de interface. A linguagem foi desenvolvida para, deliberadamente, ser parecida com C, tornando-a fácil para ser adotada por desenvolvedores habituados com C, Perl e linguagens similares. Tendo sido até este momento exclusiva para sistemas UNIX e sistemas compatíveis com POSIX, o potencial para uma implementação em um Windows NT começava a ser explorada.

O código tem outra reforma completa, e em Abril de 1996, combinando os nomes dos últimos lançamentos, Rasmus introduziu o PHP/FI. Esta segunda geração da implementação começou a realmente evoluir o PHP de um conjunto de ferramentas para sua própria linguagem de programação. Ele incluía suporte embutido dos banco de dados DBM, mSQL, e Postgres95, cookies, funções de apoio definidas pelo usuário, e muito mais. Em Junho, PHP/FI ganhou o status de versão 2.0. Um interessante fato sobre isso, porém, é que existia apenas um única completa versão do PHP 2.0. Quando finalmente se tornou um status beta em Novembro, 1997, o mecanismo de análise suvbjacente já estava interiramente reescrito.

Apesar de ter tido um curto período de desenvolvimento, ele continuava defrutar uma crescente popularidade em um ainda jovem mundo web desenvolvimento, Em 1997 e 1998, PHP/FI teve o apoio de milhares de usuários ao redor do mundo. Uma pesquisa Netcraft de Maio de 1998, indicou que cerca de 60.000 domínios relataram ter cabeçalhos contendo "PHP", indicando que o servidor de hospedagem de fato tinha o PHP instalado. Este número pode ser equiparado com aproximadamente 1% de todos os domínios da Internet da época. Apesar destes números impressionantes, o amadurecimento do PHP/FI foi condenado a limitações; enquanto haviam vários contribuintes menores, ainda era desenvolvido principalmente por uma única pessoa.

Exemplo #1 Exemplo de código PHP/FI

<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  Hey, you are using Netscape!<p>
<!--endif-->

<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
  Sorry, that record does not exist<p>
<!--endif exit-->
  Welcome <!--$user-->!<p>
  You have <!--$index:0--> credits left in your account.<p>

<!--include /text/footer.html-->

PHP 3

PHP 3.0 foi a primeira versão que se assemelha com o PHP como existe hoje. PHP/FI se encontrava ainda ineficiente e não tinha recursos que precisava para prover uma aplicação eCommerce que estavam desenvolvendo para um projeto da Universidade, Andi Gutmans e Zeev Suraski de Tel Aviv, Israel, começaram outra completa reescrita do interpretador em 1997. Abordando Rasmus online, eles discutiram vários aspectos para a corrente implementação e redesenvolvimento do PHP. Em um esforço para melhorar a engine e iniciar a construção em cima da base de usuários existentes do PHP/FI, Andi, Rasmus, e Zeev decidiram colaborar no desenvolvimento de uma nova e independente linguagem de programação. Essa nova linguagem foi lançada com um novo nome, que removeu a impressão do limitado uso pessoal que o nome PHP/FI 2.0 tinha mantido. Foi renomeado simplesmente para 'PHP', com o significado se tornando um acrônimo recursivo - PHP: Hypertext Preprocessor.

Um dos maiores pontos fortes do PHP 3.0 foram os fortes recursos de extensibilidade. Além de fornecer a usuários finais uma interface robusta para múltiplos banco de dados, protocolos, e APIs, a facilidade de estender a sua própria linguagem atraiu dezenas de desenvolvedores que submeteram uma variedade de módulos. Indiscutivelmente esta foi a chave para o PHP 3.0 ter sido um tremendo sucesso. Outro recurso chave foi introduzido no PHP 3.0 incluindo o suporte a programação orientada a objeto e a uma mais poderosa e consistente sintaxe de linguagem.

Em junho de 1998, com muitos novos desenvolvedores ao redor do mundo unindo esforços, PHP 3.0 foi anunciado pelo novo time de desenvolvimento do PHP como o sucessor oficial para o PHP/FI 2.0. As melhorias no PHP/FI 2.0, cessaram em Novembro do ano anterior e agora foi oficialmente finalizado. Depois de nove meses de testes abertos ao público, quando o anúncio do lançamento oficial do PHP 3.0 chegou, prontamente foi instalado em 70.000 domínios em todo mundo, e já não era mais limitado ao sistemas operacionais compatíveis ao POSIX. Uma parcela relativamente pequena de domínios informaram que o PHP foi instalado em um host com servidores executando Windows 95, 98 e NT, Macintosh. E em seu pico, PHP 3.0 foi instalado em aproximadamente 10% dos servidores web da internet.

PHP 4

No inverno de 1998, logo após o PHP 3.0 ter sido oficialmente lançado, Andi Gutmans e Zeev Suraski começaram a trabalhar em uma reescrita do core do PHP. Os objetivos do projeto eram melhorar performance das aplicações complexas, e melhorar a modularização do código base do PHP. Tais aplicações só foram possíveis pelos novos recursos e suporte para uma ampla variedades de banco de dados de terceiros e APIs do PHP 3.0, mas o PHP 3.0 não foi projetado para trabalhar com aplicações complexas de forma eficiente.

O novo motor, chamado 'Zend Engine' (composto pelos primeiros nome, Zeev e Andi), alcançou os objetivos do projeto com sucesso, e foi introduzido em meados de 1999. O PHP 4.0 baseado neste motor, e uma variedade de novos recursos adicionais, foi oficialmente lançado em Maio de 2000, quase dois anos após seu antecessor. Além da altíssima melhoria da performance nesta versão, o PHP 4.0 incluiu outros recursos chaves, tais como suporte para maioria dos servidores web, sessões HTTP, saídas de buffering, mais maneiras seguras para manipular dados de entrada de usuários e diversas novas construções de linguagem.

PHP 5

O PHP 5 foi lançado em Julho de 2004 após um longo desenvolvimento e vários pré-lançamentos. Principalmente impulsionado pelo seu core o Zend Engine 2.0 com um novo modelo de objeto e dezenas de outros novos recursos.

O time de desenvolvimento PHP inclui dezenas de desenvolvedores, também dezenas de outros trabalhando em algo relacionado ao PHP e apoio a projetos como PEAR, PECL, documentação, infra-estrutura de rede subjacente de bem mais de uma centena de servidores web em seis dos sete continentes do mundo. Embora seja apenas uma estimativa baseada sobre estatísticas de anos anteriores, é seguro presumir que o PHP está agora instalado em dezenas, ou mesmo talvez centenas, de milhões de domínios em todo mundo.

User Contributed Notes

There are no user contributed notes for this page.


História de projetos relacionado ao PHP

PEAR

» PEAR, a PHP Extension and Application Repository (originalmente, PHP Extension and Add-on Repository) é a base de classes PHP, e pode crescer no futuro para ser uma das formas chaves para distribuir extensões PHP entre os desenvolvedores.

PEAR nasceu em discussões de encontros realizados por desenvolvedores PHP (PDM) realizado em Janeiro de 2000 em Tel Aviv. Foi criado por Stig S. Bakken, e é dedicado à sua primeira filha, Malin Bakken.

Desde o início de 2000, PEAR cresceu para ser um grande e significante projeto com um grande número de desenvolvedores trabalhando em implementar funcionalidades comuns e reutilizáveis para benefício da comunidade PHP. PEAR hoje inclui uma ampla variedade de classes para acesso ao banco de dados, cache de conteúdo, cálculos matemáticos, eCommerce e muito mais.

Mais informações sobre PEAR podem ser encontradas » no manual.

Iniciativa de Garantia da Qualidade do PHP

O » PHP Quality Assurance Initiative foi criado no verão de 2000, em resposta para críticas que versões do PHP não estavam sendo suficientemente bem testados para o ambiente de produção. O time agora consiste de um grupo de desenvolvedores com um bom entendimento do código base do PHP. Esses desenvolvedores gastam muito de seu tempo localizando e corrigindo os bugs do PHP. Além de existir muitos outros membros do time que testam e fornecem feedback de suas correções usando uma ampla variedade de plataformas.

PHP-GTK

» PHP-GTK é a solução PHP para escrever aplicações GUI no lado do cliente. Andrei Zmievski nos recorda o processo de planejamento e criação:

Programação GUI foi sempre do meu interesse, e eu achei o Gtk+ um utilitário muito fácil, exceto que programar com ele em C é pouco tedioso. Depois de testemunhar aplicações PyGtk e GTK-Perl. Eu decidi ver se o PHP poderia fazer uma interface com Gtk+, mesmo que pequena. Iniciei em Agosto de 2000, quando comecei a ter um pouco mais de tempo livre, e iniciei os experimentos. Minha principal diretriz foi a implementação PyGtk pois possia recursos bastante completos e uma boa interface de orientação a objetos. James Henstridge, o autor de PyGtk, forneceu muitos conselhos úteis durante os estágios iniciais.

Escrever as interfaces para toda as funções Gtk+ ficou fora de questão, então eu aproveitei a ideia de gerar código, similar como o PyGtk tinha feito. O gerador de código é um programa PHP que lê um conjunto de arquivos .defs contendo as classes Gtk+, constantes, e informações de métodos e gera o código C que faz a interface com PHP. O que não pode ser gerado automaticamente pode ser escrito manualmente no arquivo .overrides.

Trabalhar em um gerador de código e sua infra-estrutura levou algum tempo, pois eu só podia gastar um pouco tempo em PHP-GTK durante o outono de 2000. Depois que mostrei o PHP-GTK para Frank Kromann, ele ficou interessado e começou ajudando-me com o gerador de código e em implementaçes de Win32. Quando nós escrevemos o primeiro programa Hello World e executamos, ficamos muito emocionados. Levou dois ou mais meses para começar o projeto em uma condição apresentável e a versão inicial foi lançada em 1 de Março de 2001. A história rapidamente chegou ao SlashDot.

Sentindo que PHP-GTK podia ser extensível, montei em separado uma lista de e-mail, um repositório CVS para isto e também um website gtk.php.net com a ajuda de Colin Viebrock. Também foi preciso montar a documentação e James Moore veio a ajudar com isto.

Desde seu lançamento, o PHP-GTK foi ganhando popularidae. Nós tivemos nosso próprio time de documentação, o manual continua melhorando, pessoas começaram a escrever extensões para o PHP-GTK, e mais aplicações foram feitas com ele.

User Contributed Notes

There are no user contributed notes for this page.


Livros sobre PHP

Como o PHP cresceu, começou a ser reconhecido com uma popular plataforma de desenvolvimento web. Um das formas mais interessantes de ver esta tendência foi observando os livros sobre PHP que saiu ao longo dos anos.

Pelo que sabemos, o primeiro livro dedicado para PHP foi 'PHP - tvorba interaktivních internetových aplikací' (PHP - Criando aplicativos interativos da Internet) um livro checo publicado em 1999, cujo autor foi Jirka Kosek. No mês sequinte um livro Alemão, dos autores Egon Schmid, Christian Cartus e Richard Blume. O primeiro livro em Inglês sobre PHP foi publicado pouco depois, e foi 'Core PHP Programming' de Leon Atkinson. Este livro cobria o PHP 3.0.

Enquanto estes eram os primeiros livros deste gênero - eles foram seguidos por um grande número de livros de uma série de autores e e editores. Existem mais de 400 livros em Inglês, mais de 100 livros em Alemão, e mais de 50 livros em Francês ou Espanhol! Além, de poder encontrar livros sobre PHP em muitas outras linguas, incluindo Coreano, Japonês e Hebraico.

Obviamente, este grande número de livros, escrito por diferentes autores, publicados por muitas editoras, e sua disponibilidade em tantas línguas - é um forte testemunho do sucesso do PHP em todo o mundo.

User Contributed Notes

There are no user contributed notes for this page.


Publicações sobre PHP

Pelo que sabemos, o primeiro artigo sobre PHP em uma revista em papel foi publicado na Computerworld da Tchecoslováquia, na primavera de 1998, e cobria o PHP 3.0. Como os livros, este foi o primeiro de uma série de muitos artigos publicados sobre PHP em várias revistas reconhecidas.

Artigos sobre PHP apareceram no Dr. Dobbs, Linux Enterprise, Linux Magazine e muitos outros. Artigos sobre migração de aplicações baseadas em ASP para PHP no Windows tem aparecido até na MSDN que é da Microsoft !

User Contributed Notes

There are no user contributed notes for this page.


Migrando do PHP 8.2.x para o PHP 8.3.x

Índice

  • Novas Funcionalidades
  • Novas Classes e Interfaces
  • Novas Funções
  • Novas Constantes Globais
  • Alterações incompatíveis com versões anteriores
  • Recursos Obsoletos
  • Outras mudanças
  • Suporte do Windows

Esta nova versão menor traz consigo várias novas funcionalidades e algumas incompatibilidades que devem ser testadas antes de realizar a troca de versões do PHP em ambientes de produção.

Veja também os guias de migração das versões do 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.


Novas Funcionalidades

PHP Core

Propriedades somente leitura

Classes anônimas agora podem ser marcadas como somente leitura.

Propriedades somente leitura agora podem ser reinicializadas durante a clonagem.

Constantes de Classe Tipadas

Constantes de classe, interface, trait e enum agora suportam declarações de tipo.

Closures criados a partir de métodos mágicos

Closures criados a partir de métodos mágicos agora podem aceitar argumentos nomeados.

O modificador final com um método de uma trait

O modificador final agora pode ser usado ao utilizar um método de uma trait.

Sobreposição de atributos

Foi adicionado o atributo #[\Override] para verificar se um método existe em uma classe pai ou interface implementada.

Sintaxe para buscar constantes de classe dinamicamente.

Agora é possível acessar constantes de classe de forma dinâmica usando a sintaxe C::{$name}.

Inicializadores de variáveis Estáticas

Os inicializadores de variáveis estáticas agora podem conter expressões arbitrárias.

Sintaxe de valor de fallback para variáveis ini

O arquivo php.ini agora suporta a sintaxe de valor de fallback/default.

<?php
/*
No arquivo /path/to/user.ini estão contidas as seguintes configurações:

listen = localhost:${DRUPAL_FPM_PORT:-9000}
*/

$user_ini = parse_ini_file('/path/to/user.ini');
echo $user_ini['listen']; // localhost:9000

CLI

Agora é possível verificar a sintaxe de vários arquivos.

DOM

Foram adicionadas as propriedades DOMElement::$className e DOMElement::$id. No momento, essas propriedades não são seguras para binários devido a limitações subjacentes do libxml2. Isso significa que os valores das propriedades serão truncados em um byte NUL.

Foram adicionadas as propriedades DOMNode::$isConnected e DOMNameSpaceNode::$isConnected.

Foram adicionadas as propriedades DOMNode::$parentElement e DOMNameSpaceNode::$parentElement.

FFI

Agora é possível atribuir FFI\CData a outros FFI\CData. Isso significa que CData pode ser atribuído a estruturas e campos.

Opcache

opcache_get_status()['scripts'][n]['revalidate'] agora contém um carimbo de data e hora Unix que indica quando a próxima revalidação do carimbo de data e hora dos scripts está programada, de acordo com a diretiva INI opcache.revalidate_freq;

POSIX

A função posix_getrlimit() agora aceita um parâmetro opcional $res para permitir a recuperação de um único limite de recurso.

A função posix_isatty() agora gera avisos de tipo para inteiros, seguindo as semânticas ZPP usuais.

A função posix_ttyname() agora gera avisos de tipo para inteiros, seguindo as semânticas ZPP usuais, e avisos de valor para inteiros de descritor de arquivo inválidos.

Streams

Agora, Streams podem emitir a notificação STREAM_NOTIFY_COMPLETED. Isso não era previamente implementado.

User Contributed Notes

There are no user contributed notes for this page.


Novas Classes e 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.


Novas Funções

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.


Novas Constantes Globais

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

As seguintes opções de socket agora estão definidas se forem suportadas:

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


Alterações incompatíveis com versões anteriores

PHP Core

Programas que estavam muito próximos de estourar a pilha de chamadas.

Programas que estavam muito próximos de esgotar a pilha de chamadas agora podem lançar um Error ao usar mais do que !-- link linkend="zend.max_allowed_stack_size-zend.reserved_stack_size" -->zend.max_allowed_stack_size-zend.reserved_stack_size bytes de pilha (fiber.stack_size-zend.reserved_stack_size para fibers).

Executando proc_get_status() várias vezes

Executar proc_get_status() várias vezes agora sempre retornará o valor correto em sistemas POSIX. Anteriormente, apenas a primeira chamada da função retornava o valor correto. Executar proc_close() após proc_get_status() agora também retornará o código de saída correto. Anteriormente, isso retornaria -1. Internamente, isso funciona armazenando em cache o resultado em sistemas POSIX. Se for necessário o comportamento anterior, é possível verificar a chave "cached" no array retornado por proc_get_status() para verificar se o resultado foi armazenado em cache.

Temporizadores Máximos de Execução do Zend

Os Temporizadores Máximos de Execução do Zend agora estão habilitados por padrão para compilações ZTS no Linux.

Usos de traits com propriedades estáticas

O uso de traits com propriedades estáticas agora irá redeclarar as propriedades estáticas herdadas da classe pai. Isso criará um armazenamento de propriedade estática separado para a classe atual. Isso é análogo a adicionar a propriedade estática diretamente à classe sem o uso de traits.

Atribuir um índice negativo a um array vazio

Atribuir um índice negativo $n a um array vazio agora garantirá que o próximo índice seja $n+1, em vez de 0.

Verificação de consistência na visibilidade de constantes de classe

A variação na visibilidade de constantes de classe agora é verificada corretamente quando herdada de interfaces.

Entradas WeakMap cuja chave mapeia para si mesma

As entradas WeakMap cuja chave mapeia para si mesma (possivelmente de forma transitiva) agora podem ser removidas durante a coleta de ciclos se a chave não for alcançável, exceto por meio da iteração sobre o WeakMap (a alcançabilidade por iteração é considerada fraca). Anteriormente, tais entradas nunca seriam removidas automaticamente.

Date

A extensão DateTime introduziu exceções e erros específicos da extensão Date sob as hierarquias DateError e DateException, em vez de avisos e exceções genéricas. Isso melhora o tratamento de erros, embora exija que se verifiquem erros e exceções.

DOM

Chamar DOMChildNode::after(),
DOMChildNode::before(),
DOMChildNode::replaceWith()
em um nó que não tem pai agora não faz nada (no-op) em vez de gerar
uma exceção de hierarquia, conforme exigido pela especificação DOM.

Usar os métodos DOMParentNode e DOMChildNode sem um documento agora funciona em vez de lançar uma exceção DOM_HIERARCHY_REQUEST_ERR DOMException. Isso está de acordo com o comportamento exigido pela especificação DOM.

Chamar DOMDocument::createAttributeNS() sem especificar um prefixo criaria incorretamente um namespace padrão, colocando o elemento dentro do namespace em vez do atributo. Esse erro foi corrigido.

Anteriormente, DOMDocument::createAttributeNS() lançaria incorretamente uma exceção DOM_NAMESPACE_ERRNAMESPACE_ERR DOMException quando o prefixo já estivesse sendo usado para outro URI. Agora, ele escolhe corretamente um prefixo diferente quando há conflito de nomes de prefixo.

Foram adicionados novos métodos e propriedades a algumas classes DOM. Se uma classe definida pelo usuário herda dessas classes e declara um método ou propriedade com o mesmo nome, as declarações devem ser compatíveis. Caso contrário, ocorrerá um erro de compilação típico relacionado a declarações incompatíveis. Consulte a lista de novas funcionalidades e novas funções para obter uma lista dos métodos e propriedades recém-implementados.

FFI

As funções C que têm um tipo de retorno void agora retornam null em vez de retornar o seguinte objeto object(FFI\CData:void) { }.

Opcache

A diretiva INI opcache.consistency_checks foi removida. Essa funcionalidade estava quebrada com o tracing JIT, bem como com o inheritance cache, e foi desativada sem a possibilidade de ser habilitada desde o PHP 8.1.18 e o PHP 8.2.5. Tanto o tracing JIT quanto o inheritance cache podem modificar a memória compartilhada (shm) depois que o script foi persistido, invalidando seu checksum. A tentativa de correção ignorou os ponteiros modificáveis, mas foi rejeitada devido à complexidade. Por esse motivo, foi decidido remover a funcionalidade em vez de mantê-la.

Phar

O tipo das constantes de classe da classe Phar agora está declarado.

Standard

A função range() sofreu várias mudanças:

  • Agora é lançado um TypeError ao passar objects, resources ou arrays como entradas de limite.
  • Agora é lançado um ValueError mais descritivo ao passar 0 para $step.
  • Agora é lançado um ValueError ao usar um $step negativo para intervalos crescentes.
  • Se $step for um número em ponto flutuante que pode ser interpretado como um número inteiro, ele agora será tratado como tal.
  • Agora, um ValueError é lançado se qualquer argumento for infinito ou NAN.
  • Agora, é gerado um E_WARNING se $start ou $end for uma string vazia. O valor ainda é convertido para o valor 0.
  • Agora, é gerado um E_WARNING se $start ou $end tiver mais de um byte, desde que seja uma string não numérica.
  • Agora, é gerado um E_WARNING se $start ou $end for convertido para um inteiro porque a outra entrada de limite é um número (por exemplo, range(5, 'z');).
  • Agora, é gerado um E_WARNING se $step for um número em ponto flutuante ao tentar gerar um intervalo de caracteres, exceto se ambas as entradas de limite forem strings numéricas (por exemplo, range('5', '9', 0.5); não gera um aviso).
  • range() agora gera uma lista de caracteres se uma das entradas de limite for um dígito em forma de string, em vez de converter a outra entrada para um número inteiro (por exemplo, range('9', 'A');).
<?php
range('9', 'A'); // ["9", ":", ";", "<", "=", ">", "?", "@", "A"], a partir do PHP 8.3.0
range('9', 'A'); // [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], antes do PHP 8.3.0
?>

A verificação de erros das flags da função file() agora identifica todas as flags inválidas. Notavelmente, FILE_APPEND era anteriormente aceito silenciosamente.

SNMP

O tipo das constantes de classe da classe SNMP agora está declarado.

User Contributed Notes

There are no user contributed notes for this page.


Recursos Obsoletos

PHP Core

Operadores de incremento/decremento mais seguros

O uso do operador de incremento (++) em strings vazias, não numéricas ou não alfanuméricas está agora obsoleto. Além disso, o incremento de strings não numéricas é considerado obsoleto suave. Isso significa que nenhum diagnóstico de E_DEPRECATED é emitido, mas esse recurso não deve ser usado ao criar novo código. Em vez disso, deve ser usado a nova função str_increment().

O uso do operador de decremento (--) em strings vazias ou não numéricas está agora obsoleto.

Chamada de get_class()/get_parent_class() sem argumentos

Chamar get_class() e get_parent_class() sem argumentos está agora obsoleto.

DBA

Chamar dba_fetch() com $dba como o terceiro argumento está agora obsoleto.

FFI

Chamar FFI::cast(), FFI::new() e FFI::type() de forma estática está agora obsoleto.

Intl

A constante U_MULTIPLE_DECIMAL_SEP*E*RATORS foi obsoleta, recomenda-se usar a constante U_MULTIPLE_DECIMAL_SEP*A*RATORS em seu lugar.

A constante NumberFormatter::TYPE_CURRENCYfoi obsoleta.

LDAP

Chamar ldap_connect() com $hostname e $port separados está obsoleto.

MBString

Passar um valor negativo para $width em mb_strimwidth() agora está obsoleto.

Phar

Chamar Phar::setStub() com um resource e um $length está obsoleto. Tais chamadas devem ser substituídas por: $phar->setStub(stream_get_contents($resource));

Random

A variante MT_RAND_PHP Mt19937 está obsoleta.

Reflection

Chamar ReflectionProperty::setValue() com apenas um parâmetro está obsoleto. Para definir propriedades estáticas, passe null como o primeiro parâmetro.

Standard

A função assert_options() está agora obsoleta.

As constantes ASSERT_ACTIVE, ASSERT_BAIL, ASSERT_CALLBACK, ASSERT_EXCEPTION, e ASSERT_WARNING estão obsoletas.

As configurações assert.* no INI estão obsoletas. Consulte a página Alterações no Tratamento de Arquivos INI para obter mais detalhes.

SQLite3

O uso de exceções agora é preferido, e os avisos serão removidos no futuro. Chamar SQLite3::enableExceptions(false) desencadeará um aviso de obsolescência nesta versão.

Zip

A constante ZipArchive::FL_RECOMPRESS está obsoleta e será removida em uma versão futura do libzip.

User Contributed Notes

There are no user contributed notes for this page.


Outras mudanças

Mudanças no Core

FFI

FFI::load() agora é permitido durante o carregamento antecipado quando opcache.preload_user é o usuário do sistema atual. Anteriormente, chamar FFI::load() não era possível durante o carregamento antecipado se a diretiva opcache.preload_user estivesse definida.

FPM

O teste CLI do FPM agora falha se o caminho do socket for mais longo do que o suportado pelo sistema operacional.

Opcache

Nas SAPIs CLI e phpdbg, o carregamento antecipado não exige mais que a diretiva opcache.preload_user esteja configurada ao ser executado como root. Nas outras SAPIs, essa diretiva é necessária ao ser executado como root, pois o carregamento antecipado é feito antes da SAPI mudar para um usuário não privilegiado.

Streams

A função fread() de bloqueio em uma conexão de socket agora retorna imediatamente se houver dados em buffer, em vez de esperar por mais dados.

A memória do fluxo (memory stream) não falha mais se o deslocamento de busca estiver além do final. Em vez disso, a memória é aumentada na próxima gravação e os dados entre o antigo final e o deslocamento são preenchidos com bytes zero, da mesma forma como acontece com arquivos.

Operações de acesso ao stat() como file_exists() e similares agora usarão o caminho real em vez do caminho real da stream. Isso é consistente com a abertura de streams.

Alterações nos Módulos SAPI

CLI

Os fluxos STDOUT, STDERR e STDIN não são mais fechados na destruição de resources, o que ocorre principalmente quando o CLI termina. No entanto, ainda é possível fechar explicitamente esses fluxos usando fclose() e funções semelhantes.

Funções Alteradas

Core

gc_status() adicionou os seguintes 8 campos:

  • "running" => bool
  • "protected" => bool
  • "full" => bool
  • "buffer_size" => int
  • "application_time" => float: empo total de aplicação, em segundos (incluindo collector_time)
  • "collector_time" => float: Tempo gasto coletando ciclos, em segundos (incluindo destructor_time e free_time)
  • "destructor_time" => float: Tempo gasto executando destrutores durante a coleta de ciclos, em segundos
  • "free_time" => float: Tempo gasto liberando valores durante a coleta de ciclos, em segundos.

class_alias()agora suporta a criação de um alias de uma classe interna.

Definir open_basedir em tempo de execução usando ini_set('open_basedir', ...); não aceita mais caminhos que contenham o diretório pai (..). Anteriormente, apenas os caminhos que começavam com .. eram proibidos. Isso poderia ser facilmente contornado adicionando ./ ao início do caminho.

Os manipuladores de exceção do usuário agora capturam exceções durante a finalização.

O HTML resultante das funções highlight_string() e highlight_file() foi alterado. O espaço em branco entre as tags HTML externas é removido. As quebras de linha e espaços não são mais convertidos em entidades HTML. Todo o HTML agora é envolvido em uma tag <pre>. A tag <span> externa foi mesclada com a tag <code> .

Calendar

A função easter_date() agora suporta anos de 1970 a 2.000.000.000 em sistemas de 64 bits, anteriormente, ela suportava apenas anos no intervalo de 1970 a 2037.

Curl

A função curl_getinfo() agora suporta duas novas constantes: CURLINFO_CAPATH e CURLINFO_CAINFO. Se a opção for null, duas chaves adicionais são adicionadas: "capath" e "cainfo".

DOM

Alterada a tentativa de tipo de retorno de DOMCharacterData::appendData() para true.

DOMDocument::loadHTML(), DOMDocument::loadHTMLFile() e DOMDocument::loadXML() agora têm um tipo de retorno tentativo de bool. Anteriormente, isso estava documentado com um tipo de retorno de DOMDocument|bool, mas, a partir do PHP 8.0.0, DOMDocument não pode mais ser retornado, pois não pode ser chamado estaticamente.

Gd

A assinatura da função imagerotate() foi alterada. O parâmetro $ignore_transparent foi removido, pois era ignorado desde o PHP 5.5.0.

Intl

A função datefmt_set_timezone() (e seu alias IntlDateformatter::setTimeZone()) agora retorna true em caso de sucesso, anteriormente retornava null.

IntlBreakiterator::setText() agora retorna false em caso de falha, anteriormente era retornado null. Agora retorna true em caso de sucesso, anteriormente era retornado null.

IntlChar::enumCharNames() agora retorna um boolean. Anteriormente, ela retornava null em caso de sucesso e false em caso de falha.

O método IntlDateFormatter::construct() lançará uma exceção U_ILLEGAL_ARGUMENT_ERROR quando uma localidade inválida foi definida.

MBString

As funções mb_strtolower() e mb_convert_case() implementam regras de formatação condicional para a letra sigma grega. Para mb_convert_case(), a formatação condicional se aplica apenas aos modos MB_CASE_LOWER e MB_CASE_TITLE, não aos modos MB_CASE_LOWER_SIMPLE e MB_CASE_TITLE_SIMPLE..

A função mb_decode_mimeheader() interpreta os underscores em palavras MIME codificadas com QPrint conforme o RFC 2047; eles são convertidos em espaços. Os underscores devem ser codificados como "=5F" em tais palavras MIME codificadas.

Em casos raros, mb_encode_mimeheader() pode transferir-encode (codificar para transferência) a cadeia de entrada, enquanto em PHP 8.2 ela seria passada como ASCII bruto.

A função mb_encode_mimeheader() não descarta mais os bytes NUL (zero) ao codificar a string de entrada com QPrint. Isso anteriormente causava a corrupção de strings em determinadas codificações de texto, especialmente UTF-16 e UTF-32, ao usar mb_encode_mimeheader.

O modo "não estrito" da função mb_detect_encoding()'s agora se comporta conforme descrito na documentação. Anteriormente, retornava false se o mesmo byte (por exemplo, o primeiro byte) da string de entrada fosse inválido em todas as codificações candidatas. Mas geralmente, eliminava codificações candidatas da consideração quando um byte inválido era encontrado e, se o mesmo byte de entrada eliminasse todas as codificações restantes ainda em consideração, retornaria false. Por outro lado, se todas as codificações candidatas, exceto uma, fossem eliminadas da consideração, retornaria a última restante sem considerar quantos erros de codificação poderiam ser encontrados posteriormente na string. Isso difere do comportamento descrito na documentação, que diz: "Se estrito for definido como falso, a codificação mais próxima será retornada."

mysqli

mysqli_fetch_object() agora gera um ValueError em vez de uma Exception quando o argumento $constructor_args não está vazio e a classe não possui um construtor.

mysqli_poll() agora gera um ValueError quando nenhum dos argumentos $read nem $error é fornecido.

mysqli_field_seek() e mysqli_result::field_seek() agora especificam o tipo de retorno como true em vez de bool.

ODBC

A função odbc_autocommit() agora aceita null como valor para o parâmetro $enable. Passar null tem o mesmo comportamento que passar apenas 1 parâmetro, ou seja, indica se o recurso de autocommit está habilitado ou não.

PGSQL

pg_fetch_object() agora gera um ValueError em vez de uma Exception quando o argumento $constructor_args não está vazio e a classe não possui um construtor.

A função pg_insert() agora gera um ValueError em vez de um E_WARNING quando a tabela especificada é inválida.

As funções pg_insert() e pg_convert() agora geram um ValueError ou TypeError em vez de um E_WARNING quando o valor/tipo de um campo não corresponde adequadamente ao tipo do PostgreSQL.

O parâmetro $row das funções
pg_fetch_result(),
pg_field_prtlen(), e
pg_field_is_null() agora é opcional.

Random

A função mt_srand() e srand() foram alteradas para não verificarem o número de argumentos para determinar se uma semente (seed) aleatória deve ser usada. Passar null gerará uma semente aleatória, e ao passar 0, será usado zero como a semente. As funções agora são consistentes com com o comportamento de Random\Engine\Mt19937::__construct().

Reflection

O tipo de retorno da função ReflectionClass::getStaticProperties() não é mais nulo.

Standard

As mensagens de erro do tipo E_NOTICEs emitidas pela função unserialize() foram elevadas para E_WARNING.

unserialize() agora emite um novo E_WARNING se a entrada contiver bytes não consumidos.

array_pad() agora está limitada apenas pelo número máximo de elementos que um array pode ter. Anteriormente, era possível adicionar no máximo 1048576 elementos de cada vez.

strtok() gera um E_WARNING no caso em que o token não é fornecido ao iniciar a tokenização.

A função password_hash() agora encadeará a exceção subjacente Random\RandomException como a Exception $previous do tipo ValueError's quando a geração de salt falhar.

Se você estiver usando um array como o parâmetro $command proc_open(), ele agora deve ter pelo menos um elemento não vazio. Caso contrário, um ValueError será lançado.

proc_open() retorna falso se o array $command for inválido, em vez de um objeto do tipo resource que produz um aviso posteriormente. Este já era o comportamento no Windows mas agora também é aplicável se a implementação posix_spawn estiver em uso (maioria das plataformas Linux, BSD e MacOS). Ainda existem algumas plataformas antigas onde este comportamento não foi alterado já que posix_spawn não é suportado nelas.

array_sum() e array_product() agora emitem um aviso quando os valores no array não podem ser convertidos para int ou float. Anteriormente, arrays e objetos eram ignorados, enquanto todos os outros valores eram convertidos para int. Além disso, objetos que definem uma conversão numérica (por exemplo, GMP) agora são convertidos em vez de serem ignorados.

O parâmetro $decimal da função number_format() agora lida corretamente com números inteiros negativos. Arredondar com um valor negativo para $decimal significa que $num é arredondado para $decimals dígitos significativos antes do ponto decimal. Anteriormente, valores negativos para $decimals eram silenciosamente ignorados e o número era arredondado para zero casas decimais.

Um novo argumento $before_needle foi adicionado à função strrchr(). Ele se comporta de forma semelhante ao seu equivalente nas funções strstr() ou stristr().

str_getcsv() e fgetcsv() agora retornam uma string vazia em vez de uma string contendo um único byte nulo para o último campo, que contém apenas um encapsulamento não terminado.

Outras Alterações nas Extensões

Core

O uso dos operadores de incremento/decremento (++/--) em valores do tipo bool agora gera avisos. Isso ocorre porque atualmente não tem efeito, mas se comportará como $bool += 1 no futuro.

O uso do operador de decremento (--) em valores do tipo null agora gera avisos. Isso ocorre porque atualmente não tem efeito, mas se comportará como $null -= 1 no futuro.

Objetos internos que implementam um cast _IS_NUMBER, mas não um manipulador do operador que sobrescreve a adição e a subtração, agora podem ser incrementados e decrementados como se alguém fosse fazer $o += 1 ou $o -= 1

DOM

O mecanismo de vida útil do DOM foi reformulado de tal forma que nós implicitamente removidos ainda podem ser recuperados. Anteriormente, isso resultava em uma exceção.

SQLite3

A classe SQLite3 agora lança SQLite3Exception (que estende Exception) em vez de Exception.

O código de erro do SQLite agora é passado no código de erro da exceção, em vez de ser incluído na mensagem de erro.

Mudanças no Tratamento de Arquivos INI

  • As configurações INI assert.* foram descontinuadas. Isso inclui as seguintes configurações INI:

    • assert.active
    • assert.bail
    • assert.callback
    • assert.exception
    • assert.warning
    Se o valor da configuração for igual ao valor padrão, nenhuma notificação de descontinuação será emitida. Em vez disso, a configuração INI zzend.assertions deve ser usada.

  • zend.max_allowed_stack_size é uma nova diretiva INI que define o tamanho máximo permitido da pilha. Os valores possíveis são 0 (detectar o tamanho máximo da pilha do processo ou da thread), -1 (sem limite) ou um número positivo de bytes. O valor padrão é 0. Quando não é possível detectar o tamanho máximo da pilha do processo ou da thread, é usado um valor padrão do sistema conhecido. Definir esse valor muito alto tem o mesmo efeito que desabilitar o limite de tamanho da pilha. Fibers usam fiber.stack_size como tamanho máximo permitido da pilha. Um Error é gerado quando a pilha de chamadas do processo ultrapassa zend.max_allowed_stack_size-zend.reserved_stack_size bytes, para evitar falhas de segmentação induzidas por estouro de pilha, com o objetivo de facilitar a depuração. O tamanho da pilha aumenta durante recursões não controladas envolvendo funções internas ou os métodos mágicos __toString(), __clone(), __sleep(), __destruct(). Isso não está relacionado a estouros de buffer de pilha e não é uma medida de segurança.

  • zend.reserved_stack_size é uma nova diretiva INI que define o tamanho reservado da pilha, em bytes. Esse valor é subtraído do tamanho máximo permitido da pilha, como um buffer, ao verificar o tamanho da pilha.

Performance

DOM

A iteração sobre um DOMNodeList agora utiliza o cache. Portanto, solicitar itens não leva mais tempo quadrático por padrão.

Obter o conteúdo de texto de nós agora evita uma alocação, resultando em um ganho de desempenho.

DOMChildNode::remove()agora possui desempenho O(1),

Standard

A verificação de erros das flags na função file() agora é cerca de 7% mais rápida.

SPL

RecursiveDirectoryIterator agora realiza menos operações de entrada/saída (I/O) ao percorrer um diretório.

User Contributed Notes

There are no user contributed notes for this page.


Suporte do Windows

Core

A versão mínima do Windows suportada foi atualizada para o Windows 8 ou Windows Server 2012.

User Contributed Notes

There are no user contributed notes for this page.


Migrando do PHP 8.1.x para o PHP 8.2.x

Índice

  • Novas Funcionalidades
  • Novas Funções
  • Novas Constantes Globais
  • Alterações incompatíveis com versões anteriores
  • Funcionalidades Preteridas
  • Outras mudanças
  • Suporte do Windows

Esta nova versão menor traz vários novos recursos e algumas incompatibilidades que devem ser testadas antes da troca de versões do PHP em ambientes de produção.

Veja também os guias de migração das versões do 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.


Novas Funcionalidades

PHP Core

Atributo SensitiveParameter

Adicionado o atributo #[\SensitiveParameter] para redigir dados confidenciais em backtraces.

Diretiva INI error_log_mode

A diretiva INI error_log_mode foi adicionada, permitindo definir as permissões para o arquivo de log de erros.

Propriedades de Enumerações em expressões constantes

Agora é possível buscar propriedades de Enumerações em expressões constantes.

Melhorias no sistema de tipos

Agora é possível usar null e false como tipos autônomos.

O tipo true foi adicionado.

Agora é possível combinar tipos de interseção e união. O tipo precisa ser escrito em DNF.

Constantes em Traits

Agora é possível definir constantes em traits.

Classes Somente Leitura

Foi adicionado suporte para classes somente leitura.

cURL

Adicionada a opção CURLINFO_EFFECTIVE_METHOD, que retorna o método HTTP efetivo no valor de retorno de curl_getinfo().

Expôs várias novas constantes de libcurl 7.62 a 7.80.

Adicionada a função curl_upkeep() para executar qualquer verificação de manutenção de conexão.

DBA

O driver LMDB agora aceita as flags DBA_LMDB_USE_SUB_DIR ou DBA_LMDB_NO_SUB_DIR para determinar se deve criar um subdiretório ou não ao criar um arquivo de banco de dados.

OCI8

Adicionou a diretiva INI oci8.prefetch_lob_size e a função oci_set_prefetch_lob() para ajustar o desempenho da consulta LOB reduzindo o número de viagens de ida e volta entre bancos de dados PHP e Oracle ao buscar LOBS. Isso pode ser usado com o Oracle Database 12.2 ou posterior.

OpenSSL

Adicionado suporte AEAD para o algoritmo chacha20-poly1305.

ODBC

Adicionadas as funções odbc_connection_string_is_quoted(), odbc_connection_string_should_quote() e odbc_connection_string_quote(). Eles são usados principalmente nos bastidores nas extensões ODBC e PDO_ODBC, mas são expostos ao userland para facilitar o teste de unidade e para que os aplicativos e bibliotecas do usuário executem as próprias citações.

PCRE

Adicionado suporte para o modificador n (NO_AUTO_CAPTURE), que torna os grupos simples (xyz) sem captura. Somente grupos nomeados como (?<name>xyz) estão capturando. Isso afeta apenas quais grupos estão capturando, ainda é possível usar referências de subpadrão numeradas e a matriz de correspondências ainda conterá resultados numerados.

Random

Esta é uma nova extensão que organiza e consolida implementações existentes relacionadas a geradores de números aleatórios. Novos e melhores RNGs estão disponíveis com problemas de escopo eliminados.

User Contributed Notes

There are no user contributed notes for this page.


Novas Funções

cURL

  • curl_upkeep()

IMAP

  • imap_is_open() (desde o 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()

Reflexão

  • ReflectionFunction::isAnonymous()
  • ReflectionMethod::hasPrototype()

Sodium

XChaCha20

  • sodium_crypto_stream_xchacha20_xor_ic()

Padrão

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


Novas Constantes Globais

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

As seguintes opções de socket agora são definidas se forem suportadas:

  • SO_INCOMING_CPU
  • SO_MEMINFO
  • SO_RTABLE (OpenBSD)
  • TCP_KEEPALIVE (MacOS)
  • TCP_KEEPCNT (Linux, outros)
  • TCP_KEEPIDLE (Linux, outros)
  • TCP_KEEPINTVL (Linux, outros)
  • 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.


Alterações incompatíveis com versões anteriores

Data

DateTime::createFromImmutable() agora possui um tipo de retorno provisório static, que anteriormente era DateTime.

DateTimeImmutable::createFromMutable() agora possui um tipo de retorno provisório static, que anteriormente era DateTimeImmutable.

number em relative formats não mais aceita números com mais de um sinal, por exemplo +-2.

ODBC

Agora a extensão ODBC escapa o nome de usuário e a senha quando ambos uma string de conexão e nome de usuário/senha são fornecidos e a string precise ser acrescentada. Antes, valores dados pelo usuário contendo valores que necessitassem ser escapados poderiam criar uma string de conexão malformada ou injetar valores a partir de dados providos pelo usuário. As regras de escape devem ser idênticas às do comportamento do DbConnectionOptions do .NET BCL.

PDO_ODBC

A extensão PDO_ODBC também escapa o nome de usuário e senha quando uma string de conexão é fornecida. Veja a mudança na extensão ODBC para mais informações.

Biblioteca Padrão

glob() agora devolve um array vazio se todos os caminhos forem restringidos por open_basedir. Anteriormente, o valor devolvido era false. Além disso, agora um aviso é emitido mesmo quando apenas alguns caminhos sejam restringidos por open_basedir.

FilesystemIterator::__construct(): anteriormente ao PHP 8.2.0, FilesystemIterator::SKIP_DOTS sempre estava ativa e não podia ser desativada. Para manter a preservar o comportamento anterior, a constante deve ser informada explicitamente quanto utilizando o parâmetro flags. O valor padrão de flags não foi modificado.

strtolower(),
strtoupper(),
stristr(),
stripos(),
strripos(),
lcfirst(),
ucfirst(),
ucwords(),
e str_ireplace() não são mais sensíveis à localização.
Elas agora realizam conversão de caixa em ASCII, como se a localização fosse "C".
Versões localizadas dessas funções estão disponíveis na  extensão MBString.
Além disso, array_change_key_case() e ordenações com
SORT_FLAG_CASE agora também usam conversão de caixa em ASCII.

str_split() agora devolve um array vazio para uma string vazia. Anteriormente era devolvido um array com uma única string vazia como elemento. mb_str_split() não é afetada por essa mudança, visto que tal função já se comportava dessa maneira.

ksort() e krsort() agora fazem comparação de string numérica sob SORT_REGULAR utilizando as regras de PHP 8 padrão.

var_export() deixou de omitir a contrabarra final em classes exportadas, ou seja, agora os nomes de classes estarão completamente qualificados.

Biblioteca Padrão do PHP (SPL)

Agora os seguintes métodos obrigam sua assinatura:

  • SplFileInfo::_bad_state_ex()
  • SplFileObject::getCsvControl()
  • SplFileObject::fflush()
  • SplFileObject::ftell()
  • SplFileObject::fgetc()
  • SplFileObject::fpassthru()

SplFileObject::hasChildren() agora possui um tipo de retorno provisório false, que anteriormente era bool.

SplFileObject::getChildren() agora possui um tipo de retorno provisório null, que anteriormente era ?RecursiveIterator.

GlobIterator agora devolve um array vazio se todos os caminhos forem restringidos por open_basedir. Anteriormente o valor devolvido era false. Além disso, agora um aviso é emitido mesmo quando apenas alguns caminhos sejam restringidos por open_basedir.

User Contributed Notes

There are no user contributed notes for this page.


Funcionalidades Preteridas

PHP Core

Uso de propriedades dinâmicas

A criação de propriedades dinâmicas foi preterida a menos que a classe a ative usando o atributo #[\AllowDynamicProperties]. stdClass permite propriedades dinâmicas. O uso dos métodos mágicos __get()/__set() não é afetado por essa mudança. Um aviso de descontinuação de propriedades dinâmicas pode ser abordado das seguintes maneiras:

  • Declarando a propriedade (preferido).
  • Adicionando o atributo #[\AllowDynamicProperties] à classe (que também se aplica a todas as classes filhas).
  • Usando um WeakMap se dados adicionais precisarem ser associados a um objeto ao qual não se detém posse.

Chamáveis relativos

Chamáveis que não são aceitos pela sintaxe $callable() (mas são aceitos por call_user_func()) foram preteridos. Em particular:

  • "self::method"
  • "parent::method"
  • "static::method"
  • ["self", "method"]
  • ["parent", "method"]
  • ["static", "method"]
  • ["Foo", "Bar::method"]
  • [new Foo, "Bar::method"]
Isso não afeta chamáveis de métodos normais como "A::method" ou ["A", "method"].

Estilo de interpolação "${var}" e "${expr}"

Os estilos de interpolação de string "${var}" e "${expr}" foram preteridos. Use "$var"/"{$var}" e "{${expr}}", respectivamente.

MBString

O uso das 'codificações de texto' QPrint, Base64, Uuencode, e HTML-ENTITIES foi preterido para todas as funções de MBString. Diferente das outras codificações de texto suportadas pela MBString, essas não codificam a sequência de pontos de código Unicode, mas sim uma sequência de bytes brutos. Não está claro quais deveriam ser os valores de devolução corretos para a maioria das funções de MBString quando uma dessas não-codificações é especificada. Além disso, o PHP possui implementações separadas, embutidas, para todas elas; por exemplo, dados UUencoded podem ser manipulados utilizando convert_uuencode()/convert_uudecode().

SPL

O método interno SplFileInfo::_bad_state_ex() for preterido.

Biblioteca Padrão

utf8_encode() e utf8_decode() foram preteridas.

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


Outras mudanças

Mudanças no Core

O tipo iterable agora é um alias de tempo de compilação integrado para array|Traversable. As mensagens de erro relacionadas ao iterable agora usarão array|Traversable. Reflexão de tipo é preservada para iterable único (e ?iterable) para produzir um ReflectionNamedType com nome iterable, no entanto, o uso de iterable em tipos de união será convertido em array|Traversable.

O formato da data dos cookies enviados agora é 'D, d M Y H:i:s \G\M\T'; anteriormente era 'D, d-M-Y H:i:s T'.

Alterações nos Módulos SAPI

CLI

Os fluxos STDOUT, STDERR e STDIN não são mais fechados na destruição de recursos, que ocorre principalmente quando a CLI termina. No entanto, ainda é possível fechar explicitamente esses fluxos usando fclose() e similares.

Funções alteradas

Core

As funções strcmp(), strcasecmp(), strncmp(), strncasecmp() e substr_compare(), usando a comparação de string segura binária agora retornam -1, 0 e 1.

DBA

dba_open() e dba_popen() agora possuem a seguinte assinatura obrigatória:

dba_open(
string $path,
string $mode,
?string $handler = null,
int $permission = 0644,
int $map_size = 0,
?int $flags = null
): resource|false

O argumento opcional skip de dba_fetch()'s agora está no final de acordo com a semântica da área de usuário do PHP. Sua assinatura agora é:

dba_fetch(string|array $key, resource $handle, int $skip): string|false
A assinatura sobrecarregada:
dba_fetch(string|array $key, int $skip, resource $handle): string|false
ainda é aceito, mas é recomendável usar a nova variante padrão.

Random

random_bytes() e random_int() agora lançam um \Random\RandomException em falhas de CSPRNG. Anteriormente, um \Exception simples era lançado.

SPL

O parâmetro iterator de iterator_to_array() e iterator_count() é ampliado para iterable de Iterator, permitindo que arrays sejam passados.

Outras alterações nas extensões

Date

As propriedades de DatePeriod agora estão devidamente declaradas.

Intl

Instâncias de IntlBreakIterator, IntlRuleBasedBreakIterator, IntlCodePointBreakIterator, IntlPartsIterator, IntlCalendar, Collator, IntlIterator, UConverter, IntlDateFormatter, IntlDatePatternGenerator, MessageFormatter, ResourceBundle, Spoofchecker, IntlTimeZone, e Transliterator não são mais serializáveis. Anteriormente, eles podiam ser serializados, mas a desserialização produzia objetos inutilizáveis ou falhava.

MySQLi

O suporte para libmysql foi removido e não é mais possível compilar mysqli com libmysql. A partir de agora, a extensão mysqli pode ser compilada apenas com mysqlnd. Todos os recursos libmysql indisponíveis no mysqlnd foram removidos:

  • A propriedade reconnect de mysqli_driver
  • A diretiva INI mysqli.reconnect
  • A constante MYSQLI_IS_MARIADB foi depreciada

OCI8

A versão mínima da biblioteca Oracle Client exigida agora é 11.2.

PCRE

Caracteres NULL (\0) em strings padrão agora são suportados.

Session

Tentar alterar a diretiva INI da session.cookie_samesite enquanto a sessão está ativa ou a saída já foi enviada falhará e emitirá um aviso. Isso alinha o comportamento com todas as outras configurações INI da sessão.

SQLite3

sqlite3.defensive agora é PHP_INI_USER.

Standard

getimagesize() agora relata as dimensões reais da imagem, bits e canais de imagens AVIF. Anteriormente, as dimensões eram relatadas como 0x0 e bits e canais não eram relatados.

Tidy

As propriedades da classe tidy agora estão devidamente declaradas. E os da classe tidyNode agora são declarados corretamente como somente leitura.

Zip

A extensão Zip foi atualizada para a versão 1.20.0, que adiciona os seguintes métodos:

  • ZipArchive::clearError()
  • ZipArchive::getStreamName()
  • ZipArchive::getStreamIndex()

Alterações na manipulação de arquivos INI

O suporte para prefixos binários (0b/0B) e octal (0o/0O) foi adicionado às configurações INI de número inteiro. As configurações INI de número inteiro que começam com zero (0) continuam a ser interpretadas como um número inteiro octal.

A análise de alguns valores mal formatados agora acionará um aviso quando isso foi silenciosamente ignorado antes. Para compatibilidade com versões anteriores, a interpretação desses valores não mudou. Isso afeta as seguintes configurações:

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


Suporte do Windows

Núcleo

As mensagens de erro específicas do Windows não são mais localizadas, mas sempre exibidas em inglês para corresponder melhor às mensagens de erro do PHP.

Suporte preliminar e altamente experimental para construção em ARM64 foi adicionado.

OCI8

Como a compilação no Oracle Client 10g não é mais suportada, a opção de configuração --with-oci8 foi descartada. As opções de configuração --with-oci8-11g, --with-oci8-12c e --with-oci8-19 ainda são suportadas.

Zip

A extensão Zip foi atualizada para a versão 1.21.0 e agora é construída como biblioteca compartilhada (DLL) por padrão.

User Contributed Notes

There are no user contributed notes for this page.


Migrando do PHP 8.0.x para o PHP 8.1.x

Índice

  • Novas Funcionalidades
  • Novas Classes e Interfaces
  • Novas Funções
  • Novas Constantes Globais
  • Alterações incompatíveis com versões anteriores
  • Funcionalidades depreciadas
  • Outras Mudanças

Esta nova versão menor traz vários novos recursos e algumas incompatibilidades que devem ser testadas antes da troca de versões do PHP em ambientes de produção.

Veja também os guias de migração das versões do PHP 7.1.x, 7.2.x, 7.3.x, 7.4.x e 8.0.x.

User Contributed Notes

There are no user contributed notes for this page.


Novas Funcionalidades

PHP Core

Prefixo de Inteiro Literal Octal

Inteiros octais agora podem usar um prefixo 0o/0O explícito em inteiros literais, similar à inteiros literais binários e hexadecimais.

<?php
014; // Literal octal não-prefixado
0o14; // Literal octal prefixado
?>

Desempacotamento de Array com chaves String

Adicionado suporte para desmontagem de arrays com chave string

<?php
$arr1 = [1, 'a' => 'b'];
$arr2 = [...$arr1, 'c' => 'd']; //[1, 'a' => 'b', 'c' => 'd']
?>

Argumentos Nomeados Após Desempacotamento de Argumentos

Agora é possível especificar argumentos nomeados após um desempacotamento de argumentos. ex. foo(...$args, nomeado: $arg).

Chave do Caminho Completo para Upload de Arquivos

Upload de arquivos agora fornece uma chave adicional full_path, que contém o caminho completo (em vez de apenas o nome base) do arquivo carregado. Isso destina-se ao uso em conjunto com "upload webkitdirectory".

Enumerações

Suporte para Enumerações foi adicionado.

Fibers

Suporte para Fibers foi adicionado.

Sintaxe de Callable de Primeira Classe

Closures para callables agora podem ser criadas usando a sintaxe myFunc(...), que é idêntica a Closure::fromCallable('myFunc').

Nota: O ... é parte da sintaxe, e não uma omissão.

Tipos de Intersecção

Suporte a tipos de intersecção foi adicionado.

Cuidado

Tipos de Intersecção não podem ser usados em conjunto com tipos de união

Tipo never

Um novo tipo never de retorno apenas foi adicionado. Isso indica que a função exit(), lança uma exceção, ou não termina.

new em Inicializadores

Agora é possível usar expressões new ClassName() como o valor padrão de um parâmetro, variável estática, inicializadores de constante global, e como argumentos de atributo. Objetos também podem ser passados para define() agora.

Propriedades somente leitura

Suporte para propriedades readonly foi adicionado.

Constantes de classe finais

Adicionado suporte ao modificador final para constantes de classe. Além disso, as constantes de interface podem ser sobreescritas.

CURL

Adicionada a opção CURLOPT_DOH_URL.

Adicionadas opções para certificado blob quando 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

Adicionada CURLStringFile, que pode ser usada para postar um arquivo a partir de uma string em vez de um arquivo:

<?php
$file = new CURLStringFile($data, 'filename.txt', 'text/plain');
curl_setopt($curl, CURLOPT_POSTFIELDS, ['file' => $file]);
?>

FPM

Adicionado status de formato openmetrics. Ele pode ser usado pelo Prometheus para buscar métricas do FPM.

Adicionada nova opção de pool para o gerenciador de processo dinâmico chamada pm.max_spawn_rate. Ela permite iniciar uma séria de filhos em um ritmo mais rápido quando pm dinâmico está selecionado. O valor padrão é 32 que era o valor codificado anterior.

GD

Suporte Avif agora está disponível através de imagecreatefromavif() e imageavif(), se a libgd foi compilada com suporte Avif.

Hash

As seguintes funções hash(), hash_file(), e hash_init() agora suportam um argumento opcional options adicional, que pode ser utilizado para passar dados específicos do algoritmo.

MurmurHash3

Adicionado suporte a MurmurHash3 com porte A streaming. As seguintes variantes estão implementadas:

  • murmur3a, hash 32-bit
  • murmur3c, hash 128-bit para x86
  • murmur3f, hash 128-bit para x64

O estado de hash inicial pode ser passado através da chave seed no array options, por exemplo:

<?php
$h = hash("murmur3f", $data, options: ["seed" => 42]);
echo $h, "\n";
?>
Um valor semente válido está no intervalo de 0 até o UINT_MAX definido pela plataforma, geralmente 4294967295.

xxHash

Adicionado suporte a xxHash. As seguintes variantes estão implementadas:

  • xxh32, hash 32-bit
  • xxh64, hash 64-bit
  • xxh3, hash 64-bit
  • xxh128, hash 128-bit

O estado inicial de hash pode ser passado através da chave seed no array options, por exemplo:

<?php
$h = hash("xxh3", $data, options: ["seed" => 42]);
echo $h, "\n";
?>
O uso de segredo é suportado através da passagem do chave secret no array options, também:
<?php
$h = hash("xxh3", $data, options: ["secret" => "Segredo de pelo menos 136 bytes aqui"]);
echo $h, "\n";
?>
A qualidade do segredo personalizado é crucial para a qualidade do hash resultante. É altamente recomendado usar a melhor entropia possível para o segredo.

MySQLi

Nova diretiva INI mysqli.local_infile_directory

A diretiva INI mysqli.local_infile_directory foi adicionada, que pode ser usada para especificar um diretório a partir do qual os arquivos podem ser carregados. Só é significativo se mysqli.allow_local_infile não estiver habilitada, já que todos os diretórios são permitidos nesse caso.

Ligar parâmetros no execute

Agora é possível ligar parâmetros passando-os como um array para o mysqli_stmt::execute(). Todos os valores serão ligados como strings. Apenas arrays de lista são permitidos. Essa nova funcionalidade não está disponível quando MySQLi é compilado com libmysqlclient.

<?php
$stmt = $mysqli->prepare('INSERT INTO users(id, name) VALUES(?,?)');
$stmt->execute([1, $username]);
?>

Novo método mysqli_result::fetch_column()

mysqli_result::fetch_column() foi adicionado para permitir buscar um único valor escalar do conjunto de resultados. O novo método aceita um parâmetro opcional baseado em 0 column do tipo int especificando de qual coluna buscar.

<?php
$result = $mysqli->query('SELECT username FROM users WHERE id = 123');
echo $result->fetch_column();
?>

PDO

O atributo PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY foi adicionado, que pode ser usado para especificar um diretório no qual os arquivos podem ser carregados. É significante apenas se PDO::MYSQL_ATTR_LOCAL_INFILE não estiver habilitada, já que todos os diretórios são permitidos nesse caso.

PDO_SQLite

A sintaxe DSN "file:" do SQLite agora é suportada, que permite especificar flags adicionais. Essa funcionalidade não está disponível se open_basedir estiver definido.

<?php
new PDO('sqlite:file:caminho/para/sqlite.db?mode=ro')
?>

POSIX

Adicionadas POSIX_RLIMIT_KQUEUES and POSIX_RLIMIT_NPTS. Esses rlimits estão disponíveis apenas no FreeBSD.

Standard

fputcsv() agora aceita um novo argumento eol que permite a definição de uma sequência de fim de linha personalizada, o padrão continua o mesmo e é "\n".

SPL

SplFileObject::fputcsv() agora aceita um novo argumento eol que permite a definição de uma sequência de fim de linha personalizada, o padrão continua o mesmo e é "\n".

User Contributed Notes

There are no user contributed notes for this page.


Novas Classes e Interfaces

cURL

  • CURLStringFile

Intl

  • IntlDatePatternGenerator

Reflection

  • ReflectionFiber

User Contributed Notes

There are no user contributed notes for this page.


Novas Funções

PHP Core

  • array_is_list()

GD

  • imagecreatefromavif()
  • imageavif()

MySQLi

  • mysqli_result::fetch_column()
  • mysqli_fetch_column()

Controle de Processo

  • pcntl_rfork()

Reflexão

  • ReflectionFunctionAbstract::getClosureUsedVariables()

Padrão

  • fsync()
  • fdatasync()

Sodium

XChaCha20

  • sodium_crypto_stream_xchacha20()
  • sodium_crypto_stream_xchacha20_keygen()
  • sodium_crypto_stream_xchacha20_xor()

Ristretto255

Funções Ristretto255 estão disponíveis a partir de 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.


Novas Constantes Globais

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

    Essa constante foi adicionada como uma substituta para MYSQLI_REFRESH_SLAVE, de acordo com uma mudança vinda do MySQL. A constante antiga ainda está disponível por motivos de compatibilidade com versões anteriores, mas pode ser depreciada/removida no futuro.

PCNTL

  • PRIO_DARWIN_BG
  • PRIO_DARWIN_THREAD

POSIX

  • POSIX_RLIMIT_KQUEUES
  • POSIX_RLIMIT_NPTS

Sockets

As seguintes opções de socket agora são definidas se forem suportadas:

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


Alterações incompatíveis com versões anteriores

PHP Core

Restrições de acesso ao $GLOBALS

Acesso ao array $GLOBALS agora está sujeito a uma série de restrições. Acesso de leitura e escrita a elementos individuais de array como $GLOBALS['var'] continuam funcionando como estão. Acesso somente leitura para todo o array $GLOBALS também continua a ser suportado. No entanto, acesso de escrita para todo o array $GLOBALS não é mais suportado. Por exemplo, array_pop($GLOBALS) resultará em um erro.

Uso de variáveis static em Métodos Herdados

Quando um método usando variáveis estáticas é herdado (mas não sobreposto), o método herdado agora irá compartilhar variáveis estáticas com o método pai.

<?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), anteriormente int(1)
var_dump(B::counter()); // int(4), anteriormente int(2)
?>
Isso significa que variávies estáticas em métodos agora se comportam da mesma maneira que propriedades estáticas.

Parâmetros opcionais especificados antes de parâmetros obrigatórios

Um parâmetro opcional especificado antes de parâmetros obrigatórios agora é sempre tratado como obrigatório, mesmo ao chamar usando argumentos nomeados. A partir do PHP 8.0.0, mas antes do PHP 8.1.0, a função abaixo emite uma notícia de depreciação na definição, mas executa com sucesso quando chamada. A partir do PHP 8.1.0, um erro da classe ArgumentCountError é lançado, assim como seria lançado ao chamar argumentos posicionais.

<?php
function fazeriogurte($recipiente = "tigela", $sabor)
{
return "Fazendo um(a) $recipiente de iogurte de $sabor.\n";
}
try
{
echo fazeriogurte(sabor: "framboesa");
}
catch (Error $e)
{
echo get_class($e), ' - ', $e->getMessage(), "\n";
}
?>

Saída do exemplo acima no PHP 8.0:

Deprecated: Required parameter $sabor follows optional parameter $recipiente
 in example.php on line 3
Fazendo um(a) tigela de iogurte de framboesa.

Saída do exemplo acima no PHP 8.1:

Deprecated: Optional parameter $recepiente declared before required parameter
 $sabor is implicitly treated as a required parameter in example.php on line 3
ArgumentCountError - fazeriogurte(): Argument #1 ($recepiente) not passed

Note que um valor padrão de null pode ser usado antes de parâmetros obrigatórios para especificar um tipo anulável, mas o parâmetro ainda será obrigatório.

Compatibilidade de Tipo de Retorno com Classes Internas

A maioria dos métodos internos não-finais agora obrigam métodos que fazem sobrescrita a declarar um tipo de retorno compatível, do contrário um aviso de depreciação é emitido durante a validação de herança. Caso o tipo de retorno não possa ser declarado para um método que faz sobrescrita devido a questões de compatilidade entre versões PHP, um atributo ReturnTypeWillChange pode ser adicionado para silenciar o aviso de depreciação.

Novas Palavras-chave

readonly agora é uma palavra-chave. No entanto, ela ainda pode ser usada como nome de função.

never agora é uma palavra reservada, então ela não pode ser usada para nomear uma classe, interface ou trait, e também é proibida de ser usada em namespaces.

Migração de Recurso para Objeto

Diversos resources foram migrados para objects. Checagens de valor de retorno usando is_resource() devem ser trocadas para checagens por false.

  • As funções FileInfo agora aceitam e retornam objetos finfo em vez de resources fileinfo.

  • As funções FTP agora aceitam e retornam objetos FTP\Connection em vez de resources ftp.

  • As funções IMAP agora aceitam e retornam objetos IMAP\Connection em vez de resources imap.

  • As funções LDAP agora aceitam e retornam objetos LDAP\Connection em vez de resources ldap link.

  • As funções LDAP agora aceitam e retornam objetos LDAP\Result em vez de resources ldap result.

  • As funções LDAP agora aceitam e retornam objetos LDAP\ResultEntry em vez de resources ldap result entry.

  • As funções PgSQL agora aceitam e retornam objetos PgSql\Connection em vez de resources pgsql link.

  • As funções PgSQL agora aceitam e retornam objetos PgSql\Result em vez de resources pgsql result.

  • As funções PgSQL agora aceitam e retornam objetos PgSql\Lob em vez de resources pgsql large object.

  • As funções PSpell agora aceitam e retornam objetos PSpell\Dictionary em vez de resources pspell.

  • As funções PSpell agora aceitam e retornam objetos PSpell\Config em vez de resources pspell config.

MySQLi

mysqli_fetch_fields(), e mysqli_fetch_field_direct() agora irão sempre retornar 0 para a max_length. Essa informação pode ser computada iterando sobre o conjunto de resultados, e obtendo o tamanho máximo. Era isso que o PHP estava fazendo internamente anteriormente.

A opção MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH não tem mais efeito.

A opção MYSQLI_STORE_RESULT_COPY_DATA Não tem mais efeito. Passar qualquer valor para o parâmetro mode do mysqli::store_result() não tem mais efeito.

mysqli::connect() agora retorna true em vez de null em caso de sucesso.

O modo de manipulação de erros padrão foi alterado de "silent" para "exceptions" Veja a página Modo de relatório do MySQLi para mais detalhes sobre o que isso emplica, e como definir esse atributo explicitamente. Para restaurar o comportamento anterior use: mysqli_report(MYSQLI_REPORT_OFF);

Classes estendendo mysqli_stmt::execute() agora são obrigadas a especificar o parâmetro opcional adicional.

MySQLnd

A diretiva INI mysqlnd.fetch_data_copy foi removida. Isso não deve resultar em mudanças comportamentais visíveis pelo usuário.

OpenSSL

Chaves privadas EC agora serão exportadas no formato PKCS#8 em vez de formatos tradicionais, assim como todas as outras chaves.

openssl_pkcs7_encrypt() e openssl_cms_encrypt() agora irão por padrão usar AES-128-CBC em vez de RC2-40. O cifrador RC2-40 é considerado inseguro e não é habilitado por padrão pelo OpenSSL 3.

PHP Data Objects

PDO::ATTR_STRINGIFY_FETCHES agora stringifica valores de tipo bool para "0" iy "1". Anteriormente bools não eram stringificados.

Chamar PDOStatement::bindColumn() com PDO::PARAM_LOB agor irá constantemente vincular um resultado de stream quando PDO::ATTR_STRINGIFY_FETCHES não está habilitado. Anteriormente, o resultado seria uma stream ou string dependendo do driver de banco de dados utilizado e a hora que a vinculação é realizada.

Driver MySQL

Inteiros e floats em conjuntos de resultados agora serão retornados usando tipos nativos do PHP em vez de strings ao usar declarações preparadas emuladas. Isso corresponde ao comportamento das declarações preparadas nativas. O comportamento anterior pode ser restaurado habilitando a opção PDO::ATTR_STRINGIFY_FETCHES.

Driver SQLite

Inteiros e floats em conjuntos de resultados agora serão retornados usando tipos nativos do PHP. O comportamento anterior pode ser restaurado habilitando a opção PDO::ATTR_STRINGIFY_FETCHES.

Phar

Para cumprir com a interface ArrayAccess, Phar::offsetUnset() e PharData::offsetUnset() não retorna mais um bool.

Biblioteca Padrão

version_compare() não aceita mais abreviações de operadores não documentados.

htmlspecialchars(), htmlentities(), htmlspecialchars_decode(), html_entity_decode(), e get_html_translation_table() agora usam ENT_QUOTES | ENT_SUBSTITUTE em vez de ENT_COMPAT por padrão. Isso significa que ' é escapada para &#039; enquanto antes nada era feito. Adicionalmente, UTF-8 malformado será substituído por um caractere de substituição Unicode, ao invés de resultar em uma string vazia.

debug_zval_dump() agora imprime a refcount de wrappers de referência com sua refcount, em vez de apenas prefixar & ao valor. Isso modela de forma mais precisa a representação de referência desde o PHP 7.0.

debug_zval_dump() agora imprime interned em vez de uma refcount falso para strings internadas e arrays imutáveis.

Biblioteca Padrão do PHP (SPL)

SplFixedArray, agora será codificado em JSON como um array

User Contributed Notes

There are no user contributed notes for this page.


Funcionalidades depreciadas

PHP Core

Implementar Serializable sem __serialize() e __unserialize()

Apenas os novos métodos devem ser implementados, se nenhum suporte para PHP anterior à versão 7.4 for fornecido, ou ambos devem ser implementados.

Passar null para parâmetros não não-anuláveis de funções embutidas

Tipos escalares para funções embutidas são anuláveis por padrão. Esse comportamento está depreciado para alinhar com o comportamento de funções definidas pelo usuário, onde tipos escalares precisam ser explicitamente marcados como anuláveis.

<?php
var_dump(str_contains("foobar", null));
// Deprecated: Passing null to parameter #2 ($needle) of type string
// is deprecated
?>

Conversões float para int incompatíveis implícitas

A conversão implícita de float para int que leva a uma perda de precisão agora está depreciada. Isso afeta chaves de array, Declarações do tipo int no modo coercitivo, e operadores trabalhando em ints.

<?php
$a = [];
$a[15.5]; // depreciado, pois o valor da chave perde o componente de 0.5
$a[15.0]; // ok, pois 15.0 == 15
?>

Chamar o elemento static em um trait

Chamar um método static, ou acessar uma propriedade static diretamente em um trait está depreciado. Métodos e propriedades estáticos devem ser acessados apenas em uma classe usando o trait.

Retornar um não-array da __sleep()

Retornar um valor que não é um array da __sleep() agora gera um diagnóstico.

Retornar por referência de uma função void

<?php
function &test(): void {}
?>
Essa função é contraditória, e já emite o seguinte E_NOTICE quando chamada: Only variable references should be returned by reference.

Autovivificação a partir de false

Autovivificação é o processo de criar um novo array ao acrescentar um valor. Autovivificação é proibida a partir de valores escalares, false, no entanto era uma exceção. Isso está depreciado agora.

<?php
$arr = false;
$arr[] = 2; // depreciado
?>

Nota:

Autovivificação a partir de null e valores não indefinidos ainda é permitida:

<?php
// A partir de indefinido
$arr[] = 'some value';
$arr['doesNotExist'][] = 2;
// A partir de null
$arr = null;
$arr[] = 2;
?>

ctype

Verificar argumentos não-string

Passar um argumento não-string está depreciado. No futuro, o argumento será interpretado como uma string em vez de um codepoint ASCII. Dependendo do comportamento pretendido, o argumento deve ser convertido para string ou uma chamada explícita para chr() deve ser feita. Todas as funções ctype_*() são afetadas.

Data

date_sunrise() e date_sunset() foram depreciadas em favor de date_sun_info().

strptime() foi depreciada. Use date_parse_from_format() em vez dela (para análise independente de localidade), ou IntlDateFormatter::parse() (para análise dependente de localidade).

strftime() e gmstrftime() foram depreciadas. Em vez delas, use date() (para formatação independente de localidade), ou IntlDateFormatter::format() (para formatação dependente de localidade).

Filtros

Os filtros FILTER_SANITIZE_STRING e FILTER_SANITIZE_STRIPPED estão depreciados.

A diretiva INI filter.default está depreciada.

GD

O num_points da imagepolygon(), imageopenpolygon() e imagefilledpolygon() foi depreciado.

Hash

A mhash(),
mhash_keygen_s2k(),
mhash_count(),
mhash_get_block_size(),
e mhash_get_hash_name() foram depreciadas.
Use as funções hash_*() em vez delas.

IMAP

A constante NIL foi depreciada. Use 0 em vez dela.

Intl

Chamar IntlCalendar::roll() com um argumento bool está depreciado. Use 1 e -1 em vez de true e false respectivamente.

Multibyte String

Chamar mb_check_encoding() sem argumentos está depreciado.

MySQLi

A propriedade mysqli_driver::$driver_version foi depreciada. Ela era sem sentido e desatualizada, use PHP_VERSION_ID em vez dela.

Chamar mysqli::get_client_info() ou mysqli_get_client_info() com o argumento mysqli foi depreciado. Chame mysqli_get_client_info() sem argumentos para obter a informação de versão da biblioteca cliente.

O método mysqli::init() foi depreciado.
Substitua chamadas para parent::init() por
parent::__construct().

OCI8

A diretiva INI oci8.old_oci_close_semantics está depreciada.

ODBC

odbc_result_all() foi depreciada.

PDO

O modo de busca PDO::FETCH_SERIALIZE foi depreciado.

PgSQL

Não passar o argumento de conexão para todas as funções pgsql_*() foi depreciado.

SOAP

A opção ssl_method do SoapClient::__construct() foi depreciada em favor das opções de contexto de stream SSL.

Biblioteca Padrão

Chamar key(), current(), next(), prev(), reset(), ou end() em objects está depreciado. Primeiro converta o object para um array utilizando get_mangled_object_vars(), ou utilize os métodos fornecidos por uma classe que implemente Iterator, como por exemplo ArrayIterator.

A diretiva INI auto_detect_line_endings está depreciada. Se necessário, em vez dela, lide com quebras de linha "\r" manualmente.

As constantes FILE_BINARY e FILE_TEXT foram depreciadas. Elas nunca tiveram nenhum efeito.

User Contributed Notes

There are no user contributed notes for this page.


Outras Mudanças

Mudanças nos Módulos SAPI

CLI

Usando -a sem a extensão readline agora resultará em um erro. Anteriormente, -a sem readline havia o mesmo comportamento que chamar php sem nenhum argumento, além de imprimir uma mensagem adicional "Interactive mode enabled". Esse modo não era interativo.

PHPDBG

Funcionalidade remota do phpdbg foi removida.

Funções Alteradas

Core

A ordem das propriedades usadas em foreach, var_dump(), serialize(), comparação de objetos, etc. foi alterada. Propriedades agora são ordenadas naturalmente de acordo com a declaração e herança deles. Propriedades declaradas em uma classe base estarão antes das propriedades das filhas.

A ordem é consistente com o layout interno das propriedades na estrutura zend_object e repete a ordem em default_properties_table[] e properties_info_table[]. A velha ordem não foi documentada e era causada por detalhes de implementação de herança de classes.

Filtro

A flag FILTER_FLAG_ALLOW_OCTAL do filtro FILTER_VALIDATE_INT agora aceita strings octais com o prefixo octal ("0o"/"0O").

GMP

Todas as funções GMP agora aceitam string octal com o prefixo octal ("0o"/"0O").

PDO ODBC

PDO::getAttribute() com
PDO::ATTR_SERVER_INFO e
PDO::ATTR_SERVER_VERSION
agora retorna valores ao invés de lançar PDOException.

Reflexão

ReflectionProperty::setAccessible() e ReflectionMethod::setAccessible() não têm mais efeito. Propriedades e métodos agora são sempre considerados acessíveis via Reflexão.

Padrão

syslog() agora é segura para binários.

Outras Mudanças em Extensões

GD

imagewebp() agora pode fazer codificação WebP lossless passando IMG_WEBP_LOSSLESS como a qualidade.

Essa constante é definida apenas se a libgd utilizada suporta codificação WebP lossless.

MySQLi

mysqli_stmt::next_result() e mysqli::fetch_all() agora estão disponíveis quando linkando contra libmysqlclient.

OpenSSL

  • A extensão OpenSSLagora requer pelo menos OpenSSL versão 1.0.2.

  • OpenSSL 3.0 agora é suportado. Esteja ciente que muitos cifradores não estão mais habilitados por padrão (parte do provedor legado), e que validação de parâmetros (p. ex.: tamanho mínimo de chaves) é mais estrita agora.

Phar

  • SHA256 agora é usado por padrão para assinaturas.

  • Adicionado suporte para assinaturas OpenSSL_SHA256 e OpenSSL_SHA512.

SNMP

  • Adicionado suporte para SHA256 e SHA512 para o protocolo de segurança.

Padrão

--with-password-argon2agora usa pkg-config para detectar libargon2. Como tal, o local para uma libgargon2 alternativa deve ser especificado usando PKG_CONFIG_PATH.

Mudanças no Tratamento de Arquivos INI

  • A diretiva INI log_errors_max_len foi removida. Ela não possui mais efeito desde o PHP 8.0.0.

  • Um dólar no início de uma string entre aspas agora pode ser escapado: "\${" agora será interpretado como uma string de conteúdo ${.

  • Barras inversas em strings entre aspas duplas agora são mais consistentemente tratadas como caracteres de escape. Anteriormente, "foo\\" seguida de algo diferente de uma nova linha não era considerada uma string finalizada. Agora ela é interpretada como uma string de conteúdo foo\. No entanto, como uma exceção, a string "foo\" seguida de uma nova linha continuará sendo tratada como uma string válida de conteúdo foo\ em vez de uma string não terminada. Essa exceção existe para suportar usos ingênuos de caminhos do Windows tais como "C:\foo\".

User Contributed Notes

There are no user contributed notes for this page.


Migrando do PHP 7.4.x para o PHP 8.0.x

Índice

  • Novas Funcionalidades
  • Alterações incompatíveis com versões anteriores
  • Recursos depreciados
  • Outras mudanças

Esta nova versão menor traz vários novos recursos e algumas incompatibilidades que devem ser testadas antes da troca de versões do PHP em ambientes de produção.

Veja também os guias de migração das versões do 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.


Novas Funcionalidades

PHP Core

Argumentos nomeados

O suporte para Argumentos nomeados foi adicionado.

Atributos

Suporte para Atributos foi adicionado.

Promoção de propriedade do construtor

Suporte para promoção de propriedade do construtor (declarando propriedades na assinatura do construtor) foi adicionado.

União de Tipos

O suporte para união de tipos foi adicionado.

Expressão Match

O suporte para expressões match foi adicionado.

Operador Nullsafe

Suporte para o nullsafe operador (?->) foi adicionado.

Outros novos recursos

  • A classe WeakMap foi adicionada.

  • A classe ValueError foi adicionada.

  • Qualquer número de parâmetros de função agora pode ser substituído por um argumento variádico, desde que os tipos sejam compatíveis. Por exemplo, o seguinte código agora é permitido:

    <?php
    class A {
    public function     method(int $many, string $parameters, $here) {}
    }
    class     B extends A {
    public function     method(...$everything) {}
    }
    ?>

  • static (como em "vinculação estática tardia") agora pode ser usado como um tipo de retorno:

    <?php
    class Test {
    public function     create(): static {
    return new static();
    }
    }
    ?>

  • Agora é possível buscar o nome da classe de um objeto usando $object::class. O resultado é o mesmo que get_class($object).

  • new e instanceof agora podem ser usados com expressões arbitrárias, usando new (expression)(...$args) e $obj instanceof (expression).

  • Algumas correções de consistência na sintaxe da variável foram aplicadas, por exemplo, escrever Foo::BAR::$baz agora é permitido.

  • Adicionada interface Stringable, que é implementada automaticamente se uma classe definir um método __toString().

  • As Traits agora podem definir métodos privados abstratos. Tais métodos devem ser implementados pela classe que usa o trait.

  • throw agora pode ser usado como uma expressão. Isso permite usos como:

    <?php
    $fn     = fn() => throw new Exception('Exception in arrow function');
    $user = $session->user ?? throw new Exception('Must have user');

  • Uma vírgula final opcional agora é permitida nas listas de parâmetros.

    <?php
    function functionWithLongSignature(
    Type1 $parameter1,
    Type2 $parameter2, // <-- Esta vírgula agora é permitida.
    ) {
    }

  • Agora é possível escrever catch (Exception) para capturar uma exceção sem armazená-la em uma variável.

  • O suporte para tipo mixed foi adicionado.

  • Os métodos privados declarados em uma classe pai não impõem mais nenhuma regra de herança nos métodos de uma classe filha (com exceção dos construtores privados finais). O exemplo a seguir ilustra quais restrições foram removidas:

    <?php
    class ParentClass {
    private function     method1() {}
    private function     method2() {}
    private static function     method3() {}
    // Lança um aviso, pois "final" não tem mais efeito:
    private final function method4() {}
    }
    class     ChildClass extends ParentClass {
    // Todos os itens a seguir agora são permitidos, mesmo que os modificadores não sejam
    // o mesmo que para os métodos privados na classe pai.
    public abstract function method1() {}
    public static function     method2() {}
    public function     method3() {}
    public function     method4() {}
    }
    ?>

  • get_resource_id() foi adicionado, o que retorna o mesmo valor que (int) $resource. Ele fornece a mesma funcionalidade em uma API mais clara.

  • O InternalIterator foi adicionado.

Data e hora

  • DateTime::createFromInterface() e DateTimeImmutable::createFromInterface() foram adicionados.

  • O especificador de formato DateTime p foi adicionado, que é o mesmo que P, mas retorna Z em vez de +00:00 para UTC.

DOM

DOMParentNode e DOMChildNode com novas APIs de travessia e manipulação foram adicionadas.

Filtro

FILTER_VALIDATE_BOOL foi adicionado como um alias para FILTER_VALIDATE_BOOLEAN. O novo nome é preferido, pois usa o nome do tipo canônico.

Enchant

enchant_dict_add(), enchant_dict_is_added() e LIBENCHANT_VERSIONforam adicionados.chant

FPM

Adicionada uma nova opção pm.status_listen que permite obter o status de um terminal diferente (por exemplo, porta ou arquivo UDS), o que é útil para obter o status quando todos os filhos estão ocupados atendendo a solicitações de execução longa.

Hash

Os objetos HashContext agora podem ser serializados.

Funções de Internacionalização

As contantes IntlDateFormatter::RELATIVE_FULL,
IntlDateFormatter::RELATIVE_LONG,
IntlDateFormatter::RELATIVE_MEDIUM e
IntlDateFormatter::RELATIVE_SHORT
foram adicionadas.

LDAP

ldap_count_references() foi adicionado, o que retorna o número de mensagens de referência em um resultado de pesquisa.

OPcache

Se a configuração ini opcache.record_warnings estiver habilitada, o OPcache gravará avisos em tempo de compilação e os reproduzirá na próxima inclusão, mesmo que seja servido do cache.

OpenSSL

Adicionado suporte de sintaxe de mensagem criptográfica (CMS) (» RFC 5652) composto de funções para criptografia, descriptografia, assinatura, verificação e leitura. A API é semelhante à API para funções PKCS #7 com a adição de novas constantes de codificação: OPENSSL_ENCODING_DER, OPENSSL_ENCODING_SMIME e OPENSSL_ENCODING_PEM:

  • openssl_cms_encrypt() criptografa a mensagem no arquivo com os certificados e gera o resultado no arquivo fornecido.
  • openssl_cms_decrypt() que descriptografa a mensagem S/MIME no arquivo e envia os resultados para o arquivo fornecido.
  • openssl_cms_read() que exporta o arquivo CMS para uma matriz de certificados PEM.
  • openssl_cms_sign() que assina a mensagem MIME no arquivo com um certificado e uma chave e gera o resultado no arquivo fornecido.
  • openssl_cms_verify() que verifica se o bloco de dados está intacto, o signatário é quem diz ser e retorna os certificados dos signatários.

Regular Expressions (Perl-Compatible)

preg_last_error_msg() foi adicionado, o que retorna uma mensagem legível por humanos para o último erro PCRE. Ele complementa preg_last_error(), que retorna um valor de enumeração inteiro.

Reflection

  • Os seguintes métodos agora podem retornar informações sobre valores padrão de parâmetros de funções internas:

    • ReflectionParameter::isDefaultValueAvailable()
    • ReflectionParameter::getDefaultValue()
    • ReflectionParameter::isDefaultValueConstant()
    • ReflectionParameter::getDefaultValueConstantName()

SQLite3

SQLite3::setAuthorizer() e respectivas constantes de classe foram adicionados para definir um callback userland que será usado para autorizar ou não uma ação no banco de dados.

Biblioteca padrão

  • str_contains(), str_starts_with() e str_ends_with() foram adicionados, que verificam se haystack contém, começa com ou termina com needle, respectivamente.

  • fdiv() foi adicionado, que executa uma divisão de ponto flutuante sob a semântica IEEE 754. A divisão por zero é considerada bem definida e retornará um de Inf, -Inf ou NaN.

  • get_debug_type() foi adicionado, o que retorna um tipo útil para mensagens de erro. Ao contrário de gettype(), ele usa nomes de tipo canônico, retorna nomes de classe para objetos e indica o tipo de recurso para recursos.

  • printf() e amigos agora suportam os especificadores de formato %h e %H. Estes são os mesmos que %g e %G, mas sempre use "." como o separador decimal, em vez de determiná-lo por meio da localidade LC_NUMERIC.

  • printf() e amigos agora suportam o uso de "*" como largura ou precisão, caso em que a largura/precisão é passada como um argumento para printf. Isso também permite usar a precisão -1 com %g, %G, %h e %H. Por exemplo, o código a seguir pode ser usado para reproduzir a formatação de ponto flutuante padrão do PHP:

    <?php
    printf    ("%.*H", (int) ini_get("precision"), $float);
    printf("%.*H", (int) ini_get("serialize_precision"), $float);
    ?>

  • proc_open() agora suporta descritores pseudo-terminal (PTY). O seguinte anexa stdin, stdout e stderr ao mesmo PTY:

    <?php
    $proc     = proc_open($command, [['pty'], ['pty'], ['pty']], $pipes);
    ?>

  • proc_open() agora suporta descritores de pares de sockets. O seguinte anexa um par de sockets distinto a stdin, stdout e stderr:

    <?php
    $proc     = proc_open($command, [['socket'], ['socket'], ['socket']], $pipes);
    ?>

    Ao contrário dos pipes, os sockets não sofrem com problemas de bloqueio de E/S no Windows. No entanto, nem todos os programas podem funcionar corretamente com soquetes stdio.

  • As funções de classificação agora são estáveis, o que significa que os elementos de comparação igual manterão sua ordem original.

  • array_diff(), array_intersect() e suas variações agora podem ser usadas com um único array como argumento. Isso significa que usos como os seguintes agora são possíveis:

    <?php
    // OK, mesmo que $excludes esteja vazio:
    array_diff($array, ...$excludes);
    // OK, mesmo que $arrays contenha apenas um único array:
    array_intersect(...$arrays);
    ?>

  • O parâmetro flag de ob_implicit_flush() foi alterado para aceitar um bool em vez de um int.

Tokenizador

PhpToken adiciona uma interface baseada em objeto ao tokenizer. Ele fornece uma representação mais uniforme e ergonômica, além de ser mais eficiente em termos de memória e mais rápido.

Zip

  • A extensão Zip foi atualizada para a versão 1.19.1.

  • Novo ZipArchive::setMtimeName() e ZipArchive::setMtimeIndex() para definir a hora de modificação de uma entrada.

  • Novo ZipArchive::registerProgressCallback() para fornecer atualizações durante o fechamento do arquivo.

  • Novo ZipArchive::registerCancelCallback() para permitir o cancelamento durante o fechamento do arquivo.

  • Novo ZipArchive::replaceFile() para substituir um conteúdo de entrada.

  • Novo ZipArchive::isCompressionMethodSupported() para verificar os recursos opcionais de compactação.

  • Novo ZipArchive::isEncryptionMethodSupported() para verificar os recursos opcionais de criptografia.

  • A propriedade ZipArchive::lastId para obter o valor do índice da última entrada adicionada foi adicionada.

  • Os erros agora podem ser verificados após o fechamento de um arquivo usando as propriedades
ZipArchive::status e
ZipArchive::statusSys ou o método
ZipArchive::getStatusString().

  • A opção 'remove_path' de ZipArchive::addGlob() e ZipArchive::addPattern() agora é tratada como um prefixo de string arbitrário (para consistência com a opção 'add_path'), enquanto anteriormente era tratada como um nome de diretório.

  • Os recursos opcionais de compactação/criptografia agora estão listados no phpinfo.

User Contributed Notes

There are no user contributed notes for this page.


Alterações incompatíveis com versões anteriores

PHP Core

Comparação entre String e Número

Comparações não estritas entre números e strings não numéricas, agora funcionam convertendo o número em string e comparando as strings. As comparações entre números e strings numéricas continuam funcionando como antes. Notavelmente, isso significa que a comparação: 0 == "not-a-number" agora é considerada falsa.

Comparação | Antes | Depois
0 == "0" | true | true
0 == "0.0" | true | true
0 == "foo" | true | false
0 == "" | true | false
42 == " 42" | true | true
42 == "42foo" | true | false

Outras mudanças incompatíveis

  • match agora é uma palavra reservada.

  • mixed agora é uma palavra reservada, portanto, não pode ser usado para nomear uma classe, interface ou trait, e também é proibido de ser usado em namespaces.

  • As falhas de asserção agora são lançadas por padrão. Se o comportamento antigo é desejado, assert.exception=0 pode ser definido nas configurações INI.

  • Métodos com o mesmo nome de classe não são mais interpretados como construtores. O método __construct() deve ser utilizado em seu lugar.

  • A capacidade de chamar métodos não estáticos estaticamente foi removida. Por isso a função is_callable() irá falhar ao verificar um método não estático com um nome de classe (deve se realizar uma verificação com uma instância de objeto).

  • Foram removidas as conversões de tipos, (real) e (unset).

  • A diretiva do php.ini track_errors foi removida. Isto significa que a variável php_errormsg não está mais disponível. A função error_get_last() deve ser utilizada em seu lugar.

  • A capacidade de definir constantes que não diferenciam maiúsculas de minúsculas foi removida. O terceiro argumento para a função define() não pode ser mais true.

  • A capacidade de especificar um auto carregamento utilizando a função __autoload() foi removida. A função spl_autoload_register() deve ser utilizada em seu lugar.

  • O argumento errcontext não será mais usado para manipulação de erros personalizados definido com a função set_error_handler().

  • A função create_function() foi removida. Ao invés disso, funções anônimas devem ser utilizadas.

  • A função each() foi removida. foreach ou ArrayIterator devem ser utilizados em seu lugar.

  • Foi removida a capacidade de desvincular this de closures que foram criadas a partir de um método, usando Closure::fromCallable() ou ReflectionMethod::getClosure().

  • A habilidade de desvincular this de closures que contêm usos de this também foi removida.

  • A habilidade de utilizar a função array_key_exists() com objetos foi removida. as funções isset() ou property_exists() devem ser usadas em seu lugar.

  • O comportamento da função array_key_exists() com relação ao tipo do parâmetro key agora é consistente com a função isset() e acesso normal à arrays. Todos os tipos de chave agora usam as coerções usuais e as chaves de array/objeto lançam um TypeError.

  • Qualquer array com número n em sua primeira posição utilizará n+1 em sua próxima chave implícita mesmo se n for negativo.

  • O nível de error_reporting padrão agora é E_ALL. Anteriormente excluía E_NOTICE e E_DEPRECATED.

  • display_startup_errors agora é habilitado por padrão.

  • Usar parent dentro de uma classe sem pai agora produzirá um erro fatal em tempo de execução.

  • O operador @ não irá mais silenciar erros fatais (E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR, E_PARSE). Manipuladores de erros que esperam que error_reporting seja 0 quando @ é usado, devem ser ajustados para usar uma verificação de máscara:

    <?php
    // Substituir isso ...
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
    if (    error_reporting() == 0) {
    return     false;
    }
    // ...
    }

    // ... por isso:
    function my_error_handler($err_no, $err_msg, $filename, $linenum) {
    if (!(    error_reporting() & $err_no)) {
    return     false;
    }
    // ...
    }
    ?>

    Adicionalmente, cuidados devem ser tomados para que mensagens de erro não sejam mostradas no ambiente de produção, o que pode resultar em vazamento de informações. Certifique-se de que a diretiva display_errors=Off seja usada em conjunto com o log de erros.

  • #[ não é mais interpretado como o início de um comentário, já que esta sintaxe é utilizada agora para atributos.

  • Erros de herança devido a assinaturas de método incompatíveis (violações de LSP) agora sempre gerarão um erro fatal. Antes, um aviso era gerado em alguns casos.

  • A precedência dos operadores de concatenação foi modificada em relação ao bitshifts tanto na adição como na subtração.

    <?php
    echo "Sum: " . $a + $b;
    // Era interpretado como:
    echo ("Sum: " . $a) + $b;
    // e passa a ser interpretado como:
    echo "Sum:" . ($a + $b);
    ?>

  • Argumentos com um valor padrão que avaliam null em tempo de execução, não irão mais marcar o tipo do parâmetro como implícito. Um tipo explícito nulo, ou explicitamente null como argumento padrão deve ser usado em seu lugar.

    <?php
    // Subistituir
    function test(int $arg = CONST_RESOLVING_TO_NULL) {}
    // Por isso
    function test(?int $arg = CONST_RESOLVING_TO_NULL) {}
    // Ou isso
    function test(int $arg = null) {}
    ?>

  • Uma série de avisos foram convertidos para exceções do tipo Error:

    • A tentativa de escrita em uma propriedade de um não-objeto. Anteriormente isso criava implicitamente um objeto stdClass para strings nulas, falsas e vazias.
    • A tentativa de anexar um elemento a um array para a qual a chave PHP_INT_MAX já está em uso.
    • Tentar usar um tipo inválido (array ou objeto) como uma chave de array ou deslocamento de string.
    • A tentativa de escrever em um índice de array de um valor escalar.
    • Tentar descompactar um não-array/Traversable.
    • Tentar acessar constantes não qualificadas que são indefinidas. Anteriormente, os acessos constantes não qualificados resultavam em um aviso e eram interpretados como strings.
    • Passar o número errado de argumentos para uma função sem argumento variadic ira lançar uma exceção ArgumentCountError.

    Uma série de notificações foram convertidas em avisos:

    • A tentativa de leitura em uma variável não definida.
    • A tentativa de leitura em uma propriedade não definida.
    • A tentativa de leitura em uma chave de array não definido.
    • A tentativa de leitura em uma propriedade de um não-objeto.
    • A tentativa de acesso em um índice de array em um não-array.
    • A tentativa de conversão de um array para uma string.
    • A tentativa de usar um resource como uma chave de array.
    • A tentativa de usar null, um booleano ou um número de ponto flutuante(float) como uma posição em uma string.
    • A tentativa de leitura em uma posição fora dos limites de uma string.
    • A tentativa de atribuir uma string vazia a uma posição de uma string.

  • A tentativa de atribuir múltiplos bytes em uma posição de uma string agora emite um aviso.

  • Caracteres inesperados no código fonte (como bytes NUL fora de strings) agora irá resultar em uma exceção ParseError em vez de um aviso do compilador.

  • As exceções não capturadas agora passam por "desligamento limpo", o que significa que os destrutores são chamados após uma exceção não detectada.

  • O erro fatal em tempo de compilação "Only variables can be passed by reference" foi adiado até o tempo de execução, e convertido em uma exceção de Error "Argument cannot be passed by reference".

  • Alguns alertas do tipo "Only variables should be passed by reference" foram convertidas para exceções do tipo "Argument cannot be passed by reference"

  • O nome gerado para classes anônimas foi modificado. Agora, inclui o nome da primeira classe ou interface:

    <?php
    new class extends ParentClass {};
    // -> ParentClass@anonymous
    new class implements FirstInterface, SecondInterface {};
    // -> FirstInterface@anonymous
    new class {};
    // -> class@anonymous
    ?>

    O nome mostrado acima ainda é seguido por um byte NUL e um sufixo único.

  • As referências de método de traits não absolutas em adaptações de alias de traits agora precisam ser inequívocas:

    <?php
    class X {
    use     T1, T2 {
    func as otherFunc;
    }
    function     func() {}
    }
    ?>

    Se T1::func() e T2::func() existem, este código anteriormente era aceito de forma silenciosa e func assumia referência a T1::func. Agora irá gerar um erro fatal, e T1::func ou T2::func precisam ser escritos explicitamente.

  • A assinatura de métodos abstratos definido nas características agora é verificada no método de implementação da classe:

    <?php
    trait MyTrait {
    abstract private function     neededByTrait(): string;
    }

    class     MyClass {
    use     MyTrait;

    // Erro por conta do retorno desalinhado.
    private function neededByTrait(): int { return 42; }
    }
    ?>

  • Funções desabilitadas agora são tratadas da mesma forma que funções não existentes. Ao chamar uma função desabilitada será informado que ela é desconhecida, e redefinir uma função desabilitada agora é possível.

  • Os stream wrappers data:// não podem mais ser writable (gravável), indo de encontro ao comportamento documentado.

  • Os operadores aritméticos e bitwise (bit a bit) +, -, *, /, **, %, <<, >>, &, |, ^, ~, ++, -- irão agora apresentar um TypeError quando um dos operandos estiver em um array, resource ou em um object não sobrecarregado (non-overloaded). A única exceção a isto é a operação de mesclagem de array com +, que permanece suportada.

  • A conversão de float para string agora sempre terá o mesmo comportamento, independentemente da localidade.

    <?php
    setlocale    (LC_ALL, "de_DE");
    $f = 3.14;
    echo     $f, "\n";
    // Anteriormente: 3,14
    // Agora: 3.14
    ?>

    Veja as funções printf(), number_format() e NumberFormatter() para customizar a formatação de números.

  • O suporte para chaves (curly braces) obsoletas para acesso de deslocamento foi removida.

    <?php
    // Ao invés de:
    $array{0};
    $array{"key"};
    // Usar:
    $array[0];
    $array["key"];
    ?>

  • Aplicar o modificador final ou método privado agora irá produzir um aviso, a menos que o método seja o construtor.

  • Se um objeto construtor chama a função exit(), o objeto destrutor não será chamado. Isto vai de encontro ao comportamento que o construtor lança.

  • Nomes de Namespace não podem mais conter espaços em branco: Enquanto Foo\Bar será reconhecido como um nome de Namespace, Foo \ Bar não será. Por outro lado, as palavras-chave agora serão permitidas como segmentos de um namespace, o que permite a mudança na interpretação do código: new\x agora é o mesmo que constant('new\x'), e não new \x().

  • Os ternários aninhados agora exigem parênteses explícitos.

  • debug_backtrace() e Exception::getTrace() agora não mais apresentam referências aos argumentos. Não será possível mudar os argumentos de uma função através de um backtrace.

  • O uso de strings numéricas foi modificado para ser mais intuitivo e menos sujeito a erros. Seguindo os espaços em branco, é permitido agora strings numéricas para tratamento de consistência contendo espaços em branco. Isso afeta principalmente:

    • A função is_numeric()
    • Comparações string a string
    • Declaração de tipos
    • Operações de incremento e decremento

    O conceito de um "leading-numeric string" foi praticamente abandonado; os casos onde permanecem são para facilitar a migração. Strings que emitem um E_NOTICE "A non well-formed numeric value encountered" agora emitirão um E_WARNING "A non-numeric value encountered" e todas as strings que emitiram um E_WARNING "A non-numeric value encountered" agora lançarão um erro TypeError. Isso afeta principalmente:

    • Operações aritméticas
    • Operações bit a bit

    Esta mudança do E_WARNING para TypeError também afeta o E_WARNING "Illegal string offset 'string'" para o posicionamento ilegal de strings. O comportamento de conversões explícitas de strings para int/float não foi alterado.

  • Métodos mágicos agora podem ter argumentos e retornar tipos verificados se eles foram declarados. As assinaturas devem corresponder à seguinte lista:

    • __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

  • As chaves do array passados para a função call_user_func_array() agora podem ser interpretadas como nomes de parâmetros, em vez de serem silenciosamente ignoradas.

  • A declaração da função chamada assert() dentro de um namespace não é mais permitida e gera um E_COMPILE_ERROR. A função assert() recebe um tratamento especial pelo motor do PHP, o que pode levar a comportamentos inconsistentes quando definido como uma função de namespace com o mesmo nome.

Migração de Resource para Objeto

Diversos resources foram migrados para objects. Verificações de valor de retorno usando a função is_resource() devem ser substituídas por checagens para false.

  • A função curl_init() agora retornará um objeto CurlHandle ao invés de um resource. A função curl_close() não tem mais efeito, em vez disso a instância da classe CurlHandle é destruída automaticamente se não for mais referenciada.

  • A função curl_multi_init() agora retornará um objeto CurlMultiHandle ao invés de um resource. A função curl_multi_close() não tem mais efeito, em vez disso a instância da classe CurlMultiHandle é destruída automaticamente se não for mais referenciada.

  • curl_share_init() agora retornará um objeto CurlShareHandle em vez de um resource. A função curl_share_close() não tem mais efeito, em vez disso a instância da classe CurlShareHandle é destruída automaticamente se não for mais referenciada.

  • enchant_broker_init() agora retornará um objeto EnchantBroker em vez de um resource.

  • enchant_broker_request_dict() e enchant_broker_request_pwl_dict() agora retornarão um objeto EnchantDictionary em vez de um resource.

  • A extensão GD agora usa objetos GdImage como a estrutura de dados interna para imagens, em vez de resources. A função imagedestroy() não tem mais efeito; em vez disso a instância GdImage é destruída automaticmanete se não for mais referenciada.

  • openssl_x509_read() e openssl_csr_sign() agora retornarão um objeto OpenSSLCertificate em vez de um resource. A função openssl_x509_free() está depreciada e não tem mais efeito, em vez disso a instância OpenSSLCertificate é destruída automaticamente se não for mais referenciada.

  • openssl_csr_new() agora retornará um objeto OpenSSLCertificateSigningRequest em vez de um resource.

  • openssl_pkey_new() agora retornará um objeto OpenSSLAsymmetricKey em vez de um resource. A função openssl_pkey_free() está depreciada e não tem mais efeito, em vez disso a instância OpenSSLAsymmetricKey é destruída automaticamente se não for mais referenciada.

  • shmop_open() irá agora retornar um objeto Shmop ao invés de um resource. A função shmop_close() não tem mais efeitos, e está obsoleta. A instância de Shmop será automaticamente destruída quando não seja mais referenciada.

  • socket_create(), socket_create_listen(),
socket_accept(), socket_import_stream(),
socket_addrinfo_connect(), socket_addrinfo_bind(), e
socket_wsaprotocol_info_import() agora retornarão um
objeto Socket em vez de um resource.
socket_addrinfo_lookup() agora retornará um array de
objetos AddressInfo em vez de resources.

  • msg_get_queue() agora retornará um objeto SysvMessageQueue em vez de um resource.

  • sem_get() agora retornará um objeto SysvSemaphore em vez de um resource.

  • shm_attach() agora retornará um objeto SysvSharedMemory em vez de um resource.

  • xml_parser_create() e xml_parser_create_ns() agora retornarão um objeto XMLParser em vez de um resource. A função xml_parser_free() não tem mais efeito, em vez disso a instância XMLParser é automaticamente destruída se não for mais referenciada.

  • A função XMLWriter agora aceita e retorna, respectivamente, objetos XMLWriter em vez de resources.

  • inflate_init() agora retornará um objeto InflateContext em vez de um resource.

  • deflate_init() agora retornará um objeto DeflateContext em vez de um resource.

COM e .Net (Windows)

A capacidade de importar constantes que não diferenciam maiúsculas de minúsculas de bibliotecas de tipos foi removida. O segundo argumento para com_load_typelib() não pode mais ser falso; com.autoregister_casesensitive não pode mais ser desabilitado; marcadores que não diferenciam maiúsculas de minúsculas em com.typelib_file são ignorados.

CURL

CURLOPT_POSTFIELDS não aceita mais objetos como arrays. Para interpretar um objeto como um array, executar uma conversão explícita de (array). O mesmo se aplica a outras opções que aceitam arrays também.

Data e hora

mktime() e gmmktime() agora requer pelo menos um argumento. time() pode ser usado para obter o registro de data e hora atual.

DOM

Classes não implementadas da extensão DOM que não tinham comportamento e continham dados de teste foram removidos. Essas classes também foram removidas na versão mais recente do DOM padrão:

  • DOMNameList
  • DomImplementationList
  • DOMConfiguration
  • DomError
  • DomErrorHandler
  • DOMImplementationSource
  • DOMLocator
  • DOMUserDataHandler
  • DOMTypeInfo
  • DOMStringExtend

Métodos não implementados da extensão DOM que não tinham comportamento foram removidos:

  • DOMNamedNodeMap::setNamedItem()
  • DOMNamedNodeMap::removeNamedItem()
  • DOMNamedNodeMap::setNamedItemNS()
  • DOMNamedNodeMap::removeNamedItemNS()
  • DOMText::replaceWholeText()
  • DOMNode::compareDocumentPosition()
  • DOMNode::isEqualNode()
  • DOMNode::getFeature()
  • DOMNode::setUserData()
  • DOMNode::getUserData()
  • DOMDocument::renameNode()

Enchant

  • enchant_broker_list_dicts(), enchant_broker_describe() e enchant_dict_suggest() agora retornam um array vazio no lugar de null.

Exif

read_exif_data() foi removido; exif_read_data() deve ser usado em seu lugar.

Filter

  • A FILTER_FLAG_SCHEME_REQUIRED e FILTER_FLAG_HOST_REQUIRED sinalizadores para o filtro FILTER_VALIDATE_URL foram removidas. O scheme e host são (e foram) sempre necessários.

  • A fonte INPUT_REQUEST e INPUT_SESSION para filter_input() etc. foram removidos. Estes nunca foram implementados e seu uso sempre gerou um warning.d

GD

  • A função obsoleta image2wbmp() foi removida.

  • As funções obsoletas png2wbmp() e jpeg2wbmp() foram removidas.

  • O parametro padrão mode de imagecropauto() não aceita mais -1. IMG_CROP_DEFAULT deve ser usado no lugar.

  • No Windows, php_gd2.dll foi renomeado para php_gd.dll.

GMP

gmp_random() foi removida. Uma das gmp_random_range() ou gmp_random_bits() deve ser usado no lugar.

Iconv

implementações de iconv que não definem corretamente errno em caso de erros não são mais suportadas.

IMAP

  • O argumento default_host não utilizado de imap_headerinfo() foi removido.

  • A função imap_header() que é um alias de imap_headerinfo() foi removida.

Funções de Internacionalização

  • A constante obsoleta INTL_IDNA_VARIANT_2003 foi removida.

  • A constante obsoleta Normalizer::NONE foi removida.

LDAP

  • The deprecated functions ldap_sort(),
ldap_control_paged_result() and
ldap_control_paged_result_response() have been removed.

  • A interface deldap_set_rebind_proc() foi mudada; o parâmetro callback não aceita strings vazias; null deve ser usado no lugar.

MBString

  • A diretiva mbstring.func_overload foi removida. The related MB_OVERLOAD_MAIL, as constantes MB_OVERLOAD_STRING, e MB_OVERLOAD_REGEX também foram removidas. Finalmente, a "func_overload" e a "func_overload_list" entradas mb_get_info() foram removidas.

  • mb_parse_str() não pode mais ser usado sem especificar um array de resultados.

  • Vários aliases mbregex obsoletos foram removidos. Veja o seguinte lista para quais funções devem ser usadas:

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

  • O modificador e para mb_ereg_replace() foi removido. mb_ereg_replace_callback() deve ser usado em seu lugar.

  • Um argumento de padrão não string para mb_ereg_replace() agora será interpretado como uma string em vez de um ponto de código ASCII. O comportamento anterior pode ser restaurado com uma chamada explícita para chr().

  • O argumento needle para mb_strpos(),
mb_strrpos(), mb_stripos(),
mb_strripos(), mb_strstr(),
mb_stristr(), mb_strrchr() e
mb_strrichr() agora pode estar vazio.

  • O parâmetro is_hex, que não era usado internamente, foi removido de mb_decode_numericentity().

  • O comportamento herdado de passar a codificação como o terceiro argumento em vez de um deslocamento para a função mb_strrpos() foi removida; um 0 explícito offset com a codificação deve ser fornecido como o quarto argumento.

  • Os aliases de codificação de caracteres ISO_8859-* foram substituídos por Aliases ISO8859-* para melhor interoperabilidade com a extensão iconv. os aliases mbregex ISO 8859 com sublinhados (ISO_8859_* e ISO8859_*) também foram removidos.

  • mb_ereg() e mb_eregi() agora retornarão valores booleanos true sobre uma partida de sucesso. Anteriormente, eles retornavam inteiro 1 se matches não foi passado, ou max(1, strlen($matches[0])) se matches foi passado.

OCI8

  • A classe OCI-Lob agora é chamada de OCILob, e a a classe OCI-Collection agora se chama OCICollection para conformidade de nome imposta pelas ferramentas de anotação de tipo PHP 8 arginfo.

  • Várias funções de alias foram marcadas como obsoletas.

  • oci_internal_debug() e seu alias ociinternaldebug() foram removidos.

ODBC

  • odbc_connect() não reutiliza mais conexões.

  • O parâmetro flags não usado de odbc_exec() foi removido.

OpenSSL

  • openssl_seal() e openssl_open() agora requerem method a ser passado, como o padrão anterior de "RC4" é considerado inseguro.

Expressões regulares (Perl-Compatible)

Ao passar sequências de escape inválidas, elas não são mais interpretadas como literais. Esse comportamento anteriormente exigia o modificador X – que agora é ignorado.

Objetos de dados do PHP

  • The default error handling mode has been changed from "silent" to "exceptions". See Errors and error handling for details.

  • As assinaturas de alguns métodos PDO foram alteradas:

    • 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 foi removido.

PDO MySQL

PDO::inTransaction() agora relata o estado real da transação da conexão, em vez de uma aproximação mantida pelo PDO. Se uma consulta que é sujeito para "confirmação implícita" é executado, PDO::inTransaction() posteriormente retornará false, pois uma transação não está mais ativa.

PostgreSQL

  • A sintaxe obsoleta pg_connect() usando vários parâmetros em vez de um cadeia de conexão não é mais suportada.

  • As assinaturas obsoletas pg_lo_import() e pg_lo_export() que passam a conexão como o último argumento não são mais suportadas. A conexão deve ser passada como primeiro argumento.

  • pg_fetch_all() agora retornará uma matriz vazia em vez de false para resultado conjuntos com zero linhas.

Phar

Os metadados associados a um phar não serão mais serializados automaticamente, para corrigir possíveis vulnerabilidades de segurança devido à instanciação de objetos, carregamento automático etc.

Reflection

  • As assinaturas do método

    • ReflectionClass::newInstance($args)
    • ReflectionFunction::invoke($args)
    • ReflectionMethod::invoke($object, $args)

    foram alterados para:

    • ReflectionClass::newInstance(...$args)
    • ReflectionFunction::invoke(...$args)
    • ReflectionMethod::invoke($object, ...$args)

    O código que deve ser compatível com PHP 7 e PHP 8 pode usar as seguintes assinaturas para serem compatíveis com ambas as versões:

    • ReflectionClass::newInstance($arg = null, ...$args)
    • ReflectionFunction::invoke($arg = null, ...$args)
    • ReflectionMethod::invoke($object, $arg = null, ...$args)

  • O método ReflectionType::__toString() agora retornará uma completa representação de depuração do tipo, e não está mais obsoleta. Em particular, o resultado incluirá um indicador de nulidade para tipos anuláveis. O formato do valor de retorno não é estável e pode mudar entre as versões do PHP.

  • Métodos export() de reflexão foram removidos. Em vez disso, os objetos de reflexão podem ser convertidos em string.

  • ReflectionMethod::isConstructor() e
ReflectionMethod::isDestructor() agora também retorna true por
__construct() e
__destruct() métodos de interfaces.
Anteriormente, isso só seria verdade para métodos de classes e traits.

  • O método ReflectionType::isBuiltin() foi movido para ReflectionNamedType. ReflectionUnionType não possui esse método.

Sockets

  • As constantes obsoletas AI_IDN_ALLOW_UNASSIGNED e AI_IDN_USE_STD3_ASCII_RULES flags para socket_addrinfo_lookup() foram removidas.

Biblioteca PHP padrão (SPL)

  • SplFileObject::fgetss() foi removido.

  • SplFileObject::seek() agora sempre posiciona no começo da linha. Anteriormente, posições >=1 resultavam no começo da linha seguinte.

  • SplHeap::compare() agora especifica uma assinatura de método. Herdando classes, implementar este método agora terá que usar uma assinatura de método compatível.

  • SplDoublyLinkedList::push(), SplDoublyLinkedList::unshift() e SplQueue::enqueue() agora retornam void no lugar de true.

  • spl_autoload_register() agora sempre lançará um TypeError em argumentos inválidos, portanto, o segundo argumento do_throw é ignorado e um aviso será emitido se for definido como false.

  • SplFixedArray agora é um IteratorAggregate e não um Iterator. SplFixedArray::rewind(), SplFixedArray::current(), SplFixedArray::key(), SplFixedArray::next() e SplFixedArray::valid() foram removidos. Em seu lugar, SplFixedArray::getIterator() foi adicionado. Qualquer código que usa explicitamente iteração sobre SplFixedArray agora deve obter um Iterator até SplFixedArray::getIterator(). Isso significa que SplFixedArray agora é seguro para uso em loops aninhados.

Biblioteca padrão

  • assert() não avaliará mais argumentos de string, em vez disso, eles serão tratados como qualquer outro argumento. assert($a == $b) deve ser usado em vez de assert('$a == $b'). O assert.quiet_eval diretiva ini e as constantes ASSERT_QUIET_EVAL também foram removidas, pois não seriam mais ter qualquer efeito.

  • parse_str() não pode mais ser usado sem especificar um array de resultados.

  • The string.strip_tags filter has been removed.

  • O argumento needle de strpos(), strrpos(), stripos(), strripos(), strstr(), strchr(), strrchr() e stristr() agora sempre será interpretado como uma string. Anteriormente agulhas não-string foram interpretadas como um ponto de código ASCII. Uma chamada explícita para chr() pode ser usado para restaurar o comportamento anterior.

  • O argumento needle para strpos(),
strrpos(), stripos(), strripos(),
strstr(), stristr() e strrchr() podem
agora estar vazios.

  • O argumento length para substr(), substr_count(), substr_compare() e iconv_substr() agora pode ser null. null os valores se comportarão como se não houvesse argumento de comprimento fornecido e, portanto, retornará o restante da string em vez de uma string vazia.

  • O argumento length para array_splice() agora pode ser null. null os valores se comportarão de forma idêntica à omissão do argumento, removendo assim tudo do offset até o final do array.

  • O argumento args de vsprintf(), vfprintf() e vprintf() agora devem ser um array. Anteriormente qualquer tipo era aceito.

  • A opção 'salt' de password_hash() não é mais suportado. Se a opção 'salt' for usada, um aviso será gerado, o salt é ignorado e um salt gerado é usado em seu lugar.

  • A função quotemeta() agora retornará uma string vazia se uma string vazia foi passada. Anteriormente false era devolvido.

  • As seguintes funções foram removidas.

    • hebrevc()
    • convert_cyr_string()
    • money_format()
    • ezmlm_hash()
    • restore_include_path()
    • get_magic_quotes_gpc()
    • get_magic_quotes_runtime()
    • fgetss()

  • FILTER_SANITIZE_MAGIC_QUOTES foi removida.

  • Chamar implode() com parâmetros na ordem inversa ($pieces, $glue) não é mais suportado.

  • parse_url() agora distinguirá consultas e fragmentos ausentes e vazios:

    • 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 = ""
    Anteriormente, todos os casos resultavam em consultas e fragmentos null.

  • var_dump() e debug_zval_dump() agora serão números de ponto flutuante usando serialize_precision em vez de precisão. Em uma configuração padrão, isto significa que os números de ponto flutuante agora são impressos com total precisão por essas funções depuradoras.

  • Se o array retornado por __sleep() contiver propriedades inexistentes, estas agora são silenciosamente ignoradas. Anteriormente, tais propriedades teriam sido serializadas como se tivessem o valor null.

  • A localidade padrão na inicialização agora é sempre "C". Nenhuma localidade é herdada do ambiente por padrão. Anteriormente, LC_ALL era definida como "C", enquanto LC_CTYPE era herdada do ambiente. No entanto, algumas funções não respeitavam a localidade herdada sem uma chamada explícita setlocale(). Uma chamada setlocale() explícita agora é sempre necessária se um componente de localidade deve ser alterado do padrão.

  • O fallback DES obsoleto em crypt() foi removido. Se um desconhecido formato salt for passado para crypt(), a função falhará com *0 em vez de voltar para um hash DES fraco agora.

  • A especificação de rodadas fora do intervalo para SHA256/SHA512 crypt() agora falhará com *0 em vez de fixar no limite mais próximo. Isso corresponde ao comportamento da glibc.

  • O resultado das funções de classificação pode ter mudado, se o array contiver elementos que comparam como igual.

  • Quaisquer funções que aceitam retornos de chamada que não são explicitamente especificados para aceitar parâmetros por referência agora avisará se um retorno de chamada com parâmetros de referência for usado. Exemplos incluem array_filter() e array_reduce(). Este já era o caso para a maioria, mas não para todas as funções anteriormente.

  • O wrapper de fluxo HTTP usado por funções como file_get_contents() agora anuncia HTTP/1.1 em vez de HTTP/1.0 por padrão. Isso não muda o comportamento do cliente, mas pode fazer com que os servidores respondam de forma diferente. Para manter o comportamento antigo, defina a opção de contexto de fluxo 'protocol_version', por exemplo

    <?php
    $ctx     = stream_context_create(['http' => ['protocol_version' => '1.0']]);
    echo     file_get_contents('http://example.org', false, $ctx);
    ?>

  • Chamar crypt() sem um salt explícito não é mais suportado. Se você gostaria de produzir um hash forte com salt gerado automaticamente, use password_hash() em vez disso.

  • substr(), mb_substr(), iconv_substr() e grapheme_substr() agora fixa consistentemente os deslocamentos fora dos limites à string fronteira. Anteriormente, false era retornado em vez da string vazia em alguns casos.

  • No Windows, as funções de execução do programa (proc_open(), exec(), popen() etc.) usando o shell, agora execute consistentemente %comspec% /s /c "$commandline", que tem o mesmo efeito que executar $commandline (sem aspas adicionais).

Sysvsem

  • O parâmetro auto_release de sem_get() foi alterado para aceitar valores booleanos em vez de int.

Tidy

  • O parâmetro use_include_path, que não era usado internamente, foi removido de tidy_repair_string().

  • tidy::repairString() e tidy::repairFile() se tornaram métodos estáticos.

Tokenizer

  • Tokens T_COMMENT não incluirão mais uma quebra de linha à direita. Em vez disso, a quebra de linha será parte de um token T_WHITESPACE seguinte. Deve-se notar que T_COMMENT nem sempre é seguido de espaço em branco, Ele também pode ser seguido de T_CLOSE_TAG ou o fim do arquivo (end-of-file).

  • Nomes com agora são representados usando os tokens T_NAME_QUALIFIED (Foo\Bar), T_NAME_FULLY_QUALIFIED (\Foo\Bar) e T_NAME_RELATIVE (namespace\Foo\Bar). T_NS_SEPARATOR é usado apenas para separadores de namespace independentes, e só é sintaticamente válido em conjuncão com declarações de uso de grupo.

XMLReader

XMLReader::open() e XMLReader::xml() agora são métodos estáticos. Eles ainda podem ser chamados como métodos de instância, mas classes herdadas precisam declará-los como estáticos se elas sobrescrevem esses métodos.

XML-RPC

A extensão XML-RPC foi movida para PECL e não é mais parte da distribuição PHP.

Zip

ZipArchive::OPSYS_Z_CPM foi removida (esse nome era um erro de digitação). Em vez dela, use ZipArchive::OPSYS_CPM.

Zlib

  • gzgetss() foi removida.

  • zlib.output_compression não é mais desabilitado automaticamente para o Content-Type: image/*.

Pacotes de teste para PHP no Windows

O executor de testes foi renomeado de run-test.php para run-tests.php, para coincidir com seu nome em 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.


Recursos depreciados

PHP Core

  • Se um parâmetro com um valor padrão é seguido por um parâmetro obrigatório, o valor padrão não tem efeito. Essa funcionalidade está depreciada a partir do PHP 8.0.0 e geralmente pode ser resolvido eliminando o valor padrão, sem mudança na funcionalidade:

    <?php
    function test($a = [], $b) {} // Antes
    function test($a, $b) {} // Depois
    ?>

    Uma exceção à esta regra são os parâmetros escritos de seguinte forma: Type $param = null, onde o valor padrão nulo torna o tipo implicitamente anulável. Este uso continua permitido, mas é recomendado o uso de um tipo anulável explícito:

    <?php
    function test(A $a = null, $b) {} // Ainda é permitido
    function test(?A $a, $b) {} // Recomendável
    ?>

  • Chamar a função get_defined_functions() com o parâmetro exclude_disabled definido explicitamente como false está depreciado e não tem mais efeito. A função get_defined_functions() nunca incluirá funções desabilitadas.

Enchant

  • enchant_broker_set_dict_path() e enchant_broker_get_dict_path() estão depreciadas, porque essa funcionalidade não está disponível no libenchant < 1.5 nem na libenchant-2.

  • enchant_dict_add_to_personal() está depreciada; use enchant_dict_add() em seu lugar.

  • enchant_dict_is_in_session() está depreciada; use enchant_dict_is_added() em seu lugar.

  • enchant_broker_free() e enchant_broker_free_dict() estão depreciadas; em vez disso destrua/unset o objeto.

  • As constantes ENCHANT_MYSPELL e ENCHANT_ISPELL estão depreciadas.

LibXML

A função libxml_disable_entity_loader() foi depreciada. Como a libxml 2.9.0 agora é obrigatória, o carregamento de entidade externa está desabilitado por padrão, e esta função não é mais necessária para a proteção contra ataques XXE, a não ser que a (ainda vulnerável). LIBXML_NOENT for utilizada. Nesse caso, é recomendado refazer o código utilizando libxml_set_external_entity_loader() para suprimir o carregamento de entidades externas.

PGSQL / PDO PGSQL

  • A constante PGSQL_LIBPQ_VERSION_STR agora tem o mesmo valor que PGSQL_LIBPQ_VERSION, portanto, está depreciada.

  • Os apelidos de função na extensão pgsql foram depreciados. Consulte a lista abaixo para saber quais funções devem ser usadas em seu lugar:

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

Biblioteca Padrão

  • Funções sort que retornam true ou false agora lançam um aviso de depreciação, e deve ser substituído por uma implementação que retorna um número inteiro menor, igual ou maior que zero.

    <?php
    // Substituir
    usort($array, fn($a, $b) => $a > $b);
    // Por
    usort($array, fn($a, $b) => $a <=> $b);
    ?>

Zip

  • Usar um arquivo vazio como ZipArchive está depreciado. A Libzip 1.6.0 não aceita mais arquivos vazios como arquivos zip válidos. A solução alternativa existente será removida na próxima versão.

  • A API procedural do Zip está depreciada. Use ZipArchive em seu lugar. A iteração em todas as entradas pode ser realizada usando ZipArchive::statIndex() e um laço for:

    <?php
    // iterar usando a API procedural
    assert(is_resource($zip));
    while (    $entry = zip_read($zip)) {
    echo     zip_entry_name($entry);
    }

    // iterar usando a API orientada a objetos
    assert($zip instanceof ZipArchive);
    for (    $i = 0; $entry = $zip->statIndex($i); $i++) {
    echo     $entry['name'];
    }
    ?>

Reflection

  • O método ReflectionFunction::isDisabled() está depreciado, pois não é mais possível criar uma classe ReflectionFunction para uma função desativada. Este método agora sempre retorna false.

  • ReflectionParameter::getClass(),
ReflectionParameter::isArray(), e
ReflectionParameter::isCallable() estão depreciados.
ReflectionParameter::getType() e
ReflectionType devem ser usados em seu lugar.

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


Outras mudanças

Alterações nos Módulos SAPI

Apache2Handler

O módulo PHP foi renomeado de php7_module para php_module.

Funções alteradas

Reflection

Os resultados de ReflectionClass::getConstants() e ReflectionClass::getReflectionConstants() agora podem ser filtrados por meio de um novo filter de parâmetro. Três novas constantes foram adicionadas para serem usadas com ele:

  • ReflectionClassConstant::IS_PUBLIC
  • ReflectionClassConstant::IS_PROTECTED
  • ReflectionClassConstant::IS_PRIVATE

Padrão

As funções matemáticas abs(), ceil(), floor() e round() agora atendem adequadamente à diretiva strict_types. Anteriormente, eles coagiam o primeiro argumento mesmo no modo de tipo estrito.

Zip

  • Os métodos ZipArchive::addGlob() e ZipArchive::addPattern() aceitam mais valores no argumento do array de options:

    • flags
    • comp_method
    • comp_flags
    • env_method
    • enc_password

  • Os métodos ZipArchive::addEmptyDir(), ZipArchive::addFile() e ZipArchive::addFromString() possuem um novo argumento flags. Isso permite gerenciar a codificação de nomes (ZipArchive::FL_ENC_*) e a substituição de entradas (ZipArchive::FL_OVERWRITE).

  • ZipArchive::extractTo() agora restaura o tempo de modificação do arquivo.

Outras alterações nas extensões

CURL

  • A extensão CURL agora requer pelo menos libcurl 7.29.0.

  • A version depreciada do parâmetro de curl_version() foi removida.

Date and Time

DatePeriod agora implementa IteratorAggregate (em vez de Traversable).

DOM

DOMNamedNodeMap e DOMNodeList agora implementam IteratorAggregate (em vez de Traversable).

Intl

IntlBreakIterator e ResourceBundle agora implementam IteratorAggregate (em vez de Traversable).

Enchant

A extensão enchant agora usa libenchant-2 por padrão quando disponível. libenchant versão 1 ainda é suportada, mas está obsoleta e pode ser removida no futuro.

GD

  • O parâmetro num_points de imagepolygon(), imageopenpolygon() e imagefilledpolygon() agora é opcional, ou seja, essas funções podem ser chamadas com 3 ou 4 argumentos. Se o argumento for omitido, será calculado como count($points)/2.

  • A função imagegetinterpolation() para obter o método de interpolação atual foi adicionada.

JSON

A extensão JSON não pode mais ser desativada e é sempre parte integrante de qualquer compilação do PHP, semelhante à extensão de data.

MBString

As tabelas de dados Unicode foram atualizadas para a versão 13.0.0.

PDO

PDOStatement agora implementa IteratorAggregate (em vez de Traversable).

LibXML

A versão mínima necessária do libxml agora é 2.9.0. Isso significa que o carregamento de entidade externa agora está desativado por padrão e nenhuma etapa extra precisa ser tomada para proteger contra ataques XXE.

MySQLi / PDO MySQL

  • Quando mysqlnd não é usado (que é a opção padrão e recomendada), a versão mínima suportada do libmysqlclient agora é 5.5.

  • mysqli_result agora implementa IteratorAggregate (ao invés de Traversable).

PGSQL / PDO PGSQL

As extensões PGSQL e PDO PGSQL agora requerem pelo menos libpq 9.1.

Readline

Chamar readline_completion_function() antes do início do prompt interativo (por exemplo, em auto_prepend_file) agora substituirá a função padrão de conclusão do prompt interativo. Anteriormente, readline_completion_function() só funcionava quando chamado após iniciar o prompt interativo.

SimpleXML

SimpleXMLElement agora implementa RecursiveIterator e absorveu a funcionalidade de SimpleXMLIterator. SimpleXMLIterator é uma extensão vazia de SimpleXMLElement.

Alterações na manipulação de arquivos INI

  • com.dotnet_version é uma nova diretiva INI para escolher a versão da estrutura .NET a ser usada para objetos dotnet.

  • zend.exception_string_param_max_len é uma nova diretiva INI para definir o comprimento máximo da string em um argumento de uma string de pilha stringificada.

EBCDIC

Os destinos EBCDIC não são mais suportados, embora seja improvável que ainda estivessem funcionando.

Desempenho

  • Um compilador Just-In-Time (JIT) foi adicionado à extensão opcache.

  • array_slice() em uma matriz sem lacunas não irá mais varrer toda a matriz para encontrar o deslocamento inicial. Isso pode reduzir significativamente o tempo de execução da função com grandes deslocamentos e pequenos comprimentos.

  • strtolower() agora usa uma implementação SIMD ao usar a localidade "C" LC_CTYPE (que é o padrão).

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


Migrando do PHP 7.3.x para o PHP 7.4.x

Índice

  • Novos Recursos
  • Novas Classes e Interfaces
  • Novas Funções
  • Novas Constantes Globais
  • Alterações incompatíveis com versões anteriores
  • Recursos depreciados
  • Extensões Removidas
  • Outras mudanças
  • Suporte do Windows

Esta nova versão menor traz vários novos recursos e algumas incompatibilidades que devem ser testadas antes da troca de versões do PHP em ambientes de produção.

Veja também os guias de migração das versões do PHP 7.0.x, 7.1.x, 7.2.x e 7.3.x.

User Contributed Notes

There are no user contributed notes for this page.


Novos Recursos

PHP Core

Propriedades tipadas

As propriedades de classe agora suportam declarações de tipo.

<?php
class User {
public int $id;
public string $name;
}
?>
O exemplo acima reforçará que $user->id pode ser atribuído apenas com valores int e $user->name somente com valores de string.

Arrow functions

Arrow functions fornecem uma sintaxe abreviada para definir funções com ligação implícita por valor de escopo.

<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
// $nums = array(10, 20, 30, 40);
?>

Covariância do tipo de retorno limitado e contravariância do tipo de argumento

O código a seguir agora funcionará:

<?php
class A {}
class B extends A {}

class Producer {
public function method(): A {}
}
class ChildProducer extends Producer {
public function method(): B {}
}
?>
O suporte completo à variação só está disponível se o carregamento automático for usado. Dentro de um único arquivo, apenas as referências de tipo não cíclico são possíveis, porque todas as classes precisam estar disponíveis antes de serem referenciadas.

Operador de atribuição de coalescência nula

<?php
$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
$array['key'] = computeDefault();
}
?>

Descompactando dentro de arrays

<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
?>

Separador literal numérico

Literais numéricos podem conter underscores entre dígitos.

<?php
6.674_083e-11; // float
299_792_458; // decimal
0xCAFE_F00D; // hexadecimal
0b0101_1111; // binary
?>

Referências fracas

Referências fracas permitem que o programador mantenha uma referência a um objeto que não impede que o objeto seja destruído.

Permitir exceções de __toString()

Lançar exceções de __toString() agora é permitido. Antes isto resultava um erro fatal. Os erros fatais recuperáveis ??existentes nas conversões de string foram convertidos em exceções de Error.

CURL

CURLFile agora suporta stream wrappers, além de nomes de arquivos simples, se a extensão tiver sido criada com relação à libcurl >= 7.56.0.

Filter

O filtro FILTER_VALIDATE_FLOAT agora suporta as opções min_range e max_range com a mesma semântica que FILTER_VALIDATE_INT.

FFI

FFI é uma nova extensão, que fornece uma maneira simples de chamar funções nativas, acessar variáveis ??nativas e criar/acessar estruturas de dados definidas nas bibliotecas C.

GD

Adicionado o filtro de imagem IMG_FILTER_SCATTER para aplicar um filtro de dispersão às imagens.

Hash

Adicionado o hash crc32c usando o polinômio de Castagnoli. Essa variante CRC32 é usada por sistemas de armazenamento, como iSCSI, SCTP, Btrfs e ext4.

Multibyte String

Adicionada a função mb_str_split(), que fornece a mesma funcionalidade que str_split(), mas operando em pontos de código em vez de bytes.

OPcache

Suporte para pré-carregamento de código foi adicionado.

Expressões Regulares (Perl-Compatible)

As funções preg_replace_callback() e preg_replace_callback_array() agora aceitam um argumento flags adicional, com suporte para as flags PREG_OFFSET_CAPTURE e PREG_UNMATCHED_AS_NULL. Isso influencia o formato do array de correspondências passado para a função de retorno da chamada.

PDO

O nome de usuário e a senha agora podem ser especificados como parte do PDO DSN para os drivers mysql, mssql, sybase, dblib, firebird e oci. Antes, isso era suportado apenas pelo driver pgsql. Se um nome de usuário/senha for especificado no construtor e no DSN, o construtor terá precedência.

Agora é possível escapar pontos de interrogação nas consultas SQL para evitar que elas sejam interpretadas como espaços reservados para parâmetros. Escrever ?? permite enviar um único ponto de interrogação para o banco de dados e por exemplo, usar o operador PostgreSQL JSON key exists (?).

PDO_OCI

PDOStatement::getColumnMeta() agora está disponível.

PDO_SQLite

PDOStatement::getAttribute(PDO::SQLITE_ATTR_READONLY_STATEMENT) permite verificar se a instrução é somente leitura, ou seja, se não modifica o banco de dados.

PDO::setAttribute(PDO::SQLITE_ATTR_EXTENDED_RESULT_CODES, true) permite o uso de códigos de resultado estendidos do SQLite3 em PDO::errorInfo() e PDOStatement::errorInfo().

SQLite3

Adicionado SQLite3::lastExtendedErrorCode() para buscar o último código de resultado estendido.

Adicionado SQLite3::enableExtendedResultCodes($enable = true), que fará SQLite3::lastErrorCode() retornar códigos de resultado estendidos.

Standard

strip_tags() com array de nomes de tags

strip_tags() agora também aceita um array de tags permitidas: em vez de strip_tags($str, '<a><p>') agora você pode escrever strip_tags($str, ['a', 'p']).

Serialização de objetos personalizados

Um novo mecanismo para serialização de objetos personalizados foi adicionado, que usa dois novos métodos mágicos: __serialize e __unserialize.

<?php
// Retorna um array contendo todo o estado necessário do objeto.
public function __serialize(): array;

// Restaura o estado do objeto a partir do array de dados fornecido.
public function __unserialize(array $data): void;
?>
O novo mecanismo de serialização substitui a interface Serializable, que será descontinuada no futuro.

Funções de mesclagem de array sem argumentos

array_merge() e array_merge_recursive() agora podem ser chamados sem nenhum argumento; nesse caso, eles retornarão um array vazio. Isso é útil em conjunto com o operador de espalhamento (spread operator), por exemplo, array_merge(...$arrays).

Função proc_open()

proc_open() agora aceita um array em vez de uma string para o comando. Nesse caso, o processo será aberto diretamente (sem passar por um shell) e o PHP cuidará de qualquer argumento necessário para escapar.

<?php
proc_open(['php', '-r', 'echo "Hello World\n";'], $descriptors, $pipes);
?>

proc_open() agora suporta redirect e descritores null.

<?php
// Like 2>&1 on the shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['redirect', 1]], $pipes);
// Like 2>/dev/null or 2>nul on the shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['null']], $pipes);
?>

argon2i(d) sem libargon

password_hash() agora possui as implementações argon2i e argon2id da extensão sodium quando o PHP é compilado sem 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.


Novas Classes e Interfaces

Reflection

  • ReflectionReference

User Contributed Notes

There are no user contributed notes for this page.


Novas Funções

PHP Core

  • get_mangled_object_vars()
  • password_algos()
  • sapi_windows_set_ctrl_handler()

GD

  • imagecreatefromtga()

Multibyte String

  • mb_str_split()

OpenSSL

  • openssl_x509_verify()

Process Control

  • pcntl_unshare()

SQLite3

  • SQLite3::backup()
  • SQLite3Stmt::getSQL()

User Contributed Notes

There are no user contributed notes for this page.


Novas Constantes Globais

PHP Core

  • PHP_WINDOWS_EVENT_CTRL_C
  • PHP_WINDOWS_EVENT_CTRL_BREAK

Multibyte String

  • MB_ONIGURUMA_VERSION

Sockets

Adicionadas as seguintes opções específicas para FreeBSD socket:

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


Alterações incompatíveis com versões anteriores

PHP Core

Acesso em estilo de array em não-array

Tentar usar valores do tipo null, bool, int, float ou resource como um array (como $null["key"]) agora irá gerar um aviso.

Função get_declared_classes()

A função get_declared_classes() não retorna mais classes anônimas que ainda não foram instanciadas.

Palavra-chave fn

fn agora é uma palavra-chave reservada. Em particular, ele não pode mais ser usado como um nome de função ou classe. Ela ainda pode ser usado como um nome constante de método ou classe.

A tag <?php no final do arquivo

<?php no final do arquivo (sem seguir a nova linha) agora será interpretado como uma tag PHP de abertura. Antes, era interpretada como uma short open tag seguida por um literal php e resultava em um erro de sintaxe (com short_open_tag=1) ou era interpretada como uma string literal <?php (com short_open_tag=0).

Stream wrappers

Ao usar include/require em uma stream, streamWrapper::stream_set_option() será chamado com a opção STREAM_OPTION_READ_BUFFER. As implementações personalizadas do wrapper de fluxo podem precisar implementar o método streamWrapper::stream_set_option() para evitar um aviso (sempre retornando false é uma implementação suficiente).

Serialização

O formato o de serialização foi removido. Como nunca é produzido pelo PHP, isso pode apenas interromper a desserialização de strings criadas manualmente.

Constantes do algoritmo de senha

Os identificadores do algoritmo de hash de senha agora são sequências anuláveis ??em vez de números inteiros.

  • PASSWORD_DEFAULT era um int 1; agora é uma string '2y' (no PHP 7.4.0, 7.4.1 e 7.4.2 era null)
  • PASSWORD_BCRYPT era um int 1; agora é uma string '2y'
  • PASSWORD_ARGON2I era um int 2; agora é uma string 'argon2i'
  • PASSWORD_ARGON2ID era um int 3; agora é uma string 'argon2id'

Aplicações que usam corretamente as constantes PASSWORD_DEFAULT, PASSWORD_BCRYPT, PASSWORD_ARGON2I e PASSWORD_ARGON2ID continuarão funcionando corretamente.

Função htmlentities()

htmlentities() agora emitirá um aviso (em vez de um aviso estrito sobre os padrões) se for usado com uma codificação para a qual apenas a substituição básica de entidade é suportada; nesse caso, é equivalente ahtmlspecialchars().

Funções fread() e fwrite()

fread() e fwrite() agora retornarão false se a operação falhar. Antes uma string vazia ou 0 era retornado. EAGAIN/EWOULDBLOCK não são considerados falhas.

Essas funções agora também emitem um aviso de falha, como ao tentar gravar em um recurso de arquivo somente leitura.

Funções matemáticas de precisão arbitrária BCMath

As funções BCMath agora avisam se um número não bem formado é passado, como "32foo". O argumento será interpretado como zero, como antes.

CURL

Tentar serializar uma classe CURLFile agora irá gerar uma exceção. Antes, a exceção era lançada apenas na desserialização.

O uso de CURLPIPE_HTTP1 está depreciado, e não é mais suportado a partir do cURL 7.62.0.

O parâmetro $version de curl_version() está depreciado. Se qualquer valor diferente do padrão CURLVERSION_NOW for passado, um aviso será gerado e o parâmetro será ignorado.

Data e hora

Chamar a função var_dump() ou similar em uma instância de DateTime ou DateTimeImmutable não deixará mais propriedades acessíveis no objeto.

A comparação de objetos DateInterval (usando ==, <, e assim por diante) agora gera um aviso e sempre retorna false. Antes todos os objetos DateInterval eram considerados iguais, a menos que tivessem propriedades.

Intl

O valor padrão do parâmetro das funções idn_to_ascii() e idn_to_utf8() agora é INTL_IDNA_VARIANT_UTS46 em vez de INTL_IDNA_VARIANT_2003 depreciado.

MySQLi

A funcionalidade do servidor incorporado foi removida. Foi quebrado desde pelo menos o PHP 7.0.

A propriedade não documentada mysqli::$stat foi removida em favor de mysqli::stat().

OpenSSL

A função openssl_random_pseudo_bytes() agora lançará uma exceção em situações de erro, semelhante a random_bytes(). Em particular, um Error será lançado se o número de bytes solicitados for menor ou igual a zero, e uma Exception será lançada se não for possível reunir aleatoriedade suficiente. O argumento $crypto_strong output é garantido para sempre ser true se a função não for lançada, portanto, verificar explicitamente não é necessário.

Expressões regulares (Perl-Compatible)

Quando o modo PREG_UNMATCHED_AS_NULL é usado, os grupos de captura sem correspondência à direita agora também serão definidos como null (ou [null, -1] se a captura offset estiver ativada). Isso significa que o tamanho de $matches sempre será o mesmo.

Objetos de dados PHP

A tentativa de serializar uma instância PDO ou PDOStatement agora gerará uma Exception em vez de uma PDOException, consistente com outras classes internas que não oferecem suporte à serialização.

Reflection

Os objetos reflexion agora gerarão uma exceção se for feita uma tentativa de serializá-los. A serialização de objetos reflexion nunca foi suportada e resultou em objetos reflexions corrompidos. Foi explicitamente proibido agora.

Os valores para as constantes das classes ReflectionClassConstant, ReflectionMethod e ReflectionProperty mudaram.

Standard PHP Library (SPL)

Chamar get_object_vars() em uma instância de ArrayObject agora sempre retornará as propriedades do próprio ArrayObject (ou de uma sub classe). Antes, ele retornava os valores do array/object a menos que a flag ArrayObject::STD_PROP_LIST fosse especificado.

Outras operações afetadas são:

  • ReflectionObject::getProperties()
  • reset(), current(), etc. Use os métodos de Iterator em seu lugar.
  • Potencialmente outros trabalhando nas propriedades do objeto como uma lista, por exemplo array_walk().

(array) casts não são afetadas. Eles continuarão retornando o array agrupado, ou as propriedades ArrayObject dependendo se a flag ArrayObject::STD_PROP_LIST é usada.

SplPriorityQueue::setExtractFlags() lançará uma exceção se zero for passado. Antes, isso geraria um erro fatal recuperável na próxima operação de extração.

ArrayObject, ArrayIterator, SplDoublyLinkedList e SplObjectStorage agora oferecem suporte ao mecanismo __serialize() e __unserialize() além da interface Serializable. Isso significa que as payloads de serialização criadas em versões mais antigas do PHP ainda podem ser desserializadas, mas as novas payloads criadas pelo PHP 7.4 não serão entendidas pelas versões mais antigas.

Tokenizer

token_get_all() agora emitirá um token T_BAD_CHARACTER para caracteres inesperados em vez de deixar para trás buracos no fluxo de token.

Incoming Cookies

A partir do PHP 7.4.11, os nomes dos cookies recebidos não são mais decodificados em url por razões de segurança.

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


Recursos depreciados

PHP Core

Operadores ternários aninhados sem parênteses explícitos

Operações ternárias aninhadas devem usar explicitamente parênteses para ditar a ordem das operações. Anteriormente, quando usada sem parênteses, a associatividade esquerda não resultava no comportamento esperado na maioria dos casos.

<?php
1 ? 2 : 3 ? 4 : 5; // depreciado
(1 ? 2 : 3) ? 4 : 5; // ok
1 ? 2 : (3 ? 4 : 5); // ok
?>

Parenteses não são necessários quando organizando um operando interno, pois não gera ambiguidade ou problemas de associatividade:

1 ? 2 ? 3 : 4 : 5 // ok

Acesso a valores de array e string usando chaves

O acesso a valor de string e array usando a sintaxe de chaves está depreciado. Use $var[$idx] ao invés de $var{$idx}.

A conversão (real) e a função is_real()

A conversão (real) está depreciada, use (float) em seu lugar.

A função is_real() também está depreciada, use is_float() em seu lugar.

Desvinculando $this quando $this é usado

Desvincular $this de uma closure não estática que usa $this está depreciado.

A palavra chave parent sem uma classe parent

Usar a palavra chave parent dentro de uma classe sem parent está depreciado, e lançará um erro em tempo de compilação no futuro. Atualmente um erro será gerado apenas se/quando o parent for acessado em tempo de execução.

A diretiva INI allow_url_include

A diretiva allow_url_include está depreciada. Ativá-la gerará um aviso de depreciação na inicialização.

Caracteres inválidos nas funções de conversão de base

Passar caracteres inválidos para as funções: base_convert(), bindec(), octdec() and hexdec()agora gerará um aviso de depreciação. O resultado ainda será calculado como se os caracteres inválidos não existissem. Os espaços em branco à esquerda e à direita, bem como os prefixos do tipo 0x (dependendo da base) continuam sendo permitidos.

Usando array_key_exists() em objetos

O uso de array_key_exists() em objetos está depreciado. Em vez disso isset() ou property_exists() deve ser usado.

Funções magic quotes

As funções get_magic_quotes_gpc() e get_magic_quotes_runtime() estão depreciadas. Elas sempre retornam false.

Função hebrevc()

A função hebrevc() está depreciada. Ela pode ser substituída por nl2br(hebrev($str)) ou, preferencialmente, pelo uso do suporte Unicode RTL.

Função convert_cyr_string()

A função convert_cyr_string() está depreciada. Pode ser substituída por um dos mb_convert_string(), iconv() ou UConverter.

Função money_format()

A função money_format() está depreciada. Ela pode ser substituída pela funcionalidade intl NumberFormatter.

Função ezmlm_hash()

A função ezmlm_hash() está depreciada.

Função restore_include_path()

A função restore_include_path() está depreciada. Pode ser sbstituída por ini_restore('include_path').

Implode com a ordem histórica dos parâmetros

A passagem de parâmetros para a função implode() na ordem reversa está depreciada, use implode($glue, $parts) em vez de implode($parts, $glue).

COM

A importação de bibliotecas de tipos com registro constante que não diferencia maiúsculas de minúsculas foi depreciado.

Filter

FILTER_SANITIZE_MAGIC_QUOTES está depreciado, use FILTER_SANITIZE_ADD_SLASHES em seu lugar.

Multibyte String

A passagem de um padrão não-string para a função mb_ereg_replace() está depreciado. Atualmente, os padrões não-string são interpretados como pontos de código ASCII. No PHP 8, o padrão será interpretado como uma string.

Passar a codificação como terceiro parâmetro para a função mb_strrpos() está depreciado. Em vez disso, passe um offset 0 e a codificação como quarto parâmetro.

Lightweight Directory Access Protocol

ldap_control_paged_result_response() e ldap_control_paged_result() estão depreciados. Os controles de paginação podem ser enviados junto com a função ldap_search().

Reflection

As chamadas para ReflectionType::__toString() agora geram, um aviso de depreciação. Este método foi depreciado em favor de ReflectionNamedType::getName() na documentação a partir do PHP 7.1, mas não emitiu um aviso de depreciação por motivos técnicos.

Os métodos export() em todas as classes Reflection foram depreciados. Construa um objeto Reflection e converta-o em string em seu 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

AI_IDN_ALLOW_UNASSIGNED e AI_IDN_USE_STD3_ASCII_RULES para socket_addrinfo_lookup() foram depreciadas, devido a uma depreciação upstream na 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


Extensões Removidas

Essas extensões foram movidas para o PECL e não fazem mais parte da distribuição do PHP As versões de pacotes PECL dessas extensões serão criadas de acordo com a demanda do usuário

  • Firebird/Interbase - o acesso a um banco de dados baseado em InterBase e/ou Firebird ainda está disponível com o driver PDO Firebird.
  • Recode
  • WDDX

User Contributed Notes

There are no user contributed notes for this page.


Outras mudanças

Melhorias de desempenho

PHP Core

Um opcode VM especializado para a função array_key_exists() foi adicionado, o que melhora o desempenho desta função se ela puder ser resolvida estaticamente. No código com namespace, pode ser necessário escrever \array_key_exists() ou importar explicitamente a função.

Expressões regulares (Compatível com Perl)

Quando preg_match() no modo UTF-8 (modificador "u") é chamado repetidamente na mesma string (mas possivelmente deslocamentos diferentes), ele só será verificado para a validade UTF-8 uma vez.

Alterações na manipulação de arquivos INI

zend.exception_ignore_args é uma nova diretiva INI para incluir ou excluir argumentos de rastreamentos de pilha gerados a partir de exceções.

opcache.preload_user é uma nova diretiva INI para especificar a conta de usuário sob a qual o código de pré-carregamento é executado se, de outra forma, for executado como root (o que não é permitido por motivos de segurança).

Migração para pkg-config

Várias extensões foram migradas para usar exclusivamente pkg-config para a detecção de dependências de biblioteca. Geralmente, isso significa que, em vez de usar --with-foo-dir=DIR ou similar, apenas --with-foo é usado. Os caminhos de biblioteca personalizados podem ser especificados adicionando diretórios adicionais a PKG_CONFIG_PATH ou especificando explicitamente as opções de compilação por meio de FOO_CFLAGS e FOO_LIBS.

As seguintes extensões e SAPIs são afetadas:

  • CURL:
    • --with-curl não aceita mais um diretório.
  • Enchant:
    • --with-enchant não aceita mais um diretório.
  • FPM:
    • --with-fpm-systemd agora usa apenas pkg-config para verificações do libsystem. A versão mínima exigida do libsystemd é 209.
  • GD:
    • --with-gd torna-se --enable-gd (se para habilitar a extensão) e --with-external-gd (para optar por usar um libgd externo, em vez do empacotado).
    • --with-png-dir foi removido. libpng é obrigatório.
    • --with-zlib-dir foi removido. zlib é necessário.
    • --with-freetype-dir torna-se --with-freetype
    • --with-jpeg-dir torna-se --with-jpeg
    • --with-webp-dir torna-se --with-webp
    • --with-xpm-dir torna-se --with-xpm
  • IMAP:
    • --with-kerberos-systemd não aceita mais um diretório.
  • Intl:
    • --with-icu-dir foi removido. Se --enable-intl é passado, então libicu é sempre necessário.
  • LDAP:
    • --with-ldap-sasl não aceita mais um diretório.
  • Libxml:
    • --with-libxml-dir foi removido.
    • --enable-libxml torna-se --with-libxml.
    • --with-libexpat-dir foi renomeado para --with-expat e não aceita mais um diretório.
  • Litespeed:
    • --with-litespeed torna-se --enable-litespeed.
  • Mbstring:
    • --with-onig foi removido. A menos que --disable-mbregex foi passado, libonig é necessário.
  • ODBC:
    • --with-iodbc não aceita mais um diretório.
    • --with-unixODBC sem um diretório agora usa pkg-config (preferencial). O diretório ainda é aceito para versões antigas sem libodbc.pc.
  • OpenSSL:
    • --with-openssl não aceita mais um diretório.
  • PCRE:
    • --with-pcre-regex foi removido. Em vez disso, --with-external-pcre é fornecido para optar por usar uma biblioteca PCRE externa, em vez do pacote.
  • PDO_SQLite:
    • --with-pdo-sqlite não aceita mais um diretório.
  • Readline:
    • --with-libedit não aceita mais um diretório.
  • Sodium:
    • --with-sodium não aceita mais um diretório.
  • SQLite3:
    • --with-sqlite3 não aceita mais um diretório.
  • XSL:
    • --with-xsl não aceita mais um diretório.
  • Zip:
    • --with-libzip foi removido.
    • --enable-zip torna-se --with-zip.

CSV escaping

fputcsv(),
fgetcsv(),
SplFileObject::fputcsv(),
SplFileObject::fgetcsv(), e
SplFileObject::setCsvControl()
agora aceitam uma string vazia como argumento $escape,
que desativa o mecanismo de escape proprietário do PHP.

O comportamento de str_getcsv() foi ajustado adequadamente (anteriormente, uma string vazia era idêntica a usar o padrão).

SplFileObject::getCsvControl() agora também pode retornar uma string vazia para o terceiro elemento do array, adequadamente.

Filtragem de Dados

A extensão filter não expõe mais --with-pcre-dir para compilações Unix e agora pode ser construída de forma confiável como compartilhada ao usar ./configure

GD

O comportamento de imagecropauto() no pacote libgd foi sincronizado com o do sistema libgd:

  • IMG_CROP_DEFAULT não está mais voltando para IMG_CROP_SIDES
  • Threshold-cropping agora usa o algoritmo do sistema libgd

O parâmetro $mode padrão de ] imagecropauto() foi alterado para IMG_CROP_DEFAULT; passar -1 agora está depreciado.

imagescale() agora oferece suporte à proporção preservando a escala para uma altura fixa passando -1 como $new_width.

HASH Message Digest Framework

A extensão hash não pode mais ser desativada e é sempre parte integrante de qualquer compilação do PHP, semelhante à extensão date.

Intl

A extensão intl agora requer pelo menos ICU 50.1.

ResourceBundle agora implementa Countable.

Lightweight Directory Access Protocol

O suporte para nsldap e umich_ldap foi removido.

Libxml

Todas as extensões baseadas em libxml agora requerem libxml 2.7.6 ou mais recente.

Multibyte String

A biblioteca oniguruma não é mais empacotada com o PHP, em vez disso libonig precisa estar disponível no sistema. Alternativamente, --disable-mbregex pode ser usado para desabilitar o componente mbregex.

OPcache

As opções de configuração --disable-opcache-file e --enable-opcache-file foram removidas em favor da diretiva INI opcache.file_cache.

Password Hashing

As funções password_hash() e password_needs_rehash() agora aceitam string anulável e int para o argumento $algo.

PEAR

A instalação do PEAR (incluindo PECL) não é mais habilitada por padrão. Ele pode ser ativado explicitamente usando --with-pear. Esta opção está depreciada e pode ser removida no futuro.

Reflection

Os valores numéricos das constantes do modificador (IS_ABSTRACT, IS_DEPRECATED, IS_EXPLICIT_ABSTRACT, IS_FINAL, IS_IMPLICIT_ABSTRACT, IS_PRIVATE, IS_PROTECTED, IS_PUBLIC, e IS_STATIC) nas classes ReflectionClass, ReflectionFunction, ReflectionMethod, ReflectionObject, e ReflectionProperty foram alterados.

SimpleXML

SimpleXMLElement agora implementa Countable.

SQLite3

O pacote libsqlite foi removido. Para construir a extensão SQLite3, um sistema libsqlite3 = 3.7.4 agora é necessário. Para construir a extensão PDO_SQLite, um sistema libsqlite3 = 3.5.0 agora é necessário.

A serialização e desserialização de SQLite3, SQLite3Stmt e SQLite3Result agora são explicitamente proibidas. Anteriormente, a serialização de instâncias dessas classes era possível, mas a desserialização produzia objetos inutilizáveis.

A notação @param agora também pode ser usada para denotar parâmetros de consulta SQL.

Zip

A biblioteca libzip empacotada foi removida. Um sistema libzip >= 0.11 agora é necessário para construir a extensão zip.

User Contributed Notes

santi at mola dot io 31-Jul-2020 07:54
Note for internals/extensions:

Many opcode values changed between PHP 7.3 and 7.4, so most documentation resources are outdated in that regard. You can look the definitions at Zend/zend_vm_opcodes.h in php-src. For example, ZEND_ECHO changes from 40 to 136.

While opcode changes happen in a lot of PHP versions, the change in 7.4 is quite significant.
ohcc at 163 dot com 09-Jun-2020 04:56
As of PHP 7.4, an exception thrown within the user-defined shutdown function can be caught by the user-defined exception handler.

<?php
    set_error_handler(
        function($level, $error, $file, $line){
            if(0 === error_reporting()){
                return false;
            }
            throw new ErrorException($error, -1, $level, $file, $line);
        },
        E_ALL
    );

    register_shutdown_function(function(){
        $error = error_get_last();
        if($error){
            throw new ErrorException($error['message'], -1, $error['type'], $error['file'], $error['line']);
        }
    });

    set_exception_handler(function($exception){
        // ... more code ...
    });

    require 'NotExists.php';
Florent H (Sowapps) 16-Feb-2020 07:37
This version brings an important changes with the directive zend.exception_ignore_args set to On by default.
In all stack traces, the args key is now missing.
All php frameworks have to handle this to report errors & exceptions.


Suporte do Windows

configure flags

configure agora considera CFLAGS e LDFLAGS adicionais definidos como variáveis de ambiente.

CTRL handling

CTRL+C e CTRL+BREAK no console podem ser capturados definindo uma função de manipulador com sapi_windows_set_ctrl_handler().

proc_open() no Windows pode receber uma opção "create_process_group". É necessário se o processo filho deve lidar com eventos CTRL.

OPcache

O OPcache agora suporta um número arbitrário de caches separados por usuário por meio da diretiva INI opcache.cache_id. Todos os processos com o mesmo ID de cache e usuário compartilham uma instância do OPcache.

stat

A implementação stat foi refatorada.

  • Um número de inode é entregue e é baseado no índice de arquivo NTFS.
  • O número do dispositivo agora é baseado no número de série do volume.

Observe que ambos os valores são derivados do sistema e fornecidos como estão em sistemas de 64 bits. Em sistemas de 32 bits, esses valores podem ultrapassar o número inteiro de 32 bits no PHP, portanto, são falsos.

libsqlite3

libsqlite3 não é mais compilado estaticamente em php_sqlite3.dll e php_pdo_sqlite.dll, mas sim disponível como libsqlite3.dll. Consulte as instruções de instalação para SQLite3 e PDO_SQLITE, respectivamente.

User Contributed Notes

There are no user contributed notes for this page.


Migrando do PHP 7.2.x para o PHP 7.3.x

Índice

  • Novas Funcionalidades
  • Novas Funções
  • Novas Constantes Globais
  • Alterações incompatíveis com versões anteriores
  • Recursos depreciados
  • Outras mudanças
  • Suporte do Windows

Esta nova versão menor traz vários novos recursos e algumas incompatibilidades que devem ser testadas antes da troca de versões do PHP em ambientes de produção.

Veja também os guias de migração das versões do PHP 7.0.x, 7.1.x e 7.2.x.

User Contributed Notes

There are no user contributed notes for this page.


Novas Funcionalidades

PHP Core

Sintaxe Heredoc e Nowdoc mais flexível

O marcador de fechamento para strings doc não precisa mais ser seguido por ponto-e-vírgula ou nova linha. Além disso, o marcador de fechamento pode ser recuado, caso em que o recuo será retirado de todas as linhas na string do documento.

A desestruturação de matriz suporta atribuições de referência

A desestruturação de matriz agora suporta atribuições de referência usando a sintaxe [&$a, [$b, &$c]] = $d O mesmo também é suportado para list().

O operador Instanceof aceita Literais

instanceof agora permite literais como o primeiro operando, caso em que o resultado é sempre false.

Exceção CompileError em vez de alguns Erros de Compilação

Uma nova exceção CompileError foi adicionada, da qual ParseError herda. Um pequeno número de erros de compilação agora lançará um CompileError em vez de gerar um fatal error. Atualmente, isso afeta apenas erros de compilação que podem ser lançados por token_get_all() no modo TOKEN_PARSE, mas mais erros podem ser convertidos no futuro.

Vírgulas à direita são permitidas em chamadas

Agora são permitidas vírgulas à direita em chamadas de função e método.

Suporte Argon2id

O argumento de configuração --with-password-argon2[=dir] agora fornece suporte para os hashes Argon2i e Argon2id nas funções password_hash(), password_verify(), password_get_info() e password_needs_rehash(). As senhas podem ser hash e verificadas usando a constante PASSWORD_ARGON2ID. O suporte para Argon2i e Argon2id nas funções password_*() agora requer que o PHP seja vinculado à biblioteca de referência libargon2 = 20161029.

FastCGI Process Manager

Novas opções foram adicionadas para personalizar o log do FPM:

log_limit
Esta opção global pode ser usada para definir o limite de log para a linha registrada, o que permite registrar mensagens com mais de 1024 caracteres sem quebrar. Ele também corrige vários problemas de empacotamento.
log_buffering
Esta opção global permite um registro experimental sem buffer extra.
decorate_workers_output
Esta opção de pool permite desativar a decoração de saída para a saída dos workers quando catch_workers_output estiver ativado.

Funções BC Math

bcscale() agora também pode ser usado como getter para recuperar a escala atual em uso.

Lightweight Directory Access Protocol

Suporte completo para controles LDAP foi adicionado às funções de consulta LDAP e ldap_parse_result():

  • Um parâmetro $serverctrls para enviar controles para
o servidor em ldap_add(),
ldap_mod_replace(), ldap_mod_add(),
ldap_mod_del(), ldap_rename(),
ldap_compare(), ldap_delete(),
ldap_modify_batch(),
ldap_search(), ldap_list() e
ldap_read() foi adicionado.
  • O parâmetro de saída $serverctrls para obter controles do servidor em ldap_parse_result() foi adicionado.
  • Suporte para LDAP_OPT_SERVER_CONTROLS e LDAP_OPT_CLIENT_CONTROLS em ldap_get_option() e ldap_set_option() foi corrigido.

Functions Multibyte String

Suporte completo para Case-Mapping e Case-Folding

Foi adicionado suporte para mapeamento completo de case-mapping e case-folding. Ao contrário do case-mapping simples, o case-mapping completo pode alterar o comprimento da string. Por exemplo:

<?php
mb_strtoupper("Straße");
// Produces STRAßE on PHP 7.2
// Produces STRASSE on PHP 7.3
?>
Os diferentes modos de mapeamento e folding modes estão disponíveis atravé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 (usado por operações Case-Insensitive)
Somente o mapeamento de caso completo incondicional e agnóstico de idioma é executado.

As operações de string Case-Insensitive usam Case-Folding

As operações de string que não diferenciam maiúsculas de minúsculas agora usam case-folding em vez de case- mapping durante as comparações. Isso significa que mais caracteres serão considerados (sem distinção entre maiúsculas e minúsculas) iguais agora.

MB_CASE_TITLE executa conversão de Title-Case

mb_convert_case() com MB_CASE_TITLE agora executa conversão de maiúsculas e minúsculas com base nas propriedades Unicode derivadas de Cased e CaseIgnorable. Em particular, isso também melhora o tratamento de aspas e apóstrofos.

Support Unicode 11

As tabelas de dados Multibyte String foram atualizadas para Unicode 11.

Suporte Long String

As funções Multibyte String Functions agora suportam corretamente strings maiores que 2 GB.

Melhorias de desempenho

O desempenho da extensão Multibyte String foi significativamente melhorado em todos os aspectos. As maiores melhorias estão nas funções de conversão de caso.

Suporte a Capturas Nomeadas

As funções mb_ereg_* agora suportam capturas nomeadas. Funções de correspondência como mb_ereg() agora retornarão capturas nomeadas usando o número do grupo e o nome, semelhante ao PCRE:

<?php
mb_ereg('(?<word>\w+)', '?', $matches);
// => [0 => "?", 1 => "?", "word" => "?"];
?>
Além disso, mb_ereg_replace() agora suporta as notações \k<> and \k'' para fazer referência a capturas nomeadas na string de substituição:
<?php
mb_ereg_replace('\s*(?<word>\w+)\s*', "_\k<word>_\k'word'_", ' foo ');
// => "_foo_foo_"
?>
\k<> and \k'' também podem ser usados para referências numeradas, que também funcionam com números de grupos maiores que 9.

Readline

O suporte para as opções completion_append_character e completion_suppress_append foi adicionado a readline_info(). Essas opções só estão disponíveis se o PHP estiver vinculado a libreadline (ao invés de 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

?>


Novas Funções

PHP Core

  • array_key_first()
  • array_key_last()
  • gc_status()
  • hrtime()
  • is_countable()
  • net_get_interfaces()

FastCGI Process Manager

  • fpm_get_status()

Data e hora

  • DateTime::createFromImmutable()

GNU Multiple Precision

  • gmp_binomial()
  • gmp_kronecker()
  • gmp_lcm()
  • gmp_perfect_power()

Funções de Internacionalização

  • Normalizer::getRawDecomposition()
  • normalizer_get_raw_decomposition()
  • Spoofchecker::setRestrictionLevel()

Lightweight Directory Access Protocol

  • ldap_add_ext()
  • ldap_bind_ext()
  • ldap_delete_ext()
  • ldap_exop_refresh()
  • ldap_mod_add_ext()
  • ldap_mod_replace_ext()
  • ldap_mod_del_ext()
  • ldap_rename_ext()

OpenSSL

  • openssl_pkey_derive()

Sockets

  • socket_wsaprotocol_info_export()
  • socket_wsaprotocol_info_import()
  • socket_wsaprotocol_info_release()

User Contributed Notes

There are no user contributed notes for this page.


Novas Constantes Globais

PHP Core

  • PASSWORD_ARGON2ID

Client URL Library

  • CURLAUTH_BEARER
  • CURLAUTH_GSSAPI
  • CURLE_WEIRD_SERVER_REPLY
  • CURLINFO_APPCONNECT_TIME_T
  • CURLINFO_CONNECT_TIME_T
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD_T
  • CURLINFO_CONTENT_LENGTH_UPLOAD_T
  • CURLINFO_FILETIME_T
  • CURLINFO_HTTP_VERSION
  • CURLINFO_NAMELOOKUP_TIME_T
  • CURLINFO_PRETRANSFER_TIME_T
  • CURLINFO_PROTOCOL
  • CURLINFO_PROXY_SSL_VERIFYRESULT
  • CURLINFO_REDIRECT_TIME_T
  • CURLINFO_SCHEME
  • CURLINFO_SIZE_DOWNLOAD_T
  • CURLINFO_SIZE_UPLOAD_T
  • CURLINFO_SPEED_DOWNLOAD_T
  • CURLINFO_SPEED_UPLOAD_T
  • CURLINFO_STARTTRANSFER_TIME_T
  • CURLINFO_TOTAL_TIME_T
  • CURL_LOCK_DATA_CONNECT
  • CURL_LOCK_DATA_PSL
  • CURL_MAX_READ_SIZE
  • CURLOPT_ABSTRACT_UNIX_SOCKET
  • CURLOPT_DISALLOW_USERNAME_IN_URL
  • CURLOPT_DNS_SHUFFLE_ADDRESSES
  • CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS
  • CURLOPT_HAPROXYPROTOCOL
  • CURLOPT_KEEP_SENDING_ON_ERROR
  • CURLOPT_PRE_PROXY
  • CURLOPT_PROXY_CAINFO
  • CURLOPT_PROXY_CAPATH
  • CURLOPT_PROXY_CRLFILE
  • CURLOPT_PROXY_KEYPASSWD
  • CURLOPT_PROXY_PINNEDPUBLICKEY
  • CURLOPT_PROXY_SSLCERT
  • CURLOPT_PROXY_SSLCERTTYPE
  • CURLOPT_PROXY_SSL_CIPHER_LIST
  • CURLOPT_PROXY_SSLKEY
  • CURLOPT_PROXY_SSLKEYTYPE
  • CURLOPT_PROXY_SSL_OPTIONS
  • CURLOPT_PROXY_SSL_VERIFYHOST
  • CURLOPT_PROXY_SSL_VERIFYPEER
  • CURLOPT_PROXY_SSLVERSION
  • CURLOPT_PROXY_TLS13_CIPHERS
  • CURLOPT_PROXY_TLSAUTH_PASSWORD
  • CURLOPT_PROXY_TLSAUTH_TYPE
  • CURLOPT_PROXY_TLSAUTH_USERNAME
  • CURLOPT_REQUEST_TARGET
  • CURLOPT_SOCKS5_AUTH
  • CURLOPT_SSH_COMPRESSION
  • CURLOPT_SUPPRESS_CONNECT_HEADERS
  • CURLOPT_TIMEVALUE_LARGE
  • CURLOPT_TLS13_CIPHERS
  • CURLPROXY_HTTPS
  • CURLSSH_AUTH_GSSAPI
  • CURL_SSLVERSION_MAX_DEFAULT
  • CURL_SSLVERSION_MAX_NONE
  • CURL_SSLVERSION_MAX_TLSv1_0
  • CURL_SSLVERSION_MAX_TLSv1_1
  • CURL_SSLVERSION_MAX_TLSv1_2
  • CURL_SSLVERSION_MAX_TLSv1_3
  • CURL_SSLVERSION_TLSv1_3
  • CURL_VERSION_ALTSVC (as of PHP 7.3.6)
  • CURL_VERSION_ASYNCHDNS
  • CURL_VERSION_BROTLI
  • CURL_VERSION_CONV
  • CURL_VERSION_CURLDEBUG (a partir do 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 (a partir do PHP 7.3.6)
  • CURL_VERSION_SPNEGO
  • CURL_VERSION_SSPI
  • CURL_VERSION_TLSAUTH_SRP

Filtragem de Dados

  • FILTER_SANITIZE_ADD_SLASHES

JSON

  • JSON_THROW_ON_ERROR

Lightweight Directory Access Protocol

  • LDAP_CONTROL_ASSERT
  • LDAP_CONTROL_MANAGEDSAIT
  • LDAP_CONTROL_PROXY_AUTHZ
  • LDAP_CONTROL_SUBENTRIES
  • LDAP_CONTROL_VALUESRETURNFILTER
  • LDAP_CONTROL_PRE_READ
  • LDAP_CONTROL_POST_READ
  • LDAP_CONTROL_SORTREQUEST
  • LDAP_CONTROL_SORTRESPONSE
  • LDAP_CONTROL_PAGEDRESULTS
  • LDAP_CONTROL_AUTHZID_REQUEST
  • LDAP_CONTROL_AUTHZID_RESPONSE
  • LDAP_CONTROL_SYNC
  • LDAP_CONTROL_SYNC_STATE
  • LDAP_CONTROL_SYNC_DONE
  • LDAP_CONTROL_DONTUSECOPY
  • LDAP_CONTROL_PASSWORDPOLICYREQUEST
  • LDAP_CONTROL_PASSWORDPOLICYRESPONSE
  • LDAP_CONTROL_X_INCREMENTAL_VALUES
  • LDAP_CONTROL_X_DOMAIN_SCOPE
  • LDAP_CONTROL_X_PERMISSIVE_MODIFY
  • LDAP_CONTROL_X_SEARCH_OPTIONS
  • LDAP_CONTROL_X_TREE_DELETE
  • LDAP_CONTROL_X_EXTENDED_DN
  • LDAP_CONTROL_VLVREQUEST
  • LDAP_CONTROL_VLVRESPONSE

Multibyte String

  • MB_CASE_FOLD
  • MB_CASE_LOWER_SIMPLE
  • MB_CASE_UPPER_SIMPLE
  • MB_CASE_TITLE_SIMPLE
  • MB_CASE_FOLD_SIMPLE

OpenSSL

  • STREAM_CRYPTO_PROTO_SSLv3
  • STREAM_CRYPTO_PROTO_TLSv1_0
  • STREAM_CRYPTO_PROTO_TLSv1_1
  • STREAM_CRYPTO_PROTO_TLSv1_2

PostgreSQL

  • PGSQL_DIAG_SCHEMA_NAME
  • PGSQL_DIAG_TABLE_NAME
  • PGSQL_DIAG_COLUMN_NAME
  • PGSQL_DIAG_DATATYPE_NAME
  • PGSQL_DIAG_CONSTRAINT_NAME
  • PGSQL_DIAG_SEVERITY_NONLOCALIZED

User Contributed Notes

There are no user contributed notes for this page.


Alterações incompatíveis com versões anteriores

PHP Core

Interpretação do rótulo de finalização Heredoc/Nowdoc

Devido à introdução da sintaxe flexível heredoc/nowdoc, doc strings que contêm o rótulo final dentro de seu corpo podem causar erros de sintaxe ou alteração na interpretação. Por exemplo em:

<?php
$str = <<<FOO
abcdefg
 FOO
FOO;
?>
A ocorrência recuada de FOO não tinha anteriormente nenhum significado especial. Agora será interpretado como o final da string heredoc e o seguinte FOO; causará um erro de sintaxe. Esse problema sempre pode ser resolvido escolhendo um rótulo final que não ocorra no conteúdo da string.

Continuar problemas com o comutador de segmentação Warning

As instruções continue direcionadas às estruturas de fluxo de controle do switch agora gerarão um aviso. Em PHP, tais instruções continue são equivalentes a break, enquanto se comportam como continue 2 em outras linguagens.

<?php
while ($foo) {
switch ($bar) {
case "baz":
continue;
// Warning: "continue" targeting switch is equivalent to
// "break". Did you mean to use "continue 2"?
}
}
?>

Interpretação estrita de chaves de strings inteiras em ArrayAccess

Acessos de matriz do tipo $obj["123"], onde $obj implementa ArrayAccess e "123"" é uma string literal de inteiro não resultará mais em uma conversão implícita para inteiro, ou seja, $obj->offsetGet("123") será chamado em vez de $obj->offsetGet(123). Isso corresponde ao comportamento existente para não literais. O comportamento dos arrays não é afetado de forma alguma, eles continuam a converter implicitamente chaves de string integrais em inteiros.

Propriedades estáticas não são mais separadas por atribuição de referência

No PHP, as propriedades estáticas são compartilhadas entre as classes herdadas, a menos que a propriedade estática seja explicitamente substituída em uma classe filha. Porém, devido a um artefato de implementação foi possível separar as propriedades estáticas atribuindo uma referência. Essa brecha foi corrigida.

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

Referências retornadas por Array e Property Accesss são imediatamente desempacotadas

As referências retornadas por acessos de array e propriedade agora são desempacotadas como parte do acesso. Isso significa que não é mais possível modificar a referência entre o acesso e o uso do valor acessado:

<?php
$arr = [1];
$ref =& $arr[0];
var_dump($arr[0] + ($arr[0] = 2));
// Previously: int(4), Now: int(3)
?>
Isso torna consistente o comportamento de referências e não referências. Observe que ler e escrever um valor dentro de uma única expressão permanece um comportamento indefinido e pode mudar novamente no futuro.

Argumento de descompactação de Traversables com chaves não inteiras não é mais suportada

A descompactação de argumentos parou de funcionar com Traversables com chaves não inteiras. O código a seguir funcionou no PHP 5.6-7.2 por acidente.

<?php
function foo(...$args) {
var_dump($args);
}
function gen() {
yield 1.23 => 123;
}
foo(...gen());
?>

Diversos

O utilitário ext_skel foi completamente redesenhado com novas opções e algumas opções antigas removidas. Isso agora é escrito em PHP e não possui dependências externas.

O suporte para BeOS foi descartado.

Exceções lançadas devido à conversão automática de avisos em exceções no modo EH_THROW (por exemplo, algumas exceções DateTime) não preenchem mais o estado error_get_last(). Dessa forma, eles agora funcionam da mesma maneira que as exceções lançadas manualmente.

TypeError agora relata tipos errados como int e bool em vez de integer e boolean, respectivamente.

As variáveis indefinidas passadas para compact() agora serão relatadas como um aviso.

getimagesize() e funções relacionadas agora relatam o tipo mime de imagens BMP como image/bmp em vez de image/x-ms-bmp, já que o primeiro foi registrado na IANA (consulte » RFC 7903).

stream_socket_get_name() agora retornará endereços IPv6
entre colchetes. Por exemplo, "[::1]:1337" será
retornado em vez de "::1:1337".

BCMath Matemática de Precisão Arbitrária

Todos os avisos lançados pelas funções BCMath agora estão usando o tratamento de erros do PHP. Anteriormente, alguns avisos eram gravados diretamente no stderr.

bcmul() e bcpow() agora retornam números com a escala solicitada. Anteriormente, os números retornados podem ter omitido zeros decimais à direita.

IMAP, POP3 e NNTP

Os logins rsh/ssh são desabilitados por padrão. Use imap.enable_insecure_rsh se quiser ativá-los. Observe que a biblioteca IMAP não filtra os nomes das caixas de correio antes de passá-los para o comando rsh/ssh, portanto, passar dados não confiáveis para essa função com rsh/ssh ativado é inseguro.

Multibyte String

Devido ao suporte adicional para capturas nomeadas, os padrões mb_ereg_*() usando capturas nomeadas se comportarão de maneira diferente. Em particular, as capturas nomeadas farão parte das correspondências e mb_ereg_replace() interpretará a sintaxe adicional. Consulte Capturas nomeadas para obter mais informações.

Melhorias na extensão MySQL

As instruções preparadas agora relatam corretamente os segundos fracionários para as colunas DATETIME, TIME e TIMESTAMP com especificador de decimais (por exemplo, TIMESTAMP(6) ao usar microssegundos). Anteriormente, a parte dos segundos fracionários era simplesmente omitida dos valores retornados.

Funções do MySQL (PDO_MYSQL)

As instruções preparadas agora relatam corretamente os segundos fracionários para as colunas DATETIME, TIME e TIMESTAMP com especificador de decimais (por exemplo, TIMESTAMP(6) ao usar microssegundos). Anteriormente, a parte dos segundos fracionários era simplesmente omitida dos valores retornados. Observe que isso afeta apenas o uso de PDO_MYSQL com preparações emuladas desativadas (por exemplo, usando a funcionalidade de preparação nativa). Declarações usando conexões com PDO::ATTR_EMULATE_PREPARES=true (que é o padrão) não foram afetadas pelo bug corrigido e já obtiveram os valores de segundos fracionários apropriados do mecanismo.

Reflection

A exportação de Reflection para string agora usa int e bool em vez de integer e boolean, respectivamente.

Standard PHP Library (SPL)

Se um autoloader SPL lançar uma exceção, os seguintes autoloaders não serão executados. Anteriormente, todos os autoloaders eram executados e as exceções eram encadeadas.

SimpleXML

Operações matemáticas envolvendo objetos SimpleXML agora tratarão o texto como um int ou float, o que for mais apropriado. Anteriormente, os valores eram tratados como ints incondicionalmente.

Cookies recebidos

A partir do PHP 7.3.23, os nomes dos cookies recebidos não são mais decodificados por url por motivos de segurança.

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.


Recursos depreciados

PHP Core

Constantes Case-Insensitive

A declaração de constantes que não diferenciam maiúsculas de minúsculas foi descontinuada. Passar true como o terceiro argumento para define() agora gerará um aviso de descontinuação. O uso de constantes que não diferenciam maiúsculas de minúsculas com uma maiúscula que difere da declaração também é obsoleto.

assert() com Namespace

A declaração de uma função chamada assert() dentro de um namespace está obsoleta. A função assert() está sujeita a tratamento especial pelo mecanismo, o que pode levar a um comportamento inconsistente ao definir uma função com namespace com o mesmo nome.

Pesquisando Strings por Needle não string

Passar um valor não string para funções de pesquisa de string é obsoleto. No futuro, o valor será interpretado como uma string em vez de um ponto de código ASCII. Dependendo do comportamento pretendido, você deve converter explicitamente a valor para string ou executar uma chamada explícita para chr(). As seguintes funções são afetadas:

  • strpos()
  • strrpos()
  • stripos()
  • strripos()
  • strstr()
  • strchr()
  • strrchr()
  • stristr()

Strip-Tags Streaming

A função fgetss() e o filtro de stream string.strip_tags foram depreciados. Isso também afeta o método SplFileObject::fgetss() e a função gzgetss().

Filtragem de Dados

O uso explícito das constantes FILTER_FLAG_SCHEME_REQUIRED e FILTER_FLAG_HOST_REQUIRED agora está depreciado; ambos estão implícitos para FILTER_VALIDATE_URL de qualquer maneira.

Processamento de Imagem e GD

image2wbmp() foi depreciado.

Funções de Internacionalização

O uso de Normalizer::NONE gera um aviso de descontinuação, se o PHP estiver vinculado a ICU = 56.

Multibyte String

Os seguintes aliases mbereg_*() não documentados foram depreciados. Em vez disso, use as variantes mb_ereg_*() correspondentes.

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

Funções ODBC e DB2 (PDO_ODBC)

A configuração pdo_odbc.db2_instance_name foi formalmente depreciada. Está obsoleto na documentação a partir do PHP 5.1.1.

User Contributed Notes

There are no user contributed notes for this page.


Outras mudanças

PHP Core

Set(raw)cookie aceita Argumento $option

setcookie() e setrawcookie() agora também suportam a seguinte assinatura:

setcookie(string $name, string $value = "", array $options = []): bool
onde $options é um array associativo que pode ter qualquer uma das chaves "expires", "path", "domain", "secure", "httponly" e "samesite".

Novas Diretivas Syslog ini

As seguintes diretivas ini foram adicionadas para personalizar o log, se error_log for definido como syslog:

syslog.facility
Especifica que tipo de programa está registrando a mensagem.
syslog.filter
Especifica o tipo de filtro para filtrar as mensagens registradas, com os tipos de filtro suportados - all, no-ctrl e ascii. A partir do PHP 7.3.8, o raw também está disponível, restaurando o comportamento do syslog nas versões anteriores do PHP. Este filtro também afetará as chamadas para syslog().
syslog.ident
Especifica a string de identificação que é anexada a cada mensagem.

Garbage Collection

O cyclic GC foi aprimorado, o que pode resultar em melhorias consideráveis de desempenho.

Diversos

var_export() agora exporta objetos stdClass como um array convertido em um objeto ((object) array( ... )), em vez de usar o método inexistente stdClass::__setState().

debug_zval_dump() foi alterado para exibir arrays e objetos recursivos da mesma forma que var_dump(). Agora, ele não os exibe duas vezes.

array_push() e array_unshift() agora também podem ser chamados com um único argumento, o que é particularmente conveniente wrt. O operador de spread.

Interactive PHP Debugger

As constantes não utilizadas PHPDBG_FILE, PHPDBG_METHOD, PHPDBG_LINENO e PHPDBG_FUNC foram removidas.

FastCGI Process Manager

A função getallheaders() agora também está disponível.

Client URL Library

libcurl = 7.15.5 agora é necessário.

Filtragem de Dados

FILTER_VALIDATE_FLOAT agora também suporta a opção thousand, que define o conjunto de caracteres separadores de mil permitidos. O padrão ("',.") é totalmente compatível com versões anteriores do PHP.

FILTER_SANITIZE_ADD_SLASHES foi adicionado como um alias do filtro magic_quotes (FILTER_SANITIZE_MAGIC_QUOTES). O filtro magic_quotes está sujeito a remoção em versões futuras do PHP.

FTP

O modo de transferência padrão foi alterado para binary..

Funções de Internacionalização

Normalizer::NONE está depreciado, quando o PHP está vinculado com ICU = 56.

Introduzido NNormalizer::FORM_KC_CF como argumento Normalizer::normalize() para normalização NFKC_Casefold disponível quando vinculado a ICU = 56.

JSON

Uma nova flag foi adicionada, JSON_THROW_ON_ERROR, que pode ser usado com json_decode() ou json_encode() e faz com que essas funções lancem o novo JsonException em caso de erro, em vez de definir o estado de erro global que é recuperado com json_last_error() e json_last_error_msg(). JSON_PARTIAL_OUTPUT_ON_ERROR tem precedência sobre JSON_THROW_ON_ERROR.

Multibyte String

A opção de configuração --with-libmbfl não está mais disponível.

ODBC (Unificado)

O suporte para ODBCRouter e Birdstep, incluindo a diretiva ini birdstep.max_links, foi removido.

OPcache

A diretiva ini opcache.inherited_hack foi removida. O valor já foi ignorado desde o PHP 5.3.0.

OpenSSL

As opções de stream ssl min_proto_version e max_proto_version, bem como constantes relacionadas para possíveis valores de protocolo TLS foram adicionadas.

Expressões Regulares (Compatível com Perl)

A PCRE extension foi atualizada para PCRE2, o que pode causar pequenas alterações comportamentais (por exemplo, intervalos de caracteres em classes agora são interpretados com mais rigor) e aumenta a sintaxe de expressão regular existente.

preg_quote() agora também escapa do caractere '#'.

Funções Microsoft SQL Server e Sybase (PDO_DBLIB)

O atributo PDO::DBLIB_ATTR_SKIP_EMPTY_ROWSETS para habilitar o salto automático de conjuntos de linhas vazios foi adicionado.

O atributo PDO::DBLIB_ATTR_TDS_VERSION que expõe a versão TDS foi adicionado

As colunas DATETIME2 agora são tratadas como colunas DATETIME.

Funções SQLite (PDO_SQLITE)

Os bancos de dados SQLite3 agora podem ser abertos no modo somente leitura, definindo o novo atributo PDO::SQLITE_ATTR_OPEN_FLAGS como PDO::SQLITE_OPEN_READONLY.

Tratamento de Sessão

session_set_cookie_params() agora também suporta a seguinte assinatura:

session_set_cookie_params(array $options): bool
onde $options é um array associativo que pode ter qualquer uma das chaves "lifetime", "path", "domain", "secure", "httponly" e "samesite" Da mesma forma, o valor de retorno de session_get_cookie_params() agora também possui um elemento com a chave "samesite". Além disso, foi adicionada a nova opção ini session.cookie_samesite para definir o padrão da diretiva SameSite para cookies. O padrão é "" (string vazia), portanto, nenhuma diretiva SameSite é definida. Pode ser definido como "Lax" ou "Strict", que define a respectiva diretiva SameSite.

Tidy

Construir contra » tidyp agora também é suportado de forma transparente. Uma vez que o tidyp não oferece nenhuma API para obter a data de lançamento, tidy_get_release() e tidy::getRelease() retornam 'unknown' neste caso.

Analisador de XML

O valor de retorno do retorno de chamada xml_set_external_entity_ref_handler() não é mais ignorado se a extensão tiver sido criada em libxml. Anteriormente, o valor de retorno era ignorado e a análise nunca parava.

Zip

Compilar com o pacote libzip é desencorajado, mas ainda é possível adicionando --without-libzip à configuração.

Compressão Zlib

A opção de contexto zlib/level para o wrapper compress.zlib wrapper para facilitar a configuração do nível de compactação desejado foi adicionada.

User Contributed Notes

There are no user contributed notes for this page.


Suporte do Windows

PHP Core

Mais exclusão de arquivos em conformidade com POSIX

Os descritores de arquivo são abertos no modo compartilhado de leitura/gravação/exclusão por padrão. Isso mapeia efetivamente a semântica POSIX e permite excluir arquivos com identificadores em uso. Não é 100% igual, algumas diferenças de plataforma ainda persistem. Após a exclusão, a entrada do nome do arquivo é bloqueada, até que todos os identificadores abertos sejam fechados.

User Contributed Notes

There are no user contributed notes for this page.


Migrando do PHP 7.1.x para o PHP 7.2.x

Índice

  • New features
  • New functions
  • Novas constantes globais
  • Backward incompatible changes
  • Recursos depreciados na versão PHP 7.2.x
  • Other changes

Esta nova versão menor traz novos recursos e algumas incompatibilidades que devem ser testadas antes da troca da versão do PHP em ambientes de produção.

Veja também os guias de migração das versões do PHP 7.0.x e 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).


New functions

PHP Core

  • stream_isatty()
  • sapi_windows_vt100_support()

SPL

  • spl_object_id()

DOM

  • DomNodeList::count()
  • DOMNamedNodeMap::count()

FTP

  • ftp_append()

GD

  • imagesetclip()
  • imagegetclip()
  • imageopenpolygon()
  • imageresolution()
  • imagecreatefrombmp()
  • imagebmp()

Hash

  • hash_hmac_algos()

LDAP

  • ldap_parse_exop()
  • ldap_exop()
  • ldap_exop_passwd()
  • ldap_exop_whoami()

Multibyte String

  • mb_chr()
  • mb_ord()
  • mb_scrub()

Oracle OCI8

  • oci_register_taf_callback()
  • oci_unregister_taf_callback()

Sockets

  • socket_addrinfo_lookup()
  • socket_addrinfo_connect()
  • socket_addrinfo_bind()
  • socket_addrinfo_explain()

Sodium

  • sodium_add()
  • sodium_bin2hex()
  • sodium_compare()
  • sodium_crypto_aead_aes256gcm_decrypt()
  • sodium_crypto_aead_aes256gcm_encrypt()
  • sodium_crypto_aead_aes256gcm_is_available()
  • sodium_crypto_aead_aes256gcm_keygen()
  • sodium_crypto_aead_chacha20poly1305_decrypt()
  • sodium_crypto_aead_chacha20poly1305_encrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_decrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_encrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_keygen()
  • sodium_crypto_aead_chacha20poly1305_keygen()
  • sodium_crypto_auth_keygen()
  • sodium_crypto_auth_verify()
  • sodium_crypto_auth()
  • sodium_crypto_box_keypair_from_secretkey_and_publickey()
  • sodium_crypto_box_keypair()
  • sodium_crypto_box_open()
  • sodium_crypto_box_publickey_from_secretkey()
  • sodium_crypto_box_publickey()
  • sodium_crypto_box_seal_open()
  • sodium_crypto_box_seal()
  • sodium_crypto_box_secretkey()
  • sodium_crypto_box_seed_keypair()
  • sodium_crypto_box()
  • sodium_crypto_generichash_final()
  • sodium_crypto_generichash_init()
  • sodium_crypto_generichash_keygen()
  • sodium_crypto_generichash_update()
  • sodium_crypto_generichash()
  • sodium_crypto_kdf_derive_from_key()
  • sodium_crypto_kdf_keygen()
  • sodium_crypto_kx_client_session_keys()
  • sodium_crypto_kx_keypair()
  • sodium_crypto_kx_publickey()
  • sodium_crypto_kx_secretkey()
  • sodium_crypto_kx_seed_keypair()
  • sodium_crypto_kx_server_session_keys()
  • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify()
  • sodium_crypto_pwhash_scryptsalsa208sha256_str()
  • sodium_crypto_pwhash_scryptsalsa208sha256()
  • sodium_crypto_pwhash_str_verify()
  • sodium_crypto_pwhash_str()
  • sodium_crypto_pwhash()
  • sodium_crypto_scalarmult_base()
  • sodium_crypto_scalarmult()
  • sodium_crypto_secretbox_keygen()
  • sodium_crypto_secretbox_open()
  • sodium_crypto_secretbox()
  • sodium_crypto_shorthash_keygen()
  • sodium_crypto_shorthash()
  • sodium_crypto_sign_detached()
  • sodium_crypto_sign_ed25519_pk_to_curve25519()
  • sodium_crypto_sign_ed25519_sk_to_curve25519()
  • sodium_crypto_sign_keypair_from_secretkey_and_publickey()
  • sodium_crypto_sign_keypair()
  • sodium_crypto_sign_open()
  • sodium_crypto_sign_publickey_from_secretkey()
  • sodium_crypto_sign_publickey()
  • sodium_crypto_sign_secretkey()
  • sodium_crypto_sign_seed_keypair()
  • sodium_crypto_sign_verify_detached()
  • sodium_crypto_sign()
  • sodium_crypto_stream_keygen()
  • sodium_crypto_stream_xor()
  • sodium_crypto_stream()
  • sodium_hex2bin()
  • sodium_increment()
  • sodium_memcmp()
  • sodium_memzero()
  • sodium_pad()
  • sodium_unpad()

ZIP

  • ZipArchive::count()
  • ZipArchive::setEncryptionName()
  • ZipArchive::setEncryptionIndex()

User Contributed Notes

There are no user contributed notes for this page.


Novas constantes globais

PHP Core

  • PHP_FLOAT_DIG
  • PHP_FLOAT_EPSILON
  • PHP_FLOAT_MIN
  • PHP_FLOAT_MAX
  • PHP_OS_FAMILY

File Information

  • FILEINFO_EXTENSION

JSON

  • JSON_INVALID_UTF8_IGNORE
  • JSON_INVALID_UTF8_SUBSTITUTE

GD

  • IMG_EFFECT_MULTIPLY
  • IMG_BMP

LDAP

  • LDAP_EXOP_START_TLS
  • LDAP_EXOP_MODIFY_PASSWD
  • LDAP_EXOP_REFRESH
  • LDAP_EXOP_WHO_AM_I
  • LDAP_EXOP_TURN

Password Hashing

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


Backward incompatible changes

Prevent number_format() from returning negative zero

Previously, it was possible for the number_format() function to return -0. Whilst this is perfectly valid according to the IEEE 754 floating point specification, this oddity was not desirable for displaying formatted numbers in a human-readable form.

<?php

var_dump(number_format(-0.01)); // now outputs string(1) "0" instead of string(2) "-0"

Convert numeric keys in object and array casts

Numeric keys are now better handled when casting arrays to objects and objects to arrays (either from explicit casting or by settype()).

This means that integer (or stringy integer) keys from arrays being casted to objects are now accessible:

<?php

// array to object
$arr = [0 => 1];
$obj = (object)$arr;
var_dump(
$obj,
$obj->{'0'}, // now accessible
$obj->{0} // now accessible
);

O exemplo acima produzirá:

object(stdClass)#1 (1) {
  ["0"]=>    // string key now, rather than integer key
  int(1)
}
int(1)
int(1)

And integer (or stringy integer) keys from objects being casted to arrays are now accessible:

<?php

// object to array
$obj = new class {
public function __construct()
{
$this->{0} = 1;
}
};
$arr = (array)$obj;
var_dump(
$arr,
$arr[0], // now accessible
$arr['0'] // now accessible
);

O exemplo acima produzirá:

array(1) {
  [0]=>    // integer key now, rather than string key
  int(1)
}
int(1)
int(1)

Disallow passing null to get_class()

Previously, passing null to the get_class() function would output the name of the enclosing class. This behaviour has now been removed, where an E_WARNING will be output instead. To achieve the same behaviour as before, the argument should simply be omitted.

Warn when counting non-countable types

An E_WARNING will now be emitted when attempting to count() non-countable types (this includes the sizeof() alias function).

<?php

var_dump(
count(null), // NULL is not countable
count(1), // integers are not countable
count('abc'), // strings are not countable
count(new stdClass), // objects not implementing the Countable interface are not countable
count([1,2]) // arrays are countable
);

O exemplo acima produzirá:

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)

Move ext/hash from resources to objects

As part of the long-term migration away from resources, the Hash extension has been updated to use objects instead of resources. The change should be seamless for PHP developers, except for where is_resource() checks have been made (which will need updating to is_object() instead).

Improve SSL/TLS defaults

The following changes to the defaults have been made:

  • tls:// now defaults to TLSv1.0 or TLSv1.1 or TLSv1.2
  • ssl:// an alias of tls://
  • STREAM_CRYPTO_METHOD_TLS_* constants default to TLSv1.0 or TLSv1.1 + TLSv1.2, instead of TLSv1.0 only

gettype() return value on closed resources

Previously, using gettype() on a closed resource would return a string of "unknown type". Now, a string of "resource (closed)" will be returned.

is_object() and __PHP_Incomplete_Class

Previously, using is_object() on the __PHP_Incomplete_Class class would return false. Now, true will be returned.

Promote the error level of undefined constants

Unqualified references to undefined constants will now generate an E_WARNING (instead of an E_NOTICE). In the next major version of PHP, they will generate Error exceptions.

Windows support

The officially supported, minimum Windows versions are now Windows 7/Server 2008 R2.

Checks on default property values of traits

Compatibility checks upon default trait property values will no longer perform casting.

object for class names

The object name was previously soft-reserved in PHP 7.0. This is now hard-reserved, prohibiting it from being used as a class, trait, or interface name.

NetWare support

Support for NetWare has now been removed.

array_unique() with SORT_STRING

While array_unique() with SORT_STRING formerly copied the array and removed non-unique elements (without packing the array afterwards), now a new array is built by adding the unique elements. This can result in different numeric indexes.

bcmod() changes with floats

The bcmod() function no longer truncates fractional numbers to integers. As such, its behavior now follows fmod(), rather than the % operator. For example bcmod('4', '3.5') now returns 0.5 instead of 1.

Hashing functions and non-cryptographic hashes

The hash_hmac(), hash_hmac_file(), hash_pbkdf2(), and hash_init() (with HASH_HMAC) functions no longer accept non-cryptographic hashes.

json_decode() function options

The json_decode() function option, JSON_OBJECT_AS_ARRAY, is now used if the second parameter (assoc) is null. Previously, JSON_OBJECT_AS_ARRAY was always ignored.

rand() and mt_rand() output

Sequences generated by rand() and mt_rand() for a specific seed may differ from PHP 7.1 on 64-bit machines (due to the fixing of a modulo bias bug in the implementation).

Removal of sql.safe_mode ini setting

The sql.safe_mode ini setting has now been removed.

Changes to date_parse() and date_parse_from_format()

The zone element of the array returned by date_parse() and date_parse_from_format() represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200.

Incoming Cookies

As of PHP 7.2.34, the names of incoming cookies are no longer url-decoded for security reasons.

User Contributed Notes

There are no user contributed notes for this page.


Recursos depreciados na versão PHP 7.2.x

Strings sem aspas

Strings sem aspas que não são constantes globais são tomadas para ser strings delas mesmas. Este comportamento costumava emitir um E_NOTICE, mas agora irá emitir um E_WARNING. Na próxima versão maior do PHP, uma exceção Error será lançada no lugar.

<?php

var_dump(NONEXISTENT);

/* Output:
Warning: Use of undefined constant NONEXISTENT - assumed 'NONEXISTENT' (this will throw an Error in a future version of PHP) in %s on line %d
string(11) "NONEXISTENT"
*/

png2wbmp() e jpeg2wbmp()

As funções png2wbmp() e jpeg2wbmp() da extensão GD foram depreciadas e serão removidas na próxima versão maior do PHP.

INTL_IDNA_VARIANT_2003 variante

A extensão Intl depreciou a variante INTL_IDNA_VARIANT_2003, que está sendo usada atualmente como padrão para idn_to_ascii() e idn_to_utf8(). PHP 7.4 irá mudar esses padrões para INTL_IDNA_VARIANT_UTS46, e a próxima versão maior do PHP irá remover INTL_IDNA_VARIANT_2003 completamente.

__autoload() metódo

O método __autoload() foi depreciado porque é inferior ao spl_autoload_register() (devido a não ser permitido encadear autoloaders), e não há interoperabilidade entre os dois estilos de autoloading.

Configuração ini track_errors e variável $php_errormsg

Quando a configuração ini track_errors está ativada, uma variável $php_errormsg é criada no escopo local quando um erro não fatal ocorre. Dado que a maneira preferida de recuperar tais informações de erro é usando error_get_last(), este recurso foi depreciado.

create_function() function

Dado os problemas de segurança desta função (sendo um wrapper ao redor de eval()), esta função datada foi depreciada. A alternativa preferida é o uso de funções anônimas.

Configuração ini mbstring.func_overload

Dado os problemas de interoperabilidade das funções baseadas em string sendo usadas em ambientes com esta configuração ativada, ela será despreciada.

Conversão (unset)

Convertendo qualquer expressão para este tipo sempre resultará em null, e então esta conversão de tipo supérflua foi depreciada.

parse_str() sem um segundo argumento

Sem o segundo argumento para parse_str(), os parâmetros de string de consulta preenchiam a tabela de símbolos local. Dado as implicações de segurança disto, usar parse_str() sem um segundo parâmetro foi depreciado. A função deve sempre ser usada com dois argumentos, como o segundo argumento faz com que a string de consulta seja analisada em um array.

Função gmp_random()

Esta função gera um numero aleatório baseado em um intervalo que é calculado por um tamanho de membro específico da plataforma não exposto. Por isso, esta função foi depreciada. A maneira preferida de gerar um número aleatório usando a extesão GMP é com gmp_random_bits() e gmp_random_range().

Função each()

Esta função é muito mais lenta na iteração do que um foreach normal, e causa problemas de implementações para algumas mudanças da linguagem. Portanto, ela foi depreciada.

assert() com um argumento string

Usar assert() com um argumento string requer que a string seja eval()'iada. Dado o potencial para a execução de código remoto, usar assert() com um argumento string foi depreciada em favor de usar expressão booleanas.

$errcontext argumento para manipuladores de erros

O $errcontext argumento contém todas as variáveis locais de erro do site. Dado a raridade do uso, e os problemas causados com as otimizações interncas, ele foi depreciado. Ao invés disto, um debugger deve ser usado para recuperar informações nas variáveis locais de erro do site.

Função read_exif_data()

O atalho read_exif_data() foi depreciado. A função exif_read_data() deve ser usada no 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.


Other changes

Moving of utf8_encode() and utf8_decode()

The utf8_encode() and utf8_decode() functions have now been moved to the standard extension as string functions, whereas before the XML extension was required for them to be available.

Changes to mail() and mb_send_mail()

The $additional_headers parameter of mail() and mb_send_mail() now also accepts an array instead of a string.

LMDB support

The DBA extension now has support for LMDB.

Changes to the PHP build system

  • Unix: Autoconf 2.64 or greater is now required to build PHP.
  • Unix: --with-pdo-oci configure argument no longer needs the version number of the Oracle Instant Client.
  • Unix: --enable-gd-native-ttf configure argument has been removed. This was not used since PHP 5.5.0.
  • Windows: --with-config-profile configure argument has been added. This can be used to save specific configures, much like the magical config.nice.bat file.

Changes to GD

  • imageantialias() is now also available if compiled with a system libgd.
  • imagegd() stores truecolor images as real truecolor images. Formerly, they have been converted to palette.

Moving MCrypt to PECL

The MCrypt extension has now been moved out of the core to PECL. Given the mcrypt library has not seen any updates since 2007, its usage is highly discouraged. Instead, either the OpenSSL or Sodium extension should be used.

session_module_name()

Passing "user" to session_module_name() now raises an error of level E_RECOVERABLE_ERROR. Formerly, this has been silently ignored.

User Contributed Notes

There are no user contributed notes for this page.


Migrando do PHP 7.0.x para o PHP 7.1.x

Índice

  • New features
  • New functions
  • New global constants
  • Backward incompatible changes
  • Deprecated features in PHP 7.1.x
  • Changed functions
  • Other changes
  • Windows Support

Esta nova versão menor traz vários novos recursos e algumas incompatibilidades que devem ser testadas antes da troca de versões do PHP em ambientes de produção.

Veja também os guias de migração das versões do PHP 7.0.x.

User Contributed Notes

There are no user contributed notes for this page.


New features

Nullable types

Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, null can be passed as an argument, or returned as a value, respectively.

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

O exemplo acima produzirá:

string(10) "elePHPant"
NULL
string(10) "elePHPant"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...

Void functions

A void return type has been introduced. Functions declared with void as their return type must either omit their return statement altogether, or use an empty return statement. null is not a valid return value for a void function.

<?php
function swap(&$left, &$right): void
{
if ($left === $right) {
return;
}

$tmp = $left;
$left = $right;
$right = $tmp;
}

$a = 1;
$b = 2;
var_dump(swap($a, $b), $a, $b);

O exemplo acima produzirá:

null
int(2)
int(1)

Attempting to use a void function's return value simply evaluates to null, with no warnings emitted. The reason for this is because warnings would implicate the use of generic higher order functions.

Symmetric array destructuring

The shorthand array syntax ([]) may now be used to destructure arrays for assignments (including within foreach), as an alternative to the existing list() syntax, which is still supported.

<?php
$data = [
[1, 'Tom'],
[2, 'Fred'],
];

// list() style
list($id1, $name1) = $data[0];

// [] style
[$id1, $name1] = $data[0];

// list() style
foreach ($data as list($id, $name)) {
// logic here with $id and $name
}

// [] style
foreach ($data as [$id, $name]) {
// logic here with $id and $name
}

Class constant visibility

Support for specifying the visibility of class constants has been added.

<?php
class ConstDemo
{
const PUBLIC_CONST_A = 1;
public const PUBLIC_CONST_B = 2;
protected const PROTECTED_CONST = 3;
private const PRIVATE_CONST = 4;
}

iterable pseudo-type

A new pseudo-type (similar to callable) called iterable has been introduced. It may be used in parameter and return types, where it accepts either arrays or objects that implement the Traversable interface. With respect to subtyping, parameter types of child classes may broaden a parent's declaration of array or Traversable to iterable. With return types, child classes may narrow a parent's return type of iterable to array or an object that implements Traversable.

<?php
function iterator(iterable $iter)
{
foreach ($iter as $val) {
//
}
}

Multi catch exception handling

Multiple exceptions per catch block may now be specified using the pipe character (|). This is useful for when different exceptions from different class hierarchies are handled the same.

<?php
try {
// some code
} catch (FirstException | SecondException $e) {
// handle first and second exceptions
}

Support for keys in list()

You can now specify keys in list(), or its new shorthand [] syntax. This enables destructuring of arrays with non-integer or non-sequential keys.

<?php
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];

// list() style
list("id" => $id1, "name" => $name1) = $data[0];

// [] style
["id" => $id1, "name" => $name1] = $data[0];

// list() style
foreach ($data as list("id" => $id, "name" => $name)) {
// logic here with $id and $name
}

// [] style
foreach ($data as ["id" => $id, "name" => $name]) {
// logic here with $id and $name
}

Support for negative string offsets

Support for negative string offsets has been added to the string manipulation functions accepting offsets, as well as to string indexing with [] or {}. In such cases, a negative offset is interpreted as being an offset from the end of the string.

<?php
var_dump("abcdef"[-2]);
var_dump(strpos("aabbcc", "b", -3));

O exemplo acima produzirá:

string (1) "e"
int(3)

Negative string and array offsets are now also supported in the simple variable parsing syntax inside of strings.

<?php
$string = 'bar';
echo "The last character of '$string' is '$string[-1]'.\n";
?>

O exemplo acima produzirá:

The last character of 'bar' is 'r'.

Support for AEAD in ext/openssl

Support for AEAD (modes GCM and CCM) have been added by extending the openssl_encrypt() and openssl_decrypt() functions with additional parameters.

Convert callables to Closures with Closure::fromCallable()

A new static method has been introduced to the Closure class to allow for callables to be easily converted into Closure objects.

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

O exemplo acima produzirá:

string(10) "some value"

Asynchronous signal handling

A new function called pcntl_async_signals() has been introduced to enable asynchronous signal handling without using ticks (which introduce a lot of overhead).

<?php
pcntl_async_signals(true); // turn on async signals

pcntl_signal(SIGHUP, function($sig) {
echo "SIGHUP\n";
});

posix_kill(posix_getpid(), SIGHUP);

O exemplo acima produzirá:

SIGHUP

HTTP/2 server push support in ext/curl

Support for server push has been added to the CURL extension (requires version 7.46 and above). This can be leveraged through the curl_multi_setopt() function with the new CURLMOPT_PUSHFUNCTION constant. The constants CURL_PUSH_OK and CURL_PUSH_DENY have also been added so that the execution of the server push callback can either be approved or denied.

Stream Context Options

The tcp_nodelay stream context option has been added.

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


New functions

PHP Core

  • sapi_windows_cp_get()
  • sapi_windows_cp_set()
  • sapi_windows_cp_conv()
  • sapi_windows_cp_is_utf8()

Closure

  • Closure::fromCallable()

CURL

  • curl_multi_errno()
  • curl_share_errno()
  • curl_share_strerror()

OpenSSL

  • openssl_get_curve_names()

Session

  • session_create_id()
  • session_gc()

SPL

  • is_iterable()

PCNTL

  • pcntl_async_signals()
  • pcntl_signal_get_handler()

User Contributed Notes

There are no user contributed notes for this page.


New global constants

Core Predefined Constants

  • PHP_FD_SETSIZE

CURL

  • CURLMOPT_PUSHFUNCTION
  • CURL_PUSH_OK
  • CURL_PUSH_DENY

Data Filtering

  • FILTER_FLAG_EMAIL_UNICODE

Image Processing and GD

  • IMAGETYPE_WEBP

JSON

  • JSON_UNESCAPED_LINE_TERMINATORS

LDAP

  • LDAP_OPT_X_SASL_NOCANON
  • LDAP_OPT_X_SASL_USERNAME
  • LDAP_OPT_X_TLS_CACERTDIR
  • LDAP_OPT_X_TLS_CACERTFILE
  • LDAP_OPT_X_TLS_CERTFILE
  • LDAP_OPT_X_TLS_CIPHER_SUITE
  • LDAP_OPT_X_TLS_KEYFILE
  • LDAP_OPT_X_TLS_RANDOM_FILE
  • LDAP_OPT_X_TLS_CRLCHECK
  • LDAP_OPT_X_TLS_CRL_NONE
  • LDAP_OPT_X_TLS_CRL_PEER
  • LDAP_OPT_X_TLS_CRL_ALL
  • LDAP_OPT_X_TLS_DHFILE
  • LDAP_OPT_X_TLS_CRLFILE
  • LDAP_OPT_X_TLS_PROTOCOL_MIN
  • LDAP_OPT_X_TLS_PROTOCOL_SSL2
  • LDAP_OPT_X_TLS_PROTOCOL_SSL3
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_0
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_1
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_2
  • LDAP_OPT_X_TLS_PACKAGE
  • LDAP_OPT_X_KEEPALIVE_IDLE
  • LDAP_OPT_X_KEEPALIVE_PROBES
  • LDAP_OPT_X_KEEPALIVE_INTERVAL

PostgreSQL

  • PGSQL_NOTICE_LAST
  • PGSQL_NOTICE_ALL
  • PGSQL_NOTICE_CLEAR

SPL

  • MT_RAND_PHP

User Contributed Notes

There are no user contributed notes for this page.


Backward incompatible changes

Throw on passing too few function arguments

Previously, a warning would be emitted for invoking user-defined functions with too few arguments. Now, this warning has been promoted to an Error exception. This change only applies to user-defined functions, not internal functions. For example:

<?php
function test($param){}
test();

O exemplo acima produzirá algo semelhante 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

Forbid dynamic calls to scope introspection functions

Dynamic calls for certain functions have been forbidden (in the form of $func() or array_map('extract', ...), etc). These functions either inspect or modify another scope, and present with them ambiguous and unreliable behavior. The functions are as follows:

  • assert() - with a string as the first argument
  • compact()
  • extract()
  • func_get_args()
  • func_get_arg()
  • func_num_args()
  • get_defined_vars()
  • mb_parse_str() - with one arg
  • parse_str() - with one arg
<?php
(function () {
$func = 'func_num_args';
$func();
})();

O exemplo acima produzirá:

Warning: Cannot call func_num_args() dynamically in %s on line %d

Invalid class, interface, and trait names

The following names cannot be used to name classes, interfaces, or traits:

  • void
  • iterable

Numerical string conversions now respect scientific notation

Integer operations and conversions on numerical strings now respect scientific notation. This also includes the (int) cast operation, and the following functions: intval() (where the base is 10), settype(), decbin(), decoct(), and dechex().

Fixes to mt_rand() algorithm

mt_rand() will now default to using the fixed version of the Mersenne Twister algorithm. If deterministic output from mt_rand() was relied upon, then MT_RAND_PHP can be used as optional second parameter to mt_srand() to preserve the old (incorrect) implementation.

rand() aliased to mt_rand() and srand() aliased to mt_srand()

rand() and srand() have now been made aliases to mt_rand() and mt_srand(), respectively. This means that the output for the following functions have changed: rand(), shuffle(), str_shuffle(), and array_rand().

Disallow the ASCII delete control character in identifiers

The ASCII delete control character (0x7F) can no longer be used in identifiers that are not quoted.

error_log changes with syslog value

If the error_log ini setting is set to syslog, the PHP error levels are mapped to the syslog error levels. This brings finer differentiation in the error logs in contrary to the previous approach where all the errors are logged with the notice level only.

Do not call destructors on incomplete objects

Destructors are now never called for objects that throw an exception during the execution of their constructor. In previous versions this behavior depended on whether the object was referenced outside the constructor (e.g. by an exception backtrace).

call_user_func() handling of reference arguments

call_user_func() will now always generate a warning upon calls to functions that expect references as arguments. Previously this depended on whether the call was fully qualified.

Additionally, call_user_func() and call_user_func_array() will no longer abort the function call in this case. The "expected reference" warning will be emitted, but the call will proceed as usual.

The empty index operator is not supported for strings anymore

Applying the empty index operator to a string (e.g. $str[] = $x) throws a fatal error instead of converting silently to array.

Assignment via string index access on an empty string

String modification by character on an empty string now works like for non-empty strings, i.e. writing to an out of range offset pads the string with spaces, where non-integer types are converted to integer, and only the first character of the assigned string is used. Formerly, empty strings where silently treated like an empty array.

<?php
$a = '';
$a[10] = 'foo';
var_dump($a);
?>

Saída do exemplo acima no PHP 7.0:

array(1) {
  [10]=>
  string(3) "foo"
}

Saída do exemplo acima no PHP 7.1:

string(11) "          f"

Removed ini directives

The following ini directives have been removed:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

Array ordering when elements are automatically created during by reference assignments has changed

The order of the elements in an array has changed when those elements have been automatically created by referencing them in a by reference assignment. For example:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Saída do exemplo acima no PHP 7.0:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Saída do exemplo acima no PHP 7.1:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Sort order of equal elements

The internal sorting algorithm has been improved, what may result in different sort order of elements, which compare as equal, than before.

Nota:

Don't rely on the order of elements which compare as equal; it might change anytime.

Error message for E_RECOVERABLE errors

The error message for E_RECOVERABLE errors has been changed from "Catchable fatal error" to "Recoverable fatal error".

$options parameter of unserialize()

The allowed_classes element of the $options parameter of unserialize() is now strictly typed, i.e. if anything other than an array or a bool is given, unserialize() returns false and issues an E_WARNING.

DateTime constructor incorporates microseconds

DateTime and DateTimeImmutable now properly incorporate microseconds when constructed from the current time, either explicitly or with a relative string (e.g. "first day of next month"). This means that naive comparisons of two newly created instances will now more likely return false instead of true:

<?php
new DateTime() == new DateTime();
?>

Fatal errors to Error exceptions conversions

In the Date extension, invalid serialization data for DateTime or DatePeriod classes, or timezone initialization failure from serialized data, will now throw an Error exception from the __wakeup() or __set_state() methods, instead of resulting in a fatal error.

In the DBA extension, data modification functions (such as dba_insert()) will now throw an Error exception instead of triggering a catchable fatal error if the key does not contain exactly two elements.

In the DOM extension, invalid schema or RelaxNG validation contexts will now throw an Error exception instead of resulting in a fatal error. Similarly, attempting to register a node class that does not extend the appropriate base class, or attempting to read an invalid property or write to a readonly property, will also now throw an Error exception.

In the IMAP extension, email addresses longer than 16385 bytes will throw an Error exception instead of resulting in a fatal error.

In the Intl extension, failing to call the parent constructor in a class extending Collator before invoking the parent methods will now throw an Error instead of resulting in a recoverable fatal error. Also, cloning a Transliterator object will now throw an Error exception on failure to clone the internal transliterator instead of resulting in a fatal error.

In the LDAP extension, providing an unknown modification type to ldap_batch_modify() will now throw an Error exception instead of resulting in a fatal error.

In the mbstring extension, the mb_ereg() and mb_eregi() functions will now throw a ParseError exception if an invalid PHP expression is provided and the 'e' option is used.

In the Mcrypt extension, the mcrypt_encrypt() and mcrypt_decrypt() will now throw an Error exception instead of resulting in a fatal error if mcrypt cannot be initialized.

In the mysqli extension, attempting to read an invalid property or write to a readonly property will now throw an Error exception instead of resulting in a fatal error.

In the Reflection extension, failing to retrieve a reflection object or retrieve an object property will now throw an Error exception instead of resulting in a fatal error.

In the Session extension, custom session handlers that do not return strings for session IDs will now throw an Error exception instead of resulting in a fatal error when a function is called that must generate a session ID.

In the SimpleXML extension, creating an unnamed or duplicate attribute will now throw an Error exception instead of resulting in a fatal error.

In the SPL extension, attempting to clone an SplDirectory object will now throw an Error exception instead of resulting in a fatal error. Similarly, calling ArrayIterator::append() when iterating over an object will also now throw an Error exception.

In the standard extension, the assert() function, when provided with a string argument as its first parameter, will now throw a ParseError exception instead of resulting in a catchable fatal error if the PHP code is invalid. Similarly, calling forward_static_call() outside of a class scope will now throw an Error exception.

In the Tidy extension, creating a tidyNode manually will now throw an Error exception instead of resulting in a fatal error.

In the WDDX extension, a circular reference when serializing will now throw an Error exception instead of resulting in a fatal error.

In the XML-RPC extension, a circular reference when serializing will now throw an instance of Error exception instead of resulting in a fatal error.

In the Zip extension, the ZipArchive::addGlob() method will now throw an Error exception instead of resulting in a fatal error if glob support is not available.

Lexically bound variables cannot reuse names

Variables bound to a closure via the use construct cannot use the same name as any superglobals, $this, or any parameter. For example, all of these function definition will result in a fatal error:

<?php
$f = function () use ($_SERVER) {};
$f = function () use ($this) {};
$f = function ($param) use ($param) {};

long2ip() parameter type change

long2ip() now expects an int instead of a string.

JSON encoding and decoding

The serialize_precision ini setting now controls the serialization precision when encoding floats.

Decoding an empty key now results in an empty property name, rather than _empty_ as a property name.

<?php
var_dump(json_decode(json_encode(['' => 1])));

O exemplo acima produzirá algo semelhante a:

object(stdClass)#1 (1) {
  [""]=>
  int(1)
}

When supplying the JSON_UNESCAPED_UNICODE flag to json_encode(), the sequences U+2028 and U+2029 are now escaped.

Changes to mb_ereg() and mb_eregi() parameter semantics

The third parameter to the mb_ereg() and mb_eregi() functions (regs) will now be set to an empty array if nothing was matched. Formerly, the parameter would not have been modified.

Drop support for the sslv2 stream

The sslv2 stream has now been dropped in OpenSSL.

Forbid "return;" for typed returns already at compile-time

Return statements without argument in functions which declare a return type now trigger E_COMPILE_ERROR (unless the return type is declared as void), even if the return statement would never be reached.

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


Deprecated features in PHP 7.1.x

ext/mcrypt

The mcrypt extension has been abandonware for nearly a decade now, and was also fairly complex to use. It has therefore been deprecated in favour of OpenSSL, where it will be removed from the core and into PECL in PHP 7.2.

Eval option for mb_ereg_replace() and mb_eregi_replace()

The e pattern modifier has been deprecated for the mb_ereg_replace() and mb_eregi_replace() functions.

User Contributed Notes

There are no user contributed notes for this page.


Changed functions

PHP Core

  • getopt() has an optional third parameter that exposes the index of the next element in the argument vector list to be processed. This is done via a by-ref parameter.
  • getenv() no longer requires its parameter. If the parameter is omitted, then the current environment variables will be returned as an associative array.
  • get_headers() now has an additional parameter to enable for the passing of custom stream contexts.
  • output_reset_rewrite_vars() no longer resets session URL rewrite variables.
  • parse_url() is now more restrictive and supports RFC3986.
  • unpack() now accepts an optional third parameter to specify the offset to begin unpacking from.

File System

  • file_get_contents() now accepts a negative seek offset if the stream is seekable.
  • tempnam() now emits a notice when falling back to the system's temp directory.

JSON

  • json_encode() now accepts a new option, JSON_UNESCAPED_LINE_TERMINATORS, to disable the escaping of U+2028 and U+2029 characters when JSON_UNESCAPED_UNICODE is supplied.

Multibyte String

  • mb_ereg() now rejects illegal byte sequences.
  • mb_ereg_replace() now rejects illegal byte sequences.

PDO

  • PDO::lastInsertId() for PostgreSQL will now trigger an error when nextval has not been called for the current session (the postgres connection).

PostgreSQL

  • pg_last_notice() now accepts an optional parameter to specify an operation. This can be done with one of the following new constants: PGSQL_NOTICE_LAST, PGSQL_NOTICE_ALL, or PGSQL_NOTICE_CLEAR.
  • pg_fetch_all() now accepts an optional second parameter to specify the result type (similar to the third parameter of pg_fetch_array()).
  • pg_select() now accepts an optional fourth parameter to specify the result type (similar to the third parameter of pg_fetch_array()).

Session

  • session_start() now returns false and no longer initializes $_SESSION when it failed to start the session.

User Contributed Notes

There are no user contributed notes for this page.


Other changes

Notices and warnings on arithmetic with invalid strings

New E_WARNING and E_NOTICE errors have been introduced when invalid strings are coerced using operators expecting numbers (+ - * / ** % << >> | & ^) or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.

<?php
'1b' + 'something';

O exemplo acima produzirá:

Notice: A non well formed numeric value encountered in %s on line %d
Warning: A non-numeric value encountered in %s on line %d

Warn on octal escape sequence overflow

Previously, 3-octet octal string escape sequences would overflow silently. Now, they will still overflow, but E_WARNING will be emitted.

<?php
var_dump("\500");

O exemplo acima produzirá:

Warning: Octal escape sequence overflow \500 is greater than \377 in %s on line %d
string(1) "@"

Inconsistency fixes to $this

Whilst $this is considered a special variable in PHP, it lacked proper checks to ensure it wasn't used as a variable name or reassigned. This has now been rectified to ensure that $this cannot be a user-defined variable, reassigned to a different value, or be globalised.

Session ID generation without hashing

Session IDs will no longer be hashed upon generation. With this change brings about the removal of the following four ini settings:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

And the addition of the following two ini settings:

  • session.sid_length - defines the length of the session ID, defaulting to 32 characters for backwards compatibility)
  • session.sid_bits_per_character - defines the number of bits to be stored per character (i.e. increases the range of characters that can be used in the session ID), defaulting to 4 for backwards compatibility

Changes to INI file handling

precision

If the value is set to -1, then the dtoa mode 0 is used. The default value is still 14.

serialize_precision

If the value is set to -1, then the dtoa mode 0 is used. The value -1 is now used by default.

gd.jpeg_ignore_warning

The default of this php.ini setting has been changed to 1, so by default libjpeg warnings are ignored.

opcache.enable_cli

The default of this php.ini setting has been changed to 1 (enabled) in PHP 7.1.2, and back to 0 (disabled) in PHP 7.1.7.

Session ID generation with a CSPRNG only

Session IDs will now only be generated with a CSPRNG.

More informative TypeError messages when null is allowed

TypeError exceptions for arg_info type checks will now provide more informative error messages. If the parameter type or return type accepts null (by either having a default value of null or being a nullable type), then the error message will now mention this with a message of "must be ... or null" or "must ... or be null."

User Contributed Notes

Ta7To7 27-Feb-2018 05:47
Note that using Incrementing/Decrementing operators on string is legal
<?php
$str = "";
echo ++$str; // output: 1
?>


Windows Support

Support for long and UTF-8 path

If a web application is UTF-8 conform, no further action is required. For applications depending on paths in non UTF-8 encodings for I/O, an explicit INI directive has to be set. The encoding INI settings check relies on the order in the core:

  • internal_encoding
  • default_charset
  • zend.multibyte

Several functions for codepage handling were introduced:

  • sapi_windows_cp_set() to set the default codepage
  • sapi_windows_cp_get() to retrieve the current codepage
  • sapi_windows_cp_is_utf8()
  • sapi_windows_cp_conv() to convert between codepages, using iconv() compatible signature

These functions are thread safe.

The console output codepage is adjusted depending on the encoding used in PHP. Depending on the concrete system OEM codepage, the visible output might or might be not correct. For example, in the default cmd.exe and on a system with the OEM codepage 437, outputs in codepages 1251, 1252, 1253 and some others can be shown correctly when using UTF-8. On the same system, chars in codepage like 20932 probably won't be shown correctly. This refers to the particular system rules for codepage, font compatibility and the particular console program used. PHP automatically sets the console codepage according to the encoding rules from php.ini. Using alternative consoles instead of cmd.exe directly might bring better experience in some cases.

Nevertheless be aware, runtime codepage switch after the request start might bring unexpected side effects on CLI. The preferable way is php.ini, When PHP CLI is used in a console emulator, that doesn't support Unicode, it might possibly be required, to avoid changing the console codepage. The best way to achieve it is by setting the default or internal encoding to correspond the ANSI codepage. Another method is to set the INI directives output_encoding and input_encoding to the required codepage, in which case however the difference between internal and I/O codepage is likely to cause mojibake. In rare cases, if PHP happens to crash gracefully, the original console codepage might be not restored. In this case, the chcp command can be used, to restore it manually.

Special awareness for the DBCS systems - the codepage switch on runtime using ini_set() is likely to cause display issues. The difference to the non DBCS systems is, that the extended characters require two console cells to be displayed. In certain case, only the mapping of the characters into the glyph set of the font could happen, no actual font change. This is the nature of DBCS systems, the most simple way to prevent display issues is to avoid usage of ini_set() for the codepage change.

As a result of UTF-8 support in the streams, PHP scripts are not limited to ASCII or ANSI filenames anymore. This is supported out of the box on CLI. For other SAPI, the documentation for the corresponding server is useful.

Long paths support is transparent. Paths longer than 260 bytes get automatically prefixed with \\?\. The max path length is limited to 2048 bytes. Be aware, that the path segment limit (basename length) still persists.

For the best portability, it is strongely recommended to handle filenames, I/O and other related topics UTF-8. Additionally, for the console applications, the usage of a TrueType font is preferable and the usage of ini_set() for the codepage change is discouraged.

readline

The readline extension is supported through the » WinEditLine library. Thereby, the interactive CLI shell is supported as well (php.exe -a).

PHP_FCGI_CHILDREN

PHP_FCGI_CHILDREN is now respected. If this environment variable is defined, the first php-cgi.exe process will exec the specified number of children. These will share the same TCP socket.

ftok()

Added support for ftok()

User Contributed Notes

There are no user contributed notes for this page.


Migrando do PHP 5.6.x para o PHP 7.0.x

Índice

  • Mudanças incompatíveis com versões anteriores
  • Novos Recursos
  • Recursos depreciados no PHP 7.0.x
  • Funções alteradas
  • Novas funções
  • Novas Classes e Interfaces
  • Novas Constantes Globais
  • Modificações nos Módulos SAPI
  • Extensões e SAPIs removidas
  • Outras mudanças

Apesar do fato do PHP 7.0 ser uma versão superior, esforços foram feitos para que a migração seja feita da forma mais simples possível. Essa versão foca principalmente na remoção de funcionalidades depreciadas em versões anteriores e na melhoria da consistênciada da linguagem.

Existem algumas incompatibilidades e novos recursos que devem ser considerados, e o código deve ser testado antes de trocar a versão do PHP em ambientes de produção.

User Contributed Notes

There are no user contributed notes for this page.


Mudanças incompatíveis com versões anteriores

Modificações na manipulação de erros e exceções

Alguns erros fatais e recuperáveis foram convertidos para exceções no PHP 7. Estas exceções herdam a classe Error, que implementa a interface Throwable (a interface base que todas as exceções herdam).

Isso significa que manipuladores de erros podem não ser ativados porque exceções estão sendo disparadas em seu lugar (causando novos erros fatais por exceções Error não capturadas)

Uma descrição completa de como tratar erros no PHP 7 pode ser encontrada na página de erros do PHP 7. Este guia de migração irá enumerar apenas as mudanças compatíveis com versões anteriores.

set_exception_handler() não têm mais garantias de receber um objeto do tipo Exception.

Códigos que implementam um manipulador de exceção registrado com set_exception_handler() usando a declaração de tipo Exception causará um erro fatal quando um objeto Error for lançado.

Se o manipulador precisa trabalhar com o PHP 5 e 7, você deve remover a declaração de tipo do manipulador, enquanto que o código a migrar para funcionar exclusivamente no PHP 7, pode simplesmente trocar a declaração de tipo Exception por Throwable.

<?php
// Código da era PHP 5 que não irá funcionar.
function handler(Exception $e) { ... }
set_exception_handler('handler');

// Compatível com PHP 5 e 7.
function handler($e) { ... }

// Somente PHP 7.
function handler(Throwable $e) { ... }
?>

Construtores internos sempre lançarão exceções em caso de falha

Anteriormente, algumas classes internas retornavam null ou um objeto inútil quando o construtor falhava. Todas as classes internas agora lançam Exception neste caso, da mesma forma que classes de usuário já faziam.

Erros de Parse lançam exceções ParseError

Erros de Parser agora lançam um objeto ParseError. Manipular erros da função eval() devem incluir um bloco catch que possa manipular este erro.

Mudanças na severidade de notificações E_STRICT

Todas as notificações E_STRICT foram reclassificadas para outros níveis. A constante E_STRICT foi mantida, então chamar error_reporting(E_ALL|E_STRICT) não causará um erro.

Mudanças na severidade de notificações E_STRICT
Situação | Novo nível/Comportamento
Utilizar um recurso como índice | E_NOTICE
Métodos estáticos abstratos | Notificação removida, não dispara erro
"Redefinindo" um construtor | Notificação removida, não dispara erro
Assinatura incompatível durante a herança | E_WARNING
Mesmas propriedades(compatíveis) em duas traits utilizadas | Notificação removida, não dispara erro
Acessando propriedades estáticas de forma não estática | E_NOTICE
Somente variáveis devem ser ser atribuídas por referência | E_NOTICE
Somente variáveis devem ser passadas por referência | E_NOTICE
Chamando métodos não estáticos de forma estática | E_DEPRECATED

Mudanças na manipulação de variáveis

O PHP 7 utiliza uma sintaxe abstrata de árvore para analisar os arquivos fonte. Isso permitiu diversas melhorias para a linguagem que eram impossíveis devido a limitações no analisador utilizado em versões anteriores do PHP, porém resultou na remoção de alguns casos especiais por razões de consistência, que resulta em quebras de compatibilidades com versões anteriores. Esses casos são detalhados nesta seção.

Mudanças na manipulação indireta de variáveis, propriedades e métodos

Acessar indiretamente variáveis, propriedades, e métodos, agora serão avaliados estritamente da esquerda para a direita, o oposto dos casos especiais em versões anteriores. A tabela a seguir mostra como a ordem de avaliação mudou.

Nova e antiga avaliação de expressões indiretas
Expressão | Interpretação no PHP 5 | Interpretação no 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']()

Códigos que usam a ordem de avaliação da direita para esquerda devem ser reescritos para o uso explícito da ordem de avaliação com chaves (veja a coluna do meio). Isso fará com que o código seja compatível com versões posteriores ao PHP 7.x e compatível com o PHP 5.x.

Isso também afeta a palavra chave global. A sintaxe com chaves pode ser usada para emular o comportamento anterior se necessário:

<?php
function f() {
// Válido apenas no PHP 5.
global $$foo->bar;

// Válido no PHP 5 e 7.
global ${$foo->bar};
}
?>

Mudanças na manipulação com a função list()

A função list() não faz mais atribuições em ordem reversa

A função list() agora irá atribuir valores as variáveis na ordem em que foram definidas, em vez de ordem reversa. De modo geral, isso só afeta casos onde a função list() é utilizada em conjunção com o operador de array [], como mostrado a seguir:

<?php
list($a[], $a[], $a[]) = [1, 2, 3];
var_dump($a);
?>

Saída do exemplo acima no PHP 5:

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

Saída do exemplo acima no PHP 7:

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

De modo geral, é recomendo não confiar na ordem em que as atribuições com que a função list() ocorrem, como sua implementação detalha, isso pode mudar novamente no futuro.

Atribuições de list() vazias foram removidas

Chamadas a função list() não podem mais ser vazias. O que é visto a seguir não é mais permitido:

<?php
list() = $a;
list(,,) = $a;
list($x, list(), $y) = $a;
?>
A função list() não podem desempacotar strings

A função list() não podem mais desempacotar variáveis do tipo string. Em vez disso, a função str_split() deve ser usada.

A ordenação de arrays quando elementos são criados durante atribuições por referência mudou

A ordem dos elementos no array foi modificada quando estes elementos foram automaticamente criados por referenciação em uma atribuição por referência. Por exemplo:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Saída do exemplo acima no PHP 5:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Saída do exemplo acima no PHP 7:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Parênteses em torno de parâmetros de função não afetam mais seu comportamento

No PHP 5, usar parênteses redundantes em torno de parâmetros de uma função podem disparar avisos de quebra de padrões quando os parâmetros da função fossem passados por referência. Agora, o aviso sempre será emitido.

<?php
function getArray() {
return [1, 2, 3];
}

function squareArray(array &$a) {
foreach ($a as &$v) {
$v **= 2;
}
}

// Generates a warning in PHP 7.
squareArray((getArray()));
?>

O exemplo acima produzirá:

Notice: Only variables should be passed by reference in /tmp/test.php on line 13

Mudanças no foreach

Pequenas mudanças foram feitas no modo como a estrutura de controle foreach se comporta, principalmente na manipulação do ponteiro interno do array e modificações no array sendo iterado.

foreach não modifica mais o ponteiro interno do array

Antes do PHP 7, o ponteiro interno do array era modificado enquanto o array era iterado usando o foreach. Este não é mais o caso, como mostrado nos exemplos a seguir:

<?php
$array = [0, 1, 2];
foreach ($array as &$val) {
var_dump(current($array));
}
?>

Saída do exemplo acima no PHP 5:

int(1)
int(2)
bool(false)

Saída do exemplo acima no PHP 7:

int(0)
int(0)
int(0)

foreach por valor opera em uma cópia do array

Quando usado no modo padrão, por valor, o foreach vai operar em uma cópia do array sendo iterado, ao invés do próprio array. Isso significa que mudanças feitas durante a iteração do array, não afetarão os valores iterados.

Melhora no comporatamento da iteração por referência com foreach

Quanto iterado por referencia, o foreach fará um melhor trabalho de controlar as alterações feitas ao array durante a iteração. Por exemplo, inclusões ao array enquanto iterado, agora resultam na inclusão de valores enquanto itera, como a seguir:

<?php
$array = [0];
foreach ($array as &$val) {
var_dump($val);
$array[1] = 1;
}
?>

Saída do exemplo acima no PHP 5:

int(0)

Saída do exemplo acima no PHP 7:

int(0)
int(1)

Iteração de objetos não Traversable

Iterar objetos não Traversable agora têm o mesmo comportamento que iterar arrays por referência. Isso resulta na melhora do comportamento quando houver modificações no array durante a iteração também aplicado quando propriedades são adicionadas ou removidas do objeto.

Mudança na manipulação do int

Octais literais inválidos

Antes, octais literais que continham números inválidos, eram silenciosamente truncados (0128 se tornaria 012). Agora, um octal literal inválido causará um erro de parse.

Deslocamento de bits negativos

Deslocamento de bits por números negativos agora lançarão uma exceção ArithmeticError:

<?php
var_dump(1 >> -1);
?>

Saída do exemplo acima no PHP 5:

int(0)

Saída do exemplo acima no 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

Deslocamentos de bits fora do limite

Deslocamentos de bits (em ambas direções), além do tamanho de bits de um int sempre resultará em 0. Antes, o comportamento do deslocamento dependia da arquitetura.

Mudanças na Divisão por Zero

Antes, quando 0 era usado como divisor tanto para a operador de divisão (/) quanto para o módulo, um E_WARNING era emitido e false era retornado. Agora, o operador de divisão retornará um float +INF, -INF ou NAN, conforme a especificação IEEE 754. O E_WARNING do operador módulo foi removido e irá lançar uma exceção DivisionByZeroError.

<?php
var_dump(3/0);
var_dump(0/0);
var_dump(0%0);
?>

Saída do exemplo acima no 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)

Saída do exemplo acima no 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

Mudanças na manipulação de strings

Strings hexadecimais não são mais consideradas numéricas

Strings contendo números hexadecimais não são mais consideradas numéricas. Por exemplo:

<?php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));
?>

Saída do exemplo acima no PHP 5:

bool(true)
bool(true)
int(15)
string(2) "oo"

Saída do exemplo acima no PHP 7:

bool(false)
bool(false)
int(0)

Notice: A non well formed numeric value encountered in /tmp/test.php on line 5
string(3) "foo"

filter_var() pode ser usado se uma string contém um número hexadecimal, e também para converter uma string deste tipo para um int:

<?php
$str = "0xffff";
$int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
if (false === $int) {
throw new Exception("Inteiro Inválido!");
}
var_dump($int); // int(65535)
?>

\u{ pode causar erros

Por conta da adição da nova sintaxe de escape de códigos em Unicode, strings contendo um \u{ literal seguido de uma sequência inválida causará um erro fatal. Para evitar isso, você deve escapar a barra invertida.

Funções removidas

call_user_method() e call_user_method_array()

Estas funções foram depreciadas no PHP 4.1.0 em favor de call_user_func() e call_user_func_array(). Você também pode considerar o uso de funções variáveis e/ou o operador ... .

Todas as funções ereg*

Todas as funções ereg foram removidas. PCRE é uma alternativa recomendada.

Sinônimos do mcrypt

A função depreciada mcrypt_generic_end() foi removida em favor de mcrypt_generic_deinit().

Além disso, as funções depreciadas mcrypt_ecb(),
mcrypt_cbc(), mcrypt_cfb() e
mcrypt_ofb() foram removidas em favor do
uso da função mcrypt_decrypt() com a constante
MCRYPT_MODE_* apropriada.

Todas as funções ext/mysql

Todas as funções ext/mysql foram removidas. Para mais detalhes sobre a escolha de uma API MySQL diferente, veja a seção Escolhendo uma API MySQL.

Todas as funções ext/mssql

Todas as funções ext/mssql foram removidas.

  • PDO_SQLSRV
  • PDO_ODBC
  • SQLSRV
  • API ODBC Unificada

Sinônimos de intl

Os sinônimos depreciados datefmt_set_timezone_id() e
IntlDateFormatter::setTimeZoneID() foram
removidos em favor de datefmt_set_timezone() e
IntlDateFormatter::setTimeZone(), respectivamente.

set_magic_quotes_runtime()

set_magic_quotes_runtime(), juntamente com seu sinônimo magic_quotes_runtime(), foram removidos. Eles foram depreciados no PHP 5.3.0 e se tornaram efetivamente não funcionais com a remoção das magic quotes no PHP 5.4.0.

set_socket_blocking()

O sinônimo depreciado set_socket_blocking() foi removido em favor de stream_set_blocking().

dl() no PHP-FPM

dl() não pode mais ser utilizado no PHP-FPM. Ela permanece funcional na interface CLI e SAPIs embarcadas.

Funções GD Type1

O suporte a fontes PostScript Type1 foi removido da extensão GD, resultando na remoção das seguintes funções:

  • imagepsbbox()
  • imagepsencodefont()
  • imagepsextendfont()
  • imagepsfreefont()
  • imagepsloadfont()
  • imagepsslantfont()
  • imagepstext()

O uso de fontes TruType e suas funções associadas é recomendado.

Diretivas INI removidas

Recursos removidos

As diretivas INI a seguir foram removidas, assim como os como seus recursos associados:

  • always_populate_raw_post_data
  • asp_tags

xsl.security_prefs

A diretiva xsl.security_prefs foi removida. Em substituição, o método XsltProcessor::setSecurityPrefs() deve ser chamado para controlar as preferências de segurança por processo base.

Outras mudanças incompatíveis com versões anteriores

Novos objetos não podem ser atribuídos por referência

O resultado da declaração new não pode mais ser atribuído a uma variável por referência:

<?php
class C {}
$c =& new C;
?>

Saída do exemplo acima no PHP 5:

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

Saída do exemplo acima no PHP 7:

Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3

Nomes inválidos de classes, interfaces e traits

Os nomes a seguir não podem ser utilizados como nome de classes, interfaces ou traits:

  • bool
  • int
  • float
  • string
  • null
  • true
  • false

Além disso, os seguintes nomes não devem ser usados. Embora eles não geram um erro no PHP 7.0, eles são reservados para uso futuro e devem ser considerados depreciados.

  • resource
  • object
  • mixed
  • numeric

Tags ASP e script removidas

O suporte ao uso das tags ASP e script para delimitar o código PHP foi removido. As tags afetadas são:

Tags ASP e script removidas
Tag de abertura | Tag de fechamento
<% | %>
<%= | %>
<script language="php"> | </script>

Chamadas de contextos incompatíveis foram removidas

Anteriormente depreciadas no PHP 5.6, chamadas estáticas feitas a métodos não-estáticos com um contexto incompatível agora resultarão no método chamado tendo uma variável $this indefinida e um aviso de depreciação será emitido.

<?php
class A {
public function test() { var_dump($this); }
}

// Nota: NÃO extende A
class B {
public function callNonStaticMethodOfA() { A::test(); }
}

(new B)->callNonStaticMethodOfA();
?>

Saída do exemplo acima no PHP 5.6:

Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8
object(B)#1 (0) {
}

Saída do exemplo acima no PHP 7:

Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8

Notice: Undefined variable: this in /tmp/test.php on line 3
NULL

yield agora é um operador associativo à direita

O construtor yield não requer mais o uso de parênteses e foi alterado para um operador associativo à direita com precedência entre print e =>. Isso pode resultar em um comportamento alterado:

<?php
echo yield -1;
// Era interpretado como
echo (yield) - 1;
// E agora é interpretado como
echo yield (-1);

yield $foo or die;
// Era interpretado como
yield ($foo or die);
// E agora é interpretado como
(yield $foo) or die;
?>

Parênteses podem ser utilizados para remover a ambiguidade nestes casos.

Funções não podem ter vários parâmetros com o mesmo nome

Não é mais possível definir dois ou mais parâmetros em uma função com o mesmo nome. Por exemplo, a função a seguir vai disparar um E_COMPILE_ERROR:

<?php
function foo($a, $b, $unused, $unused) {
//
}
?>

Funções inspecionando argumentos informam o valor atual do parâmetro

func_get_arg(), func_get_args(), debug_backtrace() e backtraces de exceção não informam mais o valor original que foi passado para um parâmetro, mas ao invés disso, irão informar o valor atual (que pode ter sido modificado).

<?php
function foo($x) {
$x++;
var_dump(func_get_arg(0));
}
foo(1);?>

Saída do exemplo acima no PHP 5:

1

Saída do exemplo acima no PHP 7:

2

Declarações switch não podem ter vários blocos default

Não é mais possível definir dois ou mais blocos default em uma declaração switch. Por exemplo, a declaração switch a seguir irá disparar um E_COMPILE_ERROR:

<?php
switch (1) {
default:
break;
default:
break;
}
?>

$HTTP_RAW_POST_DATA removida

A variável $HTTP_RAW_POST_DATA não está mais disponível. Ao invés disso o stream php://input deve ser utilizado.

Comentários iniciados com # nos arquivos INI foram removidos

O suporte a comentários prefixados com # nos arquivos INI foi removido. Em vez disso, o ; (ponto-e-vírgula) deve ser usado. Esta mudança aplica-se ao php.ini, assim como aos arquivos manipulados pelas funções parse_ini_file() e parse_ini_string().

Substituição da extensão JSON por JSOND

A extensão JSON foi substituída por JSOND, causando três quebras menores de compatibilidade com versões anteriores. Em primeiro lugar, um número não pode ser terminado em um ponto decimal (isto é, 34. deve ser modificado para 34.0 ou 34). Em segundo lugar, ao usar notação científica, o expoente e não deve seguir imediatamente o ponto decimal (isto é, 3.e3 deve ser modificado para 3.0e3 ou 3e3). Finalmente, uma string vazia não é mais considerada JSON válido.

Função interna falha em caso de estouro

Antes, funções internas silenciosamente truncavam números produzidos por coerções de pontos flutuantes para inteiros quando o ponto flutuante era grande demais para ser representado como um inteiro. Agora um E_WARNING será emitido e null será retornado.

Ajustes nos valores retornados pelo manipulador de sessão customizado

Quaisquer funções de predicado implementadas por manipuladores de sessões customizadas que retornem false ou -1 resultarão em erros fatais. Se qualquer valor retornado destas funções não é um booleano, -1 ou 0, então ela irá falhar e um E_WARNING será emitido.

Ordenações de elementos iguais

O algoritmo interno de ordenação foi melhorado, o que pode resultar em diferentes ordenações de elementos, que são comparados como iguais, do que antes.

Nota:

Não confie na ordem de elementos que são comparados como iguais; ela pode mudar a qualquer momento.

Instruções break e continue deslocadas

As declarações break e continue fora de um laço ou de uma estrutura de controle switch, agora são detectados em tempo de compilação em vez de tempo de execução como antes, e dispara um erro E_COMPILE_ERROR.

Mhash não é mais uma extensão

A extensão Mhash foi completamente integrada na extensão Hash. Portanto, não é mais possível detectar o suporte à extensão Mhash com extension_loaded(); em vez disso use function_exists(). Além disso, Mhash não é mais informada por get_loaded_extensions() e recursos relacionados.

declare(ticks)

A diretiva declare(ticks) não vaza mais para diferentes unidades de compilação.

User Contributed Notes

There are no user contributed notes for this page.


Novos Recursos

Declarações de tipos escalares

Declarações de tipos escalares vêm em dois sabores: coercivo (padrão) e estrito. Para parâmetros os seguintes tipos agora podem ser forçados (tanto coercivamente quanto estritamente): strings (string), inteiros (int), números de ponto flutuante (float) e booleanos (bool). Eles incrementam os outros tipos introduzidos no PHP 5: nomes de classe, interfaces, array e callable.

<?php
// Modo coercivo
function sumOfInts(int ...$ints)
{
return array_sum($ints);
}

var_dump(sumOfInts(2, '3', 4.1));

O exemplo acima produzirá:

int(9)

Para habilitar o modo estrito, uma única diretiva declare deve ser colocada no topo do arquivo. Isto significa que a rigorosidade de tipificação para escalares é configurada por arquivo. Esta diretiva não afeta somente as declarações de tipo de parâmetros, mas também do tipo de retorno de funções (veja declarações de tipo de retorno), funções internas do PHP e funções de extensões carregadas.

A documentação completa e exemplos de declarações de tipo escalar podem ser encontradas na referência de declaração de tipo .

Declarações de tipo de retorno

O PHP 7 adiciona suporte a declarações de tipo de retorno. Similar às declarações de tipo de argumento as declarações de tipo de retorno especificam o tipo do valor que será retornado por uma função. Os mesmos tipos estão disponíveis para declarações de tipo de retorno assim como estão disponíveis para declarações de tipo de argumentos.

<?php

function arraysSum(array ...$arrays): array
{
return array_map(function(array $array): int {
return array_sum($array);
}, $arrays);
}

print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));

O exemplo acima produzirá:

Array
(
    [0] => 6
    [1] => 15
    [2] => 24
)

A documentação completa e exemplos de declarações de tipo de retorno podem ser encontradas na referência de declarações de tipo de retorno .

Operador de coalescência nula

O operador de coalescência nula (??) foi adicionado como um truque sintático para o caso trivial de precisar usar um ternário em conjunto com a função isset(). Ele retorna o primeiro operando se este existir e não for null; caso contrário retorna o segundo operando.

<?php
// Obtém o valor de $_GET['user'] e retorna 'nobody'
// se ele não existir.
$username = $_GET['user'] ?? 'nobody';
// Isto equivale a:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// A coalescência pode ser encadeada: isto irá retornar o primeiro
// valor definido entre $_GET['user'], $_POST['user'] e
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Operador "nave espacial" (spaceship)

O operador nave espacial é utilizado para comparar duas expressões. Ele retorna -1, 0 ou 1 quando $a for respectivamente menor que, igual a ou maior que $b. As comparações são feitas de acordo com as já conhecidas regras de comparação de tipos do PHP.

<?php
// Inteiros
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Números de ponto flutuante
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>

Arrays de constantes utilizando a função define()

Constantes do tipo array agora podem ser definidas com a função define(). No PHP 5.6 elas só poderiam ser definidas com const.

<?php
define('ANIMALS', [
'dog',
'cat',
'bird'
]);

echo ANIMALS[1]; // imprime "cat"
?>

Classes anônimas

O suporte a classes anônimas foi adicionado utilizando new class. Estas podem ser utilizadas no lugar de definições completas de classes para objetos descartáveis.

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

O exemplo acima produzirá:

object(class@anonymous)#2 (0) {
}

A documentação completa pode ser encontrada na referência de classes anônimas.

Sintaxe de escape de códigos Unicode

Toma um código Unicode em sua forma hexadecimal e imprime esse código em UTF-8 em uma string delimitada por aspas ou um heredoc. Qualquer código válido é aceito, com os zeros à esquerda sendo opcionais.

echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";

O exemplo acima produzirá:

ª
ª (o mesmo que antes mas com os zeros à esquerda opcionais)
?

Closure::call()

O método Closure::call() é uma forma mais eficaz e abreviada de associar temporariamente um escopo de objeto a uma closure e invocá-la.

<?php
class A {private $x = 1;}

// Código anterior ao PHP 7
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, 'A'); // intermediate closure
echo $getX();

// Código do PHP 7+
$getX = function() {return $this->x;};
echo $getX->call(new A);

O exemplo acima produzirá:

1
1

unserialize() filtrado

Esse recurso busca prover uma melhor segurança ao desserializar objetos com informações não confiáveis. Ele impede possíveis injeções de código ao permitir que o desenvolvedor liste as classes que podem ser desserializadas.

<?php

// converte todos os objetos em objetos __PHP_Incomplete_Class
$data = unserialize($foo, ["allowed_classes" => false]);

// converte todos os objetos em objetos __PHP_Incomplete_Class exceto aqueles de MyClass e MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]]);

// comportamento padrão (o mesmo que omitir o segundo argumento) que aceita todas as classes
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar

A nova classe IntlChar busca expor funcionalidades adicionais da ICU. A classe define alguns métodos estáticos e constantes que podem ser utilizados para manipular caracteres Unicode.

<?php

printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));

O exemplo acima produzirá:

10ffff
COMMERCIAL AT
bool(true)

Para utilizar esta classe a extensão Intl deve estar instalada.

Expectations

Expectations são aprimoramentos compatíveis com versões anteriores para a antiga função assert(). Permitem asserções com custo zero em código em produção e fornecem a capacidade de lançar exceções personalizadas quando a asserção falha.

Enquanto a API antiga continua sendo mantida por motivos de compatibilidade, assert() agora é um construtor de linguagem, permitindo que o primeiro parâmetro seja uma expressão, em vez de somente uma string a ser avaliada ou um valor bool a ser testado.

<?php
ini_set('assert.exception', 1);

class CustomError extends AssertionError {}

assert(false, new CustomError('Alguma mensagem de erro'));
?>

O exemplo acima produzirá:

Fatal error: Uncaught CustomError: Alguma mensagem de erro

Mais detalhes sobre este recurso, incluindo como configurá-lo tanto no ambiente de desenvolvimento quanto em produção, podem ser encontrados no pagina do manual do construtor de linguagem assert();

Agrupamento de declarações use

Classes, funções e constantes importadas do mesmo namespace, agora podem ser agrupadas em uma única declaração use

<?php
// Código anterior ao PHP 7
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;

use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// Código do PHP 7+
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
?>

Expressões de Retorno nos Geradores

Este recurso foi construído em cima da funcionalidade de geradores introduzida no PHP 5.5. Ele permite que uma declaração return seja usada dentro de um gerador para permitir que uma expressão final seja retornada (retornar por referência não é permitido). Este valor pode ser obtido usando o novo método Generator::getReturn(), que deve ser usado somente quando o gerador terminar a geração dos valores.

<?php

$gen = (function() {
yield 1;
yield 2;

return 3;
})();

foreach ($gen as $val) {
echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

O exemplo acima produzirá:

1
2
3

A habilidade de retornar explicitamente o valor final de um gerador é conveniente de se ter. Ela permite que o retorno do valor final do gerador (pode ser de uma computação concorrente) possa ser manipulado especificamente pelo código cliente que executa o gerador. Isso é bem mais simples que forçar o código cliente a primeiro checar se o valor final já foi gerado, e em caso afirmativo, manipular esse valor especificamente.

Delegação de geradores

Geradores agora podem delegar para outros geradores, objetos Traversable ou array automaticamente, sem a necessidade de escrever código repetitivo no gerador externo utilizando o construtor 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;
}
?>

O exemplo acima produzirá:

1
2
3
4

Divisão de inteiros com intdiv()

A nova função intdiv() realiza a divisão de inteiros de seus operandos e a retorna.

<?php
var_dump(intdiv(10, 3));
?>

O exemplo acima produzirá:

int(3)

Opções de sessões

A função session_start() agora aceita um array de opções que sobrescrevem as diretivas de configuração de sessões normalmente configuradas no php.ini.

Estas opções também foram expandidas para suportar session.lazy_write, que está habilitada por padrão e faz com que o PHP somente sobrescreva um arquivo de sessão se a informação da sessão foi modificada, e read_and_close, que é uma opção que só pode ser passada para a função session_start() para indicar que os dados da sessão devem ser lidos e, em seguida, a sessão deve ser imediatamente fechada sem alterações.

Por exemplo, para configurar session.cache_limiter para private e fechar imediatamente a sessão após lê-la:

<?php
session_start([
'cache_limiter' => 'private',
'read_and_close' => true,
]);
?>

preg_replace_callback_array()

A nova função preg_replace_callback_array() permite que o código seja escrito de forma mais limpa com a utilização da função preg_replace_callback(). Antes do PHP 7, callbacks que precisam ser executadas por expressões regulares exigiam que a função de callback fosse poluída com muitas ramificações.

Agora, funções de callback podem ser registradas em cada expressão regular utilizando um array associativo, onde a chave é uma expressão regular e o valor é uma função de callback.

Funções CSPRNG

Duas novas funções foram adicionadas para gerar inteiros e strings criptograficamente seguros de maneira multiplataforma: random_bytes() e random_int().

A função list() pode sempre desempacotar objetos que implementam ArrayAccess

Antes a função list() não garantia corretude em operações com objetos que implementam ArrayAccess. Isso foi corrigido.

Outros Recursos

  • Acesso a membros de classe na clonagem foi adicionado, por exemplo, (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


Recursos depreciados no PHP 7.0.x

Construtores ao estilo PHP 4

Construtores ao estilo PHP 4 (métodos que têm o mesmo nome que a classe onde estão definidos) estão depreciados, e será removido no futuro. O PHP 7 emitirá E_DEPRECATED se um construtor do PHP 4 for o único construtor definido na classe. Classes que implementam o método __construct() não são afetadas.

<?php
class foo {
function foo() {
echo 'Eu sou um construtor';
}
}
?>

O exemplo acima produzirá:

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

Chamadas estáticas a métodos não estáticos

Chamadas estáticas a métodos que não foram declarados como static estão depreciados, e podem ser removidos no futuro.

<?php
class foo {
function bar() {
echo 'Eu não sou estático!';
}
}

foo::bar();
?>

O exemplo acima produzirá:

Deprecated: Non-static method foo::bar() should not be called statically in - on line 8
I am not static!

Opção salt da função password_hash()

A opção salt da função password_hash() foi depreciada para evitar que desenvolvedores gerem seus próprios salts(geralmente inseguro). A função gerará um salt criptográfico seguro quando um salt não for fornecido pelo desenvolvedor - portanto a geração customizada de salts não é necessária.

Opção de contexto SSL na função capture_session_meta

A opção de contexto SSL capture_session_meta foi depreciada. Metadados SSL agora estão disponíveis através da função stream_get_meta_data().

Depreciações no LDAP

As funções a seguir foram depreciadas:

  • ldap_sort()

User Contributed Notes

There are no user contributed notes for this page.


Funções alteradas

Núcleo do PHP

  • debug_zval_dump() agora imprime "int" ao invés de "long" e "float" ao invés de "double".
  • dirname() agora opcionalmente recebe um segundo parâmetro, depth, para obter o nome do diretório depth níveis acima do diretório atual.
  • getrusage() agora é suportada no Windows.
  • As funções mktime() e gmmktime() não aceitam mais o parâmetro is_dst (é horário de verão).
  • A função preg_replace() não suporta mais o modificador "\e" (PREG_REPLACE_EVAL). Em vez disso, a função preg_replace_callback() deve ser usada.
  • A função setlocale() não aceita mais o parâmetro category passado como string. Em vez disso, as constantes LC_* devem ser usadas.
  • As funções exec(), system() e passthru() agora possuem proteção contra bytes nulos.
  • A função shmop_open() agora retorna um recurso ao invés de um inteiro, que deve ser passado para as funções shmop_size(), shmop_write(), shmop_read(), shmop_close() e shmop_delete().
  • As funções substr() e iconv_substr() agora retornam uma string vazia caso o comprimento do parâmetro string seja igual ao valor do parâmetro start.
  • xml_parser_free() não é mais suficiente para liberar o recurso parser, se ele faz referência a um objeto e este objeto faz referência a esse recurso parser. Neste caso, é necessário, adicionalmente, indeterminar o $parser.

User Contributed Notes

There are no user contributed notes for this page.


Novas funções

Closure

  • Closure::call()

CSPRNG

  • random_bytes()
  • random_int()

Manipulação e Registro de erros

  • error_clear_last()

Generator

  • Generator::getReturn()

GNU Multiple Precision

  • gmp_random_seed()

Math

  • intdiv()

PCRE

  • preg_replace_callback_array()

Opções PHP/Informações

  • gc_mem_caches()
  • get_resources()

POSIX

  • posix_setrlimit()

Reflection

  • ReflectionParameter::getType()
  • ReflectionParameter::hasType()
  • ReflectionFunctionAbstract::getReturnType()
  • ReflectionFunctionAbstract::hasReturnType()

Zip

  • ZipArchive::setCompressionIndex()
  • ZipArchive::setCompressionName()

Compressão Zlib

  • inflate_add()
  • deflate_add()
  • inflate_init()
  • deflate_init()

User Contributed Notes

There are no user contributed notes for this page.


Novas Classes e Interfaces

Intl

  • IntlChar

Reflexão

  • ReflectionGenerator
  • ReflectionType

Manipulação de Sessão

  • SessionUpdateTimestampHandlerInterface

Hierarquia de Exceções

  • Throwable
  • Error
  • TypeError
  • ParseError
  • AssertionError
  • ArithmeticError
  • DivisionByZeroError

User Contributed Notes

There are no user contributed notes for this page.


Novas Constantes Globais

Constantes Predefinidas do Núcleo

  • PHP_INT_MIN

GD

  • IMG_WEBP (a partir do 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.


Modificações nos Módulos SAPI

FPM

Portas de listen não qualificadas agora escutam IPv4 e IPv6

No PHP 5, uma diretiva listen com somente um número de porta escutaria em todas interfaces, mas somente no IPv4. O PHP aceitará requisições feitas tanto via IPv4 quanto IPv6.

Isso não afeta diretivas que incluem endereços de IP específicos; estas continuarão a escutar somente no endereço e protocolo especificados.

User Contributed Notes

There are no user contributed notes for this page.


Extensões e SAPIs removidas

Extensões removidas

  • ereg
  • mssql
  • mysql
  • sybase_ct

SAPIs removidas

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


Outras mudanças

Abertura nas restrições de palavras reservadas

Palavras reservadas globalmente agora são permitidas como nomes de propriedades, constante e métodos dentro de classes, interfaces e traits. Isso reduz o aspecto de quebras no BC quando novas palavras-chave são introduzidas e evita restrições de nomes em APIS.

Isso é particularmente útil quando estiver criando DSLs com interfaces fluentes:

<?php
// 'new', 'private', e 'for' eram proibidas
Project::new('Project Name')->private()->for('purpose here')->with('username here');
?>

A única limitação é que a palavra-chave class continua não podendo ser utilizada como nome de constante, caso contrário conflitará com a sintaxe de resolução de nomes de classe (ClassName::class).

Remoção do aviso do date.timezone

Anteriormente, um aviso era emitido se a configuração INI date.timezone não havia sido definida antes de utilizar qualquer função de data ou tempo. Agora, este aviso foi removido (com a diretiva date.timezone padronizada para UTC).

User Contributed Notes

There are no user contributed notes for this page.


Migrando do PHP 5.5.x para o PHP 5.6.x

Índice

  • Backward incompatible changes
  • New features
  • Deprecated features in PHP 5.6.x
  • Changed functions
  • New functions
  • OpenSSL changes in PHP 5.6.x
  • Other changes to extensions
  • Novas constantes globais

A maioria das melhorias no PHP 5.6.x não tem impacto no código existente. Existem algumas incompatibilidades e novas funcionalidades que devem ser consideradas, e o codigo deve ser testado antes de alterar a versão do PHP nos ambientes de produção.

User Contributed Notes

There are no user contributed notes for this page.


Backward incompatible changes

Although most existing PHP 5 code should work without changes, please take note of some backward incompatible changes:

Array keys won't be overwritten when defining an array as a property of a class via an array literal

Previously, arrays declared as class properties which mixed explicit and implicit keys could have array elements silently overwritten if an explicit key was the same as a sequential implicit key. For example:

<?php
class C {
const ONE = 1;
public $array = [
self::ONE => 'foo',
'bar',
'quux',
];
}

var_dump((new C)->array);
?>

Saída do exemplo acima no PHP 5.5:

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

Saída do exemplo acima no PHP 5.6:

array(3) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(4) "quux"
}

json_decode() strictness

json_decode() now rejects non-lowercase variants of the JSON literals true, false and null at all times, as per the JSON specification, and sets json_last_error() accordingly. Previously, inputs to json_decode() that consisted solely of one of these values in upper or mixed case were accepted.

This change will only affect cases where invalid JSON was being passed to json_decode(): valid JSON input is unaffected and will continue to be parsed normally.

Stream wrappers now verify peer certificates and host names by default when using SSL/TLS

Todos os streams criptografados de cliente agora permitem a verificação de mesmo nível por padrão. Por padrão, será usada a coleção de CAs padrão do OpenSSL para verificar o certificado de mesmo nível. Na maioria dos casos, nenhuma alteração precisará ser feita para se comunicar com servidores com certificados SSL válidos, pois as distribuições geralmente configuram o OpenSSL com coleções de CAs bem conhecidos.

A coleção de CAs padrão pode ser substituída globalmente definindo a configuração openssl.cafile ou openssl.capath, ou por requisição usando as opções de contexto cafile ou capath.

Embora em geral não seja recomendado, é possível desabilitar a verificação de certificado de mesmo nível para uma requisição definindo a opção de contexto verify_peer para false e é possível desabilitar a verificação de nome de mesmo nível definindo a opção de contexto verify_peer_name para false.

GMP resources are now objects

GMP resources are now objects. The functional API implemented in the GMP extension has not changed, and code should run unmodified unless it checks explicitly for a resource using is_resource() or similar.

Mcrypt functions now require valid keys and IVs

mcrypt_encrypt(), mcrypt_decrypt(), mcrypt_cbc(), mcrypt_cfb(), mcrypt_ecb(), mcrypt_generic() and mcrypt_ofb() will no longer accept keys or IVs with incorrect sizes, and block cipher modes that require IVs will now fail if an IV isn't provided.

cURL file uploads

Uploads using the @file syntax now require CURLOPT_SAFE_UPLOAD to be set to false. CURLFile should be used instead.

User Contributed Notes

There are no user contributed notes for this page.


New features

Constant expressions

It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts where PHP previously expected a static value, such as constant and property declarations and default function arguments.

<?php
const ONE = 1;
const TWO = ONE * 2;

class C {
const THREE = TWO + 1;
const ONE_THIRD = ONE / self::THREE;
const SENTENCE = 'The value of THREE is '.self::THREE;

public function f($a = ONE + self::THREE) {
return $a;
}
}

echo (new C)->f()."\n";
echo C::SENTENCE;
?>

O exemplo acima produzirá:

4
The value of THREE is 3

It is also now possible to define a constant array using the const keyword:

<?php
const ARR = ['a', 'b'];

echo ARR[0];
?>

O exemplo acima produzirá:

a

Variadic functions via ...

Variadic functions can now be implemented using the ... operator, instead of relying on func_get_args().

<?php
function f($req, $opt = null, ...$params) {
// $params is an array containing the remaining arguments.
printf('$req: %d; $opt: %d; number of params: %d'."\n",
$req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);
?>

O exemplo acima produzirá:

$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params: 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2
$req: 1; $opt: 2; number of params: 3

Argument unpacking via ...

Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ... operator. This is also known as the splat operator in other languages, including Ruby.

<?php
function add($a, $b, $c) {
return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);
?>

O exemplo acima produzirá:

6

Exponentiation via **

A right associative ** operator has been added to support exponentiation, along with a **= shorthand assignment operator.

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

O exemplo acima produzirá:

2 ** 3 ==      8
2 ** 3 ** 2 == 512
a ==           8

use function and use const

The use operator has been extended to support importing functions and constants in addition to classes. This is achieved via the use function and use const constructs, respectively.

<?php
namespace Name\Space {
const FOO = 42;
function f() { echo __FUNCTION__."\n"; }
}

namespace {
use const Name\Space\FOO;
use function Name\Space\f;

echo FOO."\n";
f();
}
?>

O exemplo acima produzirá:

42
Name\Space\f

phpdbg

PHP now includes an interactive debugger called phpdbg implemented as a SAPI module. For more information, please visit the phpdbg documentation.

Default character encoding

default_charset is now used as the default character set for the htmlentities(), html_entity_decode() and htmlspecialchars() functions. Note that if the (now deprecated) iconv and mbstring encoding settings are set, they will take precedence over default_charset for iconv and mbstring functions, respectively.

The default value for this setting is UTF-8.

php://input is reusable

php://input may now be reopened and read as many times as required. This work has also resulted in a major reduction in the amount of memory required to deal with POST data.

Large file uploads

Files larger than 2 gigabytes in size are now accepted.

GMP supports operator overloading

GMP objects now support operator overloading and casting to scalar types. This allows for more expressive code using 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;
}
?>

O exemplo acima produzirá:

59
59
59

hash_equals() for timing attack safe string comparison

The hash_equals() function has been added to compare two strings in constant time. This should be used to mitigate timing attacks; for instance, when testing crypt() password hashes (assuming that you are unable to use password_hash() and password_verify(), which aren't susceptible to timing attacks).

<?php
$expected = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('1234', '$2a$07$usesomesillystringforsalt$');

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
?>

O exemplo acima produzirá:

bool(true)
bool(false)

__debugInfo()

The __debugInfo() magic method has been added to allow objects to change the properties and values that are shown when the object is output using 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));
?>

O exemplo acima produzirá:

object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}

gost-crypto hash algorithm

The gost-crypto hash algorithm has been added. This implements the GOST hash function using the CryptoPro S-box tables as specified by » RFC 4357, section 11.2.

SSL/TLS improvements

A wide range of improvements have been made to the SSL/TLS support in PHP 5.6. These include enabling peer verification by default, supporting certificate fingerprint matching, mitigating against TLS renegotiation attacks, and many new SSL context options to allow more fine grained control over protocol and verification settings when using encrypted streams.

These changes are described in more detail in the OpenSSL changes in PHP 5.6.x section of this migration guide.

pgsql async support

The pgsql extension now supports asynchronous connections and queries, thereby enabling non-blocking behaviour when interacting with PostgreSQL databases. Asynchronous connections may be established via the PGSQL_CONNECT_ASYNC constant, and the new pg_connect_poll(), pg_socket(), pg_consume_input() and pg_flush() functions may be used to handle asynchronous connections and queries.

User Contributed Notes

There are no user contributed notes for this page.


Deprecated features in PHP 5.6.x

Calls from incompatible context

Methods called from an incompatible context are now deprecated, and will generate E_DEPRECATED errors when invoked instead of E_STRICT. Support for these calls will be removed in a future version of PHP.

An example of such a call is:

<?php
class A {
function f() { echo get_class($this); }
}

class B {
function f() { A::f(); }
}

(new B)->f();
?>

O exemplo acima produzirá:

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 and always_populate_raw_post_data

always_populate_raw_post_data will now generate an E_DEPRECATED error when $HTTP_RAW_POST_DATA is populated. New code should use php://input instead of $HTTP_RAW_POST_DATA, which will be removed in a future release. You can opt in for the new behaviour (in which $HTTP_RAW_POST_DATA is never defined hence no E_DEPRECATED error will be generated) by setting always_populate_raw_post_data to -1.

iconv and mbstring encoding settings

The iconv and mbstring configuration options related to encoding have been deprecated in favour of default_charset. The deprecated options are:

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


Changed functions

PHP Core

  • crypt() will now raise an E_NOTICE error if the salt parameter is omitted.
  • substr_compare() will now accept 0 for its length parameter.
  • unserialize() will now fail if passed serialised data that has been manipulated to attempt to instantiate an object without calling its constructor.

cURL

  • Uploads using the @file syntax are now only supported if the CURLOPT_SAFE_UPLOAD option is set to false. CURLFile should be used instead.

Mcrypt

  • The source parameter of mcrypt_create_iv() now defaults to MCRYPT_DEV_URANDOM instead of MCRYPT_DEV_RANDOM.

OpenSSL

  • stream_socket_enable_crypto() now allows the crypto_type parameter to be optional if the stream's SSL context includes the new crypto_type option.

PostgreSQL

  • pg_insert(), pg_select(), pg_update() and pg_delete() are no longer experimental.
  • pg_send_execute(), pg_send_prepare(), pg_send_query() and pg_send_query_params() will no longer block until query write completion if the underlying socket stream for the database connection is set to non-blocking mode.

Reflection

  • ReflectionClass::newInstanceWithoutConstructor() now allows non-final internal classes to be instantiated.

XMLReader

  • XMLReader::getAttributeNs() and XMLReader::getAttributeNo() now return null if the attribute could not be found, like XMLReader::getAttribute().

User Contributed Notes

There are no user contributed notes for this page.


New functions

Date and Time

  • DateTimeImmutable::createFromMutable()

GMP

  • gmp_root()
  • gmp_rootrem()

Hash

  • hash_equals()

LDAP

  • ldap_escape()
  • ldap_modify_batch()

MySQLi

  • mysqli_get_links_stats()

OCI8

  • oci_get_implicit_resultset()

OpenSSL

  • openssl_get_cert_locations()
  • openssl_x509_fingerprint()
  • openssl_spki_new()
  • openssl_spki_verify()
  • openssl_spki_export_challenge()
  • openssl_spki_export()

PostgreSQL

  • pg_connect_poll()
  • pg_consume_input()
  • pg_flush()
  • pg_socket()

PDO_PGSQL

  • PDO::pgsqlGetNotify()
  • PDO::pgsqlGetPid()

Session

  • session_abort()
  • session_reset()

Zip

  • ZipArchive::setPassword()

User Contributed Notes

There are no user contributed notes for this page.


OpenSSL changes in PHP 5.6.x

Stream wrappers now verify peer certificates and host names by default when using SSL/TLS

Todos os streams criptografados de cliente agora permitem a verificação de mesmo nível por padrão. Por padrão, será usada a coleção de CAs padrão do OpenSSL para verificar o certificado de mesmo nível. Na maioria dos casos, nenhuma alteração precisará ser feita para se comunicar com servidores com certificados SSL válidos, pois as distribuições geralmente configuram o OpenSSL com coleções de CAs bem conhecidos.

A coleção de CAs padrão pode ser substituída globalmente definindo a configuração openssl.cafile ou openssl.capath, ou por requisição usando as opções de contexto cafile ou capath.

Embora em geral não seja recomendado, é possível desabilitar a verificação de certificado de mesmo nível para uma requisição definindo a opção de contexto verify_peer para false e é possível desabilitar a verificação de nome de mesmo nível definindo a opção de contexto verify_peer_name para false.

Certificate fingerprints

Support has been added for extracting and verifying certificate fingerprints. openssl_x509_fingerprint() has been added to extract a fingerprint from an X.509 certificate, and two SSL stream context options have been added: capture_peer_cert to capture the peer's X.509 certificate, and peer_fingerprint to assert that the peer's certificate should match the given fingerprint.

Default ciphers updated

The default ciphers used by PHP have been updated to a more secure list based on the » Mozilla cipher recommendations, with two additional exclusions: anonymous Diffie-Hellman ciphers, and RC4.

This list can be accessed via the new OPENSSL_DEFAULT_STREAM_CIPHERS constant, and can be overridden (as in previous PHP versions) by setting the ciphers context option.

Compression disabled by default

SSL/TLS compression has been disabled by default to mitigate the CRIME attack. PHP 5.4.13 added a disable_compression context option to allow compression to be disabled: this is now set to true (that is, compression is disabled) by default.

Allow servers to prefer their cipher order

The honor_cipher_order SSL context option has been added to allow encrypted stream servers to mitigate BEAST vulnerabilities by preferring the server's ciphers to the client's.

Access the negotiated protocol and cipher

The protocol and cipher that were negotiated for an encrypted stream can now be accessed via stream_get_meta_data() or stream_context_get_options() when the capture_session_meta SSL context option is set to true.

<?php
$ctx = stream_context_create(['ssl' => [
'capture_session_meta' => TRUE
]]);

$html = file_get_contents('https://google.com/', FALSE, $ctx);
$meta = stream_context_get_options($ctx)['ssl']['session_meta'];
var_dump($meta);
?>

O exemplo acima produzirá:

array(4) {
  ["protocol"]=>
  string(5) "TLSv1"
  ["cipher_name"]=>
  string(20) "ECDHE-RSA-AES128-SHA"
  ["cipher_bits"]=>
  int(128)
  ["cipher_version"]=>
  string(11) "TLSv1/SSLv3"
}

New options for perfect forward secrecy in encrypted stream servers

Encrypted client streams already support perfect forward secrecy, as it is generally controlled by the server. PHP encrypted server streams using certificates capable of perfect forward secrecy do not need to take any additional action to enable PFS; however a number of new SSL context options have been added to allow more control over PFS and deal with any compatibility issues that may arise.

ecdh_curve

This option allows the selection of a specific curve for use with ECDH ciphers. If not specified, prime256v1 will be used.

dh_param

A path to a file containing parametrs for Diffie-Hellman key exchange, such as that created by the following command:

openssl dhparam -out /path/to/my/certs/dh-2048.pem 2048
single_dh_use

If set to true, a new key pair will be created when using Diffie-Hellman parameters, thereby improving forward secrecy.

single_ecdh_use

If set to true, a new key pair will always be generated when ECDH cipher suites are negotiated. This improves forward secrecy.

SSL/TLS version selection

It is now possible to select specific versions of SSL and TLS via the crypto_method SSL context option or by specifying a specific transport when creating a stream wrapper (for example, by calling stream_socket_client() or stream_socket_server()).

The crypto_method SSL context option accepts a bitmask enumerating the protocols that are permitted, as does the crypto_type of stream_socket_enable_crypto().

Selected protocol versions and corresponding options
Protocol(s) | Client flag | Server flag | Transport
Any TLS or SSL version | STREAM_CRYPTO_METHOD_ANY_CLIENT | STREAM_CRYPTO_METHOD_ANY_SERVER | ssl://
Any TLS version | STREAM_CRYPTO_METHOD_TLS_CLIENT | STREAM_CRYPTO_METHOD_TLS_SERVER | tls://
TLS 1.0 | STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_0_SERVER | tlsv1.0://
TLS 1.1 | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | tlsv1.1://
TLS 1.2 | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_SERVER | tlsv1.2://
SSL 3 | STREAM_CRYPTO_METHOD_SSLv3_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_SERVER | sslv3://
<?php

// Requiring TLS 1.0 or better when using file_get_contents():
$ctx = stream_context_create([
'ssl' => [
'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Requiring TLS 1.1 or 1.2:
$ctx = stream_context_create([
'ssl' => [
'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT |
STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Connecting using the tlsv1.2:// stream socket transport.
$sock = stream_socket_client('tlsv1.2://google.com:443/');

?>

openssl_get_cert_locations() added

The openssl_get_cert_locations() function has been added: it returns the default locations PHP will search when looking for CA bundles.

<?php
var_dump(openssl_get_cert_locations());
?>

O exemplo acima produzirá:

array(8) {
  ["default_cert_file"]=>
  string(21) "/etc/pki/tls/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(18) "/etc/pki/tls/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(20) "/etc/pki/tls/private"
  ["default_default_cert_area"]=>
  string(12) "/etc/pki/tls"
  ["ini_cafile"]=>
  string(0) ""
  ["ini_capath"]=>
  string(0) ""
}

SPKI support

Support has been added for generating, extracting and verifying signed public key and challenges (SPKAC). openssl_spki_new(), openssl_spki_verify(), openssl_spki_export_challenge(), and openssl_spki_export() have been added to create, verify export PEM public key and associated challenge from SPKAC's generated from a KeyGen HTML5 element.

openssl_spki_new

Generates a new SPKAC using private key, challenge string and hashing algorithm.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
?>

O exemplo acima produzirá:

SPKAC=MIIBXjCByDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3L0IfUijj7+A8CPC8EmhcdNoe5fUAog7OrBdhn7EkxFButUp40P7+LiYiygYG1TmoI/a5EgsLU3s9twEz3hmgY9mYIqb/rb+SF8qlD/K6KVyUORC7Wlz1Df4L8O3DuRGzx6/+3jIW6cPBpfgH1sVuYS1vDBsP/gMMIxwTsKJ4P0CAwEAARYkYjViMzYxMTktNjY5YS00ZDljLWEyYzctMGZjNGFhMjVlMmE2MA0GCSqGSIb3DQEBAwUAA4GBAF7hu0ifzmjonhAak2FhhBRsKFDzXdKIkrWxVNe8e0bZzMrWOxFM/rqBgeH3/gtOUDRS5Fnzyq425UsTYbjfiKzxGeCYCQJb1KJ2V5Ij/mIJHZr53WYEXHQTNMGR8RPm7IxwVXVSHIgAfXsXZ9IXNbFbcaLRiSTr9/N4U+MXUWL7
openssl_spki_verify

Verifies provided SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
var_dump(openssl_spki_verify($spkac));
?>
openssl_spki_export_challenge

Exports associated challenge from provided SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
$challenge = openssl_spki_export_challenge($spkac);
echo $challenge;
?>

O exemplo acima produzirá:

challenge string
openssl_spki_export

Exports the PEM formatted RSA public key from SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
echo openssl_spki_export($spkac);
?>

O exemplo acima produzirá:

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


Other changes to extensions

cURL

A number of constants marked obsolete in the cURL library have now been removed:

  • CURLOPT_CLOSEPOLICY
  • CURLCLOSEPOLICY_CALLBACK
  • CURLCLOSEPOLICY_LEAST_RECENTLY_USED
  • CURLCLOSEPOLICY_LEAST_TRAFFIC
  • CURLCLOSEPOLICY_OLDEST
  • CURLCLOSEPOLICY_SLOWEST

OCI8

  • Support for implicit result sets for Oracle Database 12c has been added via the new oci_get_implicit_resultset() function.
  • Using oci_execute($s, OCI_NO_AUTO_COMMIT) for a SELECT no longer unnecessarily initiates an internal ROLLBACK during connection close.
  • Added DTrace probes controlled by the --enable-dtrace configure option.
  • oci_internal_debug() is now a no-op.
  • The phpinfo() output format for OCI8 has changed.

Zip

A --with-libzip configure option has been added to use a system libzip installation. libzip version 0.11 is required, with 0.11.2 or later recommended.

MySQLi

A new mysqli.rollback_on_cached_plink option was added, which controls the rollback behavior of persistent connections.

User Contributed Notes

There are no user contributed notes for this page.


Novas constantes globais

GD

  • IMG_WEBP (a partir do 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.


Depurando em PHP

Índice

  • Sobre o depurador em 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 o depurador em PHP

O PHP vem equipado com um depurador básico em linha de comando, phpdbg.

A maioria das IDE tem suporte para o » Xdebug, uma ferramenta livre de debug, que permite analisar as aplicações PHP passo a passo.

User Contributed Notes

There are no user contributed notes for this page.


Opções do script Configure

Índice

  • Lista de opções do script configure

User Contributed Notes

There are no user contributed notes for this page.


Lista de opções do script configure

Abaixo está a lista parcial das opções do script configure usado pelo PHP quando compilando o mesmo em ambientes Unix-like. A maioria das opções de configuração está listada na página de referência da extensão e não aqui. Para uma lista atualizada e completa das opções do script configure, execute ./configure --help no diretórios dos fontes do PHP após executar autoconf (veja também o capítulo de Instalação). Você pode também se interessar em ler a documentação do » GNU configure para obter informações em opções adicionais do configure tais como --prefix=PREFIX.

Nota:

Essas opções são utilizadas apenas em tempo de compilação. Se você quiser alterar a configuração do PHP em tempo de execução, por favor, veja o capítulo de Configuração em tempo de execução.

  • Miscelânea
  • Comportamento do PHP
  • Servidor

Opções do Configuração do PHP

Opções Mistas

--enable-debug

Compila com símbolos para depuração.

--with-layout=TYPE

Configura a disposição dos arquivos instalados. Type pode ser PHP (padrão) ou GNU. Note que instalar manpages sob o prefixo PREFIX (default), utilize o estilo GNU de forma que estas páginas possam ser encontradas pelo utilitário manpath.

--with-pear=DIR

Instala o PEAR em DIR (padrão é PREFIX/lib/php).

--without-pear

Não instala o PEAR.

--enable-sigchild

Permite que o PHP tenha um tratador de SIGCHLD próprio.

--disable-rpath

Desabilita a passagem de caminhos adicionais onde busca por bibliotecas em tempo de execução.

--enable-libgcc

Habilita montar explicitamente com a libgcc.

--enable-php-streams

Inclui fluxos de dados (streams) experimentais do PHP. Não use a não ser que esteja testando o código!

--with-zlib-dir[=DIR]

Define a localização do diretório onde a zlib está instalada.

--with-tsrm-pthreads

Use threads POSIX (padrão).

--enable-shared[=PKGS]

Monta bibliotecas compartilhadas [padrão=yes].

--enable-static[=PKGS]

Monta bibliotecas estáticas [padrão=yes].

--enable-fast-install[=PKGS]

Optimiza para instalação rápida [padrão=yes].

--with-gnu-ld

Presume que o compilador C usa o GNU ld [padrão=no].

--disable-libtool-lock

Evita travamento (pode quebrar compilações rodando em paralelo).

--with-pic

Tenta usar apenas objetos PIC/não-PIC [padrão=use both].

--enable-versioning

Exporta apenas os símbolos necessários. Veja o arquivo INSTALL para mais informações.

Opções do PHP

--enable-maintainer-mode

Habilita criar regras e dependências que não são úteis (e algumas vezes confusas) para o instalador casual.

--with-config-file-path=PATH

Edita o caminho no qual deve procurar pelo arquivo php.ini, padrão é PREFIX/lib.

--disable-short-tags

Desabilita a forma comprimida de tag inicial <? por padrão.

--with-libdir

Especifica o diretório onde as bibliotecas necessárias para compilar o PHP se encontram em um sistema UNIX. Para sistemas 64bit, é necessário especificar o diretório lib64 desta forma: --with-libdir=lib64.

--enable-zts

Ativa segurança de thread. Anteriormente ao PHP 8.0.0 em sistemas não Windows, essa opção era chamada --enable-maintainer-zts.

Opções SAPI

A lista a seguir contêm as SAPI&s (Server Application Programming Interface) para o PHP.

--with-apxs[=FILE]

Compila o módulo compartilhado do Apache. FILE é o caminho opcional para a ferramenta apxs do Apache; padrão é apxs. Assegure-se que você especificou a versão do apxs que está atualmente instalado no seu sistema e não a que está no diretório de fontes do Apache.

--with-apache[=DIR]

Compila o módulo estático do Apache. DIR é o diretório raíz do apache, sendo que o padrão é /usr/local/apache.

--with-mod_charset

Habilita as tabelas de transferência para o mod_charset (Apache Russo).

--with-apxs2[=FILE]

Compila o módulo compartilhado do Apache 2.0. FILE é o caminho opcional para a ferramenta apxs do Apache; sendo o padrão para o apxs.

--disable-cli

Para desabilitar a utilização do PHP na linha de comando (CLI) poderá utilizar a diretiva --without-pear). Para mais informações leia sobre Utilizando o PHP a partir da linha de comando (CLI)..

--enable-phpdbg

Ativa o debug interativo phpdbg no módulo SAPI.

--enable-embed[=TYPE]

Habilita a instalação da biblioteca SAPI embutida. TYPE pode ser shared ou static, sendo o padrão shared.

--with-servlet[=DIR]

Inclue o suporte à servlet. DIR é o diretório base de instalação para a JSDK. Esse SAPI requer que a extensão java seja montada como uma dl compartilhada.

--disable-cgi

Desabilita a compilação da versão CGI do PHP.

Este argumento também habilita o FastCGI.

User Contributed Notes

atesin () gmail ! com 04-Feb-2021 08:55
i'll answer myself (FINALLY!)

current "configure options" can be viewed with "php-config" shell script, aside with other compile time options too =D!!! ...

in some distributions it comes with the "php-devel" package... but until in this online manual "php-config" is mentioned in pecl extensions documentation (i couldn't find on pecl site), idk if that "php-devel" has something to do with this

... however i noticed they are literal strings inside the script, i hope the script itself were built together with php compilation o_O

in the previous page "configure options" (link shown above ^), there is an editor note with additional info about it
atesin () gmail ! com 04-Feb-2021 02:38
please somebody tell me how to display configure options used in php actual binary

it was shown in phpinfo() some years before, it was very useful, specially with 'phpize' recompilation and to enable some pecl/pear module :/

please tell me also which ctriteria had php guys used to suddenly decided to hide (or obfuscate) this info :/

thanks in advance


php.ini directives

Índice

  • Lista de diretivas do php.ini
  • Lista das seções do php.ini
  • Descrição das principais diretivas do php.ini

User Contributed Notes

There are no user contributed notes for this page.


Lista de diretivas do php.ini

Esta lista inclui as diretivas do php.ini que você pode configurar na sua instalação PHP.

A coluna "Modificável" mostra os modos que determinam quando e onde uma diretiva pode ser definida. Veja a seção valores modificáveis para as suas definições.

Opções de configuração
Nome | Padrão | Modificável | Changelog
allow_url_fopen | "1" | PHP_INI_SYSTEM |
allow_url_include | "0" | PHP_INI_SYSTEM | Obsoleto desde PHP 7.4.0.
arg_separator.input | "&" | PHP_INI_PERDIR |
arg_separator.output | "&" | PHP_INI_ALL |
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.exception | "0" | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL | Removido a partir do PHP 8.0.0
assert.warning | "1" | PHP_INI_ALL |
auto_append_file | NULL | PHP_INI_PERDIR |
auto_detect_line_endings | "0" | PHP_INI_ALL |
auto_globals_jit | "1" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
bcmath.scale | "0" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM |
cgi.discard_path | "0" | PHP_INI_SYSTEM |
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM |
cgi.force_redirect | "1" | PHP_INI_SYSTEM |
cgi.nph | "0" | PHP_INI_ALL |
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM |
cgi.rfc2616_headers | "0" | PHP_INI_ALL |
child_terminate | "0" | PHP_INI_ALL |
cli.pager | "" | PHP_INI_ALL |
cli.prompt | "\\b \\> " | PHP_INI_ALL |
cli_server.color | "0" | PHP_INI_ALL |
com.allow_dcom | "0" | PHP_INI_SYSTEM |
com.autoregister_typelib | "0" | PHP_INI_ALL |
com.autoregister_verbose | "0" | PHP_INI_ALL |
com.autoregister_casesensitive | "1" | PHP_INI_ALL |
com.code_page | "" | PHP_INI_ALL |
com.dotnet_version | "" | PHP_INI_SYSTEM | As of PHP 8.0.0
com.typelib_file | "" | PHP_INI_SYSTEM |
curl.cainfo | NULL | PHP_INI_SYSTEM |
date.default_latitude | "31.7667" | PHP_INI_ALL |
date.default_longitude | "35.2333" | PHP_INI_ALL |
date.sunrise_zenith | "90.833333" | PHP_INI_ALL | Antes do PHP 8.0.0, o padrão era "90.583333"
date.sunset_zenith | "90.833333" | PHP_INI_ALL | Antes do PHP 8.0.0, o padrão era "90.583333"
date.timezone | "UTC" | PHP_INI_ALL | A partir do PHP 8.2, um aviso é emitido quando este parâmetros é configurado para um valor inválido ou para um string vazio.
dba.default_handler | DBA_DEFAULT | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL | Padrão para "UTF-8".
input_encoding | "" | PHP_INI_ALL |
output_encoding | "" | PHP_INI_ALL |
internal_encoding | "" | PHP_INI_ALL |
default_mimetype | "text/html" | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
disable_classes | "" | Somente no php.ini |
disable_functions | "" | Somente no php.ini |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "1" | PHP_INI_ALL | Anteriormente ao PHP 8.0.0, o valor padrão era "0".
docref_ext | "" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
doc_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM | Este recurso obsoleto certamente será removido no 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 | Disponível desde o 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" | Somente no php.ini |
extension | NULL | Somente no php.ini |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM |
fastcgi.logging | "1" | PHP_INI_SYSTEM |
file_uploads | "1" | PHP_INI_SYSTEM |
filter.default | "unsafe_raw" | PHP_INI_PERDIR | Obsoleto desde o PHP 8.1.0.
filter.default_flags | NULL | PHP_INI_PERDIR |
from | "" | PHP_INI_ALL |
gd.jpeg_ignore_warning | "1" | PHP_INI_ALL |
geoip.custom_directory | "" | PHP_INI_ALL |
hard_timeout | "2" | PHP_INI_SYSTEM | Disponível 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 |
ibase.default_user | NULL | PHP_INI_ALL |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_all_pconnect | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Available since ibm_db2 1.0.2.
ibm_db2.i5_ignore_userid | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.8.0.
iconv.input_encoding | "" | PHP_INI_ALL | Obsoleto no PHP 5.6.0.
iconv.output_encoding | "" | PHP_INI_ALL | Obsoleto no PHP 5.6.0.
iconv.internal_encoding | "" | PHP_INI_ALL | Obsoleto no PHP 5.6.0.
ignore_repeated_errors | "0" | PHP_INI_ALL |
ignore_repeated_source | "0" | PHP_INI_ALL |
ignore_user_abort | "0" | PHP_INI_ALL |
implicit_flush | "0" | PHP_INI_ALL |
include_path | ".:/path/to/php/pear" | PHP_INI_ALL |
intl.default_locale |  | PHP_INI_ALL |
intl.error_level | 0 | PHP_INI_ALL |
intl.use_exceptions | 0 | PHP_INI_ALL | Available since 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 | Somente no 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 | Deprecated
mbstring.http_output | "pass" | PHP_INI_ALL | Deprecated
mbstring.internal_encoding | NULL | PHP_INI_ALL | Deprecated
mbstring.substitute_character | NULL | PHP_INI_ALL |
mbstring.func_overload | "0" | PHP_INI_SYSTEM | Deprecated as of PHP 7.2.0; removed as of PHP 8.0.0.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR |
mbstring.http_output_conv_mimetypes | "^(text/|application/xhtml\+xml)" | PHP_INI_ALL |
mbstring.strict_detection | "0" | PHP_INI_ALL |
mbstring.regex_retry_limit | "1000000" | PHP_INI_ALL | Available as of PHP 7.4.0.
mbstring.regex_stack_limit | "100000" | PHP_INI_ALL | Available as of 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 | Available since memcache 2.0.2.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Available since memcache 2.1.0.
memcache.chunk_size | "8192" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.hash_function | "crc32" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.protocol | ascii | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.redundancy | 1 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.session_redundancy | 2 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.compress_threshold | 20000 | >PHP_INI_ALL | Supported since memcache 3.0.3
memcache.lock_timeout | 15 | >PHP_INI_ALL | Supported since memcache 3.0.4
memory_limit | "128M" | PHP_INI_ALL |
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 | "0" | PHP_INI_SYSTEM | Antes do PHP 7.2.16 e 7.3.3 o padrão era "1".
mysqli.local_infile_directory |  | PHP_INI_SYSTEM | Disponível desde o PHP 8.1.0.
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM |
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM |
mysqli.max_links | "-1" | PHP_INI_SYSTEM |
mysqli.default_port | "3306" | PHP_INI_ALL |
mysqli.default_socket | NULL | PHP_INI_ALL |
mysqli.default_host | NULL | PHP_INI_ALL |
mysqli.default_user | NULL | PHP_INI_ALL |
mysqli.default_pw | NULL | PHP_INI_ALL |
mysqli.reconnect | "0" | PHP_INI_SYSTEM | Removido no PHP 8.2.0
mysqli.rollback_on_cached_plink | "0" | PHP_INI_SYSTEM |
mysqlnd.collect_statistics | "1" | PHP_INI_SYSTEM |
mysqlnd.collect_memory_statistics | "0" | PHP_INI_SYSTEM |
mysqlnd.debug | "" | PHP_INI_SYSTEM |
mysqlnd.log_mask | 0 | PHP_INI_ALL |
mysqlnd.mempool_default_size | 16000 | PHP_INI_ALL |
mysqlnd.net_read_timeout | "86400" | PHP_INI_ALL | Before PHP 7.2.0 the default value was "31536000" and the changeability was PHP_INI_SYSTEM
mysqlnd.net_cmd_buffer_size | "4096" | PHP_INI_SYSTEM |
mysqlnd.net_read_buffer_size | "32768" | PHP_INI_SYSTEM |
mysqlnd.sha256_server_public_key | "" | PHP_INI_PERDIR |
mysqlnd.trace_alloc | "" | PHP_INI_SYSTEM |
mysqlnd.fetch_data_copy | 0 | PHP_INI_ALL | Removed as of PHP 8.1.0
oci8.connection_class | "" | PHP_INI_ALL |
oci8.default_prefetch | "100" | PHP_INI_SYSTEM |
oci8.events | Off | PHP_INI_SYSTEM |
oci8.max_persistent | "-1" | PHP_INI_SYSTEM |
oci8.old_oci_close_semantics | Off | PHP_INI_SYSTEM | Deprecated as of PHP 8.1.0.
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM |
oci8.ping_interval | "60" | PHP_INI_SYSTEM |
oci8.prefetch_lob_size | "0" | PHP_INI_SYSTEM | Available since PECL OCI8 3.2.
oci8.privileged_connect | Off | PHP_INI_SYSTEM |
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM |
odbc.default_db * | NULL | PHP_INI_ALL |
odbc.default_user * | NULL | PHP_INI_ALL |
odbc.default_pw * | NULL | PHP_INI_ALL |
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
odbc.default_cursortype | "3" | PHP_INI_ALL |
opcache.enable | "1" | PHP_INI_ALL |
opcache.enable_cli | "0" | PHP_INI_SYSTEM | Entre PHP 7.1.2 e 7.1.6 inclusive, o padrão 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 |
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 | Removido no PHP 7.2.0
opcache.enable_file_override | "0" | PHP_INI_SYSTEM |
opcache.optimization_level | "0x7FFEBFFF" | PHP_INI_SYSTEM | Alterado de 0x7FFFBFFF no PHP 7.3.0
opcache.inherited_hack | "1" | PHP_INI_SYSTEM | Removido no 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 | Desativado a partir do 8.1.18 e 8.2.5. Removido a partir do PHP 8.3.0
opcache.force_restart_timeout | "180" | PHP_INI_SYSTEM |
opcache.error_log | "" | PHP_INI_SYSTEM |
opcache.log_verbosity_level | "1" | PHP_INI_SYSTEM |
opcache.record_warnings | "0" | PHP_INI_SYSTEM | Disponível a partir do 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 | Disponível a partir do 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 | Somente Windows.
opcache.validate_permission | "0" | PHP_INI_SYSTEM | Disponível a partir do PHP 7.0.14
opcache.validate_root | "0" | PHP_INI_SYSTEM | Disponível a partir do PHP 7.0.14
opcache.preload | "" | PHP_INI_SYSTEM | Disponível a partir do PHP 7.4.0
opcache.preload_user | "" | PHP_INI_SYSTEM | Disponível a partir do PHP 7.4.0
opcache.cache_id | "" | PHP_INI_SYSTEM | Somente Windows. Disponível a partir do PHP 7.4.0
opcache.jit | "tracing" | PHP_INI_ALL | Disponível a partir do PHP 8.0.0
opcache.jit_buffer_size | "0" | PHP_INI_SYSTEM | Disponível a partir do PHP 8.0.0
opcache.jit_debug | "0" | PHP_INI_ALL | Disponível a partir do PHP 8.0.0
opcache.jit_bisect_limit | "0" | PHP_INI_ALL | Disponível a partir do PHP 8.0.0
opcache.jit_prof_threshold | "0.005" | PHP_INI_ALL | Disponível a partir do PHP 8.0.0
opcache.jit_max_root_traces | "1024" | PHP_INI_SYSTEM | Disponível a partir do PHP 8.0.0
opcache.jit_max_side_traces | "128" | PHP_INI_SYSTEM | Disponível a partir do PHP 8.0.0
opcache.jit_max_exit_counters | "8192" | PHP_INI_SYSTEM | Disponível a partir do PHP 8.0.0
opcache.jit_hot_loop | "64" | PHP_INI_SYSTEM | Disponível a partir do PHP 8.0.0
opcache.jit_hot_func | "127" | PHP_INI_SYSTEM | Disponível a partir do PHP 8.0.0
opcache.jit_hot_return | "8" | PHP_INI_SYSTEM | Disponível a partir do PHP 8.0.0
opcache.jit_hot_side_exit | "8" | PHP_INI_SYSTEM | Disponível a partir do PHP 8.0.0
opcache.jit_blacklist_root_trace | "16" | PHP_INI_ALL | Disponível a partir do PHP 8.0.0
opcache.jit_blacklist_side_trace | "8" | PHP_INI_ALL | Disponível a partir do PHP 8.0.0
opcache.jit_max_loop_unrolls | "8" | PHP_INI_ALL | Disponível a partir do PHP 8.0.0
opcache.jit_max_recursive_calls | "2" | PHP_INI_ALL | Disponível a partir do PHP 8.0.0
opcache.jit_max_recursive_returns | "2" | PHP_INI_ALL | Disponível a partir do PHP 8.0.0
opcache.jit_max_polymorphic_calls | "2" | PHP_INI_ALL | Disponível a partir do 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.* |  | Somente php.ini |
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL |
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Este recurso obsoleto certamente será removido no 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 | Antes do PHP 7.1.0, o valor padrão 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 | "0" | PHP_INI_ALL | Antes do PHP 7.2.0, o padrão era "".
session.cookie_httponly | "0" | PHP_INI_ALL | Antes do PHP 7.2.0, o padrão era "".
session.cookie_samesite | "" | PHP_INI_ALL | Disponível a partir do 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 | Disponível desde o PHP 7.1.0.
session.trans_sid_hosts | $_SERVER['HTTP_HOST'] | PHP_INI_ALL | Disponível desde o PHP 7.1.0.
session.sid_length | "32" | PHP_INI_ALL | Disponível desde o PHP 7.1.0.
session.sid_bits_per_character | "5" | PHP_INI_ALL | Disponível desde o 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 | Removido no PHP 7.1.0.
session.hash_bits_per_character | "4" | PHP_INI_ALL | Removido no PHP 7.1.0.
session.entropy_file | "" | PHP_INI_ALL | Removido no PHP 7.1.0.
session.entropy_length | "0" | PHP_INI_ALL | Removido no PHP 7.1.0
short_open_tag | "1" | PHP_INI_PERDIR |
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL |
soap.wsdl_cache_enabled | 1 | PHP_INI_ALL |
soap.wsdl_cache_dir | /tmp | PHP_INI_ALL |
soap.wsdl_cache_ttl | 86400 | PHP_INI_ALL |
soap.wsdl_cache | 1 | PHP_INI_ALL |
soap.wsdl_cache_limit | 5 | PHP_INI_ALL |
sql.safe_mode | "0" | PHP_INI_SYSTEM |
sqlite3.extension_dir | "" | PHP_INI_SYSTEM |
sqlite3.defensive | 1 | PHP_INI_USER | Available as of PHP 7.2.17 and 7.3.4 for libsqlite = 3.26.0. Prior to PHP 8.2.0 this setting was changeable only as PHP_INI_SYSTEM.
syslog.facility | "LOG_USER" | PHP_INI_SYSTEM | Disponível desde o PHP 7.3.0.
syslog.filter | "no-ctrl" | PHP_INI_ALL | Disponível desde o PHP 7.3.0.
syslog.ident | "php" | PHP_INI_SYSTEM | Disponível desde o 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 | Obsoleto desde PHP 7.2.0, removido no PHP 8.0.0.
unserialize_callback_func | null | PHP_INI_ALL |
unserialize_max_depth | "4096" | PHP_INI_ALL | Disponível a partir do PHP 7.4.0.
uploadprogress.file.filename_template | "/tmp/upt_%s.txt" | PHP_INI_ALL |
upload_max_filesize | "2M" | PHP_INI_PERDIR |
max_file_uploads | 20 | PHP_INI_SYSTEM |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL |
user_agent | NULL | PHP_INI_ALL |
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM |
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM |
uopz.disable | "0" | PHP_INI_SYSTEM | 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 |
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 | Disponível 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 | Somente no 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 das seções do php.ini

Esta lista inclui as seções do php.ini que você pode modificar para configurar sua instalação do PHP baseado em host ou em pastas. Estas seções são opcionais.

Estas seções não afetam diretamente o PHP. Elas são usadas para agrupar outras diretivas php.ini e agir de acordo um host específico ou uma pasta específica.

Estas seções são usadas somente no modo CGI/FastCGI e não podem modificar as diretivas extension e zend_extension.

Seções
Nome | Modificável | Changelog
[HOST=] | PHP_INI_SYSTEM |
[PATH=] | PHP_INI_SYSTEM |

Aqui está uma breve explicação das diretivas de configuração.

[HOST=<host>]

Esta seção permite definir um conjunto de diretivas do php.ini que terá efeito no host definido.

Exemplo #1 Ativa a exibição completa de erros na tela para o domínio dev.

[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On

[PATH=<path>]

Esta seção permite definir um conjunto de diretivas do php.ini que terá efeito quando um script for executado a partir da pasta definida.

Exemplo #2 Adiciona o script security.php para áreas 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).


Descrição das principais diretivas do php.ini

Esta lista inclui as principais diretivas do php.ini que podemos definir para configurar o PHP. Diretivas manipuladas por extensões são listadas e detalhadas nas respectivas páginas de documentação da extensão; Informações sobre diretivas de sessão, por exemplo, podem ser encontradas na página de sessões.

Nota:

Os padrões listados aqui são utilizados quando o php.ini não é carregado; os valores do php.ini de produção e desenvolvimento podem variar.

Opções de Linguagem

Opções de Linguagem e Configurações Diversas
Nome | Padrão | Modificável | Changelog
short_open_tag | "1" | PHP_INI_PERDIR |
precision | "14" | PHP_INI_ALL |
serialize_precision | "-1" | PHP_INI_ALL | Antes do PHP 7.1.0 o valor padrão era 17.
disable_functions | "" | PHP_INI_SYSTEM apenas |
disable_classes | "" | php.ini apenas |
exit_on_timeout | "" | PHP_INI_ALL |
expose_php | "1" | php.ini apenas |
hard_timeout | "2" | PHP_INI_SYSTEM | Disponível a partir do PHP 7.1.0.
zend.exception_ignore_args | "0" | PHP_INI_ALL | Disponível a partir do 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 com restrições |
zend.exception_string_param_max_len | "15" | PHP_INI_ALL | Disponível desde o PHP 8.0.0.

Aqui está uma breve explicação das diretivas de configuração.

short_open_tag bool

Informa ao PHP se a forma abreviada (<? ?>) da tag de abertura do PHP é permitida. Se quiser usar o PHP em conjunto com XML, esta opção pode ser desabilitada a fim de usar <?xml ?> em linha. Caso contrário, pode-se imprimir isto com o PHP, por exemplo <?php echo '<?xml version="1.0"?>'; ?>. Além disso, se desabilitada, deve ser usada a forma extensa da tag de abertura do PHP (<?php ?>).

Nota:

Esta diretiva não afeta o equivalente <?=, que está sempre disponível.

precision int
O número de dígitos significativos exibidos em números de ponto flutuante. -1 significa que um algoritmo avançado para arredondar estes números será utilizado.
serialize_precision int
O número de dígitos significativos armazenados durante a serialização de números de pontos flutuantes. -1 significa que um algoritmo avançado para arredondar estes números será utilizado.
expose_php bool

Expõe para o mundo que o PHP está instalado no servidor, o que inclui a versão do PHP dentro do header HTTP (por exemplo, X-Powered-By: PHP/5.3.7).

disable_functions string

Esta diretiva permite desabilitar certas funções. Ela recebe uma lista de nomes de funções separadas por vírgula.

Apenas funções internas podem ser desabilitadas usando esta diretiva. Funções definidas pelo usuário não são afetadas.

Esta diretiva deve ser configurada no php.ini. Por exemplo, ela não pode ser configurada no httpd.conf.

disable_classes string
Esta diretiva permite desabilitar certas classes. Ela recebe uma lista de nomes de classes separadas por vírgula. Esta diretiva deve ser configurada no php.ini. Por exemplo, ela não pode ser configurada no httpd.conf.
zend.assertions int
Quando configurada para 1, código assertivo será gerado e executado (modo de desenvolvimento). Quando configurada para 0 então código assertivo será gerado mas ignorado (não executado) em tempo de execução. Quando configurada para -1 código assertivo não será gerado, tornando as asserções sem custo (modo de produção).

Nota:

Se um processo é iniciado em modo de produção, zend.assertions não poderá ser modificada em tempo de execução, já que o código para as asserções não foi gerado.

Se um processo é iniciado em modo de desenvolvimento, zend.assertions não poderá ser configurada para -1 em tempo de execução.

zend.exception_string_param_max_len int
O tamanho máximo das strings na serialização string dos stack traces. Deve ser entre "0" e "1000000".
hard_timeout int

Quando o timeout é configurado em max_execution_time é alcançado, o runtime PHP irá descarregar os recursos de maneira organizada. Se algo travar nesse processo, o hard_timeout irá começar a contar os segundos configurados. Se o hard_timeout for atingido, o PHP irá descarregar de maneira desorganizada. Quando configurado para zero, o hard_timeout está desconfigurado.

Quando o PHP atinge o hard_timeout, vai ocorrer algo parecido com isso::

Fatal error: Maximum execution time of 30+2 seconds exceeded (terminated) in Unknown on line 0

zend.exception_ignore_args bool

Exclui argumentos de rastreamentos de pilha (stack traces), gerados a partir de exceções.

zend.multibyte bool

Permite a análise de arquivos fontes em codificações multibyte. Habilitar zend.multibyte é necessário para utilizar character sets como SJIS, BIG5, etc., que contém caracteres especiais em dados de strings multibyte. Codificações compatíveis com ISO-8859-1 como UTF-8, EUC, etc. não requerem esta opção.

Habilitar o zend.multibyte requer que a extensão mbstring esteja disponível.

zend.script_encoding string

Este valor será usado a menos que uma diretiva declare(encoding=...) apareça no início do script. Quando uma codificação incompatível com ISO-8859-1 é usada, ambas zend.multibyte e zend.script_encoding devem ser usadas.

Strings literais serão transliteradas de zend.script_encoding para mbstring.internal_encoding, como se a função mb_convert_encoding() tivesse sido chamada.

zend.detect_unicode bool

Verifica o BOM (Byte Order Mark) e determina se o arquivo contém caracteres multibyte válidos. Essa detecção é realizada antes do processamento de __halt_compiler(). Disponível apenas no modo Zend Multibyte.

zend.signal_check bool

Verifica se há manipuladores de sinais substituídos no encerramento.

exit_on_timeout bool

Esta é uma diretiva unicamente do módulo mod_php do Apache1 que força um subprocesso do Apache a sair se ocorrer o timeout de execução do PHP. Esse timeout causa uma chamada interna a longjmp() no Apache1 que pode deixar algumas extensões em um estado inconsistente. Ao terminar o processo, quaisquer bloqueios ou memória pendentes serão liberados.

Limites de Recursos

Limites de Recursos
Nome | Padrão | Modificável | Changelog
memory_limit | "128M" | PHP_INI_ALL |

Aqui está uma breve explicação das diretivas de configuração.

memory_limit int

Define a quantidade máxima de memória em bytes que um script pode alocar. Isto ajuda a prevenir que scripts mal escritos consumam toda a memória disponível no servidor. Note que para que não haja limite de memória, esta diretiva deve ser configurada para -1.

Quando um int é usado, o valor é medido em bytes. A notação abreviada, como descrita nesta FAQ, também pode ser usada.

Veja também: max_execution_time.

Ajustes de Desempenho

Ajustes de Desempenho
Nome | Padrão | Modificável | Changelog
realpath_cache_size | "4M" | PHP_INI_SYSTEM | Antes do PHP 7.0.16 e 7.1.2, o padrão era "16K"
realpath_cache_ttl | "120" | PHP_INI_SYSTEM |

Nota:

O uso da diretiva open_basedir irá desativar o cache do caminho real.

Aqui está uma breve explicação das diretivas de configuração.

realpath_cache_size int

Determina o tamanho do cache do realpath a ser usado pelo PHP. Este valor deve ser aumentado em sistemas onde o PHP abre muitos arquivos, para refletir a quantidade das operações de arquivo realizadas.

O tamanho representa o número total de bytes nas strings de caminhos armazenadas, mais o tamanho dos dados associados à entrada de cache. Isto significa que para armazenar caminhos mais longos no cache, o tamanho de cache deve ser maior. Esse valor não controla diretamente o número de caminhos distintos que podem ser armazenados em cache.

O tamanho necessário para os dados da entrada de cache depende do sistema operacional.

realpath_cache_ttl int

Duração do tempo (em segundos) pela qual armazenar em cache as informações do realpath para um dado arquivo ou diretório. Para sistemas com arquivos que raramente mudam, considere aumentar o valor.

Manipulação de Dados

Opções de Configuração de Manipulação de Dados
Nome | Padrão | Modificável | Changelog
arg_separator.output | "&" | PHP_INI_ALL |
arg_separator.input | "&" | PHP_INI_PERDIR |
variables_order | "EGPCS" | PHP_INI_PERDIR |
request_order | "" | PHP_INI_PERDIR |
auto_globals_jit | "1" | PHP_INI_PERDIR |
register_argc_argv | "1" | PHP_INI_PERDIR |
enable_post_data_reading | "1" | PHP_INI_PERDIR |
post_max_size | "8M" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
auto_append_file | NULL | PHP_INI_PERDIR |
default_mimetype | "text/html" | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL |
input_encoding | "" | PHP_INI_ALL |
output_encoding | "" | PHP_INI_ALL |
internal_encoding | "" | PHP_INI_ALL |

Aqui está uma breve explicação das diretivas de configuração.

arg_separator.output string

O separador usado em URLs gerados pelo PHP para separar argumentos.

arg_separator.input string

Lista de separadores usados pelo PHP para analisar URLs de entrada em variáveis.

Nota:

Cada caractere nesta diretiva é considerado como separador!

variables_order string

Configura a ordem de análise das variáveis EGPCS (Environment, Get, Post, Cookie e Server). Por exemplo, se variables_order estiver configurada como "SP" então o PHP irá criar as variáveis superglobals $_SERVER e $_POST, mas não irá criar $_ENV, $_GET e $_COOKIE. Configurar como "" significa que nenhuma superglobals será definida.

Aviso

Em ambas as SAPIs CGI e FastCGI, $_SERVER também é preenchida por valores do ambiente; S é sempre equivalente a ES independentemente da inclusão de E em outra parte desta diretiva.

Nota:

O conteúdo e a ordem de $_REQUEST também são afetados por esta diretiva.

request_order string

Esta diretiva descreve a ordem na qual o PHP registra as variáves GET, POST e Cookie no array _REQUEST. O registro é feito da esquerda para direita, valores mais recentes sobrescrevem os valores mais antigos.

Se esta diretiva não está definida variables_order é usada para o conteúdo de $_REQUEST.

Note que os arquivos php.ini da distribuição padrão não contêm o 'C' para cookies, por motivos de segurança.

auto_globals_jit bool

Quando ativada, as variáveis SERVER, REQUEST e ENV são criadas quando elas são usadas pela primeira vez ("Just In Time") ao invés de quando o script inicia. Se estas variáveis não são usadas dentro de um script, habilitar esta diretiva resultará em um ganho de desempenho.

Aviso

O uso das variáveis SERVER, REQUEST e ENV é verificado durante o tempo de compilação então usá-las, por exemplo, em variáveis variáveis não causará sua inicialização.

register_argc_argv bool
Informa ao PHP se deve declarar variáveis argv & argc (que podem conter as informações das requisições GET). Veja também PHP em linha de comando.
enable_post_data_reading bool
Desabilitar esta opção faz com que $_POST e $_FILES não sejam preenchidos. A única forma de ler dados postados será através do stream wrapper php://input. Isto pode ser útil para intermediar requisições ou para processar dados POST de uma maneira eficiente em termos de memória alocada.
post_max_size int
Configura o tamanho máximo dos dados postados. Esta configuração também afeta o upload de arquivos. Para carregar arquivos grandes este valor deve ser maior que upload_max_filesize. De maneira geral memory_limit deve ser maior que post_max_size. Quando um int é usado, o valor é medido em bytes. A notação abreviada, como descrita nesta FAQ, também pode ser usada. Se o tamanho dos dados postados for maior que post_max_size então as variáveis superglobals $_POST e $_FILES ficarão vazias. Isto pode ser observado de várias maneiras, por exemplo, passando uma variável $_GET ao script que processará os dados, por exemplo, <form action="edit.php?processed=1">, e então verificando se $_GET['processed'] está preenchida.

Nota:

O PHP permite sufixos para valores em bytes, incluindo K (kilo), M (mega) e G (giga). O PHP fará as conversões automaticamente se você utilizar qualquer um destes. Cuidado para não exceder o limite de inteiros sinalizados de 32 bit (ao usar versões de 32 bit) uma vez que isso fará o script falhar.

Changelog de post_max_size
Versão | Descrição
5.3.4 | post_max_size = 0 não irá desabilitar o limite quando o conteúdo for do tipo application/x-www-form-urlencoded ou não esteja registrado no PHP.
5.3.2 , 5.2.12 | Permite tamanho ilimitado de dados postados ao configurar post_max_size como 0.

auto_prepend_file string

Especifica o nome de um arquivo que é automaticamente analisado antes do arquivo principal. O arquivo é incluído como se tivesse sido chamado com require, então include_path é utilizado.

O valor especial none desativa a auto-inclusão.

auto_append_file string

Especifica o nome de um arquivo que é automaticamente analisado depois do arquivo principal. O arquivo é incluído como se tivesse sido chamado com require, então include_path é utilizado.

O valor especial none desativa a auto-inclusão.

Nota: Se o script for terminado com exit(), então a auto-inclusão não ocorrerá.

default_mimetype string

Por padrão o PHP irá imprimir um media type utilizando o header Content-Type. Para desabilitar o envio da codificação configure esta opção como vazio.

O padrão interno do PHP é o media type text/html.

default_charset string

"UTF-8" é o valor padrão e o valor desta diretiva é utilizado como o character set padrão para htmlentities(), html_entity_decode() e htmlspecialchars() se o parâmetro encoding for omitido. O valor de default_charset também será utilizado para configurar o character set padrão para as funções iconv se as opções de configuração iconv.input_encoding, iconv.output_encoding e iconv.internal_encoding não estiverem definidas, e também para as funções mbstring se as opções de configuração mbstring.http_input, mbstring.http_output e mbstring.internal_encoding não estiverem definidas.

Todas as versões do PHP usarão este valor como o charset no header padrão Content-Type enviado pelo PHP caso o header não seja sobrescrito por uma chamada à função header().

Configurar default_charset para um valor vazio não é recomendado.

input_encoding string

Esta configuração é utilizada por módulos multibyte como mbstring e iconv. O padrão é vazio.

output_encoding string

Esta configuração é utilizada por módulos multibyte como mbstring e iconv. O padrão é vazio.

internal_encoding string

Esta configuração é utilizada por módulos multibyte como mbstring e iconv. O padrão é vazio. Se vazio, default_charset é utilizado.

Caminhos e Diretórios

Caminhos e Opções de Configuração de Diretórios
Nome | Padrão | Modificável | Changelog
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 | Apenas no php.ini |
zend_extension | NULL | Apenas no php.ini |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM |
cgi.discard_path | "0" | PHP_INI_SYSTEM |
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM |
cgi.force_redirect | "1" | PHP_INI_SYSTEM |
cgi.nph | "0" | PHP_INI_SYSTEM |
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM |
cgi.rfc2616_headers | "0" | PHP_INI_ALL |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM |
fastcgi.logging | "1" | PHP_INI_SYSTEM |

Aqui está uma breve explicação das diretivas de configuração.

include_path string

Especifica uma lista de diretórios onde as funções require, include, fopen(), file(), readfile() e file_get_contents() procuram por arquivos. O formato é como a variável de ambiente PATH: uma lista de diretórios separados por dois pontos no Unix ou ponto e vírgula no Windows.

O PHP considera cada item no include_path separadamente ao procurar por arquivos para incluir. Ele irá verificar o primeiro caminho, e se não o encontrar, verificar o próximo caminho, até que encontre o arquivo incluído ou retorne com um E_WARNING ou um E_ERROR. Você pode modificar ou configurar o include_path em tempo de execução usando set_include_path().

Exemplo #1 include_path no Unix

include_path=".:/php/includes"

Exemplo #2 include_path no Windows

include_path=".;c:\php\includes"

Utilizar um . no include_path permite inclusões relativas ao diretório atual. Entretanto é mais eficiente utilizar explicitamente include './file' em vez de fazer o PHP sempre procurar no diretório atual a cada inclusão.

Nota:

Variáveis ENV também estão acessíveis em arquivos .ini. Assim é possível referenciar o diretório home utilizando ${LOGIN} e ${USER}.

Variáveis de ambiente podem variar entre APIs de servidor já que esses ambientes podem ser diferentes.

Exemplo #3 include_path do Unix utilizando a variável de ambiente ${USER}

include_path = ".:${USER}/pear/php"

open_basedir string

Limita os arquivos que podem ser acessados pelo PHP à árvore de diretório especificada, incluindo o próprio arquivo.

Quando um script tenta acessar o sistema de arquivos, por exemplo utilizando include ou fopen(), a localização do arquivo é verificada. Quando o arquivo está fora da árvore de diretório especificada, o PHP se recusará a acessá-lo. Todos os links simbólicos são resolvidos, então não é possível evitar esta restrição com um link simbólico. Se o arquivo não existe então o link simbólico não pode ser resolvido e o nome do arquivo é comparado a um open_basedir (resolvido).

open_basedir pode afetar mais que apenas as funções de sistema de arquivos; por exemplo, se o MySQL está configurado para utilizar os drivers mysqlnd, LOAD DATA INFILE será afetado por open_basedir. Grande parte da funcionalidade extendida do PHP utiliza open_basedir desta maneira.

O valor especial . indica que o diretório atual do script será utilizado como o diretório base. Isto é, no entanto, perigoso pois o diretório atual do script pode ser facilmente alterado com chdir().

No httpd.conf open_basedir pode ser desabilitada (por exemplo, em alguns hosts virtuais) da mesma forma que quaisquer outras diretivas de configuração com "php_admin_value open_basedir none".

No Windows os diretórios são separados com um ponto e vírgula. Em todos os outros sistemas os diretórios são separados com dois pontos. Como um módulo Apache os caminhos de open_basedir de diretórios pai agora são automaticamente herdados.

A restrição especificada com open_basedir é um nome de diretório, não um prefixo.

O padrão é permitir que todos os arquivos sejam abertos.

Nota:

open_basedir pode ser restringido em tempo de execução. Isto significa que se open_basedir é configurado para /www/ no php.ini então um script pode restringir a configuração para /www/tmp/ em tempo de execução com ini_set(). Ao listar vários diretórios é possível utilizar a constante PATH_SEPARATOR como um separador independentemente do sistema operacional.

Nota:

O uso da diretiva open_basedir definirá realpath_cache_size como 0 e assim desabilitará o cache do caminho real.

Cuidado

open_basedir é rede de segurança extra, mas não é uma proteção total, e portanto não deve-se depender para garantir a segurança.

doc_root string

O "diretório raiz" do PHP no servidor. Utilizado apenas se estiver informado. Se o PHP não foi compilado com FORCE_REDIRECT, você deve configurar doc_root se estiver rodando o PHP em modo CGI em qualquer servidor web (diferente do IIS). A alternativa é utilizar a configuração cgi.force_redirect abaixo.

user_ini.cache_ttl int

user_ini.filename string

user_dir string

O nome base do diretório utilizado como diretório home do usuário pelos arquivos do PHP, por exemplo public_html .

extension_dir string

O diretório no qual o PHP deve procurar por extensões carregadas dinamicamente. É recomendado especificar um caminho absoluto. Veja também: enable_dl e dl().

extension string

Quais extensões carregáveis dinamicamente carregar quando o PHP inicia.

zend_extension string

Nome da extensão Zend carregável dinamicamente (por exemplo, XDebug) a carregar quando o PHP inicia.

cgi.check_shebang_line bool

Controla se o PHP CGI verifica linhas iniciando com #! (shebang) no início do script em execução. Esta linha pode ser necessária se o script suporta execução tanto como script autônomo e via PHP CGI. O PHP em modo CGI pula esta linha e ignora seu conteúdo se esta diretiva estiver habilitada.

cgi.discard_path bool

Se habilitada, o binário PHP CGI pode ser colocado com segurança fora da árvore de diretório web e não será possível contornar a segurança .htaccess.

cgi.fix_pathinfo bool

Fornece suporte real a PATH_INFO/ PATH_TRANSLATED para CGI. O comportamento anterior do PHP era definir PATH_TRANSLATED como SCRIPT_FILENAME e não perceber o que PATH_INFO é. Para mais informações sobre PATH_INFO, veja as especificações do modo CGI. Configurar esta diretiva para 1 fará o modo CGI corrigir seus caminhos para obedecer à especificação. Configurar com zero faz o PHP se comportar como antes. Ela é habilitada por padrão. Você deve corrigir seus scripts de forma a usar SCRIPT_FILENAME ao invés de PATH_TRANSLATED.

cgi.force_redirect bool

cgi.force_redirect é necessário para prover segurança ao rodar o PHP em modo CGI na maioria dos servidores web. Se deixada indefinida, o PHP irá habilitá-la por padrão. Você pode desabilitá-la por sua conta e risco.

Nota:

Usuários do Windows: Ao utilizar o IIS esta opção deve ser desabilitada. O mesmo vale para servidores OmniHTTPD e Xitami.

cgi.nph bool

Se cgi.nph estiver habilitada, forçará o CGI a enviar sempre Status: 200 em todas as requisições.

cgi.redirect_status_env string

Se cgi.force_redirect estiver habilitada e você não está rodando sob servidores web Apache ou Netscape (iPlanet), você pode precisar configurar um nome de variável de ambiente que o PHP irá procurar para saber que é correto continuar a execução.

Nota:

Configurar esta variável pode causar problemas de segurança, tenha certeza do que está fazendo antes de alterar.

cgi.rfc2616_headers int

Indica ao PHP qual o tipo de headers usar ao enviar o código de resposta HTTP. Se configurada para 0, o PHP envia um header "Status:" da » RFC 3875 que é suportado pelo Apache e outros servidores web. Quando esta opção é configurada para 1, o PHP enviará headers em conformidade com a » RFC 2616.

Se esta opção estiver habilitada e o PHP estiver rodando em um ambiente CGI (por exemplo, PHP-FPM) não devem ser utilizados headers de resposta de status HTTP no padrão RFC 2616. Em vez disso, deve ser usado o seu equivalente RFC 3875, por exemplo, em vez de header("HTTP/1.0 404 Not found"); deve ser usado header("Status: 404 Not Found");.

Deixe-a configurada para 0 a não ser que saiba exatamente o que está fazendo.

fastcgi.impersonate string

O FastCGI rodando no IIS (em sistemas baseados em WINNT) suporta a habilidade de representar os tokens de segurança do cliente que faz a requisição. Isso permite ao IIS definir o contexto de segurança no qual a requisição executa. O mod_fastcgi rodando no Apache atualmente não suporta esta funcionalidade (17/03/2002) Configure para 1 ao rodar no ISS. O padrão é zero.

fastcgi.logging bool

Ativa o logging do SAPI ao utilizar o FastCGI. O padrão é habilitar o logging.

Upload de Arquivos

Opções de Configurações de Upload de Arquivos
Nome | Padrão | Modificável | Changelog
file_uploads | "1" | PHP_INI_SYSTEM |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
max_input_nesting_level | 64 | PHP_INI_PERDIR |
max_input_vars | 1000 | PHP_INI_PERDIR |
upload_max_filesize | "2M" | PHP_INI_PERDIR |
max_file_uploads | 20 | PHP_INI_PERDIR |

Aqui está uma breve explicação das diretivas de configuração.

file_uploads bool

Permite ou não upload de arquivos através do HTTP. Veja também as diretivas upload_max_filesize, upload_tmp_dir e post_max_size.

upload_tmp_dir string

O diretório temporário utilizado para armazenar arquivos durante o upload. Precisa ter permissão de escrita para qualquer usuário que o PHP esteja usando para rodar. Se não especificado o PHP usará o padrão do sistema.

Se o diretório especificado aqui não tiver permissão de escrita, o PHP tenta o diretório temporário padrão do sistema. Se open_basedir estiver habilitado, então o diretório padrão do sistema deve ser permitido para que o upload tenha sucesso.

upload_max_filesize int

O tamanho máximo de um arquivo enviado.

post_max_size precisa ser maior que esse valor.

Quando um int é usado, o valor é medido em bytes. A notação abreviada, como descrita nesta FAQ, também pode ser usada.
max_file_uploads int

O número máximo de arquivos permitidos simultaneamente durante um upload. Campos de upload deixados em branco no envio não contam para este limite.

SQL Geral

Opções de Configurações Gerais de SQL
Nome | Padrão | Modificável | Changelog
sql.safe_mode | "0" | PHP_INI_SYSTEM | Removido no PHP 7.2.0.

Aqui está uma breve explicação das diretivas de configuração.

sql.safe_mode bool

Se habilitada as funções de conexão de bancos de dados que especifiquem valores padrão usarão esses valores no lugar de quaisquer argumentos passados pelo usuário. Para detalhes sobre os valores padrão, veja a documentação das funções de conexão relevantes.

Aviso

Este recurso foi REMOVIDO a partir do PHP 7.2.0.

Windows

Opções de Configurações Específicas do Windows
Nome | Padrão | Modificável | Changelog
windows.show_crt_warning | "0" | PHP_INI_ALL |

Aqui está uma breve explicação das diretivas de configuração.

windows.show_crt_warning bool

Esta diretiva exibe os alertas do CRT do Windows quando habilitada.

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


Categorização/Lista das Extensões

Índice

  • Em ordem alfabética
  • Sociedade
  • Estado

Esse apêndice categoriza mais de 150 extensões documentadas no manual do PHP por vários critérios.

User Contributed Notes

There are no user contributed notes for this page.


Em ordem alfabética

  • Apache
  • APCu
  • Arrays
  • BC Math
  • Bzip2
  • Calendar
  • Classes/Objetos
  • CommonMark
  • COM
  • Componere
  • Ctype
  • CUBRID
  • cURL
  • Data/Hora
  • DBA
  • dBase
  • Direct IO
  • Diretórios
  • DOM
  • Data Structures
  • Eio
  • Enchant
  • Gerenciamento de Erros
  • Ev
  • Event
  • Execução de programa
  • Exif
  • Expect
  • FANN
  • FDF
  • FFI
  • Fileinfo
  • Extensão Filesystem (Sistema de Arquivos)
  • Filter
  • FastCGI Process Manager
  • FTP
  • Gerenciamento de funções
  • Gearman
  • Gender
  • GeoIP
  • Gettext
  • Gmagick
  • GMP
  • GnuPG
  • Hash
  • HRTime
  • Firebird/InterBase
  • IBM DB2
  • iconv
  • Igbinary
  • GD
  • ImageMagick
  • IMAP
  • Opções/Info do PHP
  • Inotify
  • intl
  • JSON
  • LDAP
  • libxml
  • Lua
  • LuaSandbox
  • LZF
  • Mail
  • Mailparse
  • Math
  • Multibyte String
  • Mcrypt
  • Memcache
  • Memcached
  • Mhash
  • Misc.
  • mqseries
  • MySQL (Original)
  • Mysql_xdevapi
  • MySQLi
  • Mysqlnd
  • Network
  • OAuth
  • OCI8
  • OPcache
  • OpenAL
  • OpenSSL
  • Controle de Saída
  • parallel
  • Parle
  • Password Hashing
  • PCNTL
  • PCRE
  • PDO
  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • Oracle (PDO)
  • ODBC and DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)
  • MS SQL Server (PDO)
  • PostgreSQL
  • Phar
  • phpdbg
  • POSIX
  • PS
  • Pspell
  • pthreads
  • Quickhash
  • Radius
  • Random
  • Rar
  • Readline
  • Recode
  • Reflexão
  • Rnp
  • RpmInfo
  • RRD
  • runkit7
  • ScoutAPM
  • Seaslog
  • Semaphore
  • Sessões
  • Memória Compartilhada
  • Simdjson
  • SimpleXML
  • SNMP
  • SOAP
  • Sockets
  • Sodium
  • Solr
  • SPL
  • SQLite3
  • SQLSRV
  • ssdeep
  • SSH2
  • Statistics
  • Stomp
  • Fluxos
  • Strings
  • SVM
  • SVN
  • Swoole
  • Sync
  • Taint
  • TCP
  • Tidy
  • Tokenizer
  • Trader
  • UI
  • ODBC
  • uopz
  • URLs
  • V8js
  • Manipulação de variável
  • var_representation
  • Varnish
  • WDDX
  • win32service
  • WinCache
  • wkhtmltox
  • xattr
  • xdiff
  • Xhprof
  • XLSWriter
  • Analisador de XML
  • XMLDiff
  • XMLReader
  • XML-RPC
  • XMLWriter
  • XSL
  • Yac
  • Yaconf
  • Yaf
  • Yaml
  • Yar
  • YAZ
  • Zip
  • Zlib
  • API de Mensagens 0MQ
  • ZooKeeper

User Contributed Notes

There are no user contributed notes for this page.


Sociedade

Extensões Principais

Essas não são de fato extensões. Eles são parte do núcleo do PHP e não podem ser deixadas de fora do binário do PHP através de opções de compilação.

  • Arrays

  • Classes/Objetos

  • Data/Hora

  • Diretórios

  • Gerenciamento de Erros

  • Execução de programa

  • Extensão Filesystem (Sistema de Arquivos)

  • FastCGI Process Manager

  • Gerenciamento de funções

  • Hash

  • Opções/Info do PHP

  • JSON

  • Mail

  • Math

  • Misc.

  • Network

  • OPcache

  • Controle de Saída

  • Password Hashing

  • PCRE

  • Random

  • Reflexão

  • SPL

  • Fluxos

  • Strings

  • URLs

  • Manipulação de variável

Extensões Agregadas

Essas extensões são distribuídas com o PHP.

  • Apache

  • BC Math

  • Calendar

  • COM

  • Ctype

  • DBA

  • Exif

  • FFI

  • Fileinfo

  • Filter

  • FTP

  • HRTime

  • iconv

  • GD

  • intl

  • Multibyte String

  • Mhash

  • PCNTL

  • PDO

  • Phar

  • phpdbg

  • POSIX

  • Semaphore

  • Sessões

  • Memória Compartilhada

  • Sockets

  • SQLite3

  • Tokenizer

  • Zlib

Extensões Externas

Para compilar essas extensões é preciso ter 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 and DB2 (PDO)

  • PostgreSQL (PDO)

  • SQLite (PDO)

  • PostgreSQL

  • Pspell

  • Readline

  • SimpleXML

  • SNMP

  • SOAP

  • Sodium

  • Tidy

  • ODBC

  • Analisador de XML

  • XMLReader

  • XMLWriter

  • XSL

  • Zip

Extensões PECL

Essas extensões estão disponíveis em » PECL. Elas podem requerer bibliotecas externas. Existem outras extensões PECL mas elas não estão documentadas no manual do PHP.

  • APCu

  • CommonMark

  • Componere

  • CUBRID

  • dBase

  • Direct IO

  • Data Structures

  • Eio

  • Ev

  • Event

  • Expect

  • FANN

  • FDF

  • Gearman

  • Gender

  • GeoIP

  • Gmagick

  • GnuPG

  • Firebird/InterBase

  • IBM DB2

  • Igbinary

  • ImageMagick

  • Inotify

  • Lua

  • LuaSandbox

  • LZF

  • Mailparse

  • Mcrypt

  • Memcache

  • Memcached

  • mqseries

  • MySQL (Original)

  • Mysql_xdevapi

  • OAuth

  • OpenAL

  • parallel

  • Parle

  • CUBRID (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MS SQL Server (PDO)

  • PS

  • pthreads

  • Quickhash

  • Radius

  • Rar

  • Recode

  • Rnp

  • RpmInfo

  • RRD

  • runkit7

  • ScoutAPM

  • Seaslog

  • Simdjson

  • Solr

  • SQLSRV

  • ssdeep

  • SSH2

  • Statistics

  • Stomp

  • SVM

  • SVN

  • Swoole

  • Sync

  • Taint

  • TCP

  • Trader

  • UI

  • uopz

  • V8js

  • var_representation

  • Varnish

  • WDDX

  • win32service

  • WinCache

  • wkhtmltox

  • xattr

  • xdiff

  • Xhprof

  • XLSWriter

  • XMLDiff

  • XML-RPC

  • Yac

  • Yaconf

  • Yaf

  • Yaml

  • Yar

  • YAZ

  • API de Mensagens 0MQ

  • ZooKeeper

User Contributed Notes

There are no user contributed notes for this page.


Estado

Essa parte lista as extensões não destinadas para uso de produção - elas são ou muito velhas (obsoletas) ou muito novas (experimentais).

Extensões Obsoletas

Essas extensões tornaram-se normalmente obsoletas em favor de outras extensões.

Extensões Experimentais

O comportamento dessas extensões - incluindo os nomes das suas funções e qualquer outra coisa documentada sobre essas extensões - podem mudar sem aviso em versões futuras do PHP. Use essas funções a seu próprio risco.

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


Lista de funções sinônimas (aliases)

Existem algumas poucas funções no PHP que podem ser chamadas com mais de um nome. Em alguns casos, não existe preferência entres os nomes, is_int() e is_integer() são igualmente boas, por exemplo. Entretanto existem funções que mudaram de nome para deixar API mais limpa ou por outras razões e os nomes antigos são apenas mantidos como aliases para compatibilidade com versões anteriores. Geralmente é uma má ideia usar este tipo de apelido, uma vez que eles estão obsoletos ou a ponto de serem renomeados definitivamente, o que levará a um script não portável. Esta lista é mantida para ajudá-los a atualizar scripts antigos para as novas sintaxes.

Aliases
Função sinônimo(Alias) | Função mestre | Extensão usada
_ | gettext() | Gettext
chop | rtrim() | Base syntax
close | closedir() | Base syntax
com_get | com_propget() | COM
com_propset | com_propput() | COM
com_set | com_propput() | COM
die | exit() | Miscellaneous functions
diskfreespace | disk_free_space() | Filesystem
doubleval | floatval() | Base syntax
fputs | fwrite() | Base syntax
gzputs | gzwrite() | Zlib
i18n_convert | mb_convert_encoding() | Multi-bytes Strings
i18n_discover_encoding | mb_detect_encoding() | Multi-bytes Strings
i18n_http_input | mb_http_input() | Multi-bytes Strings
i18n_http_output | mb_http_output() | Multi-bytes Strings
i18n_internal_encoding | mb_internal_encoding() | Multi-bytes Strings
i18n_ja_jp_hantozen | mb_convert_kana() | Multi-bytes Strings
i18n_mime_header_decode | mb_decode_mimeheader() | Multi-bytes Strings
i18n_mime_header_encode | mb_encode_mimeheader() | Multi-bytes Strings
imap_create | imap_createmailbox() | IMAP
imap_fetchtext | imap_body() | IMAP
imap_getmailboxes | imap_list_full() | IMAP
imap_getsubscribed | imap_lsub_full() | IMAP
imap_header | imap_headerinfo() | IMAP
imap_listmailbox | imap_list() | IMAP
imap_listsubscribed | imap_lsub() | IMAP
imap_rename | imap_renamemailbox() | IMAP
imap_scan | imap_listscan() | IMAP
imap_scanmailbox | imap_listscan() | IMAP
ini_alter | ini_set() | Base syntax
is_double | is_float() | Base syntax
is_integer | is_int() | Base syntax
is_long | is_int() | Base syntax
is_real | is_float() | Base syntax
is_writeable | is_writable() | Base syntax
join | implode() | Base syntax
key_exists | array_key_exists() | Base syntax
ldap_close | ldap_unbind() | LDAP
mbstrcut | mb_strcut() | Multi-bytes Strings
mbstrlen | mb_strlen() | Multi-bytes Strings
mbstrpos | mb_strpos() | Multi-bytes Strings
mbstrrpos | mb_strrpos() | Multi-bytes Strings
mbsubstr | mb_substr() | Multi-bytes Strings
mysql | mysql_db_query() | MySQL
mysql_createdb | mysql_create_db() | MySQL
mysql_db_name | mysql_result() | MySQL
mysql_dbname | mysql_result() | MySQL
mysql_dropdb | mysql_drop_db() | MySQL
mysql_fieldflags | mysql_field_flags() | MySQL
mysql_fieldlen | mysql_field_len() | MySQL
mysql_fieldname | mysql_field_name() | MySQL
mysql_fieldtable | mysql_field_table() | MySQL
mysql_fieldtype | mysql_field_type() | MySQL
mysql_freeresult | mysql_free_result() | MySQL
mysql_listdbs | mysql_list_dbs() | MySQL
mysql_listfields | mysql_list_fields() | MySQL
mysql_listtables | mysql_list_tables() | MySQL
mysql_numfields | mysql_num_fields() | MySQL
mysql_numrows | mysql_num_rows() | MySQL
mysql_selectdb | mysql_select_db() | MySQL
mysql_tablename | mysql_result() | MySQL
ociassignelem | OCICollection::assignElem | OCI8
ocibindbyname | oci_bind_by_name() | OCI8
ocicancel | oci_cancel() | OCI8
ocicloselob | OCILob::close | OCI8
ocicollappend | OCICollection::append | OCI8
ocicollassign | OCICollection::assign | OCI8
ocicollmax | OCICollection::max | OCI8
ocicollsize | OCICollection::size | OCI8
ocicolltrim | OCICollection::trim | OCI8
ocicolumnisnull | oci_field_is_null() | OCI8
ocicolumnname | oci_field_name() | OCI8
ocicolumnprecision | oci_field_precision() | OCI8
ocicolumnscale | oci_field_scale() | OCI8
ocicolumnsize | oci_field_size() | OCI8
ocicolumntype | oci_field_type() | OCI8
ocicolumntyperaw | oci_field_type_raw() | OCI8
ocicommit | oci_commit() | OCI8
ocidefinebyname | oci_define_by_name() | OCI8
ocierror | oci_error() | OCI8
ociexecute | oci_execute() | OCI8
ocifetch | oci_fetch() | OCI8
ocifetchinto | oci_fetch_array(), oci_fetch_row(), oci_fetch_assoc(), oci_fetch_object() | OCI8
ocifetchstatement | oci_fetch_all() | OCI8
ocifreecollection | OCICollection::free | OCI8
ocifreecursor | oci_free_statement() | OCI8
ocifreedesc | oci_free_descriptor() | OCI8
ocifreestatement | oci_free_statement() | OCI8
ocigetelem | OCICollection::getElem | OCI8
ociinternaldebug | oci_internal_debug() | OCI8
ociloadlob | OCILob::load | OCI8
ocilogon | oci_connect() | OCI8
ocinewcollection | oci_new_collection() | OCI8
ocinewcursor | oci_new_cursor() | OCI8
ocinewdescriptor | oci_new_descriptor() | OCI8
ocinlogon | oci_new_connect() | OCI8
ocinumcols | oci_num_fields() | OCI8
ociparse | oci_parse() | OCI8
ocipasswordchange | oci_password_change() | OCI8
ociplogon | oci_pconnect() | OCI8
ociresult | oci_result() | OCI8
ocirollback | oci_rollback() | OCI8
ocisavelob | OCILob::save | OCI8
ocisavelobfile | OCILob::import | OCI8
ociserverversion | oci_server_version() | OCI8
ocisetprefetch | oci_set_prefetch() | OCI8
ocistatementtype | oci_statement_type() | OCI8
ociwritelobtofile | OCILob::export | OCI8
ociwritetemporarylob | OCILob::writeTemporary | OCI8
odbc_do | odbc_exec() | ODBC
odbc_field_precision | odbc_field_len() | ODBC
pg_clientencoding | pg_client_encoding() | PostgreSQL
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL
pos | current() | Base syntax
recode | recode_string() | Recode
show_source | highlight_file() | Base syntax
sizeof | count() | Base syntax
snmpwalkoid | snmprealwalk() | SNMP
strchr | strstr() | Base syntax
xptr_new_context | xpath_new_context() |

User Contributed Notes

There are no user contributed notes for this page.


Lista de Palavras Reservadas do PHP

Índice

  • Lista de Palavras-chave (Keywords)
  • Classes Predefinidas
  • Constantes Pré-definidas
  • Lista de outras palavras reservadas

Esta é uma lista de identificadores predefinidos do PHP. Nenhum dos identificadores listados aqui deve ser usado como identificador em qualquer um dos seus scripts a menos que seja explicitamente indicado. Esta lista inclui palavras-chave e variáveis predefinidas, constantes e nomes de classes. Estas listas ainda não são exaustivas nem completas.

User Contributed Notes

There are no user contributed notes for this page.


Lista de Palavras-chave (Keywords)

Estas palavras têm um significado especial no PHP. Algumas delas representam coisas que parecem funções, algumas parecem constantes, e assim por diante - mas na verdade não o são realmente: elas são constructos da linguagem. As palavras seguintes não podem ser usadas como constantes, nomes de classes, ou nome de funções. Estas palavras-chave são permitidas em propriedades, constantes e nomes de métodos em classes, interfaces e traits, com exceção de class, que não pode ser utilizada como nome de constante.

Palavras-chave do 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 (desde o PHP 7.4) | for | foreach
function | global | goto | if | implements
include | include_once | instanceof | insteadof | interface
isset() | list() | match (desde o PHP 8.0) | namespace | new
or | print | private | protected | public
readonly (desde o PHP 8.1.0) * | require | require_once | return | static
switch | throw | trait | try | unset()
use | var | while | xor | yield
yield from |  |  |  |

* readonly pode ser utilizado como nome de função

Constantes de tempo de compilação
__CLASS__ | __DIR__ | __FILE__ | __FUNCTION__ | __LINE__ | __METHOD__
__NAMESPACE__ | __TRAIT__ |  |  |  |

User Contributed Notes

Johnny D. 22-May-2020 06:37
const FORBIDDEN_TYPES = [
    'null',

    'bool',
    'false',
    'true',

    'int',
    'float',

    'string',
];
Thomas Hansen 15-Aug-2016 10:08
Please note that reserved words are still not allowed to be used as namespace or as part of it:

<?php
namespace MyNameSpace\List;

class Test
{
}
?>

This will fail with a Parse error:  syntax error, unexpected 'List' (T_LIST), expecting identifier (T_STRING)
martindilling at gmail dot com 15-Apr-2013 10:20
RegEx to find all the keywords:

\b(
(a(bstract|nd|rray|s))|
(c(a(llable|se|tch)|l(ass|one)|on(st|tinue)))|
(d(e(clare|fault)|ie|o))|
(e(cho|lse(if)?|mpty|nd(declare|for(each)?|if|switch|while)|val|x(it|tends)))|
(f(inal|or(each)?|unction))|
(g(lobal|oto))|
(i(f|mplements|n(clude(_once)?|st(anceof|eadof)|terface)|sset))|
(n(amespace|ew))|
(p(r(i(nt|vate)|otected)|ublic))|
(re(quire(_once)?|turn))|
(s(tatic|witch))|
(t(hrow|r(ait|y)))|
(u(nset|se))|
(__halt_compiler|break|list|(x)?or|var|while)
)\b
Chris 04-Oct-2012 04:33
Here they are as arrays:

<?php
$keywords = array('__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor');

$predefined_constants = array('__CLASS__', '__DIR__', '__FILE__', '__FUNCTION__', '__LINE__', '__METHOD__', '__NAMESPACE__', '__TRAIT__');
?>

Along with get_defined_functions() and get_defined_constants(), this can be useful for checking eval() statements.


Classes Predefinidas

Esta seção lista classes predefinidas padrão. Extensões diversas definem outras classes que são descritas em suas referências.

Classes Definidas Padrão

Estas classes são definidas dentro do conjunto padrão de funções incluídas na compilação do PHP.

Directory
Criada pela função dir().
stdClass
Uma classe vazia criada como o resultado de coerção para objeto ou funções padrão da linguagem.
__PHP_Incomplete_Class
Possivelmente criada pela função unserialize().
Exception
ErrorException
php_user_filter
Closure
A classe predefinida final Closure é utilizada para representar funções anônimas.
Generator
A classe predefinida final Generator é utilizada para representar geradores.
ArithmeticError
AssertionError
DivisionByZeroError
Error
Throwable
ParseError
TypeError

Classes especiais

Os seguintes identificadores não podem ser usados como nome de classe pois eles têm um propósito especial.

self
Classe atual.
static
Classe atual em tempo de execução.
parent
Classe pai.

User Contributed Notes

xzero at elite7hackers dot net 08-Sep-2017 08:37
There comes improved version of amazing snippet posted by (spark at limao dot com dot br)  which allows dynamic methods generations and works as versatile extension of StdClass:

This one is faster, optimised for closures, and will work only with closures. Compatible: >= PHP 5.6
<?php

class Dynamic extends \stdClass
{
    public function __call($key, $params)
    {
        if ( ! isset($this->{$key})) {
            throw new Exception("Call to undefined method " . __CLASS__ . "::" . $key . "()");
        }

        return $this->{$key}->__invoke(... $params);
    }
}

?>

Usage examples:

<?php
$dynamic                = new Dynamic();
$dynamic->anotherMethod = function () {
    echo "Hey there";
};
$dynamic->randomInt     = function ($min, $max) {
    return mt_rand($min, $max); // random_int($min, $max); // <-- PHP7+
};

var_dump(
    $dynamic->randomInt(1, 11),
    $dynamic->anotherMethod()
);
?>

This will accept arrays, strings and Closures but is a bit slower due to call_user_func_array
<?php

class Dynamic extends \stdClass
{
    public function __call($key, $params)
    {
        if ( ! isset($this->{$key})) {
            throw new Exception("Call to undefined method " . __CLASS__ . "::" . $key . "()");
        }

        return call_user_func_array($this->{$key}, $params);
    }
}

?>

Usage examples:
<?php
$dynamic                = new Dynamic();
$dynamic->myMethod      = "thatFunction";
$dynamic->hisMethod     = array($dynamic, "randomInt");
$dynamic->newMethod     = array(SomeClass, "staticMethod");
$dynamic->anotherMethod = function () {
    echo "Hey there";
};
$dynamic->randomInt     = function ($min, $max) {
    return mt_rand($min, $max); // random_int($min, $max); // <-- PHP7+
};

var_dump(
    $dynamic->randomInt(1, 11),
    $dynamic->anotherMethod(),
    $dynamic->hisMethod()
);

?>
xzero at elite7hackers dot net 08-Sep-2017 08:32
There comes improved version of amazing snippet posted by which allows dynamic methods generations and works as versatile extension of StdClass:

This one is faster, optimised for closures, and will work only with closures. Compatible: >= PHP 5.6
<?php

class Dynamic extends \stdClass
{
    public function __call($key, $params)
    {
        if ( ! isset($this->{$key})) {
            throw new Exception("Call to undefined method " . __CLASS__ . "::" . $key . "()");
        }

        return $this->{$key}->__invoke(... $params);
    }
}

?>

Usage examples:

<?php
$dynamic                = new Dynamic();
$dynamic->anotherMethod = function () {
    echo "Hey there";
};
$dynamic->randomInt     = function ($min, $max) {
    return mt_rand($min, $max); // random_int($min, $max); // <-- PHP7+
};

var_dump(
    $dynamic->randomInt(1, 11),
    $dynamic->anotherMethod()
);
?>

This will accept arrays, strings and Closures but is a bit slower due to call_user_func_array
<?php

class Dynamic extends \stdClass
{
    public function __call($key, $params)
    {
        if ( ! isset($this->{$key})) {
            throw new Exception("Call to undefined method " . __CLASS__ . "::" . $key . "()");
        }

        return call_user_func_array($this->{$key}, $params);
    }
}

?>

Usage examples:
<?php
$dynamic                = new Dynamic();
$dynamic->myMethod      = "thatFunction";
$dynamic->hisMethod     = array($dynamic, "randomInt");
$dynamic->newMethod     = array(SomeClass, "staticMethod");
$dynamic->anotherMethod = function () {
    echo "Hey there";
};
$dynamic->randomInt     = function ($min, $max) {
    return mt_rand($min, $max); // random_int($min, $max); // <-- PHP7+
};

var_dump(
    $dynamic->randomInt(1, 11),
    $dynamic->anotherMethod(),
    $dynamic->hisMethod()
);

?>
Ashley Dambra 19-Feb-2014 06:43
Here a simple class that allow to set anonymous function. It's an optimised class of stdClass.

<?php
class stdObject {
    public function __construct(array $arguments = array()) {
        if (!empty($arguments)) {
            foreach ($arguments as $property => $argument) {
                if ($argument instanceOf Closure) {
                    $this->{$property} = $argument;
                } else {
                    $this->{$property} = $argument;
                }
            }
        }
    }

    public function __call($method, $arguments) {
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
        }
    }
}

$person = new stdObject(array(
    "name" => "nick",
    "age" => 23,
    "friends" => array("frank", "sally", "aaron"),
    "sayHi" => function() {
        return "Hello there";
    }
));

$person->sayHi2 = function() {
    return "Hello there 2";
};

$person->test = function() {
    return "test";
};

var_dump($person->name, $person->test(), $person->sayHi2());
?>
wyattstorch42 at outlook dot com 24-Dec-2013 01:15
If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.

However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I'd advise you to implement ::__set_state().

<?php
/**
 * An implementation of var_export() that is compatible with instances
 * of stdClass.
 * @param mixed $variable The variable you want to export
 * @param bool $return If used and set to true, improved_var_export()
 *     will return the variable representation instead of outputting it.
 * @return mixed|null Returns the variable representation when the
 *     return parameter is used and evaluates to TRUE. Otherwise, this
 *     function will return NULL.
 */
function improved_var_export ($variable, $return = false) {
    if ($variable instanceof stdClass) {
        $result = '(object) '.improved_var_export(get_object_vars($variable), true);
    } else if (is_array($variable)) {
        $array = array ();
        foreach ($variable as $key => $value) {
            $array[] = var_export($key, true).' => '.improved_var_export($value, true);
        }
        $result = 'array ('.implode(', ', $array).')';
    } else {
        $result = var_export($variable, true);
    }

    if (!$return) {
        print $result;
        return null;
    } else {
        return $result;
    }
}

// Example usage:
$obj = new stdClass;
$obj->test = 'abc';
$obj->other = 6.2;
$obj->arr = array (1, 2, 3);

improved_var_export((object) array (
    'prop1' => true,
    'prop2' => $obj,
    'assocArray' => array (
        'apple' => 'good',
        'orange' => 'great'
    )
));

/* Output:
(object) array ('prop1' => true, 'prop2' => (object) array ('test' => 'abc', 'other' => 6.2, 'arr' => array (0 => 1, 1 => 2, 2 => 3)), 'assocArray' => array ('apple' => 'good', 'orange' => 'great'))
*/
?>

Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn't formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().
spark at limao dot com dot br 15-Aug-2011 02:21
if you want a Dynamic class you can extend from, add atributes AND methods on the fly you can use this:
<?php
    class Dynamic extends stdClass{
        public function __call($key,$params){
            if(!isset($this->{$key})) throw new Exception("Call to undefined method ".get_class($this)."::".$key."()");
            $subject = $this->{$key};
            call_user_func_array($subject,$params);
        }
    }
?>

this will accept both arrays, strings and Closures:
<?php
    $dynamic->myMethod = "thatFunction";
    $dynamic->hisMethod = array($instance,"aMethod");
    $dynamic->newMethod = array(SomeClass,"staticMethod");
    $dynamic->anotherMethod = function(){
        echo "Hey there";
    };
?>

then call them away =D
Typer85 at gmail dot com 17-Feb-2007 08:58
In response to the note below mine,

This list is not incomplete. Read the Manual folks, its listed there plain and simple:

"This section lists standard predefined classes. Miscellaneous extensions define other classes which are described in their reference."

Depending on what extensions you have, they might define their own classes. This list is just the standard classes as defined by PHP with no regards to extensions.
unknown 23-Jul-2002 10:29
It's handy to have a array of the reserved classes.....
var_dump (get_declared_classes ());


Constantes Pré-definidas

Principais Constantes Predefinidas

Essas constantes são definidas pelo núcleo do PHP. Isso inclui o PHP, o engine do Zend e módulos SAPI.

PHP_VERSION (string)
A versão atual do PHP como uma string no formato "major.minor.release[extra]".
PHP_MAJOR_VERSION (int)
O número de versão "major" do PHP como um inteiro (exemplo: int(5) para a versão "5.2.7-extra").
PHP_MINOR_VERSION (int)
O número de versão "minor" do PHP como um inteiro (exemplo: int(2) para a versão "5.2.7-extra").
PHP_RELEASE_VERSION (int)
O número de versão "release" do PHP como um inteiro (exemplo: int(7) para a versão "5.2.7-extra").
PHP_VERSION_ID (int)
A versão atual do PHP como um inteiro, útil para comparações entre versões (exemplo: int(50207) na versão "5.2.7-extra").
PHP_EXTRA_VERSION (string)
A versão "extra" do PHP como uma string (exemplo: '-extra' na versão "5.2.7-extra"). Geralmente utilizado por distribuidores para indicar uma versão de empacotamento.
PHP_ZTS (int)
PHP_DEBUG (int)
PHP_MAXPATHLEN (int)
O tamanho máximo do nome de um arquivo (incluindo seus diretórios) suportado nesta versão do PHP.
PHP_OS (string)
O sistema operacional para o qual o PHP foi compilado.
PHP_OS_FAMILY (string)
A família do sistema operacional para o qual o PHP foi compilado. Qualquer uma entre 'Windows', 'BSD', 'Darwin', 'Solaris', 'Linux' ou 'Unknown'. Disponível a partir do PHP 7.2.0.
PHP_SAPI (string)
O nome da Server API para esta compilação do PHP. Veja também php_sapi_name().
PHP_EOL (string)
O símbolo correto de 'Fim de linha' para esta plataforma.
PHP_INT_MAX (int)
O maior inteiro suportado nesta compilação do PHP. Geralmente int(2147483647) em sistemas de 32 bit e int(9223372036854775807) em sistemas de 64 bits.
PHP_INT_MIN (int)
O menor inteiro suportado nesta compilação do PHP. Geralmente int(-2147483648) em sistemas 32 bits e int(-9223372036854775808) em sistemas 64 bit. Normalmente PHP_INT_MIN === ~PHP_INT_MAX.
PHP_INT_SIZE (int)
O tamanho de um inteiro em bytes nesta compilação do PHP.
PHP_FLOAT_DIG (int)
Número de dígitos decimais que podem ser arredondados para um float e recuperados sem perda de precisão. Disponível a partir do PHP 7.2.0.
PHP_FLOAT_EPSILON (float)
O menor número positivo representável x, tal que x + 1.0 != 1.0. Disponível a partir do PHP 7.2.0.
PHP_FLOAT_MIN (float)
O menor número de ponto flutuante positivo representável. Se você precisar do menor número de ponto flutuante negativo, use - PHP_FLOAT_MAX. Disponível a partir do PHP 7.2.0.
PHP_FLOAT_MAX (float)
O maior número de ponto flutuante representável. Disponível a partir do PHP 7.2.0.
DEFAULT_INCLUDE_PATH (string)
PEAR_INSTALL_DIR (string)
PEAR_EXTENSION_DIR (string)
PHP_EXTENSION_DIR (string)
O diretório padrão onde localizar extensões carregáveis dinamicamente (podendo ser sobrescrito por extension_dir). Tem como o padrão PHP_PREFIX (ou PHP_PREFIX . "\\ext" no Windows).
PHP_PREFIX (string)
O valor --prefix foi configurado durante o configure. No Windows, este é o valor de --with-prefix informado no configure.
PHP_BINDIR (string)
O valor --bindir foi configurado no configure. No Windows, é o valor informado em --with-prefix durante o configure.
PHP_BINARY (string)
Especifica o caminho do binário do PHP utilizado na execução do script.
PHP_MANDIR (string)
Especifica onde as páginas do manual foram instaladas.
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)
O sufixo de bibliotecas compartilhadas da plataforma na qual o PHP foi compilado. Geralmente "so" (Unixes) ou "dll" (Windows).
PHP_FD_SETSIZE (int)
O número máximo de descritores de arquivos para as chamadas de sistema select. Disponível a partir do PHP 7.1.0.
E_ERROR (int)
Constante para relatório de erros
E_WARNING (int)
Constante para relatório de erros
E_PARSE (int)
Constante para relatório de erros
E_NOTICE (int)
Constante para relatório de erros
E_CORE_ERROR (int)
Constante para relatório de erros
E_CORE_WARNING (int)
Constante para relatório de erros
E_COMPILE_ERROR (int)
Constante para relatório de erros
E_COMPILE_WARNING (int)
Constante para relatório de erros
E_USER_ERROR (int)
Constante para relatório de erros
E_USER_WARNING (int)
Constante para relatório de erros
E_USER_NOTICE (int)
Constante para relatório de erros
E_RECOVERABLE_ERROR (int)
Constante para relatório de erros.
E_DEPRECATED (int)
Constante para relatório de erros.
E_USER_DEPRECATED (int)
Constante para relatório de erros.
E_ALL (int)
Constante para relatório de erros
E_STRICT (int)
Constante para relatório de erros
__COMPILER_HALT_OFFSET__ (int)
true (bool)
Veja Booleanos.
false (bool)
Veja Booleanos.
null (null)
Veja Null.
PHP_WINDOWS_EVENT_CTRL_C (int)
Um evento do Windows CTRL+C. Disponível a partir do PHP 7.4.0 (somente para o Windows).
PHP_WINDOWS_EVENT_CTRL_BREAK (int)
Um evento do Windows CTRL+BREAK. Disponível a partir do PHP 7.4.0 (somente para o Windows).

Veja também: Constantes Mágicas.

Constantes Padrão Predefinidas

Todas as constantes de extensões do núcleo são definidas no PHP por padrão.

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

}
?>


Lista de outras palavras reservadas

As palavras a seguir não podem ser utilizadas como nome de classes, interfaces ou traits. Anteriormente ao PHP 8.0, também eram proibidas de ser usadas em namespaces.

Palavras reservadas
int | float | bool | string
true | false | null | void (a partir do PHP 7.1)
iterable (a partir do PHP 7.1) | object (a partir do PHP 7.2) | mixed (a partir do PHP 8.0) | never (a partir do PHP 8.1)

A seguinte lista de palavras tem reservas brandas. Embora elas possam ser utilizadas como nomes de classes, interfaces e traits, seu uso é altamente desencorajado pois elas podem se tornar palavras reservadas em versões futuras do PHP.

Palavras reservadas brandas
enum resource numeric

User Contributed Notes

There are no user contributed notes for this page.


Lista de tipos de recursos no PHP

Abaixo segue a lista de funções possíveis para manipular os recursos no PHP. A função is_resource() pode ser usada para identificar se a variável é um recurso enquanto get_resource_type() pode ser utilizada para retornar o tipo de recurso.

Tipos de recursos
Nome dos tipos de recursos | Criado por | Utilizo em | Deletado por | Definido
AddressInfo | socket_addrinfo_lookup() | socket_addrinfo_bind(), socket_addrinfo_connect(), socket_addrinfo_explain(), | None | AddressInfo (extensão sockets)
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Bzip2 file
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() | Conexão pelo banco de dados CUBRID
conexão em persistência cubrid | 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() | Conexão em persistência pelo banco de dados 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() | CUBRID request
cubrid lob | cubrid_lob_get() | cubrid_lob_export() cubrid_lob_send() cubrid_lob_size() | cubrid_lob_close() | None
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() | None
curl | curl_copy_handle(), curl_init() | curl_copy_handle(), curl_errno(), curl_error(), curl_exec(), curl_getinfo(), curl_setopt() | curl_close() | cURL handle
curl_multi | curl_multi_init() | curl_multi_errno(), curl_multi_exec(), curl_multi_info_read(), curl_multi_remove_handle(), curl_multi_select(), curl_multi_setopt() | curl_multi_close() | cURL multi handle
curl_share | curl_share_init() | curl_share_errno(), curl_share_setopt() | curl_share_close() | cURL share handle
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Link to DBA database
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | None | Persistent link to DBA database
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Link to Dbase database
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 (anteriormente ao 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 (anteriormente ao 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() | Arquivo 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() | FTP stream (anteriormente ao PHP 8.1.0)
gd | imagecreate(), imagecreatefromgd(), imagecreatefromgd2(), imagecreatefromgd2part(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatefromxbm(), imagecreatefromxpm(), imagecreatetruecolor(), imagerotate() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagerectangle(), imagerotate(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness(), image2wbmp(), imagealphablending(), imageantialias(), imagecolorallocatealpha(), imagecolorclosesthwb(), imagecolordeallocate(), imagecolormatch(), imagefilter(), imagefttext(), imagegd(), imagegd2(), imageistruecolor(), imagelayereffect(), imagepalettecopy(), imagesavealpha(), imagesetstyle(), imagexbm() | imagedestroy() | Imagem GD (anteriormente ao PHP 8.0.0)
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | None | Fonte para GD (anteriormente ao PHP 8.1.0)
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Link para os servidores IMAP e POP3 (anteriormente ao PHP 8.1.0)
interbase blob | ibase_blob_create(), ibase_blob_import(), ibase_blob_open() | ibase_blob_add(), ibase_blob_cancel(), ibase_blob_echo(), ibase_blob_get(), ibase_blob_info() | ibase_blob_close()
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Link to Interbase database
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | None | Conexão em persistência no banco de dados Interbase
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase query
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase Result
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase transaction
Link ldap | 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() | Conexão ldap (anteriormente ao PHP 8.1.0)
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | ldap search result (anteriormente ao PHP 8.1.0)
ldap result entry | ldap result entry (anteriormente ao PHP 8.1.0)
mailparse_mail_structure | mailparse_msg_create() mailparse_msg_parse_file() | mailparse_msg_extract_part_file() mailparse_msg_extract_part() mailparse_msg_extract_whole_part_file() mailparse_msg_get_part_data() mailparse_msg_get_part() mailparse_msg_get_structure() mailparse_msg_parse() | mailparse_msg_free()
Conexão mysql | 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() | Conexão para o banco de dados MySQL
Conexão persistênte para mysql | 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() | None | Conexão persistênte para MySQL
Resultado mysql | 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 MySQL
oci8 collection | oci_new_collection() | OCICollection::append(), OCICollection::assign(), OCICollection::assignElem(), OCICollection::getElem(), OCICollection::max(), OCICollection::size(), OCICollection::trim() | OCICollection::free() | Oracle Collection
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() | Connection to Oracle Database
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() | Oracle large objects
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() | Oracle cursor
Conexão odbc | 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() | Conexão para o banco de dados ODBC
Conexão persistênte para odbc | odbc_pconnect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | Nenhum | Conexão persistênte no ODBC
Resultado odbc | 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 ODBC
Conexão birdstep | Link to Birdstep database (anteriormente ao PHP 7.3.0)
Resultado birdstep | Birdstep result (anteriormente ao PHP 7.3.0)
Chave OpenSSL | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | Chave OpenSSL
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Chave 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() | PostgreSQL Large Object (anteriormente ao PHP 8.1.0)
Conexão pgsql | 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() | Conexão no banco de dados PostgreSQL (anteriormente ao PHP 8.1.0)
Conexão em persistência pgsql | 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() | Nenhum | Conexão em persistência PostgreSQL
Resultado pgsql | 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 PostgreSQL (anteriormente ao PHP 8.1.0)
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() | Nenhum | pspell dictionary (anteriormente ao PHP 8.1.0)
Configuração pspell | pspell_config_create() | pspell_new_config() | None | pspell configuration (anteriormente ao PHP 8.1.0)
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close() | Identificador de bloco de memória compartilhada (anteriormente ao 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 (extensão sockets)
stream | opendir() | readdir(), rewinddir() | closedir() | Dir handle
stream | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | File handle
stream | popen(), fsockopen(), pfsockopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Process handle
socket | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket handle
SSH2 Session | ssh2_connect() | ssh2_disconnect()
SSH2 Listener | ssh2_forward_listen()
SSH2 SFTP | ssh2_sftp()
SSH2 Publickey Subsystem | ssh2_publickey_init()
sysvmsg queue | msg_get_queue() | msg_queue_exists(), msg_receive(), msg_send(), msg_set_queue(), msg_stat_queue() | msg_remove_queue() | System V Message Queue (anteriormente ao PHP 8.0.0)
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore (anteriormente ao PHP 8.0.0)
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | Sistema V de memória compartilhada (anteriormente ao PHP 8.0.0)
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX packet
xml | xml_parser_create(), xml_parser_create_ns() | xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | XML parser (anteriormente ao PHP 8.0.0)
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-compressed file
zlib.deflate | deflate_init() | deflate_add() | None | incremental deflate context (anteriormente ao PHP 8.0.0)
zlib.inflate | inflate_init() | inflate_add(), inflate_get_read_len(), inflate_get_status() | None | incremental inflate context (anteriormente ao 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 Disponíveis

Índice

  • Filtros de String
  • Fitros de Conversão
  • Filtros de Compressão
  • Filtros de Criptografia

A seguir está uma lista de alguns filtros internos de stream para uso com stream_filter_append(). Sua versão do PHP pode ter mais filtros (ou menos) que os listados aqui.

Vale notar que existe uma leve assimetria entre stream_filter_append() e stream_filter_prepend(). Toda stream no PHP contém um pequeno buffer de leitura onde ela guarda blocos de dados recuperados do sistema de arquivos ou outro recurso (resource) com o propósito de processar dados da maneira mais eficiente. Assim que os dados são recuperados do recurso para o buffer interno da stream, eles são processados imediatamente por qualquer filtro anexo quer esteja a aplicação PHP preparada para receber os dados ou não. Se os dados estão esperando no buffer de leitura quando um filtro for anexado, esses dados serão imediatamente processados através daquele filtro, fazendo o fato de que eles estavam esperando no buffer transparente. No entanto, se os dados estão esperando no buffer de leitura quando um filtro é prefixado, esses dados NÃO serão processados por este filtro. Ao invés disso, eles esperarão até o próximo bloco de dados ser recuperado do recurso.

Para uma lista dos filtros instalados na sua versão do PHP use stream_get_filters().

User Contributed Notes

There are no user contributed notes for this page.


Filtros de String

Cada um destes filtros faz precisamente o que o seu nome implica e corresponde ao comportamento da função interna de tratamento de string homônima. Para mais informações sobre um determinado filtro, veja a página do manual para a função correspondente.

string.rot13

O uso desse filtro é equivalente a processar todos os dados da stream com a função str_rot13().

Exemplo #1 string.rot13

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "Isto é um teste.\n");
/* Saída: Vfgb é hz grfgr. */
?>

string.toupper

O uso desse filtro é equivalente a processar todos os dados da stream com a função strtoupper().

Exemplo #2 string.toupper

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "Isto é um teste.\n");
/* Saída: ISTO é UM TESTE. */
?>

string.tolower

O uso desse filtro é equivalente a processar todos os dados da stream com a função strtolower().

Exemplo #3 string.tolower

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "Isto é um teste.\n");
/* Saída: isto é um teste. */
?>

string.strip_tags

O uso desse filtro é equivalente a processar todos os dados da stream com a função strip_tags(). Ela aceita parâmetros em uma das duas formas: Ou como uma string contendo uma lista de tags similares ao segundo parâmetro da função strip_tags(), ou como um array com os nomes das tags.

Aviso

Este recurso tornou-se OBSOLETO a partir do PHP 7.3.0. O uso deste recurso é fortemente desencorajado.

Exemplo #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 em negrito</b> aumentado para um <h1>heading de nível 1</h1>\n");
fclose($fp);
/* Saída : texto em negrito</b> aumentado para um heading de nível 1 */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('b','i','u'));
fwrite($fp, "<b>texto em negrito</b> aumentado para um <h1>heading de nível 1</h1>\n");
fclose($fp);
/* Saída: texto em negrito</b> aumentado para um heading de nível 1 */
?>

User Contributed Notes

There are no user contributed notes for this page.


Fitros de Conversão

Como todos os filtros string.*, os filtros convert.* realizam ações similares aos seus nomes. Para mais informações sobre um determinado filtro, veja a página do manual para a função correspondente.

convert.base64-encode e convert.base64-decode

O uso desses filtros é equivalente a processar todos os dados da stream com as funções base64_encode() e base64_decode() respectivamente. convert.base64-encode suporta parâmetros no formato de um array associativo. Se line-length for passado, a saída do base64 será dividida em pedaços de line-length caracteres cada. Se line-break-chars for passado, cada pedaço será delimitado pelos caracteres passados. Esses parâmetros dão o mesmo efeito que usar base64_encode() com chunk_split().

Exemplo #1 convert.base64-encode & convert.base64-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "Isto é um teste.\n");
fclose($fp);
/* Saída: SXN0byDDqSB1bSB0ZXN0ZS4K */

$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, "Isto é um teste.\n");
fclose($fp);
/* Saída : SXN0byDD
: qSB1bSB0
: ZXN0ZS4K */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "SXN0byDDqSB1bSB0ZXN0ZS4K");
fclose($fp);
/* Saída: Isto é um teste. */
?>

convert.quoted-printable-encode e convert.quoted-printable-decode

O uso da versão de decodificação desse filtro é equivalente ao processamento de todos os dados da stream pela função quoted_printable_decode(). Não há nenhuma função equivalente a convert.quoted-printable-encode. convert.quoted-printable-encode suporta parâmetros passados como um array associativo. Além dos parâmetros suportados por convert.base64-encode, convert.quoted-printable-encode também suporta os argumentos booleanos binary e force-encode-first. convert.base64-decode suporta apenas o parâmetro line-break-chars como uma dica de tipo para retirar do conteúdo codificado.

Exemplo #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, "Isto é um teste.\n");
/* Saída: Isto =C3=A9 um teste.=0A */
?>

convert.iconv.*

Os filtros convert.iconv.* estarão disponíveis se o suporte a iconv estiver habilitado, e se sua utilização é equivalente a processar todos os dados do stream através do iconv(). Esses filtros não suportam parâmetros, em vez disso esperam que as codificações de entrada e saída sejam informados no nome do filtro, por exemplo, convert.iconv.<input-encoding>.<output-encoding> ou convert.iconv.<input-encoding>/<output-encoding> (ambas notações são equivalentes).

Exemplo #3 convert.iconv.*

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.iconv.utf-16le.utf-8');
fwrite($fp, "T\0h\0i\0s\0 \0i\0s\0 \0a\0 \0t\0e\0s\0t\0.\0\n\0");
fclose($fp);
/* Outputs: This is a test. */
?>

User Contributed Notes

marcus at synchromedia dot co dot uk 10-May-2022 09:50
It's not quite obvious what all the available parameters are for convert.quoted-printable-encode. If you want the stream filter to act the same way as the quoted_printable_encode function, you need these extra params, for example:

stream_filter_append(
    STDOUT,
    'convert.quoted-printable-encode',
    STREAM_FILTER_WRITE,
    [
        'line-break-chars' => PHP_EOL,
        'line-length' => 75,
    ]
);
echo stream_copy_to_stream(STDIN, STDOUT);

Without these extra params set, you may get no wrapping at all, or wrapping using the wrong line break sequence.


Filtros de Compressão

Enquanto os Wrappers de Compressão fornecem uma maneira de criar arquivos compatíveis com gzip e bz2 no sistema de arquivos local, eles não fornecem um meio para compressão generalizada sobre streams de rede, nem fornecem uma maneira de começar com uma stream não-comprimida e mudar para uma comprimida. Para isso, um filtro de compressão pode ser aplicado a qualquer recurso de stream em qualquer momento.

Nota: Filtros de compressão não geram cabeçalhos e rodapés usados por utilitários de linha de comando como o gzip. Eles apenas comprimem e descomprimem as porções de conteúdo das streams de dados comprimidas.

zlib.deflate and zlib.inflate

zlib.deflate (compressão) e zlib.inflate (descompressão) são implementações dos métodos de compressão descritos no » RFC 1951. O filtro deflate recebe até três parâmetros passados como um array associativo. level descreve o nível de compressão a ser usada (1-9). Números mais altos geralmente resultam em cargas menores com o custo de tempo de processamento adicional. Dois níveis especiais de compressão também existem: 0 (para nenhuma compressão), e -1 (padrão interno da zlib -- atualmente 6). window é o logaritmo na base 2 do tamanho da janela de loopback de compressão. Valores mais altos (até 15 -- 32768 bytes) resultam em melhor compressão ao custo de memória, enquanto valores menores (até 9 -- 512 bytes) resultam em pior compressão usando menos memória. O tamanho padrão de window atualmente é 15. memory é uma escala indicando quanta memória deve ser alocada para trabalhar. Valores válidos vão de 1 (alocação mínima) até 9 (alocação máxima). Essa alocação de memória afeta apenas a velocidade e não tem impacto sobre o tamanho do conteúdo gerado.

Nota: Pelo fato do nível de compressão ser o parâmetro mais usado normalmente, ele pode ser passado de maneira alternativa como um simples valor inteiro (ao invés de um elemento de um array).

Filtros de compressão zlib.* compression estarão disponíveis se o suporte ao zlib estiver ativado.

Exemplo #1 zlib.deflate e zlib.inflate

<?php
$params = array('level' => 6, 'window' => 15, 'memory' => 9);

$original_text = "Isto é um teste.\nIsto é apenas um teste.\nEsta não é uma string importante.\n";
echo "O texto original tem " . strlen($original_text) . " caracteres.\n";

$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);

echo "O arquivo comprimido tem " . filesize('test.deflated') . " bytes.\n";
echo "O texto original era:\n";
/* Use readfile e zlib.inflate para descomprimir de forma improvisada */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Gera a saída:

O texto original tem 79 caracteres.
O arquivo comprimido tem 61 bytes.
O texto original era:
Isto é um teste.
Isto é apenas um teste.
Esta não é uma string importante.

*/
?>

Exemplo #2 zlib.deflate simples

<?php
$original_text = "Isto é um teste.\nIsto é apenas um teste.\nEsta não é uma string importante.\n";
echo "O texto original tem " . strlen($original_text) . " caracteres.\n";

$fp = fopen('test.deflated', 'w');
/* Aqui "6" indica nível de compressão 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);

echo "O arquivo comprimido tem " . filesize('test.deflated') . " bytes.\n";

/* Gera a saída:

O texto original tem 79 caracteres.
O arquivo comprimido tem 60 bytes.

*/
?>

bzip2.compress and bzip2.decompress

bzip2.compress e bzip2.decompress funcionam da mesma maneira que os filtros da zlib descritos acima. O filtro bzip2.compress aceita até dois parâmetros passados como elementos de um array associativo: blocks é um valor inteiro de 1 até 9 especificando o número de blocos de 100kbyte de memória para alocar para o espaço de trabalho. work também é um valor inteiro variando de 0 a 250 indicando quanto esforço será realizado usando o método normal de compressão antes de desistir e usar um mais lento, mas mais confiável. Alterar esse parâmetro afeta apenas a velocidade de compressão. Nem o tamanho da saída comprimida nem o uso de memória são alterados por essa configuração. Um fator de trabalho de 0 diz à biblioteca bzip para usar o padrão interno. O filtro bzip2.decompress só aceita um parâmetro, que pode ser passado ou como um valor booleano comum ou como o elemento small de um array associativo. small, quando configurado para o valor true, diz à biblioteca bzip para fazer a descompressão usando o mínimo de memória ao custo da velocidade.

Filtros de compressão bzip2.* estão disponíveis se suporte a bz2 estiver ativado.

Exemplo #3 bzip2.compress e bzip2.decompress

<?php
$param = array('blocks' => 9, 'work' => 0);

echo "O arquivo original tem " . filesize('LICENSE') . " bytes.\n";

$fp = fopen('LICENSE.compressed', 'w');
stream_filter_append($fp, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($fp, file_get_contents('LICENSE'));
fclose($fp);

echo "O arquivo comprimido tem " . filesize('LICENSE.compressed') . " bytes.\n";

/* Gera a saída:

O arquivo original tem 3288 bytes.
O arquivo comprimido tem 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 Criptografia

Os filtros de criptografia são especialmente úteis para criptografia de arquivo/stream.

mcrypt.* and mdecrypt.*

Aviso

Este recurso tornou-se OBSOLETO a partir do PHP 7.1.0. O uso deste recurso é fortemente desencorajado.

Os filtros mcrypt.* e mdecrypt.* fornecem criptografia e descriptografia simétricas usando libmcrypt. Ambos os conjuntos de filtros suportam os mesmos algoritmos disponíveis na extensão mcrypt na forma de mcrypt.ciphername onde ciphername é o nome da cifra como seria passado para mcrypt_module_open(). Os cinco parâmetros de filtros a seguir também estão disponíveis:

Parâmetros para os filtros mcrypt
Parâmetro | Obrigatório? | Valor Padrão | Exemplos de Valores
mode | Opcional | cbc | cbc, cfb, ecb, nofb, ofb, stream
algorithms_dir | Opcional | ini_get('mcrypt.algorithms_dir') | Localização dos módulos de algoritmos
modes_dir | Opcional | ini_get('mcrypt.modes_dir') | Localização dos módulos de modos
iv | Obrigatório | N/A | Tipicamente 8, 16 ou 32 bytes de dados binários. Depende da cifra.
key | Obrigatório | N/A | Tipicamente 8, 16 ou 32 bytes de dados binários. Depende da cifra.

Exemplo #1 Criptografar/Descriptografar com Blowfish

<?php
// assume-se que $key foi gerada anteriormente
$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, 'mensagem para criptografar');
fclose($fp);

// descriptografar...
$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)); // retira o null padding
fclose($fp);
echo $data;
?>

Exemplo #2 Criptografar arquivo usando CBC AES-128 com HMAC SHA256

<?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']; } // padrão AES-128
public static function encryptFile($password, $input_stream, $aes_filename){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$fin = fopen($input_stream, "rb");
$fc = fopen($aes_filename, "wb+");
if (!empty($fin) && !empty($fc)) {
fwrite($fc, str_repeat("_", 32) ); // placeholder, HMAC SHA256 será usado aqui mais 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 is a number from 1-16
fwrite($fc, str_repeat(chr($padding), $padding) );//perform PKCS7 padding
fclose($fin);
fclose($fc);
$hmac_raw = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
$fc = fopen($aes_filename, "rb+");
fwrite($fc, $hmac_raw);//overwrite placeholder
fclose($fc);
}
}
public static function decryptFile($password, $aes_filename, $out_stream) {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$hmac_raw = file_get_contents($aes_filename, false, NULL, 0, 32);
$hmac_salt = file_get_contents($aes_filename, false, NULL, 32, $iv_size);
$hmac_calc = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
$fc = fopen($aes_filename, "rb");
$fout = fopen($out_stream, 'wb');
if (!empty($fout) && !empty($fc) && self::hash_equals($hmac_raw,$hmac_calc)) {
fread($fc, 32+$iv_size);//skip sha256 hmac and salt
$esalt = fread($fc, $iv_size);
$iv = fread($fc, $iv_size);
$ekey = hash_pbkdf2("sha256", $password, $esalt, $it=1000, self::key_size(), $raw=true);
$opts = array('mode'=>'cbc', 'iv'=>$iv, 'key'=>$ekey);
stream_filter_append($fc, 'mdecrypt.rijndael-128', STREAM_FILTER_READ, $opts);
while (!feof($fc)) {
$block = fread($fc, 8192);
if (feof($fc)) {
$padding = ord($block[strlen($block) - 1]);//assume PKCS7 padding
$block = substr($block, 0, 0-$padding);
}
fwrite($fout, $block);
}
fclose($fout);
fclose($fc);
}
}
private static function hash_equals($str1, $str2) {
if(strlen($str1) == strlen($str2)) {
$res = $str1 ^ $str2;
for($ret=0,$i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);
return !$ret;
}
return false;
}
private static function calculate_hmac_after_32bytes($password, $hsalt, $filename) {
static $init=0;
$init or $init = stream_filter_register("user-filter.skipfirst32bytes", "FileSkip32Bytes");
$stream = 'php://filter/read=user-filter.skipfirst32bytes/resource=' . $filename;
$hkey = hash_pbkdf2("sha256", $password, $hsalt, $iterations=1000, 24, $raw=true);
return hash_hmac_file('sha256', $stream, $hkey, $raw=true);
}
}
class FileSkip32Bytes extends php_user_filter
{
private $skipped=0;
function filter($in, $out, &$consumed, $closing) {
while ($bucket = stream_bucket_make_writeable($in)) {
$outlen = $bucket->datalen;
if ($this->skipped<32){
$outlen = min($bucket->datalen,32-$this->skipped);
$bucket->data = substr($bucket->data, $outlen);
$bucket->datalen = $bucket->datalen-$outlen;
$this->skipped+=$outlen;
}
$consumed += $outlen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
class AES_128_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-128']; }
}
class AES_192_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-192']; }
}
class AES_256_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-256']; }
}

User Contributed Notes

Maarten Bodewes 06-Aug-2017 12:21
The examples on this page should be destroyed with utmost urgency.

Strangely most people will fall over the use of generating the IV and 3DES key using MD5, a weak hash function, e.g. the previous note and CryptoFails blog.

http://www.cryptofails.com/post/70059608390/php-documentation-woes

A password based key derivation function should be used (bcrypt, PBKDF2).

However the use of MD-5 for key derivation however isn't that bad and if the password is strong enough (it usually isn't) then the generated DES ABC key is strong enough even now.

Using an identical IV for each password means that this function directly leaks information about the encrypted file. If the start of two encrypted files is identical then this function will directly leak information. For instance, if the routine encrypts multiple images then the JPEG header would be easily distinguished.

All in all these examples use deprecated routines (mcrypt), deprecated cryptographic functions (MD5 / DES) and then incorrectly perform the actual encryption. Enough reason to destroy them in the first place.
Uwe Ohse 22-Feb-2017 04:17
1) The mcrypt module has been deprecated with PHP 7.1.
What does that mean for the encryption filters?

2) deriving the IV from the secret passphrase seems wrong. This leaks information about the passphrase without need.

3) using md5() for this? Really? hash() has been available since PHP 5.1.2.

4) hashing the passphrase twice does not add any security.

5) using substr() on binary data (why, oh why, is true passed to md5()?) might lead to headaches if mbstring.func_overload is used.


Lista de Transportes via Socket Suportados

Índice

  • Domínios da Internet: TCP, UDP, SSL, e TLS
  • Domínio Unix: Unix e UDG

Segue a lista dos vários estilos de URL para transporte via socket que o PHP tem integrado para uso com funções de fluxos de dados baseados em socket como fsockopen(), e stream_socket_client(). Esses transportes não se aplicam à Extensão de Sockets.

Para uma lista de transportes instalados na sua versão do 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


Domínios da Internet: TCP, UDP, SSL, e TLS

ssl://, tls://, sslv2:// & sslv3://.

Nota: Se nenhum transporte for especificado, tcp:// será usado.

  • 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

Sockets nos Domínios da Internet esperam um número de porta além do endereço desejado. No caso de fsockopen(), esta é especificada no segundo parâmetro e, portanto, não afeta a formatação da URL. Com stream_socket_client() e funções relacionadas como com as URLs tradicionais, no entanto, o número da porta é especificado como um sufixo à URL delimitada por dois pontos.

  • tcp://127.0.0.1:80
  • tcp://[fe80::1]:80
  • tcp://www.example.com:80

Nota: Endereços numéricos com número de porta em IPv6
No segundo exemplo acima, enquanto os exemplos em IPv4 e nome de host permaneceram iguais, exceto pela adição do dois pontos e número da porta, o endereço em IPv6 é envolto em colchetes: [fe80::1]. Isso é para distinguir entre os dois pontos de um endereço IPv6 e como separador de porta no IPv4.

Os transportes ssl:// e tls:// (disponíveis apenas quando o suporte a openssl é compilado no PHP) são extensões do transporte tcp:// que incluem encriptação SSL.

ssl:// tentará negociar uma conexão SSL V2 ou SSL V3, dependendo das capacidades e preferências do host remoto. sslv2:// e sslv3:// selecionará o protocolo de maneira explícita.

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.


Domínio Unix: Unix e UDG

unix:// e udg://

  • unix:///tmp/mysock
  • udg:///tmp/mysock

unix:// provê acessos a conexão via Unix sockets. udg:// provê um transporte alternativo para um socket Unix usando o protocolo de datagramas de usuário (UDP).

Sockets Unix, diferentes de sockets de Internet, não esperam um número de porta. No caso de fsockopen() o parâmetro portno deve ser o valor 0.

Nota: Sockets Unix domain não são suportados no 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.


Tabela de comparações de tipos do PHP

As seguintes tabelas demonstram o comportamento dos tipos e operadores de comparação no PHP, tanto para comparações aproximadas ou exatas. Este complemento é também relacionado com a seção do manual sobre type juggling. A inspiração vem dos comentários de vários usuários e do trabalho feito pela » BlueShoes.

Antes de utilizar essas tabelas, é importante entender os tipos e seus significados. Por exemplo, "42" é uma string enquanto 42 é um int. false é um bool enquanto "false" é uma string.

Nota:

Formulários HTML não passam inteiros, floats ou booleanos; eles passam strings. Para saber se uma string é do tipo númerico, você pode usar a função is_numeric().

Nota:

Usar apenas if ($x) quando $x estiver indefinido irá gerar um erro do nível E_NOTICE. Em vez disso, considere usar empty() ou isset() ou ainda inicialize suas variáveis.

Nota:

Algumas operações númericas podem resultar em um valor representado pela constante NAN. Quaisquer comparações exatas ou aproximadas deste valor contra qualquer outro valor, incluindo ele mesmo, com exceção de true, terão como resultado false. (por exemplo NAN != NAN e NAN !== NAN) Exemplos de operações que geram NAN são sqrt(-1), asin(2), e acosh(0).

Comparações de $x com funções PHP
Expression | 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 is undefined | NULL | true | true | false | false
$x = []; | array | true | false | true | false
$x = ['a', 'b']; | array | false | false | true | true
$x = false; | bool | true | false | true | false
$x = true; | bool | false | false | true | true
$x = 1; | 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

Comparações aproximadas com ==
 | true | false | 1 | 0 | -1 | "1" | "0" | "-1" | null | [] | "php" | ""
true | true | false | true | false | true | true | false | true | false | false | true | false
false | false | true | false | true | false | false | true | false | true | true | false | true
1 | true | false | true | false | false | true | false | false | false | false | false | false
0 | false | true | false | true | false | false | true | false | true | false | false* | false*
-1 | true | false | false | false | true | false | false | true | false | false | false | false
"1" | true | false | true | false | false | true | false | false | false | false | false | false
"0" | false | true | false | true | false | false | true | false | false | false | false | false
"-1" | true | false | false | false | true | false | false | true | false | false | false | false
null | false | true | false | true | false | false | false | false | true | true | false | true
[] | false | true | false | false | false | false | false | false | true | true | false | false
"php" | true | false | false | false* | false | false | false | false | false | false | true | false
"" | false | true | false | false* | false | false | false | false | true | false | false | true
* true anteriormente ao PHP 8.0.0.

Comparações exatas com ===
 | true | false | 1 | 0 | -1 | "1" | "0" | "-1" | null | [] | "php" | ""
true | true | false | false | false | false | false | false | false | false | false | false | false
false | false | true | false | false | false | false | false | false | false | false | false | false
1 | false | false | true | false | false | false | false | false | false | false | false | false
0 | false | false | false | true | false | false | false | false | false | false | false | false
-1 | false | false | false | false | true | false | false | false | false | false | false | false
"1" | false | false | false | false | false | true | false | false | false | false | false | false
"0" | false | false | false | false | false | false | true | false | false | false | false | false
"-1" | false | false | false | false | false | false | false | true | false | false | false | false
null | false | false | false | false | false | false | false | false | true | false | false | false
[] | false | false | false | false | false | false | false | false | false | true | false | false
"php" | false | false | false | false | false | false | false | false | false | false | true | false
"" | false | false | false | false | false | false | false | false | false | false | false | true

User Contributed Notes

Jeroen 14-Jul-2023 04:26
Be aware of the difference between checking the *value* of an array item, and checking the *existence* of an array item:
<?php
$arr = [
  'x' => 0,
  'y' => null,
];

isset($arr['x']); // true, same as isset(0)
isset($arr['y']); // false, same as isset(null)

array_key_exists('y', $arr); // true, though the value is null
array_key_exists('z', $arr); // false
ray dot paseur at SometimesUsesGmail dot com 14-Feb-2023 11:37
A colorized version of the loose comparison table is here (no copyright, nor attribution required)
https://iconoun.com/php_type_comparisons.php
Anonymous 17-Nov-2020 02:24
I noticed that some "magic" also happens when comparing strings with leading zeros with only two equal signs:

<?php
var_dump('1' == '01');
var_dump('01' == '000001');
?>

Output:
bool(true)
bool(true)

If the string contains only numbers all leading zeroes seem to be ignored.
TrickyFoxy 02-Jan-2020 08:25
<?php
echo md5('240610708') == md5('QNKCDZO') ? "equal" : "not equal"; // prints equal!!!
php at ckls dot net 20-Aug-2018 02:50
regarding the editors note in php at richardneill dot org note:
[Editor's note: As of PHP 5.4.4 this is no longer true. Integral strings that overflow into floating point numbers will no longer be considered equal.]

While this is true, there is still the following behaviour:
<?php
$x = "1";
$y = "+1";
var_dump($x == $x);
?>
outputs "bool(true)".
So still be wary of string-comparison where both strings might be interpreted as numbers.
mark at theanti dot social 29-Mar-2018 08:59
There is also 0.0 which is not identical to 0.

  $x = 0.0;
  gettype($x); // double
  empty($x); // true
  is_null($x); //false
  isset($x); // true
  is_numeric($x); // true
  $x ? true : false; // false
  $x == 0; // true
  $x == "0"; // true
  $x == "0.0"; // true
  $x == false; // true
  $x == null; // true
  $x === 0; // false
  $x === false; // false
  $x === null; // false
  $x === "0"; // false
  $x === "0.0"; // false
alt dot jl-3gi8b7l at binich dot com 10-Mar-2018 03:41
Here's how PHP handles loose and strict comparisons of default parameters in functions:

Very unintuitive:

<?php
function f($x='surprise')
    {
    if ($x == 'surprise')
        return $x; // returns 0 !!
    }

echo f(0);
?>

Here some further tests:

<?php
function f($x='surprise')
    {
    if ($x == 'surprise')
        return 'A:'.$x;
    if ($x === 'surprise')
        return 'B:'.$x;
    return 'C:'.$x;
    }

echo "\n".f(0); // A:0 !!
echo "\n".f(0.0); // A:0 !!
echo "\n".f(NULL); // C: !!
echo "\n".f(FALSE); // C:
echo "\n".f(); // A:surprise
echo "\n".f(''); // C:
echo "\n".f((integer)0); // A:0
echo "\n".f((string)0); // C:0
echo "\n".f('0'); // C:0
echo "\n".f(0.1); // C:0.1
echo "\n".f(array()); // C:Array
echo "\n".f('surprise'); // A:surprise
?>
biziclop at vipmail dot hu 12-Aug-2017 08:57
Want to strictly compare integers that may or may not be converted to floats (via PHPExcel import/export, etc.)? You are out of luck:

var_dump(   (int)1 ===   (int)1 ); // bool(true)
var_dump( (float)1 === (float)1 ); // bool(true)
var_dump( (float)1 ===   (int)1 ); // bool(false)
var_dump(   (int)1 === (float)1 ); // bool(false)

This slightly complicated function might help you:

function equal_numbers( $a, $b ){
  if( $a === $b )  return true;
  if(   is_int( $a ) && is_float( $b ))  return (float)$a === $b && $a ===   (int)$b;
  if( is_float( $a ) &&   is_int( $b ))  return   (int)$a === $b && $a === (float)$b;
  return false;
}

Here are some tests:

test(100, 100.0 ); // int(100) float(100) bool(true)
test(  0,  -0   ); // int(0)   int(0)     bool(true)
test( -0,  -0.0 ); // int(0)   float(-0)  bool(true)
test(  0, 1/0   ); // int(0)   float(INF) bool(false)
test(  0, acos(2));// int(0)   float(NAN) bool(false)
test(       PHP_INT_MAX * 10, 0 );             //float(92233720368547758080) int(0) bool(false)
test((float)PHP_INT_MAX,     PHP_INT_MAX     );//float(9223372036854775808)  int(9223372036854775807) bool(false)
test((float)PHP_INT_MAX / 2, PHP_INT_MAX / 2 );//float(4611686018427387904)  float(4611686018427387904) bool(true)

function test( $a, $b ){
  var_dump( $a, $b, equal_numbers( $a, $b ));
}
engineer dot morozov at gmail dot com 07-Feb-2016 03:23
If you want to calculate how much more/less items by the criterion

Example:

in loop:
$counter += intval($item->isValid()) <=> 0.5;

if $counter >= 0 - valid items are more then invalid on $counter
if $counter  < 0 - valid items are less then invalid on $counter
trexx68 25-Apr-2015 05:11
If you want to view the truth tables colorized, just:

1. Save a local copy of this page as an .html file,
2. View the page source with any text editor.
3. Replace the opening <head> tag so it will include this:

<head>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

4. Replace the closing </body> tag with this:

  <script>
    $( "td:contains('FALSE')" ).css("color", "red");
    $( "td:contains('TRUE')" ).css("color", "green");
  </script>
</body>

5. Save the file, and view it on your browser.  Enjoy.
aravind dot a dot padmanabhan at gmail dot com 22-Apr-2015 02:31
please note that

$x = 0.0 ;
print empty($x); // returns 1 (true)

$x = "0.0";
print empty($x); // returns blank (false);
Anonymous 16-Oct-2014 06:19
The loose comparison chart is missing a few things.

array(1)==true returns true.

also:

(int)array(1) === 1 returns true

This is symmetric:

array(1) === (array)1 returns true

but the loose comparison

array(1)==1 still returns false.
blue dot hirano at gmail dot com 07-Sep-2014 02:29
The truth tables really ought to be colorized; they're very hard to read as they are right now (just big arrays of TRUE and FALSE).

Also, something to consider: clustering the values which compare similarly (like is done on qntm.org/equality) would make the table easier to read as well. (This can be done simply by hand by rearranging the order of headings to bring related values closer together).
Anonymous 21-Nov-2013 01:43
I'm running PHP 5.5.3.

This is a correction to one of the previous posts.

<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //false
?>

Output is:

true, false, false
crazy888s at hotmail dot com 14-Dec-2012 06:14
PHP's loose comparisons can be a huge convenience when used properly! It's extremely helpful to just remember the following are always FALSE:

null, false, "", 0, "0", array()

If your application never depends on a particular "empty/false/null/0/not set" value type, you won't have to worry about 99% of the other weird cases listed here. You won't need empty() or isset(). And ALL variable types will always work as expected for statements like:

if(boolean && !string){...}
if(array){...}
if(!null || int){...}

Consider the same when working with your database values.
php at richardneill dot org 12-Apr-2012 07:45
[Editor's note: As of PHP 5.4.4 this is no longer true. Integral strings that overflow into floating point numbers will no longer be considered equal.]

Be wary of string-comparison where both strings might be interpreted as numbers.  Eg:

$x="123456789012345678901234567890"; $y="123456789012345678900000000000";
echo  ($x==$y)?"equal":"not_equal";   #Prints equal !!

Both strings are getting converted to floats, then losing precision, then becoming equal :-(

Using "===" or making either of the strings non-numeric will prevent this.
[This is on a 32-bit machine, on a 64-bit, you will have to make the strings longer to see the effect]
Jouriy LYSENKO 17-Jun-2011 02:18
If $var not declared.

In php 5.2 :
<?php if($var) ?> - work

in php 5.3 :
<?php if($var) ?> - dont work and generate error E_NOTICE
php at benizi dot com 15-Feb-2010 10:31
It's interesting to note that 'empty()' and 'boolean : if($x)'
are paired as logical opposites, as are 'is_null()' and 'isset()'.
edgar at goodforall dot eu 15-Dec-2009 06:55
Some function to write out your own comparisson table in tsv format. Can be easily modified to add more testcases and/or binary functions. It will test all comparables against each other with all functions.

<?php
$funcs = array(
        /* Testing equality */
        'eq' => '==',
        'ne' => '!=',
        'gt' => '>',
        'lt' => '<',
        'ne2' => '<>',
        'lte' => '<=',
        'gte' => '>=',
        /* Testing identity */
        'id' => '===',
        'nid' => '!=='
);
class Test {
        protected $a;
        public $b;
        public function __construct($a,$b){
                $this->a = $a;
                $this->b = $b;
        }
        public function getab(){
                return $this->a.",". $this->b;
        }

}
$tst1 = new Test(1,2);
$tst2 = new Test(1,2);
$tst3 = new Test(2,2);
$tst4 = new Test(1,1);

$arr1 = array(1,2,3);
$arr2 = array(2,3,4);
$arr3 = array('a','b','c','d');
$arr4 = array('a','b','c');
$arr5 = array();

$comp1 = array(
        'ints' => array(-1,0,1,2),
        'floats' => array(-1.1,0.0,1.1,2.0),
        'string' => array('str', 'str1', '', '1'),
        'bools' => array(true, false),
        'null' => array(null),
        'objects' => array($tst1,$tst2,$tst3,$tst4),
        'arrays' => array($arr1, $arr2, $arr3, $arr4, $arr5)
);
$fbody = array();

foreach($funcs as $name => $op){
        $fbody[$name] = create_function('$a,$b', 'return $a ' . $op . ' $b;');
}

$table = array(array('function', 'comp1', 'comp2', 'f comp1 comp2', 'type'));
/* Do comparisons */
$comp2  = array();
foreach($comp1 as $type => $val){
        $comp2[$type] = $val;
}

foreach($comp1 as $key1 => $val1){
        foreach($comp2 as $key2 => $val2){
                addTableEntry($key1, $key2, $val1, $val2);
        }
}
$out = '';
foreach($table as $row){
        $out .= sprintf("%-20s\t%-20s\t%-20s\t%-20s\t%-20s\n", $row[0], $row[1], $row[2], $row[3], $row[4]);
}

print $out;
exit;

function addTableEntry($n1, $n2, $comp1, $comp2){
        global $table, $fbody;
        foreach($fbody as $fname => $func){
                        foreach($comp1 as $val1){
  foreach($comp2 as $val2){
                                        $val = $func($val1,$val2);
                                                $table[] = array($fname, gettype($val1) . ' => ' . sprintval($val1), gettype($val2) .' => ' . sprintval($val2), gettype($val) . ' => ' . sprintval($val), gettype($val1) . "-" . gettype($val2) . '-' . $fname);
                                        }
                        }
        }
}

function sprintval($val){
        if(is_object($val)){
                return 'object-' . $val->getab();
        }
        if(is_array($val)){
                return implode(',', $val);
        }
        if(is_bool($val)){
                if($val){
                        return 'true';
                }
                return 'false';
        }
        return strval($val);
}

?>
info at shaelf dot ru 06-Jan-2008 01:51
Compare object
<?php
$o = new stdClass();
$o->we = 12;

$o2 = new stdClass();
$o2->we = 12;

$o3 = clone $o2;
var_dump($o == $o2); //true
var_dump($o === $o2); //false
var_dump($o3 === $o2); //true
?>
frank 14-Aug-2007 03:06
A comparison table for <=,<,=>,> would be nice...
Following are TRUE (tested PHP4&5):
NULL <= -1
NULL <= 0
NULL <= 1
!(NULL >= -1)
NULL >= 0
!(NULL >= 1)
That was a surprise for me (and it is not like SQL, I would like to have the option to have SQL semantics with NULL...).
Jan 29-Dec-2005 11:23
Note that php comparison is not transitive:

"php" == 0 => true
0 == null => true
null == "php" => false
jerryschwartz at comfortable dot com 26-Jul-2005 01:04
In some languages, a boolean is promoted to an integer (with a value of 1 or -1, typically) if used in an expression with an integer. I found that PHP has it both ways:

If you add a boolean with a value of true to an integer with a value of 3, the result will be 4 (because the boolean is cast as an integer).

On the other hand, if you test a boolean with a value of true for equality with an integer with a value of three, the result will be true (because the integer is cast as a boolean).

Surprisingly, at first glance, if you use either < or > as the comparison operator the result is always false (again, because the integer as cast as a boolean, and true is neither greater nor less than true).
tom 17-Jun-2005 02:27
<?php
if (strlen($_POST['var']) > 0) {
    // form value is ok
}
?>

When working with HTML forms this a good way to:

(A) let "0" post values through like select or radio values that correspond to array keys or checkbox booleans that would return FALSE with empty(), and;
(B) screen out $x = "" values, that would return TRUE with isset()!

Because HTML forms post values as strings, this is a good way to test variables!

[[Editor Note: This will create a PHP Error of level E_NOTICE if the checked variable (in this case $_POST['var']) is undefined. It may be used after (in conjuection with) isset() to prevent this.]]
aidan at php dot net 24-Jan-2005 07:00
The way PHP handles comparisons when multiple types are concerned is quite confusing.

For example:
"php" == 0

This is true, because the string is casted interally to an integer. Any string (that does not start with a number), when casted to an integer, will be 0.


Lista de Tokens do Parser

Várias partes da linguagem PHP são representadas internamente por tokens. Um trecho de código que contém uma sequ?ncia inválida de tokens podem ocasionar erros como Parse error: syntax error, unexpected token "==", expecting "(" in script.php on line 10." onde o token == é internamente representado pelo identificador T_IS_EQUAL.

A tabela a seguir lista todos os tokens, disponíveis como constantes no PHP.

Nota: Uso das constantes T_*

Os valores das constantes T_* são gerados automaticamente pela infraestrutura do interpretador do PHP, sem estabilidade. Isto significa que o valor real de um token pode mudar entre duas versões do PHP. Isso significa que seu código nunca deve depender diretamente dos valores originais de T_* levando em consideração uma versão específica do PHP, para que seu código funcione em várias versões do PHP.

Para utilizar as constantes T_* entre várias versões do PHP, constantes não definidas podem ser criadas pelo usuário (utilizando-se grandes números, a partir de 10000) como uma estratégia apropriada que funcionará entre versões do PHP e os valores automaticamente definidos.

<?php
// Anteriormente ao PHP 7.4.0, T_FN não era definido.
defined('T_FN') || define('T_FN', 10001);

Tokens
Token | Sintaxe | Referência
T_ABSTRACT | abstract | Abstração de Classes
T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG | & | Declarações de tipo (disponível desde o PHP 8.1.0)
T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG | & | Declarações de tipo (disponível desde o PHP 8.1.0)
T_AND_EQUAL | &= | operadores de atribuição
T_ARRAY | array() | array(), sintaxe de array
T_ARRAY_CAST | (array) | conversão de tipo
T_AS | as | foreach
T_ATTRIBUTE | #[ | attributes (a partir do PHP 8.0.0)
T_BAD_CHARACTER |  | qualquer coisa abaixo de ASCII 32 exceto \t (0x09), \n (0x0a) and \r (0x0d) (disponível a partir do PHP 7.4.0)
T_BOOLEAN_AND | && | operadores lógicos
T_BOOLEAN_OR | || | operadores lógicos
T_BOOL_CAST | (bool) ou (boolean) | conversão de tipos
T_BREAK | break | break
T_CALLABLE | callable | callable
T_CASE | case | switch
T_CATCH | catch | Exceções
T_CLASS | class | classes e objetos
T_CLASS_C | __CLASS__ | constantes mágicas
T_CLONE | clone | classes e objetos
T_CLOSE_TAG | ?> ou %> | escapando o HTML
T_COALESCE | ?? | operadores de comparação
T_COALESCE_EQUAL | ??= | operadores de assimilação (disponível a partir do PHP 7.4.0)
T_COMMENT | // ou #, e /* */ | comentários
T_CONCAT_EQUAL | .= | operadores de atribuição
T_CONST | const | constantes
T_CONSTANT_ENCAPSED_STRING | "foo" ou 'bar' | sintaxe de string
T_CONTINUE | continue | continue
T_CURLY_OPEN | {$ | sintaxe complexa de parse (chaves)
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 atribuição
T_DNUMBER | 0.12, etc. | números de ponto flutuante
T_DO | do | do..while
T_DOC_COMMENT | /** */ | comentários PHPDoc
T_DOLLAR_OPEN_CURLY_BRACES | ${ | sintaxe complexa de parse (chaves)
T_DOUBLE_ARROW | => | sintaxe de array
T_DOUBLE_CAST | (real), (double) ou (float) | conversão de tipos
T_DOUBLE_COLON | :: | veja T_PAAMAYIM_NEKUDOTAYIM abaixo
T_ECHO | echo | echo
T_ELLIPSIS | ... | argumentos de função
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE | " $a" | interpretação de variáveis em strings
T_ENDDECLARE | enddeclare | declare, sintaxe alternativa
T_ENDFOR | endfor | for, sintaxe alternativa
T_ENDFOREACH | endforeach | foreach, sintaxe alternativa
T_ENDIF | endif | if, sintaxe alternativa
T_ENDSWITCH | endswitch | switch, sintaxe alternativa
T_ENDWHILE | endwhile | while, sintaxe alternativa
T_ENUM | enum | Enumerations (disponível desde o PHP 8.1.0)
T_END_HEREDOC |  | sintaxe heredoc
T_EVAL | eval() | eval()
T_EXIT | exit ou die | exit(), die()
T_EXTENDS | extends | extends, classes e objetos
T_FILE | __FILE__ | constantes mágicas
T_FINAL | final | final
T_FINALLY | finally | Exceções
T_FN | fn | função seta (disponível a partir do PHP 7.4.0)
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | função | funções
T_FUNC_C | __FUNCTION__ | constantes mágicas
T_GLOBAL | global | escopo de variáveis
T_GOTO | goto | goto
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 |  | escapando o HTML
T_INSTANCEOF | instanceof | operadores de tipo
T_INSTEADOF | insteadof | Traits
T_INTERFACE | interface | Interfaces de Objetos
T_INT_CAST | (int) ou (integer) | conversão de tipos
T_ISSET | isset() | isset()
T_IS_EQUAL | == | operadores de comparação
T_IS_GREATER_OR_EQUAL | >= | operadores de comparação
T_IS_IDENTICAL | === | operadores de comparação
T_IS_NOT_EQUAL | != ou <> | operadores de comparação
T_IS_NOT_IDENTICAL | !== | operadores de comparação
T_IS_SMALLER_OR_EQUAL | <= | operadores de comparação
T_LINE | __LINE__ | constantes mágicas
T_LIST | list() | list()
T_LNUMBER | 123, 012, 0x1ac, etc. | inteiros
T_LOGICAL_AND | and | operadores lógicos
T_LOGICAL_OR | or | operadores lógicos
T_LOGICAL_XOR | xor | operadores lógicos
T_MATCH | match | match (a partir do PHP 8.0.0)
T_METHOD_C | __METHOD__ | constantes mágicas
T_MINUS_EQUAL | -= | operadores de atribuição
T_MOD_EQUAL | %= | operadores de atribuição
T_MUL_EQUAL | *= | operadores de atribuição
T_NAMESPACE | namespace | namespaces
T_NAME_FULLY_QUALIFIED | \App\Namespace | namespaces (a partir do PHP 8.0.0)
T_NAME_QUALIFIED | App\Namespace | namespaces (a partir do PHP 8.0.0)
T_NAME_RELATIVE | namespace\Namespace | namespaces (a partir do PHP 8.0.0)
T_NEW | new | classes e objetos
T_NS_C | __NAMESPACE__ | namespaces
T_NS_SEPARATOR | \ | namespaces
T_NUM_STRING | "$a[0]" | interpretação de variáveis em strings
T_OBJECT_CAST | (object) | conversão de tipos
T_OBJECT_OPERATOR | -> | classes e objetos
T_NULLSAFE_OBJECT_OPERATOR | ?-> | classes e objetos
T_OPEN_TAG | <?php, <? ou <% | escapando o HTML
T_OPEN_TAG_WITH_ECHO | <?= ou <%= | escapando o HTML
T_OR_EQUAL | |= | operadores de atribuição
T_PAAMAYIM_NEKUDOTAYIM | :: | ::. Também definido como T_DOUBLE_COLON.
T_PLUS_EQUAL | += | operadores de atribuição
T_POW | ** | operadores aritméticos
T_POW_EQUAL | **= | operadores de atribuição
T_PRINT | print | print
T_PRIVATE | private | classes e objetos
T_PROTECTED | protected | classes e objetos
T_PUBLIC | public | classes e objetos
T_READONLY | readonly | classes e objetos (a partir do PHP 8.1.0)
T_REQUIRE | require | require
T_REQUIRE_ONCE | require_once | require_once
T_RETURN | return | retornando valores
T_SL | << | operador bit-a-bit
T_SL_EQUAL | <<= | operadores de atribuição
T_SPACESHIP | <=> | operadores de comparação
T_SR | >> | operador bit-a-bit
T_SR_EQUAL | >>= | operadores de atribuição
T_START_HEREDOC | <<< | sintaxe heredoc
T_STATIC | static | escopo de variáveis
T_STRING | parent, self, etc. | identificadores, ex. palavras-chaves tais como parent e self, nomes de função, nomes de classe e outros correspondem a esta categoria. Veja também T_CONSTANT_ENCAPSED_STRING.
T_STRING_CAST | (string) | conversão de tipos
T_STRING_VARNAME | "${a | sintaxe complexa de parse (chaves)
T_SWITCH | switch | switch
T_THROW | throw | Exceções
T_TRAIT | trait | Traits
T_TRAIT_C | __TRAIT__ | __TRAIT__
T_TRY | try | Exceções
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | conversão de tipos
T_USE | use | namespaces
T_VAR | var | classes e objetos
T_VARIABLE | $foo | variáveis
T_WHILE | while | while, do..while
T_WHITESPACE | \t \r\n |
T_XOR_EQUAL | ^= | operadores de atribuição
T_YIELD | yield | generators
T_YIELD_FROM | yield from | generators

Veja também 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.


Guia de nomenclatura em espaço de usuário

Índice

  • Escopo Global
  • Regras
  • Dicas

O seguinte guia tem como objetivo orientar em como escolher nome para identificadores em código PHP em espaço de usuário. Quando escolher nome para qualquer código que crie símbolos no escopo global, é importante levar em conta as seguintes orientações para previnir que futuras versões do PHP entrem em conflito com o seus símbolos.

User Contributed Notes

There are no user contributed notes for this page.


Escopo Global

Aqui está uma visão geral de artefatos de código que acabam no escopo global:

  • funções

  • classes

  • interfaces

  • constantes (menos constantes de classes)

  • variáveis definidas fora de funções e métodos

User Contributed Notes

There are no user contributed notes for this page.


Regras

A lista a seguir dá uma visão geral de quais direitos o projeto do PHP reserva para si, quando escolhe nomes para novos identificadores internos. O guia definitivo é » PADRÕES DE CÓDIGO:

  • PHP detém o escopo de alto nível, mas tenta achar nomes descritivos decentes e evita qualquer conflito óbvio.

  • Nomes de funções usam sublinhado (_) entre palavas, enquanto nomes de classe usam a notação camelCase e PascalCase.

  • O PHP prefixará quaisquer símbolos globais de uma extensão com o nome da extensão (No passado, existiam várias exceções à essa regra). Exemplos:

    • curl_close()

    • mysql_query()

    • PREG_SPLIT_DELIM_CAPTURE

    • new DOMDocument()

    • strpos() (exemplo de um erro do passado)

    • new SplFileObject()

  • Iterators e Exceptions são, no entanto, simplesmente sufixados com "Iterator" e "Exception." Exemplos:

    • ArrayIterator

    • LogicException

  • O PHP reserva todos os símbolos começando com __ como mágicos. É recomendado que você não crie símbolos começando com __ a não ser que você queira usar a funcionalidade mágica documentada. Exemplos:

    • __get

    • __autoload()

User Contributed Notes

There are no user contributed notes for this page.


Dicas

Para escrever código que não sofrerá problemas no futuro, é recomendado que você não coloque variáveis, funções ou classes no espaço global. Isto evitará colisões de nome com código de terceiros assim como futuros acréscimos à linguagem.

Uma forma de prevenir colisões de nomes em funções e classes é colocá-las em seus próprios namespaces.

<?php

namespace MyProject;

function my_function() {
return true;
}

\MyProject\my_function();

This still needs you to keep track of already used namespaces, but once you have decided on a namespace you will be using you can add all functions and classes to it without having to think about conflicts again.

Também é considerada uma boa prática limitar o número de variáveis alocadas no escopo global de forma a evitar colisões de nome com código de terceiros.

Nota: Variable scoping

Por causa das regras de escopo do PHP as variáveis definidas dentro de funções e métodos não estão no escopo global e não podem conflitar com variáveis definidas nesse escopo.

User Contributed Notes

There are no user contributed notes for this page.


Sobre o manual

Índice

  • Formatos
  • Sobre as notas dos usuários
  • Como ler uma definição de função (protótipo)
  • Versões do PHP documentadas neste manual
  • Como encontrar mais informações sobre o PHP
  • Como ajudar a melhorar a documentação
  • Como nós geramos os formatos
  • Traduções

User Contributed Notes

There are no user contributed notes for this page.


Formatos

O manual PHP é disponibilizado em diversos formatos. Estes formatos podem ser divididos em dois grupos: formatos de leitura online e pacotes para download.

Nota:

Algumas editoras fizeram versões impressas deste manual. Porém estas versões não são recomendadas, pois tendem a se tornar rapidamente desatualizadas.

O manual PHP pode ser lido online no » site do PHP.net. A versão online do manual PHP tem atualmente duas folhas de estilo CSS, uma web amigável e a outra folha de estilo para impressão.

Duas vantagens notáveis do manual online sobre a maioria dos formatos offline é a integração das notas dos usuários e os » atalhos de URL que podem ser usados para ir rapidamente para partes desejadas do manual. Uma óbvia desvantagem é o requisito de estar online para visualização desta edição do manual.

Existem diversos formatos offline do manual, e o formato mais adequado depende do sistema operacional e do estilo de leitura pessoal. Para informações de como o manual é gerado em tantos formatos, veja a seção 'Como nós geramos os formatos' deste apêndice.

A versão HTML é o formato mais multi-plataforma deste manual. Esta versão está disponível como um único arquivo HTML e como um pacote de arquivos individuais para cada seção (que resulta em uma coleção de milhares de arquivos). Nós disponibilizamos estas versões compactadas, então um programa de descompactação é necessário para recuperar os arquivos contidos dentro destes pacotes.

Para plataformas Windows, a versão Windows HTML Help do manual otimiza o formato HTML para o uso com o programa Windows HTML Help. Esta versão fornece busca de textos, índice completo e marcadores. Vários ambientes de desenvolvimento populares do PHP no Windows se integram com esse formato da documentação para facilitar o acesso à documentação. Visualizadores de CHM para desktops Linux também estão disponíveis. Veja » xCHM or » GnoCHM.

Existe também uma » versão CHM estendida disponível, que é atualizada menos frequentemente, mas que oferece muitos recursos adicionais. Entretanto ela irá funcionar apenas no Microsoft Windows, devido às tecnologias usadas para compilar as páginas de ajuda.

User Contributed Notes

There are no user contributed notes for this page.


Sobre as notas dos usuários

As notas dos usuários possuem um importante papel no desenvolvimento deste manual. Ao permitir que os leitores do manual possam contribuir com exemplos, ressalvas e outros esclarecimentos através de seus navegadores, somos capazes de incorporar esse feedback dentro do texto principal do manual. E até que as notas sejam incorporadas, elas podem ser vistas na sua forma online e em alguns dos formatos offline.

Nota:

As notas dos usuários não são moderadas antes delas aparecem online, então a qualidade da escrita ou dos exemplos de código, e mesmo a veracidade da contribuição, não podem ser garantidas. (Não que haja qualquer garantia da qualidade ou exatidão do próprio texto do manual.)

Nota:

Para fins de cobertura de licença as notas fornecidas por usuários são consideradas parte do manual do PHP, e por isso são cobertas pela mesma licença desta documentação (atualmente a licença Creative Commons Attribution). Para mais detalhes, veja a página de Direitos Autorais do Manual.

User Contributed Notes

There are no user contributed notes for this page.


Como ler uma definição de função (protótipo)

Cada função no manual é documentada para uma referência rápida. Saber como ler e entender o texto tornará a aprendizagem do PHP muito mais fácil. Mais do que simplesmente estudar exemplos ou copiar/colar, todos deveriam saber como ler as definições de funções (protótipos). Vamos começar:

Nota: Pré-requisito: Entendimento básico de tipos

Mesmo o PHP sendo uma linguagem fracamente tipada, é importante ter um entendimento básico dos tipos pois eles têm um importante significado.

Definições das funções nos dizem que tipo de valor é retornado. Vamos usar a definição da função strlen() como nosso primeiro exemplo:

strlen

(PHP 4, PHP 5, PHP 7)
strlen -- Obtém o tamanho da string

Descrição
strlen ( string $string ) : int

Retorna o tamanho da string dada.

Explicação de uma definição de função
Parte | Descrição
strlen | Nome da função.
(PHP 4, PHP 5, PHP 7) | strlen() está disponível em todas as versões do PHP 4, 5 e 7
( string $string ) | O primeiro (e neste caso, o único) parâmetro/argumento para esta função é chamado string, e é uma string.
int | Tipo do valor que esta função retorna, que é um int (isto é, o comprimento de uma string é medido em números).

Poderíamos reescrever a definição da função acima de uma maneira genérica:

      nome da função    ( tipo do parâmetro   nome do parâmetro ) : tipo retornado

Muitas funções recebem múltiplos parâmetros, tais como a função in_array(). Seu protótipo segue abaixo:

      in_array ( mixed $needle, array $haystack , bool $strict = false ) : bool

O que isso significa? in_array() retorna um valor booleano, true em caso de sucesso (se needle foi encontrado em haystack) ou false em caso de falha (se needle não foi encontrado em haystack). O primeiro parâmetro é chamado needle e pode de ser de vários tipos diferentes, por isso nós o chamamos "mixed" (misto). Esse needle mixed (o que nós estamos procurando) pode ser tanto um valor escalar (string, inteiro, ou float) ou um array. haystack (o array onde nós estamos procurando) é o segundo parâmetro. O terceiro parâmetro opcional é chamado strict. Todos os parâmetros opcionais têm valores padrão (default). Se o valor padrão é desconhecido, então é mostrado um ?. O exemplo diz que o valor padrão do parâmetro strict é o booleano false. Veja a página do manual de cada função para detalhes de como elas funcionam.

Além do mais o símbolo & (ampersand, e comercial) antes de um parâmetro de função permite ao parâmetro ser passado por referência, como no exemplo abaixo:

       preg_match ( string $pattern , string $subject , array &$matches = null,
       int $flags = 0 , int $offset = 0 ) : int|false

Neste exemplo podemos ver que o terceiro parâmetro opcional &$matches será passado por referência.

Existem também funções com informações de versões do PHP mais complexas. Tome como exemplo html_entity_decode():

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

Isto significa que esta função só está disponível a partir da versão PHP 4.3.0.

User Contributed Notes

There are no user contributed notes for this page.


Versões do PHP documentadas neste manual

O manual contém informações sobre as versões passadas, presente, e futuras do PHP. Modificações no comportamento são documentadas como notas, changelogs e em trechos nas páginas do manual. A versão mais antiga documentada é o PHP 7.0.0.

Quando a documentação existir para versões mais recentes de desenvolvimento (unreleased) do PHP, será marcada como "available in Git" ou "development version". E, embora estas mudanças sejam planejadas, em casos raros elas podem mudar.

Todo desenvolvimento ocorre no Git e o check out pode ser feito como descrito na página » acesso anônimo ao Git .

E para esclarecer, o manual refere-se a maiores, menores e específicas releases do PHP. Usando o PHP 7.3.1 como exemplo, o 7 refere-se à versão maior, 3 à menor e 1 é a release específica. Tipicamente o PHP somente adiciona novas features em maiores e menores releases, e corrige bugs em releases específicas. Porém, esta convenção nem sempre é verdadeira.

Observe também que o manual PHP é escrito no tempo presente, e não no futuro, mesmo que para recursos documentados que ainda não estão disponíveis. A razão para isto é que o manual pode resistir ao teste do tempo, portanto não exige tediosas atualizações gramaticais a cada nova release do PHP.

Muitas vezes o manual do PHP lista "Valores Padrão" para as diretivas do PHP. Estes valores são baseados em como o PHP se comporta sem um arquivo de configuração php.ini, então podem ser diferentes dos valores encontrados nos arquivos php.ini-development e php.ini-production distribuídos. Eles também referem-se à última versão do PHP, embora entradas do changelog mencionem valores anteriores. Veja o Apêndice Diretivas do PHP para detalhes a respeito destes valores e mudanças.

User Contributed Notes

There are no user contributed notes for this page.


Como encontrar mais informações sobre o PHP

Este manual não tenta fornecer instruções sobre práticas gerais de programação. Programadores de primeira viagem - ou apenas começando - podem achar difícil aprender a programar em PHP usando exclusivamente este manual. Em vez disso, procure um texto mais orientado para iniciantes.

Há uma série de listas de discussão ativas para discussões de todos os aspectos da programação com PHP. Se estiver preso com algum problema, considere o uso destas listas. Para opções de suporte, incluindo listas de discussão, veja a » página de suporte do PHP.net.

User Contributed Notes

There are no user contributed notes for this page.


Como ajudar a melhorar a documentação

Há várias maneiras de ajudar a melhorar a documentação.

Se um erro for encontrado neste manual, em qualquer linguagem, por favor informe-os usando o rastreador de problemas (issues) do respectivo repositório de linguagem em » https://github.com/php. Por exemplo, erros no manual em inglês devem ser reportados em » https://github.com/php/doc-en/issues. Todos os problemas relacionados com a documentação, inclusive sobre os formatos de manuais, devem ser enviados como relatórios de bugs.

Nota:

Por favor, não abuse dos rastreadores de problemas enviando pedidos de ajuda. Neste caso, use uma das muitas » opções de suporte.

Ao contribuir com notas, os usuários podem fornecer exemplos adicionais, ressalvas e esclarecimentos para outros leitores. Mas por favor, não informe bugs usando o sistema de anotações. Para mais detalhes, veja a seção intitulada 'Sobre as notas de usuários'.

Também é possível enviar pull requests para o » repositório espelho Github da documentação.

O manual PHP é traduzido em várias línguas. Saber inglês e uma língua estrangeira permite uma outra maneira de ajudar a melhorar o manual PHP trabalhando com um time de tradução. Para mais informações sobre como iniciar uma nova tradução, ou ajudar no projeto de tradução atual, por favor leia » http://doc.php.net/tutorial/.

O Projeto de Documentação do PHP também possui um canal IRC onde muitos autores do manual se reúnem. Passe no canal #php.doc em irc.efnet.org e discuta maneiras de melhorar a documentação do PHP.

User Contributed Notes

There are no user contributed notes for this page.


Como nós geramos os formatos

Este Manual é escrito em XML usando o » DocBook XML DTD, usando » PhD (The [PH]P based [D]ocBook renderer) para manutenção e formatação.

Usar XML como formato fonte nos dá a capacidade de gerar diversos formatos de saída a partir dos arquivos fonte, enquanto apenas um documento fonte é mantido para todos os formatos. A ferramenta usada para formatar o manual online é » PhD. Usamos » Microsoft HTML Help Workshop para gerar o formato Windows HTML Help do manual e, é claro, o próprio PHP para fazer algumas conversões e formatações.

O manual PHP é gerado em várias linguagens e formatos, veja » https://www.php.net/docs.php para maiores detalhes. O código fonte XML pode ser baixado do git e visualizado em » https://github.com/php/doc-en.

User Contributed Notes

There are no user contributed notes for this page.


Traduções

O manual do PHP está disponível não apenas em vários formatos, mas também em várias linguagens. O texto do manual é escrito primeiro em inglês, então grupos de pessoas ao redor do mundo fazem as traduções para suas línguas nativas. Se a tradução para uma específica função ou capítulo ainda não foi feita, o sistema de compilação do manual utiliza a versão original em inglês.

Pessoas envolvidas na tradução iniciam do código fonte XML disponível em » https://github.com/php/doc-en e partir daí é feita tradução para sua língua mãe. Eles não utilizam as versões geradas (como HTML ou texto plano) já que é o sistema de compilação do manual que cuida das conversões de XML para formatos mais legíveis.

Nota:

Para colaborar com a tradução da documentação entre em contato com time de tradução/documentação inscrevendo-se na lista de discussão do phpdoc: envie um e-mail vazio para » phpdoc-subscribe@lists.php.net. O endereço da lista de discussão é phpdoc@lists.php.net. Informe na mensagem o interesse em traduzir o manual e alguém irá responder com orientações sobre como avançar iniciando uma nova tradução de linguagem ou entrando em contato com o time de documentação da língua desejada.

Atualmente o manual está disponível, parcialmente ou não, em mais de 10 linguagens.

Todos eles podem ser baixados aqui: » 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.


Lista de índices

Índice

  • Lista de Funções e Métodos
  • Lista de exemplos

User Contributed Notes

There are no user contributed notes for this page.


Lista de Funções e Métodos

Lista de todas as funções e métodos no 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 cosseno
    • acosh - Arco cosseno hiperbólico
    • addcslashes - Quote string with slashes in a C style
    • addslashes - Adiciona barras a uma string
    • AllowDynamicProperties::__construct - Constrói uma nova instância do atributo AllowDynamicProperties
    • apache_child_terminate - Finaliza o processo Apache depois da requisição
    • apache_getenv - Retorna uma variável subprocess_env do Apache
    • apache_get_modules - Retorna uma lista de módulos carregados do Apache
    • apache_get_version - Retorna a versão do Apache
    • apache_lookup_uri - Realiza uma requisição parcial para a URI especificada e retorna todas as informações sobre ela
    • apache_note - Obtêm e configura notas de requisição
    • apache_request_headers - Obtém todos os cabeçalhos da requisição HTTP
    • apache_response_headers - Obtém todos os cabeçalhos da resposta HTTP
    • apache_setenv - Define uma variável subprocess_env do Apache
    • APCUIterator::current - Get current item
    • APCUIterator::getTotalCount - Get total count
    • APCUIterator::getTotalHits - Get total cache hits
    • APCUIterator::getTotalSize - Get total cache size
    • APCUIterator::key - Get iterator key
    • APCUIterator::next - Move pointer to next item
    • APCUIterator::rewind - Rewinds iterator
    • APCUIterator::valid - Checks if current position is valid
    • APCUIterator::__construct - Constructs an APCUIterator iterator object
    • apcu_add - Cache a new variable in the data store
    • apcu_cache_info - Retrieves cached information from APCu's data store
    • apcu_cas - Updates an old value with a new value
    • apcu_clear_cache - Clears the APCu cache
    • apcu_dec - Decrease a stored number
    • apcu_delete - Removes a stored variable from the cache
    • apcu_enabled - Whether APCu is usable in the current environment
    • apcu_entry - Atomically fetch or generate a cache entry
    • apcu_exists - Checks if entry exists
    • apcu_fetch - Fetch a stored variable from the cache
    • apcu_inc - Increase a stored number
    • apcu_key_info - Get detailed information about the cache key
    • apcu_sma_info - Retrieves APCu Shared Memory Allocation information
    • apcu_store - Cache a variable in the data store
    • AppendIterator::append - Appends an iterator
    • AppendIterator::current - Gets the current value
    • AppendIterator::getArrayIterator - Gets the ArrayIterator
    • AppendIterator::getIteratorIndex - Gets an index of iterators
    • AppendIterator::key - Gets the current key
    • AppendIterator::next - Moves to the next element
    • AppendIterator::rewind - Rewinds the Iterator
    • AppendIterator::valid - Checks validity of the current element
    • AppendIterator::__construct - Constructs an AppendIterator
    • array - Cria um array
    • ArrayAccess::offsetExists - Verifica se uma posição existe
    • ArrayAccess::offsetGet - Posição a ser obtida
    • ArrayAccess::offsetSet - Atribui um valor a uma posição específica
    • ArrayAccess::offsetUnset - Remove uma posição
    • ArrayIterator::append - Append an element
    • ArrayIterator::asort - Sort entries by values
    • ArrayIterator::count - Conta os elementos
    • ArrayIterator::current - Retorna o valor do elemento atual do array
    • ArrayIterator::getArrayCopy - Get array copy
    • ArrayIterator::getFlags - Retorna as flags de comportamento
    • ArrayIterator::key - Retorna a chave do elemento atual do array
    • ArrayIterator::ksort - Sort entries by keys
    • ArrayIterator::natcasesort - Sort entries naturally, case insensitive
    • ArrayIterator::natsort - Sort entries naturally
    • ArrayIterator::next - Avança para o próximo elemento
    • ArrayIterator::offsetExists - Check if offset exists
    • ArrayIterator::offsetGet - Get value for an offset
    • ArrayIterator::offsetSet - Set value for an offset
    • ArrayIterator::offsetUnset - Unset value for an offset
    • ArrayIterator::rewind - Recoloca o array no início
    • ArrayIterator::seek - Aponta para determinada posição
    • ArrayIterator::serialize - Serialize
    • ArrayIterator::setFlags - Define as flags que irão alterar o comportamento
    • ArrayIterator::uasort - Sort with a user-defined comparison function and maintain index association
    • ArrayIterator::uksort - Sort by keys using a user-defined comparison function
    • ArrayIterator::unserialize - Unserialize
    • ArrayIterator::valid - Verifica se o array possui mais elementos
    • ArrayIterator::__construct - Construct an ArrayIterator
    • ArrayObject::append - Appends the value
    • ArrayObject::asort - Sort the entries by value
    • ArrayObject::count - Get the number of public properties in the ArrayObject
    • ArrayObject::exchangeArray - Exchange the array for another one
    • ArrayObject::getArrayCopy - Creates a copy of the ArrayObject
    • ArrayObject::getFlags - Gets the behavior flags
    • ArrayObject::getIterator - Retorna o iterador do ArrayObject
    • ArrayObject::getIteratorClass - Gets the iterator classname for the ArrayObject
    • ArrayObject::ksort - Sort the entries by key
    • ArrayObject::natcasesort - Sort an array using a case insensitive "natural order" algorithm
    • ArrayObject::natsort - Sort entries using a "natural order" algorithm
    • ArrayObject::offsetExists - Returns whether the requested index exists
    • ArrayObject::offsetGet - Returns the value at the specified index
    • ArrayObject::offsetSet - Sets the value at the specified index to newval
    • ArrayObject::offsetUnset - Unsets the value at the specified index
    • ArrayObject::serialize - Serialize an ArrayObject
    • ArrayObject::setFlags - Sets the behavior flags
    • ArrayObject::setIteratorClass - Sets the iterator classname for the ArrayObject
    • ArrayObject::uasort - Sort the entries with a user-defined comparison function and maintain key association
    • ArrayObject::uksort - Sort the entries by keys using a user-defined comparison function
    • ArrayObject::unserialize - Unserialize an ArrayObject
    • ArrayObject::__construct - Construct a new array object
    • array_change_key_case - Modifica a caixa de todas as chaves em um array
    • array_chunk - Divide um array em pedaços
    • array_column - Retorna os valores de uma coluna do array informado
    • array_combine - Cria um array usando um array para chaves e outro para valores
    • array_count_values - Conta as ocorrências de cada valor distinto em um array
    • array_diff - Computa as diferenças entre arrays
    • array_diff_assoc - Computa a diferença entre arrays com checagem adicional de índice
    • array_diff_key - Computa a diferença entre arrays usando as chaves na comparação
    • array_diff_uassoc - Computa a diferença entre arrays com checagem adicional de índice que feita por uma função de callback fornecida pelo usuário
    • array_diff_ukey - Computa a diferença entre arrays usando uma função callback na comparação de chaves
    • array_fill - Preenche um array com valores
    • array_fill_keys - Preenche um array com valores, especificando chaves
    • array_filter - Filtra elementos de um array utilizando uma função callback
    • array_flip - Permuta todas as chaves e seus valores associados em um array
    • array_intersect - Calcula a interseção entre arrays
    • array_intersect_assoc - Computa a interseção de arrays com uma adicional verificação de índice
    • array_intersect_key - Calcula a interseção de arrays, comparando pelas chaves
    • array_intersect_uassoc - Computa a interseção de arrays com checagem de índice adicional, compara índices por uma função de callback
    • array_intersect_ukey - Computa a interseção de arrays usando uma função de callback nas chaves para comparação
    • array_is_list - Verifica se um array é uma lista
    • array_keys - Retorna todas as chaves ou uma parte das chaves de um array
    • array_key_exists - Checa se uma chave ou índice existe em um array
    • array_key_first - Obtém a primeira chave de um array
    • array_key_last - Obtém a última chave de um array
    • array_map - Aplica uma função em todos os elementos dos arrays dados
    • array_merge - Combina um ou mais arrays
    • array_merge_recursive - Mescla um ou mais arrays recursivamente
    • array_multisort - Ordena múltiplos arrays ou arrays multidimensionais
    • array_pad - Expande um array para um certo comprimento utilizando um determinado valor
    • array_pop - Extrai um elemento do final do array
    • array_product - Calcula o produto dos valores de um array
    • array_push - Adiciona um ou mais elementos no final de um array
    • array_rand - Escolhe uma ou mais chaves aleatórias de um array
    • array_reduce - Reduz um array para um único valor através de um processo iterativo via callback
    • array_replace - Substitui elementos de arrays passados no primeiro array
    • array_replace_recursive - Substitui elementos de arrays passado no primeiro array recursivamente
    • array_reverse - Retorna um array com os elementos na ordem inversa
    • array_search - Procura por um valor em um array e retorna sua chave correspondente caso seja encontrado
    • array_shift - Retira o primeiro elemento de um array
    • array_slice - Extrai uma parcela de um array
    • array_splice - Remove uma parte array e a substitui por outra coisa
    • array_sum - Calcula a soma dos elementos de um array
    • array_udiff - Computa a diferença de arrays usando uma função de callback para comparação dos dados
    • array_udiff_assoc - Computa a diferença entre arrays com checagem adicional de índice, compara dados por uma função de callback
    • array_udiff_uassoc - Computa a diferença entre arrays com checagem adicional de índice, compara dados e índices por uma função de callback
    • array_uintersect - Computa a interseção de array, comparando dados com uma função callback
    • array_uintersect_assoc - Computa a interseção de arrays com checagem adicional de índice, compara os dados utilizando uma função de callback
    • array_uintersect_uassoc - Computa a interseção de arrays com checagem adicional de índice, compara os dados e os índices utilizando funções de callback separadas
    • array_unique - Remove os valores duplicados de um array
    • array_unshift - Adiciona um ou mais elementos no início de um array
    • array_values - Retorna todos os valores de um array
    • array_walk - Aplica uma determinada função em cada elemento de um array
    • array_walk_recursive - Aplica um função do usuário recursivamente para cada membro de um array
    • arsort - Ordena um array em ordem descrescente e mantém a associação de índices
    • asin - Arco seno
    • asinh - Arco seno hiperbólico
    • asort - Ordena um array em ordem crescente e mantém a associação de índices
    • assert - Executa um assert
    • assert_options - Set/get the various assert flags
    • atan - Arco tangente
    • atan2 - Arco tangente de duas variáveis
    • atanh - Arco tangente hiperbólico
    • Attribute::__construct - Constrói uma nova instância da classe Attribute
  • b
    • BackedEnum::from - Mapeia um escalar para uma instância de enumeração
    • BackedEnum::tryFrom - Mapeia um escalar para uma instância de enumeração ou nulo
    • base64_decode - Decodifica dados no formato MIME base64
    • base64_encode - Codifica dados com MIME base64
    • basename - Retorna a última parte do caminho
    • BaseResult::getWarnings - Fetch warnings from last operation
    • BaseResult::getWarningsCount - Fetch warning count from last operation
    • base_convert - Converte um número entre bases arbitrárias
    • bcadd - Adicionar dois números de precisão arbitrária
    • bccomp - Comparar dois números de precisão arbitrária
    • bcdiv - Dividir dois números de precisão arbitrária
    • bcmod - Obtém o módulo de um número com precisão arbitrária
    • bcmul - Multiplicar dois números de precisão arbitrária
    • bcpow - Eleva um número de precisão arbitrária a outro
    • bcpowmod - Eleva um número de precisão arbitrária para outro, reduzido por um módulo especificado
    • bcscale - Configura ou obtêm o parâmetro escala para todas as funções bc
    • bcsqrt - Obtém a raiz quadrada de um número de precisão arbitrária
    • bcsub - Subtrai um número de precisão arbitrária de outro
    • bin2hex - Converte um dado binário em representação hexadecimal
    • bindec - Binário para decimal
    • bindtextdomain - Define ou obtém o caminho para um domínio
    • bind_textdomain_codeset - Especifica ou obtém a codificação de caracteres na qual as mensagens do catálogo de mensagens de DOMÍNIO serão retornadas
    • boolval - Obtém o valor booleano de uma variável
    • bzclose - Fecha um ponteiro de arquivo bzip2
    • bzcompress - Comprime uma string em dados codificados com bzip2
    • bzdecompress - Descomprime dados codificados com bzip2
    • bzerrno - Retorna um número de erro da bzip2
    • bzerror - Retorna o número e string de erro do bzip2 em um array
    • bzerrstr - Retorna a string de erro do bzip2
    • bzflush - Sem efeitos
    • bzopen - Abre um arquivo comprimido com bzip2
    • bzread - Leitura binária segura de arquivo bzip2
    • bzwrite - Gravação binária segura em arquivo bzip2
  • c
    • CachingIterator::count - The number of elements in the iterator
    • CachingIterator::current - Return the current element
    • CachingIterator::getCache - Retrieve the contents of the cache
    • CachingIterator::getFlags - Get flags used
    • CachingIterator::hasNext - Check whether the inner iterator has a valid next element
    • CachingIterator::key - Return the key for the current element
    • CachingIterator::next - Move the iterator forward
    • CachingIterator::offsetExists - The offsetExists purpose
    • CachingIterator::offsetGet - The offsetGet purpose
    • CachingIterator::offsetSet - The offsetSet purpose
    • CachingIterator::offsetUnset - The offsetUnset purpose
    • CachingIterator::rewind - Rewind the iterator
    • CachingIterator::setFlags - The setFlags purpose
    • CachingIterator::valid - Check whether the current element is valid
    • CachingIterator::__construct - Construct a new CachingIterator object for the iterator
    • CachingIterator::__toString - Return the string representation of the current element
    • CallbackFilterIterator::accept - Calls the callback with the current value, the current key and the inner iterator as arguments
    • CallbackFilterIterator::__construct - Create a filtered iterator from another iterator
    • call_user_func - Call the callback given by the first parameter
    • call_user_func_array - Call a callback with an array of parameters
    • cal_days_in_month - Retorna o número de dias em um mês de um calendário e ano requisitado
    • cal_from_jd - Converts from Julian Day Count to a supported calendar
    • cal_info - Returns information about a particular calendar
    • cal_to_jd - Converte um calendário (suportado) para o calendário "Julian Day Count"
    • ceil - Arredonda frações para cima
    • chdir - Muda o diretório
    • checkdate - Valida uma data gregoriana
    • checkdnsrr - Checa os registros DNS correspondentes para o nome do host ou endereço IP informado
    • chgrp - Altera o grupo do arquivo
    • chmod - Modifica as permissões do arquivo
    • chop - Sinônimo de rtrim
    • chown - Modifica o proprietário do arquivo
    • chr - Generate a single-byte string from a number
    • chroot - Muda o diretório raiz
    • chunk_split - Divide uma string em pedaços menores
    • class_alias - Cria um apelido para uma classe
    • class_exists - Verifica se uma classe foi definida
    • class_implements - Return the interfaces which are implemented by the given class or interface
    • class_parents - Return the parent classes of the given class
    • class_uses - Return the traits used by the given class
    • clearstatcache - Limpa o cache de estado de arquivos
    • 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 - Fecha o manipulador do diretório
    • closelog - Close connection to system logger
    • Closure::bind - Duplica uma closure com um objeto vinculado e um escopo de classe
    • Closure::bindTo - Duplica a closure com um novo objeto vinculado e escopo de classe.
    • Closure::call - Vincula e chama a closure
    • Closure::fromCallable - Converte um callable em uma closure
    • Closure::__construct - Construtor que desabilita a instanciação
    • Collator::asort - Sort array maintaining index association
    • Collator::compare - Compare two Unicode strings
    • Collator::create - Create a collator
    • Collator::getAttribute - Get collation attribute value
    • Collator::getErrorCode - Get collator's last error code
    • Collator::getErrorMessage - Get text for collator's last error code
    • Collator::getLocale - Get the locale name of the collator
    • Collator::getSortKey - Get sorting key for a string
    • Collator::getStrength - Get current collation strength
    • Collator::setAttribute - Set collation attribute
    • Collator::setStrength - Set collation strength
    • Collator::sort - Sort array using specified collator
    • Collator::sortWithSortKeys - Sort array using specified collator and sort keys
    • Collator::__construct - Create a collator
    • Collectable::isGarbage - Determine whether an object has been marked as garbage
    • Collection::add - Add collection document
    • Collection::addOrReplaceOne - Add or replace collection document
    • Collection::count - Get document count
    • Collection::createIndex - Create collection index
    • Collection::dropIndex - Drop collection index
    • Collection::existsInDatabase - Check if collection exists in database
    • Collection::find - Search for document
    • Collection::getName - Get collection name
    • Collection::getOne - Get one document
    • Collection::getSchema - Get schema object
    • Collection::getSession - Get session object
    • Collection::modify - Modify collection documents
    • Collection::remove - Remove collection documents
    • Collection::removeOne - Remove one collection document
    • Collection::replaceOne - Replace one collection document
    • Collection::__construct - Collection constructor
    • CollectionAdd::execute - Execute the statement
    • CollectionAdd::__construct - CollectionAdd constructor
    • CollectionFind::bind - Bind value to query placeholder
    • CollectionFind::execute - Execute the statement
    • CollectionFind::fields - Set document field filter
    • CollectionFind::groupBy - Set grouping criteria
    • CollectionFind::having - Set condition for aggregate functions
    • CollectionFind::limit - Limit number of returned documents
    • CollectionFind::lockExclusive - Execute operation with EXCLUSIVE LOCK
    • CollectionFind::lockShared - Execute operation with SHARED LOCK
    • CollectionFind::offset - Skip given number of elements to be returned
    • CollectionFind::sort - Set the sorting criteria
    • CollectionFind::__construct - CollectionFind constructor
    • CollectionModify::arrayAppend - Append element to an array field
    • CollectionModify::arrayInsert - Insert element into an array field
    • CollectionModify::bind - Bind value to query placeholder
    • CollectionModify::execute - Execute modify operation
    • CollectionModify::limit - Limit number of modified documents
    • CollectionModify::patch - Patch document
    • CollectionModify::replace - Replace document field
    • CollectionModify::set - Set document attribute
    • CollectionModify::skip - Skip elements
    • CollectionModify::sort - Set the sorting criteria
    • CollectionModify::unset - Unset the value of document fields
    • CollectionModify::__construct - CollectionModify constructor
    • CollectionRemove::bind - Bind value to placeholder
    • CollectionRemove::execute - Execute remove operation
    • CollectionRemove::limit - Limit number of documents to remove
    • CollectionRemove::sort - Set the sorting criteria
    • CollectionRemove::__construct - CollectionRemove constructor
    • ColumnResult::getCharacterSetName - Get character set
    • ColumnResult::getCollationName - Get collation name
    • ColumnResult::getColumnLabel - Get column label
    • ColumnResult::getColumnName - Get column name
    • ColumnResult::getFractionalDigits - Get fractional digit length
    • ColumnResult::getLength - Get column field length
    • ColumnResult::getSchemaName - Get schema name
    • ColumnResult::getTableLabel - Get table label
    • ColumnResult::getTableName - Get table name
    • ColumnResult::getType - Get column type
    • ColumnResult::isNumberSigned - Check if signed type
    • ColumnResult::isPadded - Check if padded
    • ColumnResult::__construct - ColumnResult constructor
    • com::__construct - com class constructor
    • CommonMark\CQL::__construct - CQL Construction
    • CommonMark\CQL::__invoke - CQL Execution
    • CommonMark\Interfaces\IVisitable::accept - Visitation
    • CommonMark\Interfaces\IVisitor::enter - Visitation
    • CommonMark\Interfaces\IVisitor::leave - Visitation
    • CommonMark\Node::accept - Visitation
    • CommonMark\Node::appendChild - AST Manipulation
    • CommonMark\Node::insertAfter - AST Manipulation
    • CommonMark\Node::insertBefore - AST Manipulation
    • CommonMark\Node::prependChild - AST Manipulation
    • CommonMark\Node::replace - AST Manipulation
    • CommonMark\Node::unlink - AST Manipulation
    • CommonMark\Node\BulletList::__construct - BulletList Construction
    • CommonMark\Node\CodeBlock::__construct - CodeBlock Construction
    • CommonMark\Node\Heading::__construct - Heading Construction
    • CommonMark\Node\Image::__construct - Image Construction
    • CommonMark\Node\Link::__construct - Link Construction
    • CommonMark\Node\OrderedList::__construct - OrderedList Construction
    • CommonMark\Node\Text::__construct - Text Construction
    • CommonMark\Parse - Parsing
    • CommonMark\Parser::finish - Parsing
    • CommonMark\Parser::parse - Parsing
    • CommonMark\Parser::__construct - Parsing
    • CommonMark\Render - Rendering
    • CommonMark\Render\HTML - Rendering
    • CommonMark\Render\Latex - Rendering
    • CommonMark\Render\Man - Rendering
    • CommonMark\Render\XML - Rendering
    • compact - Cria um array contendo variáveis e seus 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 - Add Interface
    • Componere\Abstract\Definition::addMethod - Add Method
    • Componere\Abstract\Definition::addTrait - Add Trait
    • Componere\Abstract\Definition::getReflector - Reflection
    • Componere\cast - Casting
    • Componere\cast_by_ref - Casting
    • Componere\Definition::addConstant - Add Constant
    • Componere\Definition::addProperty - Add Property
    • Componere\Definition::getClosure - Get Closure
    • Componere\Definition::getClosures - Get Closures
    • Componere\Definition::isRegistered - State Detection
    • Componere\Definition::register - Registration
    • Componere\Definition::__construct - Definition Construction
    • Componere\Method::getReflector - Reflection
    • Componere\Method::setPrivate - Accessibility Modification
    • Componere\Method::setProtected - Accessibility Modification
    • Componere\Method::setStatic - Accessibility Modification
    • Componere\Method::__construct - Method Construction
    • Componere\Patch::apply - Application
    • Componere\Patch::derive - Patch Derivation
    • Componere\Patch::getClosure - Get Closure
    • Componere\Patch::getClosures - Get Closures
    • Componere\Patch::isApplied - State Detection
    • Componere\Patch::revert - Reversal
    • Componere\Patch::__construct - Patch Construction
    • Componere\Value::hasDefault - Value Interaction
    • Componere\Value::isPrivate - Accessibility Detection
    • Componere\Value::isProtected - Accessibility Detection
    • Componere\Value::isStatic - Accessibility Detection
    • Componere\Value::setPrivate - Accessibility Modification
    • Componere\Value::setProtected - Accessibility Modification
    • Componere\Value::setStatic - Accessibility Modification
    • Componere\Value::__construct - Value Construction
    • com_create_guid - Generate a globally unique identifier (GUID)
    • com_event_sink - Connect events from a COM object to a PHP object
    • com_get_active_object - Returns a handle to an already running instance of a COM object
    • com_load_typelib - Loads a Typelib
    • com_message_pump - Process COM messages, sleeping for up to timeoutms milliseconds
    • com_print_typeinfo - Print out a PHP class definition for a dispatchable interface
    • connection_aborted - Verifica se o cliente está desconectado
    • connection_status - Retorna o campo de bits do estado da conexão
    • constant - Retorna o valor de uma constante
    • convert_cyr_string - Converte de um conjunto de caracteres cirílico para outro
    • convert_uudecode - Decodifica uma string codificada com uuencode
    • convert_uuencode - Codifica uma string com uuencode
    • copy - Copia arquivo
    • cos - Cosseno
    • cosh - Cosseno hiperbólico
    • count - Conta todos os elementos de um array ou de um objeto Countable
    • Countable::count - Count elements of an object
    • count_chars - Return information about characters used in a string
    • crc32 - Calcula polinômio crc32 de uma string
    • create_function - Cria uma função dinamicamente avaliando uma string de código
    • CrudOperationBindable::bind - Bind value to placeholder
    • CrudOperationLimitable::limit - Set result limit
    • CrudOperationSkippable::skip - Number of operations to skip
    • CrudOperationSortable::sort - Sort results
    • crypt - One-way string hashing
    • ctype_alnum - Verifica se os caracteres são alfanuméricos
    • ctype_alpha - Verifica se os caracteres são alfabéticos
    • ctype_cntrl - Verifica se os caracteres são de controle
    • ctype_digit - Verifica se os caracteres são numéricos
    • ctype_graph - Verifica se os caracteres são imprimíveis exceto espaço
    • ctype_lower - Verifica se os caracteres estão minúsculos
    • ctype_print - Verifica se os caracteres são imprimíveis
    • ctype_punct - Verifica se é um caractere imprimível que não é whitespace ou alfanumério
    • ctype_space - Verifica se os caracteres são whitespace
    • ctype_upper - Verifica se os caracteres são maiúsculos
    • ctype_xdigit - Verifica se os caracteres representam um dígito hexadecimal
    • cubrid_affected_rows - Return the number of rows affected by the last SQL statement
    • cubrid_bind - Bind variables to a prepared statement as parameters
    • cubrid_client_encoding - Return the current CUBRID connection charset
    • cubrid_close - Close CUBRID connection
    • cubrid_close_prepare - Close the request handle
    • cubrid_close_request - Close the request handle
    • cubrid_column_names - Get the column names in result
    • cubrid_column_types - Get column types in result
    • cubrid_col_get - Get contents of collection type column using OID
    • cubrid_col_size - Get the number of elements in collection type column using OID
    • cubrid_commit - Commit a transaction
    • cubrid_connect - Open a connection to a CUBRID Server
    • cubrid_connect_with_url - Establish the environment for connecting to CUBRID server
    • cubrid_current_oid - Get OID of the current cursor location
    • cubrid_data_seek - Move the internal row pointer of the CUBRID result
    • cubrid_db_name - Get db name from results of cubrid_list_dbs
    • cubrid_disconnect - Close a database connection
    • cubrid_drop - Delete an instance using OID
    • cubrid_errno - Return the numerical value of the error message from previous CUBRID operation
    • cubrid_error - Get the error message
    • cubrid_error_code - Get error code for the most recent function call
    • cubrid_error_code_facility - Get the facility code of error
    • cubrid_error_msg - Get last error message for the most recent function call
    • cubrid_execute - Execute a prepared SQL statement
    • cubrid_fetch - Fetch the next row from a result set
    • cubrid_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • cubrid_fetch_assoc - Return the associative array that corresponds to the fetched row
    • cubrid_fetch_field - Get column information from a result and return as an object
    • cubrid_fetch_lengths - Return an array with the lengths of the values of each field from the current row
    • cubrid_fetch_object - Fetch the next row and return it as an object
    • cubrid_fetch_row - Return a numerical array with the values of the current row
    • cubrid_field_flags - Return a string with the flags of the given field offset
    • cubrid_field_len - Get the maximum length of the specified field
    • cubrid_field_name - Return the name of the specified field index
    • cubrid_field_seek - Move the result set cursor to the specified field offset
    • cubrid_field_table - Return the name of the table of the specified field
    • cubrid_field_type - Return the type of the column corresponding to the given field offset
    • cubrid_free_result - Free the memory occupied by the result data
    • cubrid_get - Get a column using OID
    • cubrid_get_autocommit - Get auto-commit mode of the connection
    • cubrid_get_charset - Return the current CUBRID connection charset
    • cubrid_get_class_name - Get the class name using OID
    • cubrid_get_client_info - Return the client library version
    • cubrid_get_db_parameter - Returns the CUBRID database parameters
    • cubrid_get_query_timeout - Get the query timeout value of the request
    • cubrid_get_server_info - Return the CUBRID server version
    • cubrid_insert_id - Return the ID generated for the last updated AUTO_INCREMENT column
    • cubrid_is_instance - Check whether the instance pointed by OID exists
    • cubrid_list_dbs - Return an array with the list of all existing CUBRID databases
    • cubrid_load_from_glo - Read data from a GLO instance and save it in a file
    • cubrid_lob2_bind - Bind a lob object or a string as a lob object to a prepared statement as parameters
    • cubrid_lob2_close - Close LOB object
    • cubrid_lob2_export - Export the lob object to a file
    • cubrid_lob2_import - Import BLOB/CLOB data from a file
    • cubrid_lob2_new - Create a lob object
    • cubrid_lob2_read - Read from BLOB/CLOB data
    • cubrid_lob2_seek - Move the cursor of a lob object
    • cubrid_lob2_seek64 - Move the cursor of a lob object
    • cubrid_lob2_size - Get a lob object's size
    • cubrid_lob2_size64 - Get a lob object's size
    • cubrid_lob2_tell - Tell the cursor position of the LOB object
    • cubrid_lob2_tell64 - Tell the cursor position of the LOB object
    • cubrid_lob2_write - Write to a lob object
    • cubrid_lob_close - Close BLOB/CLOB data
    • cubrid_lob_export - Export BLOB/CLOB data to file
    • cubrid_lob_get - Get BLOB/CLOB data
    • cubrid_lob_send - Read BLOB/CLOB data and send straight to browser
    • cubrid_lob_size - Get BLOB/CLOB data size
    • cubrid_lock_read - Set a read lock on the given OID
    • cubrid_lock_write - Set a write lock on the given OID
    • cubrid_move_cursor - Move the cursor in the result
    • cubrid_new_glo - Create a glo instance
    • cubrid_next_result - Get result of next query when executing multiple SQL statements
    • cubrid_num_cols - Return the number of columns in the result set
    • cubrid_num_fields - Return the number of columns in the result set
    • cubrid_num_rows - Get the number of rows in the result set
    • cubrid_pconnect - Open a persistent connection to a CUBRID server
    • cubrid_pconnect_with_url - Open a persistent connection to CUBRID server
    • cubrid_ping - Ping a server connection or reconnect if there is no connection
    • cubrid_prepare - Prepare a SQL statement for execution
    • cubrid_put - Update a column using OID
    • cubrid_query - Send a CUBRID query
    • cubrid_real_escape_string - Escape special characters in a string for use in an SQL statement
    • cubrid_result - Return the value of a specific field in a specific row
    • cubrid_rollback - Roll back a transaction
    • cubrid_save_to_glo - Save requested file in a GLO instance
    • cubrid_schema - Get the requested schema information
    • cubrid_send_glo - Read data from glo and send it to std output
    • cubrid_seq_drop - Delete an element from sequence type column using OID
    • cubrid_seq_insert - Insert an element to a sequence type column using OID
    • cubrid_seq_put - Update the element value of sequence type column using OID
    • cubrid_set_add - Insert a single element to set type column using OID
    • cubrid_set_autocommit - Set autocommit mode of the connection
    • cubrid_set_db_parameter - Sets the CUBRID database parameters
    • cubrid_set_drop - Delete an element from set type column using OID
    • cubrid_set_query_timeout - Set the timeout time of query execution
    • cubrid_unbuffered_query - Perform a query without fetching the results into memory
    • cubrid_version - Get the CUBRID PHP module's version
    • CURLFile::getFilename - Obtém o nome do arquivo
    • CURLFile::getMimeType - Obtém o tipo mídia
    • CURLFile::getPostFilename - Obtém o nome do arquivo para requisição POST
    • CURLFile::setMimeType - Define o tipo de mídia
    • CURLFile::setPostFilename - Define o nome do arquivo para a requisição POST
    • CURLFile::__construct - Criar um objeto CURLFile
    • CURLStringFile::__construct - Crie um objeto CURLStringFile
    • curl_close - Fecha uma sessão cURL
    • curl_copy_handle - Copia um controlador cURL com todas as suas opções
    • curl_errno - Retorna o número do último erro
    • curl_error - Retorna uma string contendo o último erro da sessão atual
    • curl_escape - Codifica uma string para o formato URL
    • curl_exec - Executa uma sessão cURL
    • curl_getinfo - Obtém informação sobre uma transferência específica
    • curl_init - Inicializar uma sessão cURL
    • curl_multi_add_handle - Adiciona um manipulador cURL comum a um manipulador cURL múltiplo
    • curl_multi_close - Fechar um conjunto de alças cURL
    • curl_multi_errno - Retorna o último número de erro de curl_multi
    • curl_multi_exec - Executa as subconexões do manipulador cURL atual
    • curl_multi_getcontent - Retorna o conteúdo de um manipulador cURL se CURLOPT_RETURNTRANSFER estiver definido
    • curl_multi_info_read - Obtém informação sobre as transferências atuais
    • curl_multi_init - Retorna um multi-manipulador cURL
    • curl_multi_remove_handle - Remove um manipulador de um conjunto de manipuladores cURL
    • curl_multi_select - Aguarda por atividade em qualquer multi-conexão cURL
    • curl_multi_setopt - Define múltiplas opções para cURL
    • curl_multi_strerror - Retorna uma string que descreve o código de erro
    • curl_pause - Pausa ou continua uma conexão
    • curl_reset - Reseta todas as opções de um controlador de sessão libcurl
    • curl_setopt - Define uma opção para uma transferência cURL
    • curl_setopt_array - Define múltiplas opções para uma transferência cURL
    • curl_share_close - Fecha um controlador de compartilhamento de cURL
    • curl_share_errno - Retorna o último número de erro do curl compartilhado
    • curl_share_init - Inicializa um controlador de compartilhamento de cURL
    • curl_share_setopt - Configura uma opção para um controlador de compartilhamento de cURL
    • curl_share_strerror - Retorna uma string descrevendo o código de erro fornecid
    • curl_strerror - Retorna uma string que descreve o código de erro informado
    • curl_unescape - Decodifica a parte codificada da URL fornecida
    • curl_upkeep - Executa qualquer verificação de manutenção de conexão
    • curl_version - Obtém informação de versão do cURL
    • current - Retorna o elemento atual em um array
  • d
    • data:// - Dados (RFC 2397)
    • DatabaseObject::existsInDatabase - Check if object exists in database
    • DatabaseObject::getName - Get object name
    • DatabaseObject::getSession - Get session name
    • date - Formatar um timestamp Unix
    • DateInterval::createFromDateString - Cria um DateInterval de porções relativas da string
    • DateInterval::format - Formata um intervalo
    • DateInterval::__construct - Cria um novo objeto DateInterval
    • DatePeriod::createFromISO8601String - Cria um novo objeto DatePeriod a partir de uma string ISO8601
    • DatePeriod::getDateInterval - Obtém o intervalo
    • DatePeriod::getEndDate - Obtém a data final
    • DatePeriod::getRecurrences - Obtém o número de recorrências
    • DatePeriod::getStartDate - Obtém a data inicial
    • DatePeriod::__construct - Cria um novo objeto DatePeriod
    • DateTime::add - Modifica um objeto DateTime, com adição de dias, meses, anos, horas, minutos e segundos.
    • DateTime::createFromFormat - Interpreta um string de data/hora de acordo com um formato especificado.
    • DateTime::createFromImmutable - Retorna uma nova instância de DateTime encapsulando o objeto DateTimeImmutable informado
    • DateTime::createFromInterface - Retorna um novo objeto DateTime encapsulando o objeto DateTimeInterface informado
    • DateTime::getLastErrors - Sinônimo de DateTimeImmutable::getLastErrors
    • DateTime::modify - Altera o timestamp
    • DateTime::setDate - Define a data
    • DateTime::setISODate - Define uma data ISO
    • DateTime::setTime - Define o horário
    • DateTime::setTimestamp - Define a data e hora baseada em um timestamp Unix
    • DateTime::setTimezone - Define o fuso horário de um objeto DateTime
    • DateTime::sub - Subtrai uma quantidade de dias, meses, anos, horas, minutos e segundos de um objeto DateTime
    • DateTime::__construct - Retorna um novo objeto DateTime
    • DateTime::__set_state - O manipulador __set_state
    • DateTime::__wakeup - O manipulador __wakeup
    • DateTimeImmutable::add - Retorna um novo objeto, com adição de dias, meses, anos, horas, minutos e segundos
    • DateTimeImmutable::createFromFormat - Interpreta um string de data/hora de acordo com o formato especificado
    • DateTimeImmutable::createFromInterface - Retorna um novo objeto DateTimeImmutable encapsulando o objeto DateTimeInterface informado
    • DateTimeImmutable::createFromMutable - Retorna uma nova instância DateTimeImmutable que encapsula um objeto DateTime informado
    • DateTimeImmutable::getLastErrors - Retorna os avisos e erros
    • DateTimeImmutable::modify - Cria um novo objeto com seu timestamp modificado
    • DateTimeImmutable::setDate - Define a data
    • DateTimeImmutable::setISODate - Define a data ISO
    • DateTimeImmutable::setTime - Define um horário
    • DateTimeImmutable::setTimestamp - Define a data e o horário com base em um timestamp Unix
    • DateTimeImmutable::setTimezone - Define o fuso horário
    • DateTimeImmutable::sub - Subtrai uma quantidade de dias, meses, anos, horas, minutos e segundos
    • DateTimeImmutable::__construct - Retorna um novo objeto DateTimeImmutable
    • DateTimeImmutable::__set_state - O manipulador __set_state
    • DateTimeInterface::diff - Retorna a diferença entre dois objetos DateTime
    • DateTimeInterface::format - Retorna a data formatada de acordo com um formato informado
    • DateTimeInterface::getOffset - Retorna o deslocamento do fuso horário
    • DateTimeInterface::getTimestamp - Obtém o timestamp Unix
    • DateTimeInterface::getTimezone - Retorna o fuso horário correspondente a um DateTime informado
    • DateTimeZone::getLocation - Retorna informações da localização de um fuso horário
    • DateTimeZone::getName - Retorna o nome do fuso horário
    • DateTimeZone::getOffset - Retorna o deslocamento do fuso horário ao Horário de Greenwish (GMT)
    • DateTimeZone::getTransitions - Retorna todas as transições para o fuso horário
    • DateTimeZone::listAbbreviations - Retorna um array associativo contendo indicativo de horário de verãorão(dst), deslocamento e nome do fuso horário
    • DateTimeZone::listIdentifiers - Retorna um array numericamente indexado contendo todos os indenticadores de fuso horário
    • DateTimeZone::__construct - Cria um novo objeto DateTimeZone
    • date_add - Sinônimo de DateTime::add
    • date_create - Cria um novo objeto DateTime
    • date_create_from_format - Sinônimo de DateTime::createFromFormat
    • date_create_immutable - Cria um novo objeto DateTimeImmutable
    • date_create_immutable_from_format - Sinônimo de DateTimeImmutable::createFromFormat
    • date_date_set - Sinônimo de DateTime::setDate
    • date_default_timezone_get - Retorna o fuso horário padrão usado por todas as funções de data e tempo em um script
    • date_default_timezone_set - Configura o fuso horário padrão utilizado por todas as funções de data e hora em um script
    • date_diff - Sinônimo de DateTime::diff
    • date_format - Sinônimo de DateTime::format
    • date_get_last_errors - Sinônimo de DateTimeImmutable::getLastErrors
    • date_interval_create_from_date_string - Sinônimo de DateInterval::createFromDateString
    • date_interval_format - Sinônimo de DateInterval::format
    • date_isodate_set - Sinônimo de DateTime::setISODate
    • date_modify - Sinônimo de DateTime::modify
    • date_offset_get - Sinônimo de DateTime::getOffset
    • date_parse - Retorna um array associativo com informações detalhadas da data/hora informada
    • date_parse_from_format - Retorna informações sobre uma data informada de acordo com um formato
    • date_sub - Sinônimo de DateTime::sub
    • date_sunrise - Retorna a hora do nascer do sol para um dia e uma localicação informados
    • date_sunset - Retorna a hora do pôr do sol para um dia e uma localização informados.
    • date_sun_info - Retorna um array com informações sobre pôr/nascer do sol e o início/fim do dia
    • date_timestamp_get - Sinônimo de DateTime::getTimestamp
    • date_timestamp_set - Sinônimo de DateTime::setTimestamp
    • date_timezone_get - Sinônimo de DateTime::getTimezone
    • date_timezone_set - Sinônimo de DateTime::setTimezone
    • date_time_set - Sinônimo de DateTime::setTime
    • db2_autocommit - Returns or sets the AUTOCOMMIT state for a database connection
    • db2_bind_param - Binds a PHP variable to an SQL statement parameter
    • db2_client_info - Returns an object with properties that describe the DB2 database client
    • db2_close - Closes a database connection
    • db2_columns - Returns a result set listing the columns and associated metadata for a table
    • db2_column_privileges - Returns a result set listing the columns and associated privileges for a table
    • db2_commit - Commits a transaction
    • db2_connect - Returns a connection to a database
    • db2_conn_error - Returns a string containing the SQLSTATE returned by the last connection attempt
    • db2_conn_errormsg - Returns the last connection error message and SQLCODE value
    • db2_cursor_type - Returns the cursor type used by a statement resource
    • db2_escape_string - Used to escape certain characters
    • db2_exec - Executes an SQL statement directly
    • db2_execute - Executes a prepared SQL statement
    • db2_fetch_array - Returns an array, indexed by column position, representing a row in a result set
    • db2_fetch_assoc - Returns an array, indexed by column name, representing a row in a result set
    • db2_fetch_both - Returns an array, indexed by both column name and position, representing a row in a result set
    • db2_fetch_object - Returns an object with properties representing columns in the fetched row
    • db2_fetch_row - Sets the result set pointer to the next row or requested row
    • db2_field_display_size - Returns the maximum number of bytes required to display a column
    • db2_field_name - Returns the name of the column in the result set
    • db2_field_num - Returns the position of the named column in a result set
    • db2_field_precision - Returns the precision of the indicated column in a result set
    • db2_field_scale - Returns the scale of the indicated column in a result set
    • db2_field_type - Returns the data type of the indicated column in a result set
    • db2_field_width - Returns the width of the current value of the indicated column in a result set
    • db2_foreign_keys - Returns a result set listing the foreign keys for a table
    • db2_free_result - Frees resources associated with a result set
    • db2_free_stmt - Frees resources associated with the indicated statement resource
    • db2_get_option - Retrieves an option value for a statement resource or a connection resource
    • db2_last_insert_id - Returns the auto generated ID of the last insert query that successfully executed on this connection
    • db2_lob_read - Gets a user defined size of LOB files with each invocation
    • db2_next_result - Requests the next result set from a stored procedure
    • db2_num_fields - Returns the number of fields contained in a result set
    • db2_num_rows - Returns the number of rows affected by an SQL statement
    • db2_pclose - Closes a persistent database connection
    • db2_pconnect - Returns a persistent connection to a database
    • db2_prepare - Prepares an SQL statement to be executed
    • db2_primary_keys - Returns a result set listing primary keys for a table
    • db2_procedures - Returns a result set listing the stored procedures registered in a database
    • db2_procedure_columns - Returns a result set listing stored procedure parameters
    • db2_result - Returns a single column from a row in the result set
    • db2_rollback - Rolls back a transaction
    • db2_server_info - Returns an object with properties that describe the DB2 database server
    • db2_set_option - Set options for connection or statement resources
    • db2_special_columns - Returns a result set listing the unique row identifier columns for a table
    • db2_statistics - Returns a result set listing the index and statistics for a table
    • db2_stmt_error - Returns a string containing the SQLSTATE returned by an SQL statement
    • db2_stmt_errormsg - Returns a string containing the last SQL statement error message
    • db2_tables - Returns a result set listing the tables and associated metadata in a database
    • db2_table_privileges - Returns a result set listing the tables and associated privileges in a database
    • dbase_add_record - Adiciona um registro a um banco de dados
    • dbase_close - Fecha um banco de dados
    • dbase_create - Cria um banco de dados
    • dbase_delete_record - Exclui um registro do banco de dados
    • dbase_get_header_info - Obtém as informações do cabeçalho do banco de dados
    • dbase_get_record - Obtém um registro do banco de dados como um array indexado
    • dbase_get_record_with_names - Obtém um registro do banco de dados como um array associativo.
    • dbase_numfields - Obtém o número de campos em um banco de dados
    • dbase_numrecords - Obtém o número de registros em um banco de dados
    • dbase_open - Abre um banco de dados
    • dbase_pack - Comprime um banco de dados
    • dbase_replace_record - Substitui um registro em um banco de dados
    • dba_close - Close a DBA database
    • dba_delete - Delete DBA entry specified by key
    • dba_exists - Check whether key exists
    • dba_fetch - Fetch data specified by key
    • dba_firstkey - Fetch first key
    • dba_handlers - List all the handlers available
    • dba_insert - Insert entry
    • dba_key_split - Splits a key in string representation into array representation
    • dba_list - List all open database files
    • dba_nextkey - Fetch next key
    • dba_open - Open database
    • dba_optimize - Optimize database
    • dba_popen - Open database persistently
    • dba_replace - Replace or insert entry
    • dba_sync - Synchronize database
    • dcgettext - Substitui o domínio por um lookup
    • dcngettext - Plural version of dcgettext
    • debug_backtrace - Generates a backtrace
    • debug_print_backtrace - Mostra um rastreamento retroativo
    • debug_zval_dump - Exibe na saída uma representação em string de uma estrutura zval interna
    • decbin - Decimal para binário
    • dechex - Decimal para hexadecimal
    • decoct - Decimal para octal
    • define - Defines a named constant
    • defined - Checks whether a given named constant exists
    • deflate_add - Incrementally deflate data
    • deflate_init - Initialize an incremental deflate context
    • deg2rad - Converte o número em graus para o equivalente em radianos
    • delete - Consulte unlink ou unset
    • dgettext - Override the current domain
    • die - Equivalent to exit
    • dio_close - Closes the file descriptor given by fd
    • dio_fcntl - Performs a c library fcntl on fd
    • dio_open - Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow
    • dio_read - Reads bytes from a file descriptor
    • dio_seek - Seeks to pos on fd from whence
    • dio_stat - Gets stat information about the file descriptor fd
    • dio_tcsetattr - Sets terminal attributes and baud rate for a serial port
    • dio_truncate - Truncates file descriptor fd to offset bytes
    • dio_write - Writes data to fd with optional truncation at length
    • dir - Retorna uma instância da classe Directory
    • Directory::close - Fecha o manipulador de diretório
    • Directory::read - Lê entrada de um manipulador de diretório
    • Directory::rewind - Retrocede um manipulador de diretório
    • DirectoryIterator::current - Return the current DirectoryIterator item
    • DirectoryIterator::getBasename - Retorna o nome do item corrente do DirectoryIterator
    • DirectoryIterator::getExtension - Obtém a extensão do arquivo
    • DirectoryIterator::getFilename - Return file name of current DirectoryIterator item
    • DirectoryIterator::isDot - Determine if current DirectoryIterator item is '.' or '..'
    • DirectoryIterator::key - Return the key for the current DirectoryIterator item
    • DirectoryIterator::next - Move forward to next DirectoryIterator item
    • DirectoryIterator::rewind - Rewind the DirectoryIterator back to the start
    • DirectoryIterator::seek - Procura uma determinada posição no item do DirectoryIterator
    • DirectoryIterator::valid - Check whether current DirectoryIterator position is a valid file
    • DirectoryIterator::__construct - Constructs a new directory iterator from a path
    • DirectoryIterator::__toString - Retorna o nome do arquivo como texto
    • dirname - Retorna o caminho para o diretório pai
    • diskfreespace - Sinônimo de disk_free_space
    • disk_free_space - Retorna o espaço disponível no sistema de arquivos ou partição de disco
    • disk_total_space - Retorna o tamanho total de um sistema de arquivos ou partição de disco
    • dl - Carrega uma extensão do PHP durante a execução
    • dngettext - Plural version of dgettext
    • dns_check_record - Sinônimo de checkdnsrr
    • dns_get_mx - Sinônimo 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 - Checks if attribute is a defined ID
    • DOMAttr::__construct - Creates a new DOMAttr object
    • DOMCdataSection::__construct - Constructs a new DOMCdataSection object
    • DOMCharacterData::after - Adds nodes after the character data
    • DOMCharacterData::appendData - Append the string to the end of the character data of the node
    • DOMCharacterData::before - Adds nodes before the node
    • DOMCharacterData::deleteData - Remove a range of characters from the node
    • DOMCharacterData::insertData - Insert a string at the specified 16-bit unit offset
    • DOMCharacterData::remove - Removes the character data
    • DOMCharacterData::replaceData - Replace a substring within the DOMCharacterData node
    • DOMCharacterData::replaceWith - Replaces the character data with new nodes
    • DOMCharacterData::substringData - Extracts a range of data from the node
    • DOMChildNode::after - Adds nodes after the node
    • DOMChildNode::before - Adds nodes before the node
    • DOMChildNode::remove - Removes the node
    • DOMChildNode::replaceWith - Replaces the node with new nodes
    • DOMComment::__construct - Creates a new DOMComment object
    • DOMDocument::adoptNode - Transfer a node from another document
    • DOMDocument::append - Appends nodes after the last child node
    • DOMDocument::createAttribute - Create new attribute
    • DOMDocument::createAttributeNS - Create new attribute node with an associated namespace
    • DOMDocument::createCDATASection - Create new cdata node
    • DOMDocument::createComment - Create new comment node
    • DOMDocument::createDocumentFragment - Create new document fragment
    • DOMDocument::createElement - Create new element node
    • DOMDocument::createElementNS - Create new element node with an associated namespace
    • DOMDocument::createEntityReference - Create new entity reference node
    • DOMDocument::createProcessingInstruction - Creates new PI node
    • DOMDocument::createTextNode - Create new text node
    • DOMDocument::getElementById - Searches for an element with a certain id
    • DOMDocument::getElementsByTagName - Searches for all elements with given local tag name
    • DOMDocument::getElementsByTagNameNS - Searches for all elements with given tag name in specified namespace
    • DOMDocument::importNode - Import node into current document
    • DOMDocument::load - Load XML from a file
    • DOMDocument::loadHTML - Load HTML from a string
    • DOMDocument::loadHTMLFile - Load HTML from a file
    • DOMDocument::loadXML - Load XML from a string
    • DOMDocument::normalizeDocument - Normalizes the document
    • DOMDocument::prepend - Prepends nodes before the first child node
    • DOMDocument::registerNodeClass - Register extended class used to create base node type
    • DOMDocument::relaxNGValidate - Performs relaxNG validation on the document
    • DOMDocument::relaxNGValidateSource - Performs relaxNG validation on the document
    • DOMDocument::replaceChildren - Replace children in document
    • DOMDocument::save - Dumps the internal XML tree back into a file
    • DOMDocument::saveHTML - Dumps the internal document into a string using HTML formatting
    • DOMDocument::saveHTMLFile - Dumps the internal document into a file using HTML formatting
    • DOMDocument::saveXML - Dumps the internal XML tree back into a string
    • DOMDocument::schemaValidate - Validates a document based on a schema. Only XML Schema 1.0 is supported.
    • DOMDocument::schemaValidateSource - Validates a document based on a schema
    • DOMDocument::validate - Validates the document based on its DTD
    • DOMDocument::xinclude - Substitutes XIncludes in a DOMDocument Object
    • DOMDocument::__construct - Creates a new DOMDocument object
    • DOMDocumentFragment::append - Appends nodes after the last child node
    • DOMDocumentFragment::appendXML - Append raw XML data
    • 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 - Returns value of attribute
    • DOMElement::getAttributeNames - Get attribute names
    • DOMElement::getAttributeNode - Returns attribute node
    • DOMElement::getAttributeNodeNS - Returns attribute node
    • DOMElement::getAttributeNS - Returns value of attribute
    • DOMElement::getElementsByTagName - Gets elements by tagname
    • DOMElement::getElementsByTagNameNS - Get elements by namespaceURI and localName
    • DOMElement::hasAttribute - Checks to see if attribute exists
    • DOMElement::hasAttributeNS - Checks to see if attribute exists
    • DOMElement::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 - Removes attribute
    • DOMElement::removeAttributeNode - Removes attribute
    • DOMElement::removeAttributeNS - Removes attribute
    • DOMElement::replaceChildren - Replace children in element
    • DOMElement::replaceWith - Replaces the element with new nodes
    • DOMElement::setAttribute - Adds new or modifies existing attribute
    • DOMElement::setAttributeNode - Adds new attribute node to element
    • DOMElement::setAttributeNodeNS - Adds new attribute node to element
    • DOMElement::setAttributeNS - Adds new attribute
    • DOMElement::setIdAttribute - Declares the attribute specified by name to be of type ID
    • DOMElement::setIdAttributeNode - Declares the attribute specified by node to be of type ID
    • DOMElement::setIdAttributeNS - Declares the attribute specified by local name and namespace URI to be of type ID
    • DOMElement::toggleAttribute - Toggle attribute
    • DOMElement::__construct - Creates a new DOMElement object
    • DOMEntityReference::__construct - Creates a new DOMEntityReference object
    • DOMImplementation::createDocument - Creates a DOMDocument object of the specified type with its document element
    • DOMImplementation::createDocumentType - Creates an empty DOMDocumentType object
    • DOMImplementation::hasFeature - Test if the DOM implementation implements a specific feature
    • DOMImplementation::__construct - Creates a new DOMImplementation object
    • DOMNamedNodeMap::count - Get number of nodes in the map
    • DOMNamedNodeMap::getIterator - Retrieve an external iterator
    • DOMNamedNodeMap::getNamedItem - Retrieves a node specified by name
    • DOMNamedNodeMap::getNamedItemNS - Retrieves a node specified by local name and namespace URI
    • DOMNamedNodeMap::item - Retrieves a node specified by index
    • DOMNode::appendChild - Adiciona um novo filho ao final dos filhos
    • DOMNode::C14N - Canonicalize nodes to a string
    • DOMNode::C14NFile - Canonicalize nodes to a file
    • DOMNode::cloneNode - Clones a node
    • DOMNode::contains - Checks if node contains other node
    • DOMNode::getLineNo - Get line number for a node
    • DOMNode::getNodePath - Get an XPath for a node
    • DOMNode::getRootNode - Get root node
    • DOMNode::hasAttributes - Checks if node has attributes
    • DOMNode::hasChildNodes - Checks if node has children
    • DOMNode::insertBefore - Adds a new child before a reference node
    • DOMNode::isDefaultNamespace - Checks if the specified namespaceURI is the default namespace or not
    • DOMNode::isEqualNode - Checks that both nodes are equal
    • DOMNode::isSameNode - Indicates if two nodes are the same node
    • DOMNode::isSupported - Checks if feature is supported for specified version
    • DOMNode::lookupNamespaceURI - Gets the namespace URI of the node based on the prefix
    • DOMNode::lookupPrefix - Gets the namespace prefix of the node based on the namespace URI
    • DOMNode::normalize - Normalizes the node
    • DOMNode::removeChild - Removes child from list of children
    • DOMNode::replaceChild - Replaces a child
    • DOMNodeList::count - Get number of nodes in the list
    • DOMNodeList::getIterator - Retrieve an external iterator
    • DOMNodeList::item - Retrieves a node specified by index
    • DOMParentNode::append - Appends nodes after the last child node
    • DOMParentNode::prepend - Prepends nodes before the first child node
    • DOMParentNode::replaceChildren - Replace children in node
    • DOMProcessingInstruction::__construct - Creates a new DOMProcessingInstruction object
    • DOMText::isElementContentWhitespace - Returns whether this text node contains whitespace in element content
    • DOMText::isWhitespaceInElementContent - Indicates whether this text node contains whitespace
    • DOMText::splitText - Quebra este nó em dois nós no deslocamento especificado
    • DOMText::__construct - Creates a new DOMText object
    • DOMXPath::evaluate - Evaluates the given XPath expression and returns a typed result if possible
    • DOMXPath::query - Evaluates the given XPath expression
    • DOMXPath::registerNamespace - Registers the namespace with the DOMXPath object
    • DOMXPath::registerPhpFunctions - Register PHP functions as XPath functions
    • DOMXPath::__construct - Creates a new DOMXPath object
    • dom_import_simplexml - Gets a DOMElement object from a SimpleXMLElement object
    • dotnet::__construct - dotnet class constructor
    • doubleval - Sinônimo de floatval
    • DSN PDO_SQLITE - Conectando a bancos de dados SQLite
    • Ds\Collection::clear - Removes all values
    • Ds\Collection::copy - Returns a shallow copy of the collection
    • Ds\Collection::isEmpty - Returns whether the collection is empty
    • Ds\Collection::toArray - Converts the collection to an array
    • Ds\Deque::allocate - Allocates enough memory for a required capacity
    • Ds\Deque::apply - Updates all values by applying a callback function to each value
    • Ds\Deque::capacity - Returns the current capacity
    • Ds\Deque::clear - Removes all values from the deque
    • Ds\Deque::contains - Determines if the deque contains given values
    • Ds\Deque::copy - Returns a shallow copy of the deque
    • Ds\Deque::count - Returns the number of values in the collection
    • Ds\Deque::filter - Creates a new deque using a callable to determine which values to include
    • Ds\Deque::find - Attempts to find a value's index
    • Ds\Deque::first - Returns the first value in the deque
    • Ds\Deque::get - Returns the value at a given index
    • Ds\Deque::insert - Inserts values at a given index
    • Ds\Deque::isEmpty - Returns whether the deque is empty
    • Ds\Deque::join - Joins all values together as a string
    • Ds\Deque::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Deque::last - Returns the last value
    • Ds\Deque::map - Returns the result of applying a callback to each value
    • Ds\Deque::merge - Returns the result of adding all given values to the deque
    • Ds\Deque::pop - Removes and returns the last value
    • Ds\Deque::push - Adds values to the end of the deque
    • Ds\Deque::reduce - Reduces the deque to a single value using a callback function
    • Ds\Deque::remove - Removes and returns a value by index
    • Ds\Deque::reverse - Reverses the deque in-place
    • Ds\Deque::reversed - Returns a reversed copy
    • Ds\Deque::rotate - Rotates the deque by a given number of rotations
    • Ds\Deque::set - Updates a value at a given index
    • Ds\Deque::shift - Removes and returns the first value
    • Ds\Deque::slice - Returns a sub-deque of a given range
    • Ds\Deque::sort - Sorts the deque in-place
    • Ds\Deque::sorted - Returns a sorted copy
    • Ds\Deque::sum - Returns the sum of all values in the deque
    • Ds\Deque::toArray - Converts the deque to an array
    • Ds\Deque::unshift - Adds values to the front of the deque
    • Ds\Deque::__construct - Creates a new instance
    • Ds\Hashable::equals - Determines whether an object is equal to the current instance
    • Ds\Hashable::hash - Returns a scalar value to be used as a hash value
    • Ds\Map::allocate - Allocates enough memory for a required capacity
    • Ds\Map::apply - Updates all values by applying a callback function to each value
    • Ds\Map::capacity - Returns the current capacity
    • Ds\Map::clear - Removes all values
    • Ds\Map::copy - Returns a shallow copy of the map
    • Ds\Map::count - Returns the number of values in the map
    • Ds\Map::diff - Creates a new map using keys that aren't in another map
    • Ds\Map::filter - Creates a new map using a callable to determine which pairs to include
    • Ds\Map::first - Returns the first pair in the map
    • Ds\Map::get - Returns the value for a given key
    • Ds\Map::hasKey - Determines whether the map contains a given key
    • Ds\Map::hasValue - Determines whether the map contains a given value
    • Ds\Map::intersect - Creates a new map by intersecting keys with another map
    • Ds\Map::isEmpty - Returns whether the map is empty
    • Ds\Map::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Map::keys - Returns a set of the map's keys
    • Ds\Map::ksort - Sorts the map in-place by key
    • Ds\Map::ksorted - Returns a copy, sorted by key
    • Ds\Map::last - Returns the last pair of the map
    • Ds\Map::map - Returns the result of applying a callback to each value
    • Ds\Map::merge - Returns the result of adding all given associations
    • Ds\Map::pairs - Returns a sequence containing all the pairs of the map
    • Ds\Map::put - Associates a key with a value
    • Ds\Map::putAll - Associates all key-value pairs of a traversable object or array
    • Ds\Map::reduce - Reduces the map to a single value using a callback function
    • Ds\Map::remove - Removes and returns a value by key
    • Ds\Map::reverse - Reverses the map in-place
    • Ds\Map::reversed - Returns a reversed copy
    • Ds\Map::skip - Returns the pair at a given positional index
    • Ds\Map::slice - Returns a subset of the map defined by a starting index and length
    • Ds\Map::sort - Sorts the map in-place by value
    • Ds\Map::sorted - Returns a copy, sorted by value
    • Ds\Map::sum - Returns the sum of all values in the map
    • Ds\Map::toArray - Converts the map to an array
    • Ds\Map::union - Creates a new map using values from the current instance and another map
    • Ds\Map::values - Returns a sequence of the map's values
    • Ds\Map::xor - Creates a new map using keys of either the current instance or of another map, but not of both
    • Ds\Map::__construct - Creates a new instance
    • Ds\Pair::clear - Removes all values
    • Ds\Pair::copy - Returns a shallow copy of the pair
    • Ds\Pair::isEmpty - Returns whether the pair is empty
    • Ds\Pair::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Pair::toArray - Converts the pair to an array
    • Ds\Pair::__construct - Creates a new instance
    • Ds\PriorityQueue::allocate - Allocates enough memory for a required capacity
    • Ds\PriorityQueue::capacity - Returns the current capacity
    • Ds\PriorityQueue::clear - Removes all values
    • Ds\PriorityQueue::copy - Returns a shallow copy of the queue
    • Ds\PriorityQueue::count - Returns the number of values in the queue
    • Ds\PriorityQueue::isEmpty - Returns whether the queue is empty
    • Ds\PriorityQueue::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\PriorityQueue::peek - Returns the value at the front of the queue
    • Ds\PriorityQueue::pop - Removes and returns the value with the highest priority
    • Ds\PriorityQueue::push - Pushes values into the queue
    • Ds\PriorityQueue::toArray - Converts the queue to an array
    • Ds\PriorityQueue::__construct - Creates a new instance
    • Ds\Queue::allocate - Allocates enough memory for a required capacity
    • Ds\Queue::capacity - Returns the current capacity
    • Ds\Queue::clear - Removes all values
    • Ds\Queue::copy - Returns a shallow copy of the queue
    • Ds\Queue::count - Returns the number of values in the queue
    • Ds\Queue::isEmpty - Returns whether the queue is empty
    • Ds\Queue::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Queue::peek - Returns the value at the front of the queue
    • Ds\Queue::pop - Removes and returns the value at the front of the queue
    • Ds\Queue::push - Pushes values into the queue
    • Ds\Queue::toArray - Converts the queue to an array
    • Ds\Queue::__construct - Creates a new instance
    • Ds\Sequence::allocate - Allocates enough memory for a required capacity
    • Ds\Sequence::apply - Updates all values by applying a callback function to each value
    • Ds\Sequence::capacity - Returns the current capacity
    • Ds\Sequence::contains - Determines if the sequence contains given values
    • Ds\Sequence::filter - Creates a new sequence using a callable to determine which values to include
    • Ds\Sequence::find - Attempts to find a value's index
    • Ds\Sequence::first - Returns the first value in the sequence
    • Ds\Sequence::get - Returns the value at a given index
    • Ds\Sequence::insert - Inserts values at a given index
    • Ds\Sequence::join - Joins all values together as a string
    • Ds\Sequence::last - Returns the last value
    • Ds\Sequence::map - Returns the result of applying a callback to each value
    • Ds\Sequence::merge - Returns the result of adding all given values to the sequence
    • Ds\Sequence::pop - Removes and returns the last value
    • Ds\Sequence::push - Adds values to the end of the sequence
    • Ds\Sequence::reduce - Reduces the sequence to a single value using a callback function
    • Ds\Sequence::remove - Removes and returns a value by index
    • Ds\Sequence::reverse - Reverses the sequence in-place
    • Ds\Sequence::reversed - Returns a reversed copy
    • Ds\Sequence::rotate - Rotates the sequence by a given number of rotations
    • Ds\Sequence::set - Updates a value at a given index
    • Ds\Sequence::shift - Removes and returns the first value
    • Ds\Sequence::slice - Returns a sub-sequence of a given range
    • Ds\Sequence::sort - Sorts the sequence in-place
    • Ds\Sequence::sorted - Returns a sorted copy
    • Ds\Sequence::sum - Returns the sum of all values in the sequence
    • Ds\Sequence::unshift - Adds values to the front of the sequence
    • Ds\Set::add - Adds values to the set
    • Ds\Set::allocate - Allocates enough memory for a required capacity
    • Ds\Set::capacity - Returns the current capacity
    • Ds\Set::clear - Removes all values
    • Ds\Set::contains - Determines if the set contains all values
    • Ds\Set::copy - Returns a shallow copy of the set
    • Ds\Set::count - Returns the number of values in the set
    • Ds\Set::diff - Creates a new set using values that aren't in another set
    • Ds\Set::filter - Creates a new set using a callable to determine which values to include
    • Ds\Set::first - Returns the first value in the set
    • Ds\Set::get - Returns the value at a given index
    • Ds\Set::intersect - Creates a new set by intersecting values with another set
    • Ds\Set::isEmpty - Returns whether the set is empty
    • Ds\Set::join - Joins all values together as a string
    • Ds\Set::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Set::last - Returns the last value in the set
    • Ds\Set::merge - Returns the result of adding all given values to the set
    • Ds\Set::reduce - Reduces the set to a single value using a callback function
    • Ds\Set::remove - Removes all given values from the set
    • Ds\Set::reverse - Reverses the set in-place
    • Ds\Set::reversed - Returns a reversed copy
    • Ds\Set::slice - Returns a sub-set of a given range
    • Ds\Set::sort - Sorts the set in-place
    • Ds\Set::sorted - Returns a sorted copy
    • Ds\Set::sum - Returns the sum of all values in the set
    • Ds\Set::toArray - Converts the set to an array
    • Ds\Set::union - Creates a new set using values from the current instance and another set
    • Ds\Set::xor - Creates a new set using values in either the current instance or in another set, but not in both
    • Ds\Set::__construct - Creates a new instance
    • Ds\Stack::allocate - Allocates enough memory for a required capacity
    • Ds\Stack::capacity - Returns the current capacity
    • Ds\Stack::clear - Removes all values
    • Ds\Stack::copy - Returns a shallow copy of the stack
    • Ds\Stack::count - Retorna o número de valores na pilha
    • Ds\Stack::isEmpty - Returns whether the stack is empty
    • Ds\Stack::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Stack::peek - Retorna o valor no topo da pilha
    • 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 - Retorna o par atual de chave e valor de um array e avança o seu cursor
    • easter_date - Get Unix timestamp for midnight on Easter of a given year
    • easter_days - Get number of days after March 21 on which Easter falls for a given year
    • echo - Output one or more strings
    • eio_busy - Artificially increase load. Could be useful in tests, benchmarking
    • eio_cancel - Cancels a request
    • eio_chmod - Change file/directory permissions
    • eio_chown - Change file/directory permissions
    • eio_close - Close file
    • eio_custom - Execute custom request like any other eio_* call
    • eio_dup2 - Duplicate a file descriptor
    • eio_event_loop - Polls libeio until all requests proceeded
    • eio_fallocate - Allows the caller to directly manipulate the allocated disk space for a file
    • eio_fchmod - Change file permissions
    • eio_fchown - Change file ownership
    • eio_fdatasync - Synchronize a file's in-core state with storage device
    • eio_fstat - Get file status
    • eio_fstatvfs - Get file system statistics
    • eio_fsync - Synchronize a file's in-core state with storage device
    • eio_ftruncate - Truncate a file
    • eio_futime - Change file last access and modification times
    • eio_get_event_stream - Get stream representing a variable used in internal communications with libeio
    • eio_get_last_error - Returns string describing the last error associated with a request resource
    • eio_grp - Creates a request group
    • eio_grp_add - Adds a request to the request group
    • eio_grp_cancel - Cancels a request group
    • eio_grp_limit - Set group limit
    • eio_init - (Re-)initialize Eio
    • eio_link - Create a hardlink for file
    • eio_lstat - Get file status
    • eio_mkdir - Create directory
    • eio_mknod - Create a special or ordinary file
    • eio_nop - Does nothing, except go through the whole request cycle
    • eio_npending - Returns number of finished, but unhandled requests
    • eio_nready - Returns number of not-yet handled requests
    • eio_nreqs - Returns number of requests to be processed
    • eio_nthreads - Returns number of threads currently in use
    • eio_open - Opens a file
    • eio_poll - Can be to be called whenever there are pending requests that need finishing
    • eio_read - Read from a file descriptor at given offset
    • eio_readahead - Perform file readahead into page cache
    • eio_readdir - Reads through a whole directory
    • eio_readlink - Read value of a symbolic link
    • eio_realpath - Get the canonicalized absolute pathname
    • eio_rename - Change the name or location of a file
    • eio_rmdir - Remove a directory
    • eio_seek - Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
    • eio_sendfile - Transfer data between file descriptors
    • eio_set_max_idle - Set maximum number of idle threads
    • eio_set_max_parallel - Set maximum parallel threads
    • eio_set_max_poll_reqs - Set maximum number of requests processed in a poll
    • eio_set_max_poll_time - Set maximum poll time
    • eio_set_min_parallel - Set minimum parallel thread number
    • eio_stat - Get file status
    • eio_statvfs - Get file system statistics
    • eio_symlink - Create a symbolic link
    • eio_sync - Commit buffer cache to disk
    • eio_syncfs - Calls Linux' syncfs syscall, if available
    • eio_sync_file_range - Sync a file segment with disk
    • eio_truncate - Truncate a file
    • eio_unlink - Delete a name and possibly the file it refers to
    • eio_utime - Change file last access and modification times
    • eio_write - Write to file
    • empty - Determina se uma variável está vazia
    • EmptyIterator::current - The current() method
    • EmptyIterator::key - The key() method
    • EmptyIterator::next - The next() method
    • EmptyIterator::rewind - The rewind() method
    • EmptyIterator::valid - The valid() method
    • enchant_broker_describe - Enumerates the Enchant providers
    • enchant_broker_dict_exists - Whether a dictionary exists or not. Using non-empty tag
    • enchant_broker_free - Free the broker resource and its dictionaries
    • enchant_broker_free_dict - Free a dictionary resource
    • enchant_broker_get_dict_path - Get the directory path for a given backend
    • enchant_broker_get_error - Returns the last error of the broker
    • enchant_broker_init - Create a new broker object capable of requesting
    • enchant_broker_list_dicts - Returns a list of available dictionaries
    • enchant_broker_request_dict - Create a new dictionary using a tag
    • enchant_broker_request_pwl_dict - Creates a dictionary using a PWL file
    • enchant_broker_set_dict_path - Set the directory path for a given backend
    • enchant_broker_set_ordering - Declares a preference of dictionaries to use for the language
    • enchant_dict_add - Add a word to personal word list
    • enchant_dict_add_to_personal - Sinônimo de enchant_dict_add
    • enchant_dict_add_to_session - Add 'word' to this spell-checking session
    • enchant_dict_check - Check whether a word is correctly spelled or not
    • enchant_dict_describe - Describes an individual dictionary
    • enchant_dict_get_error - Returns the last error of the current spelling-session
    • enchant_dict_is_added - Whether or not 'word' exists in this spelling-session
    • enchant_dict_is_in_session - Sinônimo de enchant_dict_is_added
    • enchant_dict_quick_check - Check the word is correctly spelled and provide suggestions
    • enchant_dict_store_replacement - Add a correction for a word
    • enchant_dict_suggest - Will return a list of values if any of those pre-conditions are not met
    • end - Define o ponteiro interno de um array para seu último elemento
    • enum_exists - Verifica se uma enumeração foi definida
    • Error::getCode - Recupera o código do erro
    • Error::getFile - Recupera o nome do arquivo onde o erro ocorreu
    • Error::getLine - Recupera a linha onde o erro ocorreu
    • Error::getMessage - Recupera a mensagem de erro
    • Error::getPrevious - Retorna o último Throwable
    • Error::getTrace - Recupera a pilha de rastreio
    • Error::getTraceAsString - Recupera a pilha de rastreio como uma string
    • Error::__clone - Clona o erro
    • Error::__construct - Constrói o objeto error
    • Error::__toString - Representação em string do erro
    • ErrorException::getSeverity - Obtém o nível da exceção
    • ErrorException::__construct - Constrói a exceção
    • error_clear_last - Clear the most recent error
    • error_get_last - Obtém o último erro ocorrido
    • error_log - Envia uma mensagem de erro para as rotinas de tratamento de erros definidas
    • error_reporting - Define quais erros do PHP são relatados
    • escapeshellarg - Escapa uma string para ser usada como um argumento shell
    • escapeshellcmd - Escapa metacaracteres shell
    • Ev::backend - Returns an integer describing the backend used by libev
    • Ev::depth - Returns recursion depth
    • Ev::embeddableBackends - Returns the set of backends that are embeddable in other event loops
    • Ev::feedSignal - Feed a signal event info Ev
    • Ev::feedSignalEvent - Feed signal event into the default loop
    • Ev::iteration - Return the number of times the default event loop has polled for new events
    • Ev::now - Returns the time when the last iteration of the default event loop has started
    • Ev::nowUpdate - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress
    • Ev::recommendedBackends - Returns a bit mask of recommended backends for current platform
    • Ev::resume - Resume previously suspended default event loop
    • Ev::run - Begin checking for events and calling callbacks for the default loop
    • Ev::sleep - Block the process for the given number of seconds
    • Ev::stop - Stops the default event loop
    • Ev::supportedBackends - Returns the set of backends supported by current libev configuration
    • Ev::suspend - Suspend the default event loop
    • Ev::time - Returns the current time in fractional seconds since the epoch
    • Ev::verify - Performs internal consistency checks(for debugging)
    • eval - Evaluate a string as PHP code
    • EvCheck::createStopped - Create instance of a stopped EvCheck watcher
    • EvCheck::__construct - Constructs the EvCheck watcher object
    • EvChild::createStopped - Create instance of a stopped EvCheck watcher
    • EvChild::set - Configures the watcher
    • EvChild::__construct - Constructs the EvChild watcher object
    • EvEmbed::createStopped - Create stopped EvEmbed watcher object
    • EvEmbed::set - Configures the watcher
    • EvEmbed::sweep - Make a single, non-blocking sweep over the embedded loop
    • EvEmbed::__construct - Constructs the EvEmbed object
    • Event::add - Makes event pending
    • Event::addSignal - Sinônimo de Event::add
    • Event::addTimer - Sinônimo de Event::add
    • Event::del - Makes event non-pending
    • Event::delSignal - Sinônimo de Event::del
    • Event::delTimer - Sinônimo 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 - Dispatch pending events
    • EventBase::exit - Stop dispatching events
    • EventBase::free - Free resources allocated for this event base
    • EventBase::getFeatures - Returns bitmask of features supported
    • EventBase::getMethod - Returns event method in use
    • EventBase::getTimeOfDayCached - Returns the current event base time
    • EventBase::gotExit - Checks if the event loop was told to exit
    • EventBase::gotStop - Checks if the event loop was told to exit
    • EventBase::loop - Dispatch pending events
    • EventBase::priorityInit - Sets number of priorities per event base
    • EventBase::reInit - Re-initialize event base(after a fork)
    • EventBase::stop - Tells event_base to stop dispatching events
    • EventBase::__construct - Constructs EventBase object
    • EventBuffer::add - Append data to the end of an event buffer
    • EventBuffer::addBuffer - Move all data from a buffer provided to the current instance of EventBuffer
    • EventBuffer::appendFrom - Moves the specified number of bytes from a source buffer to the end of the current buffer
    • EventBuffer::copyout - Copies out specified number of bytes from the front of the buffer
    • EventBuffer::drain - Removes specified number of bytes from the front of the buffer without copying it anywhere
    • EventBuffer::enableLocking - Descrição
    • EventBuffer::expand - Reserves space in buffer
    • EventBuffer::freeze - Prevent calls that modify an event buffer from succeeding
    • EventBuffer::lock - Acquires a lock on buffer
    • EventBuffer::prepend - Prepend data to the front of the buffer
    • EventBuffer::prependBuffer - Moves all data from source buffer to the front of current buffer
    • EventBuffer::pullup - Linearizes data within buffer and returns it's contents as a string
    • EventBuffer::read - Read data from an evbuffer and drain the bytes read
    • EventBuffer::readFrom - Read data from a file onto the end of the buffer
    • EventBuffer::readLine - Extracts a line from the front of the buffer
    • EventBuffer::search - Scans the buffer for an occurrence of a string
    • EventBuffer::searchEol - Scans the buffer for an occurrence of an end of line
    • EventBuffer::substr - Substracts a portion of the buffer data
    • EventBuffer::unfreeze - Re-enable calls that modify an event buffer
    • EventBuffer::unlock - Releases lock acquired by EventBuffer::lock
    • EventBuffer::write - Write contents of the buffer to a file or socket
    • EventBuffer::__construct - Constructs EventBuffer object
    • EventBufferEvent::close - Closes file descriptor associated with the current buffer event
    • EventBufferEvent::connect - Connect buffer event's file descriptor to given address or UNIX socket
    • EventBufferEvent::connectHost - Connects to a hostname with optionally asyncronous DNS resolving
    • EventBufferEvent::createPair - Creates two buffer events connected to each other
    • EventBufferEvent::disable - Disable events read, write, or both on a buffer event
    • EventBufferEvent::enable - Enable events read, write, or both on a buffer event
    • EventBufferEvent::free - Free a buffer event
    • EventBufferEvent::getDnsErrorString - Returns string describing the last failed DNS lookup attempt
    • EventBufferEvent::getEnabled - Returns bitmask of events currently enabled on the buffer event
    • EventBufferEvent::getInput - Returns underlying input buffer associated with current buffer event
    • EventBufferEvent::getOutput - Returns underlying output buffer associated with current buffer event
    • EventBufferEvent::read - Read buffer's data
    • EventBufferEvent::readBuffer - Drains the entire contents of the input buffer and places them into buf
    • EventBufferEvent::setCallbacks - Assigns read, write and event(status) callbacks
    • EventBufferEvent::setPriority - Assign a priority to a bufferevent
    • EventBufferEvent::setTimeouts - Set the read and write timeout for a buffer event
    • EventBufferEvent::setWatermark - Adjusts read and/or write watermarks
    • EventBufferEvent::sslError - Returns most recent OpenSSL error reported on the buffer event
    • EventBufferEvent::sslFilter - Create a new SSL buffer event to send its data over another buffer event
    • EventBufferEvent::sslGetCipherInfo - Returns a textual description of the cipher
    • EventBufferEvent::sslGetCipherName - Returns the current cipher name of the SSL connection
    • EventBufferEvent::sslGetCipherVersion - Returns version of cipher used by current SSL connection
    • EventBufferEvent::sslGetProtocol - Returns the name of the protocol used for current SSL connection
    • EventBufferEvent::sslRenegotiate - Tells a bufferevent to begin SSL renegotiation
    • EventBufferEvent::sslSocket - Creates a new SSL buffer event to send its data over an SSL on a socket
    • EventBufferEvent::write - Adds data to a buffer event's output buffer
    • EventBufferEvent::writeBuffer - Adds contents of the entire buffer to a buffer event's output buffer
    • EventBufferEvent::__construct - Constructs EventBufferEvent object
    • EventConfig::avoidMethod - Tells libevent to avoid specific event method
    • EventConfig::requireFeatures - Enters a required event method feature that the application demands
    • EventConfig::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 - Creates a stopped instance of EvPrepare watcher
    • EvPrepare::__construct - Constructs EvPrepare watcher object
    • EvSignal::createStopped - Create stopped EvSignal watcher object
    • EvSignal::set - Configures the watcher
    • EvSignal::__construct - Constructs EvSignal watcher object
    • EvStat::attr - Returns the values most recently detected by Ev
    • EvStat::createStopped - Create a stopped EvStat watcher object
    • EvStat::prev - Returns the previous set of values returned by EvStat::attr
    • EvStat::set - Configures the watcher
    • EvStat::stat - Initiates the stat call
    • EvStat::__construct - Constructs EvStat watcher object
    • EvTimer::again - Restarts the timer watcher
    • EvTimer::createStopped - Creates EvTimer stopped watcher object
    • EvTimer::set - Configures the watcher
    • EvTimer::__construct - Constructs an EvTimer watcher object
    • EvWatcher::clear - Clear watcher pending status
    • EvWatcher::feed - Feeds the given revents set into the event loop
    • EvWatcher::getLoop - Returns the loop responsible for the watcher
    • EvWatcher::invoke - Invokes the watcher callback with the given received events bit mask
    • EvWatcher::keepalive - Configures whether to keep the loop from returning
    • EvWatcher::setCallback - Sets new callback for the watcher
    • EvWatcher::start - Starts the watcher
    • EvWatcher::stop - Stops the watcher
    • EvWatcher::__construct - Abstract constructor of a watcher object
    • Exception::getCode - Obtém o código da exceção
    • Exception::getFile - Obtém o arquivo no qual a exceção foi criada
    • Exception::getLine - Obtém a linha na qual a exceção foi criada
    • Exception::getMessage - Obtém a mensagem da exceção
    • Exception::getPrevious - Retorna o Throwable anterior
    • Exception::getTrace - Obtém a stack trace
    • Exception::getTraceAsString - Obtém a stack trace como uma string
    • Exception::__clone - Clona a exceção
    • Exception::__construct - Construtor da exceção
    • Exception::__toString - Representação em string da exceção
    • exec - Executa um programa externo
    • Executable::execute - Execute statement
    • ExecutionStatus::__construct - ExecutionStatus constructor
    • exif_imagetype - Verifica o tipo de uma imagem
    • exif_read_data - Lê os cabeçalhos EXIF de um arquivo de imagen
    • exif_tagname - Obtém o nome do cabeçalho para um índice
    • exif_thumbnail - Recupera a miniatura embutida de uma imagem
    • exit - Output a message and terminate the current script
    • exp - Calcula o expoente de e
    • expect:// - Fluxos de Interação entre Processos
    • expect_expectl - Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
    • expect_popen - Execute command via Bourne shell, and open the PTY stream to the process
    • explode - Split a string by a string
    • expm1 - Retorna exp($num) - 1, computado de forma precisa mesmo quando o valor do número está próximo de zero.
    • expression - Bind prepared statement variables as parameters
    • Expression::__construct - Expression constructor
    • extension_loaded - Descobre se uma extensão está carregada
    • extract - Importa variáveis para a tabela de símbolos a partir de um array
    • ezmlm_hash - Calcula o valor do hash necessário para EZMLM
  • f
    • FANNConnection::getFromNeuron - Returns the postions of starting neuron
    • FANNConnection::getToNeuron - Returns the postions of terminating neuron
    • FANNConnection::getWeight - Returns the connection weight
    • FANNConnection::setWeight - Sets the connections weight
    • FANNConnection::__construct - The connection constructor
    • fann_cascadetrain_on_data - Trains on an entire dataset, for a period of time using the Cascade2 training algorithm
    • fann_cascadetrain_on_file - Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm
    • fann_clear_scaling_params - Clears scaling parameters
    • fann_copy - Creates a copy of a fann structure
    • fann_create_from_file - Constructs a backpropagation neural network from a configuration file
    • fann_create_shortcut - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_shortcut_array - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_sparse - Creates a standard backpropagation neural network, which is not fully connected
    • fann_create_sparse_array - Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
    • fann_create_standard - Creates a standard fully connected backpropagation neural network
    • fann_create_standard_array - Creates a standard fully connected backpropagation neural network using an array of layer sizes
    • fann_create_train - Creates an empty training data struct
    • fann_create_train_from_callback - Creates the training data struct from a user supplied function
    • fann_descale_input - Scale data in input vector after get it from ann based on previously calculated parameters
    • fann_descale_output - Scale data in output vector after get it from ann based on previously calculated parameters
    • fann_descale_train - Descale input and output data based on previously calculated parameters
    • fann_destroy - Destroys the entire network and properly freeing all the associated memory
    • fann_destroy_train - Destructs the training data
    • fann_duplicate_train_data - Returns an exact copy of a fann train data
    • fann_get_activation_function - Returns the activation function
    • fann_get_activation_steepness - Returns the activation steepness for supplied neuron and layer number
    • fann_get_bias_array - Get the number of bias in each layer in the network
    • fann_get_bit_fail - The number of fail bits
    • fann_get_bit_fail_limit - Returns the bit fail limit used during training
    • fann_get_cascade_activation_functions - Returns the cascade activation functions
    • fann_get_cascade_activation_functions_count - Returns the number of cascade activation functions
    • fann_get_cascade_activation_steepnesses - Returns the cascade activation steepnesses
    • fann_get_cascade_activation_steepnesses_count - The number of activation steepnesses
    • fann_get_cascade_candidate_change_fraction - Returns the cascade candidate change fraction
    • fann_get_cascade_candidate_limit - Return the candidate limit
    • fann_get_cascade_candidate_stagnation_epochs - Returns the number of cascade candidate stagnation epochs
    • fann_get_cascade_max_cand_epochs - Returns the maximum candidate epochs
    • fann_get_cascade_max_out_epochs - Returns the maximum out epochs
    • fann_get_cascade_min_cand_epochs - Returns the minimum candidate epochs
    • fann_get_cascade_min_out_epochs - Returns the minimum out epochs
    • fann_get_cascade_num_candidates - Returns the number of candidates used during training
    • fann_get_cascade_num_candidate_groups - Returns the number of candidate groups
    • fann_get_cascade_output_change_fraction - Returns the cascade output change fraction
    • fann_get_cascade_output_stagnation_epochs - Returns the number of cascade output stagnation epochs
    • fann_get_cascade_weight_multiplier - Returns the weight multiplier
    • fann_get_connection_array - Get connections in the network
    • fann_get_connection_rate - Get the connection rate used when the network was created
    • fann_get_errno - Returns the last error number
    • fann_get_errstr - Returns the last errstr
    • fann_get_layer_array - Get the number of neurons in each layer in the network
    • fann_get_learning_momentum - Returns the learning momentum
    • fann_get_learning_rate - Returns the learning rate
    • fann_get_MSE - Reads the mean square error from the network
    • fann_get_network_type - Get the type of neural network it was created as
    • fann_get_num_input - Get the number of input neurons
    • fann_get_num_layers - Get the number of layers in the neural network
    • fann_get_num_output - Get the number of output neurons
    • fann_get_quickprop_decay - Returns the decay which is a factor that weights should decrease in each iteration during quickprop training
    • fann_get_quickprop_mu - Returns the mu factor
    • fann_get_rprop_decrease_factor - Returns the increase factor used during RPROP training
    • fann_get_rprop_delta_max - Returns the maximum step-size
    • fann_get_rprop_delta_min - Returns the minimum step-size
    • fann_get_rprop_delta_zero - Returns the initial step-size
    • fann_get_rprop_increase_factor - Returns the increase factor used during RPROP training
    • fann_get_sarprop_step_error_shift - Returns the sarprop step error shift
    • fann_get_sarprop_step_error_threshold_factor - Returns the sarprop step error threshold factor
    • fann_get_sarprop_temperature - Returns the sarprop temperature
    • fann_get_sarprop_weight_decay_shift - Returns the sarprop weight decay shift
    • fann_get_total_connections - Get the total number of connections in the entire network
    • fann_get_total_neurons - Get the total number of neurons in the entire network
    • fann_get_training_algorithm - Returns the training algorithm
    • fann_get_train_error_function - Returns the error function used during training
    • fann_get_train_stop_function - Returns the stop function used during training
    • fann_init_weights - Initialize the weights using Widrow + Nguyen’s algorithm
    • fann_length_train_data - Returns the number of training patterns in the train data
    • fann_merge_train_data - Merges the train data
    • fann_num_input_train_data - Returns the number of inputs in each of the training patterns in the train data
    • fann_num_output_train_data - Returns the number of outputs in each of the training patterns in the train data
    • fann_print_error - Prints the error string
    • fann_randomize_weights - Give each connection a random weight between min_weight and max_weight
    • fann_read_train_from_file - Reads a file that stores training data
    • fann_reset_errno - Resets the last error number
    • fann_reset_errstr - Resets the last error string
    • fann_reset_MSE - Resets the mean square error from the network
    • fann_run - Will run input through the neural network
    • fann_save - Saves the entire network to a configuration file
    • fann_save_train - Save the training structure to a file
    • fann_scale_input - Scale data in input vector before feed it to ann based on previously calculated parameters
    • fann_scale_input_train_data - Scales the inputs in the training data to the specified range
    • fann_scale_output - Scale data in output vector before feed it to ann based on previously calculated parameters
    • fann_scale_output_train_data - Scales the outputs in the training data to the specified range
    • fann_scale_train - Scale input and output data based on previously calculated parameters
    • fann_scale_train_data - Scales the inputs and outputs in the training data to the specified range
    • fann_set_activation_function - Sets the activation function for supplied neuron and layer
    • fann_set_activation_function_hidden - Sets the activation function for all of the hidden layers
    • fann_set_activation_function_layer - Sets the activation function for all the neurons in the supplied layer
    • fann_set_activation_function_output - Sets the activation function for the output layer
    • fann_set_activation_steepness - Sets the activation steepness for supplied neuron and layer number
    • fann_set_activation_steepness_hidden - Sets the steepness of the activation steepness for all neurons in the all hidden layers
    • fann_set_activation_steepness_layer - Sets the activation steepness for all of the neurons in the supplied layer number
    • fann_set_activation_steepness_output - Sets the steepness of the activation steepness in the output layer
    • fann_set_bit_fail_limit - Set the bit fail limit used during training
    • fann_set_callback - Sets the callback function for use during training
    • fann_set_cascade_activation_functions - Sets the array of cascade candidate activation functions
    • fann_set_cascade_activation_steepnesses - Sets the array of cascade candidate activation steepnesses
    • fann_set_cascade_candidate_change_fraction - Sets the cascade candidate change fraction
    • fann_set_cascade_candidate_limit - Sets the candidate limit
    • fann_set_cascade_candidate_stagnation_epochs - Sets the number of cascade candidate stagnation epochs
    • fann_set_cascade_max_cand_epochs - Sets the max candidate epochs
    • fann_set_cascade_max_out_epochs - Sets the maximum out epochs
    • fann_set_cascade_min_cand_epochs - Sets the min candidate epochs
    • fann_set_cascade_min_out_epochs - Sets the minimum out epochs
    • fann_set_cascade_num_candidate_groups - Sets the number of candidate groups
    • fann_set_cascade_output_change_fraction - Sets the cascade output change fraction
    • fann_set_cascade_output_stagnation_epochs - Sets the number of cascade output stagnation epochs
    • fann_set_cascade_weight_multiplier - Sets the weight multiplier
    • fann_set_error_log - Sets where the errors are logged to
    • fann_set_input_scaling_params - Calculate input scaling parameters for future use based on training data
    • fann_set_learning_momentum - Sets the learning momentum
    • fann_set_learning_rate - Sets the learning rate
    • fann_set_output_scaling_params - Calculate output scaling parameters for future use based on training data
    • fann_set_quickprop_decay - Sets the quickprop decay factor
    • fann_set_quickprop_mu - Sets the quickprop mu factor
    • fann_set_rprop_decrease_factor - Sets the decrease factor used during RPROP training
    • fann_set_rprop_delta_max - Sets the maximum step-size
    • fann_set_rprop_delta_min - Sets the minimum step-size
    • fann_set_rprop_delta_zero - Sets the initial step-size
    • fann_set_rprop_increase_factor - Sets the increase factor used during RPROP training
    • fann_set_sarprop_step_error_shift - Sets the sarprop step error shift
    • fann_set_sarprop_step_error_threshold_factor - Sets the sarprop step error threshold factor
    • fann_set_sarprop_temperature - Sets the sarprop temperature
    • fann_set_sarprop_weight_decay_shift - Sets the sarprop weight decay shift
    • fann_set_scaling_params - Calculate input and output scaling parameters for future use based on training data
    • fann_set_training_algorithm - Sets the training algorithm
    • fann_set_train_error_function - Sets the error function used during training
    • fann_set_train_stop_function - Sets the stop function used during training
    • fann_set_weight - Set a connection in the network
    • fann_set_weight_array - Set connections in the network
    • fann_shuffle_train_data - Shuffles training data, randomizing the order
    • fann_subset_train_data - Returns an copy of a subset of the train data
    • fann_test - Test with a set of inputs, and a set of desired outputs
    • fann_test_data - Test a set of training data and calculates the MSE for the training data
    • fann_train - Train one iteration with a set of inputs, and a set of desired outputs
    • fann_train_epoch - Train one epoch with a set of training data
    • fann_train_on_data - Trains on an entire dataset for a period of time
    • fann_train_on_file - Trains on an entire dataset, which is read from file, for a period of time
    • fastcgi_finish_request - Envia todos os dados de resposta ao cliente
    • fbird_add_user - Sinônimo de ibase_add_user
    • fbird_affected_rows - Sinônimo de ibase_affected_rows
    • fbird_backup - Sinônimo de ibase_backup
    • fbird_blob_add - Sinônimo de ibase_blob_add
    • fbird_blob_cancel - Cancel creating blob
    • fbird_blob_close - Sinônimo de ibase_blob_close
    • fbird_blob_create - Sinônimo de ibase_blob_create
    • fbird_blob_echo - Sinônimo de ibase_blob_echo
    • fbird_blob_get - Sinônimo de ibase_blob_get
    • fbird_blob_import - Sinônimo de ibase_blob_import
    • fbird_blob_info - Sinônimo de ibase_blob_info
    • fbird_blob_open - Sinônimo de ibase_blob_open
    • fbird_close - Sinônimo de ibase_close
    • fbird_commit - Sinônimo de ibase_commit
    • fbird_commit_ret - Sinônimo de ibase_commit_ret
    • fbird_connect - Sinônimo de ibase_connect
    • fbird_db_info - Sinônimo de ibase_db_info
    • fbird_delete_user - Sinônimo de ibase_delete_user
    • fbird_drop_db - Sinônimo de ibase_drop_db
    • fbird_errcode - Sinônimo de ibase_errcode
    • fbird_errmsg - Sinônimo de ibase_errmsg
    • fbird_execute - Sinônimo de ibase_execute
    • fbird_fetch_assoc - Sinônimo de ibase_fetch_assoc
    • fbird_fetch_object - Sinônimo de ibase_fetch_object
    • fbird_fetch_row - Sinônimo de ibase_fetch_row
    • fbird_field_info - Sinônimo de ibase_field_info
    • fbird_free_event_handler - Sinônimo de ibase_free_event_handler
    • fbird_free_query - Sinônimo de ibase_free_query
    • fbird_free_result - Sinônimo de ibase_free_result
    • fbird_gen_id - Sinônimo de ibase_gen_id
    • fbird_maintain_db - Sinônimo de ibase_maintain_db
    • fbird_modify_user - Sinônimo de ibase_modify_user
    • fbird_name_result - Sinônimo de ibase_name_result
    • fbird_num_fields - Sinônimo de ibase_num_fields
    • fbird_num_params - Sinônimo de ibase_num_params
    • fbird_param_info - Sinônimo de ibase_param_info
    • fbird_pconnect - Sinônimo de ibase_pconnect
    • fbird_prepare - Sinônimo de ibase_prepare
    • fbird_query - Sinônimo de ibase_query
    • fbird_restore - Sinônimo de ibase_restore
    • fbird_rollback - Sinônimo de ibase_rollback
    • fbird_rollback_ret - Sinônimo de ibase_rollback_ret
    • fbird_server_info - Sinônimo de ibase_server_info
    • fbird_service_attach - Sinônimo de ibase_service_attach
    • fbird_service_detach - Sinônimo de ibase_service_detach
    • fbird_set_event_handler - Sinônimo de ibase_set_event_handler
    • fbird_trans - Sinônimo de ibase_trans
    • fbird_wait_event - Sinônimo de ibase_wait_event
    • fclose - Fecha um ponteiro de arquivo aberto
    • fdatasync - Sincroniza dados (mas não metadados) ao arquivo
    • fdf_add_doc_javascript - Adds javascript code to the FDF document
    • fdf_add_template - Adds a template into the FDF document
    • fdf_close - Close an FDF document
    • fdf_create - Create a new FDF document
    • fdf_enum_values - Call a user defined function for each document value
    • fdf_errno - Return error code for last fdf operation
    • fdf_error - Return error description for FDF error code
    • fdf_get_ap - Get the appearance of a field
    • fdf_get_attachment - Extracts uploaded file embedded in the FDF
    • fdf_get_encoding - Get the value of the /Encoding key
    • fdf_get_file - Get the value of the /F key
    • fdf_get_flags - Gets the flags of a field
    • fdf_get_opt - Gets a value from the opt array of a field
    • fdf_get_status - Get the value of the /STATUS key
    • fdf_get_value - Get the value of a field
    • fdf_get_version - Gets version number for FDF API or file
    • fdf_header - Sets FDF-specific output headers
    • fdf_next_field_name - Get the next field name
    • fdf_open - Open a FDF document
    • fdf_open_string - Read a FDF document from a string
    • fdf_remove_item - Sets target frame for form
    • fdf_save - Save a FDF document
    • fdf_save_string - Returns the FDF document as a string
    • fdf_set_ap - Set the appearance of a field
    • fdf_set_encoding - Sets FDF character encoding
    • fdf_set_file - Set PDF document to display FDF data in
    • fdf_set_flags - Sets a flag of a field
    • fdf_set_javascript_action - Sets an javascript action of a field
    • fdf_set_on_import_javascript - Adds javascript code to be executed when Acrobat opens the FDF
    • fdf_set_opt - Sets an option of a field
    • fdf_set_status - Set the value of the /STATUS key
    • fdf_set_submit_form_action - Sets a submit form action of a field
    • fdf_set_target_frame - Set target frame for form display
    • fdf_set_value - Set the value of a field
    • fdf_set_version - Sets version number for a FDF file
    • fdiv - Divide dois números de acordo com a IEEE 754
    • feof - Testa pelo fim-de-arquivo em um ponteiro de arquivo
    • 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 - Força a liberação do buffer para um arquivo
    • fgetc - Lê um caractere do ponteiro de arquivo
    • fgetcsv - Lê uma linha do ponteiro de arquivos e a interpreta como campos CSV
    • fgets - Lê uma linha de um ponteiro de arquivo
    • fgetss - Ler uma linha de um ponteiro de arquivo e retira as tags HTML
    • Fiber::getCurrent - Obtém a instância de Fiber sendo executada no momento
    • Fiber::getReturn - Obtém o valor retornado pela Fiber
    • Fiber::isRunning - Determina se a Fiber está em execução
    • Fiber::isStarted - Determina se uma Fiber foi iniciada
    • Fiber::isSuspended - Determina se uma Fiber está suspensa
    • Fiber::isTerminated - Determina se a Fiber terminou
    • Fiber::resume - Retoma a execução de uma Fiber com um valor
    • Fiber::start - Inicia execução de uma Fibra
    • Fiber::suspend - Suspende a execução da Fiber atual
    • Fiber::throw - Retoma a execução de uma Fiber com uma exceção
    • Fiber::__construct - Cria uma nova instância de Fiber
    • FiberError::__construct - Construtor para não permitir instanciação direta
    • file - Lê todo o arquivo para um array
    • file:// - Acessando o sistema de arquivos local
    • fileatime - Obtém o último horário de acesso do arquivo
    • filectime - Obtém o horário de modificação de inode do arquivo
    • filegroup - Lê o grupo do arquivo
    • fileinode - Lê o inode do arquivo
    • filemtime - Obtém o horário de modificação do arquivo
    • fileowner - Obtem o proprietário do arquivo
    • fileperms - Obtém permissões de arquivo
    • filesize - Obtém o tamanho do arquivo
    • FilesystemIterator::current - The current file
    • FilesystemIterator::getFlags - Get the handling flags
    • FilesystemIterator::key - Retrieve the key for the current file
    • FilesystemIterator::next - Move to the next file
    • FilesystemIterator::rewind - Rewinds back to the beginning
    • FilesystemIterator::setFlags - Sets handling flags
    • FilesystemIterator::__construct - Constructs a new filesystem iterator
    • filetype - Lê o tipo do arquivo
    • file_exists - Verifica se um arquivo ou diretório existe
    • file_get_contents - Lê todo o conteúdo de um arquivo para uma string
    • file_put_contents - Escreve dados em um arquivo
    • FilterIterator::accept - Check whether the current element of the iterator is acceptable
    • FilterIterator::current - Retorna o valor do elemento atual
    • FilterIterator::key - Retorna a chave do elemento atual
    • FilterIterator::next - Avança o iterador
    • FilterIterator::rewind - Recomeça o iterador
    • FilterIterator::valid - Verifica se o elemento atual é válido ou não
    • FilterIterator::__construct - Construct a filterIterator
    • filter_has_var - Verifica se uma variável de um especificado tipo existe
    • filter_id - Retorna o ID de filtro pertencente a um filtro nomeado
    • filter_input - Gets a specific external variable by name and optionally filters it
    • filter_input_array - Obtem variáveis externas e opcionalmente as filtra
    • filter_list - Retorna a lista de todos os filtros suportados
    • filter_var - Filters a variable with a specified filter
    • filter_var_array - Obtêm múltiplas variáveis e opcionalmente as filtra
    • finfo::buffer - Sinônimo de finfo_buffer()
    • finfo::file - Sinônimo de finfo_file()
    • finfo::set_flags - Sinônimo de finfo_set_flags()
    • finfo::__construct - Sinônimo de finfo_open
    • finfo_close - Fecha uma instância de finfo
    • finfo_open - Cria uma instância de finfo
    • floatval - Obtém o valor em ponto flutuante da variável
    • flock - Travamento consultivo portável de arquivo
    • floor - Arredonda frações para baixo
    • flush - Flush system output buffer
    • fmod - Retorna o resto (módulo) em ponto flutuante da divisão dos argumentos
    • fnmatch - Compara nome de arquivo com um padrão
    • fopen - Abre um arquivo ou URL
    • forward_static_call - Call a static method
    • forward_static_call_array - Call a static method and pass the arguments as array
    • fpassthru - Imprime todo os dados restantes de um ponteiro de arquivo
    • fpm_get_status - Returns the current FPM pool status
    • fprintf - Escreve uma string formatada para um fluxo
    • fputcsv - Formata a linha como CSV e a escreve em um ponteiro de arquivo
    • fputs - Sinônimo de fwrite
    • fread - Leitura de arquivo segura para binário
    • frenchtojd - Converts a date from the French Republican Calendar to a Julian Day Count
    • fscanf - Interpreta a leitura de um arquivo de acordo com um formato
    • fseek - Procura (seeks) em um ponteiro de arquivo
    • fsockopen - Abre uma conexão socket de domínio Unix ou Internet
    • fstat - Lê informações sobre um arquivo usando um ponteiro de arquivo aberto
    • fsync - Sincroniza mudanças ao arquivo (incluindo metadados)
    • ftell - Retorna a posição atual do ponteiro de leitura/gravação do arquivo
    • ftok - Convert a pathname and a project identifier to a System V IPC key
    • ftp:// - Acessando URLs FTP(s)
    • ftp_alloc - Allocates space for a file to be uploaded
    • ftp_append - Append the contents of a file to another file on the FTP server
    • ftp_cdup - Muda para o diretório acima
    • ftp_chdir - Muda o diretório atual em um servidor FTP
    • ftp_chmod - Define as permissões de um arquivo via FTP
    • ftp_close - Fecha uma conexão FTP
    • ftp_connect - Opens an FTP connection
    • ftp_delete - Exclui um arquivo no servidor FTP
    • ftp_exec - Solicita a execução de um comando no servidor FTP
    • ftp_fget - Downloads a file from the FTP server and saves to an open file
    • ftp_fput - Uploads from an open file to the FTP server
    • ftp_get - Downloads a file from the FTP server
    • ftp_get_option - Obtém várias opções em tempo de execução da conexão FTP atual
    • ftp_login - Realiza o login em uma conexão FTP
    • ftp_mdtm - Retorna o horário da última modificação do arquivo informado
    • ftp_mkdir - Cria um diretório
    • ftp_mlsd - Returns a list of files in the given directory
    • ftp_nb_continue - Continua a receber/enviar um arquivo (sem bloquear)
    • ftp_nb_fget - Retrieves a file from the FTP server and writes it to an open file (non-blocking)
    • ftp_nb_fput - Stores a file from an open file to the FTP server (non-blocking)
    • ftp_nb_get - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
    • ftp_nb_put - Stores a file on the FTP server (non-blocking)
    • ftp_nlist - Retorna uma lista de arquivos em um diretório
    • ftp_pasv - Liga ou desliga o modo passivo
    • ftp_put - Uploads a file to the FTP server
    • ftp_pwd - Retorna o nome do diretório atual
    • ftp_quit - Sinônimo de ftp_close
    • ftp_raw - Envia um comando arbritário a um servidor FTP
    • ftp_rawlist - Returns a detailed list of files in the given directory
    • ftp_rename - Renomeia um arquivo ou um diretório no servidor FTP
    • ftp_rmdir - Remove um diretório
    • ftp_set_option - Define opções diversas em tempo de execução
    • ftp_site - Sends a SITE command to the server
    • ftp_size - Retorna o tamanho do arquivo especificado
    • ftp_ssl_connect - Opens a Secure SSL-FTP connection
    • ftp_systype - Retorna o identificador de tipo de sistema do servidor FTP remoto
    • ftruncate - Trunca um arquivo a um tamanho especificado
    • function_exists - Retorna true se a função informada estiver definida
    • func_get_arg - Retorna um item de uma lista de argumentos
    • func_get_args - Returns an array comprising a function's argument list
    • func_num_args - Returns the number of arguments passed to the function
    • fwrite - Escrita binary-safe em arquivos
  • g
    • gc_collect_cycles - Forces collection of any existing garbage cycles
    • gc_disable - Deactivates the circular reference collector
    • gc_enable - Activates the circular reference collector
    • gc_enabled - Returns status of the circular reference collector
    • gc_mem_caches - Reclaims memory used by the Zend Engine memory manager
    • gc_status - Gets information about the garbage collector
    • gd_info - Obtém informações sobre a biblioteca GD instalada atualmente
    • GearmanClient::addOptions - Add client options
    • GearmanClient::addServer - Add a job server to the client
    • GearmanClient::addServers - Add a list of job servers to the client
    • GearmanClient::addTask - Add a task to be run in parallel
    • GearmanClient::addTaskBackground - Add a background task to be run in parallel
    • GearmanClient::addTaskHigh - Add a high priority task to run in parallel
    • GearmanClient::addTaskHighBackground - Add a high priority background task to be run in parallel
    • GearmanClient::addTaskLow - Add a low priority task to run in parallel
    • GearmanClient::addTaskLowBackground - Add a low priority background task to be run in parallel
    • GearmanClient::addTaskStatus - Add a task to get status
    • GearmanClient::clearCallbacks - Clear all task callback functions
    • GearmanClient::clone - Create a copy of a GearmanClient object
    • GearmanClient::context - Get the application context
    • GearmanClient::data - Get the application data (deprecated)
    • GearmanClient::do - Run a single task and return a result [deprecated]
    • GearmanClient::doBackground - Run a task in the background
    • GearmanClient::doHigh - Run a single high priority task
    • GearmanClient::doHighBackground - Run a high priority task in the background
    • GearmanClient::doJobHandle - Get the job handle for the running task
    • GearmanClient::doLow - Run a single low priority task
    • GearmanClient::doLowBackground - Run a low priority task in the background
    • GearmanClient::doNormal - Run a single task and return a result
    • GearmanClient::doStatus - Get the status for the running task
    • GearmanClient::echo - Send data to all job servers to see if they echo it back [deprecated]
    • GearmanClient::error - Returns an error string for the last error encountered
    • GearmanClient::getErrno - Get an errno value
    • GearmanClient::jobStatus - Get the status of a background job
    • GearmanClient::ping - Send data to all job servers to see if they echo it back
    • GearmanClient::removeOptions - Remove client options
    • GearmanClient::returnCode - Get the last Gearman return code
    • GearmanClient::runTasks - Run a list of tasks in parallel
    • GearmanClient::setClientCallback - Callback function when there is a data packet for a task (deprecated)
    • GearmanClient::setCompleteCallback - Set a function to be called on task completion
    • GearmanClient::setContext - Set application context
    • GearmanClient::setCreatedCallback - Set a callback for when a task is queued
    • GearmanClient::setData - Set application data (deprecated)
    • GearmanClient::setDataCallback - Callback function when there is a data packet for a task
    • GearmanClient::setExceptionCallback - Set a callback for worker exceptions
    • GearmanClient::setFailCallback - Set callback for job failure
    • GearmanClient::setOptions - Set client options
    • GearmanClient::setStatusCallback - Set a callback for collecting task status
    • GearmanClient::setTimeout - Set socket I/O activity timeout
    • GearmanClient::setWarningCallback - Set a callback for worker warnings
    • GearmanClient::setWorkloadCallback - Set a callback for accepting incremental data updates
    • GearmanClient::timeout - Get current socket I/O activity timeout value
    • GearmanClient::wait - Wait for I/O activity on all connections in a client
    • GearmanClient::__construct - Create a GearmanClient instance
    • GearmanJob::complete - Send the result and complete status (deprecated)
    • GearmanJob::data - Send data for a running job (deprecated)
    • GearmanJob::exception - Send exception for running job (deprecated)
    • GearmanJob::fail - Send fail status (deprecated)
    • GearmanJob::functionName - Get function name
    • GearmanJob::handle - Get the job handle
    • GearmanJob::returnCode - Get last return code
    • GearmanJob::sendComplete - Send the result and complete status
    • GearmanJob::sendData - Send data for a running job
    • GearmanJob::sendException - Send exception for running job (exception)
    • GearmanJob::sendFail - Send fail status
    • GearmanJob::sendStatus - Send status
    • GearmanJob::sendWarning - Send a warning
    • GearmanJob::setReturn - Set a return value
    • GearmanJob::status - Send status (deprecated)
    • GearmanJob::unique - Get the unique identifier
    • GearmanJob::warning - Send a warning (deprecated)
    • GearmanJob::workload - Get workload
    • GearmanJob::workloadSize - Get size of work load
    • GearmanJob::__construct - Create a GearmanJob instance
    • GearmanTask::create - Create a task (deprecated)
    • GearmanTask::data - Get data returned for a task
    • GearmanTask::dataSize - Get the size of returned data
    • GearmanTask::function - Get associated function name (deprecated)
    • GearmanTask::functionName - Get associated function name
    • GearmanTask::isKnown - Determine if task is known
    • GearmanTask::isRunning - Test whether the task is currently running
    • GearmanTask::jobHandle - Get the job handle
    • GearmanTask::recvData - Read work or result data into a buffer for a task
    • GearmanTask::returnCode - Get the last return code
    • GearmanTask::sendData - Send data for a task (deprecated)
    • GearmanTask::sendWorkload - Send data for a task
    • GearmanTask::taskDenominator - Get completion percentage denominator
    • GearmanTask::taskNumerator - Get completion percentage numerator
    • GearmanTask::unique - Get the unique identifier for a task
    • GearmanTask::uuid - Get the unique identifier for a task (deprecated)
    • GearmanTask::__construct - Create a GearmanTask instance
    • GearmanWorker::addFunction - Register and add callback function
    • GearmanWorker::addOptions - Add worker options
    • GearmanWorker::addServer - Add a job server
    • GearmanWorker::addServers - Add job servers
    • GearmanWorker::clone - Create a copy of the worker
    • GearmanWorker::echo - Test job server response
    • GearmanWorker::error - Get the last error encountered
    • GearmanWorker::getErrno - Get errno
    • GearmanWorker::options - Get worker options
    • GearmanWorker::register - Register a function with the job server
    • GearmanWorker::removeOptions - Remove worker options
    • GearmanWorker::returnCode - Get last Gearman return code
    • GearmanWorker::setId - Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers
    • GearmanWorker::setOptions - Set worker options
    • GearmanWorker::setTimeout - Set socket I/O activity timeout
    • GearmanWorker::timeout - Get socket I/O activity timeout
    • GearmanWorker::unregister - Unregister a function name with the job servers
    • GearmanWorker::unregisterAll - Unregister all function names with the job servers
    • GearmanWorker::wait - Wait for activity from one of the job servers
    • GearmanWorker::work - Wait for and perform jobs
    • GearmanWorker::__construct - Create a GearmanWorker instance
    • Gender\Gender::connect - Connect to an external name dictionary
    • Gender\Gender::country - Get textual country representation
    • Gender\Gender::get - Get gender of a name
    • Gender\Gender::isNick - Check if the name0 is an alias of the name1
    • Gender\Gender::similarNames - Get similar names
    • Gender\Gender::__construct - Construct the Gender object
    • Generator::current - Obtém o valor gerado
    • Generator::getReturn - Obtém o valor de retorno de um gerador
    • Generator::key - Obtém o chave gerada
    • Generator::next - Continua a execução do gerador
    • Generator::rewind - Reinicia o iterador
    • Generator::send - Envia um valor ao gerador
    • Generator::throw - Lança uma exceção no gerador
    • Generator::valid - Verifica se o gerador está ativo
    • Generator::__wakeup - Serializa o gerador (sempre falha)
    • 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 - Obtém todos os cabeçalhos da requisição HTTP
    • getcwd - Obtém o diretório atual
    • getdate - Recupera informações de data/hora
    • getenv - Gets the value of a single or all environment variables
    • gethostbyaddr - Obtém nome do servidor de Internet correspondente ao endereço de IP fornecido
    • gethostbyname - Obtenha o endereço IPv4 correspondente a um determinado nome de host da Internet
    • gethostbynamel - Obtenha uma lista de endereços IPv4 correspondentes a um determinado nome de host da Internet
    • gethostname - Gets the host name
    • getimagesize - Obtém o tamanho de uma imagem
    • getimagesizefromstring - Get the size of an image from a string
    • getlastmod - Obtém o horário da última modificação na página
    • getmxrr - Get MX records corresponding to a given Internet host name
    • getmygid - Obtém o GID do proprietário do script PHP
    • getmyinode - Gets the inode of the current script
    • getmypid - Obtém o ID do processo PHP
    • getmyuid - Obtém o UID do proprietário do script PHP
    • getopt - Obtêm opções da linha de comando
    • getprotobyname - Get protocol number associated with protocol name
    • getprotobynumber - Get protocol name associated with protocol number
    • getrandmax - Show largest possible random value
    • getrusage - Gets the current resource usages
    • getservbyname - Get port number associated with an Internet service and protocol
    • getservbyport - Get Internet service which corresponds to port and protocol
    • getSession - Connect to a MySQL server
    • gettext - Lookup a message in the current domain
    • gettimeofday - Obtém o horário atual
    • gettype - Obtém o tipo de uma variável
    • get_browser - Diz o que o navegador do usuário é capaz fazer
    • get_called_class - O nome da classe da qual o método estático foi chamado
    • get_cfg_var - Gets the value of a PHP configuration option
    • get_class - Retorna o nome da classe de um objeto
    • get_class_methods - Obtém o nome dos métodos da classe
    • get_class_vars - Obtém as propriedades padrão da classe
    • get_current_user - Gets the name of the owner of the current PHP script
    • get_debug_type - Obtém o nome do tipo de uma variável de forma adequada a depuração
    • get_declared_classes - Retorna um array com os nomes das classes definidas
    • get_declared_interfaces - Retorna um array com todas as interfaces declaradas
    • get_declared_traits - Retorna um array de todas as Traits declaradas
    • get_defined_constants - Returns an associative array with the names of all the constants and their values
    • get_defined_functions - Retorna um array com todas as funções definidas
    • get_defined_vars - Retorna um array com todas variáveis definidas
    • get_extension_funcs - Retorna um array com os nomes das funções de um módulo
    • get_headers - Retorna todos os cabeçalhos enviados pelo servidor em resposta a uma requisição HTTP
    • get_html_translation_table - Returns the translation table used by htmlspecialchars and htmlentities
    • get_included_files - Returns an array with the names of included or required files
    • get_include_path - Obtém a opção de configuração include_path atual
    • get_loaded_extensions - Returns an array with the names of all modules compiled and loaded
    • get_magic_quotes_gpc - Obtém a configuração atual de magic_quotes_gpc
    • get_magic_quotes_runtime - Obtém a configuração ativa para magic_quotes_runtime
    • get_mangled_object_vars - Retorna um array de nomes únicos e valores das propriedades do objeto
    • get_meta_tags - Extracts all meta tag content attributes from a file and returns an array
    • get_object_vars - Obtém as propriedades de um objeto
    • get_parent_class - Obtém o nome da classe pai para o objeto ou classe
    • get_required_files - Sinônimo de get_included_files
    • get_resources - Returns active resources
    • get_resource_id - Retorna um idenficador inteiro para o recurso informado
    • get_resource_type - Retorna o tipo de recurso
    • glob - Acha caminhos que combinam com um padrão
    • glob:// - Encontra caminhos que correspondem a um padrão
    • GlobIterator::count - Get the number of directories and files
    • GlobIterator::__construct - Construct a directory using glob
    • Gmagick::addimage - Adds new image to Gmagick object image list
    • Gmagick::addnoiseimage - Adds random noise to the image
    • Gmagick::annotateimage - Annotates an image with text
    • Gmagick::blurimage - Adds blur filter to image
    • Gmagick::borderimage - Surrounds the image with a border
    • Gmagick::charcoalimage - Simulates a charcoal drawing
    • Gmagick::chopimage - Removes a region of an image and trims
    • Gmagick::clear - Clears all resources associated to Gmagick object
    • Gmagick::commentimage - Adds a comment to your image
    • Gmagick::compositeimage - Composite one image onto another
    • Gmagick::cropimage - Extracts a region of the image
    • Gmagick::cropthumbnailimage - Creates a crop thumbnail
    • Gmagick::current - The current purpose
    • Gmagick::cyclecolormapimage - Displaces an image's colormap
    • Gmagick::deconstructimages - Returns certain pixel differences between images
    • Gmagick::despeckleimage - The despeckleimage purpose
    • Gmagick::destroy - The destroy purpose
    • Gmagick::drawimage - Renders the GmagickDraw object on the current image
    • Gmagick::edgeimage - Enhance edges within the image
    • Gmagick::embossimage - Returns a grayscale image with a three-dimensional effect
    • Gmagick::enhanceimage - Improves the quality of a noisy image
    • Gmagick::equalizeimage - Equalizes the image histogram
    • Gmagick::flipimage - Creates a vertical mirror image
    • Gmagick::flopimage - Creates a horizontal mirror image
    • Gmagick::frameimage - Adds a simulated three-dimensional border
    • Gmagick::gammaimage - Gamma-corrects an image
    • Gmagick::getcopyright - Returns the GraphicsMagick API copyright as a string
    • Gmagick::getfilename - The filename associated with an image sequence
    • Gmagick::getimagebackgroundcolor - Returns the image background color
    • Gmagick::getimageblueprimary - Returns the chromaticy blue primary point
    • Gmagick::getimagebordercolor - Returns the image border color
    • Gmagick::getimagechanneldepth - Gets the depth for a particular image channel
    • Gmagick::getimagecolors - Returns the color of the specified colormap index
    • Gmagick::getimagecolorspace - Gets the image colorspace
    • Gmagick::getimagecompose - Returns the composite operator associated with the image
    • Gmagick::getimagedelay - Gets the image delay
    • Gmagick::getimagedepth - Gets the depth of the image
    • Gmagick::getimagedispose - Gets the image disposal method
    • Gmagick::getimageextrema - Gets the extrema for the image
    • Gmagick::getimagefilename - Returns the filename of a particular image in a sequence
    • Gmagick::getimageformat - Returns the format of a particular image in a sequence
    • Gmagick::getimagegamma - Gets the image gamma
    • Gmagick::getimagegreenprimary - Returns the chromaticy green primary point
    • Gmagick::getimageheight - Returns the image height
    • Gmagick::getimagehistogram - Gets the image histogram
    • Gmagick::getimageindex - Gets the index of the current active image
    • Gmagick::getimageinterlacescheme - Gets the image interlace scheme
    • Gmagick::getimageiterations - Gets the image iterations
    • Gmagick::getimagematte - Check if the image has a matte channel
    • Gmagick::getimagemattecolor - Returns the image matte color
    • Gmagick::getimageprofile - Returns the named image profile
    • Gmagick::getimageredprimary - Returns the chromaticity red primary point
    • Gmagick::getimagerenderingintent - Gets the image rendering intent
    • Gmagick::getimageresolution - Gets the image X and Y resolution
    • Gmagick::getimagescene - Gets the image scene
    • Gmagick::getimagesignature - Generates an SHA-256 message digest
    • Gmagick::getimagetype - Gets the potential image type
    • Gmagick::getimageunits - Gets the image units of resolution
    • Gmagick::getimagewhitepoint - Returns the chromaticity white point
    • Gmagick::getimagewidth - Returns the width of the image
    • Gmagick::getpackagename - Returns the GraphicsMagick package name
    • Gmagick::getquantumdepth - Returns the Gmagick quantum depth as a string
    • Gmagick::getreleasedate - Returns the GraphicsMagick release date as a string
    • Gmagick::getsamplingfactors - Gets the horizontal and vertical sampling factor
    • Gmagick::getsize - Returns the size associated with the Gmagick object
    • Gmagick::getversion - Returns the GraphicsMagick API version
    • Gmagick::hasnextimage - Checks if the object has more images
    • Gmagick::haspreviousimage - Checks if the object has a previous image
    • Gmagick::implodeimage - Creates a new image as a copy
    • Gmagick::labelimage - Adds a label to an image
    • Gmagick::levelimage - Adjusts the levels of an image
    • Gmagick::magnifyimage - Scales an image proportionally 2x
    • Gmagick::mapimage - Replaces the colors of an image with the closest color from a reference image
    • Gmagick::medianfilterimage - Applies a digital filter
    • Gmagick::minifyimage - Scales an image proportionally to half its size
    • Gmagick::modulateimage - Control the brightness, saturation, and hue
    • Gmagick::motionblurimage - Simulates motion blur
    • Gmagick::newimage - Creates a new image
    • Gmagick::nextimage - Moves to the next image
    • Gmagick::normalizeimage - Enhances the contrast of a color image
    • Gmagick::oilpaintimage - Simulates an oil painting
    • Gmagick::previousimage - Move to the previous image in the object
    • Gmagick::profileimage - Adds or removes a profile from an image
    • Gmagick::quantizeimage - Analyzes the colors within a reference image
    • Gmagick::quantizeimages - The quantizeimages purpose
    • Gmagick::queryfontmetrics - Returns an array representing the font metrics
    • Gmagick::queryfonts - Returns the configured fonts
    • Gmagick::queryformats - Returns formats supported by Gmagick
    • Gmagick::radialblurimage - Radial blurs an image
    • Gmagick::raiseimage - Creates a simulated 3d button-like effect
    • Gmagick::read - Reads image from filename
    • Gmagick::readimage - Reads image from filename
    • Gmagick::readimageblob - Reads image from a binary string
    • Gmagick::readimagefile - The readimagefile purpose
    • Gmagick::reducenoiseimage - Smooths the contours of an image
    • Gmagick::removeimage - Removes an image from the image list
    • Gmagick::removeimageprofile - Removes the named image profile and returns it
    • Gmagick::resampleimage - Resample image to desired resolution
    • Gmagick::resizeimage - Scales an image
    • Gmagick::rollimage - Offsets an image
    • Gmagick::rotateimage - Rotates an image
    • Gmagick::scaleimage - Scales the size of an image
    • Gmagick::separateimagechannel - Separates a channel from the image
    • Gmagick::setCompressionQuality - Sets the object's default compression quality
    • Gmagick::setfilename - Sets the filename before you read or write the image
    • Gmagick::setimagebackgroundcolor - Sets the image background color
    • Gmagick::setimageblueprimary - Sets the image chromaticity blue primary point
    • Gmagick::setimagebordercolor - Sets the image border color
    • Gmagick::setimagechanneldepth - Sets the depth of a particular image channel
    • Gmagick::setimagecolorspace - Sets the image colorspace
    • Gmagick::setimagecompose - Sets the image composite operator
    • Gmagick::setimagedelay - Sets the image delay
    • Gmagick::setimagedepth - Sets the image depth
    • Gmagick::setimagedispose - Sets the image disposal method
    • Gmagick::setimagefilename - Sets the filename of a particular image in a sequence
    • Gmagick::setimageformat - Sets the format of a particular image
    • Gmagick::setimagegamma - Sets the image gamma
    • Gmagick::setimagegreenprimary - Sets the image chromaticity green primary point
    • Gmagick::setimageindex - Set the iterator to the position in the image list specified with the index parameter
    • Gmagick::setimageinterlacescheme - Sets the interlace scheme of the image
    • Gmagick::setimageiterations - Sets the image iterations
    • Gmagick::setimageprofile - Adds a named profile to the Gmagick object
    • Gmagick::setimageredprimary - Sets the image chromaticity red primary point
    • Gmagick::setimagerenderingintent - Sets the image rendering intent
    • Gmagick::setimageresolution - Sets the image resolution
    • Gmagick::setimagescene - Sets the image scene
    • Gmagick::setimagetype - Sets the image type
    • Gmagick::setimageunits - Sets the image units of resolution
    • Gmagick::setimagewhitepoint - Sets the image chromaticity white point
    • Gmagick::setsamplingfactors - Sets the image sampling factors
    • Gmagick::setsize - Sets the size of the Gmagick object
    • Gmagick::shearimage - Creating a parallelogram
    • Gmagick::solarizeimage - Applies a solarizing effect to the image
    • Gmagick::spreadimage - Randomly displaces each pixel in a block
    • Gmagick::stripimage - Strips an image of all profiles and comments
    • Gmagick::swirlimage - Swirls the pixels about the center of the image
    • Gmagick::thumbnailimage - Changes the size of an image
    • Gmagick::trimimage - Remove edges from the image
    • Gmagick::write - Sinônimo de Gmagick::writeimage
    • Gmagick::writeimage - Writes an image to the specified filename
    • Gmagick::__construct - The Gmagick constructor
    • GmagickDraw::annotate - Draws text on the image
    • GmagickDraw::arc - Draws an arc
    • GmagickDraw::bezier - Draws a bezier curve
    • GmagickDraw::ellipse - Draws an ellipse on the image
    • GmagickDraw::getfillcolor - Returns the fill color
    • GmagickDraw::getfillopacity - Returns the opacity used when drawing
    • GmagickDraw::getfont - Returns the font
    • GmagickDraw::getfontsize - Returns the font pointsize
    • GmagickDraw::getfontstyle - Returns the font style
    • GmagickDraw::getfontweight - Returns the font weight
    • GmagickDraw::getstrokecolor - Returns the color used for stroking object outlines
    • GmagickDraw::getstrokeopacity - Returns the opacity of stroked object outlines
    • GmagickDraw::getstrokewidth - Returns the width of the stroke used to draw object outlines
    • GmagickDraw::gettextdecoration - Returns the text decoration
    • GmagickDraw::gettextencoding - Returns the code set used for text annotations
    • GmagickDraw::line - Draws a line
    • GmagickDraw::point - Draws a point
    • GmagickDraw::polygon - Draws a polygon
    • GmagickDraw::polyline - Draws a polyline
    • GmagickDraw::rectangle - Draws a rectangle
    • GmagickDraw::rotate - Applies the specified rotation to the current coordinate space
    • GmagickDraw::roundrectangle - Draws a rounded rectangle
    • GmagickDraw::scale - Adjusts the scaling factor
    • GmagickDraw::setfillcolor - Sets the fill color to be used for drawing filled objects
    • GmagickDraw::setfillopacity - The setfillopacity purpose
    • GmagickDraw::setfont - Sets the fully-specified font to use when annotating with text
    • GmagickDraw::setfontsize - Sets the font pointsize to use when annotating with text
    • GmagickDraw::setfontstyle - Sets the font style to use when annotating with text
    • GmagickDraw::setfontweight - Sets the font weight
    • GmagickDraw::setstrokecolor - Sets the color used for stroking object outlines
    • GmagickDraw::setstrokeopacity - Specifies the opacity of stroked object outlines
    • GmagickDraw::setstrokewidth - Sets the width of the stroke used to draw object outlines
    • GmagickDraw::settextdecoration - Specifies a decoration
    • GmagickDraw::settextencoding - Specifies the text code set
    • GmagickPixel::getcolor - Returns the color
    • GmagickPixel::getcolorcount - Returns the color count associated with this color
    • GmagickPixel::getcolorvalue - Gets the normalized value of the provided color channel
    • GmagickPixel::setcolor - Sets the color
    • GmagickPixel::setcolorvalue - Sets the normalized value of one of the channels
    • GmagickPixel::__construct - The GmagickPixel constructor
    • gmdate - Formata uma data/hora GMT/CUT
    • gmmktime - Obtém um timestamp Unix para uma data GMT
    • GMP::__construct - Create GMP number
    • GMP::__serialize - Serializes the GMP object
    • GMP::__unserialize - Deserializes the data parameter into a GMP object
    • gmp_abs - Valor absoluto
    • gmp_add - Adiciona números
    • gmp_and - Operação binária AND
    • gmp_binomial - Calculates binomial coefficient
    • gmp_clrbit - Clear bit
    • gmp_cmp - Compara números
    • gmp_com - Calcula o complemento de um
    • gmp_div - Sinônimo de gmp_div_q
    • gmp_divexact - Divisão exata de números
    • gmp_div_q - Divide numbers
    • gmp_div_qr - Divide numbers and get quotient and remainder
    • gmp_div_r - Remainder of the division of numbers
    • gmp_export - Export to a binary string
    • gmp_fact - Factorial
    • gmp_gcd - Calcula o MDC
    • gmp_gcdext - Calcula MDC e multiplicadores
    • gmp_hamdist - Distância de Hamming
    • gmp_import - Import from a binary string
    • gmp_init - Create GMP number
    • gmp_intval - Converte um número GMP para um inteiro
    • gmp_invert - Inverse by modulo
    • gmp_jacobi - Símbolo de Jacobi
    • gmp_kronecker - Kronecker symbol
    • gmp_lcm - Calculate LCM
    • gmp_legendre - Símbolo de Legendre
    • gmp_mod - Operação Módulo
    • gmp_mul - Multiplica números
    • gmp_neg - Negativa o número
    • gmp_nextprime - Encontra o próximo número primo
    • gmp_or - Operação binária OR
    • gmp_perfect_power - Perfect power check
    • gmp_perfect_square - Perfect square check
    • gmp_popcount - Contagem de população
    • gmp_pow - Elevar o número a uma potência
    • gmp_powm - Eleva um número a uma potência com módulo
    • gmp_prob_prime - Check if number is "probably prime"
    • gmp_random - Random number
    • gmp_random_bits - Random number
    • gmp_random_range - Get a uniformly selected integer
    • gmp_random_seed - Sets the RNG seed
    • gmp_root - Take the integer part of nth root
    • gmp_rootrem - Take the integer part and remainder of nth root
    • gmp_scan0 - Scan for 0
    • gmp_scan1 - Scan for 1
    • gmp_setbit - Set bit
    • gmp_sign - Sinal do número
    • gmp_sqrt - Calcula a raiz quadrada
    • gmp_sqrtrem - Raiz quadrada com resto
    • gmp_strval - Converte um número GMP para uma string
    • gmp_sub - Subtrai números
    • gmp_testbit - Tests if a bit is set
    • gmp_xor - Operação binária XOR
    • gmstrftime - Formata uma data/hora GMT/UTC de acordo com as configurações de localidade
    • gnupg_adddecryptkey - Add a key for decryption
    • gnupg_addencryptkey - Add a key for encryption
    • gnupg_addsignkey - Add a key for signing
    • gnupg_cleardecryptkeys - Removes all keys which were set for decryption before
    • gnupg_clearencryptkeys - Removes all keys which were set for encryption before
    • gnupg_clearsignkeys - Removes all keys which were set for signing before
    • gnupg_decrypt - Decrypts a given text
    • gnupg_decryptverify - Decrypts and verifies a given text
    • gnupg_deletekey - Delete a key from the keyring
    • gnupg_encrypt - Encrypts a given text
    • gnupg_encryptsign - Encrypts and signs a given text
    • gnupg_export - Exports a key
    • gnupg_getengineinfo - Returns the engine info
    • gnupg_geterror - Returns the errortext, if a function fails
    • gnupg_geterrorinfo - Returns the error info
    • gnupg_getprotocol - Returns the currently active protocol for all operations
    • gnupg_gettrustlist - Search the trust items
    • gnupg_import - Imports a key
    • gnupg_init - Initialize a connection
    • gnupg_keyinfo - Returns an array with information about all keys that matches the given pattern
    • gnupg_listsignatures - List key signatures
    • gnupg_setarmor - Toggle armored output
    • gnupg_seterrormode - Sets the mode for error_reporting
    • gnupg_setsignmode - Sets the mode for signing
    • gnupg_sign - Signs a given text
    • gnupg_verify - Verifies a signed text
    • grapheme_extract - Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8
    • grapheme_stripos - Find position (in grapheme units) of first occurrence of a case-insensitive string
    • grapheme_stristr - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
    • grapheme_strlen - Get string length in grapheme units
    • grapheme_strpos - Find position (in grapheme units) of first occurrence of a string
    • grapheme_strripos - Find position (in grapheme units) of last occurrence of a case-insensitive string
    • grapheme_strrpos - Find position (in grapheme units) of last occurrence of a string
    • grapheme_strstr - Returns part of haystack string from the first occurrence of needle to the end of haystack
    • grapheme_substr - Return part of a string
    • gregoriantojd - Converte uma data gregoriana para o "Julian Day Count"
    • gzclose - Fecha um ponteiro para um arquivo-gz
    • gzcompress - Compress a string
    • gzdecode - Decodifica uma string comprimida usando o gzip
    • gzdeflate - Deflate a string
    • gzencode - Create a gzip compressed string
    • gzeof - Test for EOF on a gz-file pointer
    • gzfile - Read entire gz-file into an array
    • gzgetc - Get character from gz-file pointer
    • gzgets - Obtém uma linha de um ponteiro de arquivo
    • gzgetss - Get line from gz-file pointer and strip HTML tags
    • gzinflate - Inflate a deflated string
    • gzopen - Open gz-file
    • gzpassthru - Output all remaining data on a gz-file pointer
    • gzputs - Sinônimo de gzwrite
    • gzread - Binary-safe gz-file read
    • gzrewind - Retorna ao início a posição de um ponteiro para um arquivo-gz
    • gzseek - Seek on a gz-file pointer
    • gztell - Indica a posição de leitura/gravação em um ponteiro para arquivo-gz
    • gzuncompress - Uncompress a compressed string
    • gzwrite - Escrita segura para binário em arquivo-gz
  • h
    • hash - Generate a hash value (message digest)
    • HashContext::__construct - Private constructor to disallow direct instantiation
    • HashContext::__serialize - Serializes the HashContext object
    • HashContext::__unserialize - Deserializes the data parameter into a HashContext object
    • hash_algos - Return a list of registered hashing algorithms
    • hash_copy - Copy hashing context
    • hash_equals - Timing attack safe string comparison
    • hash_file - Generate a hash value using the contents of a given file
    • hash_final - Finalize an incremental hash and return resulting digest
    • hash_hkdf - Generate a HKDF key derivation of a supplied key input
    • hash_hmac - Generate a keyed hash value using the HMAC method
    • hash_hmac_algos - Return a list of registered hashing algorithms suitable for hash_hmac
    • hash_hmac_file - Generate a keyed hash value using the HMAC method and the contents of a given file
    • hash_init - Initialize an incremental hashing context
    • hash_pbkdf2 - Generate a PBKDF2 key derivation of a supplied password
    • hash_update - Pump data into an active hashing context
    • hash_update_file - Pump data into an active hashing context from a file
    • hash_update_stream - Pump data into an active hashing context from an open stream
    • header - Send a raw HTTP header
    • headers_list - Retorna uma lista de cabeçalhos de resposta enviados (ou prontos para enviar)
    • headers_sent - Checks if or where headers have been sent
    • header_register_callback - Call a header function
    • header_remove - Remove cabeçalhos definidos anteriormente
    • hebrev - Convert logical Hebrew text to visual text
    • hebrevc - Convert logical Hebrew text to visual text with newline conversion
    • hex2bin - Decodifica uma string binária codificada em hexadecimal
    • hexdec - Hexadecimal para decimal
    • highlight_file - Destaca a sintaxe de um arquivo
    • highlight_string - Syntax highlighting of a string
    • hrtime - Get the system's high resolution time
    • HRTime\PerformanceCounter::getFrequency - Timer frequency in ticks per second
    • HRTime\PerformanceCounter::getTicks - Current ticks from the system
    • HRTime\PerformanceCounter::getTicksSince - Ticks elapsed since the given value
    • HRTime\StopWatch::getElapsedTicks - Get elapsed ticks for all intervals
    • HRTime\StopWatch::getElapsedTime - Get elapsed time for all intervals
    • HRTime\StopWatch::getLastElapsedTicks - Get elapsed ticks for the last interval
    • HRTime\StopWatch::getLastElapsedTime - Get elapsed time for the last interval
    • HRTime\StopWatch::isRunning - Whether the measurement is running
    • HRTime\StopWatch::start - Start time measurement
    • HRTime\StopWatch::stop - Stop time measurement
    • htmlentities - Convert all applicable characters to HTML entities
    • htmlspecialchars - Convert special characters to HTML entities
    • htmlspecialchars_decode - Convert special HTML entities back to characters
    • html_entity_decode - Convert HTML entities to their corresponding characters
    • http:// - Acessando URLs HTTP(s)
    • http_build_query - Gera a string de consulta (query) em formato URL
    • http_response_code - Get or Set the HTTP response code
    • hypot - Calcula o comprimento da hipotenusa de triângulo retângulo
  • i
    • ibase_add_user - Adiciona um usuário a um banco de dados seguro
    • ibase_affected_rows - Retorna o número de linhas que foram afetados pela consulta anterior
    • ibase_backup - Initiates a backup task in the service manager and returns immediately
    • ibase_blob_add - Adiciona dados em um blob recém criado
    • ibase_blob_cancel - Cancel creating blob
    • ibase_blob_close - Close blob
    • ibase_blob_create - Create a new blob for adding data
    • ibase_blob_echo - Output blob contents to browser
    • ibase_blob_get - Retorna uma quantidade especificada de bytes de dados de um blob aberto
    • ibase_blob_import - Cria um blob, copia um arquivo para ele e o fecha
    • ibase_blob_info - Retorna o tamanho do blob e outras informações úteis
    • ibase_blob_open - Abre um blob para obter partes de dados
    • ibase_close - Close a connection to an InterBase database
    • ibase_commit - Commit a transaction
    • ibase_commit_ret - Commit a transaction without closing it
    • ibase_connect - Abre uma conexão com um banco de dados
    • ibase_db_info - Request statistics about a database
    • ibase_delete_user - Exclui um usuário de um banco de dados seguro
    • ibase_drop_db - Drops a database
    • ibase_errcode - Return an error code
    • ibase_errmsg - Return error messages
    • ibase_execute - Executa uma consulta preparada anteriormente
    • ibase_fetch_assoc - Fetch a result row from a query as an associative array
    • ibase_fetch_object - Get an object from a InterBase database
    • ibase_fetch_row - Fetch a row from an InterBase database
    • ibase_field_info - Obtém informação sobre um campo
    • ibase_free_event_handler - Cancela um manipulador de eventos registrado
    • ibase_free_query - Libera a memória alocada para uma consulta preparada
    • ibase_free_result - Libera um conjunto de resultados
    • ibase_gen_id - Increments the named generator and returns its new value
    • ibase_maintain_db - Execute a maintenance command on the database server
    • ibase_modify_user - Modifica um usuário para um banco de dados seguro
    • ibase_name_result - Define um nome para um conjunto de resultados
    • ibase_num_fields - Obtém o número de campos em um conjunto de resultados
    • ibase_num_params - Retorna o número de parâmetros em uma consulta preparada
    • ibase_param_info - Retorna informação sobre um parâmetro em uma consulta preparada
    • ibase_pconnect - Open a persistent connection to an InterBase database
    • ibase_prepare - Prepara uma consulta para ligação de parâmetros e execução posteriores
    • ibase_query - Executa uma consulta em um banco de dados InterBase
    • ibase_restore - Initiates a restore task in the service manager and returns immediately
    • ibase_rollback - Roll back a transaction
    • ibase_rollback_ret - Roll back a transaction without closing it
    • ibase_server_info - Request information about a database server
    • ibase_service_attach - Connect to the service manager
    • ibase_service_detach - Disconnect from the service manager
    • ibase_set_event_handler - Register a callback function to be called when events are posted
    • ibase_trans - Begin a transaction
    • ibase_wait_event - Espera por um evento ser postado pelo banco de dados
    • iconv - Converte uma string de uma codificação de caracteres para outra
    • iconv_get_encoding - Recuperar variáveis de configuração internas da extensão iconv
    • iconv_mime_decode - Decodifica um campo de cabeçalho MIME
    • iconv_mime_decode_headers - Decodifica vários campos de cabeçalho MIME de uma só vez
    • iconv_mime_encode - Compõe um campo de cabeçalho MIME
    • iconv_set_encoding - Define a configuração atual para conversão de codificação de caracteres
    • iconv_strlen - Retorna a contagem de caracteres da string
    • iconv_strpos - Localiza a posição da primeira ocorrência de um caractere em uma string
    • iconv_strrpos - Localiza a última ocorrência de um caractere em uma string
    • iconv_substr - Corta parte de uma string
    • idate - Formata uma parte de uma hora/data local como um inteiro
    • idn_to_ascii - Convert domain name to IDNA ASCII form
    • idn_to_utf8 - Convert domain name from IDNA ASCII to 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 - Set whether a client disconnect should abort script execution
    • image2wbmp - Envia a imagem para o navegador ou para um arquivo
    • imageaffine - Return an image containing the affine transformed src image, using an optional clipping area
    • imageaffinematrixconcat - Concatenate two affine transformation matrices
    • imageaffinematrixget - Get an affine transformation matrix
    • imagealphablending - Set the blending mode for an image
    • imageantialias - Should antialias functions be used or not
    • imagearc - Draws an arc
    • imageavif - Envia a imagem para o navegador ou para um arquivo
    • imagebmp - Output a BMP image to browser or file
    • imagechar - Draw a character horizontally
    • imagecharup - Draw a character vertically
    • imagecolorallocate - Allocate a color for an image
    • imagecolorallocatealpha - Allocate a color for an image
    • imagecolorat - Get the index of the color of a pixel
    • imagecolorclosest - Get the index of the closest color to the specified color
    • imagecolorclosestalpha - Get the index of the closest color to the specified color + alpha
    • imagecolorclosesthwb - Get the index of the color which has the hue, white and blackness
    • imagecolordeallocate - De-allocate a color for an image
    • imagecolorexact - Get the index of the specified color
    • imagecolorexactalpha - Get the index of the specified color + alpha
    • imagecolormatch - Makes the colors of the palette version of an image more closely match the true color version
    • imagecolorresolve - Get the index of the specified color or its closest possible alternative
    • imagecolorresolvealpha - Get the index of the specified color + alpha or its closest possible alternative
    • imagecolorset - Set the color for the specified palette index
    • imagecolorsforindex - Get the colors for an index
    • imagecolorstotal - Find out the number of colors in an image's palette
    • imagecolortransparent - Define a color as transparent
    • imageconvolution - Apply a 3x3 convolution matrix, using coefficient and offset
    • imagecopy - Copiar uma parte de uma imagem
    • imagecopymerge - Copy and merge part of an image
    • imagecopymergegray - Copy and merge part of an image with gray scale
    • imagecopyresampled - Copy and resize part of an image with resampling
    • imagecopyresized - Copy and resize part of an image
    • imagecreate - Crie uma nova imagem baseada em paleta
    • imagecreatefromavif - Cria uma nova imagem a partir de um arquivo ou URL
    • imagecreatefrombmp - Cria uma nova imagem a partir de um arquivo ou URL
    • imagecreatefromgd - Criar uma nova imagem a partir de um arquivo GD ou URL
    • imagecreatefromgd2 - Create a new image from GD2 file or URL
    • imagecreatefromgd2part - Create a new image from a given part of GD2 file or URL
    • imagecreatefromgif - Cria uma nova imagem a partir de um arquivo ou URL
    • imagecreatefromjpeg - Cria uma nova imagem a partir de um arquivo ou URL
    • imagecreatefrompng - Cria uma nova imagem a partir de um arquivo ou URL
    • imagecreatefromstring - Create a new image from the image stream in the string
    • imagecreatefromtga - Cria uma nova imagem a partir de um arquivo ou URL
    • imagecreatefromwbmp - Cria uma nova imagem a partir de um arquivo ou URL
    • imagecreatefromwebp - Cria uma nova imagem a partir de um arquivo ou URL
    • imagecreatefromxbm - Cria uma nova imagem a partir de um arquivo ou URL
    • imagecreatefromxpm - Cria uma nova imagem a partir de um arquivo ou URL
    • imagecreatetruecolor - Create a new true color image
    • imagecrop - Crop an image to the given rectangle
    • imagecropauto - Crop an image automatically using one of the available modes
    • imagedashedline - Draw a dashed line
    • imagedestroy - Destruir uma imagem
    • imageellipse - Draw an ellipse
    • imagefill - Flood fill
    • imagefilledarc - Draw a partial arc and fill it
    • imagefilledellipse - Draw a filled ellipse
    • imagefilledpolygon - Draw a filled polygon
    • imagefilledrectangle - Draw a filled rectangle
    • imagefilltoborder - Flood fill to specific color
    • imagefilter - Applies a filter to an image
    • imageflip - Flips an image using a given mode
    • imagefontheight - Get font height
    • imagefontwidth - Get font width
    • imageftbbox - Give the bounding box of a text using fonts via freetype2
    • imagefttext - Write text to the image using fonts using FreeType 2
    • imagegammacorrect - Apply a gamma correction to a GD image
    • imagegd - Output GD image to browser or file
    • imagegd2 - Output GD2 image to browser or file
    • imagegetclip - Get the clipping rectangle
    • imagegetinterpolation - Get the interpolation method
    • imagegif - Envia a imagem para o navegador ou para um arquivo
    • imagegrabscreen - Captures the whole screen
    • imagegrabwindow - Captures a window
    • imageinterlace - Enable or disable interlace
    • imageistruecolor - Finds whether an image is a truecolor image
    • imagejpeg - Envia a imagem para o navegador ou para um arquivo
    • imagelayereffect - Set the alpha blending flag to use layering effects
    • imageline - Draw a line
    • imageloadfont - Load a new font
    • imageopenpolygon - Draws an open polygon
    • imagepalettecopy - Copy the palette from one image to another
    • imagepalettetotruecolor - Converts a palette based image to true color
    • imagepng - Emite uma imagem PNG para o navegador ou arquivo
    • imagepolygon - Draws a polygon
    • imagerectangle - Draw a rectangle
    • imageresolution - Get or set the resolution of the image
    • imagerotate - Rotate an image with a given angle
    • imagesavealpha - Whether to retain full alpha channel information when saving images
    • imagescale - Scale an image using the given new width and height
    • imagesetbrush - Set the brush image for line drawing
    • imagesetclip - Set the clipping rectangle
    • imagesetinterpolation - Set the interpolation method
    • imagesetpixel - Set a single pixel
    • imagesetstyle - Set the style for line drawing
    • imagesetthickness - Set the thickness for line drawing
    • imagesettile - Set the tile image for filling
    • imagestring - Draw a string horizontally
    • imagestringup - Draw a string vertically
    • imagesx - Obtém a largura da imagem
    • imagesy - Obtém a altura da imagem
    • imagetruecolortopalette - Convert a true color image to a palette image
    • imagettfbbox - Give the bounding box of a text using TrueType fonts
    • imagettftext - Write text to the image using TrueType fonts
    • imagetypes - Retorna os tipos de imagens suportados pela instalação do PHP
    • imagewbmp - Envia a imagem para o navegador ou para um arquivo
    • imagewebp - Output a WebP image to browser or file
    • imagexbm - Output an XBM image to browser or file
    • image_type_to_extension - Get file extension for image type
    • image_type_to_mime_type - Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
    • Imagick::adaptiveBlurImage - Adds adaptive blur filter to image
    • Imagick::adaptiveResizeImage - Adaptively resize image with data dependent triangulation
    • Imagick::adaptiveSharpenImage - Adaptively sharpen the image
    • Imagick::adaptiveThresholdImage - Selects a threshold for each pixel based on a range of intensity
    • Imagick::addImage - Adds new image to Imagick object image list
    • Imagick::addNoiseImage - Adds random noise to the image
    • Imagick::affineTransformImage - Transforms an image
    • Imagick::animateImages - Animates an image or images
    • Imagick::annotateImage - Annotates an image with text
    • Imagick::appendImages - Append a set of images
    • Imagick::autoLevelImage - Adjusts the levels of a particular image channel
    • Imagick::averageImages - Average a set of images
    • Imagick::blackThresholdImage - Forces all pixels below the threshold into black
    • Imagick::blueShiftImage - Mutes the colors of the image
    • Imagick::blurImage - Adds blur filter to image
    • Imagick::borderImage - Surrounds the image with a border
    • Imagick::brightnessContrastImage - Change the brightness and/or contrast of an image
    • Imagick::charcoalImage - Simulates a charcoal drawing
    • Imagick::chopImage - Removes a region of an image and trims
    • Imagick::clampImage - Restricts the color range from 0 to the quantum depth.
    • Imagick::clear - Clears all resources associated to Imagick object
    • Imagick::clipImage - Clips along the first path from the 8BIM profile
    • Imagick::clipImagePath - Clips along the named paths from the 8BIM profile, if present
    • Imagick::clipPathImage - Clips along the named paths from the 8BIM profile
    • Imagick::clone - Makes an exact copy of the Imagick object
    • Imagick::clutImage - Replaces colors in the image
    • Imagick::coalesceImages - Composites a set of images
    • Imagick::colorFloodfillImage - Changes the color value of any pixel that matches target
    • Imagick::colorizeImage - Blends the fill color with the image
    • Imagick::colorMatrixImage - Apply color transformation to an image
    • Imagick::combineImages - Combines one or more images into a single image
    • Imagick::commentImage - Adds a comment to your image
    • Imagick::compareImageChannels - Returns the difference in one or more images
    • Imagick::compareImageLayers - Returns the maximum bounding region between images
    • Imagick::compareImages - Compares an image to a reconstructed image
    • Imagick::compositeImage - Composite one image onto another
    • Imagick::contrastImage - Change the contrast of the image
    • Imagick::contrastStretchImage - Enhances the contrast of a color image
    • Imagick::convolveImage - Applies a custom convolution kernel to the image
    • Imagick::count - Get the number of images
    • Imagick::cropImage - Extracts a region of the image
    • Imagick::cropThumbnailImage - Creates a crop thumbnail
    • Imagick::current - Returns a reference to the current Imagick object
    • Imagick::cycleColormapImage - Displaces an image's colormap
    • Imagick::decipherImage - Deciphers an image
    • Imagick::deconstructImages - Returns certain pixel differences between images
    • Imagick::deleteImageArtifact - Delete image artifact
    • Imagick::deleteImageProperty - Deletes an image property
    • Imagick::deskewImage - Removes skew from the image
    • Imagick::despeckleImage - Reduces the speckle noise in an image
    • Imagick::destroy - Destroys the Imagick object
    • Imagick::displayImage - Displays an image
    • Imagick::displayImages - Displays an image or image sequence
    • Imagick::distortImage - Distorts an image using various distortion methods
    • Imagick::drawImage - Renders the ImagickDraw object on the current image
    • Imagick::edgeImage - Enhance edges within the image
    • Imagick::embossImage - Returns a grayscale image with a three-dimensional effect
    • Imagick::encipherImage - Enciphers an image
    • Imagick::enhanceImage - Improves the quality of a noisy image
    • Imagick::equalizeImage - Equalizes the image histogram
    • Imagick::evaluateImage - Applies an expression to an image
    • Imagick::exportImagePixels - Exports raw image pixels
    • Imagick::extentImage - Set image size
    • Imagick::filter - Applies a custom convolution kernel to the image
    • Imagick::flattenImages - Merges a sequence of images
    • Imagick::flipImage - Creates a vertical mirror image
    • Imagick::floodFillPaintImage - Changes the color value of any pixel that matches target
    • Imagick::flopImage - Creates a horizontal mirror image
    • Imagick::forwardFourierTransformImage - Implements the discrete Fourier transform (DFT)
    • Imagick::frameImage - Adds a simulated three-dimensional border
    • Imagick::functionImage - Applies a function on the image
    • Imagick::fxImage - Evaluate expression for each pixel in the image
    • Imagick::gammaImage - Gamma-corrects an image
    • Imagick::gaussianBlurImage - Blurs an image
    • Imagick::getColorspace - Gets the colorspace
    • Imagick::getCompression - Gets the object compression type
    • Imagick::getCompressionQuality - Gets the object compression quality
    • Imagick::getCopyright - Returns the ImageMagick API copyright as a string
    • Imagick::getFilename - The filename associated with an image sequence
    • Imagick::getFont - Gets font
    • Imagick::getFormat - Returns the format of the Imagick object
    • Imagick::getGravity - Gets the gravity
    • Imagick::getHomeURL - Returns the ImageMagick home URL
    • Imagick::getImage - Returns a new Imagick object
    • Imagick::getImageAlphaChannel - Checks if the image has an alpha channel
    • Imagick::getImageArtifact - Get image artifact
    • Imagick::getImageAttribute - Returns a named attribute
    • Imagick::getImageBackgroundColor - Returns the image background color
    • Imagick::getImageBlob - Returns the image sequence as a blob
    • Imagick::getImageBluePrimary - Returns the chromaticy blue primary point
    • Imagick::getImageBorderColor - Returns the image border color
    • Imagick::getImageChannelDepth - Gets the depth for a particular image channel
    • Imagick::getImageChannelDistortion - Compares image channels of an image to a reconstructed image
    • Imagick::getImageChannelDistortions - Gets channel distortions
    • Imagick::getImageChannelExtrema - Gets the extrema for one or more image channels
    • Imagick::getImageChannelKurtosis - The getImageChannelKurtosis purpose
    • Imagick::getImageChannelMean - Gets the mean and standard deviation
    • Imagick::getImageChannelRange - Gets channel range
    • Imagick::getImageChannelStatistics - Returns statistics for each channel in the image
    • Imagick::getImageClipMask - Gets image clip mask
    • Imagick::getImageColormapColor - Returns the color of the specified colormap index
    • Imagick::getImageColors - Gets the number of unique colors in the image
    • Imagick::getImageColorspace - Gets the image colorspace
    • Imagick::getImageCompose - Returns the composite operator associated with the image
    • Imagick::getImageCompression - Gets the current image's compression type
    • Imagick::getImageCompressionQuality - Gets the current image's compression quality
    • Imagick::getImageDelay - Gets the image delay
    • Imagick::getImageDepth - Gets the image depth
    • Imagick::getImageDispose - Gets the image disposal method
    • Imagick::getImageDistortion - Compares an image to a reconstructed image
    • Imagick::getImageExtrema - Gets the extrema for the image
    • Imagick::getImageFilename - Returns the filename of a particular image in a sequence
    • Imagick::getImageFormat - Returns the format of a particular image in a sequence
    • Imagick::getImageGamma - Gets the image gamma
    • Imagick::getImageGeometry - Gets the width and height as an associative array
    • Imagick::getImageGravity - Gets the image gravity
    • Imagick::getImageGreenPrimary - Returns the chromaticy green primary point
    • Imagick::getImageHeight - Returns the image height
    • Imagick::getImageHistogram - Gets the image histogram
    • Imagick::getImageIndex - Gets the index of the current active image
    • Imagick::getImageInterlaceScheme - Gets the image interlace scheme
    • Imagick::getImageInterpolateMethod - Returns the interpolation method
    • Imagick::getImageIterations - Gets the image iterations
    • Imagick::getImageLength - Returns the image length in bytes
    • Imagick::getImageMatte - Return if the image has a matte channel
    • Imagick::getImageMatteColor - Returns the image matte color
    • Imagick::getImageMimeType - Returns the image mime-type
    • Imagick::getImageOrientation - Gets the image orientation
    • Imagick::getImagePage - Returns the page geometry
    • Imagick::getImagePixelColor - Returns the color of the specified pixel
    • Imagick::getImageProfile - Returns the named image profile
    • Imagick::getImageProfiles - Returns the image profiles
    • Imagick::getImageProperties - Returns the image properties
    • Imagick::getImageProperty - Returns the named image property
    • Imagick::getImageRedPrimary - Returns the chromaticity red primary point
    • Imagick::getImageRegion - Extracts a region of the image
    • Imagick::getImageRenderingIntent - Gets the image rendering intent
    • Imagick::getImageResolution - Gets the image X and Y resolution
    • Imagick::getImagesBlob - Returns all image sequences as a blob
    • Imagick::getImageScene - Gets the image scene
    • Imagick::getImageSignature - Generates an SHA-256 message digest
    • Imagick::getImageSize - Returns the image length in bytes
    • Imagick::getImageTicksPerSecond - Gets the image ticks-per-second
    • Imagick::getImageTotalInkDensity - Gets the image total ink density
    • Imagick::getImageType - Gets the potential image type
    • Imagick::getImageUnits - Gets the image units of resolution
    • Imagick::getImageVirtualPixelMethod - Returns the virtual pixel method
    • Imagick::getImageWhitePoint - Returns the chromaticity white point
    • Imagick::getImageWidth - Returns the image width
    • Imagick::getInterlaceScheme - Gets the object interlace scheme
    • Imagick::getIteratorIndex - Gets the index of the current active image
    • Imagick::getNumberImages - Returns the number of images in the object
    • Imagick::getOption - Returns a value associated with the specified key
    • Imagick::getPackageName - Returns the ImageMagick package name
    • Imagick::getPage - Returns the page geometry
    • Imagick::getPixelIterator - Returns a MagickPixelIterator
    • Imagick::getPixelRegionIterator - Get an ImagickPixelIterator for an image section
    • Imagick::getPointSize - Gets point size
    • Imagick::getQuantum - Returns the ImageMagick quantum range
    • Imagick::getQuantumDepth - Gets the quantum depth
    • Imagick::getQuantumRange - Returns the Imagick quantum range
    • Imagick::getRegistry - Get a StringRegistry entry
    • Imagick::getReleaseDate - Returns the ImageMagick release date
    • Imagick::getResource - Returns the specified resource's memory usage
    • Imagick::getResourceLimit - Returns the specified resource limit
    • Imagick::getSamplingFactors - Gets the horizontal and vertical sampling factor
    • Imagick::getSize - Returns the size associated with the Imagick object
    • Imagick::getSizeOffset - Returns the size offset
    • Imagick::getVersion - Returns the ImageMagick API version
    • Imagick::haldClutImage - Replaces colors in the image
    • Imagick::hasNextImage - Checks if the object has more images
    • Imagick::hasPreviousImage - Checks if the object has a previous image
    • Imagick::identifyFormat - Formats a string with image details
    • Imagick::identifyImage - Identifies an image and fetches attributes
    • Imagick::implodeImage - Creates a new image as a copy
    • Imagick::importImagePixels - Imports image pixels
    • Imagick::inverseFourierTransformImage - Implements the inverse discrete Fourier transform (DFT)
    • Imagick::labelImage - Adds a label to an image
    • Imagick::levelImage - Adjusts the levels of an image
    • Imagick::linearStretchImage - Stretches with saturation the image intensity
    • Imagick::liquidRescaleImage - Animates an image or images
    • Imagick::listRegistry - List all the registry settings
    • Imagick::magnifyImage - Scales an image proportionally 2x
    • Imagick::mapImage - Replaces the colors of an image with the closest color from a reference image
    • Imagick::matteFloodfillImage - Changes the transparency value of a color
    • Imagick::medianFilterImage - Applies a digital filter
    • Imagick::mergeImageLayers - Merges image layers
    • Imagick::minifyImage - Scales an image proportionally to half its size
    • Imagick::modulateImage - Control the brightness, saturation, and hue
    • Imagick::montageImage - Creates a composite image
    • Imagick::morphImages - Method morphs a set of images
    • Imagick::morphology - Applies a user supplied kernel to the image according to the given morphology method.
    • Imagick::mosaicImages - Forms a mosaic from images
    • Imagick::motionBlurImage - Simulates motion blur
    • Imagick::negateImage - Negates the colors in the reference image
    • Imagick::newImage - Creates a new image
    • Imagick::newPseudoImage - Creates a new image
    • Imagick::nextImage - Moves to the next image
    • Imagick::normalizeImage - Enhances the contrast of a color image
    • Imagick::oilPaintImage - Simulates an oil painting
    • Imagick::opaquePaintImage - Changes the color value of any pixel that matches target
    • Imagick::optimizeImageLayers - Removes repeated portions of images to optimize
    • Imagick::orderedPosterizeImage - Performs an ordered dither
    • Imagick::paintFloodfillImage - Changes the color value of any pixel that matches target
    • Imagick::paintOpaqueImage - Change any pixel that matches color
    • Imagick::paintTransparentImage - Changes any pixel that matches color with the color defined by fill
    • Imagick::pingImage - Fetch basic attributes about the image
    • Imagick::pingImageBlob - Quickly fetch attributes
    • Imagick::pingImageFile - Get basic image attributes in a lightweight manner
    • Imagick::polaroidImage - Simulates a Polaroid picture
    • Imagick::posterizeImage - Reduces the image to a limited number of color level
    • Imagick::previewImages - Quickly pin-point appropriate parameters for image processing
    • Imagick::previousImage - Move to the previous image in the object
    • Imagick::profileImage - Adds or removes a profile from an image
    • Imagick::quantizeImage - Analyzes the colors within a reference image
    • Imagick::quantizeImages - Analyzes the colors within a sequence of images
    • Imagick::queryFontMetrics - Returns an array representing the font metrics
    • Imagick::queryFonts - Returns the configured fonts
    • Imagick::queryFormats - Returns formats supported by Imagick
    • Imagick::radialBlurImage - Radial blurs an image
    • Imagick::raiseImage - Creates a simulated 3d button-like effect
    • Imagick::randomThresholdImage - Creates a high-contrast, two-color image
    • Imagick::readImage - Reads image from filename
    • Imagick::readImageBlob - Reads image from a binary string
    • Imagick::readImageFile - Reads image from open filehandle
    • Imagick::readimages - Reads image from an array of filenames
    • Imagick::recolorImage - Recolors image
    • Imagick::reduceNoiseImage - Smooths the contours of an image
    • Imagick::remapImage - Remaps image colors
    • Imagick::removeImage - Removes an image from the image list
    • Imagick::removeImageProfile - Removes the named image profile and returns it
    • Imagick::render - Renders all preceding drawing commands
    • Imagick::resampleImage - Resample image to desired resolution
    • Imagick::resetImagePage - Reset image page
    • Imagick::resizeImage - Scales an image
    • Imagick::rollImage - Offsets an image
    • Imagick::rotateImage - Rotates an image
    • Imagick::rotationalBlurImage - Rotational blurs an image
    • Imagick::roundCorners - Rounds image corners
    • Imagick::sampleImage - Scales an image with pixel sampling
    • Imagick::scaleImage - Scales the size of an image
    • Imagick::segmentImage - Segments an image
    • Imagick::selectiveBlurImage - Selectively blur an image within a contrast threshold
    • Imagick::separateImageChannel - Separates a channel from the image
    • Imagick::sepiaToneImage - Sepia tones an image
    • Imagick::setBackgroundColor - Sets the object's default background color
    • Imagick::setColorspace - Set colorspace
    • Imagick::setCompression - Sets the object's default compression type
    • Imagick::setCompressionQuality - Sets the object's default compression quality
    • Imagick::setFilename - Sets the filename before you read or write the image
    • Imagick::setFirstIterator - Sets the Imagick iterator to the first image
    • Imagick::setFont - Sets font
    • Imagick::setFormat - Sets the format of the Imagick object
    • Imagick::setGravity - Sets the gravity
    • Imagick::setImage - Replaces image in the object
    • Imagick::setImageAlphaChannel - Sets image alpha channel
    • Imagick::setImageArtifact - Set image artifact
    • Imagick::setImageAttribute - Sets an image attribute
    • Imagick::setImageBackgroundColor - Sets the image background color
    • Imagick::setImageBias - Sets the image bias for any method that convolves an image
    • Imagick::setImageBiasQuantum - Sets the image bias
    • Imagick::setImageBluePrimary - Sets the image chromaticity blue primary point
    • Imagick::setImageBorderColor - Sets the image border color
    • Imagick::setImageChannelDepth - Sets the depth of a particular image channel
    • Imagick::setImageClipMask - Sets image clip mask
    • Imagick::setImageColormapColor - Sets the color of the specified colormap index
    • Imagick::setImageColorspace - Sets the image colorspace
    • Imagick::setImageCompose - Sets the image composite operator
    • Imagick::setImageCompression - Sets the image compression
    • Imagick::setImageCompressionQuality - Sets the image compression quality
    • Imagick::setImageDelay - Sets the image delay
    • Imagick::setImageDepth - Sets the image depth
    • Imagick::setImageDispose - Sets the image disposal method
    • Imagick::setImageExtent - Sets the image size
    • Imagick::setImageFilename - Sets the filename of a particular image
    • Imagick::setImageFormat - Sets the format of a particular image
    • Imagick::setImageGamma - Sets the image gamma
    • Imagick::setImageGravity - Sets the image gravity
    • Imagick::setImageGreenPrimary - Sets the image chromaticity green primary point
    • Imagick::setImageIndex - Set the iterator position
    • Imagick::setImageInterlaceScheme - Sets the image compression
    • Imagick::setImageInterpolateMethod - Sets the image interpolate pixel method
    • Imagick::setImageIterations - Sets the image iterations
    • Imagick::setImageMatte - Sets the image matte channel
    • Imagick::setImageMatteColor - Sets the image matte color
    • Imagick::setImageOpacity - Sets the image opacity level
    • Imagick::setImageOrientation - Sets the image orientation
    • Imagick::setImagePage - Sets the page geometry of the image
    • Imagick::setImageProfile - Adds a named profile to the Imagick object
    • Imagick::setImageProperty - Sets an image property
    • Imagick::setImageRedPrimary - Sets the image chromaticity red primary point
    • Imagick::setImageRenderingIntent - Sets the image rendering intent
    • Imagick::setImageResolution - Sets the image resolution
    • Imagick::setImageScene - Sets the image scene
    • Imagick::setImageTicksPerSecond - Sets the image ticks-per-second
    • Imagick::setImageType - Sets the image type
    • Imagick::setImageUnits - Sets the image units of resolution
    • Imagick::setImageVirtualPixelMethod - Sets the image virtual pixel method
    • Imagick::setImageWhitePoint - Sets the image chromaticity white point
    • Imagick::setInterlaceScheme - Sets the image compression
    • Imagick::setIteratorIndex - Set the iterator position
    • Imagick::setLastIterator - Sets the Imagick iterator to the last image
    • Imagick::setOption - Set an option
    • Imagick::setPage - Sets the page geometry of the Imagick object
    • Imagick::setPointSize - Sets point size
    • Imagick::setProgressMonitor - Set a callback to be called during processing
    • Imagick::setRegistry - Sets the ImageMagick registry entry named key to value
    • Imagick::setResolution - Sets the image resolution
    • Imagick::setResourceLimit - Sets the limit for a particular resource
    • Imagick::setSamplingFactors - Sets the image sampling factors
    • Imagick::setSize - Sets the size of the Imagick object
    • Imagick::setSizeOffset - Sets the size and offset of the Imagick object
    • Imagick::setType - Sets the image type attribute
    • Imagick::shadeImage - Creates a 3D effect
    • Imagick::shadowImage - Simulates an image shadow
    • Imagick::sharpenImage - Sharpens an image
    • Imagick::shaveImage - Shaves pixels from the image edges
    • Imagick::shearImage - Creating a parallelogram
    • Imagick::sigmoidalContrastImage - Adjusts the contrast of an image
    • Imagick::sketchImage - Simulates a pencil sketch
    • Imagick::smushImages - Takes all images from the current image pointer to the end of the image list and smushs them
    • Imagick::solarizeImage - Applies a solarizing effect to the image
    • Imagick::sparseColorImage - Interpolates colors
    • Imagick::spliceImage - Splices a solid color into the image
    • Imagick::spreadImage - Randomly displaces each pixel in a block
    • Imagick::statisticImage - Modifies image using a statistics function
    • Imagick::steganoImage - Hides a digital watermark within the image
    • Imagick::stereoImage - Composites two images
    • Imagick::stripImage - Strips an image of all profiles and comments
    • Imagick::subImageMatch - Searches for a subimage in the current image and returns a similarity image
    • Imagick::swirlImage - Swirls the pixels about the center of the image
    • Imagick::textureImage - Repeatedly tiles the texture image
    • Imagick::thresholdImage - Changes the value of individual pixels based on a threshold
    • Imagick::thumbnailImage - Changes the size of an image
    • Imagick::tintImage - Applies a color vector to each pixel in the image
    • Imagick::transformImage - Convenience method for setting crop size and the image geometry
    • Imagick::transformImageColorspace - Transforms an image to a new colorspace
    • Imagick::transparentPaintImage - Paints pixels transparent
    • Imagick::transposeImage - Creates a vertical mirror image
    • Imagick::transverseImage - Creates a horizontal mirror image
    • Imagick::trimImage - Remove edges from the image
    • Imagick::uniqueImageColors - Discards all but one of any pixel color
    • Imagick::unsharpMaskImage - Sharpens an image
    • Imagick::valid - Checks if the current item is valid
    • Imagick::vignetteImage - Adds vignette filter to the image
    • Imagick::waveImage - Applies wave filter to the image
    • Imagick::whiteThresholdImage - Force all pixels above the threshold into white
    • Imagick::writeImage - Writes an image to the specified filename
    • Imagick::writeImageFile - Writes an image to a filehandle
    • Imagick::writeImages - Writes an image or image sequence
    • Imagick::writeImagesFile - Writes frames to a filehandle
    • Imagick::__construct - The Imagick constructor
    • Imagick::__toString - Returns the image as a string
    • ImagickDraw::affine - Adjusts the current affine transformation matrix
    • ImagickDraw::annotation - Draws text on the image
    • ImagickDraw::arc - Draws an arc
    • ImagickDraw::bezier - Draws a bezier curve
    • ImagickDraw::circle - Draws a circle
    • ImagickDraw::clear - Clears the ImagickDraw
    • ImagickDraw::clone - Makes an exact copy of the specified ImagickDraw object
    • ImagickDraw::color - Draws color on image
    • ImagickDraw::comment - Adds a comment
    • ImagickDraw::composite - Composites an image onto the current image
    • ImagickDraw::destroy - Frees all associated resources
    • ImagickDraw::ellipse - Draws an ellipse on the image
    • ImagickDraw::getClipPath - Obtains the current clipping path ID
    • ImagickDraw::getClipRule - Returns the current polygon fill rule
    • ImagickDraw::getClipUnits - Returns the interpretation of clip path units
    • ImagickDraw::getFillColor - Returns the fill color
    • ImagickDraw::getFillOpacity - Returns the opacity used when drawing
    • ImagickDraw::getFillRule - Returns the fill rule
    • ImagickDraw::getFont - Returns the font
    • ImagickDraw::getFontFamily - Returns the font family
    • ImagickDraw::getFontSize - Returns the font pointsize
    • ImagickDraw::getFontStretch - Gets the font stretch to use when annotating with text
    • ImagickDraw::getFontStyle - Returns the font style
    • ImagickDraw::getFontWeight - Returns the font weight
    • ImagickDraw::getGravity - Returns the text placement gravity
    • ImagickDraw::getStrokeAntialias - Returns the current stroke antialias setting
    • ImagickDraw::getStrokeColor - Returns the color used for stroking object outlines
    • ImagickDraw::getStrokeDashArray - Returns an array representing the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::getStrokeDashOffset - Returns the offset into the dash pattern to start the dash
    • ImagickDraw::getStrokeLineCap - Returns the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::getStrokeLineJoin - Returns the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::getStrokeMiterLimit - Returns the stroke miter limit
    • ImagickDraw::getStrokeOpacity - Returns the opacity of stroked object outlines
    • ImagickDraw::getStrokeWidth - Returns the width of the stroke used to draw object outlines
    • ImagickDraw::getTextAlignment - Returns the text alignment
    • ImagickDraw::getTextAntialias - Returns the current text antialias setting
    • ImagickDraw::getTextDecoration - Returns the text decoration
    • ImagickDraw::getTextEncoding - Returns the code set used for text annotations
    • ImagickDraw::getTextInterlineSpacing - Gets the text interword spacing
    • ImagickDraw::getTextInterwordSpacing - Gets the text interword spacing
    • ImagickDraw::getTextKerning - Gets the text kerning
    • ImagickDraw::getTextUnderColor - Returns the text under color
    • ImagickDraw::getVectorGraphics - Returns a string containing vector graphics
    • ImagickDraw::line - Draws a line
    • ImagickDraw::matte - Paints on the image's opacity channel
    • ImagickDraw::pathClose - Adds a path element to the current path
    • ImagickDraw::pathCurveToAbsolute - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierAbsolute - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierRelative - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative - Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToRelative - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothAbsolute - Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothRelative - Draws a cubic Bezier curve
    • ImagickDraw::pathEllipticArcAbsolute - Draws an elliptical arc
    • ImagickDraw::pathEllipticArcRelative - Draws an elliptical arc
    • ImagickDraw::pathFinish - Terminates the current path
    • ImagickDraw::pathLineToAbsolute - Draws a line path
    • ImagickDraw::pathLineToHorizontalAbsolute - Draws a horizontal line path
    • ImagickDraw::pathLineToHorizontalRelative - Draws a horizontal line
    • ImagickDraw::pathLineToRelative - Draws a line path
    • ImagickDraw::pathLineToVerticalAbsolute - Draws a vertical line
    • ImagickDraw::pathLineToVerticalRelative - Draws a vertical line path
    • ImagickDraw::pathMoveToAbsolute - Starts a new sub-path
    • ImagickDraw::pathMoveToRelative - Starts a new sub-path
    • ImagickDraw::pathStart - Declares the start of a path drawing list
    • ImagickDraw::point - Draws a point
    • ImagickDraw::polygon - Draws a polygon
    • ImagickDraw::polyline - Draws a polyline
    • ImagickDraw::pop - Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
    • ImagickDraw::popClipPath - Terminates a clip path definition
    • ImagickDraw::popDefs - Terminates a definition list
    • ImagickDraw::popPattern - Terminates a pattern definition
    • ImagickDraw::push - Clones the current ImagickDraw and pushes it to the stack
    • ImagickDraw::pushClipPath - Starts a clip path definition
    • ImagickDraw::pushDefs - Indicates that following commands create named elements for early processing
    • ImagickDraw::pushPattern - Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
    • ImagickDraw::rectangle - Draws a rectangle
    • ImagickDraw::render - Renders all preceding drawing commands onto the image
    • ImagickDraw::resetVectorGraphics - Resets the vector graphics
    • ImagickDraw::rotate - Applies the specified rotation to the current coordinate space
    • ImagickDraw::roundRectangle - Draws a rounded rectangle
    • ImagickDraw::scale - Adjusts the scaling factor
    • ImagickDraw::setClipPath - Associates a named clipping path with the image
    • ImagickDraw::setClipRule - Set the polygon fill rule to be used by the clipping path
    • ImagickDraw::setClipUnits - Sets the interpretation of clip path units
    • ImagickDraw::setFillAlpha - Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillColor - Sets the fill color to be used for drawing filled objects
    • ImagickDraw::setFillOpacity - Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillPatternURL - Sets the URL to use as a fill pattern for filling objects
    • ImagickDraw::setFillRule - Sets the fill rule to use while drawing polygons
    • ImagickDraw::setFont - Sets the fully-specified font to use when annotating with text
    • ImagickDraw::setFontFamily - Sets the font family to use when annotating with text
    • ImagickDraw::setFontSize - Sets the font pointsize to use when annotating with text
    • ImagickDraw::setFontStretch - Sets the font stretch to use when annotating with text
    • ImagickDraw::setFontStyle - Sets the font style to use when annotating with text
    • ImagickDraw::setFontWeight - Sets the font weight
    • ImagickDraw::setGravity - Sets the text placement gravity
    • ImagickDraw::setResolution - Sets the resolution
    • ImagickDraw::setStrokeAlpha - Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokeAntialias - Controls whether stroked outlines are antialiased
    • ImagickDraw::setStrokeColor - Sets the color used for stroking object outlines
    • ImagickDraw::setStrokeDashArray - Specifies the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::setStrokeDashOffset - Specifies the offset into the dash pattern to start the dash
    • ImagickDraw::setStrokeLineCap - Specifies the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::setStrokeLineJoin - Specifies the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::setStrokeMiterLimit - Specifies the miter limit
    • ImagickDraw::setStrokeOpacity - Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokePatternURL - Sets the pattern used for stroking object outlines
    • ImagickDraw::setStrokeWidth - Sets the width of the stroke used to draw object outlines
    • ImagickDraw::setTextAlignment - Specifies a text alignment
    • ImagickDraw::setTextAntialias - Controls whether text is antialiased
    • ImagickDraw::setTextDecoration - Specifies a decoration
    • ImagickDraw::setTextEncoding - Specifies the text code set
    • ImagickDraw::setTextInterlineSpacing - Sets the text interline spacing
    • ImagickDraw::setTextInterwordSpacing - Sets the text interword spacing
    • ImagickDraw::setTextKerning - Sets the text kerning
    • ImagickDraw::setTextUnderColor - Specifies the color of a background rectangle
    • ImagickDraw::setVectorGraphics - Sets the vector graphics
    • ImagickDraw::setViewbox - Sets the overall canvas size
    • ImagickDraw::skewX - Skews the current coordinate system in the horizontal direction
    • ImagickDraw::skewY - Skews the current coordinate system in the vertical direction
    • ImagickDraw::translate - Applies a translation to the current coordinate system
    • ImagickDraw::__construct - The ImagickDraw constructor
    • ImagickKernel::addKernel - Attach another kernel to a kernel list
    • ImagickKernel::addUnityKernel - Adds a Unity Kernel to the kernel list
    • ImagickKernel::fromBuiltIn - Create a kernel from a builtin in kernel
    • ImagickKernel::fromMatrix - Create a kernel from a 2d matrix of values
    • ImagickKernel::getMatrix - Get the 2d matrix of values used in this kernel
    • ImagickKernel::scale - Scales a kernel list by the given amount
    • ImagickKernel::separate - Separates a linked set of kernels and returns an array of ImagickKernels
    • ImagickPixel::clear - Clears resources associated with this object
    • ImagickPixel::destroy - Deallocates resources associated with this object
    • ImagickPixel::getColor - Returns the color
    • ImagickPixel::getColorAsString - Returns the color as a string
    • ImagickPixel::getColorCount - Returns the color count associated with this color
    • ImagickPixel::getColorQuantum - Returns the color of the pixel in an array as Quantum values
    • ImagickPixel::getColorValue - Gets the normalized value of the provided color channel
    • ImagickPixel::getColorValueQuantum - Gets the quantum value of a color in the ImagickPixel
    • ImagickPixel::getHSL - Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::getIndex - Gets the colormap index of the pixel wand
    • ImagickPixel::isPixelSimilar - Check the distance between this color and another
    • ImagickPixel::isPixelSimilarQuantum - Returns whether two colors differ by less than the specified distance
    • ImagickPixel::isSimilar - Check the distance between this color and another
    • ImagickPixel::setColor - Sets the color
    • ImagickPixel::setColorCount - Sets the color count associated with this color
    • ImagickPixel::setColorValue - Sets the normalized value of one of the channels
    • ImagickPixel::setColorValueQuantum - Sets the quantum value of a color element of the ImagickPixel
    • ImagickPixel::setHSL - Sets the normalized HSL color
    • ImagickPixel::setIndex - Sets the colormap index of the pixel wand
    • ImagickPixel::__construct - The ImagickPixel constructor
    • ImagickPixelIterator::clear - Clear resources associated with a PixelIterator
    • ImagickPixelIterator::destroy - Deallocates resources associated with a PixelIterator
    • ImagickPixelIterator::getCurrentIteratorRow - Returns the current row of ImagickPixel objects
    • ImagickPixelIterator::getIteratorRow - Returns the current pixel iterator row
    • ImagickPixelIterator::getNextIteratorRow - Returns the next row of the pixel iterator
    • ImagickPixelIterator::getPreviousIteratorRow - Returns the previous row
    • ImagickPixelIterator::newPixelIterator - Returns a new pixel iterator
    • ImagickPixelIterator::newPixelRegionIterator - Returns a new pixel iterator
    • ImagickPixelIterator::resetIterator - Resets the pixel iterator
    • ImagickPixelIterator::setIteratorFirstRow - Sets the pixel iterator to the first pixel row
    • ImagickPixelIterator::setIteratorLastRow - Sets the pixel iterator to the last pixel row
    • ImagickPixelIterator::setIteratorRow - Set the pixel iterator row
    • ImagickPixelIterator::syncIterator - Syncs the pixel iterator
    • ImagickPixelIterator::__construct - The ImagickPixelIterator constructor
    • imap_8bit - Convert an 8bit string to a quoted-printable string
    • imap_alerts - Returns all IMAP alert messages that have occurred
    • imap_append - Append a string message to a specified mailbox
    • imap_base64 - Decode BASE64 encoded text
    • imap_binary - Convert an 8bit string to a base64 string
    • imap_body - Read the message body
    • imap_bodystruct - Read the structure of a specified body section of a specific message
    • imap_check - Check current mailbox
    • imap_clearflag_full - Clears flags on messages
    • imap_close - Close an IMAP stream
    • imap_create - Sinônimo de imap_createmailbox
    • imap_createmailbox - Create a new mailbox
    • imap_delete - Mark a message for deletion from current mailbox
    • imap_deletemailbox - Delete a mailbox
    • imap_errors - Returns all of the IMAP errors that have occurred
    • imap_expunge - Delete all messages marked for deletion
    • imap_fetchbody - Fetch a particular section of the body of the message
    • imap_fetchheader - Returns header for a message
    • imap_fetchmime - Fetch MIME headers for a particular section of the message
    • imap_fetchstructure - Read the structure of a particular message
    • imap_fetchtext - Sinônimo de imap_body
    • imap_fetch_overview - Read an overview of the information in the headers of the given message
    • imap_gc - Clears IMAP cache
    • imap_getacl - Gets the ACL for a given mailbox
    • imap_getmailboxes - Read the list of mailboxes, returning detailed information on each one
    • imap_getsubscribed - List all the subscribed mailboxes
    • imap_get_quota - Retrieve the quota level settings, and usage statics per mailbox
    • imap_get_quotaroot - Retrieve the quota settings per user
    • imap_header - Sinônimo de imap_headerinfo
    • imap_headerinfo - Read the header of the message
    • imap_headers - Returns headers for all messages in a mailbox
    • imap_is_open - Check if the IMAP stream is still valid
    • imap_last_error - Gets the last IMAP error that occurred during this page request
    • imap_list - Read the list of mailboxes
    • imap_listmailbox - Sinônimo de imap_list
    • imap_listscan - Returns the list of mailboxes that matches the given text
    • imap_listsubscribed - Sinônimo de imap_lsub
    • imap_lsub - List all the subscribed mailboxes
    • imap_mail - Send an email message
    • imap_mailboxmsginfo - Get information about the current mailbox
    • imap_mail_compose - Create a MIME message based on given envelope and body sections
    • imap_mail_copy - Copy specified messages to a mailbox
    • imap_mail_move - Move specified messages to a mailbox
    • imap_mime_header_decode - Decode MIME header elements
    • imap_msgno - Gets the message sequence number for the given UID
    • imap_mutf7_to_utf8 - Decode a modified UTF-7 string to UTF-8
    • imap_num_msg - Gets the number of messages in the current mailbox
    • imap_num_recent - Gets the number of recent messages in current mailbox
    • imap_open - Open an IMAP stream to a mailbox
    • imap_ping - Check if the IMAP stream is still active
    • imap_qprint - Convert a quoted-printable string to an 8 bit string
    • imap_rename - Sinônimo de imap_renamemailbox
    • imap_renamemailbox - Rename an old mailbox to new mailbox
    • imap_reopen - Reopen IMAP stream to new mailbox
    • imap_rfc822_parse_adrlist - Parses an address string
    • imap_rfc822_parse_headers - Parse mail headers from a string
    • imap_rfc822_write_address - Returns a properly formatted email address given the mailbox, host, and personal info
    • imap_savebody - Save a specific body section to a file
    • imap_scan - Sinônimo de imap_listscan
    • imap_scanmailbox - Sinônimo de imap_listscan
    • imap_search - This function returns an array of messages matching the given search criteria
    • imap_setacl - Sets the ACL for a given mailbox
    • imap_setflag_full - Sets flags on messages
    • imap_set_quota - Sets a quota for a given mailbox
    • imap_sort - Gets and sort messages
    • imap_status - Returns status information on a mailbox
    • imap_subscribe - Subscribe to a mailbox
    • imap_thread - Returns a tree of threaded message
    • imap_timeout - Set or fetch imap timeout
    • imap_uid - This function returns the UID for the given message sequence number
    • imap_undelete - Unmark the message which is marked deleted
    • imap_unsubscribe - Unsubscribe from a mailbox
    • imap_utf7_decode - Decodes a modified UTF-7 encoded string
    • imap_utf7_encode - Converts ISO-8859-1 string to modified UTF-7 text
    • imap_utf8 - Converts MIME-encoded text to UTF-8
    • imap_utf8_to_mutf7 - Encode a UTF-8 string to modified UTF-7
    • implode - Join array elements with a string
    • inet_ntop - Converts a packed internet address to a human readable representation
    • inet_pton - Converts a human readable IP address to its packed in_addr representation
    • InfiniteIterator::next - Moves the inner Iterator forward or rewinds it
    • InfiniteIterator::__construct - Constructs an InfiniteIterator
    • inflate_add - Incrementally inflate encoded data
    • inflate_get_read_len - Get number of bytes read so far
    • inflate_get_status - Get decompression status
    • inflate_init - Initialize an incremental inflate context
    • ini_alter - Sinônimo de ini_set
    • ini_get - Gets the value of a configuration option
    • ini_get_all - Gets all configuration options
    • ini_parse_quantity - Get interpreted size from ini shorthand syntax
    • ini_restore - Restores the value of a configuration option
    • ini_set - Sets the value of a configuration option
    • inotify_add_watch - Add a watch to an initialized inotify instance
    • inotify_init - Initialize an inotify instance
    • inotify_queue_len - Return a number upper than zero if there are pending events
    • inotify_read - Read events from an inotify instance
    • inotify_rm_watch - Remove an existing watch from an inotify instance
    • intdiv - Divisão de inteiros
    • interface_exists - Verifica se a interface foi definida
    • InternalIterator::current - Retorna o elemento atual
    • InternalIterator::key - Retorna a chave do elemento atual
    • InternalIterator::next - Move para o próximo elemento
    • InternalIterator::rewind - Retreocede o Iterator para o primeiro elemento
    • InternalIterator::valid - Verifica se a posição atual é válida
    • InternalIterator::__construct - Construtor privado para não permitir instanciação direta
    • IntlBreakIterator::createCharacterInstance - Create break iterator for boundaries of combining character sequences
    • IntlBreakIterator::createCodePointInstance - Create break iterator for boundaries of code points
    • IntlBreakIterator::createLineInstance - Create break iterator for logically possible line breaks
    • IntlBreakIterator::createSentenceInstance - Create break iterator for sentence breaks
    • IntlBreakIterator::createTitleInstance - Create break iterator for title-casing breaks
    • IntlBreakIterator::createWordInstance - Create break iterator for word breaks
    • IntlBreakIterator::current - Get index of current position
    • IntlBreakIterator::first - Set position to the first character in the text
    • IntlBreakIterator::following - Advance the iterator to the first boundary following specified offset
    • IntlBreakIterator::getErrorCode - Get last error code on the object
    • IntlBreakIterator::getErrorMessage - Get last error message on the object
    • IntlBreakIterator::getLocale - Get the locale associated with the object
    • IntlBreakIterator::getPartsIterator - Create iterator for navigating fragments between boundaries
    • IntlBreakIterator::getText - Get the text being scanned
    • IntlBreakIterator::isBoundary - Tell whether an offset is a boundary's offset
    • IntlBreakIterator::last - Set the iterator position to index beyond the last character
    • IntlBreakIterator::next - Advance the iterator the next boundary
    • IntlBreakIterator::preceding - Set the iterator position to the first boundary before an offset
    • IntlBreakIterator::previous - Set the iterator position to the boundary immediately before the current
    • IntlBreakIterator::setText - Set the text being scanned
    • IntlBreakIterator::__construct - Private constructor for disallowing instantiation
    • IntlCalendar::add - Add a (signed) amount of time to a field
    • IntlCalendar::after - Whether this object's time is after that of the passed object
    • IntlCalendar::before - Whether this object's time is before that of the passed object
    • IntlCalendar::clear - Clear a field or all fields
    • IntlCalendar::createInstance - Create a new IntlCalendar
    • IntlCalendar::equals - Compare time of two IntlCalendar objects for equality
    • IntlCalendar::fieldDifference - Calculate difference between given time and this object's time
    • IntlCalendar::fromDateTime - Create an IntlCalendar from a DateTime object or string
    • IntlCalendar::get - Get the value for a field
    • IntlCalendar::getActualMaximum - The maximum value for a field, considering the object's current time
    • IntlCalendar::getActualMinimum - The minimum value for a field, considering the object's current time
    • IntlCalendar::getAvailableLocales - Get array of locales for which there is data
    • IntlCalendar::getDayOfWeekType - Tell whether a day is a weekday, weekend or a day that has a transition between the two
    • IntlCalendar::getErrorCode - Get last error code on the object
    • IntlCalendar::getErrorMessage - Get last error message on the object
    • IntlCalendar::getFirstDayOfWeek - Get the first day of the week for the calendar's locale
    • IntlCalendar::getGreatestMinimum - Get the largest local minimum value for a field
    • IntlCalendar::getKeywordValuesForLocale - Get set of locale keyword values
    • IntlCalendar::getLeastMaximum - Get the smallest local maximum for a field
    • IntlCalendar::getLocale - Get the locale associated with the object
    • IntlCalendar::getMaximum - Get the global maximum value for a field
    • IntlCalendar::getMinimalDaysInFirstWeek - Get minimal number of days the first week in a year or month can have
    • IntlCalendar::getMinimum - Get the global minimum value for a field
    • IntlCalendar::getNow - Get number representing the current time
    • IntlCalendar::getRepeatedWallTimeOption - Get behavior for handling repeating wall time
    • IntlCalendar::getSkippedWallTimeOption - Get behavior for handling skipped wall time
    • IntlCalendar::getTime - Get time currently represented by the object
    • IntlCalendar::getTimeZone - Get the object's timezone
    • IntlCalendar::getType - Get the calendar type
    • IntlCalendar::getWeekendTransition - Get time of the day at which weekend begins or ends
    • IntlCalendar::inDaylightTime - Whether the object's time is in Daylight Savings Time
    • IntlCalendar::isEquivalentTo - Whether another calendar is equal but for a different time
    • IntlCalendar::isLenient - Whether date/time interpretation is in lenient mode
    • IntlCalendar::isSet - Whether a field is set
    • IntlCalendar::isWeekend - Whether a certain date/time is in the weekend
    • IntlCalendar::roll - Add value to field without carrying into more significant fields
    • IntlCalendar::set - Set a time field or several common fields at once
    • IntlCalendar::setDate - Set a date fields
    • IntlCalendar::setDateTime - Set a date and time fields
    • IntlCalendar::setFirstDayOfWeek - Set the day on which the week is deemed to start
    • IntlCalendar::setLenient - Set whether date/time interpretation is to be lenient
    • IntlCalendar::setMinimalDaysInFirstWeek - Set minimal number of days the first week in a year or month can have
    • IntlCalendar::setRepeatedWallTimeOption - Set behavior for handling repeating wall times at negative timezone offset transitions
    • IntlCalendar::setSkippedWallTimeOption - Set behavior for handling skipped wall times at positive timezone offset transitions
    • IntlCalendar::setTime - Set the calendar time in milliseconds since the epoch
    • IntlCalendar::setTimeZone - Set the timezone used by this calendar
    • IntlCalendar::toDateTime - Convert an IntlCalendar into a DateTime object
    • IntlCalendar::__construct - Private constructor for disallowing instantiation
    • IntlChar::charAge - Get the "age" of the code point
    • IntlChar::charDigitValue - Get the decimal digit value of a decimal digit character
    • IntlChar::charDirection - Get bidirectional category value for a code point
    • IntlChar::charFromName - Find Unicode character by name and return its code point value
    • IntlChar::charMirror - Get the "mirror-image" character for a code point
    • IntlChar::charName - Retrieve the name of a Unicode character
    • IntlChar::charType - Get the general category value for a code point
    • IntlChar::chr - Return Unicode character by code point value
    • IntlChar::digit - Get the decimal digit value of a code point for a given radix
    • IntlChar::enumCharNames - Enumerate all assigned Unicode characters within a range
    • IntlChar::enumCharTypes - Enumerate all code points with their Unicode general categories
    • IntlChar::foldCase - Perform case folding on a code point
    • IntlChar::forDigit - Get character representation for a given digit and radix
    • IntlChar::getBidiPairedBracket - Get the paired bracket character for a code point
    • IntlChar::getBlockCode - Get the Unicode allocation block containing a code point
    • IntlChar::getCombiningClass - Get the combining class of a code point
    • IntlChar::getFC_NFKC_Closure - Get the FC_NFKC_Closure property for a code point
    • IntlChar::getIntPropertyMaxValue - Get the max value for a Unicode property
    • IntlChar::getIntPropertyMinValue - Get the min value for a Unicode property
    • IntlChar::getIntPropertyValue - Get the value for a Unicode property for a code point
    • IntlChar::getNumericValue - Get the numeric value for a Unicode code point
    • IntlChar::getPropertyEnum - Get the property constant value for a given property name
    • IntlChar::getPropertyName - Get the Unicode name for a property
    • IntlChar::getPropertyValueEnum - Get the property value for a given value name
    • IntlChar::getPropertyValueName - Get the Unicode name for a property value
    • IntlChar::getUnicodeVersion - Get the Unicode version
    • IntlChar::hasBinaryProperty - Check a binary Unicode property for a code point
    • IntlChar::isalnum - Check if code point is an alphanumeric character
    • IntlChar::isalpha - Check if code point is a letter character
    • IntlChar::isbase - Check if code point is a base character
    • IntlChar::isblank - Check if code point is a "blank" or "horizontal space" character
    • IntlChar::iscntrl - Check if code point is a control character
    • IntlChar::isdefined - Check whether the code point is defined
    • IntlChar::isdigit - Check if code point is a digit character
    • IntlChar::isgraph - Check if code point is a graphic character
    • IntlChar::isIDIgnorable - Check if code point is an ignorable character
    • IntlChar::isIDPart - Check if code point is permissible in an identifier
    • IntlChar::isIDStart - Check if code point is permissible as the first character in an identifier
    • IntlChar::isISOControl - Check if code point is an ISO control code
    • IntlChar::isJavaIDPart - Check if code point is permissible in a Java identifier
    • IntlChar::isJavaIDStart - Check if code point is permissible as the first character in a Java identifier
    • IntlChar::isJavaSpaceChar - Check if code point is a space character according to Java
    • IntlChar::islower - Check if code point is a lowercase letter
    • IntlChar::isMirrored - Check if code point has the Bidi_Mirrored property
    • IntlChar::isprint - Check if code point is a printable character
    • IntlChar::ispunct - Check if code point is punctuation character
    • IntlChar::isspace - Check if code point is a space character
    • IntlChar::istitle - Check if code point is a titlecase letter
    • IntlChar::isUAlphabetic - Check if code point has the Alphabetic Unicode property
    • IntlChar::isULowercase - Check if code point has the Lowercase Unicode property
    • IntlChar::isupper - Check if code point has the general category "Lu" (uppercase letter)
    • IntlChar::isUUppercase - Check if code point has the Uppercase Unicode property
    • IntlChar::isUWhiteSpace - Check if code point has the White_Space Unicode property
    • IntlChar::isWhitespace - Check if code point is a whitespace character according to ICU
    • IntlChar::isxdigit - Check if code point is a hexadecimal digit
    • IntlChar::ord - Return Unicode code point value of character
    • IntlChar::tolower - Make Unicode character lowercase
    • IntlChar::totitle - Make Unicode character titlecase
    • IntlChar::toupper - Make Unicode character uppercase
    • IntlCodePointBreakIterator::getLastCodePoint - Obtém o último code point passado após avançar ou retroceder o iterador
    • IntlDateFormatter::create - Create a date formatter
    • IntlDateFormatter::format - Format the date/time value as a string
    • IntlDateFormatter::formatObject - Formats an object
    • IntlDateFormatter::getCalendar - Get the calendar type used for the IntlDateFormatter
    • IntlDateFormatter::getCalendarObject - Get copy of formatter's calendar object
    • IntlDateFormatter::getDateType - Get the datetype used for the IntlDateFormatter
    • IntlDateFormatter::getErrorCode - Get the error code from last operation
    • IntlDateFormatter::getErrorMessage - Get the error text from the last operation
    • IntlDateFormatter::getLocale - Get the locale used by formatter
    • IntlDateFormatter::getPattern - Get the pattern used for the IntlDateFormatter
    • IntlDateFormatter::getTimeType - Get the timetype used for the IntlDateFormatter
    • IntlDateFormatter::getTimeZone - Get formatter's timezone
    • IntlDateFormatter::getTimeZoneId - Get the timezone-id used for the IntlDateFormatter
    • IntlDateFormatter::isLenient - Get the lenient used for the IntlDateFormatter
    • IntlDateFormatter::localtime - Parse string to a field-based time value
    • IntlDateFormatter::parse - Parse string to a timestamp value
    • IntlDateFormatter::setCalendar - Sets the calendar type used by the formatter
    • IntlDateFormatter::setLenient - Set the leniency of the parser
    • IntlDateFormatter::setPattern - Set the pattern used for the IntlDateFormatter
    • IntlDateFormatter::setTimeZone - Sets formatter's timezone
    • IntlDatePatternGenerator::create - Creates a new IntlDatePatternGenerator instance
    • IntlDatePatternGenerator::getBestPattern - Determines the most suitable date/time format
    • IntlGregorianCalendar::createFromDate - Create a new IntlGregorianCalendar instance from date
    • IntlGregorianCalendar::createFromDateTime - Create a new IntlGregorianCalendar instance from date and time
    • IntlGregorianCalendar::getGregorianChange - Get the Gregorian Calendar change date
    • IntlGregorianCalendar::isLeapYear - Determine if the given year is a leap year
    • IntlGregorianCalendar::setGregorianChange - Set the Gregorian Calendar the change date
    • IntlGregorianCalendar::__construct - Create the Gregorian Calendar class
    • IntlIterator::current - Retorna o elemento atual
    • IntlIterator::key - Retorna a chave do elemento atual
    • IntlIterator::next - Avança para o próximo elemento
    • IntlIterator::rewind - Rebobina o iterador para o primeiro elemento
    • IntlIterator::valid - Verifica se a posição atual é válida
    • IntlPartsIterator::getBreakIterator - Obtém o IntlBreakIterator que é utilizado pelo iterador
    • IntlRuleBasedBreakIterator::getBinaryRules - Get the binary form of compiled rules
    • IntlRuleBasedBreakIterator::getRules - Get the rule set used to create this object
    • IntlRuleBasedBreakIterator::getRuleStatus - Get the largest status value from the break rules that determined the current break position
    • IntlRuleBasedBreakIterator::getRuleStatusVec - Get the status values from the break rules that determined the current break position
    • IntlRuleBasedBreakIterator::__construct - Create iterator from ruleset
    • IntlTimeZone::countEquivalentIDs - Get the number of IDs in the equivalency group that includes the given ID
    • IntlTimeZone::createDefault - Create a new copy of the default timezone for this host
    • IntlTimeZone::createEnumeration - Get an enumeration over time zone IDs associated with the given country or offset
    • IntlTimeZone::createTimeZone - Create a timezone object for the given ID
    • IntlTimeZone::createTimeZoneIDEnumeration - Get an enumeration over system time zone IDs with the given filter conditions
    • IntlTimeZone::fromDateTimeZone - Create a timezone object from DateTimeZone
    • IntlTimeZone::getCanonicalID - Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
    • IntlTimeZone::getDisplayName - Get a name of this time zone suitable for presentation to the user
    • IntlTimeZone::getDSTSavings - Get the amount of time to be added to local standard time to get local wall clock time
    • IntlTimeZone::getEquivalentID - Get an ID in the equivalency group that includes the given ID
    • IntlTimeZone::getErrorCode - Get last error code on the object
    • IntlTimeZone::getErrorMessage - Get last error message on the object
    • IntlTimeZone::getGMT - Create GMT (UTC) timezone
    • IntlTimeZone::getID - Get timezone ID
    • IntlTimeZone::getIDForWindowsID - Translate a Windows timezone into a system timezone
    • IntlTimeZone::getOffset - Get the time zone raw and GMT offset for the given moment in time
    • IntlTimeZone::getRawOffset - Get the raw GMT offset (before taking daylight savings time into account
    • IntlTimeZone::getRegion - Get the region code associated with the given system time zone ID
    • IntlTimeZone::getTZDataVersion - Get the timezone data version currently used by ICU
    • IntlTimeZone::getUnknown - Get the "unknown" time zone
    • IntlTimeZone::getWindowsID - Translate a system timezone into a Windows timezone
    • IntlTimeZone::hasSameRules - Check if this zone has the same rules and offset as another zone
    • IntlTimeZone::toDateTimeZone - Convert to DateTimeZone object
    • IntlTimeZone::useDaylightTime - Check if this time zone uses daylight savings time
    • IntlTimeZone::__construct - Private constructor to disallow direct instantiation
    • intl_error_name - Get symbolic name for a given error code
    • intl_get_error_code - Get the last error code
    • intl_get_error_message - Get description of the last error
    • intl_is_failure - Check whether the given error code indicates failure
    • intval - Obtém o valor em número inteiro de uma variável
    • in_array - Checa se um valor existe em um array
    • ip2long - Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer
    • iptcembed - Embeds binary IPTC data into a JPEG image
    • iptcparse - Parse a binary IPTC block into single tags
    • isset - Determina se uma variável está declarada e é diferente de null
    • is_a - Verifica se um objeto é ou herda de uma classe
    • is_array - Verifica se a variável é um array
    • is_bool - Verifica se a variável é um booleano
    • is_callable - Verifica se um valor pode ser chamado como uma função a partir do escopo atual.
    • is_countable - Verifica se o conteúdo de uma variável é um valor contável
    • is_dir - Diz se o caminho é um diretório
    • is_double - Sinônimo de is_float
    • is_executable - Diz se um arquivo é executável
    • is_file - Informa se o arquivo é um arquivo comum
    • is_finite - Verifica se um float é finito
    • is_float - Verifica se a variável é do tipo float
    • is_infinite - Verifica se um float é infinito
    • is_int - Informa se o tipo de uma variável é um inteiro
    • is_integer - Sinônimo de is_int
    • is_iterable - Verifica se o conteúdo de uma variável é um valor iterável
    • is_link - Informa se o arquivo é uma ligação simbólica
    • is_long - Sinônimo de is_int
    • is_nan - Verifica se um float é NAN
    • is_null - Verifica se uma variável é null
    • is_numeric - Verifica se uma variável é um número ou uma string numérica
    • is_object - Verifica se uma variável é um objeto
    • is_readable - Diz se o arquivo existe e se ele pode ser lido
    • is_real - Sinônimo de is_float
    • is_resource - Verifica se uma variável é um recurso
    • is_scalar - Verifica se é uma váriavel é escalar
    • is_soap_fault - Checks if a SOAP call has failed
    • is_string - Verifica se o tipo de uma variável é string
    • is_subclass_of - Verifica se o objeto tem esta classe como uma de suas classes pai
    • is_tainted - Checks whether a string is tainted
    • is_uploaded_file - Informa se o arquivo foi enviado por POST HTTP
    • is_writable - Diz se o arquivo pode ser modificado
    • is_writeable - Sinônimo de is_writable
    • Iterator::current - Retorna o elemento atual
    • Iterator::key - Retorna a chave do elemento atual
    • Iterator::next - Move para o próximo elemento
    • Iterator::rewind - Retreocede o Iterator para o primeiro elemento
    • Iterator::valid - Verifica se a posição atual é válida
    • IteratorAggregate::getIterator - Recupera um iterator externo
    • IteratorIterator::current - Get the current value
    • IteratorIterator::getInnerIterator - Get the inner iterator
    • IteratorIterator::key - Get the key of the current element
    • IteratorIterator::next - Forward to the next element
    • IteratorIterator::rewind - Rewind to the first element
    • IteratorIterator::valid - Checks if the iterator is valid
    • IteratorIterator::__construct - Create an iterator from anything that is traversable
    • iterator_apply - Call a function for every element in an iterator
    • iterator_count - Count the elements in an iterator
    • iterator_to_array - Copia o iterador em um array
  • j
    • jddayofweek - Returns the day of the week
    • jdmonthname - Retorna o nome de um mês
    • jdtofrench - Converte do calendário "Julian Day Count" para o calendário Republicano Francês
    • jdtogregorian - Converte uma data no formato "Julian Day Count" para o formato Gregoriano
    • jdtojewish - Converts a Julian day count to a Jewish calendar date
    • jdtojulian - Converte uma data do calendário "Julian Day Count" para o calendário "Julian"
    • jdtounix - Converte do formato de dada Juliana para Unix timestamp
    • jewishtojd - Converte uma data do calendário Judaico para o calendário "Julian Day Count"
    • join - Sinônimo de implode
    • jpeg2wbmp - Convert JPEG image file to WBMP image file
    • JsonSerializable::jsonSerialize - Especifique os dados que devem ser serializados para JSON
    • json_decode - Decodifica uma string JSON
    • json_encode - Retorna a representação JSON de um valor
    • json_last_error - Retorna o último erro ocorrido
    • json_last_error_msg - Retorna uma string contento a mensagem de erro da última chamada de json_encode() ou json_decode()
    • json_validate - Checks if a string contains valid JSON
    • juliantojd - Converte datas no formato "Julian" para o formato "Julian Day Count"
  • k
    • key - Retorna uma chave de um array
    • key_exists - Sinônimo de array_key_exists
    • krsort - Ordena um array pelas chaves em ordem descrescente
    • ksort - Ordena um array pelas chaves em ordem crescente
  • l
    • lcfirst - Torna minúsculo o primeiro caractere de uma string
    • lcg_value - Combined linear congruential generator
    • lchgrp - Modifica o grupo de porprietário da ligação simbólica
    • lchown - Modifica o proprietário da ligação simbólica
    • ldap_8859_to_t61 - Translate 8859 characters to t61 characters
    • ldap_add - Add entries to LDAP directory
    • ldap_add_ext - Add entries to LDAP directory
    • ldap_bind - Bind to LDAP directory
    • ldap_bind_ext - Bind to LDAP directory
    • ldap_close - Sinônimo de ldap_unbind
    • ldap_compare - Compare value of attribute found in entry specified with DN
    • ldap_connect - Connect to an LDAP server
    • ldap_connect_wallet - Connect to an LDAP server
    • ldap_control_paged_result - Send LDAP pagination control
    • ldap_control_paged_result_response - Retrieve the LDAP pagination cookie
    • ldap_count_entries - Count the number of entries in a search
    • ldap_count_references - Counts the number of references in a search result
    • ldap_delete - Delete an entry from a directory
    • ldap_delete_ext - Delete an entry from a directory
    • ldap_dn2ufn - Convert DN to User Friendly Naming format
    • ldap_err2str - Convert LDAP error number into string error message
    • ldap_errno - Return the LDAP error number of the last LDAP command
    • ldap_error - Return the LDAP error message of the last LDAP command
    • ldap_escape - Escape a string for use in an LDAP filter or DN
    • ldap_exop - Performs an extended operation
    • ldap_exop_passwd - PASSWD extended operation helper
    • ldap_exop_refresh - Refresh extended operation helper
    • ldap_exop_sync - Performs an extended operation
    • ldap_exop_whoami - WHOAMI extended operation helper
    • ldap_explode_dn - Splits DN into its component parts
    • ldap_first_attribute - Return first attribute
    • ldap_first_entry - Return first result id
    • ldap_first_reference - Return first reference
    • ldap_free_result - Free result memory
    • ldap_get_attributes - Get attributes from a search result entry
    • ldap_get_dn - Get the DN of a result entry
    • ldap_get_entries - Get all result entries
    • ldap_get_option - Get the current value for given option
    • ldap_get_values - Get all values from a result entry
    • ldap_get_values_len - Get all binary values from a result entry
    • ldap_list - Single-level search
    • ldap_modify - Sinônimo de ldap_mod_replace
    • ldap_modify_batch - Batch and execute modifications on an LDAP entry
    • ldap_mod_add - Add attribute values to current attributes
    • ldap_mod_add_ext - Add attribute values to current attributes
    • ldap_mod_del - Delete attribute values from current attributes
    • ldap_mod_del_ext - Delete attribute values from current attributes
    • ldap_mod_replace - Replace attribute values with new ones
    • ldap_mod_replace_ext - Replace attribute values with new ones
    • ldap_next_attribute - Get the next attribute in result
    • ldap_next_entry - Get next result entry
    • ldap_next_reference - Get next reference
    • ldap_parse_exop - Parse result object from an LDAP extended operation
    • ldap_parse_reference - Extract information from reference entry
    • ldap_parse_result - Extract information from result
    • ldap_read - Read an entry
    • ldap_rename - Modify the name of an entry
    • ldap_rename_ext - Modify the name of an entry
    • ldap_sasl_bind - Bind to LDAP directory using SASL
    • ldap_search - Search LDAP tree
    • ldap_set_option - Set the value of the given option
    • ldap_set_rebind_proc - Set a callback function to do re-binds on referral chasing
    • ldap_sort - Sort LDAP result entries on the client side
    • ldap_start_tls - Start TLS
    • ldap_t61_to_8859 - Translate t61 characters to 8859 characters
    • ldap_unbind - Unbind from LDAP directory
    • levenshtein - Calculate Levenshtein distance between two strings
    • libxml_clear_errors - Limpa o buffer de erro da libxml
    • libxml_disable_entity_loader - Disable the ability to load external entities
    • libxml_get_errors - Obtém um array de erros
    • libxml_get_external_entity_loader - Get the current external entity loader
    • libxml_get_last_error - Obtém o último erro da libxml
    • libxml_set_external_entity_loader - Changes the default external entity loader
    • libxml_set_streams_context - Define o contexto de fluxos para o próximo carregamento ou escrita de documento libxml
    • libxml_use_internal_errors - Desabilita erros da libxml e permite que o usuário obtenha informações de erro conforme necessário
    • LimitIterator::current - Get current element
    • LimitIterator::getPosition - Retorna a posição atual
    • LimitIterator::key - Get current key
    • LimitIterator::next - Avança o iterador
    • LimitIterator::rewind - Retorna o iterador para o começo especificado no construtor
    • LimitIterator::seek - Aponta para a posição especificada
    • LimitIterator::valid - Verifica se o elemento atual é válido ou não
    • LimitIterator::__construct - Construct a LimitIterator
    • link - Criando uma ligação rígida
    • linkinfo - Obtém informação sobre uma ligação
    • list - Cria variáveis como se fossem arrays
    • Locale::acceptFromHttp - Tries to find out best available locale based on HTTP "Accept-Language" header
    • Locale::canonicalize - Canonicalize the locale string
    • Locale::composeLocale - Returns a correctly ordered and delimited locale ID
    • Locale::filterMatches - Checks if a language tag filter matches with locale
    • Locale::getAllVariants - Gets the variants for the input locale
    • Locale::getDefault - Gets the default locale value from the INTL global 'default_locale'
    • Locale::getDisplayLanguage - Returns an appropriately localized display name for language of the inputlocale
    • Locale::getDisplayName - Returns an appropriately localized display name for the input locale
    • Locale::getDisplayRegion - Returns an appropriately localized display name for region of the input locale
    • Locale::getDisplayScript - Returns an appropriately localized display name for script of the input locale
    • Locale::getDisplayVariant - Returns an appropriately localized display name for variants of the input locale
    • Locale::getKeywords - Gets the keywords for the input locale
    • Locale::getPrimaryLanguage - Gets the primary language for the input locale
    • Locale::getRegion - Gets the region for the input locale
    • Locale::getScript - Gets the script for the input locale
    • Locale::lookup - Searches the language tag list for the best match to the language
    • Locale::parseLocale - Returns a key-value array of locale ID subtag elements
    • Locale::setDefault - Sets the default runtime locale
    • localeconv - Get numeric formatting information
    • localtime - Obtém o horário local
    • log - Logaritmo natural
    • log1p - Retorna log(1 + número), calculado de forma que seja preciso mesmo quando o valor do número seja próximo de zero.
    • log10 - Logaritmo na base 10
    • long2ip - Converts a long integer address into a string in (IPv4) Internet standard dotted format
    • lstat - Obtém informações sobre um arquivo ou ligação simbólica
    • ltrim - Retira espaços em branco (ou outros caracteres) do início de uma string
    • Lua::assign - Atribui uma variável PHP para o script Lua
    • Lua::call - Executa funções Lua
    • Lua::eval - Avalia uma string como código Lua
    • Lua::getVersion - Obtém a versão do interpretador Lua
    • Lua::include - Inclui e interpreta um arquivo de script Lua
    • Lua::registerCallback - Registra uma função PHP no interpretador Lua
    • Lua::__construct - Construtor Lua
    • LuaClosure::__invoke - Invoca uma closure lua
    • 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 - Compressão LZF
    • lzf_decompress - Descompressão LZF
    • lzf_optimized_for - Determina para quê a extensão LZF foi otimizada
  • m
    • mail - Envia e-mail
    • mailparse_determine_best_xfer_encoding - Gets the best way of encoding
    • mailparse_msg_create - Create a mime mail resource
    • mailparse_msg_extract_part - Extracts/decodes a message section
    • mailparse_msg_extract_part_file - Extracts/decodes a message section
    • mailparse_msg_extract_whole_part_file - Extracts a message section including headers without decoding the transfer encoding
    • mailparse_msg_free - Frees a MIME resource
    • mailparse_msg_get_part - Returns a handle on a given section in a mimemessage
    • mailparse_msg_get_part_data - Returns an associative array of info about the message
    • mailparse_msg_get_structure - Returns an array of mime section names in the supplied message
    • mailparse_msg_parse - Incrementally parse data into buffer
    • mailparse_msg_parse_file - Parses a file
    • mailparse_rfc822_parse_addresses - Parse RFC 822 compliant addresses
    • mailparse_stream_encode - Streams data from source file pointer, apply encoding and write to destfp
    • mailparse_uudecode_all - Scans the data from fp and extract each embedded uuencoded file
    • max - Localiza o maior valor
    • mb_check_encoding - Check if strings are valid for the specified encoding
    • mb_chr - Return character by Unicode code point value
    • mb_convert_case - Perform case folding on a string
    • mb_convert_encoding - Convert a string from one character encoding to another
    • mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
    • mb_convert_variables - Convert character code in variable(s)
    • mb_decode_mimeheader - Decode string in MIME header field
    • mb_decode_numericentity - Decode HTML numeric string reference to character
    • mb_detect_encoding - Detect character encoding
    • mb_detect_order - Set/Get character encoding detection order
    • mb_encode_mimeheader - Encode string for MIME header
    • mb_encode_numericentity - Encode character to HTML numeric string reference
    • mb_encoding_aliases - Get aliases of a known encoding type
    • mb_ereg - Regular expression match with multibyte support
    • mb_eregi - Regular expression match ignoring case with multibyte support
    • mb_eregi_replace - Replace regular expression with multibyte support ignoring case
    • mb_ereg_match - Regular expression match for multibyte string
    • mb_ereg_replace - Replace regular expression with multibyte support
    • mb_ereg_replace_callback - Perform a regular expression search and replace with multibyte support using a callback
    • mb_ereg_search - Multibyte regular expression match for predefined multibyte string
    • mb_ereg_search_getpos - Returns start point for next regular expression match
    • mb_ereg_search_getregs - Retrieve the result from the last multibyte regular expression match
    • mb_ereg_search_init - Setup string and regular expression for a multibyte regular expression match
    • mb_ereg_search_pos - Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
    • mb_ereg_search_regs - Returns the matched part of a multibyte regular expression
    • mb_ereg_search_setpos - Set start point of next regular expression match
    • mb_get_info - Get internal settings of mbstring
    • mb_http_input - Detect HTTP input character encoding
    • mb_http_output - Set/Get HTTP output character encoding
    • mb_internal_encoding - Set/Get internal character encoding
    • mb_language - Set/Get current language
    • mb_list_encodings - Returns an array of all supported encodings
    • mb_ord - Get Unicode code point of character
    • mb_output_handler - Callback function converts character encoding in output buffer
    • mb_parse_str - Parse GET/POST/COOKIE data and set global variable
    • mb_preferred_mime_name - Get MIME charset string
    • mb_regex_encoding - Set/Get character encoding for multibyte regex
    • mb_regex_set_options - Set/Get the default options for mbregex functions
    • mb_scrub - Replace ill-formed byte sequences with the substitute character
    • mb_send_mail - Send encoded mail
    • mb_split - Split multibyte string using regular expression
    • mb_strcut - Get part of string
    • mb_strimwidth - Get truncated string with specified width
    • mb_stripos - Finds position of first occurrence of a string within another, case insensitive
    • mb_stristr - Finds first occurrence of a string within another, case insensitive
    • mb_strlen - Get string length
    • mb_strpos - Find position of first occurrence of string in a string
    • mb_strrchr - Finds the last occurrence of a character in a string within another
    • mb_strrichr - Finds the last occurrence of a character in a string within another, case insensitive
    • mb_strripos - Finds position of last occurrence of a string within another, case insensitive
    • mb_strrpos - Find position of last occurrence of a string in a string
    • mb_strstr - Finds first occurrence of a string within another
    • mb_strtolower - Torna uma string minúscula
    • mb_strtoupper - Make a string uppercase
    • mb_strwidth - Return width of 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 - Set/Get substitution character
    • mb_substr - Get part of string
    • mb_substr_count - Count the number of substring occurrences
    • 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 - Calculate the md5 hash of a string
    • md5_file - Calculates the md5 hash of a given file
    • mdecrypt_generic - Decrypts data
    • Memcache::add - Add an item to the server
    • Memcache::addServer - Add a memcached server to connection pool
    • Memcache::close - Close memcached server connection
    • Memcache::connect - Open memcached server connection
    • Memcache::decrement - Decrement item's value
    • Memcache::delete - Delete item from the server
    • Memcache::flush - Flush all existing items at the server
    • Memcache::get - Retrieve item from the server
    • Memcache::getExtendedStats - Get statistics from all servers in pool
    • Memcache::getServerStatus - Returns server status
    • Memcache::getStats - Get statistics of the server
    • Memcache::getVersion - Return version of the server
    • Memcache::increment - Increment item's value
    • Memcache::pconnect - Open memcached server persistent connection
    • Memcache::replace - Replace value of the existing item
    • Memcache::set - Store data at the server
    • Memcache::setCompressThreshold - Enable automatic compression of large values
    • Memcache::setServerParams - Changes server parameters and status at runtime
    • Memcached::add - Adiciona um item em uma nova key
    • Memcached::addByKey - Adiciona um item sob uma nova key em um servidor específico
    • Memcached::addServer - Adiciona um servidor ao pool de servidores
    • Memcached::addServers - Adiciona múltiplos servidores ao pool de servidores
    • Memcached::append - Anexa dados a um item existente
    • Memcached::appendByKey - Anexa dados a um item existente em um servidor específico
    • Memcached::cas - Compara e troca um item
    • Memcached::casByKey - Compara e troca um item em um servidor específico
    • Memcached::decrement - Decrementa o valor do item numérico
    • Memcached::decrementByKey - Decrementa o valor do item numérico, armazenado em um servidor específico
    • Memcached::delete - Remover um item
    • Memcached::deleteByKey - Remover um item de um servidor específico
    • Memcached::deleteMulti - Remover vários itens
    • Memcached::deleteMultiByKey - Remover vários itens de um servidor específico
    • Memcached::fetch - Busca o próximo resultado
    • Memcached::fetchAll - Busca todos os resultados restantes
    • Memcached::flush - Invalida todos os itens no cache
    • Memcached::get - Recupera um item
    • Memcached::getAllKeys - Obtém as keys armazenadas em todos os servidores
    • Memcached::getByKey - Recupera item de um servidor específico
    • Memcached::getDelayed - Solicita vários itens
    • Memcached::getDelayedByKey - Solicita vários itens de um servidor específico
    • Memcached::getMulti - Recupera vários itens
    • Memcached::getMultiByKey - Recupere vários itens de um servidor específico
    • Memcached::getOption - Recupera um valor de opção do Memcached
    • Memcached::getResultCode - Retorna o código de resultado da última operação
    • Memcached::getResultMessage - Retorna a mensagem descrevendo o resultado da última operação
    • Memcached::getServerByKey - Mapear uma key para um servidor
    • Memcached::getServerList - Obtenha a lista dos servidores no pool
    • Memcached::getStats - Obtem estatísticas do pool de servidores
    • Memcached::getVersion - Obtem informações da versão do pool de servidores
    • Memcached::increment - Incrementa o valor do item numérico
    • Memcached::incrementByKey - Incrementa o valor do item numérico, armazenado em um servidor específico
    • Memcached::isPersistent - Verifica se uma conexão permanente com o memcache está sendo usada
    • Memcached::isPristine - Verifica se a instância foi criada recentemente
    • Memcached::prepend - Anexa dados a um item existente
    • Memcached::prependByKey - Anexa dados a um item existente em um servidor específico
    • Memcached::quit - Fecha todas as conexões abertas
    • Memcached::replace - Substitua o item em uma key existente
    • Memcached::replaceByKey - Substitua o item em uma key existente em um servidor específico
    • Memcached::resetServerList - Limpa todos os servidores da lista de servidores
    • Memcached::set - Armazena um item
    • Memcached::setByKey - Armazena um item em um servidor específico
    • Memcached::setMulti - Armazena vários itens
    • Memcached::setMultiByKey - Armazena vários itens em um servidor específico
    • Memcached::setOption - Define uma opção Memcached
    • Memcached::setOptions - Define opções do Memcached
    • Memcached::setSaslAuthData - Define as credenciais a serem usadas para autenticação
    • Memcached::touch - Define uma nova expiração para um item
    • Memcached::touchByKey - Define uma nova expiração para um item em um servidor específico
    • Memcached::__construct - Cria uma instância do Memcached
    • memcache_debug - Turn debug output on/off
    • memory_get_peak_usage - Returns the peak of memory allocated by PHP
    • memory_get_usage - Returns the amount of memory allocated to PHP
    • memory_reset_peak_usage - Reset the peak memory usage
    • MessageFormatter::create - Constructs a new Message Formatter
    • MessageFormatter::format - Format the message
    • MessageFormatter::formatMessage - Quick format message
    • MessageFormatter::getErrorCode - Get the error code from last operation
    • MessageFormatter::getErrorMessage - Get the error text from the last operation
    • MessageFormatter::getLocale - Get the locale for which the formatter was created
    • MessageFormatter::getPattern - Get the pattern used by the formatter
    • MessageFormatter::parse - Parse input string according to pattern
    • MessageFormatter::parseMessage - Quick parse input string
    • MessageFormatter::setPattern - Set the pattern used by the formatter
    • metaphone - Calculate the metaphone key of a string
    • method_exists - Verifica se o método da classe existe
    • mhash - Computa a hash
    • mhash_count - Obtém o ID de hash mais alto disponível
    • mhash_get_block_size - Obtém o tamanho de bloco da hash especificada
    • mhash_get_hash_name - Obtém o nome da hash especificada
    • mhash_keygen_s2k - Gera uma chave
    • microtime - Retorna um timestamp Unix com microsegundos
    • mime_content_type - Detecta o tipo de conteúdo MIME de um arquivo
    • min - Encontra o menor valor
    • mkdir - Cria um diretório
    • mktime - Obtém um timestamp Unix de uma data
    • money_format - Formata um número como uma string de moeda
    • 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\Document::fromBSON - Construct a new document instance from a BSON string
    • MongoDB\BSON\Document::fromJSON - Construct a new document instance from a JSON string
    • MongoDB\BSON\Document::fromPHP - Construct a new document instance from PHP data
    • MongoDB\BSON\Document::get - Returns the value of a key in the document
    • MongoDB\BSON\Document::getIterator - Returns an iterator for the BSON document
    • MongoDB\BSON\Document::has - Returns whether a key is present in the document
    • MongoDB\BSON\Document::serialize - Serialize a Document
    • MongoDB\BSON\Document::toCanonicalExtendedJSON - Returns the Canonical Extended JSON representation of the BSON document
    • MongoDB\BSON\Document::toPHP - Returns the PHP representation of the BSON document
    • MongoDB\BSON\Document::toRelaxedExtendedJSON - Returns the Relaxed Extended JSON representation of the BSON document
    • MongoDB\BSON\Document::unserialize - Unserialize a BSON document
    • MongoDB\BSON\Document::__construct - Construct a new BSON document (unused)
    • MongoDB\BSON\Document::__toString - Returns the string representation of this BSON Document
    • MongoDB\BSON\fromJSON - 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\Iterator::current - Returns the current element
    • MongoDB\BSON\Iterator::key - Returns the key of the current element
    • MongoDB\BSON\Iterator::next - Advances the iterator to next element
    • MongoDB\BSON\Iterator::rewind - Rewinds the Iterator to the first element
    • MongoDB\BSON\Iterator::valid - Checks if current position is valid
    • MongoDB\BSON\Iterator::__construct - Construct a new BSON iterator (unused)
    • MongoDB\BSON\Javascript::getCode - 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\PackedArray::fromPHP - Construct a new BSON array instance from PHP data
    • MongoDB\BSON\PackedArray::get - Returns the value of an index in the array
    • MongoDB\BSON\PackedArray::getIterator - Returns an iterator for the BSON array
    • MongoDB\BSON\PackedArray::has - Returns whether a index is present in the array
    • MongoDB\BSON\PackedArray::serialize - Serialize a BSON array
    • MongoDB\BSON\PackedArray::toPHP - Returns the PHP representation of the BSON array
    • MongoDB\BSON\PackedArray::unserialize - Unserialize a BSON array
    • MongoDB\BSON\PackedArray::__construct - Construct a new BSON array (unused)
    • MongoDB\BSON\PackedArray::__toString - Returns the string representation of this BSON array
    • MongoDB\BSON\Persistable::bsonSerialize - Provides an array or document to serialize as BSON
    • MongoDB\BSON\Regex::getFlags - 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\LogSubscriber::log - Notification method for a log message
    • 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 - Move um arquivo enviado para uma nova localização
    • mqseries_back - MQSeries MQBACK
    • mqseries_begin - MQseries MQBEGIN
    • mqseries_close - MQSeries MQCLOSE
    • mqseries_cmit - MQSeries MQCMIT
    • mqseries_conn - MQSeries MQCONN
    • mqseries_connx - MQSeries MQCONNX
    • mqseries_disc - MQSeries MQDISC
    • mqseries_get - MQSeries MQGET
    • mqseries_inq - MQSeries MQINQ
    • mqseries_open - MQSeries MQOPEN
    • mqseries_put - MQSeries MQPUT
    • mqseries_put1 - MQSeries MQPUT1
    • mqseries_set - MQSeries MQSET
    • mqseries_strerror - Returns the error message corresponding to a result code (MQRC)
    • msg_get_queue - Create or attach to a message queue
    • msg_queue_exists - Check whether a message queue exists
    • msg_receive - Receive a message from a message queue
    • msg_remove_queue - Destroy a message queue
    • msg_send - Send a message to a message queue
    • msg_set_queue - Set information in the message queue data structure
    • msg_stat_queue - Returns information from the message queue data structure
    • mt_getrandmax - 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 - Attaches iterator information
    • MultipleIterator::containsIterator - Checks if an iterator is attached
    • MultipleIterator::countIterators - Gets the number of attached iterator instances
    • MultipleIterator::current - Gets the registered iterator instances
    • MultipleIterator::detachIterator - Detaches an iterator
    • MultipleIterator::getFlags - Gets the flag information
    • MultipleIterator::key - Gets the registered iterator instances
    • MultipleIterator::next - Moves all attached iterator instances forward
    • MultipleIterator::rewind - Rewinds all attached iterator instances
    • MultipleIterator::setFlags - Sets flags
    • MultipleIterator::valid - Checks the validity of sub iterators
    • MultipleIterator::__construct - Constructs a new MultipleIterator
    • mysqli->errno - Retorna o código de erro para a chamada de função mais recente
    • mysqli->error - Retorna uma string descrevendo o último erro
    • mysqli::$affected_rows - Retorna o número de linhas afetadas pela operação MySQL anterior
    • mysqli::$client_info - Obtém informação do cliente MySQL
    • mysqli::$client_version - Retorna a versão do cliente MySQL como um inteiro
    • mysqli::$connect_errno - Retorna o código de erro da última chamada de conexão
    • mysqli::$connect_error - Retorna uma descrição do último erro de conexão
    • mysqli::$error_list - Retorna uma lista de erros do último comando executado
    • mysqli::$field_count - Retorna o número de campos para a consulta mais recente
    • mysqli::$host_info - Retorna uma string representando o tipo de conexão utilizada
    • mysqli::$info - Recupera informação sobre a recente consulta executada
    • mysqli::$insert_id - Retorna o valor gerado para uma coluna AUTO_INCREMENT pela última consulta
    • mysqli::$protocol_version - Retorna a versão do protocolo MySQL usada
    • mysqli::$server_info - Retorna a versão do servidor MySQL
    • mysqli::$server_version - Retorna a versão do servidor MySQL como um inteiro
    • mysqli::$sqlstate - Retorna o erro SQLSTATE da operação MySQL anterior
    • mysqli::$thread_id - Retorna o ID da thread para a conexão atual
    • mysqli::$warning_count - Retorna o número de avisos da última consulta para o link fornecido
    • mysqli::autocommit - Ativa ou desativa a gravação automática das modificações no banco de dados
    • mysqli::begin_transaction - Inicia uma transação
    • mysqli::change_user - Modifica o usuário para a conexão com o banco de dados especificada
    • mysqli::character_set_name - Retorna o conjunto de caracteres atual da conexão com o banco de dados
    • mysqli::close - Fecha uma conexão ao banco de dados previamente aberta
    • mysqli::commit - Grava a transação atual
    • mysqli::debug - Realiza operações de depuração
    • mysqli::dump_debug_info - Descarrega informação de debug no log
    • mysqli::escape_string - Sinônimo de mysqli_real_escape_string
    • mysqli::execute_query - Prepara, vincula parâmetros e executa a instrução SQL
    • mysqli::get_charset - Retorna um objeto de conjunto de caracteres
    • mysqli::get_connection_stats - Retorna estatísticas sobre a conexão do cliente
    • mysqli::get_warnings - Obtém o resultado de SHOW WARNINGS
    • mysqli::init - Inicializa o MySQLi e retorna um objeto a ser utilizado com mysqli_real_connect()
    • mysqli::kill - Solicita ao servidor o encerramento de um thread do MySQL
    • mysqli::more_results - Verifica se há mais algum resultado de uma consulta múltipla
    • mysqli::multi_query - Executa uma ou mais consultas no banco de dados
    • mysqli::next_result - Prepara o próximo resultado de multi_query
    • mysqli::options - Define opções
    • mysqli::ping - Faz ping em uma conexão de servidor ou tenta reconectar se a conexão cair
    • mysqli::poll - Sondagem de conexões
    • mysqli::prepare - Prepara uma instrução SQL para execução
    • mysqli::query - Executa uma consulta no banco de dados
    • mysqli::real_connect - Abre uma conexão com um servidor mysql
    • mysqli::real_escape_string - Escape caracteres especiais em uma string para uso em uma instrução SQL, levando em consideração o conjunto de caracteres atual da conexão
    • mysqli::real_query - Executa uma consulta SQL
    • mysqli::reap_async_query - Obtenha o resultado da consulta assíncrona
    • mysqli::refresh - Atualiza
    • mysqli::release_savepoint - Remove o ponto de salvamento nomeado do conjunto de pontos de salvamento da transação atual
    • mysqli::rollback - Reverte a transação atual
    • mysqli::savepoint - Define um ponto de salvamento de transação nomeado
    • mysqli::select_db - Seleciona o banco de dados padrão para consultas de banco de dados
    • mysqli::set_charset - Define o conjunto de caracteres do cliente
    • mysqli::set_opt - Sinônimo de mysqli_options
    • mysqli::ssl_set - Usado para estabelecer conexões seguras usando SSL
    • mysqli::stat - Obtém o status atual do sistema
    • mysqli::stmt_init - Inicializa uma instrução e retorna um objeto para uso com mysqli_stmt_prepare
    • mysqli::store_result - Transfere um conjunto de resultados da última consulta
    • mysqli::thread_safe - Retorna se a segurança de thread é dada ou não
    • mysqli::use_result - Iniciar uma recuperação de conjunto de resultados
    • mysqli::__construct - Abre uma nova conexão com o servidor MySQL
    • mysqli_connect - Sinônimo de mysqli::__construct
    • mysqli_driver::$report_mode - Define o modo de relatório de erros do mysqli
    • mysqli_driver::embedded_server_end - Para o servidor incorporado
    • mysqli_driver::embedded_server_start - Inicializa e dispara o servidor incorporado
    • mysqli_execute - Sinônimo de mysqli_stmt_execute
    • mysqli_get_client_stats - Retorna as estatísticas do cliente por processo
    • mysqli_get_links_stats - Retorna informações sobre links abertos e em cache
    • mysqli_report - Sinônimo de mysqli_driver->report_mode
    • mysqli_result::$current_field - Obtém o deslocamento atual de campo de um ponteiro de resultado
    • mysqli_result::$field_count - Obtém o número de campos no conjunto de resultados
    • mysqli_result::$lengths - Retorna os comprimentos das colunas da linha atual do resultado
    • mysqli_result::$num_rows - Obtém o número de linhas no resultado
    • mysqli_result::data_seek - Ajusta o ponteiro do resultado para uma linha arbritária no resultado
    • mysqli_result::fetch_all - Recebe todas as linhas de resultado como array associativo, numérico, ou ambos
    • mysqli_result::fetch_array - Recebe a próxima linha de resultado como array associativo, numérico, ou ambos
    • mysqli_result::fetch_assoc - Obtém a próxima linha do conjunto de resultados como um array associativo
    • mysqli_result::fetch_column - Recebe uma única coluna da próxima linha de um resultado
    • mysqli_result::fetch_field - Retorna o próximo campo no conjunto de resultados
    • mysqli_result::fetch_fields - Retorna um array de objetos representando os campos em um conjunto de resultados
    • mysqli_result::fetch_field_direct - Recebe metadados para um único campo
    • mysqli_result::fetch_object - Recebe a próxima linha de um resultado como um objeto
    • mysqli_result::fetch_row - Obtém a próxima linha de um resultado como um array enumerado
    • mysqli_result::field_seek - Move o ponteiro do resultado para um campo especificado
    • mysqli_result::free - Libera memória associada a um resultado
    • mysqli_result::getIterator - Obtém um iterador externo
    • mysqli_result::__construct - Constrói um objeto mysqli_result
    • mysqli_sql_exception::getSqlState - Retorna o código de erro SQLSTATE
    • mysqli_stmt::$affected_rows - Retorna o número total de linhas modificadas, apagadas, inseridas ou correspondidas pela última instrução executada
    • mysqli_stmt::$errno - Retorna o código de erro para a chamada de instrução mais recente
    • mysqli_stmt::$error - Retorna uma descrição em string para o último erro de instrução
    • mysqli_stmt::$error_list - Retorna uma lista de erros da última instrução executada
    • mysqli_stmt::$field_count - Retorna o número de colunas na instrução informada
    • mysqli_stmt::$insert_id - Obtém o ID gerado pela operação INSERT anterior
    • mysqli_stmt::$num_rows - Retorna o número de linhas recebidas pelo servidor
    • mysqli_stmt::$param_count - Retorna o número de parâmetros para uma instrução fornecida
    • mysqli_stmt::$sqlstate - Retorna o erro SQLSTATE da operação da instrução anterior
    • mysqli_stmt::attr_get - Usado para obter o valor atual de um atributo de instrução
    • mysqli_stmt::attr_set - Usado para modificar o comportamento de uma instrução preparada
    • mysqli_stmt::bind_param - Liga variáveis a uma declaração preparada como parâmetros
    • mysqli_stmt::bind_result - Liga variáveis a uma declaração preparada para armazenamento de resultado
    • mysqli_stmt::close - Fecha uma instrução preparada
    • mysqli_stmt::data_seek - Ajusta o ponteiro de resultado para uma linha arbitrária no resultado com buffer
    • mysqli_stmt::execute - Executa uma instrução preparada
    • mysqli_stmt::fetch - Recebe resultados de uma instrução preparada nas variáveis vinculadas
    • mysqli_stmt::free_result - Libera memória do resultado armazenado para o manipulador de instrução informado
    • mysqli_stmt::get_result - Obtém um resultado de uma instrução preparada como um objeto mysqli_result
    • mysqli_stmt::get_warnings - Obtém o resultado de SHOW WARNINGS
    • mysqli_stmt::more_results - Verifica se há mais resultados de uma consulta múltipla
    • mysqli_stmt::next_result - Lê o próximo resultado de uma consulta múltipla
    • mysqli_stmt::prepare - Prepara uma declaração SQL para execução
    • mysqli_stmt::reset - Redefine uma instrução preparada
    • mysqli_stmt::result_metadata - Retorna os metadados de resultado de uma instrução preparada
    • mysqli_stmt::send_long_data - Envia dados em blocos
    • mysqli_stmt::store_result - Armazena um conjunto de resultados em um buffer interno
    • mysqli_stmt::__construct - Constrói um novo objeto mysqli_stmt
    • mysqli_warning::next - Busca o próximo aviso
    • mysqli_warning::__construct - Construtor privado para proibir instanciação direta
    • mysql_affected_rows - Obtém o número de linhas afetadas na operação anterior do MySQL
    • mysql_client_encoding - Returns the name of the character set
    • mysql_close - Fecha a conexão MySQL
    • mysql_connect - Open a connection to a MySQL Server
    • mysql_create_db - Cria um banco de dados MySQL
    • mysql_data_seek - Move o ponteiro interno do resultado
    • mysql_db_name - Obtém o nome do banco de dados a partir da chamada à mysql_list_dbs
    • mysql_db_query - Selects a database and executes a query on it
    • mysql_drop_db - Drop (exclui) um banco de dados MySQL
    • mysql_errno - Retorna o valor numérico da mensagem de erro da operação MySQL anterior
    • mysql_error - Retorna o texto da mensagem de erro da operação MySQL anterior
    • mysql_escape_string - Escapa uma string para usá-la em uma função mysql_query
    • mysql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • mysql_fetch_assoc - Obtém uma linha do resultado como um array associativo
    • mysql_fetch_field - Get column information from a result and return as an object
    • mysql_fetch_lengths - Obtém o tamanho de cada saída de um resultado
    • mysql_fetch_object - Obtém o resultado de uma linha como um objeto
    • mysql_fetch_row - Obtém uma linha como um array numérico
    • mysql_field_flags - Get the flags associated with the specified field in a result
    • mysql_field_len - Retorna o tamanho do campo especificado
    • mysql_field_name - Obtém o nome do campo especificado em um resultado
    • mysql_field_seek - Define o ponteiro do resultado para o índice de campo especificado
    • mysql_field_table - Obtém o nome da tabela na qual o campo especificado esta
    • mysql_field_type - Obtém o tipo do campo especificado em um resultado
    • mysql_free_result - Free result memory
    • mysql_get_client_info - Obtém informações do cliente MySQL
    • mysql_get_host_info - Obtém informações do servidor MySQL
    • mysql_get_proto_info - Obtém informações do protocolo MySQL
    • mysql_get_server_info - Obtém informações do servidor MySQL
    • mysql_info - Obtém informação sobre a consulta mais recente
    • mysql_insert_id - Obtém o ID gerado pela operação INSERT anterior
    • mysql_list_dbs - Lista os bancos de dados disponíveis em um servidor MySQL
    • mysql_list_fields - Lista os campos de uma tabela MySQL
    • mysql_list_processes - Lista os processos MySQL
    • mysql_list_tables - List tables in a MySQL database
    • mysql_num_fields - Obtém o numero de campos em um resultado
    • mysql_num_rows - Obtém o número de linhas em um resultado
    • mysql_pconnect - Open a persistent connection to a MySQL server
    • mysql_ping - Pinga uma conexão com o servidor ou reconecta se não houver conexão
    • mysql_query - Send a MySQL query
    • mysql_real_escape_string - Escapes special characters in a string for use in an SQL statement
    • mysql_result - Get result data
    • mysql_select_db - Select a MySQL database
    • mysql_set_charset - Sets the client character set
    • mysql_stat - Get current system status
    • mysql_tablename - Get table name of field
    • mysql_thread_id - Return the current thread ID
    • mysql_unbuffered_query - Send an SQL query to MySQL without fetching and buffering the result rows
    • mysql_xdevapi\Client::close - Close client
  • n
    • natcasesort - Ordena um array utilizando o algoritmo da "ordem natural" sem diferenciar maiúsculas e minúsculas
    • natsort - Ordena um array utilizando o algoritmo de "ordem natural"
    • net_get_interfaces - Get network interfaces
    • next - Avança o ponteiro interno de um array
    • ngettext - Versão plural de gettext
    • nl2br - Inserts HTML line breaks before all newlines in a string
    • nl_langinfo - Query language and locale information
    • NoRewindIterator::current - Get the current value
    • NoRewindIterator::key - Get the current key
    • NoRewindIterator::next - Forward to the next element
    • NoRewindIterator::rewind - Prevents the rewind operation on the inner iterator
    • NoRewindIterator::valid - Validates the iterator
    • NoRewindIterator::__construct - Construct a NoRewindIterator
    • Normalizer::getRawDecomposition - Gets the Decomposition_Mapping property for the given UTF-8 encoded code point
    • Normalizer::isNormalized - Verifica se a string fornecida já está na forma normalizada na forma especificada.
    • Normalizer::normalize - Normaliza a entrada fornecida e retorna a string normalizada
    • NumberFormatter::create - Create a number formatter
    • NumberFormatter::format - Format a number
    • NumberFormatter::formatCurrency - Format a currency value
    • NumberFormatter::getAttribute - Get an attribute
    • NumberFormatter::getErrorCode - Get formatter's last error code
    • NumberFormatter::getErrorMessage - Get formatter's last error message
    • NumberFormatter::getLocale - Get formatter locale
    • NumberFormatter::getPattern - Get formatter pattern
    • NumberFormatter::getSymbol - Get a symbol value
    • NumberFormatter::getTextAttribute - Get a text attribute
    • NumberFormatter::parse - Parse a number
    • NumberFormatter::parseCurrency - Parse a currency number
    • NumberFormatter::setAttribute - Set an attribute
    • NumberFormatter::setPattern - Set formatter pattern
    • NumberFormatter::setSymbol - Set a symbol value
    • NumberFormatter::setTextAttribute - Set a text attribute
    • number_format - Format a number with grouped thousands
  • o
    • OAuth::disableDebug - Turn off verbose debugging
    • OAuth::disableRedirects - Turn off redirects
    • OAuth::disableSSLChecks - Turn off SSL checks
    • OAuth::enableDebug - Turn on verbose debugging
    • OAuth::enableRedirects - Turn on redirects
    • OAuth::enableSSLChecks - Turn on SSL checks
    • OAuth::fetch - Fetch an OAuth protected resource
    • OAuth::generateSignature - Generate a signature
    • OAuth::getAccessToken - Fetch an access token
    • OAuth::getCAPath - Gets CA information
    • OAuth::getLastResponse - Get the last response
    • OAuth::getLastResponseHeaders - Get headers for last response
    • OAuth::getLastResponseInfo - Get HTTP information about the last response
    • OAuth::getRequestHeader - Generate OAuth header string signature
    • OAuth::getRequestToken - Fetch a request token
    • OAuth::setAuthType - Set authorization type
    • OAuth::setCAPath - Set CA path and info
    • OAuth::setNonce - Set the nonce for subsequent requests
    • OAuth::setRequestEngine - The setRequestEngine purpose
    • OAuth::setRSACertificate - Set the RSA certificate
    • OAuth::setSSLChecks - Tweak specific SSL checks for requests
    • OAuth::setTimestamp - Set the timestamp
    • OAuth::setToken - Sets the token and secret
    • OAuth::setVersion - Set the OAuth version
    • OAuth::__construct - Create a new OAuth object
    • OAuth::__destruct - The destructor
    • OAuthProvider::addRequiredParameter - Add required parameters
    • OAuthProvider::callconsumerHandler - Calls the consumerNonceHandler callback
    • OAuthProvider::callTimestampNonceHandler - Calls the timestampNonceHandler callback
    • OAuthProvider::calltokenHandler - Calls the tokenNonceHandler callback
    • OAuthProvider::checkOAuthRequest - Check an oauth request
    • OAuthProvider::consumerHandler - Set the consumerHandler handler callback
    • OAuthProvider::generateToken - Generate a random token
    • OAuthProvider::is2LeggedEndpoint - is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint - Sets isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter - Remove a required parameter
    • OAuthProvider::reportProblem - Report a problem
    • OAuthProvider::setParam - Set a parameter
    • OAuthProvider::setRequestTokenPath - Set request token path
    • OAuthProvider::timestampNonceHandler - Set the timestampNonceHandler handler callback
    • OAuthProvider::tokenHandler - Set the tokenHandler handler callback
    • OAuthProvider::__construct - Constructs a new OAuthProvider object
    • oauth_get_sbs - Generate a Signature Base String
    • oauth_urlencode - Encode a URI to RFC 3986
    • ob_clean - Limpa (apaga) o buffer de saída
    • ob_end_clean - Clean (erase) the output buffer and turn off output buffering
    • ob_end_flush - Flush (send) the output buffer and turn off output buffering
    • ob_flush - Descarrega (envia) o buffer de saída
    • ob_get_clean - Get current buffer contents and delete current output buffer
    • ob_get_contents - Retorna o conteúdo do buffer de saída
    • ob_get_flush - Flush the output buffer, return it as a string and turn off output buffering
    • ob_get_length - Retorna o comprimento do buffer de saída
    • ob_get_level - Return the nesting level of the output buffering mechanism
    • ob_get_status - Get status of output buffers
    • ob_gzhandler - ob_start callback function to gzip output buffer
    • ob_iconv_handler - Converte codificação de caracteres como manipulador de buffer de saída
    • ob_implicit_flush - Turn implicit flush on/off
    • ob_list_handlers - List all output handlers in use
    • ob_start - Ativa o buffer de saída
    • ob_tidyhandler - ob_start callback function to repair the buffer
    • ocibindbyname - Sinônimo de oci_bind_by_name
    • ocicancel - Sinônimo de oci_cancel
    • ocicloselob - Sinônimo de OCILob::close
    • ocicollappend - Sinônimo de OCICollection::append
    • ocicollassign - Sinônimo de OCICollection::assign
    • ocicollassignelem - Sinônimo de OCICollection::assignElem
    • OCICollection::append - Appends element to the collection
    • OCICollection::assign - Assigns a value to the collection from another existing collection
    • OCICollection::assignElem - Assigns a value to the element of the collection
    • OCICollection::free - Frees the resources associated with the collection object
    • OCICollection::getElem - Returns value of the element
    • OCICollection::max - Returns the maximum number of elements in the collection
    • OCICollection::size - Returns size of the collection
    • OCICollection::trim - Trims elements from the end of the collection
    • ocicollgetelem - Sinônimo de OCICollection::getElem
    • ocicollmax - Sinônimo de OCICollection::max
    • ocicollsize - Sinônimo de OCICollection::size
    • ocicolltrim - Sinônimo de OCICollection::trim
    • ocicolumnisnull - Sinônimo de oci_field_is_null
    • ocicolumnname - Sinônimo de oci_field_name
    • ocicolumnprecision - Sinônimo de oci_field_precision
    • ocicolumnscale - Sinônimo de oci_field_scale
    • ocicolumnsize - Sinônimo de oci_field_size
    • ocicolumntype - Sinônimo de oci_field_type
    • ocicolumntyperaw - Sinônimo de oci_field_type_raw
    • ocicommit - Sinônimo de oci_commit
    • ocidefinebyname - Sinônimo de oci_define_by_name
    • ocierror - Sinônimo de oci_error
    • ociexecute - Sinônimo de oci_execute
    • ocifetch - Sinônimo de oci_fetch
    • ocifetchinto - Variante obsoleta de oci_fetch_array, oci_fetch_object, oci_fetch_assoc e oci_fetch_row
    • ocifetchstatement - Sinônimo de oci_fetch_all
    • ocifreecollection - Sinônimo de OCICollection::free
    • ocifreecursor - Sinônimo de oci_free_statement
    • ocifreedesc - Sinônimo de OCILob::free
    • ocifreestatement - Sinônimo de oci_free_statement
    • ociinternaldebug - Sinônimo de oci_internal_debug
    • ociloadlob - Sinônimo de OCILob::load
    • OCILob::append - Appends data from the large object to another large object
    • OCILob::close - Closes LOB descriptor
    • OCILob::eof - Tests for end-of-file on a large object's descriptor
    • OCILob::erase - Erases a specified portion of the internal LOB data
    • OCILob::export - Exports LOB's contents to a file
    • OCILob::flush - Flushes/writes buffer of the LOB to the server
    • OCILob::free - Frees resources associated with the LOB descriptor
    • OCILob::getBuffering - Returns current state of buffering for the large object
    • OCILob::import - Imports file data to the LOB
    • OCILob::load - Returns large object's contents
    • OCILob::read - Reads part of the large object
    • OCILob::rewind - Moves the internal pointer to the beginning of the large object
    • OCILob::save - Saves data to the large object
    • OCILob::saveFile - Sinônimo de OCILob::import
    • OCILob::seek - Sets the internal pointer of the large object
    • OCILob::setBuffering - Changes current state of buffering for the large object
    • OCILob::size - Returns size of large object
    • OCILob::tell - Returns the current position of internal pointer of large object
    • OCILob::truncate - Truncates large object
    • OCILob::write - Writes data to the large object
    • OCILob::writeTemporary - Escreve um large object temporário
    • OCILob::writeToFile - Sinônimo de OCILob::export
    • ocilogoff - Sinônimo de oci_close
    • ocilogon - Sinônimo de oci_connect
    • ocinewcollection - Sinônimo de oci_new_collection
    • ocinewcursor - Sinônimo de oci_new_cursor
    • ocinewdescriptor - Sinônimo de oci_new_descriptor
    • ocinlogon - Sinônimo de oci_new_connect
    • ocinumcols - Sinônimo de oci_num_fields
    • ociparse - Sinônimo de oci_parse
    • ociplogon - Sinônimo de oci_pconnect
    • ociresult - Sinônimo de oci_result
    • ocirollback - Sinônimo de oci_rollback
    • ocirowcount - Sinônimo de oci_num_rows
    • ocisavelob - Sinônimo de OCILob::save
    • ocisavelobfile - Sinônimo de OCILob::import
    • ociserverversion - Sinônimo de oci_server_version
    • ocisetprefetch - Sinônimo de oci_set_prefetch
    • ocistatementtype - Sinônimo de oci_statement_type
    • ociwritelobtofile - Sinônimo de OCILob::export
    • ociwritetemporarylob - Sinônimo de OCILob::writeTemporary
    • oci_bind_array_by_name - Binds a PHP array to an Oracle PL/SQL array parameter
    • oci_bind_by_name - Binds a PHP variable to an Oracle placeholder
    • oci_cancel - Cancels reading from cursor
    • oci_client_version - Returns the Oracle client library version
    • oci_close - Closes an Oracle connection
    • oci_commit - Commits the outstanding database transaction
    • oci_connect - Connect to an Oracle database
    • oci_define_by_name - Associates a PHP variable with a column for query fetches
    • oci_error - Returns the last error found
    • oci_execute - Executes a statement
    • oci_fetch - Fetches the next row from a query into internal buffers
    • oci_fetch_all - Fetches multiple rows from a query into a two-dimensional array
    • oci_fetch_array - Returns the next row from a query as an associative or numeric array
    • oci_fetch_assoc - Returns the next row from a query as an associative array
    • oci_fetch_object - Returns the next row from a query as an object
    • oci_fetch_row - Returns the next row from a query as a numeric array
    • oci_field_is_null - Checks if a field in the currently fetched row is null
    • oci_field_name - Returns the name of a field from the statement
    • oci_field_precision - Tell the precision of a field
    • oci_field_scale - Tell the scale of the field
    • oci_field_size - Returns field's size
    • oci_field_type - Returns a field's data type name
    • oci_field_type_raw - Tell the raw Oracle data type of the field
    • oci_free_descriptor - Frees a descriptor
    • oci_free_statement - Frees all resources associated with statement or cursor
    • oci_get_implicit_resultset - Returns the next child statement resource from a parent statement resource that has Oracle Database Implicit Result Sets
    • oci_internal_debug - Enables or disables internal debug output
    • oci_lob_copy - Copies large object
    • oci_lob_is_equal - Compares two LOB/FILE locators for equality
    • oci_new_collection - Allocates new collection object
    • oci_new_connect - Connect to the Oracle server using a unique connection
    • oci_new_cursor - Allocates and returns a new cursor (statement handle)
    • oci_new_descriptor - Initializes a new empty LOB or FILE descriptor
    • oci_num_fields - Returns the number of result columns in a statement
    • oci_num_rows - Returns number of rows affected during statement execution
    • oci_parse - Prepares an Oracle statement for execution
    • oci_password_change - Changes password of Oracle's user
    • oci_pconnect - Connect to an Oracle database using a persistent connection
    • oci_register_taf_callback - Register a user-defined callback function for Oracle Database TAF
    • oci_result - Returns field's value from the fetched row
    • oci_rollback - Rolls back the outstanding database transaction
    • oci_server_version - Returns the Oracle Database version
    • oci_set_action - Sets the action name
    • oci_set_call_timeout - Sets a millisecond timeout for database calls
    • oci_set_client_identifier - Sets the client identifier
    • oci_set_client_info - Sets the client information
    • oci_set_db_operation - Sets the database operation
    • oci_set_edition - Sets the database edition
    • oci_set_module_name - Sets the module name
    • oci_set_prefetch - Sets number of rows to be prefetched by queries
    • oci_set_prefetch_lob - Sets the amount of data prefetched for each CLOB or BLOB.
    • oci_statement_type - Returns the type of a statement
    • oci_unregister_taf_callback - Unregister a user-defined callback function for Oracle Database TAF
    • octdec - Octal para decimal
    • odbc_autocommit - Toggle autocommit behaviour
    • odbc_binmode - Handling of binary column data
    • odbc_close - Close an ODBC connection
    • odbc_close_all - Close all ODBC connections
    • odbc_columnprivileges - Lists columns and associated privileges for the given table
    • odbc_columns - Lists the column names in specified tables
    • odbc_commit - Commit an ODBC transaction
    • odbc_connect - Connect to a datasource
    • odbc_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 - Obtém o nome do cursor
    • odbc_data_source - Returns information about available DSNs
    • odbc_do - Sinônimo de odbc_exec
    • odbc_error - Get the last error code
    • odbc_errormsg - Get the last error message
    • odbc_exec - Directly execute an SQL statement
    • odbc_execute - Executa um comando preparado
    • odbc_fetch_array - Obtém uma linha do resultado como um array associativo
    • odbc_fetch_into - Fetch one result row into array
    • odbc_fetch_object - Obtém um conjunto de resultados como um objeto
    • odbc_fetch_row - Obtém uma linha
    • odbc_field_len - Obtém o tamanho (precisão) de um campo
    • odbc_field_name - Obtém o nome da coluna
    • odbc_field_num - Retorna o número da coluna
    • odbc_field_precision - Sinônimo de odbc_field_len
    • odbc_field_scale - Obtém a precisão de um campo
    • odbc_field_type - Tipo de dados de um campo
    • odbc_foreignkeys - Retrieves a list of foreign keys
    • odbc_free_result - Libera os recursos associados a um resultado
    • odbc_gettypeinfo - Retrieves information about data types supported by the data source
    • odbc_longreadlen - Manipulação de colunas LONG
    • odbc_next_result - Confere se resultados múltiplos estão disponíveis
    • odbc_num_fields - Número de colunas em um resultado
    • odbc_num_rows - Número de linhas em um resultado
    • odbc_pconnect - Open a persistent database connection
    • odbc_prepare - Prepara um comando para execução
    • odbc_primarykeys - Gets the primary keys for a table
    • odbc_procedurecolumns - Retrieve information about parameters to procedures
    • odbc_procedures - Get the list of procedures stored in a specific data source
    • odbc_result - Get result data
    • odbc_result_all - Mostra o resultado como uma tabela HTML
    • odbc_rollback - Rollback a transaction
    • odbc_setoption - Adjust ODBC settings
    • odbc_specialcolumns - Retrieves special columns
    • odbc_statistics - Retrieve statistics about a table
    • odbc_tableprivileges - Lists tables and the privileges associated with each table
    • odbc_tables - Get the list of table names stored in a specific data source
    • ogg:// - Streams de áudio
    • Opções de contexto de Socket - Lista de opções de contexto de Socket
    • Opções de contexto de SSL - Lista de opções de contexto de SSL
    • Opções de contexto do FTP - Lista de opções de contexto do FTP
    • Opções de contexto do HTTP - Lista de opções de contexto do HTTP
    • Opções de contexto do Phar - Lista de opções de contexto do Phar
    • Opções de contexto para Zip - Listagem de opções de contexto para Zip
    • Opções de contexto Zlib - Listagem de opções de contexto Zlib
    • opcache_compile_file - Compila e armazena em cache um script PHP sem executá-lo
    • opcache_get_configuration - Obtém informações de configuração sobre o cache
    • opcache_get_status - Obtém informações de status sobre o cache
    • opcache_invalidate - Invalida um script em cache
    • opcache_is_script_cached - Informa se um script é armazenado em cache no OPCache
    • opcache_reset - Redefine o conteúdo do cache opcode
    • openal_buffer_create - Generate OpenAL buffer
    • openal_buffer_data - Load a buffer with data
    • openal_buffer_destroy - Destroys an OpenAL buffer
    • openal_buffer_get - Retrieve an OpenAL buffer property
    • openal_buffer_loadwav - Load a .wav file into a buffer
    • openal_context_create - Create an audio processing context
    • openal_context_current - Make the specified context current
    • openal_context_destroy - Destroys a context
    • openal_context_process - Process the specified context
    • openal_context_suspend - Suspend the specified context
    • openal_device_close - Close an OpenAL device
    • openal_device_open - Initialize the OpenAL audio layer
    • openal_listener_get - Retrieve a listener property
    • openal_listener_set - Set a listener property
    • openal_source_create - Generate a source resource
    • openal_source_destroy - Destroy a source resource
    • openal_source_get - Retrieve an OpenAL source property
    • openal_source_pause - Pause the source
    • openal_source_play - Start playing the source
    • openal_source_rewind - Rewind the source
    • openal_source_set - Set source property
    • openal_source_stop - Stop playing the source
    • openal_stream - Begin streaming on a source
    • opendir - Abre um manipulador de diretório
    • openlog - Open connection to system logger
    • openssl_cipher_iv_length - Gets the cipher iv length
    • 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 - Exports a CSR as a string
    • openssl_csr_export_to_file - Exports a CSR to a file
    • openssl_csr_get_public_key - Returns the public key of a CSR
    • openssl_csr_get_subject - Returns the subject of a CSR
    • openssl_csr_new - Generates a CSR
    • openssl_csr_sign - Sign a CSR with another certificate (or itself) and generate a certificate
    • openssl_decrypt - Decrypts data
    • openssl_dh_compute_key - Computes shared secret for public value of remote DH public key and local DH key
    • openssl_digest - Computes a digest
    • openssl_encrypt - Encrypts data
    • openssl_error_string - Return openSSL error message
    • openssl_free_key - Free key resource
    • openssl_get_cert_locations - Retrieve the available certificate locations
    • openssl_get_cipher_methods - Gets available cipher methods
    • openssl_get_curve_names - Gets list of available curve names for ECC
    • openssl_get_md_methods - Gets available digest methods
    • openssl_get_privatekey - Sinônimo de openssl_pkey_get_private
    • openssl_get_publickey - Sinônimo de openssl_pkey_get_public
    • openssl_open - Open sealed data
    • openssl_pbkdf2 - Generates a PKCS5 v2 PBKDF2 string
    • openssl_pkcs7_decrypt - Decrypts an S/MIME encrypted message
    • openssl_pkcs7_encrypt - Encrypt an S/MIME message
    • openssl_pkcs7_read - Export the PKCS7 file to an array of PEM certificates
    • openssl_pkcs7_sign - Sign an S/MIME message
    • openssl_pkcs7_verify - Verifies the signature of an S/MIME signed message
    • openssl_pkcs12_export - Exports a PKCS#12 Compatible Certificate Store File to variable
    • openssl_pkcs12_export_to_file - Exports a PKCS#12 Compatible Certificate Store File
    • openssl_pkcs12_read - Parse a PKCS#12 Certificate Store into an array
    • openssl_pkey_derive - Computes shared secret for public value of remote and local DH or ECDH key
    • openssl_pkey_export - Gets an exportable representation of a key into a string
    • openssl_pkey_export_to_file - Gets an exportable representation of a key into a file
    • openssl_pkey_free - Frees a private key
    • openssl_pkey_get_details - Returns an array with the key details
    • openssl_pkey_get_private - Get a private key
    • openssl_pkey_get_public - Extract public key from certificate and prepare it for use
    • openssl_pkey_new - Generates a new private key
    • openssl_private_decrypt - Decrypts data with private key
    • openssl_private_encrypt - Encrypts data with private key
    • openssl_public_decrypt - Decrypts data with public key
    • openssl_public_encrypt - Encrypts data with public key
    • openssl_random_pseudo_bytes - Generate a pseudo-random string of bytes
    • openssl_seal - Seal (encrypt) data
    • openssl_sign - Generate signature
    • openssl_spki_export - Exports a valid PEM formatted public key signed public key and challenge
    • openssl_spki_export_challenge - Exports the challenge associated with a signed public key and challenge
    • openssl_spki_new - Generate a new signed public key and challenge
    • openssl_spki_verify - Verifies a signed public key and challenge
    • openssl_verify - Verify signature
    • openssl_x509_checkpurpose - Verifies if a certificate can be used for a particular purpose
    • openssl_x509_check_private_key - Checks if a private key corresponds to a certificate
    • openssl_x509_export - Exports a certificate as a string
    • openssl_x509_export_to_file - Exports a certificate to file
    • openssl_x509_fingerprint - Calculates the fingerprint, or digest, of a given X.509 certificate
    • openssl_x509_free - Free certificate resource
    • openssl_x509_parse - Parse an X509 certificate and return the information as an array
    • openssl_x509_read - Parse an X.509 certificate and return an object for it
    • openssl_x509_verify - Verifies digital signature of x509 certificate against a public key
    • ord - Converte o primeiro byte de uma string para um valor entre 0 e 255
    • OuterIterator::getInnerIterator - Returns the inner iterator for the current entry
    • output_add_rewrite_var - Add URL rewriter values
    • output_reset_rewrite_vars - Reset URL rewriter values
  • p
    • pack - Pack data into binary string
    • Parâmetros de contexto - Listagem de parâmetros de contexto
    • parallel\bootstrap - Bootstrapping
    • parallel\Channel::close - Closing
    • parallel\Channel::make - Access
    • parallel\Channel::open - Access
    • parallel\Channel::recv - Sharing
    • parallel\Channel::send - Sharing
    • parallel\Channel::__construct - Channel Construction
    • parallel\Events::addChannel - Targets
    • parallel\Events::addFuture - Targets
    • parallel\Events::poll - Polling
    • parallel\Events::remove - Targets
    • parallel\Events::setBlocking - Behaviour
    • parallel\Events::setInput - Input
    • parallel\Events::setTimeout - Behaviour
    • parallel\Events\Input::add - Inputs
    • parallel\Events\Input::clear - Inputs
    • parallel\Events\Input::remove - Inputs
    • parallel\Future::cancel - Cancellation
    • parallel\Future::cancelled - State Detection
    • parallel\Future::done - State Detection
    • parallel\Future::value - Resolution
    • parallel\run - Execution
    • parallel\Runtime::close - Runtime Graceful Join
    • parallel\Runtime::kill - Runtime Join
    • parallel\Runtime::run - Execution
    • parallel\Runtime::__construct - Runtime Construction
    • parallel\Sync::get - Access
    • parallel\Sync::notify - Synchronization
    • parallel\Sync::set - Access
    • parallel\Sync::wait - Synchronization
    • parallel\Sync::__construct - Construction
    • parallel\Sync::__invoke - Synchronization
    • ParentIterator::accept - Determines acceptability
    • ParentIterator::getChildren - Retorna os filhos do iterador interno de um ParentIterator
    • ParentIterator::hasChildren - Verifica se o elemento atual do iterador interno tem ou não filhos
    • ParentIterator::next - Avança o iterador
    • ParentIterator::rewind - Recomeça o iterador
    • ParentIterator::__construct - Constructs a ParentIterator
    • Parle\Lexer::advance - Process next lexer rule
    • Parle\Lexer::build - Finalize the lexer rule set
    • Parle\Lexer::callout - Define token callback
    • Parle\Lexer::consume - Pass the data for processing
    • Parle\Lexer::dump - Dump the state machine
    • Parle\Lexer::getToken - Retrieve the current token
    • Parle\Lexer::insertMacro - Insert regex macro
    • Parle\Lexer::push - Add a lexer rule
    • Parle\Lexer::reset - Reset lexer
    • Parle\Parser::advance - Process next parser rule
    • Parle\Parser::build - Finalize the grammar rules
    • Parle\Parser::consume - Consume the data for processing
    • Parle\Parser::dump - Dump the grammar
    • Parle\Parser::errorInfo - Retrieve the error information
    • Parle\Parser::left - Declare a token with left-associativity
    • Parle\Parser::nonassoc - Declare a token with no associativity
    • Parle\Parser::precedence - Declare a precedence rule
    • Parle\Parser::push - Add a grammar rule
    • Parle\Parser::reset - Reset parser state
    • Parle\Parser::right - Declare a token with right-associativity
    • Parle\Parser::sigil - Retrieve a matching part of a rule
    • Parle\Parser::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 - Interpreta um arquivo de configuração
    • parse_ini_string - Interpreta uma string de configuração
    • parse_str - Converte a string em variáveis
    • parse_url - Parse a URL and return its components
    • passthru - Execute an external program and display raw output
    • password_get_info - Retorna a informações sobre o hash fornecido
    • password_hash - Cria um hash de senha
    • password_needs_rehash - Verifica se o hash informado corresponde às opções especificadas
    • password_verify - Verifica se uma senha corresponde a um hash
    • pathinfo - Retorna informações sobre um caminho de arquivo
    • pclose - Fecha o ponteiro de arquivo de processo
    • 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 - Sinônimo 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 uma transação
    • PDO::commit - Envia uma transação
    • PDO::cubrid_schema - Get the requested schema information
    • PDO::errorCode - Fetch the SQLSTATE associated with the last operation on the database handle
    • PDO::errorInfo - Fetch extended error information associated with the last operation on the database handle
    • PDO::exec - Executa uma instrução SQL e retorna o número de linhas afetadas
    • PDO::getAttribute - Recuperar um atributo da conexão com o banco de dados
    • PDO::getAvailableDrivers - Retorna um array com os drivers PDO disponíveis
    • PDO::inTransaction - Checks if inside a transaction
    • PDO::lastInsertId - Returns the ID of the last inserted row or sequence value
    • PDO::pgsqlCopyFromArray - Copy data from PHP array into table
    • PDO::pgsqlCopyFromFile - Copy data from file into table
    • PDO::pgsqlCopyToArray - Copy data from database table into PHP array
    • PDO::pgsqlCopyToFile - Copy data from table into file
    • PDO::pgsqlGetNotify - Get asynchronous notification
    • PDO::pgsqlGetPid - Get the server PID
    • PDO::pgsqlLOBCreate - Creates a new large object
    • PDO::pgsqlLOBOpen - Opens an existing large object stream
    • PDO::pgsqlLOBUnlink - Deletes the large object
    • PDO::prepare - Prepares a statement for execution and returns a statement object
    • PDO::query - Prepares and executes an SQL statement without placeholders
    • PDO::quote - Quotes a string for use in a query
    • PDO::rollBack - Rolls back a transaction
    • PDO::setAttribute - Set an attribute
    • PDO::sqliteCreateAggregate - Registra uma função de agregação definida pelo usuário para uso em declarações SQL
    • PDO::sqliteCreateCollation - Registra uma Função Definida pelo Usuário para uso como função de collation em declarações SQL
    • PDO::sqliteCreateFunction - Registra uma Função Definida pelo Usuário para uso em declarações SQL
    • PDO::__construct - Creates a PDO instance representing a connection to a database
    • PDOStatement::bindColumn - Bind a column to a PHP variable
    • PDOStatement::bindParam - Binds a parameter to the specified variable name
    • PDOStatement::bindValue - Binds a value to a parameter
    • PDOStatement::closeCursor - Closes the cursor, enabling the statement to be executed again
    • PDOStatement::columnCount - Returns the number of columns in the result set
    • PDOStatement::debugDumpParams - Dump an SQL prepared command
    • PDOStatement::errorCode - Fetch the SQLSTATE associated with the last operation on the statement handle
    • PDOStatement::errorInfo - Fetch extended error information associated with the last operation on the statement handle
    • PDOStatement::execute - Executes a prepared statement
    • PDOStatement::fetch - Fetches the next row from a result set
    • PDOStatement::fetchAll - Fetches the remaining rows from a result set
    • PDOStatement::fetchColumn - Returns a single column from the next row of a result set
    • PDOStatement::fetchObject - Fetches the next row and returns it as an object
    • PDOStatement::getAttribute - Retrieve a statement attribute
    • PDOStatement::getColumnMeta - Returns metadata for a column in a result set
    • PDOStatement::getIterator - Gets result set iterator
    • PDOStatement::nextRowset - Advances to the next rowset in a multi-rowset statement handle
    • PDOStatement::rowCount - Returns the number of rows affected by the last SQL statement
    • PDOStatement::setAttribute - Define um atributo na instrução
    • PDOStatement::setFetchMode - Define o modo de carga de dados para esta instrução
    • PDO_CUBRID DSN - Connecting to CUBRID databases
    • PDO_DBLIB DSN - Connecting to Microsoft SQL Server and Sybase databases
    • PDO_FIREBIRD DSN - Connecting to Firebird databases
    • PDO_IBM DSN - Connecting to IBM databases
    • PDO_INFORMIX DSN - Connecting to Informix databases
    • PDO_MYSQL DSN - Conectando a bancos de dados MySQL
    • PDO_OCI DSN - Connecting to Oracle databases
    • PDO_ODBC DSN - Connecting to ODBC or DB2 databases
    • PDO_PGSQL DSN - Connecting to PostgreSQL databases
    • PDO_SQLSRV DSN - Connecting to MS SQL Server and SQL Azure databases
    • pfsockopen - Open persistent Internet or Unix domain socket connection
    • pg_affected_rows - Returns number of affected records (tuples)
    • pg_cancel_query - Cancel an asynchronous query
    • pg_client_encoding - Gets the client encoding
    • pg_close - Closes a PostgreSQL connection
    • pg_connect - Open a PostgreSQL connection
    • pg_connection_busy - Get connection is busy or not
    • pg_connection_reset - Reset connection (reconnect)
    • pg_connection_status - Get connection status
    • pg_connect_poll - Poll the status of an in-progress asynchronous PostgreSQL connection attempt
    • pg_consume_input - Reads input on the connection
    • pg_convert - Convert associative array values into forms suitable for SQL statements
    • pg_copy_from - Insert records into a table from an array
    • pg_copy_to - Copy a table to an array
    • pg_dbname - Get the database name
    • pg_delete - Deletes records
    • pg_end_copy - Sync with PostgreSQL backend
    • pg_escape_bytea - Escape a string for insertion into a bytea field
    • 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 - Sends a request to execute a prepared statement with given parameters, and waits for the result
    • pg_fetch_all - Fetches all rows from a result as an 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 - Returns the type name for the corresponding field number
    • 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 - Gets the backend's process ID
    • pg_get_result - Get asynchronous query result
    • pg_host - Returns the host name associated with the connection
    • pg_insert - Insert array into table
    • pg_last_error - Get the last error message string of a connection
    • pg_last_notice - Returns the last notice message from PostgreSQL server
    • 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 - Get the options associated with the connection
    • pg_parameter_status - Looks up a current parameter setting of the server
    • pg_pconnect - Open a persistent PostgreSQL connection
    • pg_ping - Ping database connection
    • pg_port - Return the port number associated with the connection
    • pg_prepare - Submits a request to create a prepared statement with the given parameters, and waits for completion
    • pg_put_line - Send a NULL-terminated string to PostgreSQL backend
    • pg_query - Execute a query
    • pg_query_params - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
    • pg_result_error - 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 - Sends a request to create a prepared statement with the given parameters, without waiting for completion
    • 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 - Get a read only handle to the socket underlying a PostgreSQL connection
    • pg_trace - Enable tracing a PostgreSQL connection
    • pg_transaction_status - Returns the current in-transaction status of the server
    • pg_tty - Return the TTY name associated with the connection
    • pg_unescape_bytea - Unescape binary for bytea type
    • pg_untrace - Disable tracing of a PostgreSQL connection
    • pg_update - Update table
    • pg_version - Returns an array with client, protocol and server version (when available)
    • phar:// - Arquivo PHP
    • Phar::addEmptyDir - Add an empty directory to the phar archive
    • Phar::addFile - Add a file from the filesystem to the phar archive
    • Phar::addFromString - Add a file from a string to the phar archive
    • Phar::apiVersion - Returns the api version
    • Phar::buildFromDirectory - Construct a phar archive from the files within a directory
    • Phar::buildFromIterator - Construct a phar archive from an iterator
    • Phar::canCompress - Returns whether phar extension supports compression using either zlib or bzip2
    • Phar::canWrite - Returns whether phar extension supports writing and creating phars
    • Phar::compress - Compresses the entire Phar archive using Gzip or Bzip2 compression
    • Phar::compressFiles - Compresses all files in the current Phar archive
    • Phar::convertToData - Convert a phar archive to a non-executable tar or zip file
    • Phar::convertToExecutable - Convert a phar archive to another executable phar archive file format
    • Phar::copy - Copy a file internal to the phar archive to another new file within the phar
    • Phar::count - Returns the number of entries (files) in the Phar archive
    • Phar::createDefaultStub - Create a phar-file format specific stub
    • Phar::decompress - Decompresses the entire Phar archive
    • Phar::decompressFiles - Decompresses all files in the current Phar archive
    • Phar::delete - Delete a file within a phar archive
    • Phar::delMetadata - Deletes the global metadata of the phar
    • Phar::extractTo - Extract the contents of a phar archive to a directory
    • Phar::getAlias - Get the alias for Phar
    • Phar::getMetadata - Returns phar archive meta-data
    • Phar::getModified - Return whether phar was modified
    • Phar::getPath - Get the real path to the Phar archive on disk
    • Phar::getSignature - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
    • Phar::getStub - Return the PHP loader or bootstrap stub of a Phar archive
    • Phar::getSupportedCompression - Return array of supported compression algorithms
    • Phar::getSupportedSignatures - Return array of supported signature types
    • Phar::getVersion - Return version info of Phar archive
    • Phar::hasMetadata - Returns whether phar has global meta-data
    • Phar::interceptFileFuncs - Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
    • Phar::isBuffering - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
    • Phar::isCompressed - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
    • Phar::isFileFormat - Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
    • Phar::isValidPharFilename - Returns whether the given filename is a valid phar filename
    • Phar::isWritable - Returns true if the phar archive can be modified
    • Phar::loadPhar - Loads any phar archive with an alias
    • Phar::mapPhar - Reads the currently executed file (a phar) and registers its manifest
    • Phar::mount - Mount an external path or file to a virtual location within the phar archive
    • Phar::mungServer - Defines a list of up to 4 $_SERVER variables that should be modified for execution
    • Phar::offsetExists - Determines whether a file exists in the phar
    • Phar::offsetGet - Gets a PharFileInfo object for a specific file
    • Phar::offsetSet - Set the contents of an internal file to those of an external file
    • Phar::offsetUnset - Remove a file from a phar
    • Phar::running - Returns the full path on disk or full phar URL to the currently executing Phar archive
    • Phar::setAlias - Set the alias for the Phar archive
    • Phar::setDefaultStub - Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
    • Phar::setMetadata - Sets phar archive meta-data
    • Phar::setSignatureAlgorithm - Set the signature algorithm for a phar and apply it
    • Phar::setStub - Used to set the PHP loader or bootstrap stub of a Phar archive
    • Phar::startBuffering - Start buffering Phar write operations, do not modify the Phar object on disk
    • Phar::stopBuffering - Stop buffering write requests to the Phar archive, and save changes to disk
    • Phar::unlinkArchive - Completely remove a phar archive from disk and from memory
    • Phar::webPhar - Routes a request from a web browser to an internal file within the phar archive
    • Phar::__construct - Construct a Phar archive object
    • Phar::__destruct - Destructs a Phar archive object
    • PharData::addEmptyDir - Add an empty directory to the tar/zip archive
    • PharData::addFile - Add a file from the filesystem to the tar/zip archive
    • PharData::addFromString - Add a file from a string to the tar/zip archive
    • PharData::buildFromDirectory - Construct a tar/zip archive from the files within a directory
    • PharData::buildFromIterator - Construct a tar or zip archive from an iterator
    • PharData::compress - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
    • PharData::compressFiles - Compresses all files in the current tar/zip archive
    • PharData::convertToData - Convert a phar archive to a non-executable tar or zip file
    • PharData::convertToExecutable - Convert a non-executable tar/zip archive to an executable phar archive
    • PharData::copy - Copy a file internal to the phar archive to another new file within the phar
    • PharData::decompress - Decompresses the entire Phar archive
    • PharData::decompressFiles - Decompresses all files in the current zip archive
    • PharData::delete - Delete a file within a tar/zip archive
    • PharData::delMetadata - Deletes the global metadata of a zip archive
    • PharData::extractTo - Extract the contents of a tar/zip archive to a directory
    • PharData::isWritable - Returns true if the tar/zip archive can be modified
    • PharData::offsetSet - Set the contents of a file within the tar/zip to those of an external file or string
    • PharData::offsetUnset - Remove a file from a tar/zip archive
    • PharData::setAlias - Dummy function (Phar::setAlias is not valid for PharData)
    • PharData::setDefaultStub - Dummy function (Phar::setDefaultStub is not valid for PharData)
    • PharData::setMetadata - Sets phar archive meta-data
    • PharData::setSignatureAlgorithm - Set the signature algorithm for a phar and apply it
    • PharData::setStub - Dummy function (Phar::setStub is not valid for PharData)
    • PharData::__construct - Construct a non-executable tar or zip archive object
    • PharData::__destruct - Destructs a non-executable tar or zip archive object
    • PharFileInfo::chmod - Sets file-specific permission bits
    • PharFileInfo::compress - Compresses the current Phar entry with either zlib or bzip2 compression
    • PharFileInfo::decompress - Decompresses the current Phar entry within the phar
    • PharFileInfo::delMetadata - Deletes the metadata of the entry
    • PharFileInfo::getCompressedSize - Returns the actual size of the file (with compression) inside the Phar archive
    • PharFileInfo::getContent - Get the complete file contents of the entry
    • PharFileInfo::getCRC32 - Returns CRC32 code or throws an exception if CRC has not been verified
    • PharFileInfo::getMetadata - Returns file-specific meta-data saved with a file
    • PharFileInfo::getPharFlags - Returns the Phar file entry flags
    • PharFileInfo::hasMetadata - Returns the metadata of the entry
    • PharFileInfo::isCompressed - Returns whether the entry is compressed
    • PharFileInfo::isCRCChecked - Returns whether file entry has had its CRC verified
    • PharFileInfo::setMetadata - Sets file-specific meta-data saved with a file
    • PharFileInfo::__construct - Construct a Phar entry object
    • PharFileInfo::__destruct - Destructs a Phar entry object
    • php:// - Acessando vários fluxos de E/S
    • phpcredits - Prints out the credits for PHP
    • phpdbg_break_file - Insere um ponto de interrupção em uma linha de um arquivo
    • phpdbg_break_function - Insere um ponto de interrupção na entrada de uma função
    • phpdbg_break_method - Insere um ponto de interrupção na entrada de um método
    • phpdbg_break_next - Insere um ponto de interrupção no próximo opcode
    • phpdbg_clear - Limpa todos os pontos de interrupção
    • phpdbg_color - Define a cor de certos elementos
    • phpdbg_end_oplog - Descrição
    • phpdbg_exec - Tenta definir o contexto de execução
    • phpdbg_get_executable - Descrição
    • phpdbg_prompt - Define o prompt de comando
    • phpdbg_start_oplog - Descrição
    • phpinfo - Outputs information about PHP's configuration
    • PhpToken::getTokenName - Returns the name of the token.
    • PhpToken::is - Tells whether the token is of given kind.
    • PhpToken::isIgnorable - Tells whether the token would be ignored by the PHP parser.
    • PhpToken::tokenize - Splits given source into PHP tokens, represented by PhpToken objects.
    • PhpToken::__construct - Returns a new PhpToken object
    • PhpToken::__toString - Returns the textual content of the token.
    • phpversion - Gets the current PHP version
    • php_ini_loaded_file - Retrieve a path to the loaded php.ini file
    • php_ini_scanned_files - Return a list of .ini files parsed from the additional ini dir
    • php_sapi_name - Returns the type of interface between web server and PHP
    • php_strip_whitespace - Retorna o código com comentários e espaços em branco removidos
    • php_uname - Returns information about the operating system PHP is running on
    • php_user_filter::filter - Chamada na aplicação do filtro
    • php_user_filter::onClose - Chamado no fechamento do filtro
    • php_user_filter::onCreate - Chamado na criação do filtro
    • pi - Obtém o valor de pi
    • png2wbmp - Convert PNG image file to WBMP image file
    • 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 um processo como ponteiro de arquivo
    • pos - Sinônimo de current
    • posix_access - Determine accessibility of a file
    • posix_ctermid - Get path name of controlling terminal
    • posix_eaccess - Determine accessibility of a file
    • posix_errno - Sinônimo de posix_get_last_error
    • posix_fpathconf - Returns the value of a configurable limit
    • posix_getcwd - Pathname of current directory
    • posix_getegid - Return the effective group ID of the current process
    • posix_geteuid - Return the effective user ID of the current process
    • posix_getgid - Return the real group ID of the current process
    • posix_getgrgid - Return info about a group by group id
    • posix_getgrnam - Return info about a group by name
    • posix_getgroups - Return the group set of the current process
    • posix_getlogin - Return login name
    • posix_getpgid - Get process group id for job control
    • posix_getpgrp - Return the current process group identifier
    • posix_getpid - Return the current process identifier
    • posix_getppid - Return the parent process identifier
    • posix_getpwnam - Return info about a user by username
    • posix_getpwuid - Return info about a user by user id
    • posix_getrlimit - Return info about system resource limits
    • posix_getsid - Get the current sid of the process
    • posix_getuid - Return the real user ID of the current process
    • posix_get_last_error - Retrieve the error number set by the last posix function that failed
    • posix_initgroups - Calculate the group access list
    • posix_isatty - Determine if a file descriptor is an interactive terminal
    • posix_kill - Send a signal to a process
    • posix_mkfifo - Create a fifo special file (a named pipe)
    • posix_mknod - Create a special or ordinary file (POSIX.1)
    • posix_pathconf - Returns the value of a configurable limit
    • posix_setegid - Set the effective GID of the current process
    • posix_seteuid - Set the effective UID of the current process
    • posix_setgid - Set the GID of the current process
    • posix_setpgid - Set process group id for job control
    • posix_setrlimit - Set system resource limits
    • posix_setsid - Make the current process a session leader
    • posix_setuid - Set the UID of the current process
    • posix_strerror - Retrieve the system error message associated with the given errno
    • posix_sysconf - Returns system runtime information
    • posix_times - Get process times
    • posix_ttyname - Determine terminal device name
    • posix_uname - Get system name
    • pow - Expressão exponencial
    • preg_filter - Perform a regular expression search and replace
    • preg_grep - Return array entries that match the pattern
    • preg_last_error - Retorna o código de erro da última expressão regular PCRE executada
    • preg_last_error_msg - Returns the error message of the last PCRE regex execution
    • preg_match - Perform a regular expression match
    • preg_match_all - Perform a global regular expression match
    • preg_quote - Quote regular expression characters
    • preg_replace - Realiza uma pesquisa por uma expressão regular e substitui
    • preg_replace_callback - Executa uma busca por expressão regular e substitui usando uma chamada de retorno
    • preg_replace_callback_array - Perform a regular expression search and replace using callbacks
    • preg_split - Split string by a regular expression
    • prev - Retrocede o ponteiro interno de um array
    • print - Mostra uma string
    • printf - Output a formatted string
    • print_r - Exibe informação legível sobre uma variável
    • proc_close - Close a process opened by proc_open and return the exit code of that process
    • proc_get_status - Obtem informação sobre um processo aberto por proc_open
    • proc_nice - Muda a prioridade do processo atual
    • proc_open - Execute a command and open file pointers for input/output
    • proc_terminate - Kills a process opened by proc_open
    • property_exists - Verifica se o objeto ou a classe tem uma propriedade
    • pspell_add_to_personal - Add the word to a personal wordlist
    • pspell_add_to_session - Add the word to the wordlist in the current session
    • pspell_check - Check a word
    • pspell_clear_session - Clear the current session
    • pspell_config_create - Create a config used to open a dictionary
    • pspell_config_data_dir - Location of language data files
    • pspell_config_dict_dir - Location of the main word list
    • pspell_config_ignore - Ignore words less than N characters long
    • pspell_config_mode - Change the mode number of suggestions returned
    • pspell_config_personal - Set a file that contains personal wordlist
    • pspell_config_repl - Set a file that contains replacement pairs
    • pspell_config_runtogether - Consider run-together words as valid compounds
    • pspell_config_save_repl - Determine whether to save a replacement pairs list along with the wordlist
    • pspell_new - Load a new dictionary
    • pspell_new_config - Load a new dictionary with settings based on a given config
    • pspell_new_personal - Load a new dictionary with personal wordlist
    • pspell_save_wordlist - Save the personal wordlist to a file
    • pspell_store_replacement - Store a replacement pair for a word
    • pspell_suggest - Suggest spellings of a word
    • ps_add_bookmark - Add bookmark to current page
    • ps_add_launchlink - Adds link which launches file
    • ps_add_locallink - Adds link to a page in the same document
    • ps_add_note - Adds note to current page
    • ps_add_pdflink - Adds link to a page in a second pdf document
    • ps_add_weblink - Adds link to a web location
    • ps_arc - Draws an arc counterclockwise
    • ps_arcn - Draws an arc clockwise
    • ps_begin_page - Start a new page
    • ps_begin_pattern - Start a new pattern
    • ps_begin_template - Start a new template
    • ps_circle - Draws a circle
    • ps_clip - Clips drawing to current path
    • ps_close - Closes a PostScript document
    • ps_closepath - Closes path
    • ps_closepath_stroke - Closes and strokes path
    • ps_close_image - Closes image and frees memory
    • ps_continue_text - Continue text in next line
    • ps_curveto - Draws a curve
    • ps_delete - Deletes all resources of a PostScript document
    • ps_end_page - End a page
    • ps_end_pattern - End a pattern
    • ps_end_template - End a template
    • ps_fill - Fills the current path
    • ps_fill_stroke - Fills and strokes the current path
    • ps_findfont - Loads a font
    • ps_get_buffer - Fetches the full buffer containig the generated PS data
    • ps_get_parameter - Gets certain parameters
    • ps_get_value - Gets certain values
    • ps_hyphenate - Hyphenates a word
    • ps_include_file - Reads an external file with raw PostScript code
    • ps_lineto - Draws a line
    • ps_makespotcolor - Create spot color
    • ps_moveto - Sets current point
    • ps_new - Creates a new PostScript document object
    • ps_open_file - Opens a file for output
    • ps_open_image - Reads an image for later placement
    • ps_open_image_file - Opens image from file
    • ps_open_memory_image - Takes an GD image and returns an image for placement in a PS document
    • ps_place_image - Places image on the page
    • ps_rect - Draws a rectangle
    • ps_restore - Restore previously save context
    • ps_rotate - Sets rotation factor
    • ps_save - Save current context
    • ps_scale - Sets scaling factor
    • ps_setcolor - Sets current color
    • ps_setdash - Sets appearance of a dashed line
    • ps_setflat - Sets flatness
    • ps_setfont - Sets font to use for following output
    • ps_setgray - Sets gray value
    • ps_setlinecap - Sets appearance of line ends
    • ps_setlinejoin - Sets how contected lines are joined
    • ps_setlinewidth - Sets width of a line
    • ps_setmiterlimit - Sets the miter limit
    • ps_setoverprintmode - Sets overprint mode
    • ps_setpolydash - Sets appearance of a dashed line
    • ps_set_border_color - Sets color of border for annotations
    • ps_set_border_dash - Sets length of dashes for border of annotations
    • ps_set_border_style - Sets border style of annotations
    • ps_set_info - Sets information fields of document
    • ps_set_parameter - Sets certain parameters
    • ps_set_text_pos - Sets position for text output
    • ps_set_value - Sets certain values
    • ps_shading - Creates a shading for later use
    • ps_shading_pattern - Creates a pattern based on a shading
    • ps_shfill - Fills an area with a shading
    • ps_show - Output text
    • ps_show2 - Output a text at current position
    • ps_show_boxed - Output text in a box
    • ps_show_xy - Output text at given position
    • ps_show_xy2 - Output text at position
    • ps_stringwidth - Gets width of a string
    • ps_string_geometry - Gets geometry of a string
    • ps_stroke - Draws the current path
    • ps_symbol - Output a glyph
    • ps_symbol_name - Gets name of a glyph
    • ps_symbol_width - Gets width of a glyph
    • ps_translate - Sets translation
    • putenv - Define o valor de uma variável de ambiente
  • 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 - Converte uma string Quoted-Printable para uma string de 8 bits
    • quoted_printable_encode - Converte uma string de 8 bits para uma string Quoted-Printable
    • quotemeta - Quote meta characters
  • r
    • rad2deg - Converte o número em radianos para o equivalente em graus
    • radius_acct_open - Creates a Radius handle for accounting
    • radius_add_server - Adds a server
    • radius_auth_open - Creates a Radius handle for authentication
    • radius_close - Frees all ressources
    • radius_config - Causes the library to read the given configuration file
    • radius_create_request - Create accounting or authentication request
    • radius_cvt_addr - Converts raw data to IP-Address
    • radius_cvt_int - Converts raw data to integer
    • radius_cvt_string - Converts raw data to string
    • radius_demangle - Demangles data
    • radius_demangle_mppe_key - Derives mppe-keys from mangled data
    • radius_get_attr - Extracts an attribute
    • radius_get_tagged_attr_data - Extracts the data from a tagged attribute
    • radius_get_tagged_attr_tag - Extracts the tag from a tagged attribute
    • radius_get_vendor_attr - Extracts a vendor specific attribute
    • radius_put_addr - Attaches an IP address attribute
    • radius_put_attr - Attaches a binary attribute
    • radius_put_int - Attaches an integer attribute
    • radius_put_string - Attaches a string attribute
    • radius_put_vendor_addr - Attaches a vendor specific IP address attribute
    • radius_put_vendor_attr - Attaches a vendor specific binary attribute
    • radius_put_vendor_int - Attaches a vendor specific integer attribute
    • radius_put_vendor_string - Attaches a vendor specific string attribute
    • radius_request_authenticator - Returns the request authenticator
    • radius_salt_encrypt_attr - Salt-encrypts a value
    • radius_send_request - Sends the request and waits for a reply
    • radius_server_secret - Returns the shared secret
    • radius_strerror - Returns an error message
    • rand - 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 - Cria um array contendo uma faixa de elementos
    • rar:// - RAR
    • RarArchive::close - Close RAR archive and free all resources
    • RarArchive::getComment - Get comment text from the RAR archive
    • RarArchive::getEntries - Get full list of entries from the RAR archive
    • RarArchive::getEntry - Get entry object from the RAR archive
    • RarArchive::isBroken - Test whether an archive is broken (incomplete)
    • RarArchive::isSolid - Check whether the RAR archive is solid
    • RarArchive::open - Open RAR archive
    • RarArchive::setAllowBroken - Whether opening broken archives is allowed
    • RarArchive::__toString - Get text representation
    • RarEntry::extract - Extract entry from the archive
    • RarEntry::getAttr - Get attributes of the entry
    • RarEntry::getCrc - Get CRC of the entry
    • RarEntry::getFileTime - Get entry last modification time
    • RarEntry::getHostOs - Get entry host OS
    • RarEntry::getMethod - Get pack method of the entry
    • RarEntry::getName - Get name of the entry
    • RarEntry::getPackedSize - Get packed size of the entry
    • RarEntry::getStream - Get file handler for entry
    • RarEntry::getUnpackedSize - Get unpacked size of the entry
    • RarEntry::getVersion - Get minimum version of RAR program required to unpack the entry
    • RarEntry::isDirectory - Test whether an entry represents a directory
    • RarEntry::isEncrypted - Test whether an entry is encrypted
    • RarEntry::__toString - Get text representation of entry
    • RarException::isUsingExceptions - Check whether error handling with exceptions is in use
    • RarException::setUsingExceptions - Activate and deactivate error handling with exceptions
    • rar_wrapper_cache_stats - Cache hits and misses for the URL wrapper
    • rawurldecode - Decodifica uma URL
    • rawurlencode - Codifica uma URL de acordo com RFC 3986
    • readdir - Lê entrada do manipulador do diretório
    • readfile - Exibe o conteúdo de um arquivo
    • readgzfile - Output a gz-file
    • readline - Lê uma linha
    • readline_add_history - Adiciona uma linha ao histórico
    • readline_callback_handler_install - Initializes the readline callback interface and terminal, prints the prompt and returns immediately
    • readline_callback_handler_remove - Removes a previously installed callback handler and restores terminal settings
    • readline_callback_read_char - Reads a character and informs the readline callback interface when a line is received
    • readline_clear_history - Limpa a história
    • readline_completion_function - Registra uma função de completar
    • readline_info - Obtém/Define várias variáveis internas do readline
    • readline_list_history - Lista a história
    • readline_on_new_line - Inform readline that the cursor has moved to a new line
    • readline_read_history - Lê a história
    • readline_redisplay - Redraws the display
    • readline_write_history - Grava a história
    • readlink - Retornar o alvo de uma ligação simbólica
    • read_exif_data - Sinônimo de exif_read_data
    • realpath - Retorna o path absoluto canonizado
    • realpath_cache_get - Obter entradas de cache do caminho absoluto
    • realpath_cache_size - Obter o tamanho do cache do caminho absoluto
    • recode - Sinônimo de recode_string
    • recode_file - Recode from file to file according to recode request
    • recode_string - Recode a string according to a recode request
    • RecursiveArrayIterator::getChildren - Returns an iterator for the current entry if it is an array or an object
    • RecursiveArrayIterator::hasChildren - Returns whether current entry is an array or an object
    • RecursiveCachingIterator::getChildren - Retorna os filhos do iterador interno como um RecursiveCachingIterator
    • RecursiveCachingIterator::hasChildren - Check whether the current element of the inner iterator has children
    • RecursiveCachingIterator::__construct - Construct
    • RecursiveCallbackFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
    • RecursiveCallbackFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveCallbackFilterIterator::__construct - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
    • RecursiveDirectoryIterator::getChildren - Retorna um iterador para o elemento atual se ele for um diretório
    • RecursiveDirectoryIterator::getSubPath - Get sub path
    • RecursiveDirectoryIterator::getSubPathname - Get sub path and name
    • RecursiveDirectoryIterator::hasChildren - Retorna se o elemento atual é ou não um diretório que não seja '.' nem '..'
    • RecursiveDirectoryIterator::key - Retorna o caminho e o nome do arquivo do elemento atual do diretório
    • RecursiveDirectoryIterator::next - Avança para o próximo elemento
    • RecursiveDirectoryIterator::rewind - Recomeça a iteração do diretório
    • RecursiveDirectoryIterator::__construct - Constructs a RecursiveDirectoryIterator
    • RecursiveFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveFilterIterator
    • RecursiveFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveFilterIterator::__construct - Create a RecursiveFilterIterator from a RecursiveIterator
    • RecursiveIterator::getChildren - Returns an iterator for the current entry
    • RecursiveIterator::hasChildren - Returns if an iterator can be created for the current entry
    • RecursiveIteratorIterator::beginChildren - Begin children
    • RecursiveIteratorIterator::beginIteration - Begin Iteration
    • RecursiveIteratorIterator::callGetChildren - Get children
    • RecursiveIteratorIterator::callHasChildren - Has children
    • RecursiveIteratorIterator::current - Retorna o valor do elemento atual
    • RecursiveIteratorIterator::endChildren - End children
    • RecursiveIteratorIterator::endIteration - End Iteration
    • RecursiveIteratorIterator::getDepth - Retorna a profundidade atual da iteração recursiva
    • RecursiveIteratorIterator::getInnerIterator - Get inner iterator
    • RecursiveIteratorIterator::getMaxDepth - Get max depth
    • RecursiveIteratorIterator::getSubIterator - Retorna o sub-iterador ativo atual
    • RecursiveIteratorIterator::key - Retorna a chave atual
    • RecursiveIteratorIterator::next - Avança para o próximo elemento
    • RecursiveIteratorIterator::nextElement - Next element
    • RecursiveIteratorIterator::rewind - Recomeça o iterador no primeiro elemento do primeiro iterador interno
    • RecursiveIteratorIterator::setMaxDepth - Set max depth
    • RecursiveIteratorIterator::valid - Check whether the current position is valid
    • RecursiveIteratorIterator::__construct - Construct a RecursiveIteratorIterator
    • RecursiveRegexIterator::getChildren - Returns an iterator for the current entry
    • RecursiveRegexIterator::hasChildren - Returns whether an iterator can be obtained for the current entry
    • RecursiveRegexIterator::__construct - Creates a new RecursiveRegexIterator
    • RecursiveTreeIterator::beginChildren - Begin children
    • RecursiveTreeIterator::beginIteration - Begin iteration
    • RecursiveTreeIterator::callGetChildren - Get children
    • RecursiveTreeIterator::callHasChildren - Has children
    • RecursiveTreeIterator::current - Get current element
    • RecursiveTreeIterator::endChildren - End children
    • RecursiveTreeIterator::endIteration - End iteration
    • RecursiveTreeIterator::getEntry - Get current entry
    • RecursiveTreeIterator::getPostfix - Get the postfix
    • RecursiveTreeIterator::getPrefix - Get the prefix
    • RecursiveTreeIterator::key - Get the key of the current element
    • RecursiveTreeIterator::next - Move to next element
    • RecursiveTreeIterator::nextElement - Next element
    • RecursiveTreeIterator::rewind - Rewind iterator
    • RecursiveTreeIterator::setPostfix - Set postfix
    • RecursiveTreeIterator::setPrefixPart - Set a part of the prefix
    • RecursiveTreeIterator::valid - Check validity
    • RecursiveTreeIterator::__construct - Construct a RecursiveTreeIterator
    • Reflection::export - Exports
    • Reflection::getModifierNames - Gets modifier names
    • ReflectionAttribute::getArguments - Gets arguments passed to attribute
    • ReflectionAttribute::getName - Gets attribute name
    • ReflectionAttribute::getTarget - Returns the target of the attribute as bitmask
    • ReflectionAttribute::isRepeated - Returns whether the attribute of this name has been repeated on a code element
    • ReflectionAttribute::newInstance - Instantiates the attribute class represented by this ReflectionAttribute class and arguments
    • ReflectionAttribute::__construct - Private constructor to disallow direct instantiation
    • ReflectionClass::export - Exports a class
    • ReflectionClass::getAttributes - Gets Attributes
    • ReflectionClass::getConstant - Gets defined constant
    • ReflectionClass::getConstants - Gets constants
    • ReflectionClass::getConstructor - Gets the constructor of the class
    • ReflectionClass::getDefaultProperties - Gets default properties
    • ReflectionClass::getDocComment - Gets doc comments
    • ReflectionClass::getEndLine - Gets end line
    • ReflectionClass::getExtension - Gets a ReflectionExtension object for the extension which defined the class
    • ReflectionClass::getExtensionName - Gets the name of the extension which defined the class
    • ReflectionClass::getFileName - Gets the filename of the file in which the class has been defined
    • ReflectionClass::getInterfaceNames - Gets the interface names
    • ReflectionClass::getInterfaces - Gets the interfaces
    • ReflectionClass::getMethod - Gets a ReflectionMethod for a class method
    • ReflectionClass::getMethods - Gets an array of methods
    • ReflectionClass::getModifiers - Gets the class modifiers
    • ReflectionClass::getName - Gets class name
    • ReflectionClass::getNamespaceName - Gets namespace name
    • ReflectionClass::getParentClass - Gets parent class
    • ReflectionClass::getProperties - Gets properties
    • ReflectionClass::getProperty - Gets a ReflectionProperty for a class's property
    • ReflectionClass::getReflectionConstant - Gets a ReflectionClassConstant for a class's constant
    • ReflectionClass::getReflectionConstants - Gets class constants
    • ReflectionClass::getShortName - Gets short name
    • ReflectionClass::getStartLine - Gets starting line number
    • ReflectionClass::getStaticProperties - Gets static properties
    • ReflectionClass::getStaticPropertyValue - Gets static property value
    • ReflectionClass::getTraitAliases - Returns an array of trait aliases
    • ReflectionClass::getTraitNames - Returns an array of names of traits used by this class
    • ReflectionClass::getTraits - Returns an array of traits used by this class
    • ReflectionClass::hasConstant - Checks if constant is defined
    • ReflectionClass::hasMethod - Checks if method is defined
    • ReflectionClass::hasProperty - Checks if property is defined
    • ReflectionClass::implementsInterface - Implements interface
    • ReflectionClass::inNamespace - Checks if in namespace
    • ReflectionClass::isAbstract - Checks if class is abstract
    • ReflectionClass::isAnonymous - Checks if class is anonymous
    • ReflectionClass::isCloneable - Returns whether this class is cloneable
    • ReflectionClass::isEnum - Returns whether this is an enum
    • ReflectionClass::isFinal - Checks if class is final
    • ReflectionClass::isInstance - Checks class for instance
    • ReflectionClass::isInstantiable - Checks if the class is instantiable
    • ReflectionClass::isInterface - Checks if the class is an interface
    • ReflectionClass::isInternal - Checks if class is defined internally by an extension, or the core
    • ReflectionClass::isIterable - Check whether this class is iterable
    • ReflectionClass::isIterateable - Sinônimo de ReflectionClass::isIterable
    • ReflectionClass::isReadOnly - Checks if class is readonly
    • ReflectionClass::isSubclassOf - Checks if a subclass
    • ReflectionClass::isTrait - Returns whether this is a trait
    • ReflectionClass::isUserDefined - Checks if user defined
    • ReflectionClass::newInstance - Creates a new class instance from given arguments
    • ReflectionClass::newInstanceArgs - Creates a new class instance from given arguments
    • ReflectionClass::newInstanceWithoutConstructor - Creates a new class instance without invoking the constructor
    • ReflectionClass::setStaticPropertyValue - Sets static property value
    • ReflectionClass::__construct - Constructs a ReflectionClass
    • ReflectionClass::__toString - Returns the string representation of the ReflectionClass object
    • 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
    • ReflectionEnum::getBackingType - Gets the backing type of an Enum, if any
    • ReflectionEnum::getCase - Returns a specific case of an Enum
    • ReflectionEnum::getCases - Returns a list of all cases on an Enum
    • ReflectionEnum::hasCase - Checks for a case on an Enum
    • ReflectionEnum::isBacked - Determines if an Enum is a Backed Enum
    • ReflectionEnum::__construct - Instantiates a ReflectionEnum object
    • ReflectionEnumBackedCase::getBackingValue - Gets the scalar value backing this Enum case
    • ReflectionEnumBackedCase::__construct - Instantiates a ReflectionEnumBackedCase object
    • ReflectionEnumUnitCase::getEnum - Gets the reflection of the enum of this case
    • ReflectionEnumUnitCase::getValue - Gets the enum case object described by this reflection object
    • ReflectionEnumUnitCase::__construct - Instantiates a ReflectionEnumUnitCase object
    • ReflectionExtension::export - Export
    • ReflectionExtension::getClasses - Gets classes
    • ReflectionExtension::getClassNames - Gets class names
    • ReflectionExtension::getConstants - Gets constants
    • ReflectionExtension::getDependencies - Gets dependencies
    • ReflectionExtension::getFunctions - Gets extension functions
    • ReflectionExtension::getINIEntries - Gets extension ini entries
    • ReflectionExtension::getName - Gets extension name
    • ReflectionExtension::getVersion - Gets extension version
    • ReflectionExtension::info - Imprime informações da extensão
    • ReflectionExtension::isPersistent - Returns whether this extension is persistent
    • ReflectionExtension::isTemporary - Returns whether this extension is temporary
    • ReflectionExtension::__clone - Clones
    • ReflectionExtension::__construct - Constructs a ReflectionExtension
    • ReflectionExtension::__toString - To string
    • ReflectionFiber::getCallable - Gets the callable used to create the Fiber
    • ReflectionFiber::getExecutingFile - Get the file name of the current execution point
    • ReflectionFiber::getExecutingLine - Get the line number of the current execution point
    • ReflectionFiber::getFiber - Get the reflected Fiber instance
    • ReflectionFiber::getTrace - Get the backtrace of the current execution point
    • ReflectionFiber::__construct - Constructs a ReflectionFiber object
    • ReflectionFunction::export - Exports function
    • ReflectionFunction::getClosure - Returns a dynamically created closure for the function
    • ReflectionFunction::invoke - Invokes function
    • ReflectionFunction::invokeArgs - Invokes function args
    • ReflectionFunction::isAnonymous - Checks if a function is anonymous
    • ReflectionFunction::isDisabled - Checks if function is disabled
    • ReflectionFunction::__construct - Constructs a ReflectionFunction object
    • ReflectionFunction::__toString - Returns the string representation of the ReflectionFunction object
    • ReflectionFunctionAbstract::getAttributes - Gets Attributes
    • ReflectionFunctionAbstract::getClosureScopeClass - Returns the scope class associated with the closure
    • ReflectionFunctionAbstract::getClosureThis - Returns this pointer bound to closure
    • ReflectionFunctionAbstract::getClosureUsedVariables - Returns an array of the used variables in the Closure
    • ReflectionFunctionAbstract::getDocComment - Gets doc comment
    • ReflectionFunctionAbstract::getEndLine - Gets end line number
    • ReflectionFunctionAbstract::getExtension - Gets extension info
    • ReflectionFunctionAbstract::getExtensionName - Gets extension name
    • ReflectionFunctionAbstract::getFileName - Gets file name
    • ReflectionFunctionAbstract::getName - Gets function name
    • ReflectionFunctionAbstract::getNamespaceName - Gets namespace name
    • ReflectionFunctionAbstract::getNumberOfParameters - Gets number of parameters
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters - Gets number of required parameters
    • ReflectionFunctionAbstract::getParameters - Gets parameters
    • ReflectionFunctionAbstract::getReturnType - Gets the specified return type of a function
    • ReflectionFunctionAbstract::getShortName - Gets function short name
    • ReflectionFunctionAbstract::getStartLine - Gets starting line number
    • ReflectionFunctionAbstract::getStaticVariables - Gets static variables
    • ReflectionFunctionAbstract::getTentativeReturnType - Returns the tentative return type associated with the function
    • ReflectionFunctionAbstract::hasReturnType - Checks if the function has a specified return type
    • ReflectionFunctionAbstract::hasTentativeReturnType - Returns whether the function has a tentative return type
    • ReflectionFunctionAbstract::inNamespace - Checks if function in namespace
    • ReflectionFunctionAbstract::isClosure - Checks if closure
    • ReflectionFunctionAbstract::isDeprecated - Checks if deprecated
    • ReflectionFunctionAbstract::isGenerator - Returns whether this function is a generator
    • ReflectionFunctionAbstract::isInternal - Checks if is internal
    • ReflectionFunctionAbstract::isStatic - Checks if the function is static
    • ReflectionFunctionAbstract::isUserDefined - Checks if user defined
    • ReflectionFunctionAbstract::isVariadic - Checks if the function is variadic
    • ReflectionFunctionAbstract::returnsReference - Checks if returns reference
    • ReflectionFunctionAbstract::__clone - Clones function
    • ReflectionFunctionAbstract::__toString - Returns the string representation of the ReflectionFunctionAbstract object
    • ReflectionGenerator::getExecutingFile - Gets the file name of the currently executing generator
    • ReflectionGenerator::getExecutingGenerator - Gets the executing Generator object
    • ReflectionGenerator::getExecutingLine - Gets the currently executing line of the generator
    • ReflectionGenerator::getFunction - Gets the function name of the generator
    • ReflectionGenerator::getThis - Gets the $this value of the generator
    • ReflectionGenerator::getTrace - Gets the trace of the executing generator
    • ReflectionGenerator::__construct - Constructs a ReflectionGenerator object
    • ReflectionIntersectionType::getTypes - Returns the types included in the intersection type
    • ReflectionMethod::createFromMethodName - Creates a new ReflectionMethod
    • ReflectionMethod::export - Export a reflection method
    • ReflectionMethod::getClosure - Returns a dynamically created closure for the method
    • ReflectionMethod::getDeclaringClass - Gets declaring class for the reflected method
    • ReflectionMethod::getModifiers - Gets the method modifiers
    • ReflectionMethod::getPrototype - Gets the method prototype (if there is one)
    • ReflectionMethod::hasPrototype - Returns whether a method has a prototype
    • ReflectionMethod::invoke - Invoke
    • ReflectionMethod::invokeArgs - Invoke args
    • ReflectionMethod::isAbstract - Checks if method is abstract
    • ReflectionMethod::isConstructor - Checks if method is a constructor
    • ReflectionMethod::isDestructor - Checks if method is a destructor
    • ReflectionMethod::isFinal - Checks if method is final
    • ReflectionMethod::isPrivate - Checks if method is private
    • ReflectionMethod::isProtected - Checks if method is protected
    • ReflectionMethod::isPublic - Checks if method is public
    • ReflectionMethod::setAccessible - Set method accessibility
    • ReflectionMethod::__construct - Constructs a ReflectionMethod
    • ReflectionMethod::__toString - Returns the string representation of the Reflection method object
    • ReflectionNamedType::getName - Obtém o nome do tipo como uma string
    • ReflectionNamedType::isBuiltin - Checks if it is a built-in type
    • ReflectionObject::export - Export
    • ReflectionObject::__construct - Constructs a ReflectionObject
    • ReflectionParameter::allowsNull - Checks if null is allowed
    • ReflectionParameter::canBePassedByValue - Returns whether this parameter can be passed by value
    • ReflectionParameter::export - Exports
    • ReflectionParameter::getAttributes - Gets Attributes
    • ReflectionParameter::getClass - Get a ReflectionClass object for the parameter being reflected or null
    • ReflectionParameter::getDeclaringClass - Gets declaring class
    • ReflectionParameter::getDeclaringFunction - Gets declaring function
    • ReflectionParameter::getDefaultValue - Gets default parameter value
    • ReflectionParameter::getDefaultValueConstantName - Returns the default value's constant name if default value is constant or null
    • ReflectionParameter::getName - Gets parameter name
    • ReflectionParameter::getPosition - Gets parameter position
    • ReflectionParameter::getType - Gets a parameter's type
    • ReflectionParameter::hasType - Checks if parameter has a type
    • ReflectionParameter::isArray - Checks if parameter expects an array
    • ReflectionParameter::isCallable - Returns whether parameter MUST be callable
    • ReflectionParameter::isDefaultValueAvailable - Checks if a default value is available
    • ReflectionParameter::isDefaultValueConstant - Returns whether the default value of this parameter is a constant
    • ReflectionParameter::isOptional - Checks if optional
    • ReflectionParameter::isPassedByReference - Checks if passed by reference
    • ReflectionParameter::isVariadic - Checks if the parameter is variadic
    • ReflectionParameter::__clone - Clone
    • ReflectionParameter::__construct - Construct
    • ReflectionParameter::__toString - To string
    • ReflectionProperty::export - Export
    • ReflectionProperty::getAttributes - Gets Attributes
    • ReflectionProperty::getDeclaringClass - Gets declaring class
    • ReflectionProperty::getDefaultValue - Returns the default value declared for a property
    • ReflectionProperty::getDocComment - Gets the property doc comment
    • ReflectionProperty::getModifiers - Gets the property modifiers
    • ReflectionProperty::getName - Gets property name
    • ReflectionProperty::getType - Gets a property's type
    • ReflectionProperty::getValue - Gets value
    • ReflectionProperty::hasDefaultValue - Checks if property has a default value declared
    • ReflectionProperty::hasType - Checks if property has a type
    • ReflectionProperty::isDefault - Checks if property is a default property
    • ReflectionProperty::isInitialized - Checks whether a property is initialized
    • ReflectionProperty::isPrivate - Checks if property is private
    • ReflectionProperty::isPromoted - Checks if property is promoted
    • ReflectionProperty::isProtected - Checks if property is protected
    • ReflectionProperty::isPublic - Checks if property is public
    • ReflectionProperty::isReadOnly - Checks if property is readonly
    • ReflectionProperty::isStatic - Checks if property is static
    • ReflectionProperty::setAccessible - Set property accessibility
    • ReflectionProperty::setValue - Set property value
    • ReflectionProperty::__clone - Clone
    • ReflectionProperty::__construct - Construct a ReflectionProperty object
    • ReflectionProperty::__toString - To string
    • 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 - Export
    • ReflectionZendExtension::getAuthor - Gets author
    • ReflectionZendExtension::getCopyright - Gets copyright
    • ReflectionZendExtension::getName - Gets name
    • ReflectionZendExtension::getURL - Gets URL
    • ReflectionZendExtension::getVersion - Gets version
    • ReflectionZendExtension::__clone - Clone handler
    • ReflectionZendExtension::__construct - Constructs a ReflectionZendExtension object
    • ReflectionZendExtension::__toString - To string handler
    • Reflector::export - Exports
    • RegexIterator::accept - Get accept status
    • RegexIterator::getFlags - Get flags
    • RegexIterator::getMode - Returns operation mode
    • RegexIterator::getPregFlags - Returns the regular expression flags
    • RegexIterator::getRegex - Returns current regular expression
    • RegexIterator::setFlags - Sets the flags
    • RegexIterator::setMode - Sets the operation mode
    • RegexIterator::setPregFlags - Sets the regular expression flags
    • RegexIterator::__construct - Create a new RegexIterator
    • register_shutdown_function - Register a function for execution on shutdown
    • register_tick_function - Register a function for execution on each tick
    • rename - Renomeia um arquivo ou diretório
    • reset - Faz o ponteiro interno de um array apontar para o seu primeiro elemento
    • ResourceBundle::count - Obtém o número de elementos no pacote
    • ResourceBundle::create - Cria um pacote de recursos
    • ResourceBundle::get - Obtém os dados do pacote
    • ResourceBundle::getErrorCode - Obtém o código do último erro gerado pelo pacote.
    • ResourceBundle::getErrorMessage - Obtém a última mensagem de erro gerada pelo pacote
    • ResourceBundle::getLocales - Obtém as localidades suportadas
    • restore_error_handler - Restaura a função anterior de gerenciamento de erro
    • restore_exception_handler - Restores the previously defined exception handler function
    • restore_include_path - Restaura o valor da opção de configuração 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 - Constrói uma nova instância do atributo ReturnTypeWillChange
    • rewind - Retrocede a posição de um ponteiro de arquivos
    • rewinddir - Retroceder o manipulador de diretório
    • rmdir - Remove um diretório
    • 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 - Arredonda um 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 - Adds RRA - archive of data values for each data source
    • RRDCreator::addDataSource - Adds data source definition for RRD database
    • RRDCreator::save - Saves the RRD database to a file
    • RRDCreator::__construct - Creates new RRDCreator instance
    • rrdc_disconnect - Close any outstanding connection to rrd caching daemon
    • RRDGraph::save - Saves the result of query into image
    • RRDGraph::saveVerbose - Saves the RRD database query into image and returns the verbose information about generated graph
    • RRDGraph::setOptions - Sets the options for rrd graph export
    • RRDGraph::__construct - Creates new RRDGraph instance
    • RRDUpdater::update - Update the RRD database file
    • RRDUpdater::__construct - Creates new RRDUpdater instance
    • rrd_create - Creates rrd database file
    • rrd_error - Gets latest error message
    • rrd_fetch - Fetch the data for graph as array
    • rrd_first - Gets the timestamp of the first sample from rrd file
    • rrd_graph - Creates image from a data
    • rrd_info - Gets information about rrd file
    • rrd_last - Gets unix timestamp of the last sample
    • rrd_lastupdate - Gets information about last updated data
    • rrd_restore - Restores the RRD file from XML dump
    • rrd_tune - Tunes some RRD database file header options
    • rrd_update - Updates the RRD database
    • rrd_version - Gets information about underlying rrdtool library
    • rrd_xport - Exports the information about RRD database
    • rsort - Ordena um array em ordem descrescente
    • rtrim - Retira espaço em branco (ou outros caracteres) do final de uma string
    • runkit7_constant_add - Similar to define(), but allows defining in class definitions as well
    • runkit7_constant_redefine - Redefine an already defined constant
    • runkit7_constant_remove - Remove/Delete an already defined constant
    • runkit7_function_add - Add a new function, similar to create_function
    • runkit7_function_copy - Copy a function to a new function name
    • runkit7_function_redefine - Replace a function definition with a new implementation
    • runkit7_function_remove - Remove a function definition
    • runkit7_function_rename - Change a function's name
    • runkit7_import - Process a PHP file importing function and class definitions, overwriting where appropriate
    • runkit7_method_add - Dynamically adds a new method to a given class
    • runkit7_method_copy - Copies a method from class to another
    • runkit7_method_redefine - Dynamically changes the code of the given method
    • runkit7_method_remove - Dynamically removes the given method
    • runkit7_method_rename - Dynamically changes the name of the given method
    • runkit7_object_id - Return the integer object handle for given object
    • runkit7_superglobals - Return numerically indexed array of registered superglobals
    • runkit7_zval_inspect - Returns information about the passed in value with data types, reference counts, etc
  • s
    • sapi_windows_cp_conv - Convert string from one codepage to another
    • sapi_windows_cp_get - Get current codepage
    • sapi_windows_cp_is_utf8 - Indicates whether the codepage is UTF-8 compatible
    • sapi_windows_cp_set - Set process codepage
    • sapi_windows_generate_ctrl_event - Send a CTRL event to another process
    • sapi_windows_set_ctrl_handler - Set or remove a CTRL event handler
    • sapi_windows_vt100_support - Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.
    • scandir - Lista arquivos e diretórios dentro do caminho especificado
    • 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 - Seeks to a position
    • sem_acquire - Acquire a semaphore
    • sem_get - Get a semaphore id
    • sem_release - Release a semaphore
    • sem_remove - Remove a semaphore
    • SensitiveParameter::__construct - Constrói uma nova instância do atributo SensitiveParameter
    • SensitiveParameterValue::getValue - Retorna o valor sensível
    • SensitiveParameterValue::__construct - Constrói um novo objeto SensitiveParameterValue
    • SensitiveParameterValue::__debugInfo - Protege os valores sensíveis de exposição acidental
    • Serializable::serialize - Representação em string de um objeto
    • Serializable::unserialize - Constrói o objeto
    • serialize - Gera uma representação armazenável de um 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 - Fecha a sessão
    • SessionHandler::create_sid - Retorna um novo ID de sessão
    • SessionHandler::destroy - Destrói uma sessão
    • SessionHandler::gc - Apaga sessões antigas
    • SessionHandler::open - Inicia uma sessão
    • SessionHandler::read - Lê os dados de sessão
    • SessionHandler::write - Escreve os dados de sessão
    • SessionHandlerInterface::close - Fecha a sessão
    • SessionHandlerInterface::destroy - Destrói uma sessão
    • SessionHandlerInterface::gc - Remove sessões antigas
    • SessionHandlerInterface::open - Inicializa uma sessão
    • SessionHandlerInterface::read - Lê os dados de sessão
    • SessionHandlerInterface::write - Escreve os dados de sessão
    • SessionIdInterface::create_sid - Cria um ID de sessão.
    • SessionUpdateTimestampHandlerInterface::updateTimestamp - Atualiza o timestamp
    • SessionUpdateTimestampHandlerInterface::validateId - Valida o ID
    • session_abort - Descarta as alterações no array da sessão e encerra a sessão
    • session_cache_expire - Obter e/ou definir a expiração do cache atual
    • session_cache_limiter - Obtém e/ou define o limitador do cache atual
    • session_commit - Sinônimo de session_write_close
    • session_create_id - Cria novo ID de sessão
    • session_decode - Decodifica dados de sessão de uma sessão codificada em formato string
    • session_destroy - Destrói todos os dados registrados em uma sessão
    • session_encode - Codifica os dados atuais da sessão como uma sessão codificada em formato string
    • session_gc - Executa a coleta de lixo de dados da sessão
    • session_get_cookie_params - Obtém os parâmetros do cookie da sessão
    • session_id - Obtém e/ou define o id de sessão atual
    • session_module_name - Obtém e/ou define o módulo da sessão atual
    • session_name - Obtém e/ou define o nome da sessão atual
    • session_regenerate_id - Atualiza o id da sessão atual com um novo id gerado
    • session_register_shutdown - Função de finalização da sessão
    • session_reset - Reinicializa um array de sessão com os valores originais
    • session_save_path - Obtém e/ou define o caminho para armazenamento da sessão atual
    • session_set_cookie_params - Define os parâmetros do cookie de sessão
    • session_set_save_handler - Define funções de armazenamento de sessão à nível de usuário
    • session_start - Inicia uma nova sessão ou resume uma sessão existente
    • session_status - Retorna o status atual da sessão
    • session_unset - Libera todas as variáveis de sessão
    • session_write_close - Guarda os dados de sessão e fecha a sessão
    • setcookie - Envia um cookie
    • setlocale - Set locale information
    • setrawcookie - Send a cookie without urlencoding the cookie value
    • settype - Define o tipo de uma variável
    • set_error_handler - Sets a user-defined error handler function
    • set_exception_handler - Sets a user-defined exception handler function
    • set_file_buffer - Sinônimo de stream_set_write_buffer
    • set_include_path - Sets the include_path configuration option
    • set_time_limit - Limits the maximum execution time
    • sha1 - Calculate the sha1 hash of a string
    • sha1_file - Calcula a hash sha1 de um arquivo
    • shell_exec - Executa um comando via shell e retorna a saída inteira como uma string
    • shmop_close - Fecha um bloco de memória compartilhada
    • shmop_delete - Deleta um bloco de memória compartilhada
    • shmop_open - Create or open shared memory block
    • shmop_read - Read data from shared memory block
    • shmop_size - Obtém o tamanho do bloco de memória compartilhada
    • shmop_write - Write data into shared memory block
    • shm_attach - Creates or open a shared memory segment
    • shm_detach - Disconnects from shared memory segment
    • shm_get_var - Returns a variable from shared memory
    • shm_has_var - Check whether a specific entry exists
    • shm_put_var - Inserts or updates a variable in shared memory
    • shm_remove - Removes shared memory from Unix systems
    • shm_remove_var - Removes a variable from shared memory
    • show_source - Sinônimo de highlight_file
    • shuffle - Embaralha um 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 a similaridade entre duas strings
    • SimpleXMLElement::addAttribute - Adiciona um atributo a elemento SimpleXML
    • SimpleXMLElement::addChild - Adiciona um elemento filho à um nó XML
    • SimpleXMLElement::asXML - Retorna uma string XML bem formada (well-formed) baseada em um elemento SimpleXML
    • SimpleXMLElement::attributes - Identifica um atributo de um elemento
    • SimpleXMLElement::children - Encontra os nós filhos de um dado nó
    • SimpleXMLElement::count - Conta os filhos de um elemento
    • SimpleXMLElement::current - Returns the current element
    • SimpleXMLElement::getChildren - Returns the sub-elements of the current element
    • SimpleXMLElement::getDocNamespaces - Retorna um namespace declarado no documento
    • SimpleXMLElement::getName - Pega o nome de um elemento XML
    • SimpleXMLElement::getNamespaces - Retorna os namespaces utilizados no documento
    • SimpleXMLElement::hasChildren - Checks whether the current element has sub elements
    • SimpleXMLElement::key - Return current key
    • SimpleXMLElement::next - Move to next element
    • SimpleXMLElement::registerXPathNamespace - Cria um prefixo/namespace de contexto para a próxima consulta XPath
    • SimpleXMLElement::rewind - Rewind to the first element
    • SimpleXMLElement::saveXML - Sinônimo de SimpleXMLElement::asXML
    • SimpleXMLElement::valid - Check whether the current element is valid
    • SimpleXMLElement::xpath - Executa uma consulta XPath em dados XML
    • SimpleXMLElement::__construct - Cria um novo objeto SimpleXMLElement
    • SimpleXMLElement::__toString - Retorna o conteúdo como uma string
    • simplexml_import_dom - Recebe um objeto SimpleXMLElement de um nó DOM
    • simplexml_load_file - Interpreta um arquivo XML e o transforma em um objeto
    • simplexml_load_string - Interpreta uma string XML e a transforma em um objeto
    • sin - Seno
    • sinh - Seno hiperbólico
    • sizeof - Sinônimo de count
    • sleep - Delay execution
    • snmp2_get - Fetch an SNMP object
    • snmp2_getnext - Fetch the SNMP object which follows the given object id
    • snmp2_real_walk - Return all objects including their respective object ID within the specified one
    • snmp2_set - Set the value of an SNMP object
    • snmp2_walk - Fetch all the SNMP objects from an agent
    • snmp3_get - Fetch an SNMP object
    • snmp3_getnext - Fetch the SNMP object which follows the given object id
    • snmp3_real_walk - Return all objects including their respective object ID within the specified one
    • snmp3_set - Set the value of an SNMP object
    • snmp3_walk - Fetch all the SNMP objects from an agent
    • SNMP::close - Close SNMP session
    • SNMP::get - Fetch an SNMP object
    • SNMP::getErrno - Get last error code
    • SNMP::getError - Get last error message
    • SNMP::getnext - Fetch an SNMP object which follows the given object id
    • SNMP::set - Set the value of an SNMP object
    • SNMP::setSecurity - Configures security-related SNMPv3 session parameters
    • SNMP::walk - Fetch SNMP object subtree
    • SNMP::__construct - Creates SNMP instance representing session to remote SNMP agent
    • snmpget - 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 - Sinônimo 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 - Chama uma função SOAP (obsoleta)
    • SoapClient::__construct - SoapClient constructor
    • SoapClient::__doRequest - Performs a SOAP request
    • SoapClient::__getCookies - Get list of cookies
    • SoapClient::__getFunctions - Returns list of available SOAP functions
    • SoapClient::__getLastRequest - Returns last SOAP request
    • SoapClient::__getLastRequestHeaders - Returns the SOAP headers from the last request
    • SoapClient::__getLastResponse - Returns last SOAP response
    • SoapClient::__getLastResponseHeaders - Returns the SOAP headers from the last response
    • SoapClient::__getTypes - Returns a list of SOAP types
    • SoapClient::__setCookie - Defines a cookie for SOAP requests
    • SoapClient::__setLocation - Sets the location of the Web service to use
    • SoapClient::__setSoapHeaders - Sets SOAP headers for subsequent calls
    • SoapClient::__soapCall - Calls a SOAP function
    • SoapFault::__construct - SoapFault constructor
    • SoapFault::__toString - Obtain a string representation of a SoapFault
    • SoapHeader::__construct - SoapHeader constructor
    • SoapParam::__construct - SoapParam constructor
    • SoapServer::addFunction - Adds one or more functions to handle SOAP requests
    • SoapServer::addSoapHeader - Add a SOAP header to the response
    • SoapServer::fault - Issue SoapServer fault indicating an error
    • SoapServer::getFunctions - Returns list of defined functions
    • SoapServer::handle - Handles a SOAP request
    • SoapServer::setClass - Sets the class which handles SOAP requests
    • SoapServer::setObject - Sets the object which will be used to handle SOAP requests
    • SoapServer::setPersistence - Sets SoapServer persistence mode
    • SoapServer::__construct - SoapServer constructor
    • SoapVar::__construct - SoapVar constructor
    • socket_accept - Aceita uma conexão em um 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 - Determina se o socket está na marca fora-de-banda
    • socket_bind - Binds a name to a socket
    • socket_clear_error - Limpa o erro no socket ou o último código de erro
    • socket_close - Closes a Socket instance
    • socket_cmsg_space - Calculate message buffer size
    • socket_connect - Initiates a connection on a socket
    • socket_create - Create a socket (endpoint for communication)
    • socket_create_listen - Opens a socket on port to accept connections
    • socket_create_pair - Creates a pair of indistinguishable sockets and stores them in an array
    • socket_export_stream - Export a socket into a stream that encapsulates a socket
    • socket_getopt - Sinônimo de socket_get_option
    • socket_getpeername - Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_getsockname - Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_get_option - Gets socket options for the socket
    • socket_get_status - Sinônimo de stream_get_meta_data
    • socket_import_stream - Import a stream
    • socket_last_error - Returns the last error on the socket
    • socket_listen - Listens for a connection on a socket
    • socket_read - Reads a maximum of length bytes from a socket
    • socket_recv - Recebe dados de um socket conectado
    • socket_recvfrom - Receives data from a socket whether or not it is connection-oriented
    • socket_recvmsg - Read a message
    • socket_select - Runs the select() system call on the given arrays of sockets with a specified timeout
    • socket_send - Sends data to a connected socket
    • socket_sendmsg - Send a message
    • socket_sendto - Sends a message to a socket, whether it is connected or not
    • socket_setopt - Sinônimo de socket_set_option
    • socket_set_block - Sets blocking mode on a socket
    • socket_set_blocking - Sinônimo de stream_set_blocking
    • socket_set_nonblock - Sets nonblocking mode for file descriptor fd
    • socket_set_option - Sets socket options for the socket
    • socket_set_timeout - Sinônimo de stream_set_timeout
    • socket_shutdown - Shuts down a socket for receiving, sending, or both
    • socket_strerror - Return a string describing a socket error
    • socket_write - Write to a socket
    • socket_wsaprotocol_info_export - Exports the WSAPROTOCOL_INFO Structure
    • socket_wsaprotocol_info_import - Imports a Socket from another Process
    • socket_wsaprotocol_info_release - Releases an exported WSAPROTOCOL_INFO Structure
    • sodium_add - Add large numbers
    • sodium_base642bin - 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 - Sinônimo 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 - Adds a document to the index
    • SolrClient::addDocuments - Adds a collection of SolrInputDocument instances to the index
    • SolrClient::commit - Finalizes all add/deletes made to the index
    • SolrClient::deleteById - Delete by Id
    • SolrClient::deleteByIds - Deletes by Ids
    • SolrClient::deleteByQueries - Removes all documents matching any of the queries
    • SolrClient::deleteByQuery - Deletes all documents matching the given query
    • SolrClient::getById - Get Document By Id. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getByIds - Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getDebug - Returns the debug data for the last connection attempt
    • SolrClient::getOptions - Returns the client options set internally
    • SolrClient::optimize - Defragments the index
    • SolrClient::ping - Checks if Solr server is still up
    • SolrClient::query - Sends a query to the server
    • SolrClient::request - Sends a raw update request
    • SolrClient::rollback - Rollbacks all add/deletes made to the index since the last commit
    • SolrClient::setResponseWriter - Sets the response writer used to prepare the response from Solr
    • SolrClient::setServlet - Changes the specified servlet type to a new value
    • SolrClient::system - Retrieve Solr Server information
    • SolrClient::threads - Checks the threads status
    • SolrClient::__construct - Constructor for the SolrClient object
    • SolrClient::__destruct - Destructor for SolrClient
    • SolrClientException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrCollapseFunction::getField - Returns the field that is being collapsed on
    • SolrCollapseFunction::getHint - Returns collapse hint
    • SolrCollapseFunction::getMax - Returns max parameter
    • SolrCollapseFunction::getMin - Returns min parameter
    • SolrCollapseFunction::getNullPolicy - Returns null policy
    • SolrCollapseFunction::getSize - Returns size parameter
    • SolrCollapseFunction::setField - Sets the field to collapse on
    • SolrCollapseFunction::setHint - Sets collapse hint
    • SolrCollapseFunction::setMax - Selects the group heads by the max value of a numeric field or function query
    • SolrCollapseFunction::setMin - Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::setNullPolicy - Sets the NULL Policy
    • SolrCollapseFunction::setSize - Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::__construct - Constructor
    • SolrCollapseFunction::__toString - Returns a string representing the constructed collapse function
    • SolrDisMaxQuery::addBigramPhraseField - Adds a Phrase Bigram Field (pf2 parameter)
    • SolrDisMaxQuery::addBoostQuery - Adds a boost query field with value and optional boost (bq parameter)
    • SolrDisMaxQuery::addPhraseField - Adds a Phrase Field (pf parameter)
    • SolrDisMaxQuery::addQueryField - Add a query field with optional boost (qf parameter)
    • SolrDisMaxQuery::addTrigramPhraseField - Adds a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::addUserField - Adds a field to User Fields Parameter (uf)
    • SolrDisMaxQuery::removeBigramPhraseField - Removes phrase bigram field (pf2 parameter)
    • SolrDisMaxQuery::removeBoostQuery - Removes a boost query partial by field name (bq)
    • SolrDisMaxQuery::removePhraseField - Removes a Phrase Field (pf parameter)
    • SolrDisMaxQuery::removeQueryField - Removes a Query Field (qf parameter)
    • SolrDisMaxQuery::removeTrigramPhraseField - Removes a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::removeUserField - Removes a field from The User Fields Parameter (uf)
    • SolrDisMaxQuery::setBigramPhraseFields - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setBigramPhraseSlop - Sets Bigram Phrase Slop (ps2 parameter)
    • SolrDisMaxQuery::setBoostFunction - Sets a Boost Function (bf parameter)
    • SolrDisMaxQuery::setBoostQuery - Directly Sets Boost Query Parameter (bq)
    • SolrDisMaxQuery::setMinimumMatch - Set Minimum "Should" Match (mm)
    • SolrDisMaxQuery::setPhraseFields - Sets Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setPhraseSlop - Sets the default slop on phrase queries (ps parameter)
    • SolrDisMaxQuery::setQueryAlt - Set Query Alternate (q.alt parameter)
    • SolrDisMaxQuery::setQueryPhraseSlop - Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)
    • SolrDisMaxQuery::setTieBreaker - Sets Tie Breaker parameter (tie parameter)
    • SolrDisMaxQuery::setTrigramPhraseFields - Directly Sets Trigram Phrase Fields (pf3 parameter)
    • SolrDisMaxQuery::setTrigramPhraseSlop - Sets Trigram Phrase Slop (ps3 parameter)
    • SolrDisMaxQuery::setUserFields - Sets User Fields parameter (uf)
    • SolrDisMaxQuery::useDisMaxQueryParser - Switch QueryParser to be DisMax Query Parser
    • SolrDisMaxQuery::useEDisMaxQueryParser - Switch QueryParser to be EDisMax
    • SolrDisMaxQuery::__construct - Class Constructor
    • SolrDocument::addField - Adds a field to the document
    • SolrDocument::clear - Drops all the fields in the document
    • SolrDocument::current - Retrieves the current field
    • SolrDocument::deleteField - Removes a field from the document
    • SolrDocument::fieldExists - Checks if a field exists in the document
    • SolrDocument::getChildDocuments - Returns an array of child documents (SolrDocument)
    • SolrDocument::getChildDocumentsCount - Returns the number of child documents
    • SolrDocument::getField - Retrieves a field by name
    • SolrDocument::getFieldCount - Returns the number of fields in this document
    • SolrDocument::getFieldNames - Returns an array of fields names in the document
    • SolrDocument::getInputDocument - Returns a SolrInputDocument equivalent of the object
    • SolrDocument::hasChildDocuments - Checks whether the document has any child documents
    • SolrDocument::key - Retrieves the current key
    • SolrDocument::merge - Merges source to the current SolrDocument
    • SolrDocument::next - Moves the internal pointer to the next field
    • SolrDocument::offsetExists - Checks if a particular field exists
    • SolrDocument::offsetGet - Retrieves a field
    • SolrDocument::offsetSet - Adds a field to the document
    • SolrDocument::offsetUnset - Removes a field
    • SolrDocument::reset - Sinônimo de SolrDocument::clear
    • SolrDocument::rewind - Resets the internal pointer to the beginning
    • SolrDocument::serialize - Used for custom serialization
    • SolrDocument::sort - Sorts the fields in the document
    • SolrDocument::toArray - Returns an array representation of the document
    • SolrDocument::unserialize - Custom serialization of SolrDocument objects
    • SolrDocument::valid - Checks if the current position internally is still valid
    • SolrDocument::__clone - Creates a copy of a SolrDocument object
    • SolrDocument::__construct - Constructor
    • SolrDocument::__destruct - Destructor
    • SolrDocument::__get - Access the field as a property
    • SolrDocument::__isset - Checks if a field exists
    • SolrDocument::__set - Adds another field to the document
    • SolrDocument::__unset - Removes a field from the document
    • SolrDocumentField::__construct - Constructor
    • SolrDocumentField::__destruct - Destructor
    • SolrException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrGenericResponse::__construct - Constructor
    • SolrGenericResponse::__destruct - Destructor
    • SolrIllegalArgumentException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrIllegalOperationException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrInputDocument::addChildDocument - Adds a child document for block indexing
    • SolrInputDocument::addChildDocuments - Adds an array of child documents
    • SolrInputDocument::addField - Adds a field to the document
    • SolrInputDocument::clear - Resets the input document
    • SolrInputDocument::deleteField - Removes a field from the document
    • SolrInputDocument::fieldExists - Checks if a field exists
    • SolrInputDocument::getBoost - Retrieves the current boost value for the document
    • SolrInputDocument::getChildDocuments - Returns an array of child documents (SolrInputDocument)
    • SolrInputDocument::getChildDocumentsCount - Returns the number of child documents
    • SolrInputDocument::getField - Retrieves a field by name
    • SolrInputDocument::getFieldBoost - Retrieves the boost value for a particular field
    • SolrInputDocument::getFieldCount - Returns the number of fields in the document
    • SolrInputDocument::getFieldNames - Returns an array containing all the fields in the document
    • SolrInputDocument::hasChildDocuments - Returns true if the document has any child documents
    • SolrInputDocument::merge - Merges one input document into another
    • SolrInputDocument::reset - Sinônimo de SolrInputDocument::clear
    • SolrInputDocument::setBoost - Sets the boost value for this document
    • SolrInputDocument::setFieldBoost - Sets the index-time boost value for a field
    • SolrInputDocument::sort - Sorts the fields within the document
    • SolrInputDocument::toArray - Returns an array representation of the input document
    • SolrInputDocument::__clone - Creates a copy of a SolrDocument
    • SolrInputDocument::__construct - Constructor
    • SolrInputDocument::__destruct - Destructor
    • SolrModifiableParams::__construct - Constructor
    • SolrModifiableParams::__destruct - Destructor
    • SolrObject::getPropertyNames - Returns an array of all the names of the properties
    • SolrObject::offsetExists - Checks if the property exists
    • SolrObject::offsetGet - Used to retrieve a property
    • SolrObject::offsetSet - Sets the value for a property
    • SolrObject::offsetUnset - Unsets the value for the property
    • SolrObject::__construct - Creates Solr object
    • SolrObject::__destruct - Destructor
    • SolrParams::add - Sinônimo de SolrParams::addParam
    • SolrParams::addParam - Adds a parameter to the object
    • SolrParams::get - Sinônimo de SolrParams::getParam
    • SolrParams::getParam - Returns a parameter value
    • SolrParams::getParams - Returns an array of non URL-encoded parameters
    • SolrParams::getPreparedParams - Returns an array of URL-encoded parameters
    • SolrParams::serialize - Used for custom serialization
    • SolrParams::set - Sinônimo de SolrParams::setParam
    • SolrParams::setParam - Sets the parameter to the specified value
    • SolrParams::toString - Returns all the name-value pair parameters in the object
    • SolrParams::unserialize - Used for custom serialization
    • SolrPingResponse::getResponse - Returns the response from the server
    • SolrPingResponse::__construct - Constructor
    • SolrPingResponse::__destruct - Destructor
    • SolrQuery::addExpandFilterQuery - Overrides main filter query, determines which documents to include in the main group
    • SolrQuery::addExpandSortField - Orders the documents within the expanded groups (expand.sort parameter)
    • SolrQuery::addFacetDateField - Maps to facet.date
    • SolrQuery::addFacetDateOther - Adds another facet.date.other parameter
    • SolrQuery::addFacetField - Adds another field to the facet
    • SolrQuery::addFacetQuery - Adds a facet query
    • SolrQuery::addField - Specifies which fields to return in the result
    • SolrQuery::addFilterQuery - Specifies a filter query
    • SolrQuery::addGroupField - Add a field to be used to group results
    • SolrQuery::addGroupFunction - Allows grouping results based on the unique values of a function query (group.func parameter)
    • SolrQuery::addGroupQuery - Allows grouping of documents that match the given query
    • SolrQuery::addGroupSortField - Add a group sort field (group.sort parameter)
    • SolrQuery::addHighlightField - Maps to hl.fl
    • SolrQuery::addMltField - Sets a field to use for similarity
    • SolrQuery::addMltQueryField - Maps to mlt.qf
    • SolrQuery::addSortField - Used to control how the results should be sorted
    • SolrQuery::addStatsFacet - Requests a return of sub results for values within the given facet
    • SolrQuery::addStatsField - Maps to stats.field parameter
    • SolrQuery::collapse - Collapses the result set to a single document per group
    • SolrQuery::getExpand - Returns true if group expanding is enabled
    • SolrQuery::getExpandFilterQueries - Returns the expand filter queries
    • SolrQuery::getExpandQuery - Returns the expand query expand.q parameter
    • SolrQuery::getExpandRows - Returns The number of rows to display in each group (expand.rows)
    • SolrQuery::getExpandSortFields - Returns an array of fields
    • SolrQuery::getFacet - Returns the value of the facet parameter
    • SolrQuery::getFacetDateEnd - Returns the value for the facet.date.end parameter
    • SolrQuery::getFacetDateFields - Returns all the facet.date fields
    • SolrQuery::getFacetDateGap - Returns the value of the facet.date.gap parameter
    • SolrQuery::getFacetDateHardEnd - Returns the value of the facet.date.hardend parameter
    • SolrQuery::getFacetDateOther - Returns the value for the facet.date.other parameter
    • SolrQuery::getFacetDateStart - Returns the lower bound for the first date range for all date faceting on this field
    • SolrQuery::getFacetFields - Returns all the facet fields
    • SolrQuery::getFacetLimit - Returns the maximum number of constraint counts that should be returned for the facet fields
    • SolrQuery::getFacetMethod - Returns the value of the facet.method parameter
    • SolrQuery::getFacetMinCount - Returns the minimum counts for facet fields should be included in the response
    • SolrQuery::getFacetMissing - Returns the current state of the facet.missing parameter
    • SolrQuery::getFacetOffset - Returns an offset into the list of constraints to be used for pagination
    • SolrQuery::getFacetPrefix - Returns the facet prefix
    • SolrQuery::getFacetQueries - Returns all the facet queries
    • SolrQuery::getFacetSort - Returns the facet sort type
    • SolrQuery::getFields - Returns the list of fields that will be returned in the response
    • SolrQuery::getFilterQueries - Returns an array of filter queries
    • SolrQuery::getGroup - Returns true if grouping is enabled
    • SolrQuery::getGroupCachePercent - Returns group cache percent value
    • SolrQuery::getGroupFacet - Returns the group.facet parameter value
    • SolrQuery::getGroupFields - Returns group fields (group.field parameter values)
    • SolrQuery::getGroupFormat - Returns the group.format value
    • SolrQuery::getGroupFunctions - Returns group functions (group.func parameter values)
    • SolrQuery::getGroupLimit - Returns the group.limit value
    • SolrQuery::getGroupMain - Returns the group.main value
    • SolrQuery::getGroupNGroups - Returns the group.ngroups value
    • SolrQuery::getGroupOffset - Returns the group.offset value
    • SolrQuery::getGroupQueries - Returns all the group.query parameter values
    • SolrQuery::getGroupSortFields - Returns the group.sort value
    • SolrQuery::getGroupTruncate - Returns the group.truncate value
    • SolrQuery::getHighlight - Returns the state of the hl parameter
    • SolrQuery::getHighlightAlternateField - Returns the highlight field to use as backup or default
    • SolrQuery::getHighlightFields - Returns all the fields that Solr should generate highlighted snippets for
    • SolrQuery::getHighlightFormatter - Returns the formatter for the highlighted output
    • SolrQuery::getHighlightFragmenter - Returns the text snippet generator for highlighted text
    • SolrQuery::getHighlightFragsize - Returns the number of characters of fragments to consider for highlighting
    • SolrQuery::getHighlightHighlightMultiTerm - Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
    • SolrQuery::getHighlightMaxAlternateFieldLength - Returns the maximum number of characters of the field to return
    • SolrQuery::getHighlightMaxAnalyzedChars - Returns the maximum number of characters into a document to look for suitable snippets
    • SolrQuery::getHighlightMergeContiguous - Returns whether or not the collapse contiguous fragments into a single fragment
    • SolrQuery::getHighlightRegexMaxAnalyzedChars - Returns the maximum number of characters from a field when using the regex fragmenter
    • SolrQuery::getHighlightRegexPattern - Returns the regular expression for fragmenting
    • SolrQuery::getHighlightRegexSlop - Returns the deviation factor from the ideal fragment size
    • SolrQuery::getHighlightRequireFieldMatch - Returns if a field will only be highlighted if the query matched in this particular field
    • SolrQuery::getHighlightSimplePost - Returns the text which appears after a highlighted term
    • SolrQuery::getHighlightSimplePre - Returns the text which appears before a highlighted term
    • SolrQuery::getHighlightSnippets - Returns the maximum number of highlighted snippets to generate per field
    • SolrQuery::getHighlightUsePhraseHighlighter - Returns the state of the hl.usePhraseHighlighter parameter
    • SolrQuery::getMlt - Returns whether or not MoreLikeThis results should be enabled
    • SolrQuery::getMltBoost - Returns whether or not the query will be boosted by the interesting term relevance
    • SolrQuery::getMltCount - Returns the number of similar documents to return for each result
    • SolrQuery::getMltFields - Returns all the fields to use for similarity
    • SolrQuery::getMltMaxNumQueryTerms - Returns the maximum number of query terms that will be included in any generated query
    • SolrQuery::getMltMaxNumTokens - Retorna o número máximo de tokens para analisar em cada campo do documento que não está armazenado com suporte a TermVector
    • SolrQuery::getMltMaxWordLength - Returns the maximum word length above which words will be ignored
    • SolrQuery::getMltMinDocFrequency - Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
    • SolrQuery::getMltMinTermFrequency - Returns the frequency below which terms will be ignored in the source document
    • SolrQuery::getMltMinWordLength - Returns the minimum word length below which words will be ignored
    • SolrQuery::getMltQueryFields - Returns the query fields and their boosts
    • SolrQuery::getQuery - Returns the main query
    • SolrQuery::getRows - Returns the maximum number of documents
    • SolrQuery::getSortFields - Returns all the sort fields
    • SolrQuery::getStart - Returns the offset in the complete result set
    • SolrQuery::getStats - Returns whether or not stats is enabled
    • SolrQuery::getStatsFacets - Returns all the stats facets that were set
    • SolrQuery::getStatsFields - Returns all the statistics fields
    • SolrQuery::getTerms - Returns whether or not the TermsComponent is enabled
    • SolrQuery::getTermsField - Returns the field from which the terms are retrieved
    • SolrQuery::getTermsIncludeLowerBound - Returns whether or not to include the lower bound in the result set
    • SolrQuery::getTermsIncludeUpperBound - Returns whether or not to include the upper bound term in the result set
    • SolrQuery::getTermsLimit - Returns the maximum number of terms Solr should return
    • SolrQuery::getTermsLowerBound - Returns the term to start at
    • SolrQuery::getTermsMaxCount - Returns the maximum document frequency
    • SolrQuery::getTermsMinCount - Returns the minimum document frequency to return in order to be included
    • SolrQuery::getTermsPrefix - Returns the term prefix
    • SolrQuery::getTermsReturnRaw - Whether or not to return raw characters
    • SolrQuery::getTermsSort - Returns an integer indicating how terms are sorted
    • SolrQuery::getTermsUpperBound - Returns the term to stop at
    • SolrQuery::getTimeAllowed - Returns the time in milliseconds allowed for the query to finish
    • SolrQuery::removeExpandFilterQuery - Removes an expand filter query
    • SolrQuery::removeExpandSortField - Removes an expand sort field from the expand.sort parameter
    • SolrQuery::removeFacetDateField - Removes one of the facet date fields
    • SolrQuery::removeFacetDateOther - Removes one of the facet.date.other parameters
    • SolrQuery::removeFacetField - Removes one of the facet.date parameters
    • SolrQuery::removeFacetQuery - Removes one of the facet.query parameters
    • SolrQuery::removeField - Removes a field from the list of fields
    • SolrQuery::removeFilterQuery - Removes a filter query
    • SolrQuery::removeHighlightField - Removes one of the fields used for highlighting
    • SolrQuery::removeMltField - Removes one of the moreLikeThis fields
    • SolrQuery::removeMltQueryField - Removes one of the moreLikeThis query fields
    • SolrQuery::removeSortField - Removes one of the sort fields
    • SolrQuery::removeStatsFacet - Removes one of the stats.facet parameters
    • SolrQuery::removeStatsField - Removes one of the stats.field parameters
    • SolrQuery::setEchoHandler - Toggles the echoHandler parameter
    • SolrQuery::setEchoParams - Determines what kind of parameters to include in the response
    • SolrQuery::setExpand - Enables/Disables the Expand Component
    • SolrQuery::setExpandQuery - Sets the expand.q parameter
    • SolrQuery::setExpandRows - Sets the number of rows to display in each group (expand.rows). Server Default 5
    • SolrQuery::setExplainOther - Sets the explainOther common query parameter
    • SolrQuery::setFacet - Maps to the facet parameter. Enables or disables facetting
    • SolrQuery::setFacetDateEnd - Maps to facet.date.end
    • SolrQuery::setFacetDateGap - Maps to facet.date.gap
    • SolrQuery::setFacetDateHardEnd - Maps to facet.date.hardend
    • SolrQuery::setFacetDateStart - Maps to facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency - Sets the minimum document frequency used for determining term count
    • SolrQuery::setFacetLimit - Maps to facet.limit
    • SolrQuery::setFacetMethod - Specifies the type of algorithm to use when faceting a field
    • SolrQuery::setFacetMinCount - Maps to facet.mincount
    • SolrQuery::setFacetMissing - Maps to facet.missing
    • SolrQuery::setFacetOffset - Sets the offset into the list of constraints to allow for pagination
    • SolrQuery::setFacetPrefix - Specifies a string prefix with which to limits the terms on which to facet
    • SolrQuery::setFacetSort - Determines the ordering of the facet field constraints
    • SolrQuery::setGroup - Enable/Disable result grouping (group parameter)
    • SolrQuery::setGroupCachePercent - Enables caching for result grouping
    • SolrQuery::setGroupFacet - Sets group.facet parameter
    • SolrQuery::setGroupFormat - Sets the group format, result structure (group.format parameter)
    • SolrQuery::setGroupLimit - Specifies the number of results to return for each group. The server default value is 1
    • SolrQuery::setGroupMain - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
    • SolrQuery::setGroupNGroups - If true, Solr includes the number of groups that have matched the query in the results
    • SolrQuery::setGroupOffset - Sets the group.offset parameter
    • SolrQuery::setGroupTruncate - If true, facet counts are based on the most relevant document of each group matching the query
    • SolrQuery::setHighlight - Enables or disables highlighting
    • SolrQuery::setHighlightAlternateField - Specifies the backup field to use
    • SolrQuery::setHighlightFormatter - Specify a formatter for the highlight output
    • SolrQuery::setHighlightFragmenter - Sets a text snippet generator for highlighted text
    • SolrQuery::setHighlightFragsize - The size of fragments to consider for highlighting
    • SolrQuery::setHighlightHighlightMultiTerm - Use SpanScorer to highlight phrase terms
    • SolrQuery::setHighlightMaxAlternateFieldLength - Sets the maximum number of characters of the field to return
    • SolrQuery::setHighlightMaxAnalyzedChars - Specifies the number of characters into a document to look for suitable snippets
    • SolrQuery::setHighlightMergeContiguous - Whether or not to collapse contiguous fragments into a single fragment
    • SolrQuery::setHighlightRegexMaxAnalyzedChars - Specify the maximum number of characters to analyze
    • SolrQuery::setHighlightRegexPattern - Specify the regular expression for fragmenting
    • SolrQuery::setHighlightRegexSlop - Sets the factor by which the regex fragmenter can stray from the ideal fragment size
    • SolrQuery::setHighlightRequireFieldMatch - Require field matching during highlighting
    • SolrQuery::setHighlightSimplePost - Sets the text which appears after a highlighted term
    • SolrQuery::setHighlightSimplePre - Sets the text which appears before a highlighted term
    • SolrQuery::setHighlightSnippets - Sets the maximum number of highlighted snippets to generate per field
    • SolrQuery::setHighlightUsePhraseHighlighter - Whether to highlight phrase terms only when they appear within the query phrase
    • SolrQuery::setMlt - Enables or disables moreLikeThis
    • SolrQuery::setMltBoost - Set if the query will be boosted by the interesting term relevance
    • SolrQuery::setMltCount - Set the number of similar documents to return for each result
    • SolrQuery::setMltMaxNumQueryTerms - Sets the maximum number of query terms included
    • SolrQuery::setMltMaxNumTokens - Specifies the maximum number of tokens to parse
    • SolrQuery::setMltMaxWordLength - Sets the maximum word length
    • SolrQuery::setMltMinDocFrequency - Sets the mltMinDoc frequency
    • SolrQuery::setMltMinTermFrequency - Sets the frequency below which terms will be ignored in the source docs
    • SolrQuery::setMltMinWordLength - Sets the minimum word length
    • SolrQuery::setOmitHeader - Exclude the header from the returned results
    • SolrQuery::setQuery - Sets the search query
    • SolrQuery::setRows - Specifies the maximum number of rows to return in the result
    • SolrQuery::setShowDebugInfo - Flag to show debug information
    • SolrQuery::setStart - Specifies the number of rows to skip
    • SolrQuery::setStats - Enables or disables the Stats component
    • SolrQuery::setTerms - Enables or disables the TermsComponent
    • SolrQuery::setTermsField - Sets the name of the field to get the Terms from
    • SolrQuery::setTermsIncludeLowerBound - Include the lower bound term in the result set
    • SolrQuery::setTermsIncludeUpperBound - Include the upper bound term in the result set
    • SolrQuery::setTermsLimit - Sets the maximum number of terms to return
    • SolrQuery::setTermsLowerBound - Specifies the Term to start from
    • SolrQuery::setTermsMaxCount - Sets the maximum document frequency
    • SolrQuery::setTermsMinCount - Sets the minimum document frequency
    • SolrQuery::setTermsPrefix - Restrict matches to terms that start with the prefix
    • SolrQuery::setTermsReturnRaw - Return the raw characters of the indexed term
    • SolrQuery::setTermsSort - Specifies how to sort the returned terms
    • SolrQuery::setTermsUpperBound - Sets the term to stop at
    • SolrQuery::setTimeAllowed - The time allowed for search to finish
    • SolrQuery::__construct - Constructor
    • SolrQuery::__destruct - Destructor
    • SolrQueryResponse::__construct - Constructor
    • SolrQueryResponse::__destruct - Destructor
    • SolrResponse::getDigestedResponse - Returns the XML response as serialized PHP data
    • SolrResponse::getHttpStatus - Returns the HTTP status of the response
    • SolrResponse::getHttpStatusMessage - Returns more details on the HTTP status
    • SolrResponse::getRawRequest - Returns the raw request sent to the Solr server
    • SolrResponse::getRawRequestHeaders - Returns the raw request headers sent to the Solr server
    • SolrResponse::getRawResponse - Returns the raw response from the server
    • SolrResponse::getRawResponseHeaders - Returns the raw response headers from the server
    • SolrResponse::getRequestUrl - Returns the full URL the request was sent to
    • SolrResponse::getResponse - Returns a SolrObject representing the XML response from the server
    • SolrResponse::setParseMode - Sets the parse mode
    • SolrResponse::success - Was the request a success
    • SolrServerException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrUpdateResponse::__construct - Constructor
    • SolrUpdateResponse::__destruct - Destructor
    • SolrUtils::digestXmlResponse - Parses an response XML string into a SolrObject
    • SolrUtils::escapeQueryChars - Escapes a lucene query string
    • SolrUtils::getSolrVersion - Returns the current version of the Solr extension
    • SolrUtils::queryPhrase - Prepares a phrase from an unescaped lucene string
    • solr_get_version - Retorna a versão atual da extensão Apache Solr
    • sort - Ordena um array em ordem ascendente
    • soundex - Calcula a chave soundex de uma string
    • SplDoublyLinkedList::add - Add/insert a new value at the specified index
    • SplDoublyLinkedList::bottom - Peeks at the node from the beginning of the doubly linked list
    • SplDoublyLinkedList::count - Counts the number of elements in the doubly linked list
    • SplDoublyLinkedList::current - Return current array entry
    • SplDoublyLinkedList::getIteratorMode - Returns the mode of iteration
    • SplDoublyLinkedList::isEmpty - Checks whether the doubly linked list is empty
    • SplDoublyLinkedList::key - Return current node index
    • SplDoublyLinkedList::next - Move to next entry
    • SplDoublyLinkedList::offsetExists - Returns whether the requested $index exists
    • SplDoublyLinkedList::offsetGet - Returns the value at the specified $index
    • SplDoublyLinkedList::offsetSet - Sets the value at the specified $index to $value
    • SplDoublyLinkedList::offsetUnset - Unsets the value at the specified $index
    • SplDoublyLinkedList::pop - Pops a node from the end of the doubly linked list
    • SplDoublyLinkedList::prev - Move to previous entry
    • SplDoublyLinkedList::push - Pushes an element at the end of the doubly linked list
    • SplDoublyLinkedList::rewind - Rewind iterator back to the start
    • SplDoublyLinkedList::serialize - Serializes the storage
    • SplDoublyLinkedList::setIteratorMode - Sets the mode of iteration
    • SplDoublyLinkedList::shift - Shifts a node from the beginning of the doubly linked list
    • SplDoublyLinkedList::top - Peeks at the node from the end of the doubly linked list
    • SplDoublyLinkedList::unserialize - Unserializes the storage
    • SplDoublyLinkedList::unshift - Prepends the doubly linked list with an element
    • SplDoublyLinkedList::valid - Check whether the doubly linked list contains more nodes
    • SplFileInfo::getATime - Gets last access time of the file
    • SplFileInfo::getBasename - Gets the base name of the file
    • SplFileInfo::getCTime - Gets the inode change time
    • SplFileInfo::getExtension - Gets the file extension
    • SplFileInfo::getFileInfo - Gets an SplFileInfo object for the file
    • SplFileInfo::getFilename - Gets the filename
    • SplFileInfo::getGroup - Gets the file group
    • SplFileInfo::getInode - Gets the inode for the file
    • SplFileInfo::getLinkTarget - Gets the target of a link
    • SplFileInfo::getMTime - Gets the last modified time
    • SplFileInfo::getOwner - Gets the owner of the file
    • SplFileInfo::getPath - Gets the path without filename
    • SplFileInfo::getPathInfo - Gets an SplFileInfo object for the path
    • SplFileInfo::getPathname - Gets the path to the file
    • SplFileInfo::getPerms - Gets file permissions
    • SplFileInfo::getRealPath - Gets absolute path to file
    • SplFileInfo::getSize - Gets file size
    • SplFileInfo::getType - Gets file type
    • SplFileInfo::isDir - Tells if the file is a directory
    • SplFileInfo::isExecutable - Tells if the file is executable
    • SplFileInfo::isFile - Tells if the object references a regular file
    • SplFileInfo::isLink - Tells if the file is a link
    • SplFileInfo::isReadable - Tells if file is readable
    • SplFileInfo::isWritable - Tells if the entry is writable
    • SplFileInfo::openFile - Gets an SplFileObject object for the file
    • SplFileInfo::setFileClass - Sets the class used with SplFileInfo::openFile
    • SplFileInfo::setInfoClass - Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo
    • SplFileInfo::__construct - Construct a new SplFileInfo object
    • SplFileInfo::__toString - Returns the path to the file as a string
    • SplFileObject::current - Retrieve current line of file
    • SplFileObject::eof - Reached end of file
    • SplFileObject::fflush - Flushes the output to the file
    • SplFileObject::fgetc - Gets character from file
    • SplFileObject::fgetcsv - Gets line from file and parse as CSV fields
    • SplFileObject::fgets - Gets line from file
    • SplFileObject::fgetss - Gets line from file and strip HTML tags
    • SplFileObject::flock - Portable file locking
    • SplFileObject::fpassthru - Output all remaining data on a file pointer
    • SplFileObject::fputcsv - Write a field array as a CSV line
    • SplFileObject::fread - Read from file
    • SplFileObject::fscanf - Parses input from file according to a format
    • SplFileObject::fseek - Seek to a position
    • SplFileObject::fstat - Gets information about the file
    • SplFileObject::ftell - Return current file position
    • SplFileObject::ftruncate - Truncates the file to a given length
    • SplFileObject::fwrite - Write to file
    • SplFileObject::getChildren - No purpose
    • SplFileObject::getCsvControl - Get the delimiter, enclosure and escape character for CSV
    • SplFileObject::getCurrentLine - Sinônimo de SplFileObject::fgets
    • SplFileObject::getFlags - Gets flags for the SplFileObject
    • SplFileObject::getMaxLineLen - Get maximum line length
    • SplFileObject::hasChildren - SplFileObject does not have children
    • SplFileObject::key - Get line number
    • SplFileObject::next - Read next line
    • SplFileObject::rewind - Rewind the file to the first line
    • SplFileObject::seek - Seek to specified line
    • SplFileObject::setCsvControl - Set the delimiter, enclosure and escape character for CSV
    • SplFileObject::setFlags - Sets flags for the SplFileObject
    • SplFileObject::setMaxLineLen - Set maximum line length
    • SplFileObject::valid - Not at EOF
    • SplFileObject::__construct - Construct a new file object
    • SplFileObject::__toString - Returns the current line as a string
    • SplFixedArray::count - Returns the size of the array
    • SplFixedArray::current - Return current array entry
    • SplFixedArray::fromArray - Import a PHP array in a SplFixedArray instance
    • SplFixedArray::getIterator - Retrieve the iterator to go through the array
    • SplFixedArray::getSize - Gets the size of the array
    • SplFixedArray::jsonSerialize - Returns a representation that can be converted to JSON
    • SplFixedArray::key - Return current array index
    • SplFixedArray::next - Move to next entry
    • SplFixedArray::offsetExists - Returns whether the requested index exists
    • SplFixedArray::offsetGet - Returns the value at the specified index
    • SplFixedArray::offsetSet - Sets a new value at a specified index
    • SplFixedArray::offsetUnset - Unsets the value at the specified $index
    • SplFixedArray::rewind - Rewind iterator back to the start
    • SplFixedArray::setSize - Change the size of an array
    • SplFixedArray::toArray - Returns a PHP array from the fixed array
    • SplFixedArray::valid - Check whether the array contains more elements
    • SplFixedArray::__construct - Constructs a new fixed array
    • SplFixedArray::__serialize - Serializes the SplFixedArray object
    • SplFixedArray::__unserialize - Deserializes the data parameter into an SplFixedArray object
    • SplFixedArray::__wakeup - Reinitialises the array after being unserialised
    • SplHeap::compare - Compare elements in order to place them correctly in the heap while sifting up
    • SplHeap::count - Counts the number of elements in the heap
    • SplHeap::current - Return current node pointed by the iterator
    • SplHeap::extract - Extracts a node from top of the heap and sift up
    • SplHeap::insert - Inserts an element in the heap by sifting it up
    • SplHeap::isCorrupted - Tells if the heap is in a corrupted state
    • SplHeap::isEmpty - Checks whether the heap is empty
    • SplHeap::key - Return current node index
    • SplHeap::next - Move to the next node
    • SplHeap::recoverFromCorruption - Recover from the corrupted state and allow further actions on the heap
    • SplHeap::rewind - Rewind iterator back to the start (no-op)
    • SplHeap::top - Peeks at the node from the top of the heap
    • SplHeap::valid - Check whether the heap contains more nodes
    • SplMaxHeap::compare - Compare elements in order to place them correctly in the heap while sifting up
    • SplMinHeap::compare - Compare elements in order to place them correctly in the heap while sifting up
    • SplObjectStorage::addAll - Adds all objects from another storage
    • SplObjectStorage::attach - Adds an object in the storage
    • SplObjectStorage::contains - Checks if the storage contains a specific object
    • SplObjectStorage::count - Returns the number of objects in the storage
    • SplObjectStorage::current - Returns the current storage entry
    • SplObjectStorage::detach - Removes an object from the storage
    • SplObjectStorage::getHash - Calculate a unique identifier for the contained objects
    • SplObjectStorage::getInfo - Returns the data associated with the current iterator entry
    • SplObjectStorage::key - Returns the index at which the iterator currently is
    • SplObjectStorage::next - Move to the next entry
    • SplObjectStorage::offsetExists - Checks whether an object exists in the storage
    • SplObjectStorage::offsetGet - Returns the data associated with an object
    • SplObjectStorage::offsetSet - Associates data to an object in the storage
    • SplObjectStorage::offsetUnset - Removes an object from the storage
    • SplObjectStorage::removeAll - Removes objects contained in another storage from the current storage
    • SplObjectStorage::removeAllExcept - Removes all objects except for those contained in another storage from the current storage
    • SplObjectStorage::rewind - Rewind the iterator to the first storage element
    • SplObjectStorage::serialize - Serializes the storage
    • SplObjectStorage::setInfo - Sets the data associated with the current iterator entry
    • SplObjectStorage::unserialize - Unserializes a storage from its string representation
    • SplObjectStorage::valid - Returns if the current iterator entry is valid
    • SplObserver::update - Receive update from subject
    • SplPriorityQueue::compare - Compare priorities in order to place elements correctly in the heap while sifting up
    • SplPriorityQueue::count - Counts the number of elements in the queue
    • SplPriorityQueue::current - Return current node pointed by the iterator
    • SplPriorityQueue::extract - Extracts a node from top of the heap and sift up
    • SplPriorityQueue::getExtractFlags - Get the flags of extraction
    • SplPriorityQueue::insert - Inserts an element in the queue by sifting it up
    • SplPriorityQueue::isCorrupted - Tells if the priority queue is in a corrupted state
    • SplPriorityQueue::isEmpty - Checks whether the queue is empty
    • SplPriorityQueue::key - Return current node index
    • SplPriorityQueue::next - Move to the next node
    • SplPriorityQueue::recoverFromCorruption - Recover from the corrupted state and allow further actions on the queue
    • SplPriorityQueue::rewind - Rewind iterator back to the start (no-op)
    • SplPriorityQueue::setExtractFlags - Sets the mode of extraction
    • SplPriorityQueue::top - Peeks at the node from the top of the queue
    • SplPriorityQueue::valid - Check whether the queue contains more nodes
    • SplQueue::dequeue - Dequeues a node from the queue
    • SplQueue::enqueue - Adds an element to the queue
    • SplSubject::attach - Attach an SplObserver
    • SplSubject::detach - Detach an observer
    • SplSubject::notify - Notify an observer
    • SplTempFileObject::__construct - Construct a new temporary file object
    • spl_autoload - Default implementation for __autoload()
    • spl_autoload_call - Tenta todas as funções __autoload() registradas para carregar a classe solicitada
    • spl_autoload_extensions - Register and return default file extensions for spl_autoload
    • spl_autoload_functions - Return all registered __autoload() functions
    • spl_autoload_register - Register given function as __autoload() implementation
    • spl_autoload_unregister - Unregister given function as __autoload() implementation
    • spl_classes - Retorna as classes da SPL disponíveis
    • spl_object_hash - Return hash id for given object
    • spl_object_id - Return the integer object handle for given object
    • Spoofchecker::areConfusable - Checks if given strings can be confused
    • Spoofchecker::isSuspicious - Checks if a given text contains any suspicious characters
    • Spoofchecker::setAllowedLocales - Locales to use when running checks
    • Spoofchecker::setChecks - Set the checks to run
    • Spoofchecker::setRestrictionLevel - Set the restriction level
    • Spoofchecker::__construct - Constructor
    • sprintf - Return a formatted string
    • SQLite3::backup - Backup one database to another database
    • SQLite3::busyTimeout - Sets the busy connection handler
    • SQLite3::changes - Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
    • SQLite3::close - Closes the database connection
    • SQLite3::createAggregate - Registers a PHP function for use as an SQL aggregate function
    • SQLite3::createCollation - Registers a PHP function for use as an SQL collating function
    • SQLite3::createFunction - Registers a PHP function for use as an SQL scalar function
    • SQLite3::enableExceptions - Enable throwing exceptions
    • SQLite3::escapeString - Returns a string that has been properly escaped
    • SQLite3::exec - Executes a result-less query against a given database
    • SQLite3::lastErrorCode - Returns the numeric result code of the most recent failed SQLite request
    • SQLite3::lastErrorMsg - Returns English text describing the most recent failed SQLite request
    • SQLite3::lastInsertRowID - Returns the row ID of the most recent INSERT into the database
    • SQLite3::loadExtension - Attempts to load an SQLite extension library
    • SQLite3::open - Opens an SQLite database
    • SQLite3::openBlob - Opens a stream resource to read a BLOB
    • SQLite3::prepare - Prepares an SQL statement for execution
    • SQLite3::query - Executes an SQL query
    • SQLite3::querySingle - Executes a query and returns a single result
    • SQLite3::setAuthorizer - Configures a callback to be used as an authorizer to limit what a statement can do
    • SQLite3::version - Returns the SQLite3 library version as a string constant and as a number
    • SQLite3::__construct - Instantiates an SQLite3 object and opens an SQLite 3 database
    • SQLite3Result::columnName - Returns the name of the nth column
    • SQLite3Result::columnType - Returns the type of the nth column
    • SQLite3Result::fetchArray - Fetches a result row as an associative or numerically indexed array or both
    • SQLite3Result::finalize - Closes the result set
    • SQLite3Result::numColumns - Returns the number of columns in the result set
    • SQLite3Result::reset - Resets the result set back to the first row
    • SQLite3Result::__construct - Constructs an SQLite3Result
    • SQLite3Stmt::bindParam - Binds a parameter to a statement variable
    • SQLite3Stmt::bindValue - Binds the value of a parameter to a statement variable
    • SQLite3Stmt::clear - Clears all current bound parameters
    • SQLite3Stmt::close - Closes the prepared statement
    • SQLite3Stmt::execute - Executes a prepared statement and returns a result set object
    • SQLite3Stmt::getSQL - Get the SQL of the statement
    • SQLite3Stmt::paramCount - Returns the number of parameters within the prepared statement
    • SQLite3Stmt::readOnly - Returns whether a statement is definitely read only
    • SQLite3Stmt::reset - Resets the prepared statement
    • SQLite3Stmt::__construct - Constructs an SQLite3Stmt object
    • sqlsrv_begin_transaction - Begins a database transaction
    • sqlsrv_cancel - Cancels a statement
    • sqlsrv_client_info - Returns information about the client and specified connection
    • sqlsrv_close - Closes an open connection and releases resourses associated with the connection
    • sqlsrv_commit - Commits a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_configure - Changes the driver error handling and logging configurations
    • sqlsrv_connect - Opens a connection to a Microsoft SQL Server database
    • sqlsrv_errors - Returns error and warning information about the last SQLSRV operation performed
    • sqlsrv_execute - Executes a statement prepared with sqlsrv_prepare
    • sqlsrv_fetch - Makes the next row in a result set available for reading
    • sqlsrv_fetch_array - Returns a row as an array
    • sqlsrv_fetch_object - Retrieves the next row of data in a result set as an object
    • sqlsrv_field_metadata - Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
    • sqlsrv_free_stmt - Frees all resources for the specified statement
    • sqlsrv_get_config - Returns the value of the specified configuration setting
    • sqlsrv_get_field - Gets field data from the currently selected row
    • sqlsrv_has_rows - Indicates whether the specified statement has rows
    • sqlsrv_next_result - Makes the next result of the specified statement active
    • sqlsrv_num_fields - Retrieves the number of fields (columns) on a statement
    • sqlsrv_num_rows - Retrieves the number of rows in a result set
    • sqlsrv_prepare - Prepares a query for execution
    • sqlsrv_query - Prepares and executes a query
    • sqlsrv_rollback - Rolls back a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_rows_affected - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
    • sqlsrv_send_stream_data - Sends data from parameter streams to the server
    • sqlsrv_server_info - Returns information about the server
    • SqlStatement::bind - Bind statement parameters
    • SqlStatement::execute - Execute the operation
    • SqlStatement::getNextResult - Get next result
    • SqlStatement::getResult - Get result
    • SqlStatement::hasMoreResults - Check for more results
    • SqlStatement::__construct - Description constructor
    • SqlStatementResult::fetchAll - Get all rows from result
    • SqlStatementResult::fetchOne - Get single row
    • SqlStatementResult::getAffectedItemsCount - Get affected row count
    • SqlStatementResult::getColumnNames - Get column names
    • SqlStatementResult::getColumns - Get columns
    • SqlStatementResult::getColumnsCount - Get column count
    • SqlStatementResult::getGeneratedIds - Get generated ids
    • SqlStatementResult::getLastInsertId - Get last insert id
    • SqlStatementResult::getWarnings - Get warnings from last operation
    • SqlStatementResult::getWarningsCount - Get warning count from last operation
    • SqlStatementResult::hasData - Check if result has data
    • SqlStatementResult::nextResult - Get next result
    • SqlStatementResult::__construct - Description constructor
    • sqrt - Raiz quadrada
    • srand - Seed the random number generator
    • sscanf - Interpreta a entrada de uma string de acordo com um 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:// - Shell Seguro 2
    • ssh2_auth_agent - Authenticate over SSH using the ssh agent
    • ssh2_auth_hostbased_file - Authenticate using a public hostkey
    • ssh2_auth_none - Authenticate as "none"
    • ssh2_auth_password - Authenticate over SSH using a plain password
    • ssh2_auth_pubkey_file - Authenticate using a public key
    • ssh2_connect - Connect to an SSH server
    • ssh2_disconnect - Close a connection to a remote SSH server
    • ssh2_exec - Execute a command on a remote server
    • ssh2_fetch_stream - Fetch an extended data stream
    • ssh2_fingerprint - Retrieve fingerprint of remote server
    • ssh2_forward_accept - Accept a connection created by a listener
    • ssh2_forward_listen - Bind a port on the remote server and listen for connections
    • ssh2_methods_negotiated - Return list of negotiated methods
    • ssh2_poll - Poll the channels/listeners/streams for events
    • ssh2_publickey_add - Add an authorized publickey
    • ssh2_publickey_init - Initialize Publickey subsystem
    • ssh2_publickey_list - List currently authorized publickeys
    • ssh2_publickey_remove - Remove an authorized publickey
    • ssh2_scp_recv - Request a file via SCP
    • ssh2_scp_send - Send a file via SCP
    • ssh2_send_eof - Send EOF to stream
    • ssh2_sftp - Initialize SFTP subsystem
    • ssh2_sftp_chmod - Changes file mode
    • ssh2_sftp_lstat - Stat a symbolic link
    • ssh2_sftp_mkdir - Create a directory
    • ssh2_sftp_readlink - Return the target of a symbolic link
    • ssh2_sftp_realpath - Resolve the realpath of a provided path string
    • ssh2_sftp_rename - Rename a remote file
    • ssh2_sftp_rmdir - Remove a directory
    • ssh2_sftp_stat - Stat a file on a remote filesystem
    • ssh2_sftp_symlink - Create a symlink
    • ssh2_sftp_unlink - Delete a file
    • ssh2_shell - Request an interactive shell
    • ssh2_tunnel - Open a tunnel through a remote server
    • stat - Obtém informações sobre um arquivo
    • Statement::getNextResult - Get next result
    • Statement::getResult - Get result
    • Statement::hasMoreResults - Check if more results
    • Statement::__construct - Description constructor
    • stats_absolute_deviation - Returns the absolute deviation of an array of values
    • stats_cdf_beta - Calculates any one parameter of the beta distribution given values for the others
    • stats_cdf_binomial - Calculates any one parameter of the binomial distribution given values for the others
    • stats_cdf_cauchy - Calculates any one parameter of the Cauchy distribution given values for the others
    • stats_cdf_chisquare - Calculates any one parameter of the chi-square distribution given values for the others
    • stats_cdf_exponential - Calculates any one parameter of the exponential distribution given values for the others
    • stats_cdf_f - Calculates any one parameter of the F distribution given values for the others
    • stats_cdf_gamma - Calculates any one parameter of the gamma distribution given values for the others
    • stats_cdf_laplace - Calculates any one parameter of the Laplace distribution given values for the others
    • stats_cdf_logistic - Calculates any one parameter of the logistic distribution given values for the others
    • stats_cdf_negative_binomial - Calculates any one parameter of the negative binomial distribution given values for the others
    • stats_cdf_noncentral_chisquare - Calculates any one parameter of the non-central chi-square distribution given values for the others
    • stats_cdf_noncentral_f - Calculates any one parameter of the non-central F distribution given values for the others
    • stats_cdf_noncentral_t - Calculates any one parameter of the non-central t-distribution give values for the others
    • stats_cdf_normal - Calculates any one parameter of the normal distribution given values for the others
    • stats_cdf_poisson - Calculates any one parameter of the Poisson distribution given values for the others
    • stats_cdf_t - Calculates any one parameter of the t-distribution given values for the others
    • stats_cdf_uniform - Calculates any one parameter of the uniform distribution given values for the others
    • stats_cdf_weibull - Calculates any one parameter of the Weibull distribution given values for the others
    • stats_covariance - Computes the covariance of two data sets
    • stats_dens_beta - Probability density function of the beta distribution
    • stats_dens_cauchy - Probability density function of the Cauchy distribution
    • stats_dens_chisquare - Probability density function of the chi-square distribution
    • stats_dens_exponential - Probability density function of the exponential distribution
    • stats_dens_f - Probability density function of the F distribution
    • stats_dens_gamma - Probability density function of the gamma distribution
    • stats_dens_laplace - Probability density function of the Laplace distribution
    • stats_dens_logistic - Probability density function of the logistic distribution
    • stats_dens_normal - Probability density function of the normal distribution
    • stats_dens_pmf_binomial - Probability mass function of the binomial distribution
    • stats_dens_pmf_hypergeometric - Probability mass function of the hypergeometric distribution
    • stats_dens_pmf_negative_binomial - Probability mass function of the negative binomial distribution
    • stats_dens_pmf_poisson - Probability mass function of the Poisson distribution
    • stats_dens_t - Probability density function of the t-distribution
    • stats_dens_uniform - Probability density function of the uniform distribution
    • stats_dens_weibull - Probability density function of the Weibull distribution
    • stats_harmonic_mean - Returns the harmonic mean of an array of values
    • stats_kurtosis - Computes the kurtosis of the data in the array
    • stats_rand_gen_beta - Generates a random deviate from the beta distribution
    • stats_rand_gen_chisquare - Generates a random deviate from the chi-square distribution
    • stats_rand_gen_exponential - Generates a random deviate from the exponential distribution
    • stats_rand_gen_f - Generates a random deviate from the F distribution
    • stats_rand_gen_funiform - Generates uniform float between low (exclusive) and high (exclusive)
    • stats_rand_gen_gamma - Generates a random deviate from the gamma distribution
    • stats_rand_gen_ibinomial - Generates a random deviate from the binomial distribution
    • stats_rand_gen_ibinomial_negative - Generates a random deviate from the negative binomial distribution
    • stats_rand_gen_int - Generates random integer between 1 and 2147483562
    • stats_rand_gen_ipoisson - Generates a single random deviate from a Poisson distribution
    • stats_rand_gen_iuniform - Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
    • stats_rand_gen_noncentral_chisquare - Generates a random deviate from the non-central chi-square distribution
    • stats_rand_gen_noncentral_f - Generates a random deviate from the noncentral F distribution
    • stats_rand_gen_noncentral_t - Generates a single random deviate from a non-central t-distribution
    • stats_rand_gen_normal - Generates a single random deviate from a normal distribution
    • stats_rand_gen_t - Generates a single random deviate from a t-distribution
    • stats_rand_get_seeds - Get the seed values of the random number generator
    • stats_rand_phrase_to_seeds - Generate two seeds for the RGN random number generator
    • stats_rand_ranf - Generates a random floating point number between 0 and 1
    • stats_rand_setall - Set seed values to the random generator
    • stats_skew - Computes the skewness of the data in the array
    • stats_standard_deviation - Returns the standard deviation
    • stats_stat_binomial_coef - Returns a binomial coefficient
    • stats_stat_correlation - Returns the Pearson correlation coefficient of two data sets
    • stats_stat_factorial - Returns the factorial of an integer
    • stats_stat_independent_t - Returns the t-value from the independent two-sample t-test
    • stats_stat_innerproduct - Returns the inner product of two vectors
    • stats_stat_paired_t - Returns the t-value of the dependent t-test for paired samples
    • stats_stat_percentile - Returns the percentile value
    • stats_stat_powersum - Returns the power sum of a vector
    • stats_variance - Returns the variance
    • Stomp::abort - Rolls back a transaction in progress
    • Stomp::ack - Acknowledges consumption of a message
    • Stomp::begin - Starts a transaction
    • Stomp::commit - Commits a transaction in progress
    • Stomp::error - Gets the last stomp error
    • Stomp::getReadTimeout - Gets read timeout
    • Stomp::getSessionId - Gets the current stomp session ID
    • Stomp::hasFrame - Indicates whether or not there is a frame ready to read
    • Stomp::readFrame - Reads the next frame
    • Stomp::send - Sends a message
    • Stomp::setReadTimeout - Sets read timeout
    • Stomp::subscribe - Registers to listen to a given destination
    • Stomp::unsubscribe - Removes an existing subscription
    • Stomp::__construct - Opens a connection
    • Stomp::__destruct - Closes stomp connection
    • StompException::getDetails - Get exception details
    • StompFrame::__construct - Constructor
    • stomp_connect_error - Returns a string description of the last connect error
    • stomp_version - Gets the current stomp extension version
    • strcasecmp - Binary safe case-insensitive string comparison
    • strchr - Sinônimo de strstr
    • strcmp - Binary safe string comparison
    • strcoll - Locale based string comparison
    • strcspn - Encontra o tamanho do segmento inicial que não corresponde à máscara
    • streamWrapper::dir_closedir - Fecha o manipulador de diretório
    • streamWrapper::dir_opendir - Abre um manipulador de diretório
    • streamWrapper::dir_readdir - Lê entrada do manipulador de diretório
    • streamWrapper::dir_rewinddir - Retrocede um manipulador de diretório
    • streamWrapper::mkdir - Cria um diretório
    • streamWrapper::rename - Renomeia um arquivo ou diretório
    • streamWrapper::rmdir - Remove um diretório
    • streamWrapper::stream_cast - Obtém o recurso subjacente
    • streamWrapper::stream_close - Fecha um recurso
    • streamWrapper::stream_eof - Teste para fim de arquivo em ponteiros
    • streamWrapper::stream_flush - Descarrega a saída
    • streamWrapper::stream_lock - Travamento de aviso para arquivos
    • streamWrapper::stream_metadata - Alterar metadados de fluxo
    • streamWrapper::stream_open - Abre arquivo ou URL
    • streamWrapper::stream_read - Lê dados do fluxo
    • streamWrapper::stream_seek - Pesquisa uma localização específica em um fluxo
    • streamWrapper::stream_set_option - Altera as opções do fluxo
    • streamWrapper::stream_stat - Obtém informação sobre um recurso de arquivo
    • streamWrapper::stream_tell - Obtém a posição atual de um fluxo
    • streamWrapper::stream_truncate - Trunca o fluxo
    • streamWrapper::stream_write - Escreve no fluxo
    • streamWrapper::unlink - Remove um arquivo
    • streamWrapper::url_stat - Obtém informação sobre um arquivo
    • streamWrapper::__construct - Constrói um novo empacotador de fluxo
    • streamWrapper::__destruct - Destrói um empacotador de fluxo existente
    • stream_bucket_append - Anexa o bucket à brigada
    • stream_bucket_make_writeable - Retorna um objeto bucket da brigada para se operar sobre ele
    • stream_bucket_new - Cria um novo bucket para uso no fluxo atual
    • stream_bucket_prepend - Adiciona um bucket ao início da brigada
    • stream_context_create - Cria um contexto de fluxo
    • stream_context_get_default - Obtém o contexto padrão de fluxo
    • stream_context_get_options - Obtém opções para um fluxo/empacotador/contexto
    • stream_context_get_params - Obtém parâmetros de um contexto
    • stream_context_set_default - Define o contexto padrão do fluxo
    • stream_context_set_option - Define uma opção para um fluxo/empacotador/contexto
    • stream_context_set_options - Define opções no contexto especificado
    • stream_context_set_params - Define parâmetros para um fluxo/empacotador/contexto
    • stream_copy_to_stream - Copia dados de um fluxo para outro
    • stream_filter_append - Anexa um filtro a um fluxo
    • stream_filter_prepend - Anexa um filtro a um fluxo
    • stream_filter_register - Registra um filtro de fluxo definido pelo usuário
    • stream_filter_remove - Remove um filtro de um fluxo
    • stream_get_contents - Lê o restante de um fluxo em uma string
    • stream_get_filters - Obtém lista de filtros registrados
    • stream_get_line - Obtém uma linha do recurso do fluxo até um delimitador informado
    • stream_get_meta_data - Obtém cabeçalhos/metadados de ponteiros de arquivos/fluxos
    • stream_get_transports - Obtém lista de transportes socket registrados
    • stream_get_wrappers - Obtém lista de fluxos registrados
    • stream_isatty - Verifica se um fluxo é um TTY
    • stream_is_local - Verifica se o fluxo é local
    • stream_notification_callback - Uma função de chamada de retorno para o parâmetro de contexto de notification
    • stream_register_wrapper - Sinônimo de stream_wrapper_register
    • stream_resolve_include_path - Resolve o nome do arquivo em relação ao caminho de include
    • stream_select - Executa o equivalente à chamada de sistema select() nos arrays de fluxos informados com um limite de tempo especificado por segundos e microssegundos
    • stream_set_blocking - Definir modo de bloqueio/não-bloqueio em um fluxo
    • stream_set_chunk_size - Define o tamanho do pacote do fluxo
    • stream_set_read_buffer - Define o tamanho de buffer de leitura do stream
    • stream_set_timeout - Define o limite de tempo em um fluxo
    • stream_set_write_buffer - Define o tamanho do buffer de escrita do fluxo
    • stream_socket_accept - Aceita uma conexão em um socket criado por stream_socket_server
    • stream_socket_client - Abre conexão de socket de domínio Internet ou Unix
    • stream_socket_enable_crypto - Liga ou desliga criptografia em socket já conectado
    • stream_socket_get_name - Obtém o nome do socket local ou remoto
    • stream_socket_pair - Cria um par de fluxos de socket conectados e indistinguíveis
    • stream_socket_recvfrom - Recebe dados de um socket, conectado ou não
    • stream_socket_sendto - Envia uma mensagem a um socket, conectado ou não
    • stream_socket_server - Cria socket de servidor de domínio Internet ou Unix
    • stream_socket_shutdown - Fecha uma conexão full-duplex
    • stream_supports_lock - Informa se o fluxo suporta travamento
    • stream_wrapper_register - Registra um empacotador URL implementado como uma classe PHP
    • stream_wrapper_restore - Restaura um empacotador interno anteriormente desregistrado
    • stream_wrapper_unregister - Desregistra um empacotador URL
    • strftime - Formata uma hora/data de acordo com as configurações locais
    • Stringable::__toString - Obtém a representação em string do objeto
    • stripcslashes - Remove o escape de strings escapadas com addcslashes
    • stripos - Find the position of the first occurrence of a case-insensitive substring in a string
    • stripslashes - Desfaz os escapes de uma string escapada
    • strip_tags - Retira as tags HTML e PHP de uma string
    • stristr - Case-insensitive strstr
    • strlen - Retorna o tamanho de uma string
    • strnatcasecmp - Comparação de strings insensível a maiúsculas/minúsculas usando o algoritmo de "ordem natural"
    • strnatcmp - String comparisons using a "natural order" algorithm
    • strncasecmp - Comparação binária de strings, insensível a maiúsculas/minúsculas, dos primeiros n caracteres
    • strncmp - Binary safe string comparison of the first n characters
    • strpbrk - Procura na string por um dos caracteres de um conjunto
    • strpos - Find the position of the first occurrence of a substring in a string
    • strptime - Interpreta uma hora/data gerada pela função strftime
    • strrchr - Find the last occurrence of a character in a string
    • strrev - Reverte uma string
    • strripos - Find the position of the last occurrence of a case-insensitive substring in a string
    • strrpos - Find the position of the last occurrence of a substring in a string
    • strspn - Encontra o comprimento do segmento inicial de uma string composta totalmente de caracteres contidos em uma máscara informada
    • strstr - Find the first occurrence of a string
    • strtok - Tokenize string
    • strtolower - Converte uma string para minúsculas
    • strtotime - Interpreta qualquer descrição textual de data/hora em inglês para timestamp Unix
    • strtoupper - Make a string uppercase
    • strtr - Translate characters or replace substrings
    • strval - Retorna o valor string de uma variável
    • str_contains - Determina se uma string contém uma substring fornecida
    • str_decrement - Decrement an alphanumeric string
    • str_ends_with - Verifica se uma string termina com uma substring fornecida
    • str_getcsv - Analisa uma string CSV e retorna os dados em um array
    • str_increment - Increment an alphanumeric string
    • str_ireplace - Case-insensitive version of str_replace
    • str_pad - Pad a string to a certain length with another string
    • str_repeat - Repete uma string
    • str_replace - Substitui todas as ocorrências da string de pesquisa com a string de substituição
    • str_rot13 - Executa a transformação rot13 em uma string
    • str_shuffle - Embaralha uma string aleatoriamente
    • str_split - Convert a string to an array
    • str_starts_with - Verifica se uma string começa com uma substring fornecida
    • str_word_count - Retorna informação sobre palavras usadas em uma string
    • substr - Retorna parte de uma string
    • substr_compare - Comparação binária de duas strings a partir de uma posição até n caracteres
    • substr_count - Conta o número de ocorrências de uma substring
    • substr_replace - Substitui o texto dentro de uma parte de uma 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 - Construct a new SVM object
    • SVMModel::checkProbabilityModel - Returns true if the model has probability information
    • SVMModel::getLabels - Get the labels the model was trained on
    • SVMModel::getNrClass - Returns the number of classes the model was trained with
    • SVMModel::getSvmType - Get the SVM type the model was trained with
    • SVMModel::getSvrProbability - Get the sigma value for regression types
    • SVMModel::load - Load a saved SVM Model
    • SVMModel::predict - Predict a value for previously unseen data
    • SVMModel::predict_probability - Return class probabilities for previous unseen data
    • SVMModel::save - Save a model to a file
    • SVMModel::__construct - Construct a new SVMModel
    • svn_add - Schedules the addition of an item in a working directory
    • svn_auth_get_parameter - Retrieves authentication parameter
    • svn_auth_set_parameter - Sets an authentication parameter
    • svn_blame - Get the SVN blame for a file
    • svn_cat - Returns the contents of a file in a repository
    • svn_checkout - Checks out a working copy from the repository
    • svn_cleanup - Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
    • svn_client_version - Returns the version of the SVN client libraries
    • svn_commit - Sends changes from the local working copy to the repository
    • svn_delete - Delete items from a working copy or repository
    • svn_diff - Recursively diffs two paths
    • svn_export - Export the contents of a SVN directory
    • svn_fs_abort_txn - Aborts a transaction
    • svn_fs_apply_text - Creates and returns a stream that will be used to replace
    • svn_fs_begin_txn2 - Create a new transaction
    • svn_fs_change_node_prop - Return true if everything is ok, false otherwise
    • svn_fs_check_path - Determines what kind of item lives at path in a given repository fsroot
    • svn_fs_contents_changed - Return true if content is different, false otherwise
    • svn_fs_copy - Copies a file or a directory
    • svn_fs_delete - Deletes a file or a directory
    • svn_fs_dir_entries - Enumerates the directory entries under path; returns a hash of dir names to file type
    • svn_fs_file_contents - Returns a stream to access the contents of a file from a given version of the fs
    • svn_fs_file_length - Returns the length of a file from a given version of the fs
    • svn_fs_is_dir - Determines if a path points to a directory
    • svn_fs_is_file - Determines if a path points to a file
    • svn_fs_make_dir - Creates a new empty directory
    • svn_fs_make_file - Creates a new empty file
    • svn_fs_node_created_rev - Returns the revision in which path under fsroot was created
    • svn_fs_node_prop - Returns the value of a property for a node
    • svn_fs_props_changed - Return true if props are different, false otherwise
    • svn_fs_revision_prop - Fetches the value of a named property
    • svn_fs_revision_root - Get a handle on a specific version of the repository root
    • svn_fs_txn_root - Creates and returns a transaction root
    • svn_fs_youngest_rev - Returns the number of the youngest revision in the filesystem
    • svn_import - Imports an unversioned path into a repository
    • svn_log - Returns the commit log messages of a repository URL
    • svn_ls - Returns list of directory contents in repository URL, optionally at revision number
    • svn_mkdir - Creates a directory in a working copy or repository
    • svn_repos_create - Create a new subversion repository at path
    • svn_repos_fs - Gets a handle on the filesystem for a repository
    • svn_repos_fs_begin_txn_for_commit - Create a new transaction
    • svn_repos_fs_commit_txn - Commits a transaction and returns the new revision
    • svn_repos_hotcopy - Make a hot-copy of the repos at repospath; copy it to destpath
    • svn_repos_open - Open a shared lock on a repository
    • svn_repos_recover - Run recovery procedures on the repository located at path
    • svn_revert - Revert changes to the working copy
    • svn_status - Returns the status of working copy files and directories
    • svn_update - Update working copy
    • Swoole\Async::dnsLookup - Async and non-blocking hostname to IP lookup.
    • Swoole\Async::read - Read file stream asynchronously.
    • Swoole\Async::readFile - Read a file asynchronously.
    • Swoole\Async::set - Update the async I/O options.
    • Swoole\Async::write - Write data to a file stream asynchronously.
    • Swoole\Async::writeFile - Description
    • Swoole\Atomic::add - Add a number to the value to the atomic object.
    • Swoole\Atomic::cmpset - Compare and set the value of the atomic object.
    • Swoole\Atomic::get - Get the current value of the atomic object.
    • Swoole\Atomic::set - Set a new value to the atomic object.
    • Swoole\Atomic::sub - Subtract a number to the value of the atomic object.
    • Swoole\Atomic::__construct - Construct a swoole atomic object.
    • Swoole\Buffer::append - Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.
    • Swoole\Buffer::clear - Reset the memory buffer.
    • Swoole\Buffer::expand - Expand the size of memory buffer.
    • Swoole\Buffer::read - Read data from the memory buffer based on offset and length.
    • Swoole\Buffer::recycle - Release the memory to OS which is not used by the memory buffer.
    • Swoole\Buffer::substr - Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.
    • Swoole\Buffer::write - Write data to the memory buffer. The memory allocated for the buffer will not be changed.
    • Swoole\Buffer::__construct - Fixed size memory blocks allocation.
    • Swoole\Buffer::__destruct - Destruct the Swoole memory buffer.
    • Swoole\Buffer::__toString - Get the string value of the memory buffer.
    • Swoole\Channel::pop - Read and pop data from swoole channel.
    • Swoole\Channel::push - Write and push data into Swoole channel.
    • Swoole\Channel::stats - Get stats of swoole channel.
    • Swoole\Channel::__construct - Construct a Swoole Channel
    • Swoole\Channel::__destruct - Destruct a Swoole channel.
    • Swoole\Client::close - Close the connection established.
    • Swoole\Client::connect - Connect to the remote TCP or UDP port.
    • Swoole\Client::getpeername - Get the remote socket name of the connection.
    • Swoole\Client::getsockname - Get the local socket name of the connection.
    • Swoole\Client::isConnected - Check if the connection is established.
    • Swoole\Client::on - Add callback functions triggered by events.
    • Swoole\Client::pause - Pause receiving data.
    • Swoole\Client::pipe - Redirect the data to another file descriptor.
    • Swoole\Client::recv - Receive data from the remote socket.
    • Swoole\Client::resume - Resume receiving data.
    • Swoole\Client::send - Send data to the remote TCP socket.
    • Swoole\Client::sendfile - Send file to the remote TCP socket.
    • Swoole\Client::sendto - Send data to the remote UDP address.
    • Swoole\Client::set - Set the Swoole client parameters before the connection is established.
    • Swoole\Client::sleep - Remove the TCP client from system event loop.
    • Swoole\Client::wakeup - Add the TCP client back into the system event loop.
    • Swoole\Client::__construct - Create Swoole sync or async TCP/UDP client, with or without SSL.
    • Swoole\Client::__destruct - Destruct the Swoole client.
    • Swoole\Connection\Iterator::count - Count connections.
    • Swoole\Connection\Iterator::current - Return current connection entry.
    • Swoole\Connection\Iterator::key - Return key of the current connection.
    • Swoole\Connection\Iterator::next - Move to the next connection.
    • Swoole\Connection\Iterator::offsetExists - Check if offet exists.
    • Swoole\Connection\Iterator::offsetGet - Offset to retrieve.
    • Swoole\Connection\Iterator::offsetSet - Assign a Connection to the specified offset.
    • Swoole\Connection\Iterator::offsetUnset - Unset an offset.
    • Swoole\Connection\Iterator::rewind - Rewinds iterator
    • Swoole\Connection\Iterator::valid - Check if current position is valid.
    • Swoole\Coroutine::call_user_func - Call a callback given by the first parameter
    • Swoole\Coroutine::call_user_func_array - Call a callback with an array of parameters
    • Swoole\Coroutine::cli_wait - Description
    • Swoole\Coroutine::create - Description
    • Swoole\Coroutine::getuid - Description
    • Swoole\Coroutine::resume - Description
    • Swoole\Coroutine::suspend - Description
    • Swoole\Coroutine\Client::close - Description
    • Swoole\Coroutine\Client::connect - Description
    • Swoole\Coroutine\Client::getpeername - Description
    • Swoole\Coroutine\Client::getsockname - Description
    • Swoole\Coroutine\Client::isConnected - Description
    • Swoole\Coroutine\Client::recv - Description
    • Swoole\Coroutine\Client::send - Description
    • Swoole\Coroutine\Client::sendfile - Description
    • Swoole\Coroutine\Client::sendto - Description
    • Swoole\Coroutine\Client::set - Description
    • Swoole\Coroutine\Client::__construct - Description
    • Swoole\Coroutine\Client::__destruct - Description
    • Swoole\Coroutine\Http\Client::addFile - Description
    • Swoole\Coroutine\Http\Client::close - Description
    • Swoole\Coroutine\Http\Client::execute - Description
    • Swoole\Coroutine\Http\Client::get - Description
    • Swoole\Coroutine\Http\Client::getDefer - Description
    • Swoole\Coroutine\Http\Client::isConnected - Description
    • Swoole\Coroutine\Http\Client::post - Description
    • Swoole\Coroutine\Http\Client::recv - Description
    • Swoole\Coroutine\Http\Client::set - Description
    • Swoole\Coroutine\Http\Client::setCookies - Description
    • Swoole\Coroutine\Http\Client::setData - Description
    • Swoole\Coroutine\Http\Client::setDefer - Description
    • Swoole\Coroutine\Http\Client::setHeaders - Description
    • Swoole\Coroutine\Http\Client::setMethod - Description
    • Swoole\Coroutine\Http\Client::__construct - Description
    • Swoole\Coroutine\Http\Client::__destruct - Description
    • Swoole\Coroutine\MySQL::close - Description
    • Swoole\Coroutine\MySQL::connect - Description
    • Swoole\Coroutine\MySQL::getDefer - Description
    • Swoole\Coroutine\MySQL::query - Description
    • Swoole\Coroutine\MySQL::recv - Description
    • Swoole\Coroutine\MySQL::setDefer - Description
    • Swoole\Coroutine\MySQL::__construct - Description
    • Swoole\Coroutine\MySQL::__destruct - Description
    • Swoole\Event::add - Add new callback functions of a socket into the EventLoop.
    • Swoole\Event::defer - Add a callback function to the next event loop.
    • Swoole\Event::del - Remove all event callback functions of a socket.
    • Swoole\Event::exit - Exit the eventloop, only available at client side.
    • Swoole\Event::set - Update the event callback functions of a socket.
    • Swoole\Event::wait - Description
    • Swoole\Event::write - Write data to the socket.
    • Swoole\Http\Client::addFile - Add a file to the post form.
    • Swoole\Http\Client::close - Close the http connection.
    • Swoole\Http\Client::download - Download a file from the remote server.
    • Swoole\Http\Client::execute - Send the HTTP request after setting the parameters.
    • Swoole\Http\Client::get - Send GET http request to the remote server.
    • Swoole\Http\Client::isConnected - Check if the HTTP connection is connected.
    • Swoole\Http\Client::on - Register callback function by event name.
    • Swoole\Http\Client::post - Send POST http request to the remote server.
    • Swoole\Http\Client::push - Push data to websocket client.
    • Swoole\Http\Client::set - Update the HTTP client paramters.
    • Swoole\Http\Client::setCookies - Set the http request cookies.
    • Swoole\Http\Client::setData - Set the HTTP request body data.
    • Swoole\Http\Client::setHeaders - Set the HTTP request headers.
    • Swoole\Http\Client::setMethod - Set the HTTP request method.
    • Swoole\Http\Client::upgrade - Upgrade to websocket protocol.
    • Swoole\Http\Client::__construct - Construct the async HTTP client.
    • Swoole\Http\Client::__destruct - Destruct the HTTP client.
    • Swoole\Http\Request::rawcontent - Get the raw HTTP POST body.
    • Swoole\Http\Request::__destruct - Destruct the HTTP request.
    • Swoole\Http\Response::cookie - Set the cookies of the HTTP response.
    • Swoole\Http\Response::end - Send data for the HTTP request and finish the response.
    • Swoole\Http\Response::gzip - Enable the gzip of response content.
    • Swoole\Http\Response::header - Set the HTTP response headers.
    • Swoole\Http\Response::initHeader - Init the HTTP response header.
    • Swoole\Http\Response::rawcookie - Set the raw cookies to the HTTP response.
    • Swoole\Http\Response::sendfile - Send file through the HTTP response.
    • Swoole\Http\Response::status - Set the status code of the HTTP response.
    • Swoole\Http\Response::write - Append HTTP body content to the HTTP response.
    • Swoole\Http\Response::__destruct - Destruct the HTTP response.
    • Swoole\Http\Server::on - Vincula a função de retorno (callback) ao servidor HTTP pelo nome do evento.
    • Swoole\Http\Server::start - Iniciar o servidor http swoole.
    • 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 - Inicia o servidor Swoole.
    • 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 - Cria uma ligação simbólica
    • SyncEvent::fire - Fires/sets the event
    • SyncEvent::reset - Resets a manual event
    • SyncEvent::wait - Waits for the event to be fired/set
    • SyncEvent::__construct - Constructs a new SyncEvent object
    • SyncMutex::lock - Waits for an exclusive lock
    • SyncMutex::unlock - Unlocks the mutex
    • SyncMutex::__construct - Constructs a new SyncMutex object
    • SyncReaderWriter::readlock - Waits for a read lock
    • SyncReaderWriter::readunlock - Releases a read lock
    • SyncReaderWriter::writelock - Waits for an exclusive write lock
    • SyncReaderWriter::writeunlock - Releases a write lock
    • SyncReaderWriter::__construct - Constructs a new SyncReaderWriter object
    • SyncSemaphore::lock - Decreases the count of the semaphore or waits
    • SyncSemaphore::unlock - Increases the count of the semaphore
    • SyncSemaphore::__construct - Constructs a new SyncSemaphore object
    • SyncSharedMemory::first - Check to see if the object is the first instance system-wide of named shared memory
    • SyncSharedMemory::read - Copy data from named shared memory
    • SyncSharedMemory::size - Returns the size of the named shared memory
    • SyncSharedMemory::write - Copy data to named shared memory
    • SyncSharedMemory::__construct - Constructs a new SyncSharedMemory object
    • syslog - Generate a system log message
    • system - Executa um programa externo e mostra a saída
    • sys_getloadavg - Gets system load average
    • sys_get_temp_dir - Returns directory path used for temporary files
  • t
    • Table::count - Get row count
    • Table::delete - Delete rows from table
    • Table::existsInDatabase - Check if table exists in database
    • Table::getName - Get table name
    • Table::getSchema - Get table schema
    • Table::getSession - Get table session
    • Table::insert - Insert table rows
    • Table::isView - Check if table is view
    • Table::select - Select rows from table
    • Table::update - Update rows in table
    • Table::__construct - Table constructor
    • TableDelete::bind - Bind delete query parameters
    • TableDelete::execute - Execute delete query
    • TableDelete::limit - Limit deleted rows
    • TableDelete::orderby - Set delete sort criteria
    • TableDelete::where - Set delete search condition
    • TableDelete::__construct - TableDelete constructor
    • TableInsert::execute - Execute insert query
    • TableInsert::values - Add insert row values
    • TableInsert::__construct - TableInsert constructor
    • TableSelect::bind - Bind select query parameters
    • TableSelect::execute - Execute select statement
    • TableSelect::groupBy - Set select grouping criteria
    • TableSelect::having - Set select having condition
    • TableSelect::limit - Limit selected rows
    • TableSelect::lockExclusive - Execute EXCLUSIVE LOCK
    • TableSelect::lockShared - Execute SHARED LOCK
    • TableSelect::offset - Set limit offset
    • TableSelect::orderby - Set select sort criteria
    • TableSelect::where - Set select search condition
    • TableSelect::__construct - TableSelect constructor
    • TableUpdate::bind - Bind update query parameters
    • TableUpdate::execute - Execute update query
    • TableUpdate::limit - Limit update row count
    • TableUpdate::orderby - Set sorting criteria
    • TableUpdate::set - Add field to be updated
    • TableUpdate::where - Set search filter
    • TableUpdate::__construct - TableUpdate constructor
    • taint - Taint a string
    • tan - Tangente
    • tanh - Tangente hiperbólica
    • tcpwrap_check - Performs a tcpwrap check
    • tempnam - Cria arquivo com nome único
    • textdomain - Sets the default domain
    • Thread::getCreatorId - Identification
    • Thread::getCurrentThread - Identification
    • 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 - Obtém o código da exceção
    • Throwable::getFile - Obtém o arquivo no qual o objeto foi criado
    • Throwable::getLine - Obtém a linha na qual o objeto foi instanciado
    • Throwable::getMessage - Obtém a mensagem
    • Throwable::getPrevious - Retorna o Throwable anterior
    • Throwable::getTrace - Obtém o rastreamento de pilha
    • Throwable::getTraceAsString - Obtém o rastreamento de pilha como uma string
    • Throwable::__toString - Obtém uma representação em string do objeto disparado
    • tidy::$errorBuffer - Return warnings and errors which occurred parsing the specified document
    • tidy::body - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
    • tidy::cleanRepair - Execute configured cleanup and repair operations on parsed markup
    • tidy::diagnose - Run configured diagnostics on parsed and repaired markup
    • tidy::getConfig - Get current Tidy configuration
    • tidy::getHtmlVer - Get the Detected HTML version for the specified document
    • tidy::getOpt - Returns the value of the specified configuration option for the tidy document
    • tidy::getOptDoc - Returns the documentation for the given option name
    • tidy::getRelease - Get release date (version) for Tidy library
    • tidy::getStatus - Get status of specified document
    • tidy::head - Returns a tidyNode object starting from the <head> tag of the tidy parse tree
    • tidy::html - Returns a tidyNode object starting from the <html> tag of the tidy parse tree
    • tidy::isXhtml - Indicates if the document is a XHTML document
    • tidy::isXml - Indicates if the document is a generic (non HTML/XHTML) XML document
    • tidy::parseFile - Parse markup in file or URI
    • tidy::parseString - Parse a document stored in a string
    • tidy::repairFile - Repair a file and return it as a string
    • tidy::repairString - Repair a string using an optionally provided configuration file
    • tidy::root - Returns a tidyNode object representing the root of the tidy parse tree
    • tidy::__construct - Constructs a new tidy object
    • tidyNode::getParent - Returns the parent node of the current node
    • tidyNode::hasChildren - Checks if a node has children
    • tidyNode::hasSiblings - Checks if a node has siblings
    • tidyNode::isAsp - Checks if this node is ASP
    • tidyNode::isComment - Checks if a node represents a comment
    • tidyNode::isHtml - Checks if a node is an element node
    • tidyNode::isJste - Checks if this node is JSTE
    • tidyNode::isPhp - Checks if a node is PHP
    • tidyNode::isText - Checks if a node represents text (no markup)
    • tidyNode::__construct - Private constructor to disallow direct instantiation
    • tidy_access_count - Returns the Number of Tidy accessibility warnings encountered for specified document
    • tidy_config_count - Returns the Number of Tidy configuration errors encountered for specified document
    • tidy_error_count - Returns the Number of Tidy errors encountered for specified document
    • tidy_get_output - Return a string representing the parsed tidy markup
    • tidy_warning_count - Returns the Number of Tidy warnings encountered for specified document
    • time - Retorna o timestamp Unix atual
    • timezone_abbreviations_list - Sinônimo de DateTimeZone::listAbbreviations
    • timezone_identifiers_list - Sinônimo de DateTimeZone::listIdentifiers
    • timezone_location_get - Sinônimo de DateTimeZone::getLocation
    • timezone_name_from_abbr - Retorna um nome de fuso horário através da abreviatura e do deslocamento UTC
    • timezone_name_get - Sinônimo de DateTimeZone::getName
    • timezone_offset_get - Sinônimo de DateTimeZone::getOffset
    • timezone_open - Sinônimo de DateTimeZone::__construct
    • timezone_transitions_get - Sinônimo de DateTimeZone::getTransitions
    • timezone_version_get - Obtém a versão do banco de dados de fuso horário.
    • time_nanosleep - Delay for a number of seconds and nanoseconds
    • time_sleep_until - Make the script sleep until the specified time
    • tmpfile - Cria um arquivo temporário
    • token_get_all - Divide um dado fonte em tokens do PHP
    • token_name - Pega o nome simbólico de um dado token do PHP
    • touch - Define horário de acesso e de modificação de arquivo
    • trader_acos - Vector Trigonometric ACos
    • trader_ad - Chaikin A/D Line
    • trader_add - Vector Arithmetic Add
    • trader_adosc - Chaikin A/D Oscillator
    • trader_adx - Average Directional Movement Index
    • trader_adxr - Average Directional Movement Index Rating
    • trader_apo - Absolute Price Oscillator
    • trader_aroon - Aroon
    • trader_aroonosc - Aroon Oscillator
    • trader_asin - Vector Trigonometric ASin
    • trader_atan - Vector Trigonometric ATan
    • trader_atr - Average True Range
    • trader_avgprice - Average Price
    • trader_bbands - Bollinger Bands
    • trader_beta - Beta
    • trader_bop - Balance Of Power
    • trader_cci - Commodity Channel Index
    • trader_cdl2crows - Two Crows
    • trader_cdl3blackcrows - Three Black Crows
    • trader_cdl3inside - Three Inside Up/Down
    • trader_cdl3linestrike - Three-Line Strike
    • trader_cdl3outside - Three Outside Up/Down
    • trader_cdl3starsinsouth - Three Stars In The South
    • trader_cdl3whitesoldiers - Three Advancing White Soldiers
    • trader_cdlabandonedbaby - Abandoned Baby
    • trader_cdladvanceblock - Advance Block
    • trader_cdlbelthold - Belt-hold
    • trader_cdlbreakaway - Breakaway
    • trader_cdlclosingmarubozu - Closing Marubozu
    • trader_cdlconcealbabyswall - Concealing Baby Swallow
    • trader_cdlcounterattack - Counterattack
    • trader_cdldarkcloudcover - Dark Cloud Cover
    • trader_cdldoji - Doji
    • trader_cdldojistar - Doji Star
    • trader_cdldragonflydoji - Dragonfly Doji
    • trader_cdlengulfing - Engulfing Pattern
    • trader_cdleveningdojistar - Evening Doji Star
    • trader_cdleveningstar - Evening Star
    • trader_cdlgapsidesidewhite - Up/Down-gap side-by-side white lines
    • trader_cdlgravestonedoji - Gravestone Doji
    • trader_cdlhammer - Hammer
    • trader_cdlhangingman - Hanging Man
    • trader_cdlharami - Harami Pattern
    • trader_cdlharamicross - Harami Cross Pattern
    • trader_cdlhighwave - High-Wave Candle
    • trader_cdlhikkake - Hikkake Pattern
    • trader_cdlhikkakemod - Modified Hikkake Pattern
    • trader_cdlhomingpigeon - Homing Pigeon
    • trader_cdlidentical3crows - Identical Three Crows
    • trader_cdlinneck - In-Neck Pattern
    • trader_cdlinvertedhammer - Inverted Hammer
    • trader_cdlkicking - Kicking
    • trader_cdlkickingbylength - Kicking - bull/bear determined by the longer marubozu
    • trader_cdlladderbottom - Ladder Bottom
    • trader_cdllongleggeddoji - Long Legged Doji
    • trader_cdllongline - Long Line Candle
    • trader_cdlmarubozu - Marubozu
    • trader_cdlmatchinglow - Matching Low
    • trader_cdlmathold - Mat Hold
    • trader_cdlmorningdojistar - Morning Doji Star
    • trader_cdlmorningstar - Morning Star
    • trader_cdlonneck - On-Neck Pattern
    • trader_cdlpiercing - Piercing Pattern
    • trader_cdlrickshawman - Rickshaw Man
    • trader_cdlrisefall3methods - Rising/Falling Three Methods
    • trader_cdlseparatinglines - Separating Lines
    • trader_cdlshootingstar - Shooting Star
    • trader_cdlshortline - Short Line Candle
    • trader_cdlspinningtop - Spinning Top
    • trader_cdlstalledpattern - Stalled Pattern
    • trader_cdlsticksandwich - Stick Sandwich
    • trader_cdltakuri - Takuri (Dragonfly Doji with very long lower shadow)
    • trader_cdltasukigap - Tasuki Gap
    • trader_cdlthrusting - Thrusting Pattern
    • trader_cdltristar - Tristar Pattern
    • trader_cdlunique3river - Unique 3 River
    • trader_cdlupsidegap2crows - Upside Gap Two Crows
    • trader_cdlxsidegap3methods - Upside/Downside Gap Three Methods
    • trader_ceil - Vector Ceil
    • trader_cmo - Chande Momentum Oscillator
    • trader_correl - Pearson's Correlation Coefficient (r)
    • trader_cos - Vector Trigonometric Cos
    • trader_cosh - Vector Trigonometric Cosh
    • trader_dema - Double Exponential Moving Average
    • trader_div - Vector Arithmetic Div
    • trader_dx - Directional Movement Index
    • trader_ema - Exponential Moving Average
    • trader_errno - Get error code
    • trader_exp - Vector Arithmetic Exp
    • trader_floor - Vector Floor
    • trader_get_compat - Get compatibility mode
    • trader_get_unstable_period - Get unstable period
    • trader_ht_dcperiod - Hilbert Transform - Dominant Cycle Period
    • trader_ht_dcphase - Hilbert Transform - Dominant Cycle Phase
    • trader_ht_phasor - Hilbert Transform - Phasor Components
    • trader_ht_sine - Hilbert Transform - SineWave
    • trader_ht_trendline - Hilbert Transform - Instantaneous Trendline
    • trader_ht_trendmode - Hilbert Transform - Trend vs Cycle Mode
    • trader_kama - Kaufman Adaptive Moving Average
    • trader_linearreg - Linear Regression
    • trader_linearreg_angle - Linear Regression Angle
    • trader_linearreg_intercept - Linear Regression Intercept
    • trader_linearreg_slope - Linear Regression Slope
    • trader_ln - Vector Log Natural
    • trader_log10 - Vector Log10
    • trader_ma - Moving average
    • trader_macd - Moving Average Convergence/Divergence
    • trader_macdext - MACD with controllable MA type
    • trader_macdfix - Moving Average Convergence/Divergence Fix 12/26
    • trader_mama - MESA Adaptive Moving Average
    • trader_mavp - Moving average with variable period
    • trader_max - Highest value over a specified period
    • trader_maxindex - Index of highest value over a specified period
    • trader_medprice - Median Price
    • trader_mfi - Money Flow Index
    • trader_midpoint - MidPoint over period
    • trader_midprice - Midpoint Price over period
    • trader_min - Lowest value over a specified period
    • trader_minindex - Index of lowest value over a specified period
    • trader_minmax - Lowest and highest values over a specified period
    • trader_minmaxindex - Indexes of lowest and highest values over a specified period
    • trader_minus_di - Minus Directional Indicator
    • trader_minus_dm - Minus Directional Movement
    • trader_mom - Momentum
    • trader_mult - Vector Arithmetic Mult
    • trader_natr - Normalized Average True Range
    • trader_obv - On Balance Volume
    • trader_plus_di - Plus Directional Indicator
    • trader_plus_dm - Plus Directional Movement
    • trader_ppo - Percentage Price Oscillator
    • trader_roc - Rate of change : ((price/prevPrice)-1)*100
    • trader_rocp - Rate of change Percentage: (price-prevPrice)/prevPrice
    • trader_rocr - Rate of change ratio: (price/prevPrice)
    • trader_rocr100 - Rate of change ratio 100 scale: (price/prevPrice)*100
    • trader_rsi - Relative Strength Index
    • trader_sar - Parabolic SAR
    • trader_sarext - Parabolic SAR - Extended
    • trader_set_compat - Set compatibility mode
    • trader_set_unstable_period - Set unstable period
    • trader_sin - Vector Trigonometric Sin
    • trader_sinh - Vector Trigonometric Sinh
    • trader_sma - Simple Moving Average
    • trader_sqrt - Vector Square Root
    • trader_stddev - Standard Deviation
    • trader_stoch - Stochastic
    • trader_stochf - Stochastic Fast
    • trader_stochrsi - Stochastic Relative Strength Index
    • trader_sub - Vector Arithmetic Subtraction
    • trader_sum - Summation
    • trader_t3 - Triple Exponential Moving Average (T3)
    • trader_tan - Vector Trigonometric Tan
    • trader_tanh - Vector Trigonometric Tanh
    • trader_tema - Triple Exponential Moving Average
    • trader_trange - True Range
    • trader_trima - Triangular Moving Average
    • trader_trix - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
    • trader_tsf - Time Series Forecast
    • trader_typprice - Typical Price
    • trader_ultosc - Ultimate Oscillator
    • trader_var - Variance
    • trader_wclprice - Weighted Close Price
    • trader_willr - Williams' %R
    • trader_wma - Weighted Moving Average
    • trait_exists - Verifica se a trait existe
    • Transliterator::create - Create a transliterator
    • Transliterator::createFromRules - Create transliterator from rules
    • Transliterator::createInverse - Create an inverse transliterator
    • Transliterator::getErrorCode - Get last error code
    • Transliterator::getErrorMessage - Get last error message
    • Transliterator::listIDs - Get transliterator IDs
    • Transliterator::transliterate - Transliterate a string
    • Transliterator::__construct - Private constructor to deny instantiation
    • trigger_error - Gera uma mensagem a nível de usuário de erro/alerta/nota
    • trim - Retira espaço (ou outros caracteres) do início e do final de uma string
  • u
    • uasort - Ordena um array com uma função de comparação definida pelo usuário e mantém associações de índices
    • ucfirst - Make a string's first character uppercase
    • UConverter::convert - Converte uma string de um conjunto de caracteres (charset) para outro
    • UConverter::fromUCallback - Função de retorno de origem padrão
    • UConverter::getAliases - Obtém o pseudônimo de um nome
    • UConverter::getAvailable - Obtém os nomes canônicos dos conversores disponíveis
    • UConverter::getDestinationEncoding - Obtém a codificação de destino
    • UConverter::getDestinationType - Obtém o tipo do conversor de destino
    • UConverter::getErrorCode - Obtém o código do último erro gerado pelo objeto
    • UConverter::getErrorMessage - Obtém a mensagem do último erro gerado pelo objeto
    • UConverter::getSourceEncoding - Obtém a codificação de origem
    • UConverter::getSourceType - Obtém o tipo do conversor de origem
    • UConverter::getStandards - Obtém os nomes dos conversores padrão associados
    • UConverter::getSubstChars - Obtém os caracteres de substituição
    • UConverter::reasonText - Obtém uma representação em string da razão da chamada de retorno
    • UConverter::setDestinationEncoding - Define a codificação de destino
    • UConverter::setSourceEncoding - Define a codificação da origem
    • UConverter::setSubstChars - Define os caracteres de substituição
    • UConverter::toUCallback - Função de retorno padrão de destino
    • UConverter::transcode - Converte uma string de uma codificação de caracteres para outra
    • UConverter::__construct - Cria um objeto UConverter
    • ucwords - Converte para maiúsculas o primeiro caractere de cada palavra
    • UI\Area::onDraw - Draw Callback
    • UI\Area::onKey - Key Callback
    • UI\Area::onMouse - Mouse Callback
    • UI\Area::redraw - Redraw Area
    • UI\Area::scrollTo - Area Scroll
    • UI\Area::setSize - Set Size
    • UI\Control::destroy - Destroy Control
    • UI\Control::disable - Disable Control
    • UI\Control::enable - Enable Control
    • UI\Control::getParent - Get Parent Control
    • UI\Control::getTopLevel - Get Top Level
    • UI\Control::hide - Hide Control
    • UI\Control::isEnabled - Determine if Control is enabled
    • UI\Control::isVisible - Determine if Control is visible
    • UI\Control::setParent - Set Parent Control
    • UI\Control::show - Control Show
    • UI\Controls\Box::append - Append Control
    • UI\Controls\Box::delete - Delete Control
    • UI\Controls\Box::getOrientation - Get Orientation
    • UI\Controls\Box::isPadded - Padding Detection
    • UI\Controls\Box::setPadded - Set Padding
    • UI\Controls\Box::__construct - Construct a new Box
    • UI\Controls\Button::getText - Get Text
    • UI\Controls\Button::onClick - Click Handler
    • UI\Controls\Button::setText - Set Text
    • UI\Controls\Button::__construct - Construct a new Button
    • UI\Controls\Check::getText - Get Text
    • UI\Controls\Check::isChecked - Checked Detection
    • UI\Controls\Check::onToggle - Toggle Callback
    • UI\Controls\Check::setChecked - Set Checked
    • UI\Controls\Check::setText - Set Text
    • UI\Controls\Check::__construct - Construct a new Check
    • UI\Controls\ColorButton::getColor - Get Color
    • UI\Controls\ColorButton::onChange - Change Handler
    • UI\Controls\ColorButton::setColor - Set Color
    • UI\Controls\Combo::append - Append Option
    • UI\Controls\Combo::getSelected - Get Selected Option
    • UI\Controls\Combo::onSelected - Selected Handler
    • UI\Controls\Combo::setSelected - Set Selected Option
    • UI\Controls\EditableCombo::append - Append Option
    • UI\Controls\EditableCombo::getText - Get Text
    • UI\Controls\EditableCombo::onChange - Change Handler
    • UI\Controls\EditableCombo::setText - Set Text
    • UI\Controls\Entry::getText - Get Text
    • UI\Controls\Entry::isReadOnly - Detect Read Only
    • UI\Controls\Entry::onChange - Change Handler
    • UI\Controls\Entry::setReadOnly - Set Read Only
    • UI\Controls\Entry::setText - Set Text
    • UI\Controls\Entry::__construct - Construct a new Entry
    • UI\Controls\Form::append - Append Control
    • UI\Controls\Form::delete - Delete Control
    • UI\Controls\Form::isPadded - Padding Detection
    • UI\Controls\Form::setPadded - Set Padding
    • UI\Controls\Grid::append - Append Control
    • UI\Controls\Grid::isPadded - Padding Detection
    • UI\Controls\Grid::setPadded - Set Padding
    • UI\Controls\Group::append - Append Control
    • UI\Controls\Group::getTitle - Get Title
    • UI\Controls\Group::hasMargin - Margin Detection
    • UI\Controls\Group::setMargin - Set Margin
    • UI\Controls\Group::setTitle - Set Title
    • UI\Controls\Group::__construct - Construct a new Group
    • UI\Controls\Label::getText - Get Text
    • UI\Controls\Label::setText - Set Text
    • UI\Controls\Label::__construct - Construct a new Label
    • UI\Controls\MultilineEntry::append - Append Text
    • UI\Controls\MultilineEntry::getText - Get Text
    • UI\Controls\MultilineEntry::isReadOnly - Read Only Detection
    • UI\Controls\MultilineEntry::onChange - Change Handler
    • UI\Controls\MultilineEntry::setReadOnly - Set Read Only
    • UI\Controls\MultilineEntry::setText - Set Text
    • UI\Controls\MultilineEntry::__construct - Construct a new Multiline Entry
    • UI\Controls\Picker::__construct - Construct a new Picker
    • UI\Controls\Progress::getValue - Get Value
    • UI\Controls\Progress::setValue - Set Value
    • UI\Controls\Radio::append - Append Option
    • UI\Controls\Radio::getSelected - Get Selected Option
    • UI\Controls\Radio::onSelected - Selected Handler
    • UI\Controls\Radio::setSelected - Set Selected Option
    • UI\Controls\Separator::__construct - Construct a new Separator
    • UI\Controls\Slider::getValue - Get Value
    • UI\Controls\Slider::onChange - Change Handler
    • UI\Controls\Slider::setValue - Set Value
    • UI\Controls\Slider::__construct - Construct a new Slider
    • UI\Controls\Spin::getValue - Get Value
    • UI\Controls\Spin::onChange - Change Handler
    • UI\Controls\Spin::setValue - Set Value
    • UI\Controls\Spin::__construct - Construct a new Spin
    • UI\Controls\Tab::append - Append Page
    • UI\Controls\Tab::delete - Delete Page
    • UI\Controls\Tab::hasMargin - Margin Detection
    • UI\Controls\Tab::insertAt - Insert Page
    • UI\Controls\Tab::pages - Page Count
    • UI\Controls\Tab::setMargin - Set Margin
    • UI\Draw\Brush::getColor - Get Color
    • UI\Draw\Brush::setColor - Set Color
    • UI\Draw\Brush::__construct - Construct a new Brush
    • UI\Draw\Brush\Gradient::addStop - Stop Manipulation
    • UI\Draw\Brush\Gradient::delStop - Stop Manipulation
    • UI\Draw\Brush\Gradient::setStop - Stop Manipulation
    • UI\Draw\Brush\LinearGradient::__construct - Construct a Linear Gradient
    • UI\Draw\Brush\RadialGradient::__construct - Construct a new Radial Gradient
    • UI\Draw\Color::getChannel - Color Manipulation
    • UI\Draw\Color::setChannel - Color Manipulation
    • UI\Draw\Color::__construct - Construct new Color
    • UI\Draw\Matrix::invert - Invert Matrix
    • UI\Draw\Matrix::isInvertible - Invertible Detection
    • UI\Draw\Matrix::multiply - Multiply Matrix
    • UI\Draw\Matrix::rotate - Rotate Matrix
    • UI\Draw\Matrix::scale - Scale Matrix
    • UI\Draw\Matrix::skew - Skew Matrix
    • UI\Draw\Matrix::translate - Translate Matrix
    • UI\Draw\Path::addRectangle - Draw a Rectangle
    • UI\Draw\Path::arcTo - Draw an Arc
    • UI\Draw\Path::bezierTo - Draw Bezier Curve
    • UI\Draw\Path::closeFigure - Close Figure
    • UI\Draw\Path::end - Finalize Path
    • UI\Draw\Path::lineTo - Draw a Line
    • UI\Draw\Path::newFigure - Draw Figure
    • UI\Draw\Path::newFigureWithArc - Draw Figure with Arc
    • UI\Draw\Path::__construct - Construct a new Path
    • UI\Draw\Pen::clip - Clip a Path
    • UI\Draw\Pen::fill - Fill a Path
    • UI\Draw\Pen::restore - Restore
    • UI\Draw\Pen::save - Save
    • UI\Draw\Pen::stroke - Stroke a Path
    • UI\Draw\Pen::transform - Matrix Transform
    • UI\Draw\Pen::write - Draw Text at Point
    • UI\Draw\Stroke::getCap - Get Line Cap
    • UI\Draw\Stroke::getJoin - Get Line Join
    • UI\Draw\Stroke::getMiterLimit - Get Miter Limit
    • UI\Draw\Stroke::getThickness - Get Thickness
    • UI\Draw\Stroke::setCap - Set Line Cap
    • UI\Draw\Stroke::setJoin - Set Line Join
    • UI\Draw\Stroke::setMiterLimit - Set Miter Limit
    • UI\Draw\Stroke::setThickness - Set Thickness
    • UI\Draw\Stroke::__construct - Construct a new Stroke
    • UI\Draw\Text\Font::getAscent - Font Metrics
    • UI\Draw\Text\Font::getDescent - Font Metrics
    • UI\Draw\Text\Font::getLeading - Font Metrics
    • UI\Draw\Text\Font::getUnderlinePosition - Font Metrics
    • UI\Draw\Text\Font::getUnderlineThickness - Font Metrics
    • UI\Draw\Text\Font::__construct - Construct a new Font
    • UI\Draw\Text\Font\Descriptor::getFamily - Get Font Family
    • UI\Draw\Text\Font\Descriptor::getItalic - Style Detection
    • UI\Draw\Text\Font\Descriptor::getSize - Size Detection
    • UI\Draw\Text\Font\Descriptor::getStretch - Style Detection
    • UI\Draw\Text\Font\Descriptor::getWeight - Weight Detection
    • UI\Draw\Text\Font\Descriptor::__construct - Construct a new Font Descriptor
    • UI\Draw\Text\Font\fontFamilies - Retrieve Font Families
    • UI\Draw\Text\Layout::setColor - Set Color
    • UI\Draw\Text\Layout::setWidth - Set Width
    • UI\Draw\Text\Layout::__construct - Construct a new Text Layout
    • UI\Executor::kill - Stop Executor
    • UI\Executor::onExecute - Execution Callback
    • UI\Executor::setInterval - Interval Manipulation
    • UI\Executor::__construct - Construct a new Executor
    • UI\Menu::append - Append Menu Item
    • UI\Menu::appendAbout - Append About Menu Item
    • UI\Menu::appendCheck - Append Checkable Menu Item
    • UI\Menu::appendPreferences - Append Preferences Menu Item
    • UI\Menu::appendQuit - Append Quit Menu Item
    • UI\Menu::appendSeparator - Append Menu Item Separator
    • UI\Menu::__construct - Construct a new Menu
    • UI\MenuItem::disable - Disable Menu Item
    • UI\MenuItem::enable - Enable Menu Item
    • UI\MenuItem::isChecked - Detect Checked
    • UI\MenuItem::onClick - On Click Callback
    • UI\MenuItem::setChecked - Set Checked
    • UI\Point::at - Size Coercion
    • UI\Point::getX - Retrieves X
    • UI\Point::getY - Retrieves Y
    • UI\Point::setX - Set X
    • UI\Point::setY - Set Y
    • UI\Point::__construct - Construct a new Point
    • UI\quit - Quit UI Loop
    • UI\run - Enter UI Loop
    • UI\Size::getHeight - Retrieves Height
    • UI\Size::getWidth - Retrives Width
    • UI\Size::of - Point Coercion
    • UI\Size::setHeight - Set Height
    • UI\Size::setWidth - Set Width
    • UI\Size::__construct - Construct a new Size
    • UI\Window::add - Add a Control
    • UI\Window::error - Show Error Box
    • UI\Window::getSize - Get Window Size
    • UI\Window::getTitle - Get Title
    • UI\Window::hasBorders - Border Detection
    • UI\Window::hasMargin - Margin Detection
    • UI\Window::isFullScreen - Full Screen Detection
    • UI\Window::msg - Show Message Box
    • UI\Window::onClosing - Closing Callback
    • UI\Window::open - Open Dialog
    • UI\Window::save - Save Dialog
    • UI\Window::setBorders - Border Use
    • UI\Window::setFullScreen - Full Screen Use
    • UI\Window::setMargin - Margin Use
    • UI\Window::setSize - Set Size
    • UI\Window::setTitle - Window Title
    • UI\Window::__construct - Construct a new Window
    • uksort - Ordena um array pelas chaves utilizando uma função de comparação definida pelo usuário.
    • umask - Modificar a umask atual
    • uniqid - Gera um ID único
    • UnitEnum::cases - Gera uma lista de casos de uma enumeração
    • unixtojd - Convert Unix timestamp to Julian Day
    • unlink - Apaga um arquivo
    • unpack - Unpack data from binary string
    • unregister_tick_function - Desregistra uma função executada a cada instante
    • unserialize - Cria um valor PHP a partir de uma representação armazenada
    • unset - Remove a definição de uma variável informada
    • untaint - Untaint strings
    • uopz_add_function - Adds non-existent function or method
    • uopz_allow_exit - Allows control over disabled exit opcode
    • uopz_backup - Backup a function
    • uopz_compose - Compose a class
    • uopz_copy - Copy a function
    • uopz_delete - Delete a function
    • uopz_del_function - Deletes previously added function or method
    • uopz_extend - Extend a class at runtime
    • uopz_flags - Get or set flags on function or class
    • uopz_function - Creates a function at runtime
    • uopz_get_exit_status - Retrieve the last set exit status
    • uopz_get_hook - Gets previously set hook on function or method
    • uopz_get_mock - Get the current mock for a class
    • uopz_get_property - Gets value of class or instance property
    • uopz_get_return - Gets a previous set return value for a function
    • uopz_get_static - Gets the static variables from function or method scope
    • uopz_implement - Implements an interface at runtime
    • uopz_overload - Overload a VM opcode
    • uopz_redefine - Redefine a constant
    • uopz_rename - Rename a function at runtime
    • uopz_restore - Restore a previously backed up function
    • uopz_set_hook - Sets hook to execute when entering a function or method
    • uopz_set_mock - Use mock instead of class for new objects
    • uopz_set_property - Sets value of existing class or instance property
    • uopz_set_return - Provide a return value for an existing function
    • uopz_set_static - Sets the static variables in function or method scope
    • uopz_undefine - Undefine a constant
    • uopz_unset_hook - Removes previously set hook on function or method
    • uopz_unset_mock - Unset previously set mock
    • uopz_unset_return - Unsets a previously set return value for a function
    • urldecode - Decodifica uma URL codificada
    • urlencode - URL-encodes string
    • user_error - Sinônimo de trigger_error
    • use_soap_error_handler - Set whether to use the SOAP error handler
    • usleep - Delay execution in microseconds
    • usort - Ordena um array pelos valores utilizando uma função de comparação definida pelo usuário
    • utf8_decode - Converts a string from UTF-8 to ISO-8859-1, replacing invalid or unrepresentable characters
    • utf8_encode - Converts a string from ISO-8859-1 to UTF-8
  • v
    • V8Js::executeString - Execute a string as Javascript code
    • V8Js::getExtensions - Return an array of registered extensions
    • V8Js::getPendingException - Return pending uncaught Javascript exception
    • V8Js::registerExtension - Register Javascript extensions for V8Js
    • V8Js::__construct - Construct a new V8Js object
    • V8JsException::getJsFileName - The getJsFileName purpose
    • V8JsException::getJsLineNumber - The getJsLineNumber purpose
    • V8JsException::getJsSourceLine - The getJsSourceLine purpose
    • V8JsException::getJsTrace - The getJsTrace purpose
    • variant::__construct - variant class constructor
    • variant_abs - Returns the absolute value of a variant
    • variant_add - "Adds" two variant values together and returns the result
    • variant_and - Performs a bitwise AND operation between two variants
    • variant_cast - Convert a variant into a new variant object of another type
    • variant_cat - Concatenates two variant values together and returns the result
    • variant_cmp - Compares two variants
    • variant_date_from_timestamp - Returns a variant date representation of a Unix timestamp
    • variant_date_to_timestamp - Converts a variant date/time value to Unix timestamp
    • variant_div - Returns the result from dividing two variants
    • variant_eqv - Performs a bitwise equivalence on two variants
    • variant_fix - Returns the integer portion of a variant
    • variant_get_type - Returns the type of a variant object
    • variant_idiv - Converts variants to integers and then returns the result from dividing them
    • variant_imp - Performs a bitwise implication on two variants
    • variant_int - Returns the integer portion of a variant
    • variant_mod - Divides two variants and returns only the remainder
    • variant_mul - Multiplies the values of the two variants
    • variant_neg - Performs logical negation on a variant
    • variant_not - Performs bitwise not negation on a variant
    • variant_or - Performs a logical disjunction on two variants
    • variant_pow - Returns the result of performing the power function with two variants
    • variant_round - Rounds a variant to the specified number of decimal places
    • variant_set - Assigns a new value for a variant object
    • variant_set_type - Convert a variant into another type "in-place"
    • variant_sub - Subtracts the value of the right variant from the left variant value
    • variant_xor - Performs a logical exclusion on two variants
    • VarnishAdmin::auth - Authenticate on a varnish instance
    • VarnishAdmin::ban - Ban URLs using a VCL expression
    • VarnishAdmin::banUrl - Ban an URL using a VCL expression
    • VarnishAdmin::clearPanic - Clear varnish instance panic messages
    • VarnishAdmin::connect - Connect to a varnish instance administration interface
    • VarnishAdmin::disconnect - Disconnect from a varnish instance administration interface
    • VarnishAdmin::getPanic - Get the last panic message on a varnish instance
    • VarnishAdmin::getParams - Fetch current varnish instance configuration parameters
    • VarnishAdmin::isRunning - Check if the varnish slave process is currently running
    • VarnishAdmin::setCompat - Set the class compat configuration param
    • VarnishAdmin::setHost - Set the class host configuration param
    • VarnishAdmin::setIdent - Set the class ident configuration param
    • VarnishAdmin::setParam - Set configuration param on the current varnish instance
    • VarnishAdmin::setPort - Set the class port configuration param
    • VarnishAdmin::setSecret - Set the class secret configuration param
    • VarnishAdmin::setTimeout - Set the class timeout configuration param
    • VarnishAdmin::start - Start varnish worker process
    • VarnishAdmin::stop - Stop varnish worker process
    • VarnishAdmin::__construct - VarnishAdmin constructor
    • VarnishLog::getLine - Get next log line
    • VarnishLog::getTagName - Get the log tag string representation by its index
    • VarnishLog::__construct - Varnishlog constructor
    • VarnishStat::getSnapshot - Get the current varnish instance statistics snapshot
    • VarnishStat::__construct - VarnishStat constructor
    • var_dump - Despeja na saída informações sobre uma variável
    • var_export - Mostra ou retorna uma representação string analisável de uma variável
    • var_representation - Returns a short, readable, parsable string representation of a variable
    • version_compare - Compares two "PHP-standardized" version number strings
    • vfprintf - Escreve uma string formatada para um fluxo
    • virtual - Realiza uma sub-requisição Apache
    • vprintf - Output a formatted string
    • vsprintf - Return a formatted string
    • 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 - Desserializa um pacote WDDX
    • wddx_packet_end - Finaliza um pacote WDDX com o ID especificado
    • wddx_packet_start - Inicializa um novo pacote WDDX com uma estrutura dentro dele
    • wddx_serialize_value - Serializa um único valor em um pacote WDDX
    • wddx_serialize_vars - Serializa variáveis em um pacote WDDX
    • WeakMap::count - Conta o número de entradas ativas no mapa
    • WeakMap::getIterator - Obtém um iderador externo
    • WeakMap::offsetExists - Verifica se um certo objeto está no mapa
    • WeakMap::offsetGet - Retorna o valor apontado por um certo objeto
    • WeakMap::offsetSet - Atualiza o mapa com um novo par chave-valor
    • WeakMap::offsetUnset - Remove uma entrada do mapa
    • WeakReference::create - Cria uma nova referência fraca
    • WeakReference::get - Obtém um objeto fracamente referenciado
    • WeakReference::__construct - Construtor que desabilita a instanciação
    • win32_continue_service - Resumes a paused service
    • win32_create_service - Creates a new service entry in the SCM database
    • win32_delete_service - Deletes a service entry from the SCM database
    • win32_get_last_control_message - Returns the last control message that was sent to this service
    • win32_pause_service - Pauses a service
    • win32_query_service_status - Queries the status of a service
    • win32_send_custom_control - Send a custom control to the service
    • win32_set_service_exit_code - Define or return the exit code for the current running service
    • win32_set_service_exit_mode - Define or return the exit mode for the current running service
    • win32_set_service_status - Update the service status
    • win32_start_service - Starts a service
    • win32_start_service_ctrl_dispatcher - Registers the script with the SCM, so that it can act as the service with the given name
    • win32_stop_service - Stops a service
    • wincache_fcache_fileinfo - Retrieves information about files cached in the file cache
    • wincache_fcache_meminfo - Retrieves information about file cache memory usage
    • wincache_lock - Acquires an exclusive lock on a given key
    • wincache_ocache_fileinfo - Retrieves information about files cached in the opcode cache
    • wincache_ocache_meminfo - Retrieves information about opcode cache memory usage
    • wincache_refresh_if_changed - Refreshes the cache entries for the cached files
    • wincache_rplist_fileinfo - Retrieves information about resolve file path cache
    • wincache_rplist_meminfo - Retrieves information about memory usage by the resolve file path cache
    • wincache_scache_info - Retrieves information about files cached in the session cache
    • wincache_scache_meminfo - Retrieves information about session cache memory usage
    • wincache_ucache_add - Adds a variable in user cache only if variable does not already exist in the cache
    • wincache_ucache_cas - Compares the variable with old value and assigns new value to it
    • wincache_ucache_clear - Deletes entire content of the user cache
    • wincache_ucache_dec - Decrements the value associated with the key
    • wincache_ucache_delete - Deletes variables from the user cache
    • wincache_ucache_exists - Checks if a variable exists in the user cache
    • wincache_ucache_get - Gets a variable stored in the user cache
    • wincache_ucache_inc - Increments the value associated with the key
    • wincache_ucache_info - Retrieves information about data stored in the user cache
    • wincache_ucache_meminfo - Retrieves information about user cache memory usage
    • wincache_ucache_set - Adds a variable in user cache and overwrites a variable if it already exists in the cache
    • wincache_unlock - Releases an exclusive lock on a given key
    • wkhtmltox\Image\Converter::convert - Perform Image conversion
    • wkhtmltox\Image\Converter::getVersion - Determine version of Converter
    • wkhtmltox\Image\Converter::__construct - Create a new Image converter
    • wkhtmltox\PDF\Converter::add - Add an object for conversion
    • wkhtmltox\PDF\Converter::convert - Perform PDF conversion
    • wkhtmltox\PDF\Converter::getVersion - Determine version of Converter
    • wkhtmltox\PDF\Converter::__construct - Create a new PDF converter
    • wkhtmltox\PDF\Object::__construct - Create a new PDF Object
    • wordwrap - Quebra uma string em um dado número 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 - Get an extended attribute
    • xattr_list - Get a list of extended attributes
    • xattr_remove - Remove an extended attribute
    • xattr_set - Set an extended attribute
    • xattr_supported - Check if filesystem supports extended attributes
    • xdiff_file_bdiff - Make binary diff of two files
    • xdiff_file_bdiff_size - Read a size of file created by applying a binary diff
    • xdiff_file_bpatch - Patch a file with a binary diff
    • xdiff_file_diff - Make unified diff of two files
    • xdiff_file_diff_binary - Sinônimo de xdiff_file_bdiff
    • xdiff_file_merge3 - Merge 3 files into one
    • xdiff_file_patch - Patch a file with an unified diff
    • xdiff_file_patch_binary - Sinônimo de xdiff_file_bpatch
    • xdiff_file_rabdiff - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
    • xdiff_string_bdiff - Make binary diff of two strings
    • xdiff_string_bdiff_size - Read a size of file created by applying a binary diff
    • xdiff_string_bpatch - Patch a string with a binary diff
    • xdiff_string_diff - Make unified diff of two strings
    • xdiff_string_diff_binary - Sinônimo de xdiff_string_bdiff
    • xdiff_string_merge3 - Merge 3 strings into one
    • xdiff_string_patch - Patch a string with an unified diff
    • xdiff_string_patch_binary - Sinônimo de xdiff_string_bpatch
    • xdiff_string_rabdiff - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
    • xhprof_disable - Stops xhprof profiler
    • xhprof_enable - Start xhprof profiler
    • xhprof_sample_disable - Stops xhprof sample profiler
    • xhprof_sample_enable - Start XHProf profiling in sampling mode
    • XMLDiff\Base::diff - Produce diff of two XML documents
    • XMLDiff\Base::merge - Produce new XML document based on diff
    • XMLDiff\Base::__construct - Constructor
    • XMLDiff\DOM::diff - Diff two DOMDocument objects
    • XMLDiff\DOM::merge - Produce merged DOMDocument
    • XMLDiff\File::diff - Diff two XML files
    • XMLDiff\File::merge - Produce merged XML document
    • XMLDiff\Memory::diff - Diff two XML documents
    • XMLDiff\Memory::merge - Produce merged XML document
    • XMLReader::close - Close the XMLReader input
    • XMLReader::expand - Returns a copy of the current node as a DOM object
    • XMLReader::getAttribute - Get the value of a named attribute
    • XMLReader::getAttributeNo - Get the value of an attribute by index
    • XMLReader::getAttributeNs - Get the value of an attribute by localname and URI
    • XMLReader::getParserProperty - Indicates if specified property has been set
    • XMLReader::isValid - Indicates if the parsed document is valid
    • XMLReader::lookupNamespace - Lookup namespace for a prefix
    • XMLReader::moveToAttribute - Move cursor to a named attribute
    • XMLReader::moveToAttributeNo - Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs - Move cursor to a named attribute
    • XMLReader::moveToElement - Position cursor on the parent Element of current Attribute
    • XMLReader::moveToFirstAttribute - Position cursor on the first Attribute
    • XMLReader::moveToNextAttribute - Position cursor on the next Attribute
    • XMLReader::next - Move cursor to next node skipping all subtrees
    • XMLReader::open - Set the URI containing the XML to parse
    • XMLReader::read - Move to next node in document
    • XMLReader::readInnerXml - Retrieve XML from current node
    • XMLReader::readOuterXml - Retrieve XML from current node, including itself
    • XMLReader::readString - Reads the contents of the current node as a string
    • XMLReader::setParserProperty - Set parser options
    • XMLReader::setRelaxNGSchema - Set the filename or URI for a RelaxNG Schema
    • XMLReader::setRelaxNGSchemaSource - Set the data containing a RelaxNG Schema
    • XMLReader::setSchema - Validate document against XSD
    • XMLReader::XML - Set the data containing the XML to parse
    • xmlrpc_decode - Decodifica XML para tipos nativos do PHP
    • xmlrpc_decode_request - Decodifica XML para tipos nativos do PHP
    • xmlrpc_encode - Gera XML para um valor do PHP
    • xmlrpc_encode_request - Gera XML para uma requisição de método
    • xmlrpc_get_type - Obtém o tipo XML-RPC para um valor PHP
    • xmlrpc_is_fault - Determina se um valor de array representa uma falha XML-RPC
    • xmlrpc_parse_method_descriptions - Decodifica XML e gera uma lista de descrição de métodos
    • xmlrpc_server_add_introspection_data - Adiciona documentação de introspecção
    • xmlrpc_server_call_method - Trata requisiçães de XML e chamadas de métodos
    • xmlrpc_server_create - Cria um servidor xmlrpc
    • xmlrpc_server_destroy - Destrói recursos de servidor
    • xmlrpc_server_register_introspection_callback - Registra uma função do PHP para gerar documentação
    • xmlrpc_server_register_method - Registra uma função do PHP para o método com nome method_name
    • xmlrpc_set_type - Sets xmlrpc type, base64 or datetime, for a PHP string value
    • XMLWriter::endAttribute - End attribute
    • XMLWriter::endCdata - End current CDATA
    • XMLWriter::endComment - Create end comment
    • XMLWriter::endDocument - End current document
    • XMLWriter::endDtd - End current DTD
    • XMLWriter::endDtdAttlist - End current DTD AttList
    • XMLWriter::endDtdElement - End current DTD element
    • XMLWriter::endDtdEntity - End current DTD Entity
    • XMLWriter::endElement - End current element
    • XMLWriter::endPi - End current PI
    • XMLWriter::flush - Flush current buffer
    • XMLWriter::fullEndElement - End current element
    • XMLWriter::openMemory - Create new xmlwriter using memory for string output
    • XMLWriter::openUri - Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory - Returns current buffer
    • XMLWriter::setIndent - Toggle indentation on/off
    • XMLWriter::setIndentString - Set string used for indenting
    • XMLWriter::startAttribute - Create start attribute
    • XMLWriter::startAttributeNs - Create start namespaced attribute
    • XMLWriter::startCdata - Create start CDATA tag
    • XMLWriter::startComment - Create start comment
    • XMLWriter::startDocument - Create document tag
    • XMLWriter::startDtd - Create start DTD tag
    • XMLWriter::startDtdAttlist - Create start DTD AttList
    • XMLWriter::startDtdElement - Create start DTD element
    • XMLWriter::startDtdEntity - Create start DTD Entity
    • XMLWriter::startElement - Create start element tag
    • XMLWriter::startElementNs - Create start namespaced element tag
    • XMLWriter::startPi - Create start PI tag
    • XMLWriter::text - Write text
    • XMLWriter::writeAttribute - Write full attribute
    • XMLWriter::writeAttributeNs - Write full namespaced attribute
    • XMLWriter::writeCdata - Write full CDATA tag
    • XMLWriter::writeComment - Write full comment tag
    • XMLWriter::writeDtd - Write full DTD tag
    • XMLWriter::writeDtdAttlist - Write full DTD AttList tag
    • XMLWriter::writeDtdElement - Write full DTD element tag
    • XMLWriter::writeDtdEntity - Write full DTD Entity tag
    • XMLWriter::writeElement - Write full element tag
    • XMLWriter::writeElementNs - Write full namespaced element tag
    • XMLWriter::writePi - Writes a PI
    • XMLWriter::writeRaw - Write a raw XML text
    • xml_error_string - Obtém uma string de erro do analisador XML
    • xml_get_current_byte_index - Get current byte index for an XML parser
    • xml_get_current_column_number - Get current column number for an XML parser
    • xml_get_current_line_number - Get current line number for an XML parser
    • xml_get_error_code - Obtém um código de erro do analisador XML
    • xml_parse - Start parsing an XML document
    • xml_parser_create - Cria um analisador XML
    • xml_parser_create_ns - Cria um analisador XML com suporte a espaço de nomes
    • xml_parser_free - Libera um analisador XML
    • xml_parser_get_option - Obtém as opções de um analisador XML
    • xml_parser_set_option - Define opções em um analisador XML
    • xml_parse_into_struct - Analisa dados XML dentro de uma estrutura de array
    • xml_set_character_data_handler - Set up character data handler
    • xml_set_default_handler - Set up default handler
    • xml_set_element_handler - Set up start and end element handlers
    • xml_set_end_namespace_decl_handler - Set up end namespace declaration handler
    • xml_set_external_entity_ref_handler - Set up external entity reference handler
    • xml_set_notation_decl_handler - Set up notation declaration handler
    • xml_set_object - Use XML Parser within an object
    • xml_set_processing_instruction_handler - Set up processing instruction (PI) handler
    • xml_set_start_namespace_decl_handler - Set up start namespace declaration handler
    • xml_set_unparsed_entity_decl_handler - Set up unparsed entity declaration handler
    • XSLTProcessor::getParameter - Obtém o valor de um parâmetro
    • XSLTProcessor::getSecurityPrefs - Obtém as preferências de segurança
    • XSLTProcessor::hasExsltSupport - Verifica se o PHP tem suporte a EXSLT
    • XSLTProcessor::importStylesheet - Importa folha de estilos
    • XSLTProcessor::registerPHPFunctions - Habilita o uso de funções do PHP como funções XSLT
    • XSLTProcessor::removeParameter - Remove parâmetro
    • XSLTProcessor::setParameter - Define um valor para um parâmetro
    • XSLTProcessor::setProfiling - Define o arquivo de saída de perfil
    • XSLTProcessor::setSecurityPrefs - Define preferências de segurança
    • XSLTProcessor::transformToDoc - Transforma em um documento
    • XSLTProcessor::transformToURI - Transforma em URI
    • XSLTProcessor::transformToXml - Transforma em XML
    • XSLTProcessor::__construct - Cria um novo objeto XSLTProcessor
  • y
    • Yac::add - Store into cache
    • Yac::delete - Remove items from cache
    • Yac::dump - Dump cache
    • Yac::flush - Flush the cache
    • Yac::get - Retrieve values from cache
    • Yac::info - Status of cache
    • Yac::set - Store into cache
    • Yac::__construct - Constructor
    • Yac::__get - Getter
    • Yac::__set - Setter
    • Yaconf::get - Retrieve a item
    • Yaconf::has - Determine if a item exists
    • Yaf_Action_Abstract::execute - Action entry point
    • Yaf_Action_Abstract::getController - Retrieve controller object
    • Yaf_Action_Abstract::getControllerName - Get controller name
    • Yaf_Application::app - Retrieve an Application instance
    • Yaf_Application::bootstrap - Call bootstrap
    • Yaf_Application::clearLastError - Clear the last error info
    • Yaf_Application::environ - Retrive environ
    • Yaf_Application::execute - Execute a callback
    • Yaf_Application::getAppDirectory - Get the application directory
    • Yaf_Application::getConfig - Retrive the config instance
    • Yaf_Application::getDispatcher - Get Yaf_Dispatcher instance
    • Yaf_Application::getLastErrorMsg - Get message of the last occurred error
    • Yaf_Application::getLastErrorNo - Get code of last occurred error
    • Yaf_Application::getModules - Get defined module names
    • Yaf_Application::run - Start Yaf_Application
    • Yaf_Application::setAppDirectory - Change the application directory
    • Yaf_Application::__construct - Yaf_Application constructor
    • Yaf_Application::__destruct - The __destruct purpose
    • Yaf_Config_Abstract::get - Getter
    • Yaf_Config_Abstract::readonly - Find a config whether readonly
    • Yaf_Config_Abstract::set - Setter
    • Yaf_Config_Abstract::toArray - Cast to array
    • Yaf_Config_Ini::count - Count all elements in Yaf_Config.ini
    • Yaf_Config_Ini::current - Retrieve the current value
    • Yaf_Config_Ini::key - Fetch current element's key
    • Yaf_Config_Ini::next - Advance the internal pointer
    • Yaf_Config_Ini::offsetExists - The offsetExists purpose
    • Yaf_Config_Ini::offsetGet - The offsetGet purpose
    • Yaf_Config_Ini::offsetSet - The offsetSet purpose
    • Yaf_Config_Ini::offsetUnset - The offsetUnset purpose
    • Yaf_Config_Ini::readonly - The readonly purpose
    • Yaf_Config_Ini::rewind - The rewind purpose
    • Yaf_Config_Ini::toArray - Return config as a PHP array
    • Yaf_Config_Ini::valid - The valid purpose
    • Yaf_Config_Ini::__construct - Yaf_Config_Ini constructor
    • Yaf_Config_Ini::__get - Retrieve a element
    • Yaf_Config_Ini::__isset - Determine if a key is exists
    • Yaf_Config_Ini::__set - The __set purpose
    • Yaf_Config_Simple::count - The count purpose
    • Yaf_Config_Simple::current - The current purpose
    • Yaf_Config_Simple::key - The key purpose
    • Yaf_Config_Simple::next - The next purpose
    • Yaf_Config_Simple::offsetExists - The offsetExists purpose
    • Yaf_Config_Simple::offsetGet - The offsetGet purpose
    • Yaf_Config_Simple::offsetSet - The offsetSet purpose
    • Yaf_Config_Simple::offsetUnset - The offsetUnset purpose
    • Yaf_Config_Simple::readonly - The readonly purpose
    • Yaf_Config_Simple::rewind - The rewind purpose
    • Yaf_Config_Simple::toArray - Returns a PHP array
    • Yaf_Config_Simple::valid - The valid purpose
    • Yaf_Config_Simple::__construct - The __construct purpose
    • Yaf_Config_Simple::__get - The __get purpose
    • Yaf_Config_Simple::__isset - The __isset purpose
    • Yaf_Config_Simple::__set - The __set purpose
    • Yaf_Controller_Abstract::display - The display purpose
    • Yaf_Controller_Abstract::forward - Forward to another action
    • Yaf_Controller_Abstract::getInvokeArg - The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs - The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName - Get module name
    • Yaf_Controller_Abstract::getName - Get self name
    • Yaf_Controller_Abstract::getRequest - Retrieve current request object
    • Yaf_Controller_Abstract::getResponse - Retrieve current response object
    • Yaf_Controller_Abstract::getView - Retrieve the view engine
    • Yaf_Controller_Abstract::getViewpath - The getViewpath purpose
    • Yaf_Controller_Abstract::init - Controller initializer
    • Yaf_Controller_Abstract::initView - The initView purpose
    • Yaf_Controller_Abstract::redirect - Redirect to a URL
    • Yaf_Controller_Abstract::render - Render view template
    • Yaf_Controller_Abstract::setViewpath - The setViewpath purpose
    • Yaf_Controller_Abstract::__construct - Yaf_Controller_Abstract constructor
    • Yaf_Dispatcher::autoRender - Switch on/off autorendering
    • Yaf_Dispatcher::catchException - Switch on/off exception catching
    • Yaf_Dispatcher::disableView - Disable view rendering
    • Yaf_Dispatcher::dispatch - Dispatch a request
    • Yaf_Dispatcher::enableView - Enable view rendering
    • Yaf_Dispatcher::flushInstantly - Switch on/off the instant flushing
    • Yaf_Dispatcher::getApplication - Retrieve the application
    • Yaf_Dispatcher::getDefaultAction - Retrive the default action name
    • Yaf_Dispatcher::getDefaultController - Retrive the default controller name
    • Yaf_Dispatcher::getDefaultModule - Retrive the default module name
    • Yaf_Dispatcher::getInstance - Retrive the dispatcher instance
    • Yaf_Dispatcher::getRequest - Retrive the request instance
    • Yaf_Dispatcher::getRouter - Retrive router instance
    • Yaf_Dispatcher::initView - Initialize view and return it
    • Yaf_Dispatcher::registerPlugin - Register a plugin
    • Yaf_Dispatcher::returnResponse - The returnResponse purpose
    • Yaf_Dispatcher::setDefaultAction - Change default action name
    • Yaf_Dispatcher::setDefaultController - Change default controller name
    • Yaf_Dispatcher::setDefaultModule - Change default module name
    • Yaf_Dispatcher::setErrorHandler - Set error handler
    • Yaf_Dispatcher::setRequest - The setRequest purpose
    • Yaf_Dispatcher::setView - Set a custom view engine
    • Yaf_Dispatcher::throwException - Switch on/off exception throwing
    • Yaf_Dispatcher::__construct - Yaf_Dispatcher constructor
    • Yaf_Exception::getPrevious - The getPrevious purpose
    • Yaf_Exception::__construct - The __construct purpose
    • Yaf_Loader::autoload - The autoload purpose
    • Yaf_Loader::clearLocalNamespace - The clearLocalNamespace purpose
    • Yaf_Loader::getInstance - The getInstance purpose
    • Yaf_Loader::getLibraryPath - Get the library path
    • Yaf_Loader::getLocalNamespace - Retrive all register namespaces info
    • Yaf_Loader::getNamespacePath - Retieve path of a registered namespace
    • Yaf_Loader::import - The import purpose
    • Yaf_Loader::isLocalName - The isLocalName purpose
    • Yaf_Loader::registerLocalNamespace - Register local class prefix
    • Yaf_Loader::registerNamespace - Register namespace with searching path
    • Yaf_Loader::setLibraryPath - Change the library path
    • Yaf_Loader::__construct - The __construct purpose
    • Yaf_Plugin_Abstract::dispatchLoopShutdown - The dispatchLoopShutdown purpose
    • Yaf_Plugin_Abstract::dispatchLoopStartup - Hook before dispatch loop
    • Yaf_Plugin_Abstract::postDispatch - The postDispatch purpose
    • Yaf_Plugin_Abstract::preDispatch - The preDispatch purpose
    • Yaf_Plugin_Abstract::preResponse - The preResponse purpose
    • Yaf_Plugin_Abstract::routerShutdown - The routerShutdown purpose
    • Yaf_Plugin_Abstract::routerStartup - RouterStartup hook
    • Yaf_Registry::del - Remove an item from registry
    • Yaf_Registry::get - Retrieve an item from registry
    • Yaf_Registry::has - Check whether an item exists
    • Yaf_Registry::set - Add an item into registry
    • Yaf_Registry::__construct - Yaf_Registry implements singleton
    • Yaf_Request_Abstract::clearParams - Remove all params
    • Yaf_Request_Abstract::getActionName - The getActionName purpose
    • Yaf_Request_Abstract::getBaseUri - The getBaseUri purpose
    • Yaf_Request_Abstract::getControllerName - The getControllerName purpose
    • Yaf_Request_Abstract::getEnv - Retrieve ENV varialbe
    • Yaf_Request_Abstract::getException - The getException purpose
    • Yaf_Request_Abstract::getLanguage - Retrieve client's preferred language
    • Yaf_Request_Abstract::getMethod - Retrieve the request method
    • Yaf_Request_Abstract::getModuleName - The getModuleName purpose
    • Yaf_Request_Abstract::getParam - Retrieve calling parameter
    • Yaf_Request_Abstract::getParams - Retrieve all calling parameters
    • Yaf_Request_Abstract::getRequestUri - The getRequestUri purpose
    • Yaf_Request_Abstract::getServer - Retrieve SERVER variable
    • Yaf_Request_Abstract::isCli - Determine if request is CLI request
    • Yaf_Request_Abstract::isDispatched - Determin if the request is dispatched
    • Yaf_Request_Abstract::isGet - Determine if request is GET request
    • Yaf_Request_Abstract::isHead - Determine if request is HEAD request
    • Yaf_Request_Abstract::isOptions - Determine if request is OPTIONS request
    • Yaf_Request_Abstract::isPost - Determine if request is POST request
    • Yaf_Request_Abstract::isPut - Determine if request is PUT request
    • Yaf_Request_Abstract::isRouted - Determin if request has been routed
    • Yaf_Request_Abstract::isXmlHttpRequest - Determine if request is AJAX request
    • Yaf_Request_Abstract::setActionName - Set action name
    • Yaf_Request_Abstract::setBaseUri - Set base URI
    • Yaf_Request_Abstract::setControllerName - Set controller name
    • Yaf_Request_Abstract::setDispatched - The setDispatched purpose
    • Yaf_Request_Abstract::setModuleName - Set module name
    • Yaf_Request_Abstract::setParam - Set a calling parameter to a request
    • Yaf_Request_Abstract::setRequestUri - The setRequestUri purpose
    • Yaf_Request_Abstract::setRouted - The setRouted purpose
    • Yaf_Request_Http::get - Retrieve variable from client
    • Yaf_Request_Http::getCookie - Retrieve Cookie variable
    • Yaf_Request_Http::getFiles - The getFiles purpose
    • Yaf_Request_Http::getPost - Retrieve POST variable
    • Yaf_Request_Http::getQuery - Fetch a query parameter
    • Yaf_Request_Http::getRaw - Retrieve Raw request body
    • Yaf_Request_Http::getRequest - The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest - Determin if request is Ajax Request
    • Yaf_Request_Http::__construct - Constructor of Yaf_Request_Http
    • Yaf_Request_Simple::get - The get purpose
    • Yaf_Request_Simple::getCookie - The getCookie purpose
    • Yaf_Request_Simple::getFiles - The getFiles purpose
    • Yaf_Request_Simple::getPost - The getPost purpose
    • Yaf_Request_Simple::getQuery - The getQuery purpose
    • Yaf_Request_Simple::getRequest - The getRequest purpose
    • Yaf_Request_Simple::isXmlHttpRequest - Determin if request is AJAX request
    • Yaf_Request_Simple::__construct - Constructor of Yaf_Request_Simple
    • Yaf_Response_Abstract::appendBody - Append to response body
    • Yaf_Response_Abstract::clearBody - Discard all exists response body
    • Yaf_Response_Abstract::clearHeaders - Discard all set headers
    • Yaf_Response_Abstract::getBody - Retrieve a exists content
    • Yaf_Response_Abstract::getHeader - The getHeader purpose
    • Yaf_Response_Abstract::prependBody - The prependBody purpose
    • Yaf_Response_Abstract::response - Send response
    • Yaf_Response_Abstract::setAllHeaders - The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody - Set content to response
    • Yaf_Response_Abstract::setHeader - Set reponse header
    • Yaf_Response_Abstract::setRedirect - The setRedirect purpose
    • Yaf_Response_Abstract::__construct - The __construct purpose
    • Yaf_Response_Abstract::__destruct - The __destruct purpose
    • Yaf_Response_Abstract::__toString - Retrieve all bodys as string
    • Yaf_Router::addConfig - Add config-defined routes into Router
    • Yaf_Router::addRoute - Add new Route into Router
    • Yaf_Router::getCurrentRoute - Get the effective route name
    • Yaf_Router::getRoute - Retrieve a route by name
    • Yaf_Router::getRoutes - Retrieve registered routes
    • Yaf_Router::route - The route purpose
    • Yaf_Router::__construct - Yaf_Router constructor
    • Yaf_Route_Interface::assemble - Assemble a request
    • Yaf_Route_Interface::route - Route a request
    • Yaf_Route_Map::assemble - Assemble a url
    • Yaf_Route_Map::route - The route purpose
    • Yaf_Route_Map::__construct - The __construct purpose
    • Yaf_Route_Regex::assemble - Assemble a url
    • Yaf_Route_Regex::route - The route purpose
    • Yaf_Route_Regex::__construct - Yaf_Route_Regex constructor
    • Yaf_Route_Rewrite::assemble - Assemble a url
    • Yaf_Route_Rewrite::route - The route purpose
    • Yaf_Route_Rewrite::__construct - Yaf_Route_Rewrite constructor
    • Yaf_Route_Simple::assemble - Assemble a url
    • Yaf_Route_Simple::route - Route a request
    • Yaf_Route_Simple::__construct - Yaf_Route_Simple constructor
    • Yaf_Route_Static::assemble - Assemble a url
    • Yaf_Route_Static::match - The match purpose
    • Yaf_Route_Static::route - Route a request
    • Yaf_Route_Supervar::assemble - Assemble a url
    • Yaf_Route_Supervar::route - The route purpose
    • Yaf_Route_Supervar::__construct - The __construct purpose
    • Yaf_Session::count - The count purpose
    • Yaf_Session::current - The current purpose
    • Yaf_Session::del - The del purpose
    • Yaf_Session::getInstance - The getInstance purpose
    • Yaf_Session::has - The has purpose
    • Yaf_Session::key - The key purpose
    • Yaf_Session::next - The next purpose
    • Yaf_Session::offsetExists - The offsetExists purpose
    • Yaf_Session::offsetGet - The offsetGet purpose
    • Yaf_Session::offsetSet - The offsetSet purpose
    • Yaf_Session::offsetUnset - The offsetUnset purpose
    • Yaf_Session::rewind - The rewind purpose
    • Yaf_Session::start - The start purpose
    • Yaf_Session::valid - The valid purpose
    • Yaf_Session::__construct - Constructor of Yaf_Session
    • Yaf_Session::__get - The __get purpose
    • Yaf_Session::__isset - The __isset purpose
    • Yaf_Session::__set - The __set purpose
    • Yaf_Session::__unset - The __unset purpose
    • Yaf_View_Interface::assign - Assign value to View engine
    • Yaf_View_Interface::display - Render and output a template
    • Yaf_View_Interface::getScriptPath - The getScriptPath purpose
    • Yaf_View_Interface::render - Render a template
    • Yaf_View_Interface::setScriptPath - The setScriptPath purpose
    • Yaf_View_Simple::assign - Assign values
    • Yaf_View_Simple::assignRef - The assignRef purpose
    • Yaf_View_Simple::clear - Clear Assigned values
    • Yaf_View_Simple::display - Render and display
    • Yaf_View_Simple::eval - Render template
    • Yaf_View_Simple::getScriptPath - Get templates directory
    • Yaf_View_Simple::render - Render template
    • Yaf_View_Simple::setScriptPath - Set tempaltes directory
    • Yaf_View_Simple::__construct - Constructor of Yaf_View_Simple
    • Yaf_View_Simple::__get - Retrieve assigned variable
    • Yaf_View_Simple::__isset - The __isset purpose
    • Yaf_View_Simple::__set - Set value to engine
    • yaml_emit - Returns the YAML representation of a value
    • yaml_emit_file - Send the YAML representation of a value to a file
    • yaml_parse - Parse a YAML stream
    • yaml_parse_file - Parse a YAML stream from a file
    • yaml_parse_url - Parse a Yaml stream from a URL
    • Yar_Client::setOpt - Set calling contexts
    • Yar_Client::__call - Call service
    • Yar_Client::__construct - Create a client
    • Yar_Client_Exception::getType - Retrieve exception's type
    • Yar_Concurrent_Client::call - Register a concurrent call
    • Yar_Concurrent_Client::loop - Send all calls
    • Yar_Concurrent_Client::reset - Clean all registered calls
    • Yar_Server::handle - Start RPC Server
    • Yar_Server::__construct - Register a server
    • Yar_Server_Exception::getType - Retrieve exception's type
    • yaz_addinfo - Returns additional error information
    • yaz_ccl_conf - Configure CCL parser
    • yaz_ccl_parse - Invoke CCL Parser
    • yaz_close - Close YAZ connection
    • yaz_connect - Prepares for a connection to a Z39.50 server
    • yaz_database - Specifies the databases within a session
    • yaz_element - Specifies Element-Set Name for retrieval
    • yaz_errno - Returns error number
    • yaz_error - Returns error description
    • yaz_es - Prepares for an Extended Service Request
    • yaz_es_result - Inspects Extended Services Result
    • yaz_get_option - Returns value of option for connection
    • yaz_hits - Returns number of hits for last search
    • yaz_itemorder - Prepares for Z39.50 Item Order with an ILL-Request package
    • yaz_present - Prepares for retrieval (Z39.50 present)
    • yaz_range - Specifies a range of records to retrieve
    • yaz_record - Returns a record
    • yaz_scan - Prepares for a scan
    • yaz_scan_result - Returns Scan Response result
    • yaz_schema - Specifies schema for retrieval
    • yaz_search - Prepares for a search
    • yaz_set_option - Sets one or more options for connection
    • yaz_sort - Sets sorting criteria
    • yaz_syntax - Specifies the preferred record syntax for retrieval
    • yaz_wait - Wait for Z39.50 requests to complete
  • z
    • zend_thread_id - Returns a unique identifier for the current thread
    • zend_version - Obtém a versão do motor Zend atual
    • ZipArchive::addEmptyDir - Add a new directory
    • ZipArchive::addFile - Adds a file to a ZIP archive from the given path
    • ZipArchive::addFromString - Add a file to a ZIP archive using its contents
    • ZipArchive::addGlob - Add files from a directory by glob pattern
    • ZipArchive::addPattern - Add files from a directory by PCRE pattern
    • ZipArchive::clearError - Clear the status error message, system and/or zip messages
    • ZipArchive::close - Close the active archive (opened or newly created)
    • ZipArchive::count - Counts the number of files in the archive
    • ZipArchive::deleteIndex - Delete an entry in the archive using its index
    • ZipArchive::deleteName - Delete an entry in the archive using its name
    • ZipArchive::extractTo - Extract the archive contents
    • ZipArchive::getArchiveComment - Returns the Zip archive comment
    • ZipArchive::getArchiveFlag - Returns the value of a Zip archive global flag
    • ZipArchive::getCommentIndex - Returns the comment of an entry using the entry index
    • ZipArchive::getCommentName - Returns the comment of an entry using the entry name
    • ZipArchive::getExternalAttributesIndex - Retrieve the external attributes of an entry defined by its index
    • ZipArchive::getExternalAttributesName - Retrieve the external attributes of an entry defined by its name
    • ZipArchive::getFromIndex - Returns the entry contents using its index
    • ZipArchive::getFromName - Returns the entry contents using its name
    • ZipArchive::getNameIndex - Returns the name of an entry using its index
    • ZipArchive::getStatusString - Returns the status error message, system and/or zip messages
    • ZipArchive::getStream - Get a file handler to the entry defined by its name (read only)
    • ZipArchive::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 - Returns the index of the entry in the archive
    • ZipArchive::open - Open a ZIP file archive
    • ZipArchive::registerCancelCallback - Register a callback to allow cancellation during archive close.
    • ZipArchive::registerProgressCallback - Register a callback to provide updates during archive close.
    • ZipArchive::renameIndex - Renames an entry defined by its index
    • ZipArchive::renameName - Renames an entry defined by its name
    • ZipArchive::replaceFile - Replace file in ZIP archive with a given path
    • ZipArchive::setArchiveComment - Set the comment of a ZIP archive
    • ZipArchive::setArchiveFlag - Set a global flag of a ZIP archive
    • ZipArchive::setCommentIndex - Set the comment of an entry defined by its index
    • ZipArchive::setCommentName - Set the comment of an entry defined by its name
    • ZipArchive::setCompressionIndex - Set the compression method of an entry defined by its index
    • ZipArchive::setCompressionName - Set the compression method of an entry defined by its name
    • ZipArchive::setEncryptionIndex - Set the encryption method of an entry defined by its index
    • ZipArchive::setEncryptionName - Set the encryption method of an entry defined by its name
    • ZipArchive::setExternalAttributesIndex - Set the external attributes of an entry defined by its index
    • ZipArchive::setExternalAttributesName - Set the external attributes of an entry defined by its name
    • ZipArchive::setMtimeIndex - Set the modification time of an entry defined by its index
    • ZipArchive::setMtimeName - Set the modification time of an entry defined by its name
    • ZipArchive::setPassword - Set the password for the active archive
    • ZipArchive::statIndex - Get the details of an entry defined by its index
    • ZipArchive::statName - Get the details of an entry defined by its name
    • ZipArchive::unchangeAll - Undo all changes done in the archive
    • ZipArchive::unchangeArchive - Revert all global changes done in the archive
    • ZipArchive::unchangeIndex - Revert all changes done to an entry at the given index
    • ZipArchive::unchangeName - Revert all changes done to an entry with the given name
    • zip_close - Fecha um arquivo ZIP
    • zip_entry_close - Fecha o arquivo que está aberto
    • zip_entry_compressedsize - Obtém o tamanho comprimido do item
    • zip_entry_compressionmethod - Recupera qual o método de compressão foi utilizado no arquivo
    • zip_entry_filesize - Retorna o tamanho de um item de diretório
    • zip_entry_name - Retorna o nome do arquivo
    • zip_entry_open - Abre um arquivo para leitura
    • zip_entry_read - Obtém dados de um arquivo
    • zip_open - Abre um arquivo ZIP
    • zip_read - Lê o próximo item em um arquivo ZIP
    • zlib:// - Streams de compactação
    • zlib_decode - Uncompress any raw/gzip/zlib encoded data
    • zlib_encode - Compress data with the specified encoding
    • zlib_get_coding_type - Retorna o tipo de codificação para a compressão de saída
    • ZMQ::__construct - Construtor da classe ZMQ
    • ZMQContext::getOpt - Obtém uma opção de contexto
    • ZMQContext::getSocket - Cria um novo socket
    • ZMQContext::isPersistent - Retorna se o contexto é persistente
    • ZMQContext::setOpt - Define uma opção de socket
    • ZMQContext::__construct - Constrói um novo objeto ZMQContext
    • ZMQDevice::getIdleTimeout - Obtém o tempo limite de inatividade
    • ZMQDevice::getTimerTimeout - Obtém o tempo limite do temporizador
    • ZMQDevice::run - Executa o novo dispositivo
    • ZMQDevice::setIdleCallback - Define a função de retorno de inatividade
    • ZMQDevice::setIdleTimeout - Define o tempo limite de inatividade
    • ZMQDevice::setTimerCallback - Define a função de retorno do temporizador
    • ZMQDevice::setTimerTimeout - Define o tempo limite do temporizador
    • ZMQDevice::__construct - Constrói um novo dispositivo
    • ZMQPoll::add - Adiciona o item na lista de pesquisa
    • ZMQPoll::clear - Limpa a lista de consulta
    • ZMQPoll::count - Conta os itens na lista de consulta
    • ZMQPoll::getLastErrors - Obtém erros da consulta
    • ZMQPoll::poll - Consulta os itens
    • ZMQPoll::remove - Remove um item da lista de consulta
    • ZMQSocket::bind - Associa o socket
    • ZMQSocket::connect - Conecta o socket
    • ZMQSocket::disconnect - Desconecta um socket
    • ZMQSocket::getEndpoints - Obtém uma lista de destinos
    • ZMQSocket::getPersistentId - Obtém o id persistente
    • ZMQSocket::getSocketType - Retorna o tipo de socket
    • ZMQSocket::getSockOpt - Obtém a opção do socket
    • ZMQSocket::isPersistent - Se o socket é persistente
    • ZMQSocket::recv - Recebe uma mensagem
    • ZMQSocket::recvMulti - Recebe uma mensagem de partes múltiplas
    • ZMQSocket::send - Envia uma mensagem
    • ZMQSocket::sendmulti - Envia uma mensagem de múltiplas partes
    • ZMQSocket::setSockOpt - Define uma opção de socket
    • ZMQSocket::unbind - Desvincula o socket
    • ZMQSocket::__construct - Constrói um novo 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 - Tenta carregar uma classe indefinida
    • __halt_compiler - Halts the compiler execution

User Contributed Notes

There are no user contributed notes for this page.


Lista de exemplos

Lista de todos os exemplos no manual

  • Example#0 - Um exemplo introdutório
  • Example#1 - Nosso primeiro script PHP: hello.php
  • Example#2 - Como obter informações sobre o PHP
  • Example#3 - Imprimindo uma variável (elemento do Array)
  • Example#4 - Exemplo utilizando estruturas de controle e funções
  • Example#5 - Mesclando entre os modos PHP e HTML
  • Example#6 - Um simples formulário HTML
  • Example#7 - Imprimindo dados de nosso formulário
  • Example#8 - lighttpd.conf parcial
  • Example#9 - Iniciando Respondedores FastCGI
  • Example#10 - Conectando a instâncias remotas de php-fastcgi
  • Example#11 - Exemplo de instalação de pacote no OpenBSD
  • Example#12 - Exemplo de instalação no Debian com Apache 2
  • Example#13 - Parando e iniciando o Apache depois do PHP instalado
  • Example#14 - Métodos listar pacotes adicionais do PHP
  • Example#15 - Instalando PHP com MySQL e cURL
  • Example#16 - Configuração recomendada do OpCache
  • Example#17 - Configuração WinCache recomendada
  • Example#18 - Linha de comando para configurar IIS e PHP
  • Example#19 - Alterações de Registro
  • Example#20 - PHP e Apache 2.x como controlador
  • Example#21 - PHP e Apache 2.x como CGI
  • Example#22 - Configure o Apache para executar PHP como FastCGI
  • Example#23 - Passando variáveis de ambiente e configurações do PHP para a rotina
  • Example#24 - definir as configurações de PHP no nginx.conf
  • Example#25 - A função phpinfo
  • Example#26 - php.ini Variáveis de ambiente
  • Example#27 - Exemplo de arquivo php.ini
  • Example#28 - Exemplo de configuração do Apache
  • Example#29 - Tags de Abertura e Fechamento do PHP
  • Example#30 - Escape avançado usando condições
  • Example#31 - Exemplo mostrando a tag de fechamento incluindo uma nova linha final
  • Example#32 - Literais inteiras
  • Example#33 - Overflow de inteiros em sistemas 32-bit
  • Example#34 - Overflow de inteiros em sistemas 64-bit
  • Example#35 - Exemplo Heredoc simples no PHP 7.3.0
  • Example#36 - Identificador de fechamento indentado diferente das linhas do corpo
  • Example#37 - Indentação diferente entre corpo e fechamento
  • Example#38 - Continuando uma expressão após o identificador de fechamento
  • Example#39 - Identificador de fechamento no corpo da string pode causar um ParseError
  • Example#40 - Exemplo inválido, anteriormente ao PHP 7.3.0
  • Example#41 - Exemplo válido, anteriormente ao PHP 7.3.0
  • Example#42 - Exemplo de delimitação de strings heredoc
  • Example#43 - Exemplo de Heredoc em argumentos
  • Example#44 - Utilizando o Heredoc na inicialização de valores estáticos
  • Example#45 - Usando aspas duplas no Heredoc
  • Example#46 - Exemplo de string em Nowdoc
  • Example#47 - Exemplo de Nowdoc, com variáveis
  • Example#48 - Exemplo de dado estático
  • Example#49 - Exemplo com sintaxe simples
  • Example#50 - Índices numéricos negativos
  • Example#51 - Alguns exemplos com strings
  • Example#52 - Exemplo de índices inválidos em strings
  • Example#53 - Um array simples
  • Example#54 - Exemplo de conversão de tipo e sobrescrita
  • Example#55 - Misturando int e string nas chaves
  • Example#56 - Arrays indexados sem chaves
  • Example#57 - Chaves em alguns elementos
  • Example#58 - Exemplo de sobrescrita e cast de tipo complexo
  • Example#59 - Acessando elementos do array
  • Example#60 - Referenciando elemento de um array
  • Example#61 - Expansão de arrays
  • Example#62 - Expansão de arrays com chaves duplicadas
  • Example#63 - Utilizando array()
  • Example#64 - Coleção
  • Example#65 - Alterando valores em um laço
  • Example#66 - Array baseado em 1
  • Example#67 - Preenchendo um array
  • Example#68 - Ordenando arrays
  • Example#69 - Arrays recursivos e multidimensionais
  • Example#70 - Exemplos de funções de callback
  • Example#71 - Exemplo de Callback utilizando uma Closure
  • Example#72 - Exemplo de tipo de retorno do gerador iterable
  • Example#73 -
  • Example#74 - Parâmetros de passagem por referência digitados
  • Example#75 - Maneira antiga de tornar os argumentos anuláveis
  • Example#76 - Declaração de tipo de classe básica
  • Example#77 - Declaração de tipo de interface básica
  • Example#78 - Declaração de tipo de retorno básico
  • Example#79 - Retornando um objeto
  • Example#80 - Declaração de tipo de argumento anulável
  • Example#81 - Declaração de tipo de retorno anulável
  • Example#82 - Declaração de tipo de propriedade
  • Example#83 - Tipagem estrita para valores de argumentos
  • Example#84 - Tipagem coercitiva para valores de argumento
  • Example#85 - Tipagem estrita para valores de retorno
  • Example#86 - Exemplo de tipos que podem ser convertidos em tipos union
  • Example#87 - Valores padrões de variáveis não inicializadas
  • Example#88 - Usando global
  • Example#89 - Usando $GLOBALS no lugar de global
  • Example#90 - Exemplo demonstrando superglobals e escopos
  • Example#91 - Exemplo demonstrando a necessidade de variáveis estáticas
  • Example#92 - Exemplo de uso de variáveis estáticas
  • Example#93 - Variáveis estáticas em funções recursivas
  • Example#94 - Declarando variáveis estáticas
  • Example#95 - Uso de variáveis estáticas em métodos herdados
  • Example#96 - Exemplo de propriedade variável
  • Example#97 - Um formulário HTML simples
  • Example#98 - Acessando dados de um formulário HTML via POST
  • Example#99 - Variáveis de formulários mais complexos
  • Example#100 - Exemplo setcookie
  • Example#101 - Nomes de constantes válidos e inválidos
  • Example#102 - Definindo Constantes
  • Example#103 - Definindo Constantes usando a palavra-chave const
  • Example#104 - Associação
  • Example#105 - Ordem de avaliação não definida
  • Example#106 - +, - and . possuem a mesma precedência
  • Example#107 - Exemplo de incremento de string estilo PERL
  • Example#108 - Strings alfanuméricas convertida para float
  • Example#109 - Atribuição por referência
  • Example#110 - Operações bitwise AND, OR e XOR em inteiros
  • Example#111 - Operações de bit XOR em strings
  • Example#112 - Deslocamento de bits em inteiros
  • Example#113 - Comparações de boolean e null
  • Example#114 - Transcrição do padrão de comparação de array
  • Example#115 - Atribuindo um valor padrão
  • Example#116 - Comportamento não óbvio do ternário
  • Example#117 - Encadeamento de ternários curtos
  • Example#118 - Atribuindo um valor padrão
  • Example#119 - Aninhando o operador null coalescing
  • Example#120 - Ilustrando operadores lógicos
  • Example#121 - Comparando arrays
  • Example#122 - Usando instanceof com classes
  • Example#123 - Usando instanceof com herança
  • Example#124 - Usando instanceof para verificar se o objeto não é uma instância da classe
  • Example#125 - Usando instanceof para classe
  • Example#126 - Usando instanceof com outras variáveis
  • Example#127 - Utilizando instanceof para testar outras variáveis
  • Example#128 - Utilizando instanceof em constantes
  • Example#129 - Usando instanceof em expressões arbitrárias
  • Example#130 - Estrutura do switch
  • Example#131 - Basic match usage
  • Example#132 - Estrutura de uma expressão match
  • Example#133 - Exemplo de uma expressão match não tratada
  • Example#134 - Usando uma expressão match generalizada para ramificar com base em intervalos de inteiros
  • Example#135 - Usando uma expressão match generalizada para ramificar com base no conteúdo de strings
  • Example#136 - Exemplo de uso do Tick
  • Example#137 - Declarando o encoding do script.
  • Example#138 - Exemplo básico do construtor include
  • Example#139 - Inclusão em funções
  • Example#140 - Usando include via HTTP
  • Example#141 - Comparando valores de retorno do include
  • Example#142 - include e a instrução return
  • Example#143 - Usando buffer de saída para incluir um arquivo PHP em uma string
  • Example#144 - Exemplo da estrutura de controle goto
  • Example#145 - Exemplo da estrutura de controle goto em um laço
  • Example#146 - Isto não irá funcionar
  • Example#147 - Pseudo-código de demonstração de uma função
  • Example#148 - Funções definidas condicionalmente
  • Example#149 - Funções dentro de funções
  • Example#150 - Funções Recursivas
  • Example#151 - Passando arrays para funções
  • Example#152 - Argumentos de função com uma vírgula final
  • Example#153 - Passando parâmetros de função por referência
  • Example#154 - Utilizando parâmetros padrão em funções
  • Example#155 - Usando tipos não escalares como valores padrões
  • Example#156 - Usando objetos como valores padrão (a partir do PHP 8.1.0)
  • Example#157 - Uso incorreto de parâmetros padrão de função
  • Example#158 - Uso correto de parâmetros padrão de função
  • Example#159 - Uso correto de argumentos padrão de função
  • Example#160 - Declarando argumentos opcionais após argumentos obrigatórios
  • Example#161 - Utilizando ... para acessar argumentos variáveis
  • Example#162 - Utilizando ... para fornecer argumentos
  • Example#163 - Argumentos variáveis com type hint
  • Example#164 - Sintaxe dos argumentos nomeados
  • Example#165 - Comparando argumentos posicionais e nomeados
  • Example#166 - Mesmo exemplo com argumentos em ordem diferente
  • Example#167 - Combinando argumentos posicionais e nomeados
  • Example#168 - Erro lançado ao passar o mesmo argumento nomeado mais de uma vez
  • Example#169 - Usando argumentos nomeados após desempacotar
  • Example#170 - O uso de return
  • Example#171 - Retornando um array para devolver vários valores
  • Example#172 - Retornando uma referência de uma função
  • Example#173 - Exemplo de funções variáveis
  • Example#174 - Exemplo de chamada de um método variável
  • Example#175 - Método variávei com propriedades estáticas
  • Example#176 - Callables complexos
  • Example#177 -
  • Example#178 - Exemplo de função anônima
  • Example#179 - Exemplo de como definir uma função anônima para uma variável
  • Example#180 - Herdando variáveis do escopo anterior
  • Example#181 - Closures e escopo
  • Example#182 - Vinculação automática do $this
  • Example#183 - Tentando utilizar o $this de dentro de uma função anônima estática
  • Example#184 - Tentando vincular um objeto a uma função anônima estática
  • Example#185 - Arrow functions capturam variáveis por valor automaticamente
  • Example#186 - Arrow functions capturam variáveis por valor automaticamente, mesmo quando aninhadas
  • Example#187 - Examplos de arrow functions
  • Example#188 - Valores do escopo externo não podem ser modificados por arrow functions
  • Example#189 - Sintaxe de callable de primeira classe simples
  • Example#190 - Comparação de escopo de CallableExpr(...) e callable tradicional
  • Example#191 -
  • Example#192 - Definição Simples de uma Classe
  • Example#193 - Alguns exemplos da pseudo variável $this
  • Example#194 -
  • Example#195 -
  • Example#196 - Criando uma instância
  • Example#197 - Criando uma instância usando uma expressão arbitrária
  • Example#198 - Atribuição de Objetos
  • Example#199 - Criando novos objetos
  • Example#200 - Access member of newly created object
  • Example#201 - Acesso a propriedade vs. chamar um método
  • Example#202 - Chamando uma função anônima armazenada em uma propriedade
  • Example#203 - Herança da Classe Simples
  • Example#204 - Métodos compatíveis
  • Example#205 - Erro fatal quando um método derivado remove um parâmetro
  • Example#206 - Erro falta quando um método derivado transforma um parâmetro opcional em mandatório
  • Example#207 - Erro ao utilizar argumentos nomeados renomeados em uma classe derivada
  • Example#208 - Resolução de nome da classe
  • Example#209 - Resolução de um nome de classe de classe ausente
  • Example#210 - Resolução de nome de objeto
  • Example#211 - Operador nullsafe
  • Example#212 - Declaração de propriedades
  • Example#213 - Exemplo de propriedades tipadas
  • Example#214 - Acessando propriedades
  • Example#215 - Exemplo de propriedade somente leitura
  • Example#216 - Inicilização ilegal de propriedades somente leitura.
  • Example#217 -
  • Example#218 -
  • Example#219 -
  • Example#220 - Definindo e usando uma constante
  • Example#221 - Exemplo com informação estática
  • Example#222 - Exemplo de expressão constante
  • Example#223 - Modificadores de visibilidade em constantes de classe
  • Example#224 - Exemplo de Autoload
  • Example#225 - Outro exemplo de Autoload
  • Example#226 - Construtoras em herança
  • Example#227 - Utilizando argumentos de construtor
  • Example#228 - Utilizando promoção de propriedades no construtor
  • Example#229 - New em inicializações
  • Example#230 - Utilizando métodos estáticos para construção
  • Example#231 - Exemplo de Destrutor
  • Example#232 - Declaração de propriedade
  • Example#233 - Declaração de método
  • Example#234 - Declaração de constantes (desde o PHP 7.1.0)
  • Example#235 - Acessando membros privados entre objetos do mesmo tipo
  • Example#236 -
  • Example#237 - Exemplo de Herança
  • Example#238 - O método que sobrepõe não declara nenhum tipo de retorno
  • Example#239 - O método que sobrepõe declara um tipo de retorno errado
  • Example#240 - O método que sobrepõe declara um tipo de retorno errado sem uma notícia de depreciação
  • Example#241 - :: de fora da definição da classe
  • Example#242 - :: de dentro da definição da classe
  • Example#243 - Chamando um método pai
  • Example#244 - Exemplo de método estático
  • Example#245 - Exemplo de propriedade estática
  • Example#246 - Exemplo de classe abstrata
  • Example#247 - Exemplo de classe abstrata
  • Example#248 - Exemplo de Interface
  • Example#249 - Interfaces estendíveis
  • Example#250 - Compatibilidade de variância com interfaces múltiplas
  • Example#251 - Herança de várias interfaces
  • Example#252 - Interfaces com constantes
  • Example#253 - Interfaces with abstract classes
  • Example#254 - Extendendo e implementando ao mesmo tempo
  • Example#255 - Exemplo de Trait
  • Example#256 - Exemplo de Ordem de Precedência
  • Example#257 - Exemplo de Ordem de Precedência Alternativa
  • Example#258 - Uso de Traits Múltiplas
  • Example#259 - Exemplo de Resolução de Conflito
  • Example#260 - Exemplo de Mudança de Visibilidade de Método
  • Example#261 - Exemplo de Traits Compostas de Traits
  • Example#262 - Requisitos Expressos por Métodos Abstratos
  • Example#263 - Variáveis Estáticas
  • Example#264 - Métodos Estáticos
  • Example#265 - Propriedades Estáticas
  • Example#266 - Definindo Propriedades
  • Example#267 - Resolução de Conflito
  • Example#268 - Definindo Constantes
  • Example#269 - Resolução de Conflito
  • Example#270 - Sobrecarregando propriedades com __get(),
     __set(), __isset()
     and __unset()
  • Example#271 - Sobrecarga de métodos instanciados com __call() e __callStatic()
  • Example#272 - Iteração simples de objetos
  • Example#273 - Sleep e wakeup
  • Example#274 - Serialize e unserialize
  • Example#275 - Exemplo Simples
  • Example#276 - Usando __invoke()
  • Example#277 - Exemplo de __invoke()
  • Example#278 - Usando __set_state()
  • Example#279 - Utilizando o __debugInfo()
  • Example#280 - Exemplo de métodos final
  • Example#281 - Exemplo de classe Final
  • Example#282 - Exemplo de constantes finais (PHP 8.1.0 em diante)
  • Example#283 - Clonando um objeto
  • Example#284 - Acessar um membro de um objeto recém clonado
  • Example#285 - Exemplo de comparação de objetos
  • Example#286 - Uso do self::
  • Example#287 - Simples uso do static::
  • Example#288 - Uso do static:: em um contexto não-estático
  • Example#289 - Chamadas repassadas e não repassadas
  • Example#290 - Referências e Objetos
  • Example#291 - Exemplo da sintaxe de namespace
  • Example#292 - Declarando um único namespace
  • Example#293 - Declarando um único namespace
  • Example#294 - Declarando um único namespace com hierarquia
  • Example#295 - Declarando vários namespaces, sintaxe de combinação simples
  • Example#296 - Declarando vários namespaces, sintaxe de colchetes
  • Example#297 - Declarando vários namespaces e código sem namespace
  • Example#298 - Declarando vários namespaces e código sem namespace
  • Example#299 - Acessando classes, funções e constantes globais em um namespace
  • Example#300 - Acessando elementos dinamicamente
  • Example#301 - Acessando dinamicamente elementos com namespace
  • Example#302 - Exemplo de __NAMESPACE__, código com namespace
  • Example#303 - Exemplo de __NAMESPACE__, código global
  • Example#304 - Usando __NAMESPACE__ para construção dinâmica de nomes
  • Example#305 - O operador namespace, em um namespace
  • Example#306 - O operador namespace, em código global
  • Example#307 - Importanto ou apelidando com o operador use
  • Example#308 - Importando ou criando apelidos com várias declarações use combinadas
  • Example#309 - Importação e nomes dinâmicos
  • Example#310 - Importação e nomes completamente qualificados
  • Example#311 - Regra de importação inválida
  • Example#312 - Usando a especificação do espaço global
  • Example#313 - Acessando classes globais em um namespace
  • Example#314 - Recorrendo a funções/constantes globais em um namespace
  • Example#315 - Resoluções de nomes ilustradas
  • Example#316 - Acessando classes globais fora de um namespace
  • Example#317 - Acessando classes globais fora de um namespace
  • Example#318 - Acessando classes internas em namespaces
  • Example#319 - Acessando classes, funções ou constantes internas em namespaces
  • Example#320 - Nomes totalmente qualificados
  • Example#321 - Nomes qualificados
  • Example#322 - Nomes de classe não qualificados
  • Example#323 - Nomes de funções ou constantes não qualificados
  • Example#324 - Perigos do uso de nomes com namespace em uma string com aspas duplas
  • Example#325 - Constantes não definidas
  • Example#326 - Constantes não definidas
  • Example#327 - Valores limitados básicos
  • Example#328 - Valores exclusivos avançados
  • Example#329 - Convertendo avisos de erros em exceções
  • Example#330 - Lançando uma exceção
  • Example#331 - Manipulação de exceções com bloco finally
  • Example#332 - Interação entre blocos finally e return
  • Example#333 - Exceções alinhadas
  • Example#334 - Manipulação de múltiplas exceções no mesmo bloco catch
  • Example#335 - Omissão da variável de captura de exceções
  • Example#336 - Throw as an expression
  • Example#337 - A classe nativa Exception
  • Example#338 - Estendendo a classe Exception
  • Example#339 - Uso básico
  • Example#340 - Implementando range como um generator
  • Example#341 - Um exemplo simples de valores yield
  • Example#342 - Produzindo um par de chave/valor
  • Example#343 - Produzindo valores nullos
  • Example#344 - Produzindo valores por referência
  • Example#345 - yield from com iterator_to_array
  • Example#346 - Uso básico de yield from
  • Example#347 - yield from e valores retornados
  • Example#348 - Implementando métodos opcionais de uma interface com Atributos
  • Example#349 - Sintaxe de Atributo
  • Example#350 - Lendo Atributos Usando a API Reflection
  • Example#351 - Lendo Atributos Específicos Usando a API Reflection
  • Example#352 - Classe de Atributo Simples
  • Example#353 - Usando a especificação de destino para restringir onde os atributos podem ser usados
  • Example#354 - Usando IS_REPEATABLE para permitir o atributo em uma declaração várias vezes
  • Example#355 - Usando referência com variáveis indefinidas
  • Example#356 - Referenciando variáveis globais de dentro de funções
  • Example#357 - Referências e o comando foreach
  • Example#358 - Exemplo da $GLOBALS
  • Example#359 - Escrever em todo o $GLOBALS irá resultar em um erro.
  • Example#360 - Exemplo da $_SERVER
  • Example#361 - Exemplo da $_GET
  • Example#362 - Exemplo da $_POST
  • Example#363 - Exemplo da $_ENV
  • Example#364 - Exemplo da $_COOKIE
  • Example#365 - Exemplo da $php_errormsg
  • Example#366 - Exemplo da $http_response_header
  • Example#367 - Exemplo da $argc
  • Example#368 - Exemplo da $argv
  • Example#369 - Exemplo da Exception::getMessage
  • Example#370 - Exception::getPrevious example
  • Example#371 - Exemplo da Exception::getCode
  • Example#372 - Exemplo da Exception::getFile
  • Example#373 - Exemplo da Exception::getLine
  • Example#374 - Exemplo da Exception::getTrace
  • Example#375 - Exemplo da Exception::getTraceAsString
  • Example#376 - Exemplo da Exception::__toString
  • Example#377 - Use a função set_error_handler para transformar mensagens de erro em ErrorException.
  • Example#378 - Exemplo do método ErrorException::getSeverity
  • Example#379 - Exemplo do método Error::getMessage
  • Example#380 - Exemplo do método Error::getPrevious
  • Example#381 - Exemplo do método Error::getCode
  • Example#382 - Exemplo do método Error::getFile
  • Example#383 - Exemplo do método Error::getLine
  • Example#384 - Exemplo do método Error::getTrace
  • Example#385 - Exemplo do método Error::getTraceAsString
  • Example#386 - Exemplo do método Error::__toString
  • Example#387 - Utilização básica
  • Example#388 - Basic usage
  • Example#389 - Utilização básica
  • Example#390 - Exemplo do método ArrayAccess::offsetExists
  • Example#391 - Basic usage
  • Example#392 - Exemplo do método Closure::bind
  • Example#393 - Exemplo de Closure::bindTo
  • Example#394 - Exemplo do método Closure::call
  • Example#395 - Criado como resultado de uma conversão de tipo em um objeto
  • Example#396 - Criado como resultado da função json_decode
  • Example#397 - Declarando propriedades dinâmicas
  • Example#398 - Exemplo do método Generator::getReturn
  • Example#399 - Exemplo do método Generator::key
  • Example#400 - Usando o método Generator::send para injetar valores
  • Example#401 - Lança uma exceção no gerador
  • Example#402 - Uso básico de referência fraca
  • Example#403 - Exemplo de uso de Weakmap
  • Example#404 - Uso Básico de Stringable
  • Example#405 - Uso básico
  • Example#406 - Uso Básico
  • Example#407 - Uso básico
  • Example#408 - Passando um objeto SensitiveParameterValue para var_dump
  • Example#409 - Exemplo de SensitiveParameterValue::getValue
  • Example#410 -
  • Example#411 -
  • Example#412 - Exemplo básico de uso do parâmetro bindto
  • Example#413 - Buscando uma página e enviando dados pelo método POST
  • Example#414 - Ignorando redirecionamentos, mas trazendo os cabeçalhos e conteúdo
  • Example#415 - Exemplo básico de uso de password
  • Example#416 - Detectando a qual se chegou depois de todos os redirecionamentos
  • Example#417 - php://temp/maxmemory
  • Example#418 - php://filter/resource=<fluxo a ser filtrado>
  • Example#419 - php://filter/read=<lista de filtros a aplicar à cadeia de leitura>
  • Example#420 - php://filter/write=<lista de filtros a aplicar à cadeia de escrita>
  • Example#421 - php://memory e php://temp não são reutilizáveis
  • Example#422 - Imprimir conteúdo de data://
  • Example#423 - Obtém o tipo de mídia
  • Example#424 - Uso básico
  • Example#425 - Abrindo um fluxo para conexão ativa
  • Example#426 - Esta variável $session deve ser mantida disponível!
  • Example#427 - Explorando um arquivo RAR
  • Example#428 - Abrindo um arquivo criptografado (criptografia de cabeçalho)
  • Example#429 - Checagem fraca de variáveis resulta em....
  • Example#430 - ... um ataque ao sistema de arquivos
  • Example#431 - Checagem com mais segura do nome do arquivo
  • Example#432 - Checagem mais segura do nome do arquivo
  • Example#433 - Script vulnerável à bytes nulos
  • Example#434 - Validando entrada corretamente
  • Example#435 - Usando campo de senha hasheado
  • Example#436 - Dividindo o result set em páginas ... e criando super-usuários (PostgreSQL)
  • Example#437 - Listando artigos ... e algumas senhas (qualquer banco de dados)
  • Example#438 - De recuperando uma senha ... para ganhando mais privilégios (qualquer banco de dados)
  • Example#439 - Atacando o sistema de um banco de dados (MSSQL Server)
  • Example#440 - Evitando SQL injection ao utilizar instruções preparadas PDO
  • Example#441 - Atacando variáveis com uma página HTML personalizada
  • Example#442 - Explorando variáveis comuns de depuração
  • Example#443 - Encontrado variáveis perigosas com E_ALL
  • Example#444 - Uso Perigoso de Variáveis
  • Example#445 - Escondendo o PHP como outra linguagem
  • Example#446 - Usando extensões desconhecidas para o PHP
  • Example#447 - Usando extensão HTML para arquivos PHP
  • Example#448 - Exemplo de Autenticação HTTP "Basic"
  • Example#449 - Exemplo de autenticação HTTP "Digest"
  • Example#450 - Exemplo de Autenticação HTTP forçando um novo nome/senha
  • Example#451 - Um formulário XForms simples de busca
  • Example#452 - Usando um XForm para popular o $_POST
  • Example#453 - Formulário para Upload de Arquivo
  • Example#454 - Validando o upload de arquivos
  • Example#455 - Enviando um array de arquivos
  • Example#456 - Carregando múltiplos arquivos
  • Example#457 - Carregando um diretório inteiro
  • Example#458 - Salvando arquivos HTTP PUT
  • Example#459 - Pegando o título de uma página remota
  • Example#460 - Guardando informação em um servidor remoto
  • Example#461 - Exemplo demonstrando a diferença entre CGI e SAPI:
  • Example#462 -
  • Example#463 - Retorna os módulos PHP e Zend embutidos e carregados
  • Example#464 - Recebendo um erro de sintaxe ao usar aspas duplas
  • Example#465 - Usar aspas simples previne a substituição de variáveis pelo ambiente de linha de comando
  • Example#466 - Usando as opções -B, -R e -E para contar o número de linhas de um projeto.
  • Example#467 - Use -v para requisitar o nome SAPI e a versão do PHP e Zend Engine
  • Example#468 - --ini exemplo
  • Example#469 - uso básico da opção --rf
  • Example#470 - exemplo de --rc
  • Example#471 - Exemplo de --re
  • Example#472 - exemplo de --ri
  • Example#473 - Executando scripts PHP como shell scripts
  • Example#474 - Script planejado para ser executado na linha de comando (script.php)
  • Example#475 - Arquivo batch para rodar um script de linha de comando em PHP (script.bat)
  • Example#476 - Executando código usando o shell interativo
  • Example#477 - Sugestões de complemento com tab
  • Example#478 - Definindo configurações php.ini no shell interativo
  • Example#479 - Iniciando o servidor web
  • Example#480 - Iniciando o servidor web com um diretório raiz específico
  • Example#481 - Usando um script de roteamento
  • Example#482 - Verificando o Uso do CLI Web Server
  • Example#483 - Tratando de tipos de arquivos não suportados
  • Example#484 - Acessando o servidor web CLI de máquinas remotas
  • Example#485 - Criando um novo contêiner zval
  • Example#486 - Mostrando a informação zval
  • Example#487 - Aumentando o "refcount" de um zval
  • Example#488 - Diminuindo o "refcount" de zval
  • Example#489 - Criando um zval de array
  • Example#490 - Adicionando elemento já existente a um array
  • Example#491 - Removendo um elemento de um array
  • Example#492 - Adicionando o próprio array como um elemento de si mesmo
  • Example#493 - Removendo a atribuição de $a
  • Example#494 - Exemplo de uso de memória
  • Example#495 - Influência do Coletor de Lixo no desempenho
  • Example#496 - Executando o script acima
  • Example#497 - Recompilando o PHP para habilitar o benchmarking de GC
  • Example#498 - Estatísticas GC
  • Example#499 - Arquivo all_probes.d para instrumentar todos os Sensores Estáticos PHP com DTrace
  • Example#500 - all_probes.stp para instrumentação de todos os Sensores Estáticos do PHP com SystemTap
  • Example#501 - A apcu_add example
  • Example#502 - A apcu_cache_info example
  • Example#503 - apcu_cas example
  • Example#504 - apcu_dec example
  • Example#505 - A apcu_delete example
  • Example#506 - An apcu_entry example
  • Example#507 - apcu_exists example
  • Example#508 - A apcu_fetch example
  • Example#509 - apcu_inc example
  • Example#510 - A apcu_key_info example
  • Example#511 - A apcu_sma_info example
  • Example#512 - A apcu_store example
  • Example#513 - A APCUIterator::__construct example
  • Example#514 - Usando gerenciamento de erro em um script
  • Example#515 - debug_backtrace example
  • Example#516 - Exemplo de debug_print_backtrace
  • Example#517 - An error_clear_last example
  • Example#518 - Um exemplo de error_get_last
  • Example#519 - Exemplos error_log
  • Example#520 - Exemplo error_reporting
  • Example#521 - Exemplo de restore_error_handler
  • Example#522 - restore_exception_handler example
  • Example#523 - Error handling with set_error_handler and trigger_error
  • Example#524 - set_exception_handler example
  • Example#525 - Exemplo de trigger_error
  • Example#526 - Calling a function from shared library
  • Example#527 - Calling a function, returning a structure through an argument
  • Example#528 - Accessing existing C variables
  • Example#529 - Creating and Modifying C variables
  • Example#530 - Working with C arrays
  • Example#531 - Working with C enums
  • Example#532 -
  • Example#533 -
  • Example#534 - Exemplo de Controle de Saída
  • Example#535 - Exemplo de re-escrita na saída
  • Example#536 - ob_end_clean example
  • Example#537 - ob_end_flush example
  • Example#538 - A simple ob_get_clean example
  • Example#539 - Um simples exemplo de ob_get_contents
  • Example#540 - ob_get_flush example
  • Example#541 - Um simples exemplo de ob_get_length
  • Example#542 - ob_gzhandler example
  • Example#543 - ob_list_handlers example
  • Example#544 - Exemplo de uma função de callback
  • Example#545 - Criando um buffer de saída não apagável
  • Example#546 - output_add_rewrite_var example
  • Example#547 - output_reset_rewrite_vars example
  • Example#548 - assert_options example
  • Example#549 - Exemplo de assert
  • Example#550 - Utilizando uma mensagem customizada
  • Example#551 - Utilizando uma classe exception
  • Example#552 - cli_get_process_title example
  • Example#553 - cli_set_process_title example
  • Example#554 - Exemplosdl
  • Example#555 - Exemplo de extension_loaded
  • Example#556 - A gc_enabled example
  • Example#557 - gc_status Usage
  • Example#558 - get_current_user example
  • Example#559 - get_defined_constants Example
  • Example#560 - Imprime as funções de XML
  • Example#561 - Exemplo de get_include_path
  • Example#562 - get_included_files example
  • Example#563 - get_loaded_extensions Example
  • Example#564 - Unfiltered get_resources
  • Example#565 - Filtered get_resources
  • Example#566 - getenv Example
  • Example#567 - Exemplo de getlastmod
  • Example#568 - Exemplo básico de getopt
  • Example#569 - Exemplo de getopt com opções longas
  • Example#570 - getopt example: Passing multiple options as one
  • Example#571 - Exemplo de getopt com rest_index
  • Example#572 - getrusage example
  • Example#573 - ini_get_all examples
  • Example#574 - Disabling details
  • Example#575 - A few ini_get examples
  • Example#576 - A few ini_parse_quantity examples
  • Example#577 - ini_restore example
  • Example#578 - Setting an ini option
  • Example#579 - A memory_get_usage example
  • Example#580 - memory_reset_peak_usage example
  • Example#581 - php_ini_loaded_file example
  • Example#582 - A simple example to list the returned ini files
  • Example#583 - php_sapi_name example
  • Example#584 - Some php_uname examples
  • Example#585 - A few OS related constant examples
  • Example#586 - Prints the general credits
  • Example#587 - Prints the core developers and the documentation group
  • Example#588 - Printing all the credits
  • Example#589 - phpinfo Example
  • Example#590 - phpversion example
  • Example#591 - PHP_VERSION_ID example and usage
  • Example#592 - Definindo uma variável de ambiente
  • Example#593 - Exemplo de restore_include_path
  • Example#594 - set_include_path example
  • Example#595 - Adding to the include path
  • Example#596 - sys_get_temp_dir example
  • Example#597 - version_compare examples
  • Example#598 - zend_thread_id example
  • Example#599 - Exemplo de zend_version
  • Example#600 - Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini
  • Example#601 - A runkit7_function_add example
  • Example#602 - A runkit7_function_copy example
  • Example#603 - A runkit7_function_redefine example
  • Example#604 - runkit7_method_add example
  • Example#605 - runkit7_method_copy example
  • Example#606 - runkit7_method_redefine example
  • Example#607 - runkit7_method_remove example
  • Example#608 - runkit7_method_rename example
  • Example#609 - runkit7_zval_inspect example
  • Example#610 - Basic uopz_add_function Usage
  • Example#611 - uopz_allow_exit example
  • Example#612 - uopz_backup example
  • Example#613 - uopz_compose example
  • Example#614 - uopz_copy example
  • Example#615 - Basic uopz_del_function Usage
  • Example#616 - uopz_delete example
  • Example#617 - uopz_delete class example
  • Example#618 - uopz_extend example
  • Example#619 - uopz_flags example
  • Example#620 - "Unfinalize" a Class
  • Example#621 - uopz_function example
  • Example#622 - uopz_function class example
  • Example#623 - uopz_get_exit_status example
  • Example#624 - Basic uopz_get_hook Usage
  • Example#625 - uopz_get_mock example
  • Example#626 - Basic uopz_get_property Usage
  • Example#627 - uopz_get_return example
  • Example#628 - Basic uopz_get_static Usage
  • Example#629 - uopz_implement example
  • Example#630 - uopz_overload example
  • Example#631 - uopz_redefine example
  • Example#632 - uopz_rename example
  • Example#633 - uopz_rename class example
  • Example#634 - uopz_restore example
  • Example#635 - Basic uopz_set_hook Usage
  • Example#636 - uopz_set_mock example
  • Example#637 - uopz_set_mock example
  • Example#638 - uopz_set_mock and static members
  • Example#639 - Basic uopz_set_property Usage
  • Example#640 - uopz_set_return example
  • Example#641 - uopz_set_return example
  • Example#642 - uopz_set_return class example
  • Example#643 - Basic uopz_set_static Usage
  • Example#644 - uopz_undefine example
  • Example#645 - Basic uopz_unset_hook Usage
  • Example#646 - uopz_unset_mock example
  • Example#647 - uopz_unset_return example
  • Example#648 - wincache.ignorelist example
  • Example#649 - Authentication configuration for wincache.php
  • Example#650 - Enabling WinCache session handler
  • Example#651 - Enabling WinCache functions reroutes
  • Example#652 - Reroute.ini file content
  • Example#653 - A wincache_fcache_fileinfo example
  • Example#654 - A wincache_fcache_meminfo example
  • Example#655 - Using wincache_lock
  • Example#656 - A wincache_ocache_fileinfo example
  • Example#657 - A wincache_ocache_meminfo example
  • Example#658 - A wincache_refresh_if_changed example
  • Example#659 - A wincache_rplist_fileinfo example
  • Example#660 - A wincache_rplist_meminfo example
  • Example#661 - A wincache_scache_info example
  • Example#662 - A wincache_scache_meminfo example
  • Example#663 - wincache_ucache_add with key as a string
  • Example#664 - wincache_ucache_add with key as an array
  • Example#665 - Using wincache_ucache_cas
  • Example#666 - using wincache_ucache_clear
  • Example#667 - Using wincache_ucache_dec
  • Example#668 - Using wincache_ucache_delete with key as a string
  • Example#669 - Usingwincache_ucache_delete with key as an array
  • Example#670 - Using wincache_ucache_delete with key as an array where some elements cannot be deleted
  • Example#671 - Using wincache_ucache_exists
  • Example#672 - wincache_ucache_get with key as a string
  • Example#673 - wincache_ucache_get with key as an array
  • Example#674 - Using wincache_ucache_inc
  • Example#675 - Using wincache_ucache_info
  • Example#676 - A wincache_ucache_meminfo example
  • Example#677 - wincache_ucache_set with key as a string
  • Example#678 - wincache_ucache_set with key as an array
  • Example#679 - Using wincache_unlock
  • Example#680 - Xhprof example with the optional GUI
  • Example#681 - xhprof_disable example
  • Example#682 - xhprof_enable examples
  • Example#683 - xhprof_sample_disable example
  • Example#684 - Make sure the item is stored
  • Example#685 - Using CHAP passwords
  • Example#686 - radius_acct_open example
  • Example#687 - radius_add_server example
  • Example#688 - radius_auth_open example
  • Example#689 - radius_create_request example
  • Example#690 - radius_cvt_addr example
  • Example#691 - radius_cvt_int example
  • Example#692 - radius_cvt_string example
  • Example#693 - radius_get_attr example
  • Example#694 - radius_get_tagged_attr_data example
  • Example#695 - radius_get_tagged_attr_tag example
  • Example#696 - radius_get_vendor_attr example
  • Example#697 - radius_put_attr example
  • Example#698 - radius_put_int example
  • Example#699 - radius_put_string example
  • Example#700 - radius_put_vendor_attr example
  • Example#701 - Readline Callback Interface Example
  • Example#702 - readline
  • Example#703 - Um exemplo simples de bzip2
  • Example#704 - Comprimindo dados
  • Example#705 - Descomprimindo uma String
  • Example#706 - Exemplo da bzerror
  • Example#707 - Exemplo de bzopen
  • Example#708 - Exemplo de bzread
  • Example#709 - Exemplo de bzwrite
  • Example#710 - Using an external file
  • Example#711 - Using a file within a phar archive
  • Example#712 - Converting a phar archive from phar to tar file format
  • Example#713 - phar.cache_list usage example
  • Example#714 - A Phar::addEmptyDir example
  • Example#715 - A Phar::addFile example
  • Example#716 - A Phar::addFromString example
  • Example#717 - A Phar::apiVersion example
  • Example#718 - A Phar::buildFromDirectory example
  • Example#719 - A Phar::buildFromIterator with SplFileInfo
  • Example#720 - A Phar::buildFromIterator with other iterators
  • Example#721 - A Phar::canCompress example
  • Example#722 - A Phar::canWrite example
  • Example#723 - A Phar::compress example
  • Example#724 - A Phar::compressFiles example
  • Example#725 - A Phar::__construct example
  • Example#726 - A Phar::convertToData example
  • Example#727 - A Phar::convertToExecutable example
  • Example#728 - A Phar::copy example
  • Example#729 - A Phar::count example
  • Example#730 - A Phar::createDefaultStub example
  • Example#731 - A Phar::decompress example
  • Example#732 - A Phar::decompressFiles example
  • Example#733 - A Phar::delMetaData example
  • Example#734 - A Phar::delete example
  • Example#735 - A Phar::extractTo example
  • Example#736 - A Phar::getMetadata example
  • Example#737 - A Phar::getStub example
  • Example#738 - A Phar::hasMetadata example
  • Example#739 - A Phar::interceptFileFuncs example
  • Example#740 - A Phar::interceptFileFuncs example
  • Example#741 - A Phar::isBuffering example
  • Example#742 - A Phar::isCompressed example
  • Example#743 - A Phar::loadPhar example
  • Example#744 - A Phar::mapPhar example
  • Example#745 - A Phar::mount example
  • Example#746 - A Phar::mungServer example
  • Example#747 - A Phar::offsetExists example
  • Example#748 - Phar::offsetGet example
  • Example#749 - A Phar::offsetSet example
  • Example#750 - A Phar::offsetUnset example
  • Example#751 - A Phar::running example
  • Example#752 - A Phar::setAlias example
  • Example#753 - A Phar::setDefaultStub example
  • Example#754 - A Phar::setMetadata example
  • Example#755 - A Phar::setStub example
  • Example#756 - A Phar::startBuffering example
  • Example#757 - A Phar::stopBuffering example
  • Example#758 - A Phar::unlinkArchive example
  • Example#759 - A Phar::webPhar example
  • Example#760 - A PharData::addEmptyDir example
  • Example#761 - A PharData::addFile example
  • Example#762 - A PharData::addFromString example
  • Example#763 - A PharData::buildFromDirectory example
  • Example#764 - A PharData::buildFromIterator with SplFileInfo
  • Example#765 - A PharData::buildFromIterator with other iterators
  • Example#766 - A PharData::compress example
  • Example#767 - A PharData::compressFiles example
  • Example#768 - A PharData::__construct example
  • Example#769 - A PharData::convertToData example
  • Example#770 - A PharData::convertToExecutable example
  • Example#771 - A PharData::copy example
  • Example#772 - A PharData::decompress example
  • Example#773 - A PharData::decompressFiles example
  • Example#774 - A PharData::delMetaData example
  • Example#775 - A PharData::delete example
  • Example#776 - A PharData::extractTo example
  • Example#777 - A PharData::offsetSet example
  • Example#778 - A PharData::offsetUnset example
  • Example#779 - A Phar::setMetadata example
  • Example#780 - A PharFileInfo::chmod example
  • Example#781 - A PharFileInfo::compress example
  • Example#782 - A PharFileInfo::__construct example
  • Example#783 - A PharFileInfo::decompress example
  • Example#784 - A PharFileInfo::delMetaData example
  • Example#785 - A PharFileInfo::getCRC32 example
  • Example#786 - A PharFileInfo::getCompressedSize example
  • Example#787 - A PharFileInfo::getMetadata example
  • Example#788 - A PharFileInfo::getPharFlags example
  • Example#789 - A PharFileInfo::isCRCChecked example
  • Example#790 - A PharFileInfo::isCompressed example
  • Example#791 - A PharFileInfo::setMetadata example
  • Example#792 - Rar installation
  • Example#793 - On-the-fly decompression
  • Example#794 - RAR extension filesystem extraction example
  • Example#795 - Estilo orientado a objetos
  • Example#796 - Estilo procedural
  • Example#797 - Estilo orientado a objetos
  • Example#798 - Estilo procedural
  • Example#799 - Estilo orientado a objetos
  • Example#800 - Estilo procedural
  • Example#801 - Estilo orientado a objetos
  • Example#802 - Estilo procedural
  • Example#803 - Estilo orientado a objetos
  • Example#804 - Estilo procedural
  • Example#805 - Estilo orientado a objetos
  • Example#806 - Estilo procedural
  • Example#807 - Estilo orientado a objetos
  • Example#808 - Estilo procedural
  • Example#809 - Volume Callback
  • Example#810 - Estilo orientado a objetos
  • Example#811 - Estilo procedural
  • Example#812 - RarArchive::__toString example
  • Example#813 - RarEntry::extract example
  • Example#814 - How to extract all files in archive:
  • Example#815 - RarEntry::getAttr example
  • Example#816 - RarEntry::getHostOs example (version >= 2.0.0)
  • Example#817 - RarEntry::getHostOs example (version <= 1.0.0)
  • Example#818 - RarEntry::getMethod example
  • Example#819 - RarEntry::getName example
  • Example#820 - RarEntry::getPackedSize example
  • Example#821 - RarEntry::getStream example
  • Example#822 - RarEntry::getUnpackedSize example
  • Example#823 - RarEntry::getVersion example
  • Example#824 - RarException::isUsingExceptions example
  • Example#825 - RarException::setUsingExceptions example
  • Example#826 - Criando um arquivo Zip
  • Example#827 - Exibindo detalhes dos arquivos e listando-os
  • Example#828 - Zip stream wrapper, lendo um OpenOffice meta info
  • Example#829 - Exemplo de uso
  • Example#830 - Create a new directory in an archive
  • Example#831 - Open and add
  • Example#832 - Add an entry to a new archive
  • Example#833 - Add file to a directory inside an archive
  • Example#834 - ZipArchive::addGlob example
  • Example#835 - ZipArchive::addPattern example
  • Example#836 - Delete file from archive using its index
  • Example#837 - Deleting a file and directory from an archive, using names
  • Example#838 - Extract all entries
  • Example#839 - Extract two entries
  • Example#840 - Dump an archive comment
  • Example#841 - Test if archive is a torrentzip format
  • Example#842 - Dump an entry comment
  • Example#843 - Dump an entry comment
  • Example#844 - Extract all entries with Unix rights
  • Example#845 - Get the file contents
  • Example#846 - Get the file contents
  • Example#847 - Convert an image from a zip entry
  • Example#848 - ZipArchive::getNameIndex example
  • Example#849 - Get the entry contents with fread and store it
  • Example#850 - Same as the previous example but with fopen and the zip stream wrapper
  • Example#851 - Stream wrapper and image, can be used with the xml function as well
  • Example#852 - Get the entry contents with fread and store it
  • Example#853 - Get the entry contents with fread and store it
  • Example#854 - Create an archive and then use it with ZipArchive::locateName
  • Example#855 - Open and extract
  • Example#856 - Create an archive
  • Example#857 - Create an temporary archive
  • Example#858 - Archive a file
  • Example#859 - Archive a file
  • Example#860 - Rename one entry
  • Example#861 - Rename one entry
  • Example#862 - Open and replace
  • Example#863 - Create an archive and set a comment
  • Example#864 - Create a torrentzip archive
  • Example#865 - Open an archive and set a comment for an entry
  • Example#866 - Open an archive and set a comment for an entry
  • Example#867 - Add files with different compression methods to an archive
  • Example#868 - Add files with different compression methods to an archive
  • Example#869 - Add file and set compression method
  • Example#870 - Archive and encrypt a file
  • Example#871 - Archive a file, with its Unix rights
  • Example#872 - Archive a file
  • Example#873 - Archive a file
  • Example#874 - Dump the stat info of an entry
  • Example#875 - Dump the stat info of an entry
  • Example#876 - Pequeno Exemplo da Zlib
  • Example#877 - Utilizando a API de compressão/expansão incremental
  • Example#878 - Exemplo gzclose
  • Example#879 - gzcompress example
  • Example#880 - gzdeflate example
  • Example#881 - Creating a gzip file
  • Example#882 - gzeof example
  • Example#883 - gzfile example
  • Example#884 - gzgetc example
  • Example#885 - gzgets example
  • Example#886 - gzgetss example
  • Example#887 - gzinflate example
  • Example#888 - gzopen Example
  • Example#889 - gzpassthru example
  • Example#890 - gzread example
  • Example#891 - gzseek example
  • Example#892 - gzuncompress example
  • Example#893 - Exemplo da gzwrite
  • Example#894 - zlib_encode example
  • Example#895 - hash_algos example
  • Example#896 - hash_copy example
  • Example#897 - hash_equals example
  • Example#898 - Using hash_file
  • Example#899 - hash_hkdf example
  • Example#900 - hash_hmac_algos example
  • Example#901 - hash_hmac_file example
  • Example#902 - hash_hmac example
  • Example#903 - Incremental hashing example
  • Example#904 - hash_pbkdf2 example, basic usage
  • Example#905 - hash_update_stream example
  • Example#906 - A hash example
  • Example#907 - mcrypt_create_iv Example
  • Example#908 - mcrypt_enc_get_algorithms_name example
  • Example#909 - mcrypt_enc_get_modes_name example
  • Example#910 - mcrypt_enc_get_supported_key_sizes example
  • Example#911 - mcrypt_encrypt Example
  • Example#912 - mcrypt_get_block_size example
  • Example#913 - mcrypt_get_cipher_name Example
  • Example#914 - mcrypt_get_iv_size Example
  • Example#915 - mcrypt_get_key_size Example
  • Example#916 - mcrypt_list_algorithms Example
  • Example#917 - mcrypt_list_modes Example
  • Example#918 - mcrypt_module_open Examples
  • Example#919 - Using mcrypt_module_open in encryption
  • Example#920 - mcrypt_module_self_test example
  • Example#921 - mdecrypt_generic Example
  • Example#922 - Calcula o MD5 compiladodigest e hmac e imprimi como hex
  • Example#923 - Listando todas as hashes
  • Example#924 - Exemplo de mhash_get_block_size
  • Example#925 - Exemplo de mhash_get_hash_name
  • Example#926 - openssl_cipher_iv_length example
  • Example#927 - openssl_cipher_key_length example
  • Example#928 - openssl_cms_sign example
  • Example#929 - openssl_csr_export_to_file() example
  • Example#930 - openssl_csr_export() example
  • Example#931 - openssl_csr_get_public_key() example
  • Example#932 - openssl_csr_get_subject() example
  • Example#933 - Creating a self-signed certificate
  • Example#934 - Creating a self-signed ECC certificate (as of PHP 7.1.0)
  • Example#935 - openssl_csr_sign example - signing a CSR (how to implement your own CA)
  • Example#936 - Compute a shared secret
  • Example#937 - Generate a DH public/private keypair in php
  • Example#938 - AES Authenticated Encryption in GCM mode example for PHP 7.1+
  • Example#939 - AES Authenticated Encryption example prior to PHP 7.1
  • Example#940 - openssl_error_string example
  • Example#941 - openssl_get_cert_locations example
  • Example#942 - openssl_get_cipher_methods example
  • Example#943 - openssl_get_curve_names example
  • Example#944 - openssl_get_md_methods example
  • Example#945 - openssl_open example
  • Example#946 - openssl_pbkdf2() example
  • Example#947 - openssl_pkcs12_read example
  • Example#948 - openssl_pkcs7_decrypt example
  • Example#949 - openssl_pkcs7_encrypt example
  • Example#950 - Get a PEM array from a P7B file
  • Example#951 - openssl_pkcs7_sign example
  • Example#952 - openssl_pkey_derive example
  • Example#953 - Obtain the public key from a private key
  • Example#954 - openssl_random_pseudo_bytes example
  • Example#955 - openssl_seal example
  • Example#956 - openssl_sign example
  • Example#957 - openssl_sign example
  • Example#958 - openssl_spki_export_challenge example
  • Example#959 - openssl_spki_export_challenge example from <keygen>
  • Example#960 - openssl_spki_export example
  • Example#961 - openssl_spki_export example from <keygen>
  • Example#962 - openssl_spki_new example
  • Example#963 - openssl_spki_verify example
  • Example#964 - openssl_spki_verify example from <keygen>
  • Example#965 - openssl_verify example
  • Example#966 - openssl_verify example
  • Example#967 - openssl_x509_verify example
  • Example#968 - Exemplo de password_hash
  • Example#969 - Exemplo de configuração do custo de password_hash manualmente
  • Example#970 - Exemplo de busca de um bom custo para password_hash
  • Example#971 - Exemplo de password_hash usando Argon2i
  • Example#972 - Utilização de password_needs_rehash
  • Example#973 - Exemplo de password_verify
  • Example#974 - RNP clearsign example
  • Example#975 - simple callback function example
  • Example#976 - sodium_crypto_box_seal_open example
  • Example#977 - sodium_crypto_box_seal example
  • Example#978 - sodium_crypto_core_ristretto255_add example
  • Example#979 - sodium_crypto_core_ristretto255_from_hash example
  • Example#980 - sodium_crypto_core_ristretto255_is_valid_point example
  • Example#981 - sodium_crypto_core_ristretto255_random example
  • Example#982 - sodium_crypto_core_ristretto255_scalar_add example
  • Example#983 - sodium_crypto_core_ristretto255_scalar_invert example
  • Example#984 - sodium_crypto_core_ristretto255_scalar_negate example
  • Example#985 - sodium_crypto_core_ristretto255_scalar_random example
  • Example#986 - sodium_crypto_core_ristretto255_scalar_sub example
  • Example#987 - sodium_crypto_core_ristretto255_sub example
  • Example#988 - sodium_crypto_generichash_final example
  • Example#989 - sodium_crypto_generichash_init example
  • Example#990 - sodium_crypto_generichash_update example
  • Example#991 - sodium_crypto_kx_keypair usage
  • Example#992 - sodium_crypto_pwhash_str example
  • Example#993 - sodium_crypto_pwhash example
  • Example#994 - sodium_crypto_secretbox_keygen example
  • Example#995 - Comparing sodium_crypto_secretbox_keygen with random_bytes
  • Example#996 - sodium_crypto_secretbox_open example
  • Example#997 - sodium_crypto_secretbox example
  • Example#998 - sodium_crypto_secretstream_xchacha20poly1305_init_pull example
  • Example#999 - sodium_crypto_secretstream_xchacha20poly1305_init_push example
  • Example#1000 - sodium_crypto_stream_xchacha20_xor_ic example
  • Example#1001 - DBA example
  • Example#1002 - Traversing a database
  • Example#1003 - dba_handlers Example
  • Example#1004 - List Privileges for a Column
  • Example#1005 - List Columns of a Table
  • Example#1006 - DSN-less connections
  • Example#1007 - odbc_connection_string_quote example
  • Example#1008 - List available DSNs
  • Example#1009 - Exemplos de odbc_execute e odbc_prepare
  • Example#1010 - odbc_fetch_into examples
  • Example#1011 - odbc_next_result
  • Example#1012 - Exemplos de odbc_execute e odbc_prepare
  • Example#1013 - List primary Keys of a Column
  • Example#1014 - List Columns of a stored Procedure
  • Example#1015 - List stored Procedures of a Database
  • Example#1016 - odbc_result examples
  • Example#1017 - odbc_setoption examples
  • Example#1018 - List Statistics of a Table
  • Example#1019 - List Privileges of a Table
  • Example#1020 - List Tables in a Catalog
  • Example#1021 - using PDO::ATTR_DRIVER_NAME
  • Example#1022 - Connecting to MySQL
  • Example#1023 - Handling connection errors
  • Example#1024 - Closing a connection
  • Example#1025 - Persistent connections
  • Example#1026 - Executing a batch in a transaction
  • Example#1027 - Repeated inserts using prepared statements
  • Example#1028 - Repeated inserts using prepared statements
  • Example#1029 - Fetching data using prepared statements
  • Example#1030 - Calling a stored procedure with an output parameter
  • Example#1031 - Calling a stored procedure with an input/output parameter
  • Example#1032 - Invalid use of placeholder
  • Example#1033 - Create a PDO instance and set the error mode
  • Example#1034 - Create a PDO instance and set the error mode from the constructor
  • Example#1035 - Displaying an image from a database
  • Example#1036 - Inserting an image into a database
  • Example#1037 - Inserting an image into a database: Oracle
  • Example#1038 - Reverter uma transação
  • Example#1039 - Enviando uma transação básica
  • Example#1040 - Enviando uma transação DDL
  • Example#1041 - Create a PDO instance via driver invocation
  • Example#1042 - Create a PDO instance via URI invocation
  • Example#1043 - Create a PDO instance using an alias
  • Example#1044 - Retrieving an SQLSTATE code
  • Example#1045 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#1046 - Emitindo uma instrução DELETE
  • Example#1047 - Recuperando atributos de uma conexão com o banco de dados
  • Example#1048 - Exemplo de PDO::getAvailableDrivers
  • Example#1049 - SQL statement template with named parameters
  • Example#1050 - SQL statement template with question mark parameters
  • Example#1051 - SQL statement template with question mark escaped
  • Example#1052 - SQL with no placeholders can be executed using PDO::query
  • Example#1053 - Quoting a normal string
  • Example#1054 - Quoting a dangerous string
  • Example#1055 - Quoting a complex string
  • Example#1056 - Roll back a transaction
  • Example#1057 - Binding result set output to PHP variables
  • Example#1058 - Execute a prepared statement with named placeholders
  • Example#1059 - Execute a prepared statement with question mark placeholders
  • Example#1060 - Call a stored procedure with an INOUT parameter
  • Example#1061 - Execute a prepared statement with named placeholders
  • Example#1062 - Execute a prepared statement with question mark placeholders
  • Example#1063 - A PDOStatement::closeCursor example
  • Example#1064 - Counting columns
  • Example#1065 - PDOStatement::debugDumpParams example with named parameters
  • Example#1066 - PDOStatement::debugDumpParams example with unnamed parameters
  • Example#1067 - Retrieving an SQLSTATE code
  • Example#1068 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#1069 - Execute a prepared statement with a bound variable and value
  • Example#1070 - Execute a prepared statement with an array of named values
  • Example#1071 - Execute a prepared statement with an array of positional values
  • Example#1072 - Execute a prepared statement with variables bound to positional placeholders
  • Example#1073 - Execute a prepared statement using array for IN clause
  • Example#1074 - Fetching rows using different fetch styles
  • Example#1075 - Fetching rows with a scrollable cursor
  • Example#1076 - Construction order
  • Example#1077 - Fetch all remaining rows in a result set
  • Example#1078 - Fetching all values of a single column from a result set
  • Example#1079 - Grouping all values by a single column
  • Example#1080 - Instantiating a class for each result
  • Example#1081 - Calling a function for each result
  • Example#1082 - Return first column of the next row
  • Example#1083 - Retrieving column metadata
  • Example#1084 - Fetching multiple rowsets returned from a stored procedure
  • Example#1085 - Return the number of deleted rows
  • Example#1086 - Counting rows returned by a SELECT statement
  • Example#1087 - Definindo um modo de carga
  • Example#1088 - Insert LOBs in CUBRID PDO
  • Example#1089 - Fetch LOBs in CUBRID PDO
  • Example#1090 - Insert set in CUBRID PDO with default data type.
  • Example#1091 - Specify data type when insert set in CUBRID PDO
  • Example#1092 - PDO_CUBRID DSN examples
  • Example#1093 - A PDO::cubrid_schema example
  • Example#1094 - PDO_DBLIB DSN examples
  • Example#1095 - PDO_FIREBIRD DSN example with path
  • Example#1096 - PDO_FIREBIRD DSN example with port and path
  • Example#1097 - PDO_FIREBIRD DSN example with localhost and path to employee.fdb on Debian system
  • Example#1098 - PDO_FIREBIRD DSN to connect to a dialect 1 database
  • Example#1099 - PDO_IBM DSN example using db2cli.ini
  • Example#1100 - PDO_IBM DSN example using a connection string
  • Example#1101 - PDO_INFORMIX DSN example using odbc.ini
  • Example#1102 - PDO_INFORMIX DSN example using a connection string
  • Example#1103 - Configurando o mode sem buffer no MySQL
  • Example#1104 - PDO_MYSQL DSN examples
  • Example#1105 - PDO_SQLSRV DSN examples
  • Example#1106 - PDO_OCI DSN examples
  • Example#1107 - PDO_ODBC DSN example (ODBC driver manager)
  • Example#1108 - PDO_ODBC DSN example (IBM DB2 uncataloged connection)
  • Example#1109 - PDO_ODBC DSN example (Microsoft Access uncataloged connection)
  • Example#1110 - PDO_PGSQL DSN examples
  • Example#1111 - A PDO::pgsqlLOBCreate example
  • Example#1112 - A PDO::pgsqlLOBOpen example
  • Example#1113 - A PDO::pgsqlLOBUnlink example
  • Example#1114 - Exemplos de DSN PDO_SQLITE
  • Example#1115 - Exemplo de função de agregação max_length
  • Example#1116 - Exemplo de PDO::sqliteCreateCollation
  • Example#1117 - Exemplo de PDO::sqliteCreateFunction
  • Example#1118 - Example of Data Retrieval
  • Example#1119 - Example of Data Insertion
  • Example#1120 - cubrid_bind example
  • Example#1121 - cubrid_bind BLOB/CLOB example
  • Example#1122 - cubrid_bind BLOB/CLOB example
  • Example#1123 - cubrid_close_prepare example
  • Example#1124 - cubrid_close_request example
  • Example#1125 - cubrid_col_get example
  • Example#1126 - cubrid_col_size example
  • Example#1127 - cubrid_column_names example
  • Example#1128 - cubrid_column_types example
  • Example#1129 - cubrid_commit example
  • Example#1130 - cubrid_connect_with_url url without properties example
  • Example#1131 - cubrid_connect_with_url url with properties example
  • Example#1132 - cubrid_connect example
  • Example#1133 - cubrid_current_oid example
  • Example#1134 - cubrid_disconnect example
  • Example#1135 - cubrid_drop example
  • Example#1136 - cubrid_error_code_facility example
  • Example#1137 - cubrid_error_code example
  • Example#1138 - cubrid_error_msg example
  • Example#1139 - cubrid_execute example
  • Example#1140 - cubrid_fetch example
  • Example#1141 - cubrid_free_result example
  • Example#1142 - cubrid_get_charset example
  • Example#1143 - cubrid_get_class_name example
  • Example#1144 - cubrid_get_client_info example
  • Example#1145 - cubrid_get_db_parameter example
  • Example#1146 - cubrid_get_query_timeout example
  • Example#1147 - cubrid_get_server_info example
  • Example#1148 - cubrid_get example
  • Example#1149 - cubrid_insert_id example
  • Example#1150 - cubrid_is_instance example
  • Example#1151 - cubrid_lob_close example
  • Example#1152 - cubrid_lob_export example
  • Example#1153 - cubrid_lob_get example
  • Example#1154 - cubrid_lob_send example
  • Example#1155 - cubrid_lob_size example
  • Example#1156 - cubrid_lob2_bind example
  • Example#1157 - cubrid_lob2_export example
  • Example#1158 - cubrid_lob2_export example
  • Example#1159 - cubrid_lob2_read example 1
  • Example#1160 - cubrid_lob2_read example 2
  • Example#1161 - cubrid_lob2_seek64 example
  • Example#1162 - cubrid_lob2_seek example
  • Example#1163 - cubrid_lob2_write example 1
  • Example#1164 - cubrid_lob2_write example 2
  • Example#1165 - cubrid_lock_read example
  • Example#1166 - cubrid_lock_write example
  • Example#1167 - cubrid_move_cursor example
  • Example#1168 - cubrid_next_result example
  • Example#1169 - cubrid_num_cols example
  • Example#1170 - cubrid_num_rows example
  • Example#1171 - cubrid_pconnect_with_url url without properties example
  • Example#1172 - cubrid_pconnect_with_url url with properties example
  • Example#1173 - cubrid_connect example
  • Example#1174 - cubrid_prepare example
  • Example#1175 - cubrid_put example
  • Example#1176 - cubrid_rollback example
  • Example#1177 - cubrid_schema example
  • Example#1178 - cubrid_seq_drop example
  • Example#1179 - cubrid_seq_insert example
  • Example#1180 - cubrid_seq_put example
  • Example#1181 - cubrid_set_add example
  • Example#1182 - cubrid_get_db_parameter example
  • Example#1183 - cubrid_set_drop example
  • Example#1184 - cubrid_version example
  • Example#1185 - cubrid_affected_rows example
  • Example#1186 - cubrid_client_encoding example
  • Example#1187 - cubrid_close example
  • Example#1188 - cubrid_data_seek example
  • Example#1189 - cubrid_db_name example
  • Example#1190 - cubrid_errno example
  • Example#1191 - cubrid_error example
  • Example#1192 - cubrid_fetch_array example
  • Example#1193 - cubrid_fetch_assoc example
  • Example#1194 - cubrid_fetch_field example
  • Example#1195 - cubrid_fetch_lengths example
  • Example#1196 - cubrid_fetch_object example
  • Example#1197 - cubrid_fetch_row example
  • Example#1198 - cubrid_field_flags example
  • Example#1199 - cubrid_field_len example
  • Example#1200 - cubrid_field_name example
  • Example#1201 - cubrid_field_seek example
  • Example#1202 - cubrid_field_table example
  • Example#1203 - cubrid_field_type example
  • Example#1204 - cubrid_list_dbs example
  • Example#1205 - cubrid_num_fields example
  • Example#1206 - cubrid_ping example
  • Example#1207 - Invalid Query
  • Example#1208 - Valid Query
  • Example#1209 - cubrid_real_escape_string example
  • Example#1210 - cubrid_result example
  • Example#1211 - cubrid_unbuffered_query example
  • Example#1212 - cubrid_load_from_glo example
  • Example#1213 - cubrid_new_glo example
  • Example#1214 - cubrid_save_to_glo example
  • Example#1215 - cubrid_send_glo example
  • Example#1216 - Inserindo um registro num banco de dados dBase
  • Example#1217 - Fechando um banco de dados dBase
  • Example#1218 - Criando um arquivo de banco de dados dBase
  • Example#1219 - Mostrando informações do banco de dados de um arquivo dBase
  • Example#1220 - Listando todos os membros registrados no banco de dados
  • Example#1221 - Exemplo dbase_numfields
  • Example#1222 - Lendo todos os registros de um banco de dados
  • Example#1223 - Abrindo um banco de dados dBase
  • Example#1224 - Limpando um banco de dados dBase
  • Example#1225 - Atualizando um registro no banco de dados
  • Example#1226 - ibase_backup example
  • Example#1227 - ibase_backup example with arguments
  • Example#1228 - Exemplo da ibase_blob_get
  • Example#1229 - Exemplo da ibase_blob_import
  • Example#1230 - Exemplo de ibase_connect
  • Example#1231 - Exemplo de ibase_execute
  • Example#1232 - ibase_fetch_object example
  • Example#1233 - Exemplo da ibase_field_info
  • Example#1234 - Exemplo da ibase_name_result
  • Example#1235 - Exemplo da ibase_num_fields
  • Example#1236 - Exemplo de ibase_query
  • Example#1237 - ibase_restore example
  • Example#1238 - ibase_restore example with arguments
  • Example#1239 - ibase_service_attach example
  • Example#1240 - ibase_service_attach example
  • Example#1241 - ibase_service_attach example using hostname/port syntax
  • Example#1242 - ibase_service_detach example
  • Example#1243 - ibase_set_event_handler example
  • Example#1244 - Retrieving the AUTOCOMMIT value for a connection
  • Example#1245 - Setting the AUTOCOMMIT value for a connection
  • Example#1246 - Binding PHP variables to a prepared statement
  • Example#1247 - Calling stored procedures with IN and OUT parameters
  • Example#1248 - Inserting a binary large object (BLOB) directly from a file
  • Example#1249 - A db2_client_info example
  • Example#1250 - Closing a connection
  • Example#1251 - Retrieving an SQLSTATE value for a failed connection attempt
  • Example#1252 - Retrieving the error message returned by a failed connection attempt
  • Example#1253 - Creating a cataloged connection
  • Example#1254 - Creating an uncataloged connection
  • Example#1255 - Creating a connection with autocommit off by default
  • Example#1256 - i5/OS best performance
  • Example#1257 - Using trusted context
  • Example#1258 - A db2_escape_string example
  • Example#1259 - Creating a table with db2_exec
  • Example#1260 - Executing a SELECT statement with a scrollable cursor
  • Example#1261 - Returning XML data as an SQL ResultSet
  • Example#1262 - Performing a "JOIN" with XML data
  • Example#1263 - Returning SQL data as part of a larger XML document
  • Example#1264 - Preparing and executing an SQL statement with parameter markers
  • Example#1265 - Calling a stored procedure with an OUT parameter
  • Example#1266 - Returning XML data as an SQL ResultSet
  • Example#1267 - Performing a "JOIN" with XML data
  • Example#1268 - Returning SQL data as part of a larger XML document
  • Example#1269 - Iterating through a forward-only cursor
  • Example#1270 - Retrieving specific rows with db2_fetch_array from a scrollable cursor
  • Example#1271 - Iterating through a forward-only cursor
  • Example#1272 - Retrieving specific rows with db2_fetch_assoc from a scrollable cursor
  • Example#1273 - Iterating through a forward-only cursor
  • Example#1274 - Retrieving specific rows with db2_fetch_both from a scrollable cursor
  • Example#1275 - A db2_fetch_object example
  • Example#1276 - Iterating through a result set
  • Example#1277 - i5/OS recommended alternatives to db2_fetch_row/db2_result
  • Example#1278 - Setting and retrieving parameters through a connection resource
  • Example#1279 - A db2_last_insert_id example
  • Example#1280 - Iterating through different types of data
  • Example#1281 - Calling a stored procedure that returns multiple result sets
  • Example#1282 - Retrieving the number of fields in a result set
  • Example#1283 - Closing a persistent connection
  • Example#1284 - A db2_pconnect example
  • Example#1285 - Using trusted context
  • Example#1286 - Preparing and executing an SQL statement with parameter markers
  • Example#1287 - A db2_result example
  • Example#1288 - Rolling back a DELETE statement
  • Example#1289 - A db2_server_info example
  • Example#1290 - Setting one parameter with a connection resource
  • Example#1291 - Setting multiple parameters with a connection resource
  • Example#1292 - Setting multiple parameters with an invalid key
  • Example#1293 - Setting multiple parameters with an invalid value
  • Example#1294 - Setting multiple parameters with a connection resource and the wrong type
  • Example#1295 - Setting multiple parameters with the wrong resource
  • Example#1296 - Putting it all together
  • Example#1297 - i5/OS cursors are read-only
  • Example#1298 - MongoDB\Driver\Manager::__construct basic example
  • Example#1299 - MongoDB\Driver\Manager::__construct basic examples
  • Example#1300 - MongoDB\Driver\Manager::executeBulkWrite example
  • Example#1301 - MongoDB\Driver\Manager::executeCommand with a command returning a single result document
  • Example#1302 - MongoDB\Driver\Manager::executeCommand with a command returning a cursor
  • Example#1303 - Limiting execution time for a command
  • Example#1304 - MongoDB\Driver\Manager::executeQuery example
  • Example#1305 - Limiting execution time for a query
  • Example#1306 - MongoDB\Driver\Manager::getReadConcern example
  • Example#1307 - MongoDB\Driver\Manager::getReadPreference example
  • Example#1308 - MongoDB\Driver\Manager::getServers example
  • Example#1309 - MongoDB\Driver\Manager::getWriteConcern example
  • Example#1310 - Composing MongoDB\Driver\Command to provide a helper to create collections
  • Example#1311 - MongoDB\Driver\Command::__construct example
  • Example#1312 - MongoDB\Driver\Command::__construct example
  • Example#1313 - MongoDB\Driver\Query::__construct example
  • Example#1314 - Mixed write operations are grouped by type
  • Example#1315 - Ordered write operations causing an error
  • Example#1316 - MongoDB\Driver\BulkWrite::__construct example
  • Example#1317 - MongoDB\Driver\BulkWrite::count example
  • Example#1318 - MongoDB\Driver\BulkWrite::delete example
  • Example#1319 - MongoDB\Driver\BulkWrite::insert example
  • Example#1320 - MongoDB\Driver\BulkWrite::update example
  • Example#1321 - Declare an API version on a manager
  • Example#1322 - Declare a strict API version on a manager
  • Example#1323 - MongoDB\Driver\WriteConcern::bsonSerialize with majority write concern
  • Example#1324 - MongoDB\Driver\WriteConcern::bsonSerialize with wtimeout and journal
  • Example#1325 - MongoDB\Driver\WriteConcern::__construct example
  • Example#1326 - MongoDB\Driver\WriteConcern::getJournal example
  • Example#1327 - MongoDB\Driver\WriteConcern::getW example
  • Example#1328 - MongoDB\Driver\WriteConcern::getWtimeout example
  • Example#1329 - MongoDB\Driver\WriteConcern::isDefault example
  • Example#1330 - MongoDB\Driver\ReadPreference::bsonSerialize with primary read preference
  • Example#1331 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and tag sets
  • Example#1332 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and max staleness
  • Example#1333 - MongoDB\Driver\ReadPreference::__construct example
  • Example#1334 - MongoDB\Driver\ReadPreference::getMaxStalenessSeconds example
  • Example#1335 - MongoDB\Driver\ReadPreference::getMode example
  • Example#1336 - MongoDB\Driver\ReadPreference::getModeString example
  • Example#1337 - MongoDB\Driver\ReadPreference::getTagSets example
  • Example#1338 - MongoDB\Driver\ReadConcern::bsonSerialize with empty read concern
  • Example#1339 - MongoDB\Driver\ReadConcern::bsonSerialize with local read concern
  • Example#1340 - MongoDB\Driver\ReadConcern::__construct example
  • Example#1341 - MongoDB\Driver\ReadConcern::getLevel example
  • Example#1342 - MongoDB\Driver\ReadConcern::isDefault example
  • Example#1343 - Reading a result set
  • Example#1344 - Reading a result set for a tailable cursor
  • Example#1345 - MongoDB\Driver\Cursor::getId example
  • Example#1346 - MongoDB\Driver\Cursor::getServer example
  • Example#1347 - MongoDB\Driver\Cursor::isDead example
  • Example#1348 - MongoDB\Driver\Cursor::setTypeMap example
  • Example#1349 - MongoDB\Driver\Cursor::toArray example
  • Example#1350 - MongoDB\Driver\CursorId::__toString example
  • Example#1351 - MongoDB\Driver\Server::getHost example
  • Example#1352 - MongoDB\Driver\Server::getInfo example
  • Example#1353 - MongoDB\Driver\Server::getLatency example
  • Example#1354 - MongoDB\Driver\Server::getPort example
  • Example#1355 - MongoDB\Driver\WriteConcernError::getCode example
  • Example#1356 - MongoDB\Driver\WriteConcernError::getInfo example
  • Example#1357 - MongoDB\Driver\WriteConcernError::getMessage example
  • Example#1358 - MongoDB\Driver\WriteError::getCode example
  • Example#1359 - MongoDB\Driver\WriteError::getIndex example
  • Example#1360 - MongoDB\Driver\WriteError::getMessage example
  • Example#1361 - MongoDB\Driver\WriteResult::getDeletedCount example
  • Example#1362 - MongoDB\Driver\WriteResult::getInsertedCount example
  • Example#1363 - MongoDB\Driver\WriteResult::getMatchedCount example
  • Example#1364 - MongoDB\Driver\WriteResult::getModifiedCount example
  • Example#1365 - MongoDB\Driver\WriteResult::getServer example
  • Example#1366 - MongoDB\Driver\WriteResult::getUpsertedCount example
  • Example#1367 - MongoDB\Driver\WriteResult::getUpsertedIds example
  • Example#1368 - MongoDB\Driver\WriteResult::getWriteConcernError example
  • Example#1369 - MongoDB\Driver\WriteResult::getWriteErrors with a single error
  • Example#1370 - MongoDB\Driver\WriteResult::getWriteErrors with multiple errors
  • Example#1371 - MongoDB\Driver\WriteResult::isAcknowledged with acknowledged write concern
  • Example#1372 - MongoDB\Driver\WriteResult::isAcknowledged with unacknowledged write concern
  • Example#1373 - MongoDB\BSON\fromJSON example
  • Example#1374 - MongoDB\BSON\fromPHP example
  • Example#1375 - MongoDB\BSON\toCanonicalExtendedJSON example
  • Example#1376 - MongoDB\BSON\toJSON example
  • Example#1377 - MongoDB\BSON\toPHP example
  • Example#1378 - MongoDB\BSON\toRelaxedExtendedJSON example
  • Example#1379 - MongoDB\BSON\Document::toCanonicalExtendedJSON example
  • Example#1380 - MongoDB\BSON\Document::toRelaxedExtendedJSON example
  • Example#1381 - MongoDB\BSON\Binary::__construct example
  • Example#1382 - MongoDB\BSON\Binary::getData example
  • Example#1383 - MongoDB\BSON\Binary::getType example
  • Example#1384 - MongoDB\BSON\Binary::__toString example
  • Example#1385 - MongoDB\BSON\Decimal128::__construct example
  • Example#1386 - MongoDB\BSON\Decimal128::__toString example
  • Example#1387 - MongoDB\BSON\Javascript::__construct example
  • Example#1388 - MongoDB\BSON\Javascript::getCode example
  • Example#1389 - MongoDB\BSON\Javascript::getScope example
  • Example#1390 - MongoDB\BSON\Javascript::__toString example
  • Example#1391 - MongoDB\BSON\MaxKey::__construct example
  • Example#1392 - MongoDB\BSON\MinKey::__construct example
  • Example#1393 - MongoDB\BSON\ObjectId::__construct example
  • Example#1394 - MongoDB\BSON\ObjectId::getTimestamp example
  • Example#1395 - MongoDB\BSON\ObjectId::__toString example
  • Example#1396 - MongoDB\BSON\Regex::__construct example
  • Example#1397 - MongoDB\BSON\Regex::getFlags example
  • Example#1398 - MongoDB\BSON\Regex::getPattern example
  • Example#1399 - MongoDB\BSON\Regex::__toString example
  • Example#1400 - MongoDB\BSON\Timestamp::__construct example
  • Example#1401 - MongoDB\BSON\Timestamp::__toString example
  • Example#1402 - MongoDB\BSON\UTCDateTime::__construct example
  • Example#1403 - MongoDB\BSON\UTCDatetime::toDateTime example
  • Example#1404 - MongoDB\BSON\UTCDateTime::__toString example
  • Example#1405 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for root document
  • Example#1406 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for root document
  • Example#1407 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for document field
  • Example#1408 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for document field
  • Example#1409 - MongoDB\BSON\Unserializable::bsonUnserialize example
  • Example#1410 - MongoDB\BSON\Int64::__toString example
  • Example#1411 - MongoDB\Driver\Exception\WriteException::getWriteResult example
  • Example#1412 - Comparing the MySQL APIs
  • Example#1413 - Comparing prepared statements
  • Example#1414 - Configure commands for using mysqlnd or libmysqlclient
  • Example#1415 - Unbuffered query example: mysqli
  • Example#1416 - Unbuffered query example: pdo_mysql
  • Example#1417 - Problems with setting the character set with SQL
  • Example#1418 - Setting the character set example: mysqli
  • Example#1419 - Setting the character set example: pdo_mysql
  • Example#1420 - Migração fácil da antiga extensão mysql
  • Example#1421 - Interface orientada a objeto e procedural
  • Example#1422 - Estilo de código ruim
  • Example#1423 - Significado especial de localhost
  • Example#1424 - Padrões de configuração
  • Example#1425 - Executando consultas
  • Example#1426 - Navegando através de resultados em buffer
  • Example#1427 - Navegando através de resultados sem buffer
  • Example#1428 - Protocolo de texto retorna strings por padrão
  • Example#1429 - Tipos de dados nativos com mysqlnd e opção de conexão
  • Example#1430 - Instrução preparada
  • Example#1431 - INSERT preparado uma vez, executado múltiplas vezes
  • Example#1432 - Menos idas e voltas usando o multi-INSERT do SQL
  • Example#1433 - Tipos nativos de dados
  • Example#1434 - Vinculação de variável de saída
  • Example#1435 - Usando mysqli_result para receber resultados
  • Example#1436 - Conjunto de resultados com buffer para leitura flexível
  • Example#1437 - Chamando um procedimento armazenado
  • Example#1438 - Uso de variáveis de sessão
  • Example#1439 - Recebendo resultados de procedimentos armazenados
  • Example#1440 - Procedimentos Armazenados e Instruções Preparadas
  • Example#1441 - Procedimentos Armazenados e Instruções Preparadas usando a API bind
  • Example#1442 - Instruções Múltiplas
  • Example#1443 - Injeção SQL
  • Example#1444 - Configurando o modo autocommit com SQL e através da API
  • Example#1445 - Enviando e desfazendo transações
  • Example#1446 - Acessando metadados do conjunto de resultados
  • Example#1447 - Metadados de instruções preparadas
  • Example#1448 - Exemplo de $mysqli->affected_rows
  • Example#1449 - Exemplo de mysqli::autocommit
  • Example#1450 - mysqli::begin_transaction exemplo
  • Example#1451 - Exemplo de mysqli::change_user
  • Example#1452 - Exemplo de mysqli::character_set_name
  • Example#1453 - Exemplo de mysqli::close
  • Example#1454 - Exemplo de $mysqli->connect_errno
  • Example#1455 - Exemplo de $mysqli->connect_error
  • Example#1456 - Exemplo d emysqli::__construct
  • Example#1457 - Estendendo a classe mysqli
  • Example#1458 - Tratamento manual de erros
  • Example#1459 - Gerando um Aqruivo de Rastreamento
  • Example#1460 - Exemplo de $mysqli->errno
  • Example#1461 - $mysqli->error_list exemplo
  • Example#1462 - Exemplo de $mysqli->error
  • Example#1463 - mysqli::execute_query exemplo
  • Example#1464 - Exemplo de $mysqli->field_count
  • Example#1465 - mysqli::get_charset exemplo
  • Example#1466 - mysqli_get_client_info
  • Example#1467 - mysqli_get_client_version
  • Example#1468 - mysqli_get_connection_stats exemplo
  • Example#1469 - Exemplo de $mysqli->host_info
  • Example#1470 - Exemplo de $mysqli->protocol_version
  • Example#1471 - Exemplo de $mysqli->server_info
  • Example#1472 - Exemplo de $mysqli->server_version
  • Example#1473 - Exemplo de $mysqli->info
  • Example#1474 - Exemplo de $mysqli->insert_id
  • Example#1475 - Exemplo de mysqli::kill
  • Example#1476 - Exemplo de mysqli::multi_query
  • Example#1477 - mysqli::ping exemplo
  • Example#1478 - Um exemplo de mysqli_poll
  • Example#1479 - mysqli::prepare exemplo
  • Example#1480 - mysqli::query exemplo
  • Example#1481 - mysqli::real_connect exemplo
  • Example#1482 - mysqli::real_escape_string exemplo
  • Example#1483 - mysqli::select_db exemplo
  • Example#1484 - mysqli::set_charset exemplo
  • Example#1485 - $mysqli->sqlstate example
  • Example#1486 - mysqli::stat exemplo
  • Example#1487 - $mysqli->thread_id exemplo
  • Example#1488 - mysqli::use_result exemplo
  • Example#1489 - $mysqli->warning_count exemplo
  • Example#1490 - Exemplo de mysqli_stmt_affected_rows
  • Example#1491 - Exemplo de mysqli_stmt::bind_param
  • Example#1492 - Usando ... para fornecer argumentos
  • Example#1493 - Estilo orientado a objetos
  • Example#1494 - Estilo procedural
  • Example#1495 - Estilo orientado a objetos
  • Example#1496 - Estilo procedural
  • Example#1497 - Estilo orientado a objetos
  • Example#1498 - Estilo procedural
  • Example#1499 - Estilo orientado a objetos
  • Example#1500 - Estilo procedural
  • Example#1501 - Estilo orientado a objetos
  • Example#1502 - Estilo procedural
  • Example#1503 - Executa a instrução preparada com variáveis vinculadas
  • Example#1504 - Executa uma isntrução preparada com um array de valores
  • Example#1505 - Estilo orientado a objetos
  • Example#1506 - Estilo procedural
  • Example#1507 - Estilo orientado a objetos
  • Example#1508 - Estilo procedural
  • Example#1509 - Estilo orientado a objetos
  • Example#1510 - Estilo procedural
  • Example#1511 - Estilo orientado a objetos
  • Example#1512 - Estilo procedural
  • Example#1513 - Estilo orientado a objetos
  • Example#1514 - Estilo procedural
  • Example#1515 - Exemplo de mysqli_stmt::prepare
  • Example#1516 - Estilo orientado a objetos
  • Example#1517 - Estilo procedural
  • Example#1518 - Estilo orientado a objetos
  • Example#1519 - Estilo orientado a objetos
  • Example#1520 - Estilo procedural
  • Example#1521 - Estilo orientado a objetos
  • Example#1522 - Estilo procedural
  • Example#1523 - Criação de um objeto mysqli_result
  • Example#1524 - Estilo orientado a objetos
  • Example#1525 - Estilo procedural
  • Example#1526 - mysqli::data_seek example
  • Example#1527 - Ajustando o ponteiro de resultado na iteração
  • Example#1528 - Exemplo de mysqli_result::fetch_all
  • Example#1529 - Exemplo de mysqli_result::fetch_array
  • Example#1530 - Exemplo de mysqli_result::fetch_assoc
  • Example#1531 - Comparação de mysqli_result iterator e uso de mysqli_result::fetch_assoc
  • Example#1532 - Exemplo de mysqli_result::fetch_column
  • Example#1533 - Estilo orientado a objetos
  • Example#1534 - Estilo procedural
  • Example#1535 - Estilo orientado a objetos
  • Example#1536 - Estilo procedural
  • Example#1537 - Estilo orientado a objetos
  • Example#1538 - Estilo procedural
  • Example#1539 - Exemplo de mysqli_result::fetch_object
  • Example#1540 - Exemplo de mysqli_result::fetch_row
  • Example#1541 - Estilo orientado a objetos
  • Example#1542 - Estilo procedural
  • Example#1543 - Estilo orientado a objetos
  • Example#1544 - Estilo procedural
  • Example#1545 - Estilo orientado a objetos
  • Example#1546 - Estilo procedural
  • Example#1547 - Estilo orientado a objetos
  • Example#1548 - Estilo procedural
  • Example#1549 - Estilo orientado a objetos
  • Example#1550 - Estilo procedural
  • Example#1551 - Relatório de erros, exceto erros de índice ruim
  • Example#1552 - mysqli_get_client_stats exemplo
  • Example#1553 - Connecting to a MySQL Server
  • Example#1554 - Creating a Schema and Collection on the MySQL Server
  • Example#1555 - Storing and Retrieving Data
  • Example#1556 - Fetching and Iterating Multiple Documents
  • Example#1557 - mysql_xdevapi\Expression example
  • Example#1558 - URI examples
  • Example#1559 - mysql_xdevapi\getSession example
  • Example#1560 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1561 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1562 - mysql_xdevapi\Client::__construct example
  • Example#1563 - mysql_xdevapi\Collection::add example
  • Example#1564 - mysql_xdevapi\Collection::addOrReplaceOne example
  • Example#1565 - mysql_xdevapi\Collection::getOne example
  • Example#1566 - mysql_xdevapi\Collection::count example
  • Example#1567 - mysql_xdevapi\Collection::createIndex example
  • Example#1568 - mysql_xdevapi\Collection::dropIndex example
  • Example#1569 - mysql_xdevapi\Collection::existsInDatabase example
  • Example#1570 - mysql_xdevapi\Collection::find example
  • Example#1571 - mysql_xdevapi\Collection::getName example
  • Example#1572 - mysql_xdevapi\Collection::getOne example
  • Example#1573 - mysql_xdevapi\Collection::getSchema example
  • Example#1574 - mysql_xdevapi\Collection::getSession example
  • Example#1575 - mysql_xdevapi\Collection::modify example
  • Example#1576 - mysql_xdevapi\Collection::remove example
  • Example#1577 - mysql_xdevapi\Collection::removeOne example
  • Example#1578 - mysql_xdevapi\Collection::replaceOne example
  • Example#1579 - mysql_xdevapi\CollectionAdd::__construct example
  • Example#1580 - mysql_xdevapi\CollectionAdd::execute example
  • Example#1581 - mysql_xdevapi\CollectionFind::bind example
  • Example#1582 - CollectionFind example
  • Example#1583 - CollectionFind example
  • Example#1584 - mysql_xdevapi\CollectionFind::fields example
  • Example#1585 - mysql_xdevapi\CollectionFind::groupBy example
  • Example#1586 - mysql_xdevapi\CollectionFind::having example
  • Example#1587 - mysql_xdevapi\CollectionFind::limit example
  • Example#1588 - mysql_xdevapi\CollectionFind::lockExclusive example
  • Example#1589 - mysql_xdevapi\CollectionFind::lockShared example
  • Example#1590 - mysql_xdevapi\CollectionFind::offset example
  • Example#1591 - mysql_xdevapi\CollectionFind::sort example
  • Example#1592 - mysql_xdevapi\CollectionModify::arrayAppend example
  • Example#1593 - mysql_xdevapi\CollectionModify::arrayInsert example
  • Example#1594 - mysql_xdevapi\CollectionModify::bind example
  • Example#1595 - mysql_xdevapi\CollectionModify::__construct example
  • Example#1596 - mysql_xdevapi\CollectionModify::execute example
  • Example#1597 - mysql_xdevapi\CollectionModify::limit example
  • Example#1598 - mysql_xdevapi\CollectionModify::patch example
  • Example#1599 - mysql_xdevapi\CollectionModify::replace example
  • Example#1600 - mysql_xdevapi\CollectionModify::set example
  • Example#1601 - mysql_xdevapi\CollectionModify::skip example
  • Example#1602 - mysql_xdevapi\CollectionModify::sort example
  • Example#1603 - mysql_xdevapi\CollectionModify::unset example
  • Example#1604 - mysql_xdevapi\CollectionRemove::bind example
  • Example#1605 - mysql_xdevapi\Collection::remove example
  • Example#1606 - mysql_xdevapi\CollectionRemove::execute example
  • Example#1607 - mysql_xdevapi\CollectionRemove::limit example
  • Example#1608 - mysql_xdevapi\CollectionRemove::sort example
  • Example#1609 - mysql_xdevapi\ColumnResult::__construct example
  • Example#1610 - mysql_xdevapi\ColumnResult::getCharacterSetName example
  • Example#1611 - mysql_xdevapi\ColumnResult::getCollationName example
  • Example#1612 - mysql_xdevapi\ColumnResult::getColumnLabel example
  • Example#1613 - mysql_xdevapi\ColumnResult::getColumnName example
  • Example#1614 - mysql_xdevapi\ColumnResult::getFractionalDigits example
  • Example#1615 - mysql_xdevapi\ColumnResult::getLength example
  • Example#1616 - mysql_xdevapi\ColumnResult::getSchemaName example
  • Example#1617 - mysql_xdevapi\ColumnResult::getTableLabel example
  • Example#1618 - mysql_xdevapi\ColumnResult::getTableName example
  • Example#1619 - mysql_xdevapi\ColumnResult::getType example
  • Example#1620 - mysql_xdevapi\ColumnResult::isNumberSigned example
  • Example#1621 - mysql_xdevapi\ColumnResult::isPadded example
  • Example#1622 - mysql_xdevapi\CrudOperationBindable::bind example
  • Example#1623 - mysql_xdevapi\CrudOperationLimitable::limit example
  • Example#1624 - mysql_xdevapi\CrudOperationSkippable::skip example
  • Example#1625 - mysql_xdevapi\CrudOperationSortable::sort example
  • Example#1626 - mysql_xdevapi\DatabaseObject::existsInDatabase example
  • Example#1627 - mysql_xdevapi\DatabaseObject::getName example
  • Example#1628 - mysql_xdevapi\DatabaseObject::getSession example
  • Example#1629 - A DocResult example
  • Example#1630 - mysql_xdevapi\DocResult::fetchAll example
  • Example#1631 - mysql_xdevapi\DocResult::fetchOne example
  • Example#1632 - mysql_xdevapi\DocResult::getWarnings example
  • Example#1633 - mysql_xdevapi\DocResult::getWarningsCount example
  • Example#1634 - execute() examples
  • Example#1635 - mysql_xdevapi\ExecutionStatus::__construct example
  • Example#1636 - mysql_xdevapi\Expression::__construct example
  • Example#1637 - mysql_xdevapi\Result::__construct example
  • Example#1638 - mysql_xdevapi\Result::getAffectedItemsCount example
  • Example#1639 - mysql_xdevapi\Result::getAutoIncrementValue example
  • Example#1640 - mysql_xdevapi\Result::getGeneratedIds example
  • Example#1641 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1642 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1643 - mysql_xdevapi\RowResult::__construct example
  • Example#1644 - mysql_xdevapi\RowResult::fetchAll example
  • Example#1645 - mysql_xdevapi\RowResult::fetchOne example
  • Example#1646 - mysql_xdevapi\RowResult::getColumnsCount example
  • Example#1647 - mysql_xdevapi\RowResult::getColumnNames example
  • Example#1648 - mysql_xdevapi\RowResult::getColumns example
  • Example#1649 - mysql_xdevapi\RowResult::getWarnings example
  • Example#1650 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#1651 - Schema::__construct example
  • Example#1652 - Schema::createCollection example
  • Example#1653 - Schema::createCollection validate parameter example
  • Example#1654 - Schema::dropCollection example
  • Example#1655 - Schema::existsInDatabase example
  • Example#1656 - Schema::getCollection example
  • Example#1657 - Schema::getCollectionAsTable example
  • Example#1658 - mysql_xdevapi\Schema::getCollections example
  • Example#1659 - mysql_xdevapi\Schema::getName example
  • Example#1660 - mysql_xdevapi\Schema::getSession example
  • Example#1661 - mysql_xdevapi\Schema::getTable example
  • Example#1662 - mysql_xdevapi\Schema::getTables example
  • Example#1663 - mysql_xdevapi\Session::getSchema example
  • Example#1664 - mysql_xdevapi\Session::close example
  • Example#1665 - mysql_xdevapi\Session::commit example
  • Example#1666 - mysql_xdevapi\Session::__construct example
  • Example#1667 - mysql_xdevapi\Session::createSchema example
  • Example#1668 - mysql_xdevapi\Session::dropSchema example
  • Example#1669 - mysql_xdevapi\Session::generateUuid example
  • Example#1670 - mysql_xdevapi\Session::getSchema example
  • Example#1671 - mysql_xdevapi\Session::getSchema example
  • Example#1672 - mysql_xdevapi\Session::getSchemas example
  • Example#1673 - mysql_xdevapi\Session::getServerVersion example
  • Example#1674 - mysql_xdevapi\Session::listClients example
  • Example#1675 - mysql_xdevapi\Session::quoteName example
  • Example#1676 - mysql_xdevapi\Session::releaseSavepoint example
  • Example#1677 - mysql_xdevapi\Session::rollback example
  • Example#1678 - mysql_xdevapi\Session::rollbackTo example
  • Example#1679 - mysql_xdevapi\Session::setSavepoint example
  • Example#1680 - mysql_xdevapi\Session::sql example
  • Example#1681 - mysql_xdevapi\Session::startTransaction example
  • Example#1682 - mysql_xdevapi\SqlStatement::bind example
  • Example#1683 - mysql_xdevapi\SqlStatement::__construct example
  • Example#1684 - mysql_xdevapi\SqlStatement::execute example
  • Example#1685 - mysql_xdevapi\SqlStatement::getNextResult example
  • Example#1686 - mysql_xdevapi\SqlStatement::getResult example
  • Example#1687 - mysql_xdevapi\SqlStatement::hasMoreResults example
  • Example#1688 - mysql_xdevapi\SqlStatementResult::__construct example
  • Example#1689 - mysql_xdevapi\SqlStatementResult::fetchAll example
  • Example#1690 - mysql_xdevapi\SqlStatementResult::fetchOne example
  • Example#1691 - mysql_xdevapi\SqlStatementResult::getAffectedItemsCount example
  • Example#1692 - mysql_xdevapi\SqlStatementResult::getColumnsCount example
  • Example#1693 - mysql_xdevapi\SqlStatementResult::getColumnNames example
  • Example#1694 - mysql_xdevapi\SqlStatementResult::getColumns example
  • Example#1695 - mysql_xdevapi\SqlStatementResult::getGeneratedIds example
  • Example#1696 - mysql_xdevapi\SqlStatementResult::getLastInsertId example
  • Example#1697 - mysql_xdevapi\SqlStatementResult::getWarnings example
  • Example#1698 - mysql_xdevapi\SqlStatementResult::getWarningsCount example
  • Example#1699 - mysql_xdevapi\SqlStatementResult::hasData example
  • Example#1700 - mysql_xdevapi\SqlStatementResult::nextResult example
  • Example#1701 - mysql_xdevapi\Statement::__construct example
  • Example#1702 - mysql_xdevapi\Statement::getNextResult example
  • Example#1703 - mysql_xdevapi\Statement::getResult example
  • Example#1704 - mysql_xdevapi\Statement::hasMoreResults example
  • Example#1705 - mysql_xdevapi\Table::__construct example
  • Example#1706 - mysql_xdevapi\Table::count example
  • Example#1707 - mysql_xdevapi\Table::delete example
  • Example#1708 - mysql_xdevapi\Table::existsInDatabase example
  • Example#1709 - mysql_xdevapi\Table::getName example
  • Example#1710 - mysql_xdevapi\Table::getSchema example
  • Example#1711 - mysql_xdevapi\Table::getSession example
  • Example#1712 - mysql_xdevapi\Table::insert example
  • Example#1713 - mysql_xdevapi\Table::isView example
  • Example#1714 - mysql_xdevapi\Table::count example
  • Example#1715 - mysql_xdevapi\Table::update example
  • Example#1716 - mysql_xdevapi\TableDelete::bind example
  • Example#1717 - mysql_xdevapi\TableDelete::__construct example
  • Example#1718 - mysql_xdevapi\TableDelete::execute example
  • Example#1719 - mysql_xdevapi\TableDelete::limit example
  • Example#1720 - mysql_xdevapi\TableDelete::orderBy example
  • Example#1721 - mysql_xdevapi\TableDelete::where example
  • Example#1722 - mysql_xdevapi\TableInsert::__construct example
  • Example#1723 - mysql_xdevapi\TableInsert::execute example
  • Example#1724 - mysql_xdevapi\TableInsert::values example
  • Example#1725 - mysql_xdevapi\TableSelect::bind example
  • Example#1726 - mysql_xdevapi\TableSelect::__construct example
  • Example#1727 - mysql_xdevapi\TableSelect::execute example
  • Example#1728 - mysql_xdevapi\TableSelect::groupBy example
  • Example#1729 - mysql_xdevapi\TableSelect::having example
  • Example#1730 - mysql_xdevapi\TableSelect::limit example
  • Example#1731 - mysql_xdevapi\TableSelect::lockExclusive example
  • Example#1732 - mysql_xdevapi\TableSelect::lockShared example
  • Example#1733 - mysql_xdevapi\TableSelect::offset example
  • Example#1734 - mysql_xdevapi\TableSelect::orderBy example
  • Example#1735 - mysql_xdevapi\TableSelect::where example
  • Example#1736 - mysql_xdevapi\TableUpdate::bind example
  • Example#1737 - mysql_xdevapi\TableUpdate::__construct example
  • Example#1738 - mysql_xdevapi\TableUpdate::execute example
  • Example#1739 - mysql_xdevapi\TableUpdate::limit example
  • Example#1740 - mysql_xdevapi\TableUpdate::orderby example
  • Example#1741 - mysql_xdevapi\TableUpdate::set example
  • Example#1742 - mysql_xdevapi\TableUpdate::where example
  • Example#1743 - mysql_xdevapi\Warning::__construct example
  • Example#1744 - Exemplo de uso da extensão MySQL
  • Example#1745 - Exemplo mysql_affected_rows
  • Example#1746 - Exemplo de mysql_affected_rows usando transações
  • Example#1747 - mysql_client_encoding example
  • Example#1748 - Exemplo mysql_close
  • Example#1749 - mysql_connect example
  • Example#1750 - mysql_connect example using hostname:port syntax
  • Example#1751 - mysql_connect example using ":/path/to/socket" syntax
  • Example#1752 - Exemplo alternativo de mysql_create_db
  • Example#1753 - Exemplo mysql_data_seek
  • Example#1754 - Exemplo mysql_db_name
  • Example#1755 - mysql_db_query alternative example
  • Example#1756 - Exemplo alternativo de mysql_drop_db
  • Example#1757 - Exemplo mysql_errno
  • Example#1758 - Exemplo mysql_error
  • Example#1759 - Exemplo de mysql_escape_string
  • Example#1760 - Query with aliased duplicate field names
  • Example#1761 - mysql_fetch_array with MYSQL_NUM
  • Example#1762 - mysql_fetch_array with MYSQL_ASSOC
  • Example#1763 - mysql_fetch_array with MYSQL_BOTH
  • Example#1764 - Um exemplo expandido de mysql_fetch_assoc
  • Example#1765 - mysql_fetch_field example
  • Example#1766 - Exemplo mysql_fetch_lengths
  • Example#1767 - Exemplo mysql_fetch_object
  • Example#1768 - Exemplo mysql_fetch_object
  • Example#1769 - Obtendo uma linha com mysql_fetch_row
  • Example#1770 - A mysql_field_flags example
  • Example#1771 - mysql_field_len example
  • Example#1772 - Exemplo mysql_field_name
  • Example#1773 - Exemplo mysql_field_table
  • Example#1774 - Exemplo mysql_field_type
  • Example#1775 - A mysql_free_result example
  • Example#1776 - Exemplo mysql_get_client_info
  • Example#1777 - Exemplo mysql_get_host_info
  • Example#1778 - Exemplo mysql_get_proto_info
  • Example#1779 - Exemplo mysql_get_server_info
  • Example#1780 - Comandos MySQL relevantes
  • Example#1781 - Exemplo mysql_insert_id
  • Example#1782 - Exemplo mysql_list_dbs
  • Example#1783 - Alternativa para a obsoleta mysql_list_fields
  • Example#1784 - Exemplo mysql_list_processes
  • Example#1785 - mysql_list_tables alternative example
  • Example#1786 - Exemplo mysql_num_fields
  • Example#1787 - Exemplo mysql_num_rows
  • Example#1788 - Exemplo mysql_ping
  • Example#1789 - Invalid Query
  • Example#1790 - Valid Query
  • Example#1791 - Simple mysql_real_escape_string example
  • Example#1792 - mysql_real_escape_string requires a connection example
  • Example#1793 - An example SQL Injection Attack
  • Example#1794 - mysql_result example
  • Example#1795 - mysql_select_db example
  • Example#1796 - mysql_stat example
  • Example#1797 - Alternative mysql_stat example
  • Example#1798 - mysql_tablename example
  • Example#1799 - mysql_thread_id example
  • Example#1800 - Consulta básica
  • Example#1801 - Inserindo com variáveis vinculadas
  • Example#1802 - Vinculando em cláusula WHERE de uma consulta
  • Example#1803 - Inserindo e recebendo um CLOB
  • Example#1804 - Usando uma função armazenada PL/SQL
  • Example#1805 - Usando um procedimento armazenado PL/SQL
  • Example#1806 - Chamando uma função PL/SQL que retorna um REF CURSOR
  • Example#1807 -
  • Example#1808 - user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace
  • Example#1809 - oci_bind_array_by_name example
  • Example#1810 - Inserting data with oci_bind_by_name
  • Example#1811 - Binding once for multiple executions
  • Example#1812 - Binding with a foreach loop
  • Example#1813 - Binding in a WHERE clause
  • Example#1814 - Binding with a LIKE clause
  • Example#1815 - Binding with REGEXP_LIKE
  • Example#1816 - Binding Multiple Values in an IN Clause
  • Example#1817 - Binding a ROWID returned by a query
  • Example#1818 - Binding a ROWID on INSERT
  • Example#1819 - Binding for a PL/SQL stored function
  • Example#1820 - Binding parameters for a PL/SQL stored procedure
  • Example#1821 - Binding a CLOB column
  • Example#1822 - Binding a PL/SQL BOOLEAN
  • Example#1823 - oci_client_version example
  • Example#1824 - Closing a connection
  • Example#1825 - Database connections are not closed until all references are closed
  • Example#1826 - Closing a connection opened more than once
  • Example#1827 - Connections are closed when variables go out of scope
  • Example#1828 - oci_commit example
  • Example#1829 - Basic oci_connect using Easy Connect syntax
  • Example#1830 - Basic oci_connect using a Network Connect name
  • Example#1831 - oci_connect with an explicit character set
  • Example#1832 - Using multiple calls to oci_connect
  • Example#1833 - oci_define_by_name example
  • Example#1834 - oci_define_by_name with case sensitive column names
  • Example#1835 - oci_define_by_name with LOB columns
  • Example#1836 - oci_define_by_name with an explicit type
  • Example#1837 - Displaying the Oracle error message after a connection error
  • Example#1838 - Displaying the Oracle error message after a parsing error
  • Example#1839 - Displaying the Oracle error message, the problematic statement, and the position of the problem of an execution error
  • Example#1840 - oci_execute for queries
  • Example#1841 - oci_execute without specifying a mode example
  • Example#1842 - oci_execute with OCI_NO_AUTO_COMMIT example
  • Example#1843 - oci_execute with different commit modes example
  • Example#1844 - oci_execute with OCI_DESCRIBE_ONLY example
  • Example#1845 - oci_fetch_all example
  • Example#1846 - oci_fetch_all example with OCI_FETCHSTATEMENT_BY_ROW
  • Example#1847 - oci_fetch_all with OCI_NUM
  • Example#1848 - oci_fetch_array with OCI_BOTH
  • Example#1849 - oci_fetch_array with OCI_NUM
  • Example#1850 - oci_fetch_array with OCI_ASSOC
  • Example#1851 - oci_fetch_array with OCI_RETURN_NULLS
  • Example#1852 - oci_fetch_array with OCI_RETURN_LOBS
  • Example#1853 - oci_fetch_array with case sensitive column names
  • Example#1854 - oci_fetch_array with columns having duplicate names
  • Example#1855 - oci_fetch_array with DATE columns
  • Example#1856 - oci_fetch_array with REF CURSOR
  • Example#1857 - Pagination with oci_fetch_array using a LIMIT-like query
  • Example#1858 - oci_fetch_array with Oracle Database Implicit Result Sets
  • Example#1859 - oci_fetch_assoc Example
  • Example#1860 - oci_fetch_object example
  • Example#1861 - oci_fetch_object with case sensitive column names
  • Example#1862 - oci_fetch_object with LOBs
  • Example#1863 - oci_fetch_row Example
  • Example#1864 - oci_fetch with defined variables
  • Example#1865 - oci_fetch with oci_result
  • Example#1866 - oci_field_name example
  • Example#1867 - oci_field_name example
  • Example#1868 - oci_field_precision Example
  • Example#1869 - oci_field_scale Example
  • Example#1870 - oci_field_size example
  • Example#1871 - oci_field_type_raw Example
  • Example#1872 - oci_field_type example
  • Example#1873 - Fetching Implicit Result Sets in a loop
  • Example#1874 - Getting child statement handles individually
  • Example#1875 - Explicitly setting the Prefetch Count
  • Example#1876 - Implicit Result Set example without using oci_get_implicit_resultset
  • Example#1877 - oci_new_connect example
  • Example#1878 - Binding a REF CURSOR in an Oracle stored procedure call
  • Example#1879 - oci_new_descriptor example
  • Example#1880 - oci_new_descriptor example
  • Example#1881 - oci_num_fields example
  • Example#1882 - oci_num_rows example
  • Example#1883 - oci_parse example for SQL statements
  • Example#1884 - oci_parse example for PL/SQL statements
  • Example#1885 - oci_password_change example changing the password of an already connected user
  • Example#1886 - oci_password_change example of connecting and changing the password in one step
  • Example#1887 - Basic oci_pconnect Example using Easy Connect syntax
  • Example#1888 - oci_fetch with oci_result
  • Example#1889 - oci_rollback example
  • Example#1890 - Rolling back to a SAVEPOINT example
  • Example#1891 - oci_server_version example
  • Example#1892 - Setting the action
  • Example#1893 - Setting the timeout
  • Example#1894 - Setting the client identifier to the application user
  • Example#1895 - Setting the client information
  • Example#1896 - Setting the DBOP
  • Example#1897 - Two scripts can use different versions of myfunc() at the same time
  • Example#1898 - Setting the module name
  • Example#1899 - Changing the LOB prefetch value for a query
  • Example#1900 - Changing the default prefetch value for a query
  • Example#1901 - Changing the default prefetch for a REF CURSOR fetch
  • Example#1902 - Setting the prefetch value when passing a REF CURSOR back to Oracle
  • Example#1903 - oci_statement_type example
  • Example#1904 - Exemplo geral da extensão PostgreSQL
  • Example#1905 - Exemplo de funções definidas pelo usuário no PostgreSQL
  • Example#1906 - pg_affected_rows example
  • Example#1907 - pg_cancel_query example
  • Example#1908 - pg_client_encoding example
  • Example#1909 - pg_close example
  • Example#1910 - Using pg_connect
  • Example#1911 - pg_connection_busy example
  • Example#1912 - pg_connection_reset example
  • Example#1913 - pg_connection_status example
  • Example#1914 - pg_convert example
  • Example#1915 - pg_copy_from example
  • Example#1916 - pg_copy_to example
  • Example#1917 - pg_dbname example
  • Example#1918 - pg_delete example
  • Example#1919 - pg_end_copy example
  • Example#1920 - pg_escape_bytea example
  • Example#1921 - pg_escape_identifier example
  • Example#1922 - pg_escape_literal example
  • Example#1923 - pg_escape_string example
  • Example#1924 - Using pg_execute
  • Example#1925 - pg_fetch_all_columns example
  • Example#1926 - PostgreSQL fetch all
  • Example#1927 - pg_fetch_array example
  • Example#1928 - pg_fetch_assoc example
  • Example#1929 - pg_fetch_object example
  • Example#1930 - pg_fetch_result example
  • Example#1931 - pg_fetch_row example
  • Example#1932 - pg_field_is_null example
  • Example#1933 - Getting information about fields
  • Example#1934 - Getting information about fields
  • Example#1935 - Getting information about fields
  • Example#1936 - Getting information about fields
  • Example#1937 - Getting table information about a field
  • Example#1938 - Getting information about fields
  • Example#1939 - Getting information about fields
  • Example#1940 - pg_free_result example
  • Example#1941 - PostgreSQL NOTIFY message
  • Example#1942 - PostgreSQL backend PID
  • Example#1943 - pg_get_result example
  • Example#1944 - pg_host example
  • Example#1945 - pg_insert example
  • Example#1946 - pg_last_error example
  • Example#1947 - pg_last_notice example
  • Example#1948 - pg_last_oid example
  • Example#1949 - pg_lo_close example
  • Example#1950 - pg_lo_create example
  • Example#1951 - pg_lo_export example
  • Example#1952 - pg_lo_import example
  • Example#1953 - pg_lo_open example
  • Example#1954 - pg_lo_read_all example
  • Example#1955 - pg_lo_read example
  • Example#1956 - pg_lo_seek example
  • Example#1957 - pg_lo_tell example
  • Example#1958 - pg_lo_truncate example
  • Example#1959 - pg_lo_unlink example
  • Example#1960 - pg_lo_write example
  • Example#1961 - Getting table metadata
  • Example#1962 - pg_num_fields example
  • Example#1963 - pg_num_rows example
  • Example#1964 - pg_options example
  • Example#1965 - pg_parameter_status example
  • Example#1966 - Using pg_pconnect
  • Example#1967 - pg_ping example
  • Example#1968 - pg_port example
  • Example#1969 - Using pg_prepare
  • Example#1970 - pg_put_line example
  • Example#1971 - Using pg_query_params
  • Example#1972 - pg_query example
  • Example#1973 - Using pg_query with multiple statements
  • Example#1974 - pg_result_error_field example
  • Example#1975 - pg_result_error example
  • Example#1976 - pg_result_seek example
  • Example#1977 - pg_result_status example
  • Example#1978 - pg_select example
  • Example#1979 - Using pg_send_execute
  • Example#1980 - Using pg_send_prepare
  • Example#1981 - Using pg_send_query_params
  • Example#1982 - pg_send_query example
  • Example#1983 - pg_set_client_encoding example
  • Example#1984 - pg_set_error_context_visibility example
  • Example#1985 - pg_set_error_verbosity example
  • Example#1986 - pg_trace example
  • Example#1987 - pg_transaction_status example
  • Example#1988 - pg_tty example
  • Example#1989 - pg_unescape_bytea example
  • Example#1990 - pg_untrace example
  • Example#1991 - pg_update example
  • Example#1992 - pg_version example
  • Example#1993 - Backup an existing database
  • Example#1994 - SQLite3::changes example
  • Example#1995 - SQLite3::close example
  • Example#1996 - SQLite3::__construct example
  • Example#1997 - max_length aggregation function example
  • Example#1998 - SQLite3::createCollation example
  • Example#1999 - SQLite3::createFunction example
  • Example#2000 - SQLite3::enableExceptions example
  • Example#2001 - SQLite3::exec example
  • Example#2002 - SQLite3::loadExtension example
  • Example#2003 - SQLite3::open example
  • Example#2004 - SQLite3::openBlob example
  • Example#2005 - Incrementally writing a BLOB
  • Example#2006 - SQLite3::prepare example
  • Example#2007 - SQLite3::query example
  • Example#2008 - SQLite3::querySingle example
  • Example#2009 - SQLite3::setAuthorizer example
  • Example#2010 - SQLite3::version example
  • Example#2011 - SQLite3Stmt::bindParam Usage
  • Example#2012 - SQLite3Stmt::bindValue example
  • Example#2013 - Inspecting the expanded SQL
  • Example#2014 - sqlsrv_begin_transaction example
  • Example#2015 - sqlsrv_cancel example
  • Example#2016 - sqlsrv_client_info example
  • Example#2017 - sqlsrv_close example
  • Example#2018 - sqlsrv_commit example
  • Example#2019 - Connect using Windows Authentication.
  • Example#2020 - Connect by specifying a user name and password.
  • Example#2021 - Connect on a specified port.
  • Example#2022 - functionname example
  • Example#2023 - sqlsrv_execute example
  • Example#2024 - Retrieving an associative array.
  • Example#2025 - Retrieving a numeric array.
  • Example#2026 - sqlsrv_fetch_object example
  • Example#2027 - sqlsrv_fetch example
  • Example#2028 - sqlsrv_field_metadata example
  • Example#2029 - sqlsrv_free_stmt example
  • Example#2030 - sqlsrv_get_field example
  • Example#2031 - sqlsrv_has_rows example
  • Example#2032 - sqlsrv_next_result example
  • Example#2033 - sqlsrv_num_fields example
  • Example#2034 - sqlsrv_num_rows example
  • Example#2035 - sqlsrv_prepare example
  • Example#2036 - sqlsrv_query example
  • Example#2037 - sqlsrv_rollback example
  • Example#2038 - sqlsrv_rows_affected example
  • Example#2039 - sqlsrv_send_stream_data example
  • Example#2040 - sqlsrv_server_info example
  • Example#2041 - Exemplo da cal_days_in_month
  • Example#2042 - cal_from_jd example
  • Example#2043 - cal_info example
  • Example#2044 - easter_date example
  • Example#2045 - Using easter_date with DateTime
  • Example#2046 - easter_days example
  • Example#2047 - Funções de Calendário
  • Example#2048 - Overflow behavior
  • Example#2049 - jdtojewish Example
  • Example#2050 - DateTimeImmutable::add/sub adicionando intervalos que tempo decorrido
  • Example#2051 - DateTimeImmutable::modify e strtotime incrementando ou decrementando valores de componentes individuais
  • Example#2052 - Adicionar ou substrair períodos pode causar transferência de datas
  • Example#2053 - Criando um objeto de data/hora mutável
  • Example#2054 - Criando um objeto de data/hora mutável
  • Example#2055 - Exemplo do método DateTime::modify
  • Example#2056 - Cuidados na adição ou subtração de meses
  • Example#2057 - Todos os formatos de data e horário são suportados
  • Example#2058 - Exemplo do método DateTime::setTimeZone
  • Example#2059 - Exemplo da função DateTimeImmutable::add
  • Example#2060 - Mais exemplos da função DateTimeImmutable::add
  • Example#2061 - Cuidado ao adicionar meses
  • Example#2062 - Exemplo da função DateTimeImmutable::__construct
  • Example#2063 - Complexidades de DateTimeImmutable::__construct
  • Example#2064 - Mudando o fuso horário associado
  • Example#2065 - Usando uma string relativo de data/hora
  • Example#2066 - Exemplo de DateTimeImmutable::createFromFormat
  • Example#2067 - Usando constantes predefinidas de formato com DateTimeImmutable::createFromFormat
  • Example#2068 - Complexidades de DateTimeImmutable::createFromFormat
  • Example#2069 - String de formatação com caracteres literais
  • Example#2070 - Comportamento de transferência
  • Example#2071 - Comportamento de transferência do nome do dia
  • Example#2072 - Detectando transferência de datas/horas
  • Example#2073 - Comportamento de análise ambicioso
  • Example#2074 - Criando um objeto de data/hora imutável
  • Example#2075 - Criando um objeto DateTime imutável
  • Example#2076 - Exemplo da função DateTimeImmutable::getLastErrors
  • Example#2077 - Exemplo da função DateTimeImmutable::modify
  • Example#2078 - Cuidado na adição ou subtração de meses
  • Example#2079 - Exemplo da função DateTimeImmutable::setDate
  • Example#2080 - Valores que excedem os limites são adicionados aos valores pai.
  • Example#2081 - Exemplo da função DateTimeImmutable::setISODate
  • Example#2082 - Valores que excedem os limites são adicionados a seus valores pai.
  • Example#2083 - Para encontrar o mês no qual uma semana se localiza
  • Example#2084 - Exemplo da função DateTimeImmutable::setTime
  • Example#2085 - Valores que excedem os limites são adicionados a seus valores pai
  • Example#2086 - Exemplo da função DateTimeImmutable::setTimestamp
  • Example#2087 - Exemplo da função DateTimeImmutable::setTimeZone
  • Example#2088 - Exemplo da função DateTimeImmutable::sub
  • Example#2089 - Mais exemplos da função DateTimeImmutable::sub
  • Example#2090 - Cuidado ao subtrair meses
  • Example#2091 - Exemplo do método DateTimeImmutable::diff
  • Example#2092 - DateTimeInterface::diff durante mudança de horário de verão
  • Example#2093 - Intervalo do método DateTimeInterface::diff
  • Example#2094 - Comparação entre objetos DateTime
  • Example#2095 - Exemplo de DateTimeInterface::format
  • Example#2096 - Mais exemplos
  • Example#2097 - Escapando caracteres ao formatar
  • Example#2098 - Exemplo do método DateTime::getOffset
  • Example#2099 - Exemplo do método DateTime::getTimestamp
  • Example#2100 - Recuperando o timestamp com resolução de mili e microssegundos
  • Example#2101 - Exemplo do método DateTime::getTimezone
  • Example#2102 - Criando e anexando DateTimeZone a um DateTimeImmutable
  • Example#2103 - Capturando erros na instanciação de DateTimeZone
  • Example#2104 - Exemplo do método DateTimeZone::getLocation
  • Example#2105 - Exemplos do método DateTimeZone::getOffset
  • Example#2106 - Exemplo do método timezone_transitions_get
  • Example#2107 - Um exemplo da função timezone_transitions_get com o parâmetro timestampBegin
  • Example#2108 - Exemplo da função timezone_abbreviations_list
  • Example#2109 - Um exemplo do método DateTimeZone::listIdentifiers
  • Example#2110 - Listando identificadores para uma região específica
  • Example#2111 - Listando identificadores para múltiplas regiões
  • Example#2112 - Listando identificadores para um único país
  • Example#2113 - Construindo e usando objetos da classe DateInterval
  • Example#2114 - Exemplo da classe DateInterval
  • Example#2115 - Analisando intervalos de datas válidos
  • Example#2116 - Analisando combinações e intervalos negativos
  • Example#2117 - Analisando intervalos de data especiais
  • Example#2118 - Exemplo da classe DateInterval
  • Example#2119 - A classe DateInterval e os pontos de transferência
  • Example#2120 - DateInterval e DateTime::diff com os modificadores %a e %d
  • Example#2121 -
  • Example#2122 - Exemplos de DatePeriod
  • Example#2123 - Exemplo de DatePeriod com DatePeriod::EXCLUDE_START_DATE
  • Example#2124 - Exemplo de DatePeriod mostrando todas as últimas quintas-feiras do ano
  • Example#2125 - Exemplo de DatePeriod::createFromISO8601String
  • Example#2126 - Exemplo de DatePeriod::getDateInterval
  • Example#2127 - Exemplo de DatePeriod::getEndDate
  • Example#2128 - Exemplo de DatePeriod::getEndDate sem uma data final
  • Example#2129 - Diferentes valores para DatePeriod::getRecurrences
  • Example#2130 - Exemplo de DatePeriod::getStartDate
  • Example#2131 - Exemplo da checkdate
  • Example#2132 - Lendo o fuso horário padrão
  • Example#2133 - Lendo a abreviação de um fuso horário
  • Example#2134 - Lendo o fuso horário padrão
  • Example#2135 - Exemplo da função date_parse_from_format
  • Example#2136 - Exemplo da função date_parse_from_format com avisos
  • Example#2137 - Exemplo da função date_parse_from_format com erros
  • Example#2138 - Um exemplo da função date_parsecom um string datetime compreensivo
  • Example#2139 - Exemplo da função date_parse com informação de abreviação de fuso horário
  • Example#2140 - Exemplo da função date_parse com informação de identificador de fuso horário
  • Example#2141 - Função date_parse com um string minimizado
  • Example#2142 - date_parse com formatos relativos
  • Example#2143 - Função date_parse com efeitos colaterais
  • Example#2144 - Um exemplo de date_sun_info
  • Example#2145 - Noite polar, com algum processamento
  • Example#2146 - Sol da meia-noite (Tromsø, Norway)
  • Example#2147 - Calculando a duração do dia (Kiev)
  • Example#2148 - Exemplo da função date_sunrise
  • Example#2149 - Sem nascer do sol
  • Example#2150 - Exemplo da função date_sunset
  • Example#2151 - Sem pôr do sol
  • Example#2152 - Exemplos da função date
  • Example#2153 - Caracteres de escape em date
  • Example#2154 - Exemplo da date e mktime
  • Example#2155 - Formatação com a função date
  • Example#2156 - Exemplo da função getdate
  • Example#2157 - Exemplo da função gettimeofday
  • Example#2158 - Exemplo da gmdate
  • Example#2159 - A função gmmktime no Windows
  • Example#2160 - Exemplo da função gmstrftime
  • Example#2161 - Exemplo da função idate
  • Example#2162 - Exemplo da função localtime
  • Example#2163 - Cronometrando a execução do script
  • Example#2164 - microtime e REQUEST_TIME_FLOAT
  • Example#2165 - Exemplo básico da função mktime
  • Example#2166 - Exemplo da mktime
  • Example#2167 - Último dia do próximo mês
  • Example#2168 - Exemplo da função strftime com idiomas
  • Example#2169 - Exemplo do número de semana ISO 8601:1988
  • Example#2170 - Exemplo do uso do modificador %e compatível com múltiplas plataformas
  • Example#2171 - Mostra os formatos conhecidos e desconhecidos
  • Example#2172 - Exemplo da função strptime
  • Example#2173 - Exemplo da função strtotime
  • Example#2174 - Checando por falha
  • Example#2175 - Exemplo de time
  • Example#2176 - Um exemplo da função timezone_name_from_abbr
  • Example#2177 - Obtendo a versão do banco de dados de fuso horário
  • Example#2178 -
  • Example#2179 -
  • Example#2180 - Measure several code blocks execution and get the total
  • Example#2181 - Closing an open file descriptor
  • Example#2182 - Setting and clearing a lock
  • Example#2183 - Opening a file descriptor
  • Example#2184 - Positioning in a file
  • Example#2185 - Setting the baud rate on a serial port
  • Example#2186 - Exemplo de chdir
  • Example#2187 - Exemplo de chroot
  • Example#2188 - Exemplo da closedir
  • Example#2189 - Exemplo da dir
  • Example#2190 - Exemplo de getcwd
  • Example#2191 - Exemplo de opendir
  • Example#2192 - Listando todas as entradas de um diretório
  • Example#2193 - Lista todas as entradas no diretório atual e remove . e ..
  • Example#2194 - Um exemplo simples de scandir
  • Example#2195 - Exemplo de finfo_buffer
  • Example#2196 - Exemplo de finfo_file
  • Example#2197 - Estilo orientado a objetos
  • Example#2198 - Estilo procedural
  • Example#2199 - Exemplo de mime_content_type
  • Example#2200 - Exemplo de basename
  • Example#2201 - Alterando o grupo de um arquivo
  • Example#2202 - Uso simples de chown
  • Example#2203 - Exemplo de clearstatcache
  • Example#2204 - Exemplo de copy
  • Example#2205 - Exemplo de dirname
  • Example#2206 - Exemplo de disk_free_space
  • Example#2207 - Exemplo de disk_total_space
  • Example#2208 - Exemplo de fclose
  • Example#2209 - Exemplo de fdatasync
  • Example#2210 - Handling timeouts with feof
  • Example#2211 - Exemplo de feof com um ponteiro de arquivo inválido
  • Example#2212 - File write example using fflush
  • Example#2213 - Um exemplo da fgetc
  • Example#2214 - Lê e imprime todo o conteúdo de um arquivo CSV
  • Example#2215 - Lendo um arquivo linha por linha
  • Example#2216 - Reading a PHP file line-by-line
  • Example#2217 - Testando se um arquivo existe
  • Example#2218 - Obtém e exibe o código-fonte da página inicial de um website
  • Example#2219 - Buscando no include_path
  • Example#2220 - Lendo uma sessão de um arquivo
  • Example#2221 - Usando contextos de fluxo
  • Example#2222 - Exemplo de uso simples
  • Example#2223 - Usando flags
  • Example#2224 - Exemplo de file
  • Example#2225 - Exemplo de fileatime
  • Example#2226 - Exemplo de filectime
  • Example#2227 - Descobrindo o grupo de um arquivo
  • Example#2228 - Comparando o inode de um arquivo com o arquivo atual
  • Example#2229 - Exemplo de filemtime
  • Example#2230 - Encontrando o proprietário de um arquivo
  • Example#2231 - Mostra as permissões como um valor em octal
  • Example#2232 - Mostra as permissões completas
  • Example#2233 - Exemplo de filesize
  • Example#2234 - Exemplo de filetype
  • Example#2235 - Exemplo de flock
  • Example#2236 - flock usando a opção LOCK_NB
  • Example#2237 - Comparando uma cor com um padrão de curingas shell
  • Example#2238 - Exemplos de fopen
  • Example#2239 - Usando fpassthru com arquivo binário
  • Example#2240 - Exemplo da fputcsv
  • Example#2241 - Um simples exemplo de fread
  • Example#2242 - Exemplo de fread binário
  • Example#2243 - Exemplos de fread remoto
  • Example#2244 - Exemplo de fscanf
  • Example#2245 - Conteúdo de users.txt
  • Example#2246 - Exemplo de fseek
  • Example#2247 - Exemplo fstat
  • Example#2248 - Exemplo de fsync
  • Example#2249 - Exemplo de ftell
  • Example#2250 - File truncation example
  • Example#2251 - Exemplo de fwrite
  • Example#2252 - Modo conveniente de como glob pode susbstituir opendir e companhia.
  • Example#2253 - Exemplo da is_dir
  • Example#2254 - Exemplo da is_executable
  • Example#2255 - Exemplo da is_file
  • Example#2256 - Cria e confirma se um arquivo é uma ligação simbólica
  • Example#2257 - Exemplo de is_readable
  • Example#2258 - Exemplo de is_uploaded_file
  • Example#2259 - Exemplo de is_writable
  • Example#2260 - Alterando um grupo de um ligação simbólica
  • Example#2261 - Alterando o proprietário de uma ligação simbólica
  • Example#2262 - Criando uma ligação rígida
  • Example#2263 - Exemplo de linkinfo
  • Example#2264 - Comparação de stat e lstat
  • Example#2265 - Exemplo de mkdir
  • Example#2266 - mkdir usando o parâmetro recursive
  • Example#2267 - Enviando múltiplos arquivos
  • Example#2268 - Conteúdo de sample.ini
  • Example#2269 - Exemplo de parse_ini_file
  • Example#2270 - parse_ini_file interpretando um arquivo php.ini
  • Example#2271 - Interpolação de Valor
  • Example#2272 - Fazendo Escape de Caracteres
  • Example#2273 - Exemplo de pathinfo
  • Example#2274 - Exemplo de pathinfo mostrando a diferença entre null e nenhuma extensão
  • Example#2275 - Exemplo de pathinfo para um arquivo iniciado por ponto
  • Example#2276 - Exemplo de pathinfo com desreferenciação de array
  • Example#2277 - Exemplo de pclose
  • Example#2278 - Exemplo de popen
  • Example#2279 - Exemplo da popen
  • Example#2280 - Forçando um recebimento usando readfile
  • Example#2281 - Exemplo de readlink
  • Example#2282 - realpath_cache_get exemplo
  • Example#2283 - Exemplo de realpath_cache_size
  • Example#2284 - Exemplo de realpath
  • Example#2285 - realpath no Windows
  • Example#2286 - Exemplo da rename
  • Example#2287 - Exemplo de rewind sobrescrevendo
  • Example#2288 - Exemplo de rmdir
  • Example#2289 - stat example
  • Example#2290 - Usando informação de stat junto com a função touch
  • Example#2291 - Cria uma ligação simbólica
  • Example#2292 - Exemplo de tempnam
  • Example#2293 - Exemplo da tmpfile
  • Example#2294 - Exemplo da função touch
  • Example#2295 - touch usando o parâmetro mtime
  • Example#2296 - Exemplo da umask
  • Example#2297 - Exemplo de unlink
  • Example#2298 - Example usage of inotify
  • Example#2299 - Checks if system administrator has signed the file
  • Example#2300 - Prints names of all extended attributes of file
  • Example#2301 - Removes all extended attributes of a file
  • Example#2302 - Sets extended attributes on .wav file
  • Example#2303 - xattr_supported example
  • Example#2304 - xdiff_file_bdiff_size example
  • Example#2305 - xdiff_file_bdiff example
  • Example#2306 - xdiff_file_bpatch example
  • Example#2307 - xdiff_file_diff_binary example
  • Example#2308 - xdiff_file_diff example
  • Example#2309 - xdiff_file_merge3 example
  • Example#2310 - xdiff_file_patch_binary example
  • Example#2311 - xdiff_file_patch example
  • Example#2312 - Patch reversing example
  • Example#2313 - xdiff_file_rabdiff example
  • Example#2314 - xdiff_string_bdiff_size example
  • Example#2315 - xdiff_string_diff example
  • Example#2316 - xdiff_string_patch example
  • Example#2317 - Enchant Usage Example
  • Example#2318 - List the backends provided by the given broker
  • Example#2319 - A enchant_broker_dict_exists example
  • Example#2320 - List all available dictionaries for one broker
  • Example#2321 - A enchant_broker_request_dict example
  • Example#2322 - Adding a word to a PWL
  • Example#2323 - A enchant_dict_describe example
  • Example#2324 - A enchant_dict_quick_check example
  • Example#2325 - A enchant_dict_suggest example
  • Example#2326 - Usage example.
  • Example#2327 - Using Gender\Gender::country
  • Example#2328 - Exemplo de bindtextdomain
  • Example#2329 - gettext-check
  • Example#2330 - Exemplo de ngettext
  • Example#2331 - Exemplo iconv_get_encoding
  • Example#2332 - Exemplo iconv_mime_decode_headers
  • Example#2333 - Exemplo iconv_mime_decode
  • Example#2334 - Exemplo iconv_mime_encode
  • Example#2335 - Exemplo iconv_set_encoding
  • Example#2336 - Exemplo iconv
  • Example#2337 - Exemplo ob_iconv_handler:
  • Example#2338 - Example of using the procedural API
  • Example#2339 - Example of using the object-oriented API
  • Example#2340 - FRENCH_COLLATION rules
  • Example#2341 - ALTERNATE_HANDLING rules
  • Example#2342 - CASE_FIRST rules
  • Example#2343 - CASE_LEVEL rules
  • Example#2344 - collator_asort example
  • Example#2345 - collator_compare example
  • Example#2346 - Comparing strings without diacritics or case-sensitivity
  • Example#2347 - Collator::__construct example
  • Example#2348 - collator_create example
  • Example#2349 - collator_get_attribute example
  • Example#2350 - collator_get_error_code example
  • Example#2351 - collator_get_error_message example
  • Example#2352 - collator_get_locale example
  • Example#2353 - collator_get_sort_keyexample
  • Example#2354 - collator_get_strength example
  • Example#2355 - collator_set_attribute example
  • Example#2356 - collator_set_strength example
  • Example#2357 - collator_sort_with_sort_keys example
  • Example#2358 - collator_sort example
  • Example#2359 - numfmt_create example
  • Example#2360 - NumberFormatter::create example
  • Example#2361 - numfmt_format_currency example
  • Example#2362 - OO example
  • Example#2363 - numfmt_format example
  • Example#2364 - OO example
  • Example#2365 - numfmt_get_attribute example
  • Example#2366 - OO example
  • Example#2367 - numfmt_get_error_code example
  • Example#2368 - OO example
  • Example#2369 - numfmt_get_error_message example
  • Example#2370 - OO example
  • Example#2371 - numfmt_get_locale example
  • Example#2372 - numfmt_get_pattern example
  • Example#2373 - OO example
  • Example#2374 - numfmt_get_symbol example
  • Example#2375 - OO example
  • Example#2376 - numfmt_get_text_attribute example
  • Example#2377 - OO example
  • Example#2378 - numfmt_parse_currency example
  • Example#2379 - OO example
  • Example#2380 - numfmt_parse example
  • Example#2381 - OO example
  • Example#2382 - numfmt_set_attribute example
  • Example#2383 - OO example
  • Example#2384 - numfmt_set_pattern example
  • Example#2385 - OO example
  • Example#2386 - numfmt_set_symbol example
  • Example#2387 - OO example
  • Example#2388 - numfmt_set_text_attribute example
  • Example#2389 - OO example
  • Example#2390 - locale_accept_from_http example
  • Example#2391 - OO example
  • Example#2392 - locale_compose example
  • Example#2393 - OO example
  • Example#2394 - Subtag limits
  • Example#2395 - locale_filter_matches example
  • Example#2396 - OO example
  • Example#2397 - locale_get_all_variants example
  • Example#2398 - OO example
  • Example#2399 - locale_get_default example
  • Example#2400 - OO example
  • Example#2401 - locale_get_display_language example
  • Example#2402 - OO example
  • Example#2403 - locale_get_display_name example
  • Example#2404 - OO example
  • Example#2405 - locale_get_display_region example
  • Example#2406 - OO example
  • Example#2407 - locale_get_display_script example
  • Example#2408 - OO example
  • Example#2409 - locale_get_display_variant example
  • Example#2410 - OO example
  • Example#2411 - locale_get_keywords example
  • Example#2412 - OO example
  • Example#2413 - locale_get_primary_language example
  • Example#2414 - OO example
  • Example#2415 - locale_get_region example
  • Example#2416 - OO example
  • Example#2417 - locale_get_script example
  • Example#2418 - OO example
  • Example#2419 - locale_lookup example
  • Example#2420 - OO example
  • Example#2421 - locale_parse example
  • Example#2422 - OO example
  • Example#2423 - locale_set_default example
  • Example#2424 - OO example
  • Example#2425 - Normalizer::getRawDecomposition example
  • Example#2426 - Exemplo de normalizer_is_normalized
  • Example#2427 - Exemplo orientado a objetos
  • Example#2428 - Exemplo de normalizer_normalize
  • Example#2429 - Exemplo orientado a objetos
  • Example#2430 - msgfmt_create example
  • Example#2431 - OO example
  • Example#2432 - msgfmt_format_message example
  • Example#2433 - OO example
  • Example#2434 - Instructing ICU to format currency with common and with narrow currency symbol
  • Example#2435 - msgfmt_format example
  • Example#2436 - OO example
  • Example#2437 - msgfmt_get_error_message example
  • Example#2438 - OO example
  • Example#2439 - msgfmt_get_locale example
  • Example#2440 - OO example
  • Example#2441 - msgfmt_get_pattern example
  • Example#2442 - OO example
  • Example#2443 - msgfmt_parse_message example
  • Example#2444 - OO example
  • Example#2445 - msgfmt_parse example
  • Example#2446 - OO example
  • Example#2447 - msgfmt_set_pattern example
  • Example#2448 - OO example
  • Example#2449 - IntlCalendar::add
  • Example#2450 - IntlCalendar::after
  • Example#2451 - IntlCalendar::clear examples
  • Example#2452 - IntlCalendar::createInstance
  • Example#2453 - IntlCalendar::equals
  • Example#2454 - IntlCalendar::fieldDifference
  • Example#2455 - IntlCalendar::fromDateTime
  • Example#2456 - IntlCalendar::get
  • Example#2457 - IntlCalendar::getActualMaximum
  • Example#2458 - IntlCalendar::getAvailableLocales
  • Example#2459 - IntlCalendar::getDayOfWeekType
  • Example#2460 - IntlCalendar::getErrorCode and IntlCalendar::getErrorMessage
  • Example#2461 - IntlCalendar::getErrorMessage
  • Example#2462 - IntlCalendar::getFirstDayOfWeek
  • Example#2463 - IntlCalendar::getKeyworkValuesForLocale
  • Example#2464 - Maxima examples
  • Example#2465 - IntlCalendar::getLocale
  • Example#2466 - IntlCalendar::getMinimalDaysInFirstWeek
  • Example#2467 - IntlCalendar::getNow
  • Example#2468 - IntlCalendar::getRepeatedWallTimeOption
  • Example#2469 - IntlCalendar::getSkippedWallTimeOption
  • Example#2470 - IntlCalendar::getTime
  • Example#2471 - IntlCalendar::getTimeZone
  • Example#2472 - IntlCalendar::getType
  • Example#2473 - IntlCalendar::inDaylightTime
  • Example#2474 - IntlCalendar::isEquivalentTo
  • Example#2475 - IntlCalendar::isLenient
  • Example#2476 - IntlCalendar::isWeekend
  • Example#2477 - IntlCalendar::roll
  • Example#2478 - IntlCalendar::set
  • Example#2479 - IntlCalendar::setDate example
  • Example#2480 - IntlCalendar::setDateTime example
  • Example#2481 - IntlCalendar::setFirstDayOfWeek
  • Example#2482 - IntlCalendar::setTime
  • Example#2483 - IntlCalendar::setTimeZone
  • Example#2484 - IntlCalendar::toDateTime
  • Example#2485 - IntlGregorianCalendar::createFromDate example
  • Example#2486 - IntlCalendar::setDateTime example
  • Example#2487 - datefmt_create example
  • Example#2488 - OO example
  • Example#2489 - Example of invalid locale handling
  • Example#2490 - datefmt_format example
  • Example#2491 - OO example
  • Example#2492 - With IntlCalendar object
  • Example#2493 - IntlDateFormatter::formatObject examples
  • Example#2494 - datefmt_get_calendar example
  • Example#2495 - OO example
  • Example#2496 - Example of invalid locale handling
  • Example#2497 - datefmt_get_datetype example
  • Example#2498 - OO example
  • Example#2499 - datefmt_get_error_code example
  • Example#2500 - OO example
  • Example#2501 - datefmt_get_error_message example
  • Example#2502 - OO example
  • Example#2503 - datefmt_get_locale example
  • Example#2504 - OO example
  • Example#2505 - datefmt_get_pattern example
  • Example#2506 - OO example
  • Example#2507 - datefmt_get_timetype example
  • Example#2508 - OO example
  • Example#2509 - datefmt_get_timezone_id example
  • Example#2510 - OO example
  • Example#2511 - IntlDateFormatter::getCalendarObject example
  • Example#2512 - IntlDateFormatter::getTimeZone examples
  • Example#2513 - datefmt_is_lenient example
  • Example#2514 - OO example
  • Example#2515 - datefmt_localtime example
  • Example#2516 - OO example
  • Example#2517 - OO example
  • Example#2518 - datefmt_parse example
  • Example#2519 - datefmt_set_calendar example
  • Example#2520 - OO example
  • Example#2521 - Example with IntlCalendar argument
  • Example#2522 - datefmt_set_lenient example
  • Example#2523 - OO example
  • Example#2524 - datefmt_set_pattern example
  • Example#2525 - OO example
  • Example#2526 - IntlDateFormatter::setTimeZone examples
  • Example#2527 - Exempo da função resourcebundle_count
  • Example#2528 - Exemplo orientado a objeto
  • Example#2529 - Exemplo de resourcebundle_create
  • Example#2530 - Exemplo de ResourceBundle::create
  • Example#2531 - Exemplo da função resourcebundle_get_error_code
  • Example#2532 - Exemplo orientado à objeto
  • Example#2533 - Exemplo da função resourcebundle_get_error_message
  • Example#2534 - Exemplo orientado à objeto
  • Example#2535 - Exemplo da função resourcebundle_get
  • Example#2536 - Exemplo orientado à objeto
  • Example#2537 - Exemplo da função resourcebundle_locales
  • Example#2538 - Exemplo orientado à objetos
  • Example#2539 - Spoofchecker::areConfusable example
  • Example#2540 - Spoofchecker::isSuspicious example
  • Example#2541 - Retrieving the registered transliterator IDs
  • Example#2542 - Converting escaped UTF-16 code units
  • Example#2543 - IntlDatePatternGenerator::getBestPattern example
  • Example#2544 - Convertendo de UTF-8 para UTF-16 e vice-versa
  • Example#2545 - Caracteres inválidos na entrada
  • Example#2546 - Caracteres que não podem ser codificados
  • Example#2547 - grapheme_extract example
  • Example#2548 - grapheme_stripos example
  • Example#2549 - grapheme_stristr example
  • Example#2550 - grapheme_strlen example
  • Example#2551 - grapheme_strpos example
  • Example#2552 - grapheme_strripos example
  • Example#2553 - grapheme_strrpos example
  • Example#2554 - grapheme_strstr example
  • Example#2555 - grapheme_substr example
  • Example#2556 - idn_to_ascii example
  • Example#2557 - idn_to_utf8 example
  • Example#2558 - Testando diferentes pontos de código
  • Example#2559 - Testando diferentes pontos de código
  • Example#2560 - Testando diferentes pontos de código
  • Example#2561 - Testando diferentes pontos de código
  • Example#2562 - Testando diferentes pontos de código
  • Example#2563 - Testando diferentes pontos de código
  • Example#2564 - Testando diferentes pontos de código
  • Example#2565 - Testando diferentes pontos de código
  • Example#2566 - Testando diferentes pontos de código
  • Example#2567 - Enumerating over a sample range of code points
  • Example#2568 - Enumerating over a sample range of code points
  • Example#2569 - Testando diferentes pontos de código
  • Example#2570 - Testando diferentes pontos de código
  • Example#2571 - Testando diferentes pontos de código
  • Example#2572 - Testando diferentes pontos de código
  • Example#2573 - Testando diferentes pontos de código
  • Example#2574 - Testando diferentes propriedades
  • Example#2575 - Testando diferentes propriedades
  • Example#2576 - Testando diferentes propriedades
  • Example#2577 - Testando diferentes pontos de código
  • Example#2578 - Testando diferentes propriedades
  • Example#2579 - Testando diferentes propriedades
  • Example#2580 - Testando diferentes propriedades
  • Example#2581 - Testando diferentes propriedades
  • Example#2582 - Testando diferentes propriedades
  • Example#2583 - Testando diferentes propriedades
  • Example#2584 - Testando diferentes pontos de código
  • Example#2585 - Testando diferentes pontos de código
  • Example#2586 - Testando diferentes pontos de código
  • Example#2587 - Testando diferentes pontos de código
  • Example#2588 - Testando diferentes pontos de código
  • Example#2589 - Testando diferentes pontos de código
  • Example#2590 - Testando diferentes pontos de código
  • Example#2591 - Testando diferentes pontos de código
  • Example#2592 - Testando diferentes pontos de código
  • Example#2593 - Testando diferentes pontos de código
  • Example#2594 - Testando diferentes pontos de código
  • Example#2595 - Testando diferentes pontos de código
  • Example#2596 - Testando diferentes pontos de código
  • Example#2597 - Testando diferentes pontos de código
  • Example#2598 - Testando diferentes pontos de código
  • Example#2599 - Testando diferentes pontos de código
  • Example#2600 - Testando diferentes pontos de código
  • Example#2601 - Testando diferentes pontos de código
  • Example#2602 - Testando diferentes pontos de código
  • Example#2603 - Testando diferentes pontos de código
  • Example#2604 - Testando diferentes pontos de código
  • Example#2605 - Testando diferentes pontos de código
  • Example#2606 - Testando diferentes pontos de código
  • Example#2607 - Testando diferentes pontos de código
  • Example#2608 - Testando diferentes pontos de código
  • Example#2609 - Testando diferentes pontos de código
  • Example#2610 - Testando diferentes pontos de código
  • Example#2611 - Testando diferentes pontos de código
  • Example#2612 - Testando diferentes pontos de código
  • Example#2613 - Testando diferentes pontos de código
  • Example#2614 - Testando diferentes pontos de código
  • Example#2615 - Testando diferentes pontos de código
  • Example#2616 - intl_error_name example
  • Example#2617 - intl_get_error_code example
  • Example#2618 - intl_get_error_message example
  • Example#2619 - intl_is_failure example
  • Example#2620 - php.ini setting examples
  • Example#2621 - php.ini setting for EUC-JP users
  • Example#2622 - php.ini setting for SJIS users
  • Example#2623 - Disable HTTP input conversion in php.ini
  • Example#2624 - php.ini setting example
  • Example#2625 - Script example
  • Example#2626 - Testando diferentes pontos de código
  • Example#2627 - mb_convert_case example
  • Example#2628 - mb_convert_case example with non-Latin UTF-8 text
  • Example#2629 - mb_convert_encoding example
  • Example#2630 - mb_convert_kana example
  • Example#2631 - mb_convert_variables example
  • Example#2632 - map example
  • Example#2633 - map example escapes JavaScript string
  • Example#2634 - mb_detect_encoding example
  • Example#2635 - Effect of strict parameter
  • Example#2636 - Effect of order when multiple encodings match
  • Example#2637 - mb_detect_order examples
  • Example#2638 - Example showing useless detect orders
  • Example#2639 - mb_encode_mimeheader example
  • Example#2640 - map example
  • Example#2641 - mb_encode_numericentity example
  • Example#2642 - mb_encoding_aliases example
  • Example#2643 - mb_ereg_replace_callback example
  • Example#2644 - mb_ereg_replace_callback using anonymous function
  • Example#2645 - mb_internal_encoding example
  • Example#2646 - mb_list_encodings example
  • Example#2647 -
  • Example#2648 - mb_output_handler example
  • Example#2649 - mb_preferred_mime_name example
  • Example#2650 - mb_str_pad example
  • Example#2651 - mb_strimwidth example
  • Example#2652 - Exemplo de mb_strtolower
  • Example#2653 - Exemplo de mb_strtolower com texto UTF-8 não-Latin
  • Example#2654 - mb_strtoupper example
  • Example#2655 - mb_strtoupper example with non-Latin UTF-8 text
  • Example#2656 - mb_strwidth example
  • Example#2657 - mb_substitute_character example
  • Example#2658 - mb_substr_count example
  • Example#2659 - pspell_add_to_personal
  • Example#2660 - pspell_check Example
  • Example#2661 - pspell_add_to_personal Example
  • Example#2662 - pspell_config_create
  • Example#2663 - pspell_config_ignore
  • Example#2664 - pspell_config_mode Example
  • Example#2665 - pspell_config_personal
  • Example#2666 - pspell_config_repl
  • Example#2667 - pspell_config_runtogether
  • Example#2668 - pspell_new_config
  • Example#2669 - pspell_new_personal
  • Example#2670 - pspell_new
  • Example#2671 - pspell_add_to_personal
  • Example#2672 - pspell_store_replacement
  • Example#2673 - pspell_suggest example
  • Example#2674 - Basic recode_file example
  • Example#2675 - Basic recode_string example
  • Example#2676 - Exemplo de exif_imagetype
  • Example#2677 - Exemplo exif_read_data
  • Example#2678 - exif_read_data com fluxos, disponível a partir do PHP 7.2.0
  • Example#2679 - Exemplo de exif_tagname
  • Example#2680 - Exemplo de exif_thumbnail
  • Example#2681 - PNG creation with PHP
  • Example#2682 - Adding watermarks to images using alpha channels
  • Example#2683 - Using imagecopymerge to create a translucent watermark
  • Example#2684 - Usando gd_info
  • Example#2685 - getimagesize e tipos MIME.
  • Example#2686 - getimagesizeexemplo
  • Example#2687 - getimagesize (URL)
  • Example#2688 - getimagesize() retornando IPTC.
  • Example#2689 - getimagesizefromstring example
  • Example#2690 - image_type_to_extension example
  • Example#2691 - image_type_to_mime_type example
  • Example#2692 - image2wbmp example
  • Example#2693 - imageaffinematrixconcat example
  • Example#2694 - imageaffinematrixget example
  • Example#2695 - imagealphablending usage example
  • Example#2696 - A comparison of two lines, one with anti-aliasing switched on
  • Example#2697 - Drawing a circle with imagearc
  • Example#2698 - Saving a BMP file
  • Example#2699 - imagechar example
  • Example#2700 - imagecharup example
  • Example#2701 - imagecolorallocate example
  • Example#2702 - Example of using imagecolorallocatealpha
  • Example#2703 - Convert typical alpha values for use with imagecolorallocatealpha
  • Example#2704 - Access distinct RGB values
  • Example#2705 - Human-readable RGB values using imagecolorsforindex
  • Example#2706 - Search for a set of colors in an image
  • Example#2707 - Search for a set of colors in an image
  • Example#2708 - Example of using imagecolorclosesthwb
  • Example#2709 - Using imagecolordeallocate
  • Example#2710 - Get colors from the GD logo
  • Example#2711 - Get colors from the GD logo
  • Example#2712 - imagecolormatch example
  • Example#2713 - Using imagecoloresolve to get colors from an image
  • Example#2714 - Using imagecoloresolvealpha to get colors from an image
  • Example#2715 - imagecolorset example
  • Example#2716 - imagecolorsforindex example
  • Example#2717 - Getting total number of colors in an image using imagecolorstotal
  • Example#2718 - imagecolortransparent example
  • Example#2719 - Embossing the PHP.net logo
  • Example#2720 - Gaussian blur
  • Example#2721 - Recortando o logotipo do PHP.net
  • Example#2722 - Merging two copies of the PHP.net logo with 75% transparency
  • Example#2723 - imagecopymergegray usage
  • Example#2724 - Simple example
  • Example#2725 - Resampling an image proportionally
  • Example#2726 - Resizing an image
  • Example#2727 - Criando um novo stream de imagem GD e exibindo uma imagem.
  • Example#2728 - Convert an BMP image to a PNG image using imagecreatefrombmp
  • Example#2729 - imagecreatefromgd2 example
  • Example#2730 - imagecreatefromgd2part example
  • Example#2731 - imagecreatefromgd exemplo
  • Example#2732 - Example to handle an error during loading of a GIF
  • Example#2733 - Exemplo de como lidar com um erro durante o carregamento de uma imagem JPEG.
  • Example#2734 - Exemplo de como lidar com um erro durante o carregamento de uma imagem PNG
  • Example#2735 - imagecreatefromstring example
  • Example#2736 - Example to handle an error during loading of a WBMP
  • Example#2737 - Convert an WebP image to a jpeg image using imagecreatefromwebp
  • Example#2738 - Convert an XBM image to a png image using imagecreatefromxbm
  • Example#2739 - Creating an image instance using imagecreatefromxpm
  • Example#2740 - Creating a new GD image stream and outputting an image.
  • Example#2741 - imagecrop example
  • Example#2742 - Proper handling of auto-cropping
  • Example#2743 - imagedashedline example
  • Example#2744 - Alternative to imagedashedline
  • Example#2745 - Usando imagedestroy antes do PHP 8.0.0.
  • Example#2746 - imageellipse example
  • Example#2747 - imagefill example
  • Example#2748 - Creating a 3D looking pie
  • Example#2749 - imagefilledellipse example
  • Example#2750 - imagefilledpolygon example
  • Example#2751 - imagefilledrectangle usage
  • Example#2752 - Filling an ellipse with a color
  • Example#2753 - imagefilter grayscale example
  • Example#2754 - imagefilter brightness example
  • Example#2755 - imagefilter colorize example
  • Example#2756 - imagefilter negate example
  • Example#2757 - imagefilter pixelate example
  • Example#2758 - imagefilter scatter example
  • Example#2759 - Flips an image vertically
  • Example#2760 - Flips the image horizontally
  • Example#2761 - Using imagefontheight on built-in fonts
  • Example#2762 - Using imagefontheight together with imageloadfont
  • Example#2763 - Using imagefontwidth on built-in fonts
  • Example#2764 - Using imagefontwidth together with imageloadfont
  • Example#2765 - imageftbbox example
  • Example#2766 - imagefttext example
  • Example#2767 - imagegammacorrect usage
  • Example#2768 - Outputting a GD2 image
  • Example#2769 - Saving a GD2 image
  • Example#2770 - Outputting a GD image
  • Example#2771 - Saving a GD image
  • Example#2772 - imagegetclip example
  • Example#2773 - Outputting an image using imagegif
  • Example#2774 - Converting a PNG image to GIF using imagegif
  • Example#2775 - imagegrabscreen example
  • Example#2776 - imagegrabwindow example
  • Example#2777 - Turn on interlacing using imageinterlace
  • Example#2778 - Simple detection of true color image instances using imageistruecolor
  • Example#2779 - Outputting a JPEG image to the browser
  • Example#2780 - Saving a JPEG image to a file
  • Example#2781 - Outputting the image at 75% quality to the browser
  • Example#2782 - imagelayereffect example
  • Example#2783 - Drawing a thick line
  • Example#2784 - imageloadfont usage example
  • Example#2785 - imageopenpolygon example
  • Example#2786 - imagepalettecopy example
  • Example#2787 - Converts any image object to true color
  • Example#2788 - imagepolygon example
  • Example#2789 - Simple imagerectangle example
  • Example#2790 - Setting and getting the resolution of an image
  • Example#2791 - Rotate an image 180 degrees
  • Example#2792 - Basic imagesavealpha Usage
  • Example#2793 - imagesetbrush example
  • Example#2794 - imagesetinterpolation example
  • Example#2795 - imagesetpixel example
  • Example#2796 - imagesetstyle example
  • Example#2797 - imagesetthickness example
  • Example#2798 - imagesettile example
  • Example#2799 - imagestring example
  • Example#2800 - imagestringup example
  • Example#2801 - Usando imagesx
  • Example#2802 - Usando imagesy
  • Example#2803 - Converting a true color image to a palette-based image
  • Example#2804 - imagettfbbox example
  • Example#2805 - imagettftext example
  • Example#2806 - Verificando o suporte a PNG
  • Example#2807 - Outputting a WBMP image
  • Example#2808 - Saving the WBMP image
  • Example#2809 - Outputting the image with a different foreground
  • Example#2810 - Saving an WebP file
  • Example#2811 - Saving an XBM file
  • Example#2812 - Saving an XBM file with a different foreground color
  • Example#2813 - Embedding IPTC data into a JPEG
  • Example#2814 - iptcparse() used together with getimagesize
  • Example#2815 - jpeg2wbmp example
  • Example#2816 - png2wbmp example
  • Example#2817 - Gmagick Example
  • Example#2818 - Gmagick::despeckleimage example
  • Example#2819 - Gmagick::setCompressionQuality
  • Example#2820 - Creating a thumbnail in Imagick
  • Example#2821 - Make a thumbnail of all JPG files in a directory
  • Example#2822 - Creating a reflection of an image
  • Example#2823 - Filling text with gradient
  • Example#2824 - Read in GIF image and resize all frames
  • Example#2825 - Create a PHP logo
  • Example#2826 - Using Imagick::adaptiveBlurImage:
  • Example#2827 - Using Imagick::adaptiveResizeImage
  • Example#2828 - A Imagick::adaptiveSharpenImage example
  • Example#2829 - Imagick::adaptiveThresholdImage
  • Example#2830 - Imagick::addNoiseImage
  • Example#2831 - Imagick::affineTransformImage
  • Example#2832 - Using Imagick::annotateImage:
  • Example#2833 - Imagick::appendImages example
  • Example#2834 - Imagick::autoLevelImage
  • Example#2835 - Imagick::blackThresholdImage
  • Example#2836 - Imagick::blueShiftImage
  • Example#2837 - Using Imagick::blurImage:
  • Example#2838 - Imagick::borderImage
  • Example#2839 - Imagick::brightnessContrastImage
  • Example#2840 - Imagick::charcoalImage
  • Example#2841 - Using Imagick::chopImage:
  • Example#2842 - Imagick object cloning in different versions of imagick
  • Example#2843 - Using Imagick::clutImage:
  • Example#2844 - Imagick::colorizeImage
  • Example#2845 - Imagick::colorMatrixImage
  • Example#2846 - Using Imagick::commentImage:
  • Example#2847 - Using Imagick::compareImageLayers
  • Example#2848 - Using Imagick::compareImages:
  • Example#2849 - Using Imagick::compositeImage:
  • Example#2850 - Imagick::contrastImage
  • Example#2851 - Imagick::convolveImage
  • Example#2852 - Imagick::cropImage
  • Example#2853 - Imagick::deskewImage
  • Example#2854 - Imagick::despeckleImage
  • Example#2855 - Using Imagick::distortImage:
  • Example#2856 - Imagick::edgeImage
  • Example#2857 - Imagick::embossImage
  • Example#2858 - Imagick::enhanceImage
  • Example#2859 - Imagick::equalizeImage
  • Example#2860 - Using Imagick::evaluateImage
  • Example#2861 - Using Imagick::exportImagePixels
  • Example#2862 - Imagick::filter
  • Example#2863 - Imagick::flipImage
  • Example#2864 - Imagick::floodfillPaintImage example
  • Example#2865 - Imagick::flopImage
  • Example#2866 - Imagick::forwardFourierTransformImage
  • Example#2867 - Imagick::frameImage
  • Example#2868 - Create a sinusoidal gradient
  • Example#2869 - Create a gradient from the polynomial (4x^2 - 4x + 1)
  • Example#2870 - Create a complex gradient from the polynomial (4x^2 - 4x^2 + 1) modulated by a sinusoidal gradient
  • Example#2871 - Imagick::fxImage
  • Example#2872 - Imagick::gammaImage
  • Example#2873 - Imagick::gaussianBlurImage
  • Example#2874 - Using Imagick::getImageGeometry
  • Example#2875 - Generates Imagick::getImageHistogram
  • Example#2876 - Using Imagick::getImageLength:
  • Example#2877 - Using Imagick::getImageProperties:
  • Example#2878 - Using Imagick::getImageProperty:
  • Example#2879 - Using Imagick::getIteratorIndex:
  • Example#2880 - Imagick::getPixelIterator
  • Example#2881 - Imagick::getPixelRegionIterator example
  • Example#2882 - Getting the size of a raw RGB image set at 200x400, after scaling to 400x800 (compared to width / height)
  • Example#2883 - Imagick::haldClutImage
  • Example#2884 - Imagick::identifyFormat
  • Example#2885 - Example Result Format
  • Example#2886 - Imagick::implodeImage
  • Example#2887 - Imagick::importImagePixels example
  • Example#2888 - Imagick::levelImage
  • Example#2889 - Imagick::linearStretchImage
  • Example#2890 - Imagick::magnifyImage
  • Example#2891 - Imagick::medianFilterImage
  • Example#2892 - Imagick::mergeImageLayers
  • Example#2893 - Imagick::modulateImage
  • Example#2894 - Convolve Imagick::morphology
  • Example#2895 - Correlate Imagick::morphology
  • Example#2896 - Erode Imagick::morphology
  • Example#2897 - Erode Intensity Imagick::morphology
  • Example#2898 - Dilate Imagick::morphology
  • Example#2899 - Dilate intensity Imagick::morphology
  • Example#2900 - Distance with Chebyshev kernel Imagick::morphology
  • Example#2901 - Distance with Manhattan kernel Imagick::morphology
  • Example#2902 - Distance with ocatagonal kernel Imagick::morphology
  • Example#2903 - Distance with Euclidean kernel Imagick::morphology
  • Example#2904 - Edge Imagick::morphology
  • Example#2905 - Open Imagick::morphology
  • Example#2906 - Open intensity Imagick::morphology
  • Example#2907 - Close Imagick::morphology
  • Example#2908 - Close Intensity Imagick::morphology
  • Example#2909 - Smooth Imagick::morphology
  • Example#2910 - Edge in Imagick::morphology
  • Example#2911 - Edge out Imagick::morphology
  • Example#2912 - 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#2913 - 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#2914 - Hit and Miss Imagick::morphology
  • Example#2915 - Thinning Imagick::morphology
  • Example#2916 - Thicken Imagick::morphology
  • Example#2917 - Thick to generate a convex hull Imagick::morphology
  • Example#2918 - Iterative morphology Imagick::morphology
  • Example#2919 - Helper function to get an image silhouette Imagick::morphology
  • Example#2920 - Imagick::motionBlurImage
  • Example#2921 - Imagick::negateImage
  • Example#2922 - Using Imagick::newImage:
  • Example#2923 - Imagick::newPseudoImage
  • Example#2924 - Imagick::normalizeImage
  • Example#2925 - Imagick::oilPaintImage
  • Example#2926 - Using Imagick::optimizeImageLayers
  • Example#2927 - Imagick::orderedPosterizeImage
  • Example#2928 - Using Imagick::pingImageBlob
  • Example#2929 - Using Imagick::pingImageFile
  • Example#2930 - A Imagick::polaroidImage example
  • Example#2931 - Imagick::posterizeImage
  • Example#2932 - Imagick::quantizeImage
  • Example#2933 - Using Imagick::queryFontMetrics:
  • Example#2934 - Imagick::queryFonts
  • Example#2935 - Imagick::queryFormats
  • Example#2936 - Imagick::radialBlurImage
  • Example#2937 - Imagick::raiseImage
  • Example#2938 - Imagick::randomThresholdImage
  • Example#2939 - Imagick::readImageBlob
  • Example#2940 - Imagick::recolorImage
  • Example#2941 - Imagick::reduceNoiseImage
  • Example#2942 - Imagick::resampleImage
  • Example#2943 - Imagick::resizeImage
  • Example#2944 - Imagick::rollImage
  • Example#2945 - Imagick::rotateImage
  • Example#2946 - Imagick::rotationalBlurImage
  • Example#2947 - Using Imagick::roundCorners:
  • Example#2948 - Imagick::scaleImage
  • Example#2949 - Imagick::segmentImage
  • Example#2950 - Imagick::selectiveBlurImage
  • Example#2951 - Imagick::separateImageChannel
  • Example#2952 - Imagick::sepiaToneImage
  • Example#2953 - Imagick::setCompressionQuality
  • Example#2954 - A Imagick::setFont example
  • Example#2955 - A Imagick::setImage example
  • Example#2956 - Imagick::setImageArtifact
  • Example#2957 - Imagick::setImageBias
  • Example#2958 - Imagick::setImageClipMask
  • Example#2959 - Imagick::setImageCompressionQuality
  • Example#2960 - Modify animated Gif with Imagick::setImageDelay
  • Example#2961 - Basic Imagick::setImageIterations usage
  • Example#2962 - A Imagick::setImageOpacity example
  • Example#2963 - Imagick::setImageOrientation
  • Example#2964 - Using Imagick::setImageProperty:
  • Example#2965 - Imagick::setImageResolution
  • Example#2966 - Modify animated Gif with Imagick::setImageTicksPerSecond
  • Example#2967 - Using Imagick::setIteratorIndex:
  • Example#2968 - Attempt to reach '$extent' sizeImagick::setOption
  • Example#2969 - Imagick::setOption
  • Example#2970 - Imagick::setOption
  • Example#2971 - A Imagick::setPointSize example
  • Example#2972 - Imagick::setProgressMonitor
  • Example#2973 - Imagick::setSamplingFactors
  • Example#2974 - Imagick::shadeImage
  • Example#2975 - Imagick::shadowImage
  • Example#2976 - Imagick::sharpenImage
  • Example#2977 - Imagick::shaveImage
  • Example#2978 - Imagick::shearImage
  • Example#2979 - Create a gradient image using Imagick::sigmoidalContrastImage suitable for blending two images together smoothly, with the blending defined by $contrast and $the midpoint
  • Example#2980 - Imagick::sketchImage
  • Example#2981 - Imagick::smushImages
  • Example#2982 - Imagick::solarizeImage
  • Example#2983 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#2984 - SPARSECOLORMETHOD_BILINEAR Imagick::sparseColorImage
  • Example#2985 - SPARSECOLORMETHOD_SPEPARDS Imagick::sparseColorImage
  • Example#2986 - SPARSECOLORMETHOD_VORONOI Imagick::sparseColorImage
  • Example#2987 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#2988 - createGradientImage is used by other examples. Imagick::sparseColorImage
  • Example#2989 - Imagick::spliceImage
  • Example#2990 - Imagick::spreadImage
  • Example#2991 - Imagick::statisticImage
  • Example#2992 - Imagick::subImageMatch
  • Example#2993 - Imagick::swirlImage
  • Example#2994 - Imagick::textureImage
  • Example#2995 - Imagick::thresholdImage
  • Example#2996 - Imagick::thumbnailImage
  • Example#2997 - Imagick::tintImage
  • Example#2998 - Using Imagick::transformImage:
  • Example#2999 - Imagick::transformImageColorspace example
  • Example#3000 - Imagick::transparentPaintImage
  • Example#3001 - Imagick::transposeImage
  • Example#3002 - Imagick::transverseImage
  • Example#3003 - Using Imagick::trimImage:
  • Example#3004 - Imagick::uniqueImageColors
  • Example#3005 - Imagick::unsharpMaskImage
  • Example#3006 - Imagick::vignetteImage
  • Example#3007 - WaveImage can be quite slow Imagick::waveImage
  • Example#3008 - Imagick::whiteThresholdImage
  • Example#3009 - ImagickDraw::affine example
  • Example#3010 - ImagickDraw::arc example
  • Example#3011 - ImagickDraw::bezier example
  • Example#3012 - ImagickDraw::circle example
  • Example#3013 - ImagickDraw::composite example
  • Example#3014 - ImagickDraw::ellipse example
  • Example#3015 - ImagickDraw::line example
  • Example#3016 - ImagickDraw::matte example
  • Example#3017 - ImagickDraw::pathCurveToQuadraticBezierAbsolute example
  • Example#3018 - ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute example
  • Example#3019 - ImagickDraw::pathCurveToQuadraticBezierSmoothRelative example
  • Example#3020 - ImagickDraw::pathStart example
  • Example#3021 - ImagickDraw::point example
  • Example#3022 - ImagickDraw::polygon example
  • Example#3023 - ImagickDraw::polyline example
  • Example#3024 - ImagickDraw::popDefs example
  • Example#3025 - ImagickDraw::push example
  • Example#3026 - ImagickDraw::pushPattern example
  • Example#3027 - ImagickDraw::rectangle example
  • Example#3028 - ImagickDraw::rotate example
  • Example#3029 - ImagickDraw::roundRectangle example
  • Example#3030 - ImagickDraw::scale example
  • Example#3031 - ImagickDraw::setClipPath example
  • Example#3032 - ImagickDraw::setClipRule example
  • Example#3033 - ImagickDraw::setClipUnits example
  • Example#3034 - ImagickDraw::setFillAlpha example
  • Example#3035 - ImagickDraw::setFillColor
  • Example#3036 - ImagickDraw::setFillOpacity
  • Example#3037 - ImagickDraw::setFillRule example
  • Example#3038 - ImagickDraw::setFont example
  • Example#3039 - ImagickDraw::setFontFamily example
  • Example#3040 - ImagickDraw::setFontSize example
  • Example#3041 - ImagickDraw::setFontStretch example
  • Example#3042 - ImagickDraw::setFontStyle example
  • Example#3043 - ImagickDraw::setFontWeight example
  • Example#3044 - ImagickDraw::setGravity example
  • Example#3045 - ImagickDraw::setStrokeAlpha example
  • Example#3046 - ImagickDraw::setStrokeAntialias example
  • Example#3047 - ImagickDraw::setStrokeColor example
  • Example#3048 - ImagickDraw::setStrokeDashArray example
  • Example#3049 - ImagickDraw::setStrokeDashOffset example
  • Example#3050 - ImagickDraw::setStrokeLineCap example
  • Example#3051 - ImagickDraw::setStrokeLineJoin example
  • Example#3052 - ImagickDraw::setStrokeMiterLimit example
  • Example#3053 - ImagickDraw::setStrokeOpacity example
  • Example#3054 - ImagickDraw::setStrokeWidth example
  • Example#3055 - ImagickDraw::setTextAlignment example
  • Example#3056 - ImagickDraw::setTextAntialias example
  • Example#3057 - ImagickDraw::setTextDecoration example
  • Example#3058 - ImagickDraw::setTextUnderColor example
  • Example#3059 - ImagickDraw::setVectorGraphics example
  • Example#3060 - ImagickDraw::setViewBox example
  • Example#3061 - ImagickDraw::skewX example
  • Example#3062 - ImagickDraw::skewY example
  • Example#3063 - ImagickDraw::translate example
  • Example#3064 - ImagickPixel::construct
  • Example#3065 - Basic Imagick::getColor usage
  • Example#3066 - Basic Imagick::getColorAsString usage
  • Example#3067 - ImagickPixel getColorCount
  • Example#3068 - Basic Imagick::getColorValue usage
  • Example#3069 - ImagickPixel::getColorValueQuantum
  • Example#3070 - Basic Imagick::getHSL example
  • Example#3071 - ImagickPixel::isSimilar
  • Example#3072 - ImagickPixel::setColor
  • Example#3073 - Basic Imagick::setColorValue usage
  • Example#3074 - ImagickPixel::setColorValueQuantum
  • Example#3075 - Use ImagickPixel::setHSL to modify a color
  • Example#3076 - ImagickPixelIterator::clear
  • Example#3077 - ImagickPixelIterator::construct
  • Example#3078 - ImagickPixelIterator::getNextIteratorRow
  • Example#3079 - ImagickPixelIterator::resetIterator
  • Example#3080 - ImagickPixelIterator::setIteratorRow
  • Example#3081 - ImagickKernel::addKernel
  • Example#3082 - ImagickKernel::addUnityKernel
  • Example#3083 - ImagickKernel::addUnityKernel
  • Example#3084 - ImagickKernel::fromBuiltin
  • Example#3085 - ImagickKernel::fromMatrix
  • Example#3086 - ImagickKernel::getMatrix
  • Example#3087 - ImagickKernel::scale
  • Example#3088 - ImagickKernel::separate
  • Example#3089 - imap_append example
  • Example#3090 - imap_check example
  • Example#3091 - imap_createmailbox example
  • Example#3092 - imap_delete example
  • Example#3093 - imap_fetch_overview example
  • Example#3094 - imap_gc example
  • Example#3095 - imap_get_quota example
  • Example#3096 - imap_get_quota 4.3 or greater example
  • Example#3097 - imap_get_quotaroot example
  • Example#3098 - imap_getacl example
  • Example#3099 - imap_getmailboxes example
  • Example#3100 - imap_is_open example
  • Example#3101 - imap_list example
  • Example#3102 - imap_mail_compose example
  • Example#3103 - imap_mailboxmsginfo example
  • Example#3104 - imap_mime_header_decode example
  • Example#3105 - Different use of imap_open
  • Example#3106 - imap_open example
  • Example#3107 - imap_ping Example
  • Example#3108 - imap_reopen example
  • Example#3109 - imap_rfc822_parse_adrlist example
  • Example#3110 - imap_rfc822_write_address example
  • Example#3111 - imap_search example
  • Example#3112 - imap_set_quota example
  • Example#3113 - imap_setflag_full example
  • Example#3114 - imap_status example
  • Example#3115 - imap_thread Example
  • Example#3116 - imap_timeout example
  • Example#3117 - Basic imap_utf8 Usage
  • Example#3118 - Calculando o hash e inscrevendo um usuário
  • Example#3119 - Enviando e-mail.
  • Example#3120 - Enviando e-mail com cabeçalhos extras.
  • Example#3121 - Enviando e-mail com cabeçalhos extras no formato array
  • Example#3122 - Enviando e-mail com um parâmetro de linha de comando adicional.
  • Example#3123 - Enviando e-mail HTML
  • Example#3124 - mailparse_determine_best_xfer_encoding example
  • Example#3125 - mailparse_rfc822_parse_addresses example
  • Example#3126 - mailparse_stream_encode example
  • Example#3127 - mailparse_uudecode_all example
  • Example#3128 - Exemplo bcadd
  • Example#3129 - Exemplo da bccomp
  • Example#3130 - Exemplo da bcdiv
  • Example#3131 - Exemplo de bcmod
  • Example#3132 - Exemplo de bcmod com decimais
  • Example#3133 - Exemplo da bcmul
  • Example#3134 - Exemplo de bcmul com scale
  • Example#3135 - Exemplo da bcpow
  • Example#3136 - Exemplo bcpow com scale
  • Example#3137 - Exemplo da bcscale
  • Example#3138 - Exemplo de bcsqrt
  • Example#3139 - Exemplo de bcsub
  • Example#3140 - Função fatorial usando GMP
  • Example#3141 - Exemplo de gmp_abs
  • Example#3142 - Exemplo de gmp_add
  • Example#3143 - Exemplo de gmp_and
  • Example#3144 - gmp_clrbit example
  • Example#3145 - Exemplo de gmp_cmp
  • Example#3146 - Exemplo gmp_com
  • Example#3147 - gmp_div_q example
  • Example#3148 - Division of GMP numbers
  • Example#3149 - gmp_div_r example
  • Example#3150 - Exemplo gmp_divexact
  • Example#3151 - gmp_export example
  • Example#3152 - gmp_fact example
  • Example#3153 - Exemplo de gmp_gcd
  • Example#3154 - Resolvendo uma equação linear de Diophantine
  • Example#3155 - Exemplo de gmp_hamdist
  • Example#3156 - gmp_import example
  • Example#3157 - Creating GMP number
  • Example#3158 - Exemplo gmp_intval
  • Example#3159 - gmp_invert example
  • Example#3160 - Exemplo de gmp_jacobi
  • Example#3161 - Exemplo da gmp_legendre
  • Example#3162 - Exemplo de gmp_mod
  • Example#3163 - Exemplo da gmp_mul
  • Example#3164 - Exemplo de gmp_neg
  • Example#3165 - Exemplo de gmp_nextprime
  • Example#3166 - Exemplo de gmp_or
  • Example#3167 - gmp_perfect_square example
  • Example#3168 - Exemplo de gmp_popcount
  • Example#3169 - Exemplo gmp_pow
  • Example#3170 - Exemplo de gmp_powm
  • Example#3171 - gmp_prob_prime example
  • Example#3172 - gmp_random_bits example
  • Example#3173 - gmp_random_range example
  • Example#3174 - gmp_random_seed example
  • Example#3175 - gmp_random example
  • Example#3176 - gmp_scan0 example
  • Example#3177 - gmp_scan1 example
  • Example#3178 - gmp_setbit example - 0 index
  • Example#3179 - gmp_setbit example - 1 index
  • Example#3180 - gmp_setbit example - clearing a bit
  • Example#3181 - Exemplo de gmp_sign
  • Example#3182 - Exemplo de gmp_sqrt
  • Example#3183 - Exemplo de gmp_sqrtrem
  • Example#3184 - Convertendo um número GMP para uma string
  • Example#3185 - Exemplo da gmp_sub
  • Example#3186 - gmp_testbit example
  • Example#3187 - Exemplo de gmp_xor
  • Example#3188 - Exemplo de abs
  • Example#3189 - Exemplo de base_convert
  • Example#3190 - Exemplo de bindec
  • Example#3191 - bindec interpreta a entrada como inteiros sem sinal
  • Example#3192 - Exemplo de ceil
  • Example#3193 - Exemplo de cos
  • Example#3194 - Exemplo de decbin
  • Example#3195 - Exemplo de dechex
  • Example#3196 - Exemplo de dechex com inteiros grandes
  • Example#3197 - Exemplo de decoct
  • Example#3198 - Exemplo de deg2rad
  • Example#3199 - Exemplo de exp
  • Example#3200 - Usando fdiv
  • Example#3201 - Exemplos de floor
  • Example#3202 - Usando fmod
  • Example#3203 - Exemplo de hexdec
  • Example#3204 - Exemplo de intdiv
  • Example#3205 - Exemplo de is_finite
  • Example#3206 - Exemplo de is_infinite
  • Example#3207 - Exemplo de is_nan
  • Example#3208 - Exemplos de max
  • Example#3209 - Exemplos de min
  • Example#3210 - Exemplo da octdec
  • Example#3211 - Exemplo de pi
  • Example#3212 - Alguns exemplos de pow
  • Example#3213 - Exemplo de rad2deg
  • Example#3214 - Exemplos de round
  • Example#3215 - Como precision afeta um float
  • Example#3216 - Exemplos de mode
  • Example#3217 - Exemplos de mode com precision
  • Example#3218 - Exemplo da sin
  • Example#3219 - Exemplo da sqrt
  • Example#3220 - Exemplo da tan
  • Example#3221 - Evaluating a FDF document
  • Example#3222 - Adding JavaScript code to a FDF
  • Example#3223 - Populating a PDF document
  • Example#3224 - Storing an uploaded file
  • Example#3225 - Detecting all fieldnames in a FDF
  • Example#3226 - Accessing the form data
  • Example#3227 - Accessing the form data
  • Example#3228 - Retrieving FDF as a string
  • Example#3229 - Passing FDF data to a second form
  • Example#3230 - gnupg clearsign example (procedural)
  • Example#3231 - gnupg clearsign example (OO)
  • Example#3232 - keylistiterator
  • Example#3233 - Procedural gnupg_adddecryptkey example
  • Example#3234 - OO gnupg_adddecryptkey example
  • Example#3235 - Procedural gnupg_addencryptkey example
  • Example#3236 - OO gnupg_addencryptkey example
  • Example#3237 - Procedural gnupg_addsignkey example
  • Example#3238 - OO gnupg_addsignkey example
  • Example#3239 - Procedural gnupg_cleardecryptkeys example
  • Example#3240 - OO gnupg_cleardecryptkeys example
  • Example#3241 - Procedural gnupg_clearencryptkeys example
  • Example#3242 - OO gnupg_clearencryptkeys example
  • Example#3243 - Procedural gnupg_clearsignkeys example
  • Example#3244 - OO gnupg_clearsignkeys example
  • Example#3245 - Procedural gnupg_decrypt example
  • Example#3246 - OO gnupg_decrypt example
  • Example#3247 - Procedural gnupg_decryptverify example
  • Example#3248 - OO gnupg_decryptverify example
  • Example#3249 - Procedural gnupg_deletekey example
  • Example#3250 - OO gnupg_deletekey example
  • Example#3251 - Procedural gnupg_encrypt example
  • Example#3252 - OO gnupg_encrypt example
  • Example#3253 - Procedural gnupg_encryptsign example
  • Example#3254 - OO gnupg_encryptsign example
  • Example#3255 - Procedural gnupg_export example
  • Example#3256 - OO gnupg_export example
  • Example#3257 - Procedural gnupg_getengineinfo example
  • Example#3258 - OO gnupg_getengineinfo example
  • Example#3259 - Procedural gnupg_geterror example
  • Example#3260 - OO gnupg_geterror example
  • Example#3261 - Procedural gnupg_geterrorinfo example
  • Example#3262 - OO gnupg_geterrorinfo example
  • Example#3263 - Procedural gnupg_getprotocol example
  • Example#3264 - OO gnupg_getprotocol example
  • Example#3265 - Procedural gnupg_gettrustlist example
  • Example#3266 - OO gnupg_gettrustlist example
  • Example#3267 - Procedural gnupg_import example
  • Example#3268 - OO gnupg_import example
  • Example#3269 - Procedural gnupg_init example with default setting
  • Example#3270 - Procedural gnupg_init example with overriden file name and home dir
  • Example#3271 - OO gnupg initializer example with default setting
  • Example#3272 - OO gnupg initializer example with overriden file name and home dir
  • Example#3273 - Procedural gnupg_keyinfo example
  • Example#3274 - OO gnupg_keyinfo example
  • Example#3275 - Procedural gnupg_listsignatures example
  • Example#3276 - OO gnupg_listsignatures example
  • Example#3277 - Procedural gnupg_setarmor example
  • Example#3278 - OO gnupg_setarmor example
  • Example#3279 - Procedural gnupg_seterrormode example
  • Example#3280 - OO gnupg_seterrormode example
  • Example#3281 - Procedural gnupg_setsignmode example
  • Example#3282 - OO gnupg_setsignmode example
  • Example#3283 - Procedural gnupg_sign example
  • Example#3284 - OO gnupg_sign example
  • Example#3285 - Procedural gnupg_verify example
  • Example#3286 - OO gnupg_verify example
  • Example#3287 - Creating and using a pattern
  • Example#3288 - Creating and using a template
  • Example#3289 - Hyphennate a text
  • Example#3290 - Drawing a rectangle
  • Example#3291 - Creating and using a spot color
  • Example#3292 - Rotation of the coordinate system
  • Example#3293 - Placing text at a given position
  • Example#3294 - Drawing a dashed line
  • Example#3295 - Translation of the coordinate system
  • Example#3296 - A rpmdbinfo example
  • Example#3297 - Searching for the package owning a file
  • Example#3298 - A rpminfo example
  • Example#3299 - example
  • Example#3300 - example
  • Example#3301 - example
  • Example#3302 - example
  • Example#3303 - example
  • Example#3304 - example
  • Example#3305 - example
  • Example#3306 - example
  • Example#3307 - example
  • Example#3308 - example
  • Example#3309 - example
  • Example#3310 - example
  • Example#3311 - example
  • Example#3312 - example
  • Example#3313 - example
  • Example#3314 - example
  • Example#3315 - example
  • Example#3316 - example
  • Example#3317 - example
  • Example#3318 - Incorrect requests
  • Example#3319 - Calling request from a request callback
  • Example#3320 - Calling request from a request callback
  • Example#3321 - Using eio with libevent
  • Example#3322 - Cancelling a request
  • Example#3323 - Calling eio_chmod
  • Example#3324 - Making a custom request
  • Example#3325 - Grouping requests
  • Example#3326 - Using eio with libevent extension
  • Example#3327 - Using eio with event extension
  • Example#3328 - eio_cancel example
  • Example#3329 - eio_custom example
  • Example#3330 - eio_event_loop example
  • Example#3331 - eio_lstat example
  • Example#3332 - Using eio with libevent
  • Example#3333 - Grouping requests
  • Example#3334 - eio_grp example
  • Example#3335 - eio_link example
  • Example#3336 - eio_lstat example
  • Example#3337 - eio_mkdir example
  • Example#3338 - eio_mknod example
  • Example#3339 - eio_nreqs example
  • Example#3340 - eio_open example
  • Example#3341 - eio_poll example
  • Example#3342 - eio_read example
  • Example#3343 - eio_readdir example
  • Example#3344 - eio_readlink example
  • Example#3345 - eio_realpath example
  • Example#3346 - eio_rename example
  • Example#3347 - eio_rmdir example
  • Example#3348 - eio_stat example
  • Example#3349 - eio_statvfs example
  • Example#3350 - eio_symlink example
  • Example#3351 - Simple timers
  • Example#3352 - Periodic timer. Tick each 10.5 seconds
  • Example#3353 - Periodic timer. Use reschedule callback
  • Example#3354 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3355 - Wait until STDIN is readable
  • Example#3356 - Use some async I/O to access a socket
  • Example#3357 - Embedding one loop into another
  • Example#3358 - Embedding loop created with kqueue backend into the default loop
  • Example#3359 - Handle SIGTERM signal
  • Example#3360 - Monitor changes of /var/log/messages
  • Example#3361 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3362 - Process status changes
  • Example#3363 - Using reschedule callback
  • Example#3364 - Embedding loop created with kqueue backend into the default loop
  • Example#3365 - Embedding one loop into another
  • Example#3366 - Embedding loop created with kqueue backend into the default loop
  • Example#3367 - Embedding loop created with kqueue backend into the default loop
  • Example#3368 - Periodic timer. Use reschedule callback
  • Example#3369 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#3370 - Hourly watcher
  • Example#3371 - Handle SIGTERM signal
  • Example#3372 - Monitor changes of /var/log/messages
  • Example#3373 - Monitor changes of /var/log/messages
  • Example#3374 - Simple timers
  • Example#3375 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#3376 - Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.
  • Example#3377 - Expect Usage Example
  • Example#3378 - Another Expect Usage Example
  • Example#3379 - expect_expectl example
  • Example#3380 - expect_popen example
  • Example#3381 - Process Control Example
  • Example#3382 - pcntl_fork example
  • Example#3383 - pcntl_rfork example
  • Example#3384 - pcntl_signal_dispatch example
  • Example#3385 - pcntl_signal_get_handler example
  • Example#3386 - pcntl_signal example
  • Example#3387 - pcntl_sigprocmask example
  • Example#3388 - pcntl_sigwaitinfo example
  • Example#3389 - posix_access example
  • Example#3390 - posix_ctermid example
  • Example#3391 - posix_eaccess example
  • Example#3392 - posix_fpathconf example
  • Example#3393 - posix_get_last_error example
  • Example#3394 - posix_getcwd example
  • Example#3395 - posix_getegid example
  • Example#3396 - posix_geteuid example
  • Example#3397 - posix_getgid example
  • Example#3398 - Example use of posix_getgrgid
  • Example#3399 - Example use of posix_getgrnam
  • Example#3400 - Example use of posix_getgroups
  • Example#3401 - Example use of posix_getlogin
  • Example#3402 - Example use of posix_getpgid
  • Example#3403 - Example use of posix_getpid
  • Example#3404 - Example use of posix_getppid
  • Example#3405 - Example use of posix_getpwnam
  • Example#3406 - Example use of posix_getpwuid
  • Example#3407 - Example use of posix_getrlimit
  • Example#3408 - Example use of posix_getsid
  • Example#3409 - Example use of posix_getuid
  • Example#3410 - A posix_mknod example
  • Example#3411 - posix_pathconf example
  • Example#3412 - posix_setegid example
  • Example#3413 - posix_setgid example
  • Example#3414 - posix_setuid example
  • Example#3415 - posix_strerror example
  • Example#3416 - posix_sysconf example
  • Example#3417 - Example use of posix_times
  • Example#3418 - Example use of posix_uname
  • Example#3419 - Exemplo de escapeshellarg
  • Example#3420 - Exemplo de escapeshellcmd
  • Example#3421 - Um exemplo exec
  • Example#3422 - Usando proc_nice para definir a prioridade do processo para alta
  • Example#3423 - A proc_open example
  • Example#3424 - proc_open quirk on Windows
  • Example#3425 - Um exemplo de shell_exec
  • Example#3426 - Exemplo de system
  • Example#3427 - Example showing Future as return value
  • Example#3428 - Example showing Future as synchronization point
  • Example#3429 - Fetch a chunk of the property table
  • Example#3430 - Counting the properties of an object
  • Example#3431 - Runtime inheritance
  • Example#3432 - Detect the state of the referenced object
  • Example#3433 - Detect the state of the referenced object
  • Example#3434 - Merging into the property table of a threaded object
  • Example#3435 - Notifications and Waiting
  • Example#3436 - Notifications and Waiting
  • Example#3437 - Popping the last item from the property table of a threaded object
  • Example#3438 - Shifting the first item from the property table of a threaded object
  • Example#3439 - Synchronizing
  • Example#3440 - Notifications and Waiting
  • Example#3441 - Return the identity of the Thread or Process that created the referenced Thread
  • Example#3442 - Return the currently executing Thread
  • Example#3443 - Return the identity of the currently executing Thread
  • Example#3444 - Return the identity of the referenced Thread
  • Example#3445 - Detect the state of the referenced Thread
  • Example#3446 - Tell if the referenced Thread was started
  • Example#3447 - Join with the referenced Thread
  • Example#3448 - Starting Threads
  • Example#3449 - A basic example of Worker::collect
  • Example#3450 - A basic example of Worker::getStacked
  • Example#3451 - Detect the state of a worker
  • Example#3452 - Shutdown the referenced worker
  • Example#3453 - Stacking a task for execution onto a worker
  • Example#3454 - Removing objects from the stack of Workers
  • Example#3455 - A basic example of Pool::collect
  • Example#3456 - Creating Pools
  • Example#3457 - Shutting down a pool
  • Example#3458 - Submitting Tasks
  • Example#3459 - Submitting tasks to a specific worker
  • Example#3460 - New immutability semantics of Threaded
  • Example#3461 - Volatile use-case
  • Example#3462 - Visão Geral de Operações de Memória Compartilhada
  • Example#3463 - Fechando um bloco de memória compartilhada
  • Example#3464 - Deletando um bloco de memória compartilhada
  • Example#3465 - Create a new shared memory block
  • Example#3466 - Reading shared memory block
  • Example#3467 - Pegando o tamanho do bloco de memória compartilhada
  • Example#3468 - Writing to shared memory block
  • Example#3469 - SyncMutex::__construct named mutex with lock timeout example
  • Example#3470 - SyncMutex::__construct unnamed mutex example
  • Example#3471 - SyncMutex::lock example
  • Example#3472 - SyncMutex::unlock example
  • Example#3473 - SyncSemaphore::__construct example
  • Example#3474 - SyncSemaphore::lock example
  • Example#3475 - SyncSemaphore::unlock example
  • Example#3476 - SyncEvent::__construct example
  • Example#3477 - SyncEvent::fire example
  • Example#3478 - SyncEvent::reset example
  • Example#3479 - SyncEvent::wait example
  • Example#3480 - SyncReaderWriter::__construct example
  • Example#3481 - SyncReaderWriter::readlock example
  • Example#3482 - SyncReaderWriter::readunlock example
  • Example#3483 - SyncReaderWriter::writelock example
  • Example#3484 - SyncReaderWriter::writeunlock example
  • Example#3485 - SyncSharedMemory::__construct example
  • Example#3486 - SyncSharedMemory::first example
  • Example#3487 - SyncSharedMemory::__construct example
  • Example#3488 - SyncSharedMemory::size example
  • Example#3489 - SyncSharedMemory::write example
  • Example#3490 - A geoip_asnum_by_name example
  • Example#3491 - A geoip_continent_code_by_name example
  • Example#3492 - A geoip_country_code_by_name example
  • Example#3493 - A geoip_country_code3_by_name example
  • Example#3494 - A geoip_country_name_by_name example
  • Example#3495 - A geoip_database_info example
  • Example#3496 - A geoip_db_avail example
  • Example#3497 - A geoip_db_filename example
  • Example#3498 - A geoip_db_get_all_info example
  • Example#3499 - A geoip_db_get_all_info example
  • Example#3500 - A geoip_domain_by_name example
  • Example#3501 - A geoip_id_by_name example
  • Example#3502 - A geoip_isp_by_name example
  • Example#3503 - A geoip_netspeedcell_by_name example
  • Example#3504 - A geoip_org_by_name example
  • Example#3505 - A geoip_record_by_name example
  • Example#3506 - A geoip_region_by_name example
  • Example#3507 - A geoip_region_name_by_code example using region code for US/Canada
  • Example#3508 - A geoip_region_name_by_code example using FIPS codes
  • Example#3509 - A geoip_setup_custom_directory example
  • Example#3510 - A geoip_time_zone_by_country_and_region example using region code for US/Canada
  • Example#3511 - A geoip_time_zone_by_country_and_region example using FIPS codes
  • Example#3512 - xor.data file
  • Example#3513 - Simple train
  • Example#3514 - Simple test
  • Example#3515 - fann_create_train_from_callback example
  • Example#3516 - fann_read_train_from_file example
  • Example#3517 - igbinary_serialize example
  • Example#3518 - JsonSerializable::jsonSerialize exemplo retornando um array
  • Example#3519 - JsonSerializable::jsonSerialize exemplo retornando um array associativo
  • Example#3520 - JsonSerializable::jsonSerialize exemplo retornando um int
  • Example#3521 - JsonSerializable::jsonSerialize exemplo retornando uma string
  • Example#3522 - json_decode exemplos
  • Example#3523 - Acessando propriedades inválidas do objeto
  • Example#3524 - erros comuns usando json_decode
  • Example#3525 - erros de depth
  • Example#3526 - json_decode de inteiros grandes
  • Example#3527 - Um exemplo da json_encode
  • Example#3528 - Um exemplo de json_encode mostrando algumas opções em uso
  • Example#3529 - Exemplo com a opção JSON_NUMERIC_CHECK
  • Example#3530 - Exemplo de array sequencial versus não-sequencial
  • Example#3531 - Exemplo com a opção JSON_PRESERVE_ZERO_FRACTION
  • Example#3532 - Exemplo de json_last_error
  • Example#3533 - json_last_error com json_encode
  • Example#3534 - json_last_error and JSON_THROW_ON_ERROR
  • Example#3535 - json_validate examples
  • Example#3536 - simdjson_decode examples
  • Example#3537 - Accessing invalid object properties
  • Example#3538 - common mistakes using simdjson_decode
  • Example#3539 - depth errors
  • Example#3540 - simdjson_decode of large integers
  • Example#3541 - simdjson_decode examples
  • Example#3542 - depth errors
  • Example#3543 - Exemplo da função Lua::assign
  • Example#3544 - Exemplo da função Lua::call
  • Example#3545 - Exemplo da função Lua::eval
  • Example#3546 - Exemplo da função Lua::registerCallback
  • Example#3547 - Exemplo de função LuaClosure::__invoke
  • Example#3548 - Execute some Lua code
  • Example#3549 - Calling a Lua function
  • Example#3550 - Profiling Lua code
  • Example#3551 - Loading code into Lua
  • Example#3552 - Manipulating the usage timer
  • Example#3553 - Registering PHP functions to call from Lua
  • Example#3554 - Calling a Lua function
  • Example#3555 - Calling a Lua function
  • Example#3556 - Usando constant com Constantes
  • Example#3557 - Usando constantcom Casos de Enumeração (a partir do PHP 8.1.0)
  • Example#3558 - Defining Constants
  • Example#3559 - Constants with Reserved Names
  • Example#3560 - Checking Constants
  • Example#3561 - Checking Enum Cases (as of PHP 8.1.0)
  • Example#3562 - eval example - simple text merge
  • Example#3563 - exit example
  • Example#3564 - exit status example
  • Example#3565 - Shutdown functions and destructors run regardless
  • Example#3566 - Listando todas as informações sobre o navegador do usuário
  • Example#3567 - A __halt_compiler example
  • Example#3568 - highlight_string example
  • Example#3569 - hrtime usage
  • Example#3570 - A ignore_user_abort example
  • Example#3571 - pack example
  • Example#3572 - Exemplo de php_strip_whitespace
  • Example#3573 - Basic sapi_windows_generate_ctrl_event Usage
  • Example#3574 - Basic sapi_windows_set_ctrl_handler Usage
  • Example#3575 - sapi_windows_vt100_support default state
  • Example#3576 - sapi_windows_vt100_support changing state
  • Example#3577 - Example usage of VT100 support enabled
  • Example#3578 - sleep example
  • Example#3579 - A sys_getloadavg example
  • Example#3580 - time_nanosleep example
  • Example#3581 - A time_sleep_until example
  • Example#3582 - uniqid Example
  • Example#3583 - unpack example
  • Example#3584 - unpack example with a repeater
  • Example#3585 - unpack example with unnamed keys
  • Example#3586 - usleep example
  • Example#3587 - Random Example
  • Example#3588 - mt_rand example
  • Example#3589 - rand example
  • Example#3590 - random_bytes example
  • Example#3591 - random_int example
  • Example#3592 - Random\Randomizer::__construct example
  • Example#3593 - Random\Randomizer::getBytes example
  • Example#3594 - Random\Randomizer::getBytesFromString example
  • Example#3595 - Generate a random code for multi-factor authentication
  • Example#3596 - Select from a string with a non-uniform distribution
  • Example#3597 - Random\Randomizer::getFloat example
  • Example#3598 - Random\Randomizer::getInt example
  • Example#3599 - Random\Randomizer::nextFloat example
  • Example#3600 - Incorrect scaling using an affine transformation
  • Example#3601 - Random\Randomizer::nextInt example
  • Example#3602 - Random\Randomizer::pickArrayKeys example
  • Example#3603 - Picking random values
  • Example#3604 - Random\Randomizer::__serialize example
  • Example#3605 - Random\Randomizer::shuffleArray example
  • Example#3606 - Random\Randomizer::shuffleBytes example
  • Example#3607 - Byte-wise shuffling breaks Unicode characters
  • Example#3608 - Random\Randomizer::__unserialize example
  • Example#3609 - Random\Engine::generate example
  • Example#3610 - Random\Engine\Mt19937::__construct example
  • Example#3611 - Random\Engine\Mt19937::__debugInfo example
  • Example#3612 - Random\Engine\Mt19937::__serialize example
  • Example#3613 - Random\Engine\Mt19937::__unserialize example
  • Example#3614 - Random\Engine\PcgOneseq128XslRr64::__construct example
  • Example#3615 - Deriving a seed from a string
  • Example#3616 - Random\Engine\PcgOneseq128XslRr64::__debugInfo example
  • Example#3617 - Random\Engine\PcgOneseq128XslRr64::jump example
  • Example#3618 - Randomizer methods may call the engine more than once
  • Example#3619 - Random\Engine\PcgOneseq128XslRr64::__serialize example
  • Example#3620 - Random\Engine\PcgOneseq128XslRr64::__unserialize example
  • Example#3621 - Random\Engine\Xoshiro256StarStar::__construct example
  • Example#3622 - Deriving a seed from a string
  • Example#3623 - Random\Engine\Xoshiro256StarStar::__debugInfo example
  • Example#3624 - Random\Engine\Xoshiro256StarStar::jump example
  • Example#3625 - Random\Engine\Xoshiro256StarStar::jumpLong example
  • Example#3626 - Random\Engine\Xoshiro256StarStar::__serialize example
  • Example#3627 - Random\Engine\Xoshiro256StarStar::__unserialize example
  • Example#3628 - Get and set base path
  • Example#3629 - Get and set logger
  • Example#3630 - Fast write log
  • Example#3631 - Fast count some type of log count value
  • Example#3632 - Acquisit some type of log list
  • Example#3633 - seaslog_get_author example
  • Example#3634 - seaslog_get_version example
  • Example#3635 - SeasLog::alert example
  • Example#3636 - SeasLog::analyzerCount example
  • Example#3637 - SeasLog::analyzerDetail example
  • Example#3638 - SeasLog::closeLoggerStream example
  • Example#3639 - SeasLog::__construct example
  • Example#3640 - SeasLog::critical example
  • Example#3641 - SeasLog::debug example
  • Example#3642 - SeasLog::__destruct example
  • Example#3643 - SeasLog::emergency example
  • Example#3644 - SeasLog::error example
  • Example#3645 - SeasLog::flushBuffer example
  • Example#3646 - SeasLog::getBasePath example
  • Example#3647 - SeasLog::getBuffer example
  • Example#3648 - SeasLog::getBufferEnabled example
  • Example#3649 - SeasLog::getDatetimeFormat example
  • Example#3650 - SeasLog::getLastLogger example
  • Example#3651 - SeasLog::getRequestID example
  • Example#3652 - SeasLog::getRequestVariable example
  • Example#3653 - SeasLog::info example
  • Example#3654 - SeasLog::log example
  • Example#3655 - SeasLog::notice example
  • Example#3656 - SeasLog::setBasePath example
  • Example#3657 - SeasLog::setDatetimeFormat example
  • Example#3658 - SeasLog::setLogger example
  • Example#3659 - SeasLog::setRequestID example
  • Example#3660 - SeasLog::setRequestVariable example
  • Example#3661 - SeasLog::warning example
  • Example#3662 - SplStack example
  • Example#3663 - SplQueue example
  • Example#3664 - Efficiently handling tasks with SplQueue
  • Example#3665 - SplFixedArray usage example
  • Example#3666 - SplFixedArray::__construct example
  • Example#3667 - SplFixedArray::count example
  • Example#3668 - SplFixedArray::fromArray example
  • Example#3669 - SplFixedArray::getSize example
  • Example#3670 - SplFixedArray::setSize example
  • Example#3671 - SplFixedArray::toArray example
  • Example#3672 - SplObjectStorage as a set
  • Example#3673 - SplObjectStorage as a map
  • Example#3674 - SplObjectStorage::addAll example
  • Example#3675 - SplObjectStorage::attach example
  • Example#3676 - SplObjectStorage::contains example
  • Example#3677 - SplObjectStorage::count example
  • Example#3678 - SplObjectStorage::current example
  • Example#3679 - SplObjectStorage::detach example
  • Example#3680 - SplObjectStorage::getHash example
  • Example#3681 - SplObjectStorage::getInfo example
  • Example#3682 - SplObjectStorage::key example
  • Example#3683 - SplObjectStorage::next example
  • Example#3684 - SplObjectStorage::offsetExists example
  • Example#3685 - SplObjectStorage::offsetGet example
  • Example#3686 - SplObjectStorage::offsetSet example
  • Example#3687 - SplObjectStorage::offsetUnset example
  • Example#3688 - SplObjectStorage::removeAll example
  • Example#3689 - SplObjectStorage::removeAllExcept example
  • Example#3690 - SplObjectStorage::rewind example
  • Example#3691 - SplObjectStorage::serialize example
  • Example#3692 - SplObjectStorage::setInfo example
  • Example#3693 - SplObjectStorage::unserialize example
  • Example#3694 - SplObjectStorage::valid example
  • Example#3695 - AppendIterator::append example
  • Example#3696 - Iterating AppendIterator with foreach
  • Example#3697 - Iterating AppendIterator with the AppendIterator API
  • Example#3698 - AppendIterator.getIteratorIndex basic example
  • Example#3699 - AppendIterator::key basic example
  • Example#3700 - Exemplo de ArrayIterator::current
  • Example#3701 - Exemplo de ArrayIterator::key
  • Example#3702 - Exemplo de ArrayIterator::next
  • Example#3703 - Exemplo de ArrayIterator::rewind
  • Example#3704 - Exemplo de ArrayIterator::valid
  • Example#3705 - CachingIterator::getCache example
  • Example#3706 - Available callback arguments
  • Example#3707 - Callback basic examples
  • Example#3708 - A DirectoryIterator::__construct example
  • Example#3709 - A DirectoryIterator::current example
  • Example#3710 - Exemplo do DirectoryIterator::getBasename
  • Example#3711 - Exemplo de DirectoryIterator::getExtension
  • Example#3712 -
  • Example#3713 - A DirectoryIterator::getFilename example
  • Example#3714 - A DirectoryIterator::isDot example
  • Example#3715 - A DirectoryIterator::key example
  • Example#3716 - DirectoryIterator::next example
  • Example#3717 - DirectoryIterator::rewind example
  • Example#3718 - Exemplo do DirectoryIterator::seek
  • Example#3719 - Exemplo do DirectoryIterator::__toString
  • Example#3720 - A DirectoryIterator::valid example
  • Example#3721 - FilesystemIterator::__construct example
  • Example#3722 - FilesystemIterator::current example
  • Example#3723 - FilesystemIterator::key example
  • Example#3724 - FilesystemIterator::next example
  • Example#3725 - FilesystemIterator::rewind example
  • Example#3726 - FilesystemIterator::key example
  • Example#3727 - FilterIterator::accept example
  • Example#3728 - GlobIterator example
  • Example#3729 - GlobIterator::count example
  • Example#3730 - InfiniteIterator::__construct example
  • Example#3731 - LimitIterator usage example
  • Example#3732 - LimitIterator::__construct example
  • Example#3733 - Exemplos de LimitIterator::getPosition
  • Example#3734 - Iterating a MultipleIterator
  • Example#3735 - NoRewindIterator::__construct example
  • Example#3736 - NoRewindIterator::rewind example
  • Example#3737 - RecursiveArrayIterator::getChildren example
  • Example#3738 - RecursiveArrayIterator::hasChildren example
  • Example#3739 - Available callback arguments
  • Example#3740 - Recursive callback basic example
  • Example#3741 - RecursiveCallbackFilterIterator::hasChildren basic usage
  • Example#3742 - RecursiveDirectoryIterator example
  • Example#3743 - getSubPath example
  • Example#3744 - getSubPathname example
  • Example#3745 - Basic RecursiveFilterIterator example
  • Example#3746 - RecursiveFilterIterator example
  • Example#3747 - Iterating a RecursiveIteratorIterator
  • Example#3748 - RecursiveRegexIterator::__construct example
  • Example#3749 - RecursiveRegexIterator::getChildren example
  • Example#3750 - RecursiveRegexIterator::hasChildren example
  • Example#3751 - RegexIterator::accept example
  • Example#3752 - RegexIterator::__construct example
  • Example#3753 - RegexIterator::getFlags example
  • Example#3754 - RegexIterator::getMode example
  • Example#3755 - RegexIterator::getPregFlags example
  • Example#3756 - RegexIterator::setFlags example
  • Example#3757 - RegexIterator::setMode example
  • Example#3758 - RegexIterator::setPregFlags example
  • Example#3759 - Countable::count example
  • Example#3760 - Basic usage
  • Example#3761 - SeekableIterator::seek example
  • Example#3762 - class_implements example
  • Example#3763 - class_parents example
  • Example#3764 - class_uses example
  • Example#3765 - iterator_apply example
  • Example#3766 - iterator_count example
  • Example#3767 - iterator_count modifies position
  • Example#3768 - iterator_count in foreach loops
  • Example#3769 - Exemplo da iterator_to_array
  • Example#3770 - spl_autoload_extensions example
  • Example#3771 - spl_autoload_register as a replacement for an __autoload function
  • Example#3772 - spl_autoload_register example where the class is not loaded
  • Example#3773 - The identifier will be provided without the leading backslash
  • Example#3774 - Exemplo despl_classes
  • Example#3775 - A spl_object_hash example
  • Example#3776 - A spl_object_id example
  • Example#3777 - SplFileInfo::__construct example
  • Example#3778 - SplFileInfo::getATime example
  • Example#3779 - SplFileInfo::getBasename example
  • Example#3780 - SplFileInfo::getCTime example
  • Example#3781 - SplFileInfo::getExtension example
  • Example#3782 -
  • Example#3783 - SplFileInfo::getFilename example
  • Example#3784 - SplFileInfo::getGroup example
  • Example#3785 - SplFileInfo::getLinkTarget example
  • Example#3786 - SplFileInfo::getMTime example
  • Example#3787 - SplFileInfo::getOwner example
  • Example#3788 - SplFileInfo::getPath example
  • Example#3789 - SplFileInfo::getPathInfo example
  • Example#3790 - SplFileInfo::getPathname example
  • Example#3791 - SplFileInfo::getPerms example
  • Example#3792 - SplFileInfo::getRealPath example
  • Example#3793 - SplFileInfo::getSize example
  • Example#3794 - SplFileInfo::getType example
  • Example#3795 - SplFileInfo::isDir example
  • Example#3796 - SplFileInfo::isExecutable example
  • Example#3797 - SplFileInfo::isFile example
  • Example#3798 - SplFileInfo::isLink example
  • Example#3799 - SplFileInfo::isReadable example
  • Example#3800 - SplFileInfo::isWriteable example
  • Example#3801 - SplFileInfo::openFile example
  • Example#3802 - SplFileInfo::setFileClass example
  • Example#3803 - SplFileInfo::setFileClass example
  • Example#3804 - SplFileInfo::__toString example
  • Example#3805 - SplFileObject::__construct example
  • Example#3806 - SplFileObject::current example
  • Example#3807 - SplFileObject::eof example
  • Example#3808 - SplFileObject::fflush example
  • Example#3809 - SplFileObject::fgetc example
  • Example#3810 - SplFileObject::fgetcsv example
  • Example#3811 - SplFileObject::READ_CSV example
  • Example#3812 - SplFileObject::fgets example
  • Example#3813 - SplFileObject::fgetss example
  • Example#3814 - SplFileObject::flock example
  • Example#3815 - SplFileObject::fpassthru example
  • Example#3816 - SplFileObject::fputcsv example
  • Example#3817 - SplFileObject::fread example
  • Example#3818 - SplFileObject::fscanf example
  • Example#3819 - SplFileObject::fseek example
  • Example#3820 - SplFileObject::fstat example
  • Example#3821 - SplFileObject::ftell example
  • Example#3822 - SplFileObject::ftruncate example
  • Example#3823 - SplFileObject::fwrite example
  • Example#3824 - SplFileObject::getCsvControl example
  • Example#3825 - SplFileObject::getFlags example
  • Example#3826 - SplFileObject::getMaxLineLen example
  • Example#3827 - SplFileObject::key example
  • Example#3828 - SplFileObject::key example with SplFileObject::setMaxLineLen
  • Example#3829 - SplFileObject::next example
  • Example#3830 - SplFileObject::rewind example
  • Example#3831 - SplFileObject::seek example
  • Example#3832 - SplFileObject::setCsvControl example
  • Example#3833 - SplFileObject::setFlags example
  • Example#3834 - SplFileObject::setMaxLineLen example
  • Example#3835 - SplFileObject::valid example
  • Example#3836 - SplTempFileObject example
  • Example#3837 - ArrayObject::append example
  • Example#3838 - ArrayObject::asort example
  • Example#3839 - ArrayObject::__construct example
  • Example#3840 - ArrayObject::count example
  • Example#3841 - ArrayObject::exchangeArray example
  • Example#3842 - ArrayObject::getArrayCopy example
  • Example#3843 - ArrayObject::getFlags example
  • Example#3844 - Exemplo de ArrayObject::getIterator
  • Example#3845 - ArrayObject::getIteratorClass example
  • Example#3846 - ArrayObject::ksort example
  • Example#3847 - ArrayObject::natcasesort example
  • Example#3848 - ArrayObject::natsort example
  • Example#3849 - ArrayObject::offsetExists example
  • Example#3850 - ArrayObject::offsetGet example
  • Example#3851 - ArrayObject::offsetSet example
  • Example#3852 - ArrayObject::offsetUnset example
  • Example#3853 - ArrayObject::serialize example
  • Example#3854 - ArrayObject::setFlags example
  • Example#3855 - ArrayObject::setIteratorClass example
  • Example#3856 - ArrayObject::uasort example
  • Example#3857 - ArrayObject::uksort example
  • Example#3858 - Usando file_get_contents para obter dados de fontes múltiplas
  • Example#3859 - Realizando uma requisição POST para um servidor https
  • Example#3860 - Escrevendo dados em um arquivo compactado
  • Example#3861 - Um Fluxo para ler/escrever variáveis globais
  • Example#3862 - Listando arquivos de arquivadores tar
  • Example#3863 - Exemplos de stream_bucket_prepend
  • Example#3864 - Usando a função stream_context_create
  • Example#3865 - Usando stream_context_get_default
  • Example#3866 - Exemplo de stream_context_get_options
  • Example#3867 - Exemplo de stream_context_get_params
  • Example#3868 - Exemplo de stream_context_set_default
  • Example#3869 - Exemplo de stream_context_set_options
  • Example#3870 - Um exemplo de stream_copy_to_stream
  • Example#3871 - Controlando onde os filtros são aplicados
  • Example#3872 - Filtro para converter para maiúsculas os caracteres no fluxo foo-bar.txt
  • Example#3873 - Registrando uma classe de filtro genérica para combinar com múltiplos nomes de filtro.
  • Example#3874 - Refiltrando um fluxo dinamicamente
  • Example#3875 - Exemplo de stream_get_contents
  • Example#3876 - Usando stream_get_filters
  • Example#3877 - Exemplo de stream_get_meta_data usando fopen com http
  • Example#3878 - Exemplo de stream_get_meta_data usando stream_socket_client com https
  • Example#3879 - Usando stream_get_transports
  • Example#3880 - Exemplo de stream_get_wrappers
  • Example#3881 - Verificando a existência de um empacotador de fluxo
  • Example#3882 - Exemplo de stream_is_local
  • Example#3883 - Exemplo de stream_isatty
  • Example#3884 - Exemplo de stream_notification_callback
  • Example#3885 - Barra de progresso simples para cliente de download em linha de comando
  • Example#3886 - stream_resolve_include_path example
  • Example#3887 - Exemplo de stream_select
  • Example#3888 - Exemplo de stream_set_timeout
  • Example#3889 - Exemplo de stream_set_write_buffer
  • Example#3890 - Exemplo de stream_socket_client
  • Example#3891 - Usando conexão UDP
  • Example#3892 - Exemplo de stream_socket_enable_crypto
  • Example#3893 - Um exemplo de stream_socket_pair
  • Example#3894 - Exemplo de stream_socket_recvfrom
  • Example#3895 - Exemplo de stream_socket_sendto
  • Example#3896 - Usando sockets de servidor TCP
  • Example#3897 - Usando sockets de servidor usando UDP
  • Example#3898 - Um exemplo de stream_socket_shutdown
  • Example#3899 - Como registrar um empacotador de fluxo
  • Example#3900 - Básico uso do Tidy
  • Example#3901 - tidy::getBody example
  • Example#3902 - tidy::cleanrepair example
  • Example#3903 - tidy::__construct example
  • Example#3904 - tidy::diagnose example
  • Example#3905 - tidy_get_error_buffer example
  • Example#3906 - tidy::getConfig example
  • Example#3907 - tidy_getopt example
  • Example#3908 - Print all options along with their documentation and default value
  • Example#3909 - tidy::getStatus example
  • Example#3910 - tidy::head example
  • Example#3911 - tidy::html example
  • Example#3912 - tidy::parseFile example
  • Example#3913 - tidy::parseString example
  • Example#3914 - tidy::repairFile example
  • Example#3915 - tidy::repairString example
  • Example#3916 - tidy::root example
  • Example#3917 - tidyNode::hasChildren example
  • Example#3918 - tidyNode::hasChildren example
  • Example#3919 - tidyNode::hasSiblings example
  • Example#3920 - Extract ASP code from a mixed HTML document
  • Example#3921 - Extract comments from a mixed HTML document
  • Example#3922 - Extract HTML code from a mixed HTML document
  • Example#3923 - Extract JSTE code from a mixed HTML document
  • Example#3924 - Extract PHP code from a mixed HTML document
  • Example#3925 - Extract text from a mixed HTML document
  • Example#3926 - ob_tidyhandler example
  • Example#3927 - tidy_access_count example
  • Example#3928 - tidy_config_count example
  • Example#3929 - tidy_error_count example
  • Example#3930 - tidy_get_output example
  • Example#3931 - tidy_warning_count example
  • Example#3932 - Retirando os comentários com o tokenizer
  • Example#3933 - PhpToken::getTokenName example
  • Example#3934 - PhpToken::is example
  • Example#3935 - Usage with array
  • Example#3936 - PhpToken::isIgnorable example
  • Example#3937 - PhpToken::__toString example
  • Example#3938 - PhpToken::tokenize example
  • Example#3939 - Extending PhpToken
  • Example#3940 - Exemplo de token_get_all
  • Example#3941 - Exemplo de uso incorreto de token_get_all
  • Example#3942 - token_get_all em uma classe usando um exemplo de palavra reservada
  • Example#3943 - Exemplo de token_name
  • Example#3944 - Exemplo base64_decode
  • Example#3945 - Exemplo base64_encode
  • Example#3946 - Exemplo de get_headers
  • Example#3947 - Exemplo de get_headers usando HEAD
  • Example#3948 - What get_meta_tags parses
  • Example#3949 - What get_meta_tags returns
  • Example#3950 - Exemplo de uso de http_build_query
  • Example#3951 - http_build_query com elementos indexados numericamente.
  • Example#3952 - http_build_query com arrays complexos
  • Example#3953 - Usando http_build_query com um objeto
  • Example#3954 - A parse_url example
  • Example#3955 - A parse_url example with missing scheme
  • Example#3956 - Exemplo da rawurldecode
  • Example#3957 - Incluindo uma senha em uma URL de FTP
  • Example#3958 - Exemplo 2 de rawurlencode
  • Example#3959 - Exemplo da urldecode
  • Example#3960 - urlencode example
  • Example#3961 - urlencode and htmlentities example
  • Example#3962 - Basic Javascript execution
  • Example#3963 - Yaml Example
  • Example#3964 - Parse callback example
  • Example#3965 - Emit callback example
  • Example#3966 - yaml_emit example
  • Example#3967 - yaml_parse example
  • Example#3968 - A classic Application directory layout
  • Example#3969 - Entry
  • Example#3970 - Rewrite rule
  • Example#3971 - Application config
  • Example#3972 - Default controller
  • Example#3973 - Default view template
  • Example#3974 - Run the Application
  • Example#3975 - An PHP array example
  • Example#3976 - An ini file example
  • Example#3977 - A Bootstrapexample
  • Example#3978 - Yaf_Application::bootstrapexample
  • Example#3979 - Yaf_Application::clearLastErrorexample
  • Example#3980 - A ini config file example
  • Example#3981 - Yaf_Application::__constructexample
  • Example#3982 - Yaf_Application::__constructexample
  • Example#3983 - Yaf_Application::environexample
  • Example#3984 - Yaf_Application::executeexample
  • Example#3985 - Yaf_Application::getConfigexample
  • Example#3986 - Yaf_Application::getDispatcherexample
  • Example#3987 - Yaf_Application::getLastErrorMsgexample
  • Example#3988 - Yaf_Application::getLastErrorNoexample
  • Example#3989 - Yaf_Application::getModulesexample
  • Example#3990 - Bootstrap example
  • Example#3991 - Yaf_Dispatcher::autoRender example
  • Example#3992 - Yaf_Dispatcher::catchException example
  • Example#3993 - Yaf_Dispatcher::registerPlugin example
  • Example#3994 - A custom View engine example
  • Example#3995 - Yaf_Dispatcher::setView example
  • Example#3996 - Yaf_Dispatcher::throwexception example
  • Example#3997 - Yaf_Dispatcher::throwexceptionexample
  • Example#3998 - Yaf_Config_Iniexample
  • Example#3999 - define action in a separate file
  • Example#4000 - Dummy_action.php
  • Example#4001 - Yaf_Controller_Abstract::forwardexample
  • Example#4002 - Yaf_Action_Abstract::executeexample
  • Example#4003 - Yaf_Action_Abstract::executeexample
  • Example#4004 - Yaf_View_Simple::assignexample
  • Example#4005 - templateexample
  • Example#4006 - Yaf_View_Simple::assignRefexample
  • Example#4007 - templateexample
  • Example#4008 - Yaf_View_Simple::clearexample
  • Example#4009 - Yaf_View_Simple::__constructorexample
  • Example#4010 - Yaf_View_Simple::__setexample
  • Example#4011 - Config example
  • Example#4012 - Register localnamespace
  • Example#4013 - Load class example
  • Example#4014 - Load namespace class example
  • Example#4015 - MVC class loading example
  • Example#4016 - MVC class distinctions
  • Example#4017 - MVC loading example
  • Example#4018 - Yaf_Loader::registerNamespaceexample
  • Example#4019 - Yaf_Loader::registerLocalNamespaceexample
  • Example#4020 - Yaf_Loader::registerNamespaceexample
  • Example#4021 - Plugin example
  • Example#4022 - Yaf_Plugin_Abstract::routerShutdownexample
  • Example#4023 - Yaf_Response_Abstract::appendBodyexample
  • Example#4024 - Yaf_Response_Abstract::getBodyexample
  • Example#4025 - Yaf_Response_Abstract::prependBodyexample
  • Example#4026 - Yaf_Response_Abstract::responseexample
  • Example#4027 - Yaf_Response_Abstract::setBodyexample
  • Example#4028 - Yaf_Route_Map::assembleexample
  • Example#4029 - Yaf_Route_Mapexample
  • Example#4030 - Yaf_Route_Mapexample
  • Example#4031 - Yaf_Route_Mapexample
  • Example#4032 - Yaf_Route_Regex::assembleexample
  • Example#4033 - Yaf_Route_Regexexample
  • Example#4034 - Yaf_Route_Regex(as of 2.3.0)example
  • Example#4035 - Yaf_Route_Regex and named capture ground(as of 2.3.0)example
  • Example#4036 - Yaf_Route_Regexexample
  • Example#4037 - Yaf_Route_Rewrite::assembleexample
  • Example#4038 - Yaf_Route_Rewriteexample
  • Example#4039 - Yaf_Route_Rewriteexample
  • Example#4040 - Yaf_Route_Rewrite(as of 2.3.0)example
  • Example#4041 - Rewrite rule for Apache
  • Example#4042 - Rewrite rule for Apache
  • Example#4043 - Rewrite rule for Lighttpd
  • Example#4044 - Rewrite rule for Nginx
  • Example#4045 - Yaf_Route_Static(default route)example
  • Example#4046 - application.iniexample
  • Example#4047 - Yaf_Dispatcher::autoConfigexample
  • Example#4048 - Yaf_Dispatcher::autoRenderexample
  • Example#4049 - Register some routes in Bootstrap
  • Example#4050 - plugin Dummy.php (under application.directory/plugins)
  • Example#4051 - Yaf_Route_Simple::assembleexample
  • Example#4052 - Yaf_Route_Simple::routeexample
  • Example#4053 - Yaf_Route_Simple::routeexample
  • Example#4054 - Yaf_Route_Static::assembleexample
  • Example#4055 - Yaf_Route_Static::routeexample
  • Example#4056 - Yaf_Route_Supervar::assemble example
  • Example#4057 - Yaf_Route_Supervarexample
  • Example#4058 - INI example
  • Example#4059 - INI sections example
  • Example#4060 - INIexample
  • Example#4061 - Taintexample
  • Example#4062 - Vector
  • Example#4063 - Map
  • Example#4064 - Ds\Collection::clear example
  • Example#4065 - Ds\Collection::copy example
  • Example#4066 - Ds\Collection::isEmpty example
  • Example#4067 - Ds\Collection::toArray example
  • Example#4068 - Ds\Hashable::hash example
  • Example#4069 - Ds\Sequence::allocate example
  • Example#4070 - Ds\Sequence::apply example
  • Example#4071 - Ds\Sequence::capacity example
  • Example#4072 - Ds\Sequence::contains example
  • Example#4073 - Ds\Sequence::filter example using callback function
  • Example#4074 - Ds\Sequence::filter example without a callback function
  • Example#4075 - Ds\Sequence::find example
  • Example#4076 - Ds\Sequence::first example
  • Example#4077 - Ds\Sequence::get example
  • Example#4078 - Ds\Sequence::get example using array syntax
  • Example#4079 - Ds\Sequence::insert example
  • Example#4080 - Ds\Sequence::join example using a separator string
  • Example#4081 - Ds\Sequence::join example without a separator string
  • Example#4082 - Ds\Sequence::last example
  • Example#4083 - Ds\Sequence::map example
  • Example#4084 - Ds\Sequence::merge example
  • Example#4085 - Ds\Sequence::pop example
  • Example#4086 - Ds\Sequence::push example
  • Example#4087 - Ds\Sequence::reduce with initial value example
  • Example#4088 - Ds\Sequence::reduce without an initial value example
  • Example#4089 - Ds\Sequence::remove example
  • Example#4090 - Ds\Sequence::reverse example
  • Example#4091 - Ds\Sequence::reversed example
  • Example#4092 - Ds\Sequence::rotate example
  • Example#4093 - Ds\Sequence::set example
  • Example#4094 - Ds\Sequence::set example using array syntax
  • Example#4095 - Ds\Sequence::shift example
  • Example#4096 - Ds\Sequence::slice example
  • Example#4097 - Ds\Sequence::sort example
  • Example#4098 - Ds\Sequence::sort example using a comparator
  • Example#4099 - Ds\Sequence::sorted example
  • Example#4100 - Ds\Sequence::sorted example using a comparator
  • Example#4101 - Ds\Sequence::sum integer example
  • Example#4102 - Ds\Sequence::sum float example
  • Example#4103 - Ds\Sequence::unshift example
  • Example#4104 - Ds\Vector::allocate example
  • Example#4105 - Ds\Vector::apply example
  • Example#4106 - Ds\Vector::capacity example
  • Example#4107 - Ds\Vector::clear example
  • Example#4108 - Ds\Vector::__construct example
  • Example#4109 - Ds\Vector::contains example
  • Example#4110 - Ds\Vector::copy example
  • Example#4111 - Ds\Vector::filter example using callback function
  • Example#4112 - Ds\Vector::filter example without a callback function
  • Example#4113 - Ds\Vector::find example
  • Example#4114 - Ds\Vector::first example
  • Example#4115 - Ds\Vector::get example
  • Example#4116 - Ds\Vector::get example using array syntax
  • Example#4117 - Ds\Vector::insert example
  • Example#4118 - Ds\Vector::isEmpty example
  • Example#4119 - Ds\Vector::join example using a separator string
  • Example#4120 - Ds\Vector::join example without a separator string
  • Example#4121 - Ds\Vector::last example
  • Example#4122 - Ds\Vector::map example
  • Example#4123 - Ds\Vector::merge example
  • Example#4124 - Ds\Vector::pop example
  • Example#4125 - Ds\Vector::push example
  • Example#4126 - Ds\Vector::reduce with initial value example
  • Example#4127 - Ds\Vector::reduce without an initial value example
  • Example#4128 - Ds\Vector::remove example
  • Example#4129 - Ds\Vector::reverse example
  • Example#4130 - Ds\Vector::reversed example
  • Example#4131 - Ds\Vector::rotate example
  • Example#4132 - Ds\Vector::set example
  • Example#4133 - Ds\Vector::set example using array syntax
  • Example#4134 - Ds\Vector::shift example
  • Example#4135 - Ds\Vector::slice example
  • Example#4136 - Ds\Vector::sort example
  • Example#4137 - Ds\Vector::sort example using a comparator
  • Example#4138 - Ds\Vector::sorted example
  • Example#4139 - Ds\Vector::sorted example using a comparator
  • Example#4140 - Ds\Vector::sum integer example
  • Example#4141 - Ds\Vector::sum float example
  • Example#4142 - Ds\Vector::toArray example
  • Example#4143 - Ds\Vector::unshift example
  • Example#4144 - Ds\Deque::allocate example
  • Example#4145 - Ds\Deque::apply example
  • Example#4146 - Ds\Deque::capacity example
  • Example#4147 - Ds\Deque::clear example
  • Example#4148 - Ds\Deque::__construct example
  • Example#4149 - Ds\Deque::contains example
  • Example#4150 - Ds\Deque::copy example
  • Example#4151 - Ds\Deque::filter example using callback function
  • Example#4152 - Ds\Deque::filter example without a callback function
  • Example#4153 - Ds\Deque::find example
  • Example#4154 - Ds\Deque::first example
  • Example#4155 - Ds\Deque::get example
  • Example#4156 - Ds\Deque::get example using array syntax
  • Example#4157 - Ds\Deque::insert example
  • Example#4158 - Ds\Deque::isEmpty example
  • Example#4159 - Ds\Deque::join example using a separator string
  • Example#4160 - Ds\Deque::join example without a separator string
  • Example#4161 - Ds\Deque::last example
  • Example#4162 - Ds\Deque::map example
  • Example#4163 - Ds\Deque::merge example
  • Example#4164 - Ds\Deque::pop example
  • Example#4165 - Ds\Deque::push example
  • Example#4166 - Ds\Deque::reduce with initial value example
  • Example#4167 - Ds\Deque::reduce without an initial value example
  • Example#4168 - Ds\Deque::remove example
  • Example#4169 - Ds\Deque::reverse example
  • Example#4170 - Ds\Deque::reversed example
  • Example#4171 - Ds\Deque::rotate example
  • Example#4172 - Ds\Deque::set example
  • Example#4173 - Ds\Deque::set example using array syntax
  • Example#4174 - Ds\Deque::shift example
  • Example#4175 - Ds\Deque::slice example
  • Example#4176 - Ds\Deque::sort example
  • Example#4177 - Ds\Deque::sort example using a comparator
  • Example#4178 - Ds\Deque::sorted example
  • Example#4179 - Ds\Deque::sorted example using a comparator
  • Example#4180 - Ds\Deque::sum integer example
  • Example#4181 - Ds\Deque::sum float example
  • Example#4182 - Ds\Deque::toArray example
  • Example#4183 - Ds\Deque::unshift example
  • Example#4184 - Ds\Map::allocate example
  • Example#4185 - Ds\Map::apply example
  • Example#4186 - Ds\Map::capacity example
  • Example#4187 - Ds\Map::clear example
  • Example#4188 - Ds\Map::__construct example
  • Example#4189 - Ds\Map::copy example
  • Example#4190 - Ds\Map::diff example
  • Example#4191 - Ds\Map::filter example using callback function
  • Example#4192 - Ds\Map::filter example without a callback function
  • Example#4193 - Ds\Map::first example
  • Example#4194 - Ds\Map::get example
  • Example#4195 - Ds\Map::get example using array syntax
  • Example#4196 - Ds\Map::hasKey example
  • Example#4197 - Ds\Map::hasValue example
  • Example#4198 - Ds\Map::intersect example
  • Example#4199 - Ds\Map::isEmpty example
  • Example#4200 - Ds\Map::keys example
  • Example#4201 - Ds\Map::ksort example
  • Example#4202 - Ds\Map::ksort example using a comparator
  • Example#4203 - Ds\Map::ksorted example
  • Example#4204 - Ds\Map::ksorted example using a comparator
  • Example#4205 - Ds\Map::last example
  • Example#4206 - Ds\Map::map example
  • Example#4207 - Ds\Map::merge example
  • Example#4208 - Ds\Map::pairs example
  • Example#4209 - Ds\Map::put example
  • Example#4210 - Ds\Map::put example using objects as keys
  • Example#4211 - Ds\Map::putAll example
  • Example#4212 - Ds\Map::reduce with initial value example
  • Example#4213 - Ds\Map::reduce without an initial value example
  • Example#4214 - Ds\Map::remove example
  • Example#4215 - Ds\Map::reverse example
  • Example#4216 - Ds\Map::reversed example
  • Example#4217 - Ds\Map::skip example
  • Example#4218 - Ds\Map::slice example
  • Example#4219 - Ds\Map::sort example
  • Example#4220 - Ds\Map::sort example using a comparator
  • Example#4221 - Ds\Map::sort example
  • Example#4222 - Ds\Map::sort example using a comparator
  • Example#4223 - Ds\Map::sum integer example
  • Example#4224 - Ds\Map::sum float example
  • Example#4225 - Ds\Map::toArray example
  • Example#4226 - Ds\Map::union example
  • Example#4227 - Ds\Map::values example
  • Example#4228 - Ds\Map::xor example
  • Example#4229 - Ds\Pair::clear example
  • Example#4230 - Ds\Pair::copy example
  • Example#4231 - Ds\Pair::isEmpty example
  • Example#4232 - Ds\Pair::toArray example
  • Example#4233 - Ds\Set::add example using integers
  • Example#4234 - Ds\Set::add example using objects
  • Example#4235 - Ds\Set::allocate example
  • Example#4236 - Ds\Set::capacity example
  • Example#4237 - Ds\Set::clear example
  • Example#4238 - Ds\Set::__construct example
  • Example#4239 - Ds\Set::contains example
  • Example#4240 - Ds\Set::copy example
  • Example#4241 - Ds\Set::diff example
  • Example#4242 - Ds\Set::filter example using callback function
  • Example#4243 - Ds\Set::filter example without a callback function
  • Example#4244 - Ds\Set::first example
  • Example#4245 - Ds\Set::get example
  • Example#4246 - Ds\Set::get example using array syntax
  • Example#4247 - Ds\Set::intersect example
  • Example#4248 - Ds\Set::isEmpty example
  • Example#4249 - Ds\Set::join example using a separator string
  • Example#4250 - Ds\Set::join example without a separator string
  • Example#4251 - Ds\Set::last example
  • Example#4252 - Ds\Set::merge example
  • Example#4253 - Ds\Set::reduce with initial value example
  • Example#4254 - Ds\Set::reduce without an initial value example
  • Example#4255 - Ds\Set::remove example
  • Example#4256 - Ds\Set::reverse example
  • Example#4257 - Ds\Set::reversed example
  • Example#4258 - Ds\Set::slice example
  • Example#4259 - Ds\Set::sort example
  • Example#4260 - Ds\Set::sort example using a comparator
  • Example#4261 - Ds\Set::sorted example
  • Example#4262 - Ds\Set::sorted example using a comparator
  • Example#4263 - Ds\Set::sum integer example
  • Example#4264 - Ds\Set::sum float example
  • Example#4265 - Ds\Set::toArray example
  • Example#4266 - Ds\Set::union example
  • Example#4267 - Ds\Set::xor example
  • Example#4268 - Ds\Stack::clear example
  • Example#4269 - Ds\Stack::__construct example
  • Example#4270 - Ds\Stack::copy example
  • Example#4271 - Ds\Stack::isEmpty example
  • Example#4272 - Exemplo Ds\Stack::peek
  • Example#4273 - Ds\Stack::pop example
  • Example#4274 - Ds\Stack::push example
  • Example#4275 - Ds\Stack::toArray example
  • Example#4276 - Ds\Queue::allocate example
  • Example#4277 - Ds\Queue::capacity example
  • Example#4278 - Ds\Queue::clear example
  • Example#4279 - Ds\Queue::__construct example
  • Example#4280 - Ds\Queue::copy example
  • Example#4281 - Ds\Queue::isEmpty example
  • Example#4282 - Ds\Queue::peek example
  • Example#4283 - Ds\Queue::pop example
  • Example#4284 - Ds\Queue::push example
  • Example#4285 - Ds\Queue::toArray example
  • Example#4286 - Ds\PriorityQueue::allocate example
  • Example#4287 - Ds\PriorityQueue::capacity example
  • Example#4288 - Ds\PriorityQueue::clear example
  • Example#4289 - Ds\PriorityQueue::__construct example
  • Example#4290 - Ds\PriorityQueue::copy example
  • Example#4291 - Ds\PriorityQueue::isEmpty example
  • Example#4292 - Ds\PriorityQueue::peek example
  • Example#4293 - Ds\PriorityQueue::pop example
  • Example#4294 - Ds\PriorityQueue::push example
  • Example#4295 - Ds\PriorityQueue::toArray example
  • Example#4296 - var_representation Examples
  • Example#4297 - Escaping control characters
  • Example#4298 - Exporting stdClass
  • Example#4299 - Exporting classes
  • Example#4300 - Using __set_state()
  • Example#4301 - Usando o módulo cURL do PHP para receber a página exemplo.com.br
  • Example#4302 - Iniciando uma nova sessão cURL e acessando uma página web
  • Example#4303 - Copiando um controlador cURL
  • Example#4304 - Exemplo de curl_errno
  • Example#4305 - Exemplo de curl_error
  • Example#4306 - Exemplo de curl_escape
  • Example#4307 - Obtendo uma página da web
  • Example#4308 - Exemplo de curl_getinfo
  • Example#4309 - Exemplo de curl_getinfo com parâmetro option
  • Example#4310 - Inicializando uma nova sessão cURL e buscando uma página da web
  • Example#4311 - curl_multi_add_handle example
  • Example#4312 - curl_multi_close example
  • Example#4313 - curl_multi_exec example
  • Example#4314 - Um exemplo de curl_multi_info_read
  • Example#4315 - Exemplo de curl_multi_init
  • Example#4316 - Exemplo de curl_multi_strerror
  • Example#4317 - Exemplo de curl_reset
  • Example#4318 - Inicializando uma nova sessão cURL e recebendo uma página da web
  • Example#4319 - Inicializando uma nova sessão cURL e buscando uma página da web
  • Example#4320 - Exemplo de curl_share_setopt
  • Example#4321 - Exemplo de curl_share_init
  • Example#4322 - Exemplo de curl_share_setopt
  • Example#4323 - curl_errno example
  • Example#4324 - Exemplo de curl_escape
  • Example#4325 - curl_upkeep example
  • Example#4326 - Exemplo de curl_version
  • Example#4327 - Exemplo de CURLFile::__construct
  • Example#4328 - Exemplo de CURLFile::__construct enviando múltiplos arquivos
  • Example#4329 - Exemplo de CURLStringFile::__construct
  • Example#4330 - Simple HTTP client
  • Example#4331 - HTTP client using asynchronous DNS resolver
  • Example#4332 - Echo server
  • Example#4333 - SSL echo server
  • Example#4334 - Signal handler
  • Example#4335 - Use libevent's loop to process requests of `eio' extension
  • Example#4336 - Miscellaneous
  • Example#4337 - Simple HTTP server
  • Example#4338 - Simple HTTPS server
  • Example#4339 - OpenSSL connection
  • Example#4340 - EventHttpConnection::makeRequest example
  • Example#4341 - Connection listener based on a UNIX domain socket
  • Example#4342 - Simple SMTP server
  • Example#4343 - Handling SIGTERM signal
  • Example#4344 - Adding a custom signal
  • Example#4345 - Adding a timer
  • Example#4346 - EventBase::getFeatures example
  • Example#4347 - EventBase::getMethod example
  • Example#4348 - EventBuffer::search example
  • Example#4349 - EventBufferEvent::connect example
  • Example#4350 - Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console
  • Example#4351 - EventBufferEvent::connectHost example
  • Example#4352 - Buffer event's read callback
  • Example#4353 - EventBufferEvent::getOutput example
  • Example#4354 - EventBufferEvent::sslError example
  • Example#4355 - Simple SMTP server
  • Example#4356 - EventConfig::avoidMethod example
  • Example#4357 - EventConfig::__construct example
  • Example#4358 - EventConfig::requireFeatures example
  • Example#4359 - EventHttp::accept example
  • Example#4360 - EventHttp::addServerAlias example
  • Example#4361 - EventHttp::bind example
  • Example#4362 - Simple HTTP server
  • Example#4363 - EventHttp::setCallback example
  • Example#4364 - EventHttp::setDefaultCallback example
  • Example#4365 - EventHttpConnection::makeRequest example
  • Example#4366 - EventHttpConnection::setCloseCallback example
  • Example#4367 - EventHttpRequest::__construct example
  • Example#4368 - EventHttpRequest::sendError example
  • Example#4369 - EventListener::__construct example
  • Example#4370 - EventSslContext::__construct example
  • Example#4371 - Exemplo da extensão FTP
  • Example#4372 - ftp_alloc example
  • Example#4373 - Exemplo ftp_cdup
  • Example#4374 - Exemplo de ftp_chdir
  • Example#4375 - Exemplo de ftp_chmod
  • Example#4376 - Exemplo de ftp_close
  • Example#4377 - ftp_connect example
  • Example#4378 - Exemplo de ftp_delete
  • Example#4379 - Exemplo de ftp_exec
  • Example#4380 - ftp_fget example
  • Example#4381 - ftp_fput example
  • Example#4382 - Exemplo de ftp_get_option
  • Example#4383 - ftp_get example
  • Example#4384 - Exemplo de ftp_login
  • Example#4385 - Exemplo de ftp_mdtm
  • Example#4386 - Exemplo de ftp_mkdir
  • Example#4387 - ftp_mlsd example
  • Example#4388 - Exemplo de ftp_nb_continue
  • Example#4389 - ftp_nb_fget example
  • Example#4390 - ftp_nb_fput example
  • Example#4391 - ftp_nb_get example
  • Example#4392 - Resuming a download with ftp_nb_get
  • Example#4393 - Resuming a download at position 100 to a new file with ftp_nb_get
  • Example#4394 - ftp_nb_put example
  • Example#4395 - Resuming an upload with ftp_nb_put
  • Example#4396 - Exemplo de ftp_nlist
  • Example#4397 - Exemplo de ftp_pasv
  • Example#4398 - ftp_put example
  • Example#4399 - Exemplo de ftp_pwd
  • Example#4400 - Usando ftp_raw para fazer o login em um servidor FTP manualmente.
  • Example#4401 - ftp_rawlist example
  • Example#4402 - Exemplo de ftp_rename
  • Example#4403 - Exemplo ftp_rmdir
  • Example#4404 - Exemplo de ftp_set_option
  • Example#4405 - Sending a SITE command to an ftp server
  • Example#4406 - Exemplo de ftp_size
  • Example#4407 - ftp_ssl_connect example
  • Example#4408 - Exemplo de ftp_systype
  • Example#4409 - Basic Gearman client and worker
  • Example#4410 - Basic Gearman client and worker, background
  • Example#4411 - Basic Gearman client and worker, submitting tasks
  • Example#4412 - Adding two job servers
  • Example#4413 - Add two job servers
  • Example#4414 - Basic submission of two tasks
  • Example#4415 - Basic submission of two tasks with passing application context
  • Example#4416 - Two tasks, one background and one not
  • Example#4417 - A high priority task along with two normal tasks
  • Example#4418 - A low priority task along with two normal tasks
  • Example#4419 - Monitor completion of multiple background tasks
  • Example#4420 - Simple job submission with immediate return
  • Example#4421 - Submitting a job and retrieving incremental status
  • Example#4422 - Submit and monitor a background job
  • Example#4423 - Simple job submission with immediate return
  • Example#4424 - Submitting a job and retrieving incremental status
  • Example#4425 - Get the status of a long running job
  • Example#4426 - Monitor the status of a long running background job
  • Example#4427 - Simple worker making use of extra application context data
  • Example#4428 - Add alternate Gearman servers
  • Example#4429 - Add two job servers
  • Example#4430 - GearmanWorker::setId example
  • Example#4431 - A simple worker with a 5 second timeout
  • Example#4432 - Running worker in non-blocking mode
  • Example#4433 - GearmanWorker::work example
  • Example#4434 - Testing support for paged result control
  • Example#4435 - LDAP search example
  • Example#4436 - Bind with policy information
  • Example#4437 - Modify description only if it's not empty
  • Example#4438 - Read some values before deletion
  • Example#4439 - Delete a reference
  • Example#4440 - Use pagination for a search
  • Example#4441 - Complete example with authenticated bind
  • Example#4442 - Using LDAP Bind
  • Example#4443 - Using LDAP Bind Anonymously
  • Example#4444 - Complete example of password check
  • Example#4445 - Example of connecting to LDAP server.
  • Example#4446 - Example of connecting securely to LDAP server.
  • Example#4447 - LDAP pagination
  • Example#4448 - LDAP pagination
  • Example#4449 - ldap_count_entries example
  • Example#4450 - Enumerating all LDAP error messages
  • Example#4451 - Generating and catching an error
  • Example#4452 - Searching for an email address
  • Example#4453 - PASSWD extended operation
  • Example#4454 - Whoami extended operation
  • Example#4455 - Show the list of attributes held for a particular directory entry
  • Example#4456 - Check protocol version
  • Example#4457 - List all values of the "mail" attribute for a directory entry
  • Example#4458 - Produce a list of all organizational units of an organization
  • Example#4459 - Add a telephone number to a contact
  • Example#4460 - Rename a user
  • Example#4461 - Add two e-mail addresses to a user
  • Example#4462 - Change a user's password
  • Example#4463 - Change a user's password (Active Directory)
  • Example#4464 - ldap_parse_result example
  • Example#4465 - LDAP search
  • Example#4466 - Set protocol version
  • Example#4467 - Set server controls
  • Example#4468 - LDAP sort
  • Example#4469 - memcache extension overview example
  • Example#4470 - Using memcache session handler
  • Example#4471 - Memcache::add example
  • Example#4472 - Memcache::addServer example
  • Example#4473 - Memcache::close example
  • Example#4474 - Memcache::connect example
  • Example#4475 - Memcache::decrement example
  • Example#4476 - Memcache::delete example
  • Example#4477 - Memcache::flush example
  • Example#4478 - Memcache::get example
  • Example#4479 - Memcache::getExtendedStats example
  • Example#4480 - Memcache::getServerStatus example
  • Example#4481 - Memcache::getVersion example
  • Example#4482 - Memcache::increment example
  • Example#4483 - Memcache::pconnect example
  • Example#4484 - Memcache::replace example
  • Example#4485 - Memcache::set example
  • Example#4486 - Memcache::set example
  • Example#4487 - Memcache::setCompressThreshold example
  • Example#4488 - Memcache::setServerParams example
  • Example#4489 - Exemplo de callback de resultado
  • Example#4490 - Exemplo de callback de leitura
  • Example#4491 - Memcached::addServer exemplo
  • Example#4492 - Memcached::addServers exemplo
  • Example#4493 - Memcached::append exemplo
  • Example#4494 - Memcached::cas exemplo
  • Example#4495 - Creating a Memcached object
  • Example#4496 - Memcached::decrement exemplo
  • Example#4497 - Memcached::delete exemplo
  • Example#4498 - Memcached::fetch exemplo
  • Example#4499 - Memcached::getDelayed exemplo
  • Example#4500 - Memcached::flush exemplo
  • Example#4501 - Memcached::get exemplo #1
  • Example#4502 - Memcached::get exemplo #2
  • Example#4503 - Memcached::getDelayed exemplo
  • Example#4504 - Memcached::getMulti exemplo para Memcached v3
  • Example#4505 - Memcached::getMulti exemplo para Memcached v1 e v2
  • Example#4506 - Memcached::GET_PRESERVE_ORDER exemplo para Memcached v3
  • Example#4507 - Memcached::GET_PRESERVE_ORDER exemplo para Memcached v1 e v2
  • Example#4508 - Recuperando opções do Memcached
  • Example#4509 - Memcached::getResultCode exemplo
  • Example#4510 - Memcached::getResultMessage exemplo
  • Example#4511 - Memcached::getServerByKey exemplo
  • Example#4512 - Memcached::getServerList exemplo
  • Example#4513 - Memcached::getStats exemplo
  • Example#4514 - Memcached::getVersion exemplo
  • Example#4515 - Memcached::increment exemplo
  • Example#4516 - Memcached::prepend exemplo
  • Example#4517 - Memcached::set exemplo
  • Example#4518 - Memcached::setByKey exemplo
  • Example#4519 - Memcached::setMulti exemplo
  • Example#4520 - Definindo uma opção do Memcached
  • Example#4521 - Configurando as opções do Memcached
  • Example#4522 - mqseries_back example
  • Example#4523 - mqseries_begin example
  • Example#4524 - mqseries_close example
  • Example#4525 - mqseries_cmit example
  • Example#4526 - mqseries_conn example
  • Example#4527 - mqseries_connx example
  • Example#4528 - mqseries_connx example using SSL connection & OCSP Responder URL
  • Example#4529 - mqseries_disc example
  • Example#4530 - mqseries_get example
  • Example#4531 - mqseries_inq example
  • Example#4532 - mqseries_open example
  • Example#4533 - mqseries_put example
  • Example#4534 - mqseries_strerror example
  • Example#4535 - Using dns_get_record
  • Example#4536 - Using dns_get_record and DNS_ANY
  • Example#4537 - Exemplo de fsockopen
  • Example#4538 - Utilizando conexão UDP
  • Example#4539 - Um simples exemplo de gethostbyaddr
  • Example#4540 - Um exemplo simples gethostbyname
  • Example#4541 - gethostbynamel exemplo
  • Example#4542 - A simple gethostname example
  • Example#4543 - getprotobyname example
  • Example#4544 - getservbyname example
  • Example#4545 - header_register_callback example
  • Example#4546 - Removendo um cabeçalho específico.
  • Example#4547 - Removendo todos os cabeçalhos definidos anteriormente.
  • Example#4548 - Download dialog
  • Example#4549 - Caching directives
  • Example#4550 - Exemplo usando headers_list
  • Example#4551 - Examples using headers_sent
  • Example#4552 - Using http_response_code in a web server environment
  • Example#4553 - Using http_response_code in a CLI environment
  • Example#4554 - inet_ntop Example
  • Example#4555 - inet_pton Example
  • Example#4556 - ip2long Example
  • Example#4557 - Displaying an IP address
  • Example#4558 - Exemplo de setcookie para enviar cookies
  • Example#4559 - Exemplo de setcookie para apagar cookies
  • Example#4560 - setcookie e arrays
  • Example#4561 - Using syslog
  • Example#4562 - Procedural usage of rrd
  • Example#4563 - OO usage of rrd
  • Example#4564 - RRDGraph::setOptions example
  • Example#4565 - Set multiple color options
  • Example#4566 - RRDUpdater::update examples
  • Example#4567 - Fetch instrumented calls
  • Example#4568 - Fetch the list of functions scoutapm will instrument
  • Example#4569 - snmp_get_quick_print example
  • Example#4570 - Using snmp_get_valueretrieval
  • Example#4571 - Using snmp_read_mib
  • Example#4572 - Using snmp_set_enum_print
  • Example#4573 - Using snmprealwalk
  • Example#4574 - Using snmp_set_quick_print
  • Example#4575 - Using snmp_set_valueretrieval
  • Example#4576 - Using snmp2_get
  • Example#4577 - Using snmp2_get_next
  • Example#4578 - Using snmp2_real_walk
  • Example#4579 - Using snmp2_set
  • Example#4580 - Using snmp2_set for setting BITS SNMP object id
  • Example#4581 - snmp2_walk Example
  • Example#4582 - Using snmp3_get
  • Example#4583 - Using snmp3_getnext
  • Example#4584 - Using snmp3_real_walk
  • Example#4585 - Using snmp3_set
  • Example#4586 - Using snmp3_set for setting BITS SNMP object id
  • Example#4587 - snmp3_walk Example
  • Example#4588 - Using snmpget
  • Example#4589 - Using snmpgetnext
  • Example#4590 - Using snmprealwalk
  • Example#4591 - Using snmpset
  • Example#4592 - Using snmpset for setting BITS SNMP object id
  • Example#4593 - snmpwalk Example
  • Example#4594 - snmpwalkoid Example
  • Example#4595 - SNMP::close example
  • Example#4596 - Fetching sysLocation
  • Example#4597 - Single SNMP object
  • Example#4598 - Multiple SNMP objects
  • Example#4599 - SNMP::getErrno example
  • Example#4600 - SNMP::getError example
  • Example#4601 - Single SNMP object
  • Example#4602 - Miltiple SNMP objects
  • Example#4603 - Set single SNMP object id
  • Example#4604 - Set multiple values using single SNMP::set call
  • Example#4605 - Using SNMP::set for setting BITS SNMP object id
  • Example#4606 - SNMP::setSecurity example
  • Example#4607 - SNMP::walk example
  • Example#4608 - suffixAsKey example
  • Example#4609 - Exemplo de socket: Simples servidor TCP/IP
  • Example#4610 - Exemplo de Socket: Simples cliente TCP/IP
  • Example#4611 - Usando socket_atmark para definir o endereço da fonte
  • Example#4612 - Using socket_bind to set the source address
  • Example#4613 - socket_create_pair example
  • Example#4614 - socket_create_pair IPC example
  • Example#4615 - socket_get_option example
  • Example#4616 - socket_import_stream example
  • Example#4617 - socket_last_error example
  • Example#4618 - Exemplo de socket_recv
  • Example#4619 - socket_recvfrom example
  • Example#4620 - Using null with socket_select
  • Example#4621 - Understanding socket_select's result
  • Example#4622 - socket_select example
  • Example#4623 - socket_sendto Example
  • Example#4624 - socket_set_block example
  • Example#4625 - socket_set_nonblock example
  • Example#4626 - socket_set_option example
  • Example#4627 - socket_strerror example
  • Example#4628 - Authenticating with a ssh agent
  • Example#4629 - Authentication using a public hostkey
  • Example#4630 - Retrieving a list of authentication methods
  • Example#4631 - Authenticating with a password
  • Example#4632 - Authentication using a public key
  • Example#4633 - ssh2_connect example
  • Example#4634 - Executing a command
  • Example#4635 - Opening a shell and retrieving the stderr stream associated with it
  • Example#4636 - Checking the fingerprint against a known value
  • Example#4637 - Determining what methods were negotiated
  • Example#4638 - Adding a publickey with ssh2_publickey_add
  • Example#4639 - Listing authorized keys with ssh2_publickey_list
  • Example#4640 - Downloading a file via SCP
  • Example#4641 - Uploading a file via SCP
  • Example#4642 - Changing the mode of a file on a remote server
  • Example#4643 - Stating a symbolic link via SFTP
  • Example#4644 - Creating a directory on a remote server
  • Example#4645 - Reading a symbolic link
  • Example#4646 - Resolving a pathname
  • Example#4647 - Renaming a file via sftp
  • Example#4648 - Removing a directory on a remote server
  • Example#4649 - Stating a file via SFTP
  • Example#4650 - Creating a symbolic link
  • Example#4651 - Deleting a file
  • Example#4652 - Opening a file via SFTP
  • Example#4653 - Requesting an interactive shell
  • Example#4654 - Opening a tunnel to an arbitrary host
  • Example#4655 - Estilo orientado a objetos
  • Example#4656 - Estilo procedural
  • Example#4657 - stomp_connect_error example
  • Example#4658 - stomp_version example
  • Example#4659 - Estilo orientado a objetos
  • Example#4660 - Estilo procedural
  • Example#4661 - Estilo orientado a objetos
  • Example#4662 - Estilo procedural
  • Example#4663 - Estilo orientado a objetos
  • Example#4664 - Estilo procedural
  • Example#4665 - Estilo orientado a objetos
  • Example#4666 - Estilo procedural
  • Example#4667 - Estilo orientado a objetos
  • Example#4668 - Estilo procedural
  • Example#4669 - Estilo orientado a objetos
  • Example#4670 - Estilo procedural
  • Example#4671 - Estilo orientado a objetos
  • Example#4672 - Estilo procedural
  • Example#4673 - Estilo orientado a objetos
  • Example#4674 - Estilo procedural
  • Example#4675 - Estilo orientado a objetos
  • Example#4676 - Estilo procedural
  • Example#4677 - Train from array
  • Example#4678 - Train from a file
  • Example#4679 - svn_add example
  • Example#4680 - Default authentication example
  • Example#4681 - svn_blame example
  • Example#4682 - Basic example
  • Example#4683 - Basic example
  • Example#4684 - Basic example
  • Example#4685 - Basic example
  • Example#4686 - Basic example
  • Example#4687 - Basic example
  • Example#4688 - Diffing two revisions of a repository path
  • Example#4689 - Portably diffing two local files
  • Example#4690 - svn_export example
  • Example#4691 - Basic example
  • Example#4692 - svn_log example
  • Example#4693 - svn_ls example
  • Example#4694 - Basic example
  • Example#4695 - Basic example
  • Example#4696 - Deny all connections from localhost
  • Example#4697 - Ban an URL
  • Example#4698 - Get statistic snapshot
  • Example#4699 - Read varnish shared memory log
  • Example#4700 - VarnishAdmin::__construct example
  • Example#4701 - Parallel searching using Yaz
  • Example#4702 - CCL configuration
  • Example#4703 - CCL Parsing
  • Example#4704 - Record Update
  • Example#4705 - Array for GRS-1 record
  • Example#4706 - Working with MARCXML
  • Example#4707 - PHP function that scans titles
  • Example#4708 - Query Examples
  • Example#4709 - Sort Criterias
  • Example#4710 - Um exemplo de ZMQContext
  • Example#4711 - Um exemplo de ZMQContext
  • Example#4712 - Um exemplo de ZMQContext
  • Example#4713 - Exemplo de ZMQSocket
  • Example#4714 - Um exemplo de envio/recepção
  • Example#4715 - Um exemplo de ZMQPoll
  • Example#4716 - zookeeper_dispatch example #1
  • Example#4717 - zookeeper_dispatch example #2
  • Example#4718 - Zookeeper::addAuth example
  • Example#4719 - Zookeeper::create example
  • Example#4720 - Zookeeper::delete example
  • Example#4721 - Zookeeper::exists example
  • Example#4722 - Zookeeper::get example
  • Example#4723 - Zookeeper::get stat example
  • Example#4724 - Zookeeper::getAcl example
  • Example#4725 - Zookeeper::getChildren example
  • Example#4726 - Zookeeper::set example
  • Example#4727 - Zookeeper::setAcl example
  • Example#4728 - Zookeeper::setDebugLevel example
  • Example#4729 - ZookeeperConfig::add example
  • Example#4730 - ZookeeperConfig::get example
  • Example#4731 - ZookeeperConfig::remove example
  • Example#4732 - ZookeeperConfig::set example
  • Example#4733 - Exemplo de solr_get_version
  • Example#4734 - Contents of the BootStrap file
  • Example#4735 - Adding a document to the index
  • Example#4736 - Merging one document into another document
  • Example#4737 - Searching for documents - SolrObject responses
  • Example#4738 - Searching for documents - SolrDocument responses
  • Example#4739 - Simple TermsComponent example - basic
  • Example#4740 - Simple TermsComponent example - using a prefix
  • Example#4741 - Simple TermsComponent example - specifying a minimum frequency
  • Example#4742 - Simple Facet Example
  • Example#4743 - Simple Facet Example - with optional field override for mincount
  • Example#4744 - Facet Date Example
  • Example#4745 - Connecting to SSL-Enabled Server
  • Example#4746 - Collapsing a SolrQuery
  • Example#4747 - Solr Real Time Get (RTG) example SolrClient::getById
  • Example#4748 - SolrInputDocument::addChildDocument example
  • Example#4749 - SolrInputDocument::addChildDocuments example
  • Example#4750 - SolrDocument::toArray example
  • Example#4751 - SolrObject::__construct example
  • Example#4752 - SolrObject::offsetUnset example
  • Example#4753 - SolrClient::addDocument example
  • Example#4754 - SolrClient::addDocument example 2
  • Example#4755 - SolrClient::addDocuments example
  • Example#4756 - SolrClient::__construct example
  • Example#4757 - SolrQuery::deleteByQuery example
  • Example#4758 - SolrClient::getById example
  • Example#4759 - SolrClient::getByIds example
  • Example#4760 - SolrClient::ping example
  • Example#4761 - SolrClient::query example
  • Example#4762 - SolrClient::request example
  • Example#4763 - SolrClient::setResponseWriter example
  • Example#4764 - SolrParams::setParam example
  • Example#4765 - SolrQuery::addFacetField example
  • Example#4766 - SolrQuery::addFacetField example
  • Example#4767 - SolrQuery::addFilterQuery example
  • Example#4768 - SolrQuery::addGroupSortField example
  • Example#4769 - SolrQuery::collapse example
  • Example#4770 - SolrQuery::setExpand example
  • Example#4771 - SolrDisMaxQuery::addBigramPhraseField example
  • Example#4772 - SolrDisMaxQuery::addBoostQuery example
  • Example#4773 - SolrDisMaxQuery::addPhraseField example
  • Example#4774 - SolrDisMaxQuery::addQueryField example
  • Example#4775 - SolrDisMaxQuery::addTrigramPhraseField example
  • Example#4776 - SolrDisMaxQuery::addUserField example
  • Example#4777 - SolrDisMaxQuery::__construct example
  • Example#4778 - SolrDisMaxQuery::removeBigramPhraseField example
  • Example#4779 - SolrDisMaxQuery::removeBoostQuery example
  • Example#4780 - SolrDisMaxQuery::removePhraseField example
  • Example#4781 - SolrDisMaxQuery::removeQueryField example
  • Example#4782 - SolrDisMaxQuery::removeTrigramPhraseField example
  • Example#4783 - SolrDisMaxQuery::removeUserField example
  • Example#4784 - SolrDisMaxQuery::setBigramPhraseFields example
  • Example#4785 - SolrDisMaxQuery::setBigramPhraseSlop example
  • Example#4786 - SolrDisMaxQuery::setBoostFunction example
  • Example#4787 - SolrDisMaxQuery::setBoostQuery example
  • Example#4788 - SolrDisMaxQuery::setMinimumMatch example
  • Example#4789 - SolrDisMaxQuery::setPhraseFields example
  • Example#4790 - SolrDisMaxQuery::setPhraseSlop example
  • Example#4791 - SolrDisMaxQuery::setQueryAlt example
  • Example#4792 - SolrDisMaxQuery::setQueryPhraseSlop example
  • Example#4793 - SolrDisMaxQuery::setTieBreaker example
  • Example#4794 - SolrDisMaxQuery::setTrigramPhraseFields example
  • Example#4795 - SolrDisMaxQuery::setTrigramPhraseSlop example
  • Example#4796 - SolrDisMaxQuery::setUserFields example
  • Example#4797 - SolrDisMaxQuery::useDisMaxQueryParser example
  • Example#4798 - SolrDisMaxQuery::useEDisMaxQueryParser example
  • Example#4799 - SolrCollapseFunction::__construct example
  • Example#4800 - SolrCollapseFunction::setHint example
  • Example#4801 - SolrCollapseFunction::setMax example
  • Example#4802 - Desligando a interpretação do PHP em um diretório utilizando .htaccess
  • Example#4803 - Exemplo da função apache_get_modules
  • Example#4804 - Exemplo da função apache_get_version
  • Example#4805 - Exemplo de uso da função apache_getenv
  • Example#4806 - Exemplo da função apache_lookup_uri
  • Example#4807 - Passando informações entre PHP e Perl
  • Example#4808 - Logar valores no access.log
  • Example#4809 - Exemplo da função apache_request_headers
  • Example#4810 - Exemplo da função apache_response_headers
  • Example#4811 - Configurando uma variável Apache utilizando apache_setenv
  • Example#4812 - Exemplo da função getallheaders
  • Example#4813 - Registrando uma variável com $_SESSION.
  • Example#4814 - Desregistrando uma variável com $_SESSION.
  • Example#4815 - Contando o número de acessos de um único usuário
  • Example#4816 - Informação de exemplo
  • Example#4817 - Exemplo de session_cache_expire
  • Example#4818 - Exemplo de session_cache_limiter
  • Example#4819 - session_create_id exemplo com session_regenerate_id
  • Example#4820 - Destruindo uma sessão com $_SESSION
  • Example#4821 - Exemplo de session_gc para gerenciadores de tarefas como o cron
  • Example#4822 - session_gc example for user accessible script
  • Example#4823 - Exemplo de session_name
  • Example#4824 - Exemplo de session_regenerate_id
  • Example#4825 - Evitando a perda de sessão causada por session_regenerate_id
  • Example#4826 - Manipulador de sessão personalizado: veja o código completo na sinópse de SessionHandlerInterface.
  • Example#4827 - page1.php
  • Example#4828 - page2.php
  • Example#4829 - Sobrepondo o tempo de duração de cookie
  • Example#4830 - Lendo e fechando a sessão
  • Example#4831 - Usando SessionHandler para adicionar criptografia aos manipuladores internos do PHP de gravação.
  • Example#4832 - Exemplo usando SessionHandlerInterface
  • Example#4833 - Tokenize comma separated integer list
  • Example#4834 - Tokenize assign statement
  • Example#4835 - Simple calculator
  • Example#4836 - Parse words out from a sentence
  • Example#4837 - Exemplos de padrões válidos
  • Example#4838 - Exemplos de padrões inválidos
  • Example#4839 - Usage of comments in PCRE pattern
  • Example#4840 - Example comparing preg_filter with preg_replace
  • Example#4841 - preg_grep example
  • Example#4842 - preg_last_error_msg example
  • Example#4843 - Exemplo de preg_last_error
  • Example#4844 - Getting all phone numbers out of some text.
  • Example#4845 - Find matching HTML tags (greedy)
  • Example#4846 - Using named subpattern
  • Example#4847 - Find the string of text "php"
  • Example#4848 - Find the word "web"
  • Example#4849 - Getting the domain name out of a URL
  • Example#4850 - Using named subpattern
  • Example#4851 - preg_quote example
  • Example#4852 - Italicizing a word within some text
  • Example#4853 - preg_replace_callback_array example
  • Example#4854 - preg_replace_callback e função anônima
  • Example#4855 - Exemplo de preg_replace_callback
  • Example#4856 - preg_replace_callback usando estrutura recursiva para manipular código BB encapsulado
  • Example#4857 - Usando referências passadas seguidas por literais numéricos
  • Example#4858 - Usando array indexados com preg_replace
  • Example#4859 - Substituindo vários valores
  • Example#4860 - Removendo espaços
  • Example#4861 - Usando o parâmetro count
  • Example#4862 -
  • Example#4863 - preg_split example : Get the parts of a search string
  • Example#4864 - Splitting a string into component characters
  • Example#4865 - Splitting a string into matches and their offsets
  • Example#4866 - addcslashes example
  • Example#4867 - Exemplo com addslashes
  • Example#4868 - bin2hex example
  • Example#4869 - chr example
  • Example#4870 - Overflow behavior
  • Example#4871 - Building a UTF-8 string from individual bytes
  • Example#4872 - Exemplo da chunk_split
  • Example#4873 - Exemplo da convert_uudecode
  • Example#4874 - Exemplo da convert_uuencode
  • Example#4875 - count_chars example
  • Example#4876 - Mostrando uma soma de verificação crc32
  • Example#4877 - crypt examples
  • Example#4878 - echo examples
  • Example#4879 -
  • Example#4880 - explode examples
  • Example#4881 - explode return examples
  • Example#4882 - limit parameter examples
  • Example#4883 - fprintf: inteiros com zero à esquerda
  • Example#4884 - fprintf: formatando moeda
  • Example#4885 - Translation Table Example
  • Example#4886 - Exemplo de hex2bin
  • Example#4887 - Decoding HTML entities
  • Example#4888 - A htmlentities example
  • Example#4889 - Usage of ENT_IGNORE
  • Example#4890 - A htmlspecialchars_decode example
  • Example#4891 - htmlspecialchars example
  • Example#4892 - implode example
  • Example#4893 - Exemplo de lcfirst
  • Example#4894 - levenshtein example
  • Example#4895 - localeconv example
  • Example#4896 - Exemplo de uso de ltrim
  • Example#4897 - Usage example of md5_file
  • Example#4898 - A md5 example
  • Example#4899 - metaphone basic example
  • Example#4900 - Using the max_phonemes parameter
  • Example#4901 - Using the max_phonemes parameter
  • Example#4902 - Exemplo da money_format
  • Example#4903 - nl_langinfo example
  • Example#4904 - Using nl2br
  • Example#4905 - Generating valid HTML markup using the use_xhtml parameter
  • Example#4906 - Various newline separators
  • Example#4907 - number_format Example
  • Example#4908 - Exemplo de ord
  • Example#4909 - Examinando os bytes individuais de uma string UTF-8
  • Example#4910 - Using parse_str
  • Example#4911 - Name mangling em parse_str
  • Example#4912 - Exemplos print
  • Example#4913 -
  • Example#4914 -
  • Example#4915 - printf: various examples
  • Example#4916 - printf: string specifiers
  • Example#4917 - Exemplo de quoted_printable_decode
  • Example#4918 - Exemplo de quoted_printable_encode
  • Example#4919 - quotemeta example
  • Example#4920 - Exemplo de uso da função rtrim
  • Example#4921 - setlocale Examples
  • Example#4922 - setlocale Examples for Windows
  • Example#4923 - Exemplo de sha1_file
  • Example#4924 - A sha1 example
  • Example#4925 - Exemplo de similar_text com inversão de ordem de argumentos
  • Example#4926 - Exemplos de Soundex
  • Example#4927 - Argument swapping
  • Example#4928 - Specifying padding character
  • Example#4929 - Position specifier with other specifiers
  • Example#4930 - sprintf: zero-padded integers
  • Example#4931 - sprintf: formatting currency
  • Example#4932 - sprintf: scientific notation
  • Example#4933 - Exemplo de sscanf
  • Example#4934 - sscanf - usando parâmetros opcionais
  • Example#4935 - Usando a string vazia ''
  • Example#4936 - Mostrando o case-sensitivity
  • Example#4937 - Basic str_decrement example
  • Example#4938 - str_decrement example with a carry
  • Example#4939 - Usando a string vazia ''
  • Example#4940 - Mostrando o case-sensitivity
  • Example#4941 - Exemplo de str_getcsv
  • Example#4942 - Exemplo de str_getcsvcom uma string vazia
  • Example#4943 - Basic str_increment example
  • Example#4944 - str_increment example with a carry
  • Example#4945 - str_ireplace example
  • Example#4946 - str_pad example
  • Example#4947 - Exemplo de str_repeat
  • Example#4948 - Exemplos básicos de str_replace
  • Example#4949 - Exemplos de armadilhas potenciais de str_replace
  • Example#4950 - Exemplo de str_rot13
  • Example#4951 - Exemplo de str_shuffle
  • Example#4952 - Example uses of str_split
  • Example#4953 - Usando uma string vazia ''
  • Example#4954 - Mostrando o case-sensitivity
  • Example#4955 - Um exemplo de str_word_count
  • Example#4956 - strcasecmp example
  • Example#4957 - strcmp example
  • Example#4958 - Exemplo de strcspn
  • Example#4959 - Exemplo de strip_tags
  • Example#4960 - Exemplo de stripcslashes
  • Example#4961 - stripos examples
  • Example#4962 - Exemplo stripslashes
  • Example#4963 - Usando stripslashes em um array
  • Example#4964 - stristr example
  • Example#4965 - Testing if a string is found or not
  • Example#4966 - Using a non "string" needle
  • Example#4967 - Exemplo de strlen
  • Example#4968 - Exemplo de strnatcasecmp
  • Example#4969 - Exemplo de strncasecmp
  • Example#4970 - strncmp example
  • Example#4971 - Exemplo de strpbrk
  • Example#4972 - Using ===
  • Example#4973 - Using !==
  • Example#4974 - Using an offset
  • Example#4975 - strrchr example
  • Example#4976 - Revertendo uma string strrev
  • Example#4977 - A simple strripos example
  • Example#4978 - Checking if a needle is in the haystack
  • Example#4979 - Searching with offsets
  • Example#4980 - strspn example
  • Example#4981 - strstr example
  • Example#4982 - strtok example
  • Example#4983 - strtok behavior on empty part found
  • Example#4984 - The difference between strtok and explode
  • Example#4985 - Exemplo de strtolower
  • Example#4986 - strtoupper example
  • Example#4987 - strtr example
  • Example#4988 - strtr example with two arguments
  • Example#4989 - strtr behavior comparison
  • Example#4990 - Exemplo de substr_compare
  • Example#4991 - Exemplo de substr_count
  • Example#4992 - Exemplo de substr_replace
  • Example#4993 - Usando substr_replace para substituir múltiplas strings de uma só vez
  • Example#4994 - Usando um offset negativo
  • Example#4995 - Usando um length negativo
  • Example#4996 - Uso básico de substr
  • Example#4997 - Comportamento de conversão no substr
  • Example#4998 -
  • Example#4999 - Faixa Inválida de Caracteres
  • Example#5000 - Exemplo de uso de trim
  • Example#5001 - Usando trim em valores de array
  • Example#5002 - ucfirst example
  • Example#5003 - Exemplo da ucwords
  • Example#5004 - Exemplo de ucwords com delimitador
  • Example#5005 - Exemplo de ucwords com delimitadores adicionais
  • Example#5006 - Basic examples
  • Example#5007 - Basic example
  • Example#5008 - vfprintf: inteiros precedidos por zero
  • Example#5009 - vprintf: zero-padded integers
  • Example#5010 - vsprintf: zero-padded integers
  • Example#5011 - Exemplo de wordwrap
  • Example#5012 - Exemplo de wordwrap
  • Example#5013 - Exemplo de wordwrap
  • Example#5014 - Exemplo da função array_change_key_case
  • Example#5015 - Exemplo da função array_chunk
  • Example#5016 - Obtém a coluna first_name dos registros
  • Example#5017 - Obtém a coluna last_name dos registros, indexados pela coluna "id"
  • Example#5018 - Obtém a coluna de nomes de usuários da propriedade pública "username" de um objeto
  • Example#5019 - Obtém a coluna de nomes da propriedade privada "name" de um objeto utilizando o método mágico __get.
  • Example#5020 - Um simples exemplo usando a função array_combine
  • Example#5021 - Exemplo da array_count_values
  • Example#5022 - Exemplo de array_diff_assoc
  • Example#5023 - Exemplo da função array_diff_assoc
  • Example#5024 - Exemplo da função array_diff_key
  • Example#5025 - Exemplo de array_diff_uassoc
  • Example#5026 - Exemplo da função array_diff_ukey
  • Example#5027 - Exemplo da função array_diff
  • Example#5028 - Exemplo de array_diff com tipos não correspondentes
  • Example#5029 - Exemplo da função array_fill_keys
  • Example#5030 - Exemplo da função array_fill
  • Example#5031 - Exemplo da array_fill com um índice de início negativo
  • Example#5032 - Exemplo da função array_filter
  • Example#5033 - array_filter sem callback
  • Example#5034 - array_filter com mode
  • Example#5035 - Exemplo da função array_flip
  • Example#5036 - Exemplo da função array_flip: colisão
  • Example#5037 - Exemplo da array_intersect_assoc
  • Example#5038 - Exemplo da array_intersect_key
  • Example#5039 - Exemplo da função array_intersect_uassoc
  • Example#5040 - Exemplo da função array_intersect_ukey
  • Example#5041 - Exemplo da array_intersect
  • Example#5042 - array_is_list example
  • Example#5043 - Exemplo da função array_key_exists
  • Example#5044 - array_key_exists versus isset
  • Example#5045 - Uso básico de array_key_first
  • Example#5046 - Exemplo de array_keys
  • Example#5047 - Exemplo da função array_map
  • Example#5048 - array_map utilizando uma função lambda
  • Example#5049 - array_map - usando mais de um array
  • Example#5050 - Realizando uma operação zip de arrays
  • Example#5051 - callback null apenas com array
  • Example#5052 - array_map - com chaves string
  • Example#5053 - array_map - arrays associativos
  • Example#5054 - Exemplo de array_merge_recursive
  • Example#5055 - Exemplo de array_merge
  • Example#5056 - Exemplo simples de array_merge
  • Example#5057 - array_merge com tipos não array
  • Example#5058 - Ordenando vários arrays
  • Example#5059 - Ordenando arrays multi dimensionais
  • Example#5060 - Ordenando resultados de bancos de dados
  • Example#5061 - Ordenação case insensitive
  • Example#5062 - Exemplo de array_pad
  • Example#5063 - Exemplo da array_pop
  • Example#5064 - Exemplo da array_product
  • Example#5065 - Exemplo de array_push
  • Example#5066 - Exemplo de array_rand
  • Example#5067 - Exemplo de array_reduce
  • Example#5068 - array_replace_recursive example
  • Example#5069 - array_replace_recursive e recursive behavior
  • Example#5070 - array_replace exemplo
  • Example#5071 - array_reverse example
  • Example#5072 - Exemplo da array_search
  • Example#5073 - Exemplo da array_shift
  • Example#5074 - Exemplos de array_slice
  • Example#5075 - array_slice e arrays baseados em 1
  • Example#5076 - array_slice com chaves mistas
  • Example#5077 - Exemplos da array_splice
  • Example#5078 - Declarações equivalentes a vários exemplos da array_splice
  • Example#5079 - Exemplos da array_sum
  • Example#5080 - Exemplo de array_udiff_assoc
  • Example#5081 - Exemplo de array_udiff_uassoc
  • Example#5082 - Exemplo de array_udiff usando Objetos stdClass
  • Example#5083 - Exemplo de array_udiff usando Objetos DateTime
  • Example#5084 - Exemplo de array_uintersect_assoc
  • Example#5085 - Exemplo de array_uintersect_uassoc
  • Example#5086 - Exemplo da array_uintersect
  • Example#5087 - Exemplo de array_unique
  • Example#5088 - array_unique e tipos
  • Example#5089 - Exemplo de array_unshift
  • Example#5090 - Uso de arrays associativos
  • Example#5091 - Exemplo de array_values
  • Example#5092 - Exemplo da array_walk_recursive
  • Example#5093 - Exemplo da array_walk
  • Example#5094 - Exemplo de array_walk e funções anônimas
  • Example#5095 - Exemplo de array
  • Example#5096 - Indexação automática com array
  • Example#5097 - Array com índices a partir do 1 com array
  • Example#5098 - Acessando um array dentro de chaves
  • Example#5099 - Exemplo de arsort
  • Example#5100 - Exemplo de asort
  • Example#5101 - Exemplo de compact
  • Example#5102 - Exemplo da função count
  • Example#5103 - Exemplo de count em não-Countable|array (contra exemplo - não deve ser feito)
  • Example#5104 - Uso recursivo da função count
  • Example#5105 - Objeto Countable
  • Example#5106 - Exemplo do uso de current e amigos
  • Example#5107 - Exemplos de each
  • Example#5108 - Percorrendo um array com each
  • Example#5109 - Exemplo de end
  • Example#5110 - Exemplo da extract
  • Example#5111 - Exemplo da in_array
  • Example#5112 - in_array com checagem de tipos
  • Example#5113 - Exemplo de in_array passando um array como um needle
  • Example#5114 - Exemplo da key
  • Example#5115 - Exemplo de krsort
  • Example#5116 - Exemplo da ksort
  • Example#5117 - ksort com chaves int
  • Example#5118 - Exemplo da list
  • Example#5119 - Exemplo da list
  • Example#5120 - list e ordem das definições de índice
  • Example#5121 - Usando list com índices de array
  • Example#5122 - list com chaves
  • Example#5123 - Exemplo da natcasesort
  • Example#5124 - Exemplo de natsort demonstrando seu uso básico
  • Example#5125 - Exemplos de natsort demonstrando potenciais ciladas
  • Example#5126 - Exemplo de uso da next e funções relacionadas
  • Example#5127 - Exemplo de uso de prev e funções relacionadas
  • Example#5128 - range examples
  • Example#5129 - Exemplo da reset
  • Example#5130 - Exemplo de rsort
  • Example#5131 - Exemplo de shuffle
  • Example#5132 - Exemplo de sort
  • Example#5133 - Exemplo de sort utilizando comparações naturais ignorando maiúsculas e minúculas
  • Example#5134 - Exemplo básico de uasort
  • Example#5135 - uksort example
  • Example#5136 - Exemplo de usort
  • Example#5137 - Exemplo de usort usando um array multidimensional
  • Example#5138 - Exemplo de usort usando uma função membro de um objeto
  • Example#5139 - Exemplo de usort usando uma closure para ordernar um array multidimensional
  • Example#5140 - Exemplo de usort usando o operador nave espacial
  • Example#5141 - Definições da Classe
  • Example#5142 - test_script.php
  • Example#5143 - Exemplo de class_alias
  • Example#5144 - Exemplo de class_exists
  • Example#5145 - Exemplo do parâmetro autoload
  • Example#5146 - Exemplo de enum_exists
  • Example#5147 - Usando get_called_class
  • Example#5148 - Exemplo de get_class_methods
  • Example#5149 - Exemplo da get_class_vars
  • Example#5150 - get_class_vars e comportamento de escopo
  • Example#5151 - Usando get_class
  • Example#5152 - Usando get_class em superclasse
  • Example#5153 - Usando get_class em classe com namespace
  • Example#5154 - Exemplo de get_declared_classes
  • Example#5155 - Exemplo de uso de get_declared_interfaces
  • Example#5156 - Exemplo de get_mangled_object_vars
  • Example#5157 - Uso da get_object_vars
  • Example#5158 - Usando get_parent_class
  • Example#5159 - Exemplo de interface_exists
  • Example#5160 - Exemplo de is_a
  • Example#5161 - Utilizando o operador instanceof
  • Example#5162 - Exemplo de is_subclass_of
  • Example#5163 - Exemplo de is_subclass_of usando interface
  • Example#5164 - Exemplo de method_exists
  • Example#5165 - Exemplo de method_exists com método estático
  • Example#5166 - Exemplo de property_exists
  • Example#5167 - Um exemplo da ctype_alnum (usando a localidade padrão)
  • Example#5168 - Um exemplo da ctype_alpha (usando o locale padrão)
  • Example#5169 - Um exemplo da ctype_cntrl
  • Example#5170 - Um exemplo de ctype_digit
  • Example#5171 - Um exemplo de ctype_digit comparando strings com inteiros
  • Example#5172 - A ctype_graph example
  • Example#5173 - Um exemplo da ctype_lower (usando o locale padrão)
  • Example#5174 - Um exemplo da ctype_print
  • Example#5175 - Um exemplo da ctype_punct
  • Example#5176 - Um exemplo da ctype_space
  • Example#5177 - Um exemplo da ctype_upper (usando o locale padrão)
  • Example#5178 - Um exemplo da ctype_xdigit
  • Example#5179 - Configurando o filtro padrão para agir como htmlspecialchars
  • Example#5180 - Configurando o filtro padrão para agir como htmlspecialchars
  • Example#5181 - Validating email addresses with filter_var
  • Example#5182 - Validating IP addresses with filter_var
  • Example#5183 - Passing options to filter_var
  • Example#5184 - Sanitizing and validating email addresses
  • Example#5185 - Configuring a default filter
  • Example#5186 - Um exemplo da filter_input_array
  • Example#5187 - A filter_input example
  • Example#5188 - Um exemplo de filter_list
  • Example#5189 - Um exemplo de filter_var_array
  • Example#5190 - A filter_var example
  • Example#5191 - Filter an array example
  • Example#5192 - call_user_func_array example
  • Example#5193 - call_user_func_array using namespace name
  • Example#5194 - Using lambda function
  • Example#5195 - Passing values by reference
  • Example#5196 - call_user_func_array using named arguments
  • Example#5197 - call_user_func example and references
  • Example#5198 - call_user_func example
  • Example#5199 - call_user_func using namespace name
  • Example#5200 - Using a class method with call_user_func
  • Example#5201 - Using lambda function with call_user_func
  • Example#5202 - Criando uma função dinamicamente, com create_function ou funções anônimas
  • Example#5203 - Criação de uma função de processamento geral, com create_function ou funções anônimas
  • Example#5204 - Uso de funções anônimas como funções callback
  • Example#5205 - forward_static_call_array example
  • Example#5206 - forward_static_call example
  • Example#5207 - Exemplo de func_get_arg
  • Example#5208 - Exemplo de func_get_arg com argumentos por valor e por referência
  • Example#5209 - func_get_args example
  • Example#5210 - func_get_args example of byref and byval arguments
  • Example#5211 - func_num_args example
  • Example#5212 - Exemplo de function_exists
  • Example#5213 - Exemplo de get_defined_functions
  • Example#5214 - register_shutdown_function example
  • Example#5215 - register_tick_function example
  • Example#5216 - Quickhash Example
  • Example#5217 - Quickhash ArrayAccess Example
  • Example#5218 - Quickhash Iterator Example
  • Example#5219 - Quickhash String Values Example
  • Example#5220 - QuickHashIntSet::add example
  • Example#5221 - QuickHashIntSet::__construct example
  • Example#5222 - QuickHashIntSet::delete example
  • Example#5223 - QuickHashIntSet::exists example
  • Example#5224 - QuickHashIntSet::getSize example
  • Example#5225 - QuickHashIntSet::loadFromFile example
  • Example#5226 - QuickHashIntSet::loadFromString example
  • Example#5227 - QuickHashIntSet::saveToFile example
  • Example#5228 - QuickHashIntSet::saveToString example
  • Example#5229 - QuickHashIntHash::add example
  • Example#5230 - QuickHashIntHash::__construct example
  • Example#5231 - QuickHashIntHash::delete example
  • Example#5232 - QuickHashIntHash::exists example
  • Example#5233 - QuickHashIntHash::get example
  • Example#5234 - QuickHashIntHash::getSize example
  • Example#5235 - QuickHash IntHash file format
  • Example#5236 - QuickHash IntHash file format
  • Example#5237 - QuickHashIntHash::loadFromFile example
  • Example#5238 - QuickHashIntHash::loadFromString example
  • Example#5239 - QuickHashIntHash::saveToFile example
  • Example#5240 - QuickHashIntHash::saveToString example
  • Example#5241 - QuickHashIntHash::set example
  • Example#5242 - QuickHashIntHash::update example
  • Example#5243 - QuickHashStringIntHash::add example
  • Example#5244 - QuickHashStringIntHash::__construct example
  • Example#5245 - QuickHashStringIntHash::delete example
  • Example#5246 - QuickHashStringIntHash::get example
  • Example#5247 - QuickHashStringIntHash::getSize example
  • Example#5248 - QuickHash StringIntHash file format
  • Example#5249 - QuickHash IntHash file format
  • Example#5250 - QuickHashStringIntHash::loadFromFile example
  • Example#5251 - QuickHashStringIntHash::loadFromString example
  • Example#5252 - QuickHashStringIntHash::saveToFile example
  • Example#5253 - QuickHashStringIntHash::saveToString example
  • Example#5254 - QuickHashStringIntHash::set example
  • Example#5255 - QuickHashStringIntHash::update example
  • Example#5256 - QuickHashIntStringHash::add example
  • Example#5257 - QuickHashIntStringHash::__construct example
  • Example#5258 - QuickHashIntStringHash::delete example
  • Example#5259 - QuickHashIntStringHash::get example
  • Example#5260 - QuickHashIntStringHash::getSize example
  • Example#5261 - QuickHash IntString file format
  • Example#5262 - QuickHash IntString file format
  • Example#5263 - QuickHashIntStringHash::loadFromFile example
  • Example#5264 - QuickHashIntStringHash::loadFromString example
  • Example#5265 - QuickHashIntStringHash::saveToFile example
  • Example#5266 - QuickHashIntStringHash::saveToString example
  • Example#5267 - QuickHashIntStringHash::set example
  • Example#5268 - QuickHashIntStringHash::update example
  • Example#5269 - Exemplo de Reflexão no shell (terminal)
  • Example#5270 - Extendendo classe nativas
  • Example#5271 - Reflection::getModifierNames example
  • Example#5272 - Basic usage ReflectionClass
  • Example#5273 - Basic usage of ReflectionClass::export
  • Example#5274 - Basic usage
  • Example#5275 - Filtering results by class name
  • Example#5276 - Filtering results by class name, with inheritance
  • Example#5277 - Usage of ReflectionClass::getConstant
  • Example#5278 - Basic usage of ReflectionClass::getConstructor
  • Example#5279 - ReflectionClass::getDefaultProperties example
  • Example#5280 - ReflectionClass::getDocComment example
  • Example#5281 - ReflectionClass::getEndLine example
  • Example#5282 - Basic usage of ReflectionClass::getExtension
  • Example#5283 - Basic usage of ReflectionClass::getExtensionName
  • Example#5284 - ReflectionClass::getInterfaceNames example
  • Example#5285 - ReflectionClass::getInterfaces example
  • Example#5286 - Basic usage of ReflectionClass::getMethod
  • Example#5287 - Basic usage of ReflectionClass::getMethods
  • Example#5288 - Filtering results from ReflectionClass::getMethods
  • Example#5289 - ReflectionClass::getName example
  • Example#5290 - ReflectionClass::getNamespaceName example
  • Example#5291 - ReflectionClass::getProperties filtering example
  • Example#5292 - Basic usage of ReflectionClass::getProperty
  • Example#5293 - Basic ReflectionClass::getReflectionConstants example
  • Example#5294 - ReflectionClass::getShortName example
  • Example#5295 - Basic usage of ReflectionClass::getStaticPropertyValue
  • Example#5296 - ReflectionClass::hasConstant example
  • Example#5297 - ReflectionClass::hasMethod example
  • Example#5298 - ReflectionClass::hasProperty example
  • Example#5299 - ReflectionClass::inNamespace example
  • Example#5300 - ReflectionClass::isAbstract example
  • Example#5301 - ReflectionClass::isAnonymous example
  • Example#5302 - Basic usage of ReflectionClass::isCloneable
  • Example#5303 - ReflectionClass::isFinal example
  • Example#5304 - ReflectionClass::isInstance related examples
  • Example#5305 - ReflectionClass::isInstantiable example
  • Example#5306 - Basic usage of ReflectionClass::isInterface
  • Example#5307 - Basic usage of ReflectionClass::isInternal
  • Example#5308 - Basic ReflectionClass::isIterable Usage
  • Example#5309 - ReflectionClass::isReadOnly example
  • Example#5310 - Basic usage of ReflectionClass::newInstanceArgs
  • Example#5311 - ReflectionClass::__toString example
  • Example#5312 - Basic usage
  • Example#5313 - Filtering results by class name
  • Example#5314 - Filtering results by class name, with inheritance
  • Example#5315 - ReflectionClassConstant::isEnumCase example
  • Example#5316 - ReflectionEnum::getBackingType example
  • Example#5317 - ReflectionEnum::getCase example
  • Example#5318 - ReflectionEnum::getCases example
  • Example#5319 - ReflectionEnum::hasCase example
  • Example#5320 - ReflectionEnum::isBacked example
  • Example#5321 - ReflectionEnum::getValue example
  • Example#5322 - ReflectionEnum::getBackingValue example
  • Example#5323 - ReflectionExtension example
  • Example#5324 - ReflectionExtension::getClasses example
  • Example#5325 - ReflectionExtension::getClassNames example
  • Example#5326 - ReflectionExtension::getConstants example
  • Example#5327 - ReflectionExtension::getDependencies example
  • Example#5328 - ReflectionExtension::getFunctions example
  • Example#5329 - ReflectionExtension::getINIEntries example
  • Example#5330 - ReflectionExtension::getName example
  • Example#5331 - ReflectionExtension::getVersion example
  • Example#5332 - ReflectionExtension::info exemplo
  • Example#5333 - ReflectionFunction::__construct example
  • Example#5334 - ReflectionFunction::invoke example
  • Example#5335 - ReflectionFunction::invokeArgs example
  • Example#5336 - ReflectionFunction::invokeArgs with references example
  • Example#5337 - ReflectionFunction::isAnonymous example
  • Example#5338 - ReflectionFunction::__toString example
  • Example#5339 - Basic usage with a class method
  • Example#5340 - Basic usage with a function
  • Example#5341 - Filtering results by class name
  • Example#5342 - Filtering results by class name, with inheritance
  • Example#5343 - ReflectionFunctionAbstract::getClosureUsedVariables example
  • Example#5344 - ReflectionFunctionAbstract::getReturnType example
  • Example#5345 - Usage on built-in functions
  • Example#5346 - ReflectionFunctionAbstract::getTentativeReturnType example
  • Example#5347 - ReflectionFunctionAbstract::hasReturnType example
  • Example#5348 - Usage on built-in functions
  • Example#5349 - ReflectionFunctionAbstract::hasTentativeReturnType example
  • Example#5350 - ReflectionFunctionAbstract::isClosure example
  • Example#5351 - ReflectionFunctionAbstract::isDeprecated example
  • Example#5352 - ReflectionMethod::__construct example
  • Example#5353 - ReflectionMethod::createFromMethodName example
  • Example#5354 - ReflectionMethod::getDeclaringClass example
  • Example#5355 - ReflectionMethod::getModifiers example
  • Example#5356 - ReflectionMethod::getPrototype example
  • Example#5357 - ReflectionMethod::hasPrototype example
  • Example#5358 - ReflectionMethod::invoke example
  • Example#5359 - ReflectionMethod::invokeArgs example
  • Example#5360 - Simple Class definition
  • Example#5361 - ReflectionMethod::__toString example
  • Example#5362 - ReflectionNamedType::isBuiltin example
  • Example#5363 - Using the ReflectionParameter class
  • Example#5364 - Basic usage
  • Example#5365 - Filtering results by class name
  • Example#5366 - Filtering results by class name, with inheritance
  • Example#5367 - Using the ReflectionParameter class
  • Example#5368 - Getting the class that declared the method
  • Example#5369 - Getting default values of function parameters
  • Example#5370 - Getting default values' constant names of function parameters
  • Example#5371 - ReflectionParameter::getType Usage as of PHP 7.1.0
  • Example#5372 - ReflectionParameter::getType Usage before PHP 7.1.0
  • Example#5373 - ReflectionParameter::getType Usage in PHP 8.0.0 and later
  • Example#5374 - ReflectionParameter::hasType example
  • Example#5375 - PHP 8.0.0 equivalent
  • Example#5376 - PHP 8.0.0 equivalent
  • Example#5377 - ReflectionParameter::__toString example
  • Example#5378 - ReflectionProperty::__construct example
  • Example#5379 - Getting value from private and protected properties using ReflectionProperty class
  • Example#5380 - Basic usage
  • Example#5381 - Filtering results by class name
  • Example#5382 - Filtering results by class name, with inheritance
  • Example#5383 - ReflectionProperty::getDefaultValue example
  • Example#5384 - ReflectionProperty::getDocComment example
  • Example#5385 - Multiple property declarations
  • Example#5386 - ReflectionProperty::getType example
  • Example#5387 - ReflectionProperty::getValue example
  • Example#5388 - ReflectionProperty::hasDefaultValue example
  • Example#5389 - ReflectionProperty::hasType example
  • Example#5390 - ReflectionProperty::isDefault example
  • Example#5391 - ReflectionProperty::isInitialized example
  • Example#5392 - ReflectionProperty::isPromoted example
  • Example#5393 - Simple Class definition
  • Example#5394 - ReflectionProperty::setValue example
  • Example#5395 - ReflectionType::allowsNull example
  • Example#5396 - ReflectionType::__toString example
  • Example#5397 - ReflectionUnionType::getTypes example
  • Example#5398 - ReflectionGenerator::__construct example
  • Example#5399 - ReflectionGenerator::getExecutingFile example
  • Example#5400 - ReflectionGenerator::getExecutingGenerator example
  • Example#5401 - ReflectionGenerator::getExecutingLine example
  • Example#5402 - ReflectionGenerator::getFunction example
  • Example#5403 - ReflectionGenerator::getThis example
  • Example#5404 - ReflectionGenerator::getTrace example
  • Example#5405 - ReflectionIntersectionType::getTypes example
  • Example#5406 - Basic ReflectionReference::getId usage
  • Example#5407 - Exemplos da função boolval
  • Example#5408 - Exemplo de debug_zval_dump
  • Example#5409 -
  • Example#5410 - Uma simples comparação entre as funções empty / isset.
  • Example#5411 - Função empty em Deslocamentos de String
  • Example#5412 - Exemplo da função floatval
  • Example#5413 - Exemplo da função floatval em string com caracteres não numéricos à esquerda
  • Example#5414 - Exemplo de get_debug_type
  • Example#5415 - Exemplo da get_defined_vars
  • Example#5416 - get_resource_id produz o mesmo resultado de uma conversão int
  • Example#5417 - Exemplo de get_resource_type
  • Example#5418 - Exemplo da função gettype
  • Example#5419 - Exemplos de intval
  • Example#5420 - Verificando se a variável é um array
  • Example#5421 - Exemplo de is_bool
  • Example#5422 - Exemplo de is_callable
  • Example#5423 - Exemplo de is_callable e contrutores
  • Example#5424 - Exemplos de is_countable
  • Example#5425 - Exemplo de is_float
  • Example#5426 - Exemplo de is_int
  • Example#5427 - Exemplos de is_iterable
  • Example#5428 - Exemplo de is_null
  • Example#5429 - Exemplos de is_numeric
  • Example#5430 - is_numeric with whitespace
  • Example#5431 - Exemplo de is_object
  • Example#5432 - Exemplo de is_resource
  • Example#5433 - Exemplo de is_scalar
  • Example#5434 - Exemplo de is_string
  • Example#5435 - Exemplos de isset
  • Example#5436 - isset em Deslocamento de Strings
  • Example#5437 - Exemplo de print_r
  • Example#5438 - Exemplo do parâmetro return
  • Example#5439 - Exemplo de serialize
  • Example#5440 - Exemplo da função settype
  • Example#5441 - Exemplo de strval usando o método mágico __toString().
  • Example#5442 - Exemplo de unserialize
  • Example#5443 - Exemplo de unserialize_callback_func
  • Example#5444 - Exemplo de unset
  • Example#5445 - Usando a conversão (unset)
  • Example#5446 - Exemplo de var_dump
  • Example#5447 - Exemplos de var_export
  • Example#5448 - Exportando stdClass (a partir do PHP 7.3.0)
  • Example#5449 - Exportando classes
  • Example#5450 - Usando __set_state()
  • Example#5451 -
  • Example#5452 - OAuth::fetch example
  • Example#5453 - OAuth::getAccessToken example
  • Example#5454 - OAuth::getRequestToken example
  • Example#5455 - OAuth::setRequestEngine example
  • Example#5456 - An OAuth::setRsaCertificate example
  • Example#5457 - OAuth::setToken example
  • Example#5458 - OAuthProvider::__construct example
  • Example#5459 - Example OAuthProvider::consumerHandler callback
  • Example#5460 - OAuthProvider::generateToken example
  • Example#5461 - OAuthProvider::is2LeggedEndpoint example
  • Example#5462 - Example OAuthProvider::timestampNonceHandler callback
  • Example#5463 - Example OAuthProvider::tokenHandler callback
  • Example#5464 - is_soap_fault example
  • Example#5465 - SOAP's standard method for error reporting is exceptions
  • Example#5466 - Specifying use of TLS 1.3 only
  • Example#5467 - SoapClient::__construct example
  • Example#5468 - Using the SOAP_SINGLE_ELEMENT_ARRAYS feature
  • Example#5469 - SoapClient::__doRequest example
  • Example#5470 - SoapClient::__getFunctions example
  • Example#5471 - SoapClient::__getLastRequest() example
  • Example#5472 - SoapClient::__getLastRequestHeaders() example
  • Example#5473 - SoapClient::__getLastResponse() example
  • Example#5474 - SoapClient::__getLastResponse() example
  • Example#5475 - SoapClient::__getTypes example
  • Example#5476 - SoapClient::__setLocation example
  • Example#5477 - SoapClient::__setSoapHeaders example
  • Example#5478 - Set Multiple Headers
  • Example#5479 - SoapClient::__soapCall example
  • Example#5480 - SoapServer::addFunction example
  • Example#5481 - SoapServer::__construct example
  • Example#5482 - SoapServer::getFunctions example
  • Example#5483 - SoapServer::handle example
  • Example#5484 - SoapServer::setPersistence example
  • Example#5485 - Some examples
  • Example#5486 - Some examples
  • Example#5487 - SoapHeader::__construct example
  • Example#5488 - SoapParam::__construct example
  • Example#5489 - SoapVar::__construct example
  • Example#5490 - Yar Server Example
  • Example#5491 - Access the server in borwser(GET request)
  • Example#5492 - Yar Client Example
  • Example#5493 - Yar Concurrent Client Example
  • Example#5494 - Yar_Server::__construct example
  • Example#5495 - Yar_Server::handle example
  • Example#5496 - Yar_Client::__call example
  • Example#5497 - Yar_Client::__construct example
  • Example#5498 - Yar_Client::setOpt example
  • Example#5499 - Yar_Concurrent_Client::call example
  • Example#5500 - Yar_Concurrent_Client::loop example
  • Example#5501 - Yar_Concurrent_Client::reset example
  • Example#5502 - Yar_Server_Exception::getType example
  • Example#5503 - Yar_Client_Exception::getType example
  • Example#5504 - Exemplo de uso das funções de cliente XMLRPC
  • Example#5505 - Exemplo de tipo XML-RPC
  • Example#5506 - A xmlrpc_set_type example
  • Example#5507 - For Each in ASP
  • Example#5508 - foreach in PHP
  • Example#5509 - com example (1)
  • Example#5510 - com example (2)
  • Example#5511 - dotnet example
  • Example#5512 - variant example
  • Example#5513 - Basic COMPersistHelper::saveToFile Usage
  • Example#5514 - COM event sink example
  • Example#5515 - Registering a PHP script to run as a service
  • Example#5516 - Unregistering a service
  • Example#5517 - Running as a service
  • Example#5518 - A win32_create_service example
  • Example#5519 - A win32_create_service example with dependencies
  • Example#5520 - A win32_create_service example with recovery
  • Example#5521 - A win32_delete_service example
  • Example#5522 - A win32_start_service_ctrl_dispatcher example
  • Example#5523 - book.xml
  • Example#5524 - Creating a new DOMAttr object
  • Example#5525 - DOMAttr::isId() Example
  • Example#5526 - Creating a new DOMCdataSection object
  • Example#5527 - DOMCharacterData::after example
  • Example#5528 - DOMCharacterData::before example
  • Example#5529 - DOMCharacterData::remove example
  • Example#5530 - DOMCharacterData::replaceWith example
  • Example#5531 - Creating a new DOMComment
  • Example#5532 - DOMDocument::adoptNode example
  • Example#5533 - DOMDocument::append example
  • Example#5534 - Creating a new DOMDocument
  • Example#5535 - Creating a new element and inserting it as root
  • Example#5536 - Passing text containing an unescaped & as value
  • Example#5537 - Creating a new element and inserting it as root
  • Example#5538 - A namespace prefix example
  • Example#5539 - DOMDocument::getElementById() Example
  • Example#5540 - Basic Usage Example
  • Example#5541 - Get all the XInclude elements
  • Example#5542 - DOMDocument::importNode example
  • Example#5543 - Creating a Document
  • Example#5544 - Creating a Document
  • Example#5545 - Creating a Document
  • Example#5546 - Creating a Document
  • Example#5547 - DOMDocument::prepend example
  • Example#5548 - Adding a new method to DOMElement to ease our code
  • Example#5549 - Retrieving elements as custom class
  • Example#5550 - Retrieving owner document
  • Example#5551 - Custom objects are transient
  • Example#5552 - DOMDocument::replaceChildren example
  • Example#5553 - Saving a DOM tree into a file
  • Example#5554 - Saving a HTML tree into a string
  • Example#5555 - Saving a HTML tree into a file
  • Example#5556 - Saving a DOM tree into a string
  • Example#5557 - Example of DTD validation
  • Example#5558 - DOMDocument::xinclude() example
  • Example#5559 - DOMDocumentFragment::append example
  • Example#5560 - Appending XML data to your document
  • Example#5561 - DOMDocumentFragment::prepend example
  • Example#5562 - DOMDocumentFragment::replaceChildren example
  • Example#5563 - DOMElement::after example
  • Example#5564 - DOMElement::append example
  • Example#5565 - DOMElement::before example
  • Example#5566 - Creating a new DOMElement
  • Example#5567 - DOMElement::getAttributeNames example
  • Example#5568 - DOMElement::insertAdjacentElement example
  • Example#5569 - DOMElement::insertAdjacentText example
  • Example#5570 - DOMElement::prepend example
  • Example#5571 - DOMElement::remove example
  • Example#5572 - DOMElement::replaceChildren example
  • Example#5573 - DOMElement::replaceWith example
  • Example#5574 - Setting an attribute
  • Example#5575 - DOMElement::toggleAttribute example
  • Example#5576 - Creating a new DOMEntityReference
  • Example#5577 - Creating a document with an attached DTD
  • Example#5578 - Testing your DOM Implementation
  • Example#5579 - Adicionando um nó filho
  • Example#5580 - Filhos aninhados
  • Example#5581 - DOMNode::contains example
  • Example#5582 - DOMNode::getLineNo example
  • Example#5583 - DOMNode::getNodePath example
  • Example#5584 - DOMNode::getRootNode example
  • Example#5585 - DOMNode::isEqualNode example
  • Example#5586 - Removing a child
  • Example#5587 - Traversing all the entries of the table
  • Example#5588 - DOMParentNode::replaceChildren example
  • Example#5589 - Creating a new DOMProcessingInstruction object
  • Example#5590 - Creating a new DOMText
  • Example#5591 - Getting the count of all the english books
  • Example#5592 - Getting all the english books
  • Example#5593 - book.xml
  • Example#5594 - DOMXPath::registerPHPFunctions with php:functionString
  • Example#5595 - DOMXPath::registerPHPFunctions with php:function
  • Example#5596 - Import SimpleXML into DOM with dom_import_simplexml
  • Example#5597 - Um exemplo de libxml_get_errors
  • Example#5598 - libxml_set_external_entity_loader example
  • Example#5599 - Um exemplo de libxml_set_streams_context
  • Example#5600 - Exemplo de libxml_use_internal_errors
  • Example#5601 - Include file example.php with XML string
  • Example#5602 - Getting <plot>
  • Example#5603 - Getting <line>
  • Example#5604 - Accessing non-unique elements in SimpleXML
  • Example#5605 - Using attributes
  • Example#5606 - Comparing Elements and Attributes with Text
  • Example#5607 - Comparing Two Elements
  • Example#5608 - Using XPath
  • Example#5609 - Setting values
  • Example#5610 - Adding elements and attributes
  • Example#5611 - DOM Interoperability
  • Example#5612 - Loading broken XML string
  • Example#5613 - Adiciona atributos e filhos à um elemento SimpleXML
  • Example#5614 - Adiciona atributos e filhos à um elemento SimpleXML
  • Example#5615 - Recuperando o XML
  • Example#5616 - Utilizando asXML() em resultados SimpleXMLElement::xpath
  • Example#5617 - Interpretando uma string XML
  • Example#5618 - Percorrendo um pseudo-array children()
  • Example#5619 - Utilizando namespaces
  • Example#5620 - Cria um objeto SimpleXMLElement
  • Example#5621 - Cria um objeto SimpleXMLElement de uma URL
  • Example#5622 - Contando o número de filhos
  • Example#5623 - Return the current element
  • Example#5624 - Pega os namespaces do documento
  • Example#5625 - Trabalhando com múltiplos namespaces
  • Example#5626 - Pega os nomes dos elementos XML
  • Example#5627 - Get document namespaces in use
  • Example#5628 - Return the sub-elements of the current element
  • Example#5629 - Check whether the current element has sub-elements
  • Example#5630 - Get the current XML tag key
  • Example#5631 - Move to the next element
  • Example#5632 - Definindo um prefixo de namespace para ser usado em uma consulta XPath
  • Example#5633 - Rewind to the first element
  • Example#5634 - Recuperando o conteúdo como uma string
  • Example#5635 - Check whether the current element is valid
  • Example#5636 - Xpath
  • Example#5637 - Importando o DOM
  • Example#5638 - Interpreta um documento XML
  • Example#5639 - Interpretar uma string XML
  • Example#5640 - Serializando um único valor com WDDX
  • Example#5641 - Usando pacotes incrementais com WDDX
  • Example#5642 - Exemplo de uso de wddx_serialize_vars
  • Example#5643 - Show XML Element Structure
  • Example#5644 - Map XML to HTML
  • Example#5645 - External Entity Example
  • Example#5646 - xmltest.xml
  • Example#5647 - xmltest2.xml
  • Example#5648 - Exemplo de xml_parse_into_struct
  • Example#5649 - moldb.xml - pequeno banco de dados de informações moleculares
  • Example#5650 - parsemoldb.php - analisa moldb.xml e cria o array dos objetos moleculares
  • Example#5651 - Chunked parsing of large XML documents
  • Example#5652 - xml_set_object example
  • Example#5653 - Validating XML
  • Example#5654 - Creating a simple XML document
  • Example#5655 - Working with XML namespaces
  • Example#5656 - Working with the OO API
  • Example#5657 - Direct output of XML
  • Example#5658 - XMLWriter::setIndent and mixed Content
  • Example#5659 - Basic XMLWriter::startAttribute Usage
  • Example#5660 - Intermixing Sub-elements and Attributes
  • Example#5661 - Basic xmlwriter_write_cdata Usage
  • Example#5662 - collection.xml
  • Example#5663 - collection.xsl
  • Example#5664 - fruits.xml
  • Example#5665 - fruits.xsl
  • Example#5666 - Erros de agrupamento e impressão
  • Example#5667 - Criando um XSLTProcessor
  • Example#5668 - Testando o suporte a EXSLT
  • Example#5669 - Simples chamada de função do PHP a partir de uma folha de estilos
  • Example#5670 - Modificando o parâmetro 'owner' antes da transformação
  • Example#5671 - Exemplo de saída de perfil
  • Example#5672 - Transformando em um DOMDocument
  • Example#5673 - Transformando em um arquivo HTML
  • Example#5674 - Transformando em uma string
  • Example#5675 - Um elemento oculto de formulário HTML
  • Example#5676 - Dados a serem editados pelo usuário
  • Example#5677 - Em uma URL
  • Example#5678 - Gerando Javascript com PHP
  • Example#5679 - Exemplo de código PHP/FI
  • Example#5680 - Ativa a exibição completa de erros na tela para o domínio dev.
  • Example#5681 - Adiciona o script security.php para áreas protegidas
  • Example#5682 - include_path no Unix
  • Example#5683 - include_path no Windows
  • Example#5684 - include_path do Unix utilizando a variável de ambiente ${USER}
  • Example#5685 - string.rot13
  • Example#5686 - string.toupper
  • Example#5687 - string.tolower
  • Example#5688 - string.strip_tags
  • Example#5689 - convert.base64-encode & convert.base64-decode
  • Example#5690 - convert.quoted-printable-encode & convert.quoted-printable-decode
  • Example#5691 - convert.iconv.*
  • Example#5692 - zlib.deflate e zlib.inflate
  • Example#5693 - zlib.deflate simples
  • Example#5694 - bzip2.compress e bzip2.decompress
  • Example#5695 - Criptografar/Descriptografar com Blowfish
  • Example#5696 - Criptografar arquivo usando CBC AES-128 com HMAC SHA256

User Contributed Notes

There are no user contributed notes for this page.


Changelog

As alterações a seguir foram feitas em funções de extensões nativas

Version Function Description

User Contributed Notes

There are no user contributed notes for this page.


Versão de Ajuda em HTML

  • About This Edition
  • Using PHP Manual CHM Edition
    • The HTML Help Toolbar
    • The Navigation Pane
    • Keyboard Shortcuts
  • The Full Text Search
    • General searching rules
    • Searching for words or phrases
    • Defining search terms
    • Using nested expressions when searching
  • Integrating the PHP Manual

User Contributed Notes

There are no user contributed notes for this page.


About This Edition

The Windows HTML Help Edition of the PHP Manual is aimed at developers, who want the manual at hand every time, and would like to read manual pages and user notes without waiting for a remote web page to download. This edition gives you the full content of the manual plus the user notes, with some great features provided by the viewer application by the scripts we use to generate this format and by other contributors in the form of skins.

This distribution of the PHP Manual contains many files, including the main manual file php_manual_en.chm. You can view the manual by double clicking on this file (as you already guessed). You may also see a php_manual_en.chw file in the directory, it's generated the first time you use the index tab, and it contains an index with the manual's pages.

For those interested in technical details about Microsoft HTML Help, » http://www.helpware.net/ is a great resource. For more information and positioning of Windows HTML Help in the Microsoft help formats and services history, see this » WinWriters article.

User Contributed Notes

There are no user contributed notes for this page.


Using PHP Manual CHM Edition

Índice

  • The HTML Help Toolbar
  • The Navigation Pane
  • Keyboard Shortcuts

When you double click on a CHM, a HTML Help Viewer window opens with three panes. On the left side of the window is the Navigation pane. It contains four navigational tabs: the Contents, Index, Search and Favorites tabs. On the right side of the window is the Topic pane. It displays the selected help topic, or the default help topic on startup. The help pages are all separate HTML files, your Internet Explorer displays the pages in the Topic pane. The third pane is the toolbar, which is located below the help window title bar. You can adjust the horizontal layout with dragging the vertical border between the Navigation pane and the Topic pane.

Note, that when you open the CHM the first time, it may appear in a strange position and size. From then, Windows remembers the window position, size and the last opened tab. All these including your favorites are stored in a file named hh.dat. If you move your file to another directory, all these remembered settings will be lost (including your favorites listing!). If you replace your CHM file with a new one, with the same name, this is not a problem though. The file names and path values are stored in hh.dat.

User Contributed Notes

There are no user contributed notes for this page.


The HTML Help Toolbar

The HTML Help Toolbar contains the following icons, when you view the PHP Manual:

  • Hide/Show - Hides/shows the navigation pane.
  • Locate - Locates a topic in the contents tab (in case you reached a topic with search, index or favorites, and would like to see where it is in the table of contents tree view).
  • Back - Goes back in the history.
  • Forward - Goes forward in the history.
  • Refresh - Reloads the current page.
  • Home - Opens the startup page of the CHM.
  • Print - Opens the print dialog box.
  • Options - Provides a dropdown with more options.
Using this toolbar is really easy, many of the toolbar icons are strongly related to their Internet Explorer equivalents.

User Contributed Notes

There are no user contributed notes for this page.


The Navigation Pane

The Navigation Pane contains four navigational tabs: the Contents, Index, Search and Favorites tabs. These all provide different methods to access a topic in the help file.

  • The contents tab reveals a tree like table of contents, where you can navigate to the desired topic by opening and closing parts of the tree. You can even access the deepest sections using this TOC. If you right click on an item here and choose "Print...", you'll have the option to print the selected topic or the selected topic and all subtopics. However printing is not the initial goal of this representation of the manual (the PDF version is suitable for printing).
  • The index tab lists a huge number of "keywords" (actually manual page titles). You can pick one, or start to type a keyword, see the list adjusting to your input, and then click on a topic, or press enter if the selected topic is the one you would like to see.
  • The search tab shows one of the most powerful features of the HTML Help Viewer, the full text search (also known as FTS). Here you can type in your search expression, optionally connecting words with AND/OR/NEAR/NOT. Before you click 'List topics', you can also set some options at the bottom. After the search results are displayed, you'll realize that manual text and user note results are separated. To sort out the two types, click on the 'Location' column header. Now from the search results list, you can pick a topic, and see it's page. The keywords you searched for are highlighted on the page.
  • The favorites tab enables you to store your most used topics in a list, easily accessible. Here you can see the list, add the current topic to it, remove one, or display a selected item. You can also specify your own title for the favorite, by typing it into the 'Current topic:' box. The user note page titles are prepended with a 'N:' string so you can distinguish them from normal manual pages in the favorites listing.

User Contributed Notes

There are no user contributed notes for this page.


Keyboard Shortcuts

There are many keyboard shortcuts you can use to increase your productivity. Many users find it more appropriate to use these keyboard shortcuts to access topics, instead of clicking.

General Help Viewer Shortcuts
To | Press
Close the Help Viewer | ALT+F4
Display the Options menu | ALT+O
Hide or show the Navigation pane | ALT+O, and then T
Print a topic | ALT+O, and then P
Move back to the previous topic | ALT+LEFT ARROW
Move forward to the next topic (provided you have viewed it just previously) | ALT+RIGHT ARROW
Turn on or off search highlighting. | ALT+O, and then O
Return to the help file home page | ALT+O, and then H
Switch between the Navigation pane and the Topic pane | F6
Scroll through all the links in a topic or through all the options on a Navigation pane tab | TAB
Display context (right click) menu | SHIFT+F10
Contents Tab Shortcuts
To | Press
Display the Contents tab | ALT+C
Open and close a book or folder | PLUS SIGN and MINUS SIGN, or LEFT ARROW and RIGHT ARROW
Select a topic | DOWN ARROW and UP ARROW
Display the selected topic | ENTER
Index Tab Shortcuts
To | Press
Display the Index tab | ALT+N
Type a keyword to search for | ALT+W, and then type the word
Select a keyword in the list | UP ARROW and DOWN ARROW
Display the associated topic | ENTER or ALT+D
Search Tab shortcuts
To | Press
Display the Search tab | ALT+S
Type a keyword to search for | ALT+W, and then type the word
Start a search | ALT+L
Select a topic in the results list | ALT+T, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Search for a keyword in the result list of a prior search | ALT+U
Search for words similar to the keyword. For example, to find words like "running" and "runs" for the keyword "run" | ALT+M
Only search through topic titles | ALT+R
Favorites Tab Shortcuts
To | Press
Display the Favorites tab | ALT+I
Add the currently displayed topic to the Favorites list | ALT+A
Select a topic in the Favorites list | ALT+P, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Remove the selected topic from the list | ALT+R
Topic Pane Shortcuts
To | Press
Index Lookup | Select the words you would like to look up and press F1
Find on page | CTRL+F, and then adjust options
Refresh page | F5

User Contributed Notes

There are no user contributed notes for this page.


The Full Text Search

Índice

  • General searching rules
  • Searching for words or phrases
  • Defining search terms
  • Using nested expressions when searching

This edition of the PHP Manual includes an advanced full text search possibility provided by the viewer application. This enables users to search through every word in the help file to find a match. For example, if a user does a full-text search on the word "Apache", every topic that contains the word "Apache" will be listed. Advanced full-text search allows a user to search using boolean, wildcard, and nested expressions. A user can also limit the search to previous results, match similar words, or search topic titles only.

The usage of the search feature is fairly straightforward. Click on the search tab, type in the desired words and press ENTER (or click on "List Topics"). Then you'll receive a list of matches from the PHP Manual (and the notes). You can use the button with a right arrow on it to add boolean operators to your search (or you can type them in). As you see the results, you can use the column headings (Title, Location and Rank) to sort the topic list. The default order is by Rank. You can also adjust some parameters at the bottom of this tab.

The words found are highlighted on the current page in the Topic pane by default. You can turn off this feature by choosing the "Search Highlight Off" menu item in the Options menu. To can get this feature back similarly. If you are viewing a long topic, only the first 500 instances of a search word or phrase will be highlighted, due to a limitation of the viewer.

User Contributed Notes

There are no user contributed notes for this page.


General searching rules

A basic search consists of the word or phrase you want to find. You can use wildcard expressions, nested expressions, boolean operators, similar word matches, a previous results list, or topic titles to further define your search.

The basic rules for formulating queries are as follows:

  • Searches are not case-sensitive, so you can type your search in uppercase or lowercase characters.
  • You may search for any combination of letters (a-z) and numbers (0-9). You cannot search for single letters (a, b, c, etc.) and common words, like: an, and, as, at, be, but, by, do, for, from, have, he, in, it, not, of, on, or, she, that, the, there, they, this, to, we, which, with, you.
  • Punctuation marks such as the period (.), colon (:), semicolon (;), comma (,), and hyphen (-) are ignored during a search.
  • Group the elements of your search using double quotes or parentheses to set apart each element. You cannot search for quotation marks.

Nota:

If you are searching for a file name with an extension, you should group the entire string in double quotes, ("filename.ext"). Otherwise, the period will break the file name into two separate terms. The default operation between terms is AND, so you will create the logical equivalent to "filename AND ext."

User Contributed Notes

There are no user contributed notes for this page.


Searching for words or phrases

You can search for words or phrases and use wildcard expressions. Wildcard expressions allow you to search for one or more characters using a question mark or asterisk. The table below describes the results of these different kinds of searches.

Word and phrase searches
Search for | Example | Results
A single word | select | Topics that contain the word "select". (You will also find its grammatical variations, such as "selector" and "selection".)
A phrase | "new operator" or new operator | Topics that contain the literal phrase "new operator" and all its grammatical variations. Without the quotation marks, the query is equivalent to specifying "new AND operator," which will find topics containing both of the individual words, instead of the phrase.
Wildcard expressions | esc* or HT?? | Results for the first example include topics that contain the terms "ESC", "escape", "escalation", and so on. The asterisk cannot be the only character in the term. Results for the second example include topics that contain the terms "HTTP", "HTML" and so on. The question mark cannot be the only character in the term.

Nota:

Select the Match similar words check box to include minor grammatical variations for the phrase you search. This feature only locates variations of the word with common suffixes. For example, a search on the word "add" will find "added," but it will not find "additive". This option is independent of other options or syntax. If you do a titles-only search, variations in titles will be matched. If you use quotes (or any other query operator) any variation of the word can appear; for example, "stemmed search" will also match "stemming search".

User Contributed Notes

There are no user contributed notes for this page.


Defining search terms

The AND, OR, NOT, and NEAR operators enable you to precisely define your search by creating a relationship between search terms. The following table shows how you can use each of these operators. If no operator is specified, AND is used. For example, the query "server cgi security" is equivalent to "server AND cgi AND security".

Search operators
Search for | Example | Results
Both terms in the same topic | http AND apache | Topics containing both the words "http" and "apache".
Either term in a topic | ming OR swflib | Topics containing either the word "ming" or the word "swflib" or both.
The first term without the second term | xml NOT expat | Topics containing the word "xml" but not the word "expat".
Both terms in the same topic, close together | database NEAR security | Topics containing the word "database" within eight words of the word "security".

Nota:

The |, &, and ! characters can also be used in place of OR AND and NOT respectively. This may not work if you use a very old version of the viewer.

User Contributed Notes

There are no user contributed notes for this page.


Using nested expressions when searching

Nested expressions allow you to create complex searches for information. For example, "html AND ((smtp OR pop3) NEAR mail)" finds topics containing the word "html" along with the words "smtp" and "mail" close together, or containing "html" along with the words "pop3" and "mail" close together.

The basic rules for searching help topics using nested expressions are as follows:

  • You can use parentheses to nest expressions within a query. The expressions in parentheses are evaluated before the rest of the query.
  • If a query does not contain a nested expression, it is evaluated from left to right. For example: "mail NOT pop3 OR smtp" finds topics containing the word "mail" without the word "pop3" or topics containing the word "smtp". On the other hand, "mail NOT (pop3 OR smtp)" finds topics containing the word "mail" without either of the words "pop3" or "smtp".
  • You cannot nest expressions more than five levels deep.

User Contributed Notes

There are no user contributed notes for this page.


Integrating the PHP Manual

Nota:

The information provided here is mainly aimed at IDE authors, or advanced users who would like to integrate this CHM file to their favorite IDEs or other production environment components.

There are several editors out there with support for CHM integration, but you may need to know a few things about what the CHM contains to successfully integrate the manual into your environment.

The CHM is built using XSL style sheets from XML sources. This is unique currently in the PHP Manual family, as all other versions are generated using DSSSL style sheets. This also means, that non-intentional rendering differences may come up. A special conversion script is run on the XSLT output, adding several cute features, and packing up the manual with the preferences files and skin examples.

If you never worked with CHMs, you can think of them as compressed files with OS supported access for files inside and some added search and index support. However CHMs can only be viewed using the HTML Help Viewer, you can directly access files inside them using a special URL prefix, the CHM file name and the file you request from inside. As all the help content is stored in HTML files, you can show pages of the CHM in Internet Explorer.

Assume that you placed your php_manual_en.chm to c:\phpmanual the index file in the manual (which you see the first time) can be accessed with the following URL: mk:@MSITStore:C:\phpmanual\php_manual_en.chm::/_index.html. Here mk:@MSITStore: is the special "protocol", C:\phpmanual\php_manual_en.chm is the CHM with it's full path. The /_index.html part is the path to the index file inside the CHM and :: is just what you need to put between the CHM path and this file path.

Nota:

All files are in the root directory of the CHM, unlike the previous CHM versions which included a language directory. Images, style sheets and other supplemental files have names starting with an underscore (like the main index shown above), to avoid name collisions.

The names of generated files follow the same rules as the online manual, except that the extension is .html and not .php. The most important is that function documentation files are named function.FUNCNAME.html where FUNCNAME is the function name, with all underscores converted to hyphens. Some examples are function.echo.html, function.mysql-close.html, function.imagecopy.html.

Using all this information, you can show a manual page for a function requested by a user. A simple example is included in the distribution, named php_quickref.hta. This is a » HTML Application to demonstrate the simple process of showing a manual page for a function. The quickRef() function defined therein does the job.

If you would like to integrate the manual into an IDE without direct support for the PHP manual (actually the underscore to hyphen conversion), you can use the included _function.html file to access a function page. This file is simply a redirector, and can be parameterized via the URL, as _function.html#mysql_close. This page will redirect you to the mysql_close function page (function.mysql-close.html) automatically. You can provide the full path of this file if your IDE supports context sensitive help, and provide the IDE specified string as the parameter. An example for this is the UltraEdit 9 intergation (see the edition's website).

The index of the manual (accessible via the index tab on the navigation pane) can also be used for integrational purposes. All the HTML pages are included in the index with their titles as index terms (including function description pages).

If you are a desktop application developer and would like to tightly integrate the CHM into your program (such as displaying the TOC tree in your IDE's help box), you can find more information at » http://www.helpware.net/, as well as links to other useful resources. The official site for HTML Help is at » http://www.microsoft.com/download/en/details.aspx?id=21138.

User Contributed Notes

There are no user contributed notes for this page.